lang
stringclasses
3 values
file_path
stringlengths
5
150
repo_name
stringlengths
6
110
commit
stringlengths
40
40
file_code
stringlengths
1.52k
18.9k
prefix
stringlengths
82
16.5k
suffix
stringlengths
0
15.1k
middle
stringlengths
121
8.18k
strategy
stringclasses
8 values
context_items
listlengths
0
100
Rust
token-metadata/program/tests/freeze_delegated_account.rs
levicook/metaplex-program-library
5d13c31fec61651937033d26c295b9851da4b62d
#![cfg(feature = "test-bpf")] mod utils; use mpl_token_metadata::error::MetadataError; use num_traits::FromPrimitive; use solana_program_test::*; use solana_sdk::{ instruction::InstructionError, signature::{Keypair, Signer}, transaction::{Transaction, TransactionError}, transport::TransportError, }; use utils::*; mod freeze_delegated { use super::*; #[tokio::test] async fn freeze_delegated_token_success() { let mut context = program_test().start_with_context().await; let freeze_authority = &context.payer.pubkey(); let delegate = Keypair::new(); let test_metadata = Metadata::new(); test_metadata .create_v2( &mut context, "Test".to_string(), "TST".to_string(), "uri".to_string(), None, 10, false, Some(freeze_authority), None, None, ) .await .unwrap(); let test_master_edition = MasterEditionV2::new(&test_metadata); test_master_edition .create_v3(&mut context, Some(1)) .await .unwrap(); let approve_ix = spl_token::instruction::approve(&spl_token::id(), &test_metadata.token.pubkey(), &delegate.pubkey(), &context.payer.pubkey(), &[], 1).unwrap(); let approve_tx = Transaction::new_signed_with_payer( &[approve_ix], Some(&context.payer.pubkey()), &[&context.payer], context.last_blockhash, ); context .banks_client .process_transaction(approve_tx) .await .unwrap(); let freeze_tx = Transaction::new_signed_with_payer( &[mpl_token_metadata::instruction::freeze_delegated_account( mpl_token_metadata::id(), delegate.pubkey(), test_metadata.token.pubkey(), test_master_edition.pubkey, test_master_edition.mint_pubkey, )], Some(&context.payer.pubkey()), &[&context.payer, &delegate], context.last_blockhash, ); context .banks_client .process_transaction(freeze_tx) .await .unwrap(); let transfer_ix = spl_token::instruction::transfer(&spl_token::id(), &test_metadata.token.pubkey(), &test_metadata.token.pubkey(), &context.payer.pubkey(), &[], 1).unwrap(); let transfer_tx = Transaction::new_signed_with_payer( &[transfer_ix], Some(&context.payer.pubkey()), &[&context.payer], context.last_blockhash, ); let err = context .banks_client .process_transaction(transfer_tx) .await .unwrap_err(); assert_custom_error!(err, spl_token::error::TokenError::AccountFrozen); } #[tokio::test] async fn freeze_delegated_no_freeze_authority() { let mut context = program_test().start_with_context().await; let freeze_authority = &context.payer.pubkey(); let delegate = Keypair::new(); let test_metadata = Metadata::new(); test_metadata .create_v2( &mut context, "Test".to_string(), "TST".to_string(), "uri".to_string(), None, 10, false, Some(freeze_authority), None, None, ) .await .unwrap(); spl_token::instruction::approve(&spl_token::id(), &test_metadata.token.pubkey(), &delegate.pubkey(), &context.payer.pubkey(), &[], 1).unwrap(); let freeze_ix = mpl_token_metadata::instruction::freeze_delegated_account( mpl_token_metadata::id(), delegate.pubkey(), test_metadata.token.pubkey(), test_metadata.pubkey, test_metadata.mint.pubkey(), ); let freeze_tx = Transaction::new_signed_with_payer( &[freeze_ix], Some(&context.payer.pubkey()), &[&context.payer, &delegate], context.last_blockhash, ); let err = context .banks_client .process_transaction(freeze_tx) .await .unwrap_err(); assert_custom_error!(err, MetadataError::InvalidFreezeAuthority); } #[tokio::test] async fn freeze_delegated_token_not_delegated() { let mut context = program_test().start_with_context().await; let freeze_authority = &context.payer.pubkey(); let _delegate = Keypair::new(); let test_metadata = Metadata::new(); test_metadata .create_v2( &mut context, "Test".to_string(), "TST".to_string(), "uri".to_string(), None, 10, false, Some(freeze_authority), None, None, ) .await .unwrap(); let test_master_edition = MasterEditionV2::new(&test_metadata); test_master_edition .create_v3(&mut context, None) .await .unwrap(); let freeze_ix = mpl_token_metadata::instruction::freeze_delegated_account( mpl_token_metadata::id(), context.payer.pubkey(), test_metadata.token.pubkey(), test_master_edition.pubkey, test_master_edition.mint_pubkey, ); let freeze_tx = Transaction::new_signed_with_payer( &[freeze_ix], Some(&context.payer.pubkey()), &[&context.payer], context.last_blockhash, ); let err = context .banks_client .process_transaction(freeze_tx) .await .unwrap_err(); assert_custom_error!(err, MetadataError::InvalidDelegate); } #[tokio::test] async fn freeze_delegated_token_try_thaw() { let mut context = program_test().start_with_context().await; let freeze_authority = &context.payer.pubkey(); let delegate = Keypair::new(); let test_metadata = Metadata::new(); test_metadata .create_v2( &mut context, "Test".to_string(), "TST".to_string(), "uri".to_string(), None, 10, false, Some(freeze_authority), None, None, ) .await .unwrap(); let test_master_edition = MasterEditionV2::new(&test_metadata); test_master_edition .create_v3(&mut context, None) .await .unwrap(); spl_token::instruction::approve(&spl_token::id(), &test_metadata.token.pubkey(), &delegate.pubkey(), &context.payer.pubkey(), &[], 1).unwrap(); let freeze_ix = mpl_token_metadata::instruction::freeze_delegated_account( mpl_token_metadata::id(), delegate.pubkey(), test_metadata.token.pubkey(), test_master_edition.pubkey, test_master_edition.mint_pubkey, ); let _freeze_tx = Transaction::new_signed_with_payer( &[freeze_ix], Some(&context.payer.pubkey()), &[&context.payer, &delegate], context.last_blockhash, ); let thaw_ix = mpl_token_metadata::instruction::thaw_delegated_account( mpl_token_metadata::id(), context.payer.pubkey(), test_metadata.token.pubkey(), test_master_edition.pubkey, test_master_edition.mint_pubkey, ); let thaw_tx = Transaction::new_signed_with_payer( &[thaw_ix], Some(&context.payer.pubkey()), &[&context.payer], context.last_blockhash, ); let err = context .banks_client .process_transaction(thaw_tx) .await .unwrap_err(); assert_custom_error!(err, MetadataError::InvalidDelegate); } }
#![cfg(feature = "test-bpf")] mod utils; use mpl_token_metadata::error::MetadataError; use num_traits::FromPrimitive; use solana_program_test::*; use solana_sdk::{ instruction::InstructionError, signature::{Keypair, Signer}, transaction::{Transaction, TransactionError}, transport::TransportError, }; use utils::*; mod freeze_delegated { use super::*; #[tokio::test] async fn freeze_delegated_token_success() { let mut context = program_test().start_with_context().await; let freeze_authority = &context.payer.pubkey(); let delegate = Keypair::new(); let test_metadata = Metadata::new(); test_metadata .create_v2( &mut context, "Test".to_string(), "TST".to_string(), "uri".to_string(), None, 10, false, Some(freeze_authority), None, None, ) .await .unwrap(); let test_master_edition = MasterEditionV2::new(&test_metadata); test_master_edition .create_v3(&mut context, Some(1)) .await .unwrap(); let approve_ix = spl_token::instruction::approve(&spl_token::id(), &test_metadata.token.pubkey(), &delegate.pubkey(), &context.payer.pubkey(), &[], 1).unwrap(); let approve_tx = Transaction::new_signed_with_payer( &[approve_ix], Some(&context.payer.pubkey()), &[&context.payer], context.last_blockhash, ); context .banks_client .process_transaction(approve_tx) .await .unwrap(); let freeze_tx = Transaction::new_signed_with_paye
#[tokio::test] async fn freeze_delegated_no_freeze_authority() { let mut context = program_test().start_with_context().await; let freeze_authority = &context.payer.pubkey(); let delegate = Keypair::new(); let test_metadata = Metadata::new(); test_metadata .create_v2( &mut context, "Test".to_string(), "TST".to_string(), "uri".to_string(), None, 10, false, Some(freeze_authority), None, None, ) .await .unwrap(); spl_token::instruction::approve(&spl_token::id(), &test_metadata.token.pubkey(), &delegate.pubkey(), &context.payer.pubkey(), &[], 1).unwrap(); let freeze_ix = mpl_token_metadata::instruction::freeze_delegated_account( mpl_token_metadata::id(), delegate.pubkey(), test_metadata.token.pubkey(), test_metadata.pubkey, test_metadata.mint.pubkey(), ); let freeze_tx = Transaction::new_signed_with_payer( &[freeze_ix], Some(&context.payer.pubkey()), &[&context.payer, &delegate], context.last_blockhash, ); let err = context .banks_client .process_transaction(freeze_tx) .await .unwrap_err(); assert_custom_error!(err, MetadataError::InvalidFreezeAuthority); } #[tokio::test] async fn freeze_delegated_token_not_delegated() { let mut context = program_test().start_with_context().await; let freeze_authority = &context.payer.pubkey(); let _delegate = Keypair::new(); let test_metadata = Metadata::new(); test_metadata .create_v2( &mut context, "Test".to_string(), "TST".to_string(), "uri".to_string(), None, 10, false, Some(freeze_authority), None, None, ) .await .unwrap(); let test_master_edition = MasterEditionV2::new(&test_metadata); test_master_edition .create_v3(&mut context, None) .await .unwrap(); let freeze_ix = mpl_token_metadata::instruction::freeze_delegated_account( mpl_token_metadata::id(), context.payer.pubkey(), test_metadata.token.pubkey(), test_master_edition.pubkey, test_master_edition.mint_pubkey, ); let freeze_tx = Transaction::new_signed_with_payer( &[freeze_ix], Some(&context.payer.pubkey()), &[&context.payer], context.last_blockhash, ); let err = context .banks_client .process_transaction(freeze_tx) .await .unwrap_err(); assert_custom_error!(err, MetadataError::InvalidDelegate); } #[tokio::test] async fn freeze_delegated_token_try_thaw() { let mut context = program_test().start_with_context().await; let freeze_authority = &context.payer.pubkey(); let delegate = Keypair::new(); let test_metadata = Metadata::new(); test_metadata .create_v2( &mut context, "Test".to_string(), "TST".to_string(), "uri".to_string(), None, 10, false, Some(freeze_authority), None, None, ) .await .unwrap(); let test_master_edition = MasterEditionV2::new(&test_metadata); test_master_edition .create_v3(&mut context, None) .await .unwrap(); spl_token::instruction::approve(&spl_token::id(), &test_metadata.token.pubkey(), &delegate.pubkey(), &context.payer.pubkey(), &[], 1).unwrap(); let freeze_ix = mpl_token_metadata::instruction::freeze_delegated_account( mpl_token_metadata::id(), delegate.pubkey(), test_metadata.token.pubkey(), test_master_edition.pubkey, test_master_edition.mint_pubkey, ); let _freeze_tx = Transaction::new_signed_with_payer( &[freeze_ix], Some(&context.payer.pubkey()), &[&context.payer, &delegate], context.last_blockhash, ); let thaw_ix = mpl_token_metadata::instruction::thaw_delegated_account( mpl_token_metadata::id(), context.payer.pubkey(), test_metadata.token.pubkey(), test_master_edition.pubkey, test_master_edition.mint_pubkey, ); let thaw_tx = Transaction::new_signed_with_payer( &[thaw_ix], Some(&context.payer.pubkey()), &[&context.payer], context.last_blockhash, ); let err = context .banks_client .process_transaction(thaw_tx) .await .unwrap_err(); assert_custom_error!(err, MetadataError::InvalidDelegate); } }
r( &[mpl_token_metadata::instruction::freeze_delegated_account( mpl_token_metadata::id(), delegate.pubkey(), test_metadata.token.pubkey(), test_master_edition.pubkey, test_master_edition.mint_pubkey, )], Some(&context.payer.pubkey()), &[&context.payer, &delegate], context.last_blockhash, ); context .banks_client .process_transaction(freeze_tx) .await .unwrap(); let transfer_ix = spl_token::instruction::transfer(&spl_token::id(), &test_metadata.token.pubkey(), &test_metadata.token.pubkey(), &context.payer.pubkey(), &[], 1).unwrap(); let transfer_tx = Transaction::new_signed_with_payer( &[transfer_ix], Some(&context.payer.pubkey()), &[&context.payer], context.last_blockhash, ); let err = context .banks_client .process_transaction(transfer_tx) .await .unwrap_err(); assert_custom_error!(err, spl_token::error::TokenError::AccountFrozen); }
function_block-function_prefixed
[ { "content": "/// Strings need to be appended with `\\0`s in order to have a deterministic length.\n\n/// This supports the `memcmp` filter on get program account calls.\n\n/// NOTE: it is assumed that the metadata fields are never larger than the respective MAX_LENGTH\n\npub fn puff_out_data_fields(metadata: &mut Metadata) {\n\n metadata.data.name = puffed_out_string(&metadata.data.name, MAX_NAME_LENGTH);\n\n metadata.data.symbol = puffed_out_string(&metadata.data.symbol, MAX_SYMBOL_LENGTH);\n\n metadata.data.uri = puffed_out_string(&metadata.data.uri, MAX_URI_LENGTH);\n\n}\n\n\n", "file_path": "token-metadata/program/src/utils.rs", "rank": 0, "score": 194741.66052078115 }, { "content": "pub fn assert_delegated_tokens(\n\n delegate: &AccountInfo,\n\n mint_info: &AccountInfo,\n\n token_account_info: &AccountInfo,\n\n) -> ProgramResult {\n\n assert_owned_by(mint_info, &spl_token::id())?;\n\n\n\n let token_account: Account = assert_initialized(token_account_info)?;\n\n\n\n assert_owned_by(token_account_info, &spl_token::id())?;\n\n\n\n if token_account.mint != *mint_info.key {\n\n return Err(MetadataError::MintMismatch.into());\n\n }\n\n\n\n if token_account.amount < 1 {\n\n return Err(MetadataError::NotEnoughTokens.into());\n\n }\n\n\n\n if token_account.delegate == COption::None\n\n || token_account.delegated_amount != token_account.amount\n\n || token_account.delegate.unwrap() != *delegate.key\n\n {\n\n return Err(MetadataError::InvalidDelegate.into());\n\n }\n\n Ok(())\n\n}\n", "file_path": "token-metadata/program/src/utils.rs", "rank": 1, "score": 188899.92423990156 }, { "content": "pub fn assert_valid_delegation(\n\n src_account: &AccountInfo,\n\n dst_account: &AccountInfo,\n\n src_wallet: &AccountInfo,\n\n dst_wallet: &AccountInfo,\n\n transfer_authority: &AccountInfo,\n\n mint: &anchor_lang::prelude::Account<Mint>,\n\n paysize: u64,\n\n) -> Result<()> {\n\n match SplAccount::unpack(&src_account.data.borrow()) {\n\n Ok(token_account) => {\n\n // Ensure that the delegated amount is exactly equal to the maker_size\n\n msg!(\n\n \"Delegate {}\",\n\n token_account.delegate.unwrap_or(*src_wallet.key)\n\n );\n\n msg!(\"Delegated Amount {}\", token_account.delegated_amount);\n\n if token_account.delegated_amount != paysize {\n\n return Err(ProgramError::InvalidAccountData.into());\n\n }\n", "file_path": "auction-house/program/src/utils.rs", "rank": 2, "score": 188899.92423990156 }, { "content": "pub fn program_test<'a>() -> ProgramTest {\n\n ProgramTest::new(\"mpl_token_metadata\", mpl_token_metadata::id(), None)\n\n}\n\n\n\npub async fn get_account(context: &mut ProgramTestContext, pubkey: &Pubkey) -> Account {\n\n context\n\n .banks_client\n\n .get_account(*pubkey)\n\n .await\n\n .expect(\"account not found\")\n\n .expect(\"account empty\")\n\n}\n\n\n\npub async fn get_mint(context: &mut ProgramTestContext, pubkey: &Pubkey) -> Mint {\n\n let account = get_account(context, pubkey).await;\n\n Mint::unpack(&account.data).unwrap()\n\n}\n\n\n\npub async fn mint_tokens(\n\n context: &mut ProgramTestContext,\n", "file_path": "core/rust/testing-utils/src/utils/mod.rs", "rank": 3, "score": 186259.36462708752 }, { "content": "pub fn program_test<'a>() -> ProgramTest {\n\n ProgramTest::new(\"mpl_token_metadata\", mpl_token_metadata::id(), None)\n\n}\n\n\n\npub async fn get_account(context: &mut ProgramTestContext, pubkey: &Pubkey) -> Account {\n\n context\n\n .banks_client\n\n .get_account(*pubkey)\n\n .await\n\n .expect(\"account not found\")\n\n .expect(\"account empty\")\n\n}\n\n\n\npub async fn get_mint(context: &mut ProgramTestContext, pubkey: &Pubkey) -> Mint {\n\n let account = get_account(context, pubkey).await;\n\n Mint::unpack(&account.data).unwrap()\n\n}\n\n\n\npub async fn airdrop(\n\n context: &mut ProgramTestContext,\n", "file_path": "token-metadata/program/tests/utils/mod.rs", "rank": 4, "score": 175876.55123385382 }, { "content": "pub fn nft_packs_program_test<'a>() -> ProgramTest {\n\n let mut program = ProgramTest::new(\"mpl_nft_packs\", mpl_nft_packs::id(), None);\n\n program.add_program(\"mpl_metaplex\", mpl_metaplex::id(), None);\n\n program.add_program(\"mpl_token_metadata\", mpl_token_metadata::id(), None);\n\n program.prefer_bpf(false);\n\n program\n\n}\n\n\n\npub async fn is_empty_account(context: &mut ProgramTestContext, pubkey: &Pubkey) -> bool {\n\n match context.banks_client.get_account(*pubkey).await {\n\n Ok(account) => account.is_none(),\n\n Err(_) => false,\n\n }\n\n}\n\n\n\npub async fn get_account(context: &mut ProgramTestContext, pubkey: &Pubkey) -> Account {\n\n context\n\n .banks_client\n\n .get_account(*pubkey)\n\n .await\n", "file_path": "nft-packs/program/tests/utils/mod.rs", "rank": 5, "score": 170645.65616496434 }, { "content": "/// Assert signer\n\npub fn assert_signer(account: &AccountInfo) -> ProgramResult {\n\n if account.is_signer {\n\n return Ok(());\n\n }\n\n\n\n Err(ProgramError::MissingRequiredSignature)\n\n}\n\n\n", "file_path": "nft-packs/program/src/utils.rs", "rank": 6, "score": 168164.69390584988 }, { "content": "pub fn assert_signer(account_info: &AccountInfo) -> ProgramResult {\n\n if !account_info.is_signer {\n\n Err(ProgramError::MissingRequiredSignature)\n\n } else {\n\n Ok(())\n\n }\n\n}\n\n\n", "file_path": "auction/program/src/utils.rs", "rank": 7, "score": 168158.49543496454 }, { "content": "pub fn assert_signer(account_info: &AccountInfo) -> ProgramResult {\n\n if !account_info.is_signer {\n\n Err(ProgramError::MissingRequiredSignature)\n\n } else {\n\n Ok(())\n\n }\n\n}\n\n\n", "file_path": "metaplex/program/src/utils.rs", "rank": 8, "score": 168158.49543496454 }, { "content": "pub fn assert_signer(account_info: &AccountInfo) -> ProgramResult {\n\n if !account_info.is_signer {\n\n Err(ProgramError::MissingRequiredSignature)\n\n } else {\n\n Ok(())\n\n }\n\n}\n\n\n", "file_path": "token-metadata/program/src/utils.rs", "rank": 9, "score": 165676.05476444625 }, { "content": "/// Cheap method to just grab delegate Pubkey from token account, instead of deserializing entire thing\n\npub fn get_delegate_from_token_account(token_account_info: &AccountInfo) -> Result<Option<Pubkey>> {\n\n // TokeAccount layout: mint(32), owner(32), ...\n\n let data = token_account_info.try_borrow_data()?;\n\n let key_data = array_ref![data, 76, 32];\n\n let coption_data = u32::from_le_bytes(*array_ref![data, 72, 4]);\n\n if coption_data == 0 {\n\n Ok(None)\n\n } else {\n\n Ok(Some(Pubkey::new_from_array(*key_data)))\n\n }\n\n}\n\n\n\n/// Create account almost from scratch, lifted from\n\n/// <https://github.com/solana-labs/solana-program-library/blob/7d4873c61721aca25464d42cc5ef651a7923ca79/associated-token-account/program/src/processor.rs#L51-L98>\n", "file_path": "auction-house/program/src/utils.rs", "rank": 10, "score": 152668.23742161936 }, { "content": "pub fn assert_valid_use(\n\n incoming_use: &Option<Uses>,\n\n current_use: &Option<Uses>,\n\n) -> Result<(), ProgramError> {\n\n if let Some(i) = incoming_use {\n\n if i.use_method == UseMethod::Single && (i.total != 1 || i.remaining != 1) {\n\n return Err(MetadataError::InvalidUseMethod.into());\n\n }\n\n if i.use_method == UseMethod::Multiple && (i.total < 2 || i.total < i.remaining) {\n\n return Err(MetadataError::InvalidUseMethod.into());\n\n }\n\n }\n\n return match (incoming_use, current_use) {\n\n (Some(incoming), Some(current)) => {\n\n if incoming.use_method != current.use_method && current.total != current.remaining {\n\n return Err(MetadataError::CannotChangeUseMethodAfterFirstUse.into());\n\n }\n\n if incoming.total != current.total && current.total != current.remaining {\n\n return Err(MetadataError::CannotChangeUsesAfterFirstUse.into());\n\n }\n\n if incoming.remaining != current.remaining && current.total != current.remaining {\n\n return Err(MetadataError::CannotChangeUsesAfterFirstUse.into());\n\n }\n\n Ok(())\n\n }\n\n _ => Ok(()),\n\n };\n\n}\n\n\n", "file_path": "token-metadata/program/src/assertions/uses.rs", "rank": 11, "score": 148211.90291357035 }, { "content": "pub fn process_use_authority_validation(\n\n data_len: usize,\n\n must_be_empty: bool,\n\n) -> Result<(), ProgramError> {\n\n let record_info_empty = data_len == 0;\n\n if must_be_empty {\n\n if !record_info_empty {\n\n return Err(MetadataError::UseAuthorityRecordAlreadyExists.into());\n\n }\n\n } else {\n\n if record_info_empty {\n\n return Err(MetadataError::UseAuthorityRecordAlreadyRevoked.into());\n\n }\n\n }\n\n Ok(())\n\n}\n", "file_path": "token-metadata/program/src/assertions/uses.rs", "rank": 12, "score": 146563.48008283495 }, { "content": "pub fn assert_use_authority_derivation(\n\n program_id: &Pubkey,\n\n use_authority_record_info: &AccountInfo,\n\n user_info: &AccountInfo,\n\n mint_info: &AccountInfo,\n\n) -> Result<u8, ProgramError> {\n\n let use_authority_seeds = [\n\n PREFIX.as_bytes(),\n\n program_id.as_ref(),\n\n &mint_info.key.as_ref(),\n\n USER.as_bytes(),\n\n &user_info.key.as_ref(),\n\n ];\n\n assert_derivation(&program_id, use_authority_record_info, &use_authority_seeds)\n\n}\n\n\n", "file_path": "token-metadata/program/src/assertions/uses.rs", "rank": 13, "score": 146563.48008283495 }, { "content": "fn calculate_win_index(\n\n bidder_info: &AccountInfo,\n\n auction_info: &AccountInfo,\n\n user_provided_win_index: Option<Option<usize>>,\n\n overwrite_win_index: Option<usize>,\n\n) -> Result<Option<usize>, ProgramError> {\n\n let mut win_index: Option<usize>;\n\n // User provided us with an option of an option telling us what if anything they won. We need to validate.\n\n if let Some(up_win_index) = user_provided_win_index {\n\n // check that this person is the winner they say they are. Only if not doing an override of win index,\n\n // which we know likely wont match bidder info and is simply checking below that you arent stealing a prize.\n\n\n\n if overwrite_win_index.is_none() {\n\n if let Some(up_win_index_unwrapped) = up_win_index {\n\n let winner = AuctionData::get_winner_at(auction_info, up_win_index_unwrapped);\n\n if let Some(winner_key) = winner {\n\n if winner_key != *bidder_info.key {\n\n return Err(MetaplexError::WinnerIndexMismatch.into());\n\n }\n\n } else {\n", "file_path": "metaplex/program/src/utils.rs", "rank": 14, "score": 146059.8600063147 }, { "content": "pub fn assert_derivation(\n\n program_id: &Pubkey,\n\n account: &AccountInfo,\n\n path: &[&[u8]],\n\n) -> Result<u8, ProgramError> {\n\n let (key, bump) = Pubkey::find_program_address(&path, program_id);\n\n if key != *account.key {\n\n return Err(MetaplexError::DerivedKeyInvalid.into());\n\n }\n\n Ok(bump)\n\n}\n\n\n", "file_path": "metaplex/program/src/utils.rs", "rank": 15, "score": 140579.7705070483 }, { "content": "pub fn assert_derivation(\n\n program_id: &Pubkey,\n\n account: &AccountInfo,\n\n path: &[&[u8]],\n\n) -> Result<u8, ProgramError> {\n\n let (key, bump) = Pubkey::find_program_address(&path, program_id);\n\n if key != *account.key {\n\n return Err(AuctionError::DerivedKeyInvalid.into());\n\n }\n\n Ok(bump)\n\n}\n\n\n", "file_path": "auction/program/src/utils.rs", "rank": 16, "score": 140579.7705070483 }, { "content": "#[allow(clippy::too_many_arguments)]\n\npub fn utilize(\n\n program_id: Pubkey,\n\n metadata: Pubkey,\n\n token_account: Pubkey,\n\n mint: Pubkey,\n\n use_authority_record_pda: Option<Pubkey>,\n\n use_authority: Pubkey,\n\n owner: Pubkey,\n\n burner: Option<Pubkey>,\n\n number_of_uses: u64,\n\n) -> Instruction {\n\n let mut accounts = vec![\n\n AccountMeta::new(metadata, false),\n\n AccountMeta::new(token_account, false),\n\n AccountMeta::new(mint, false),\n\n AccountMeta::new(use_authority, true),\n\n AccountMeta::new_readonly(owner, false),\n\n AccountMeta::new_readonly(spl_token::id(), false),\n\n AccountMeta::new_readonly(spl_associated_token_account::id(), false),\n\n AccountMeta::new_readonly(solana_program::system_program::id(), false),\n", "file_path": "token-metadata/program/src/instruction.rs", "rank": 17, "score": 140579.7705070483 }, { "content": "pub fn assert_is_ata(\n\n ata: &AccountInfo,\n\n wallet: &Pubkey,\n\n mint: &Pubkey,\n\n) -> Result<SplAccount, ProgramError> {\n\n assert_owned_by(ata, &spl_token::id())?;\n\n let ata_account: SplAccount = assert_initialized(ata)?;\n\n assert_keys_equal(ata_account.owner, *wallet)?;\n\n assert_keys_equal(ata_account.mint, *mint)?;\n\n assert_keys_equal(get_associated_token_address(wallet, mint), *ata.key)?;\n\n Ok(ata_account)\n\n}\n\n\n", "file_path": "metaplex/program/src/utils.rs", "rank": 18, "score": 140579.7705070483 }, { "content": "fn get_max_supply_off_master_edition(\n\n master_edition_account_info: &AccountInfo,\n\n) -> Result<Option<u64>, ProgramError> {\n\n let data = master_edition_account_info.try_borrow_data()?;\n\n // this is an option, 9 bytes, first is 0 means is none\n\n if data[9] == 0 {\n\n Ok(None)\n\n } else {\n\n let amount_data = array_ref![data, 10, 8];\n\n Ok(Some(u64::from_le_bytes(*amount_data)))\n\n }\n\n}\n\n\n", "file_path": "token-metadata/program/src/utils.rs", "rank": 19, "score": 140132.98735452816 }, { "content": "pub fn assert_derivation(\n\n program_id: &Pubkey,\n\n account: &AccountInfo,\n\n path: &[&[u8]],\n\n) -> Result<u8, ProgramError> {\n\n let (key, bump) = Pubkey::find_program_address(&path, program_id);\n\n if key != *account.key {\n\n return Err(MetadataError::DerivedKeyInvalid.into());\n\n }\n\n Ok(bump)\n\n}\n\n\n", "file_path": "token-metadata/program/src/utils.rs", "rank": 20, "score": 138528.68103221126 }, { "content": "pub fn assert_authority_correct(\n\n auction_manager_authority: &Pubkey,\n\n authority_info: &AccountInfo,\n\n) -> ProgramResult {\n\n if auction_manager_authority != authority_info.key {\n\n return Err(MetaplexError::AuctionManagerAuthorityMismatch.into());\n\n }\n\n\n\n assert_signer(authority_info)?;\n\n\n\n Ok(())\n\n}\n\n\n", "file_path": "metaplex/program/src/utils.rs", "rank": 21, "score": 138528.68103221126 }, { "content": "pub fn assert_edition_valid(\n\n program_id: &Pubkey,\n\n mint: &Pubkey,\n\n edition_account_info: &AccountInfo,\n\n) -> ProgramResult {\n\n let edition_seeds = &[\n\n mpl_token_metadata::state::PREFIX.as_bytes(),\n\n program_id.as_ref(),\n\n &mint.as_ref(),\n\n EDITION.as_bytes(),\n\n ];\n\n let (edition_key, _) = Pubkey::find_program_address(edition_seeds, program_id);\n\n if edition_key != *edition_account_info.key {\n\n return Err(MetaplexError::InvalidEditionKey.into());\n\n }\n\n\n\n Ok(())\n\n}\n\n\n", "file_path": "metaplex/program/src/utils.rs", "rank": 22, "score": 138528.68103221126 }, { "content": "pub fn assert_derivation(\n\n program_id: &Pubkey,\n\n account: &AccountInfo,\n\n path: &[&[u8]],\n\n) -> Result<u8, ProgramError> {\n\n let (key, bump) = Pubkey::find_program_address(path, program_id);\n\n if key != *account.key {\n\n return Err(VaultError::DerivedKeyInvalid.into());\n\n }\n\n Ok(bump)\n\n}\n", "file_path": "token-vault/program/src/utils.rs", "rank": 23, "score": 138528.68103221126 }, { "content": "/// Mint new tokens.\n\npub fn mint_to(\n\n client: &RpcClient,\n\n payer: &Keypair,\n\n mint: &Pubkey,\n\n to: &Pubkey,\n\n amount: u64,\n\n) -> Result<(), error::Error> {\n\n let recent_blockhash = client.get_latest_blockhash()?;\n\n\n\n let tx = Transaction::new_signed_with_payer(\n\n &[spl_token::instruction::mint_to(\n\n &spl_token::id(),\n\n mint,\n\n to,\n\n &payer.pubkey(),\n\n &[],\n\n amount,\n\n )\n\n .unwrap()],\n\n Some(&payer.pubkey()),\n\n &[payer],\n\n recent_blockhash,\n\n );\n\n\n\n client.send_and_confirm_transaction(&tx)?;\n\n\n\n Ok(())\n\n}\n\n\n", "file_path": "fixed-price-sale/cli/src/utils.rs", "rank": 24, "score": 138528.68103221126 }, { "content": "#[allow(clippy::too_many_arguments)]\n\npub fn common_redeem_checks(\n\n args: CommonRedeemCheckArgs,\n\n) -> Result<CommonRedeemReturn, ProgramError> {\n\n let CommonRedeemCheckArgs {\n\n program_id,\n\n auction_manager_info,\n\n safety_deposit_token_store_info,\n\n destination_info,\n\n bid_redemption_info,\n\n safety_deposit_info,\n\n vault_info,\n\n auction_info,\n\n auction_extended_info,\n\n bidder_metadata_info,\n\n bidder_info,\n\n token_program_info,\n\n token_vault_program_info,\n\n token_metadata_program_info,\n\n rent_info,\n\n store_info,\n", "file_path": "metaplex/program/src/utils.rs", "rank": 25, "score": 138528.68103221126 }, { "content": "pub fn process_utilize(\n\n program_id: &Pubkey,\n\n accounts: &[AccountInfo],\n\n number_of_uses: u64,\n\n) -> ProgramResult {\n\n let account_info_iter = &mut accounts.iter();\n\n let metadata_info = next_account_info(account_info_iter)?;\n\n let token_account_info = next_account_info(account_info_iter)?;\n\n let mint_info = next_account_info(account_info_iter)?;\n\n let user_info = next_account_info(account_info_iter)?;\n\n let owner_info = next_account_info(account_info_iter)?;\n\n let token_program_account_info = next_account_info(account_info_iter)?;\n\n let _ata_program_account_info = next_account_info(account_info_iter)?;\n\n let _system_account_info = next_account_info(account_info_iter)?;\n\n let _rent_info = next_account_info(account_info_iter)?;\n\n let metadata = Metadata::from_account_info(metadata_info)?;\n\n let approved_authority_is_using = accounts.len() == 11;\n\n if metadata.uses.is_none() {\n\n return Err(MetadataError::Unusable.into());\n\n }\n", "file_path": "token-metadata/program/src/processor.rs", "rank": 26, "score": 138528.68103221126 }, { "content": "#[allow(clippy::too_many_arguments)]\n\npub fn freeze_delegated_account(\n\n program_id: Pubkey,\n\n delegate: Pubkey,\n\n token_account: Pubkey,\n\n edition: Pubkey,\n\n mint: Pubkey,\n\n) -> Instruction {\n\n Instruction {\n\n program_id,\n\n accounts: vec![\n\n AccountMeta::new(delegate, true),\n\n AccountMeta::new(token_account, false),\n\n AccountMeta::new_readonly(edition, false),\n\n AccountMeta::new_readonly(mint, false),\n\n AccountMeta::new_readonly(spl_token::id(), false),\n\n ],\n\n data: MetadataInstruction::FreezeDelegatedAccount\n\n .try_to_vec()\n\n .unwrap(),\n\n }\n", "file_path": "token-metadata/program/src/instruction.rs", "rank": 27, "score": 137356.36952015766 }, { "content": "#[allow(clippy::too_many_arguments)]\n\npub fn thaw_delegated_account(\n\n program_id: Pubkey,\n\n delegate: Pubkey,\n\n token_account: Pubkey,\n\n edition: Pubkey,\n\n mint: Pubkey,\n\n) -> Instruction {\n\n Instruction {\n\n program_id,\n\n accounts: vec![\n\n AccountMeta::new(delegate, true),\n\n AccountMeta::new(token_account, false),\n\n AccountMeta::new_readonly(edition, false),\n\n AccountMeta::new_readonly(mint, false),\n\n AccountMeta::new_readonly(spl_token::id(), false),\n\n ],\n\n data: MetadataInstruction::ThawDelegatedAccount\n\n .try_to_vec()\n\n .unwrap(),\n\n }\n\n}\n", "file_path": "token-metadata/program/src/instruction.rs", "rank": 28, "score": 137356.36952015766 }, { "content": "/// Create a bid on a specific SPL token.\n\n/// Public bids are specific to the token itself, rather than the auction, and remain open indefinitely until either the user closes it or the requirements for the bid are met and it is matched with a counter bid and closed as a transaction.\n\npub fn public_bid(\n\n ctx: Context<PublicBuy>,\n\n trade_state_bump: u8,\n\n escrow_payment_bump: u8,\n\n buyer_price: u64,\n\n token_size: u64,\n\n) -> Result<()> {\n\n bid_logic(\n\n ctx.accounts.wallet.to_owned(),\n\n ctx.accounts.payment_account.to_owned(),\n\n ctx.accounts.transfer_authority.to_owned(),\n\n ctx.accounts.treasury_mint.to_owned(),\n\n ctx.accounts.token_account.to_owned(),\n\n ctx.accounts.metadata.to_owned(),\n\n ctx.accounts.escrow_payment_account.to_owned(),\n\n ctx.accounts.authority.to_owned(),\n\n ctx.accounts.auction_house.to_owned(),\n\n ctx.accounts.auction_house_fee_account.to_owned(),\n\n ctx.accounts.buyer_trade_state.to_owned(),\n\n ctx.accounts.token_program.to_owned(),\n", "file_path": "auction-house/program/src/bid/mod.rs", "rank": 29, "score": 137285.42758990897 }, { "content": "#[allow(clippy::too_many_arguments)]\n\npub fn revoke_use_authority(\n\n program_id: Pubkey,\n\n use_authority_record: Pubkey,\n\n user: Pubkey,\n\n owner: Pubkey,\n\n owner_token_account: Pubkey,\n\n metadata: Pubkey,\n\n mint: Pubkey,\n\n) -> Instruction {\n\n Instruction {\n\n program_id,\n\n accounts: vec![\n\n AccountMeta::new(use_authority_record, false),\n\n AccountMeta::new(owner, true),\n\n AccountMeta::new_readonly(user, false),\n\n AccountMeta::new(owner_token_account, false),\n\n AccountMeta::new_readonly(mint, false),\n\n AccountMeta::new_readonly(metadata, false),\n\n AccountMeta::new_readonly(spl_token::id(), false),\n\n AccountMeta::new_readonly(solana_program::system_program::id(), false),\n", "file_path": "token-metadata/program/src/instruction.rs", "rank": 30, "score": 137277.23446146678 }, { "content": "#[allow(clippy::too_many_arguments)]\n\npub fn approve_use_authority(\n\n program_id: Pubkey,\n\n use_authority_record: Pubkey,\n\n user: Pubkey,\n\n owner: Pubkey,\n\n payer: Pubkey,\n\n owner_token_account: Pubkey,\n\n metadata: Pubkey,\n\n mint: Pubkey,\n\n burner: Pubkey,\n\n number_of_uses: u64,\n\n) -> Instruction {\n\n Instruction {\n\n program_id,\n\n accounts: vec![\n\n AccountMeta::new(use_authority_record, false),\n\n AccountMeta::new(owner, true),\n\n AccountMeta::new(payer, true),\n\n AccountMeta::new_readonly(user, false),\n\n AccountMeta::new(owner_token_account, false),\n", "file_path": "token-metadata/program/src/instruction.rs", "rank": 31, "score": 137277.23446146678 }, { "content": "/// transfer all the SOL from source to receiver\n\npub fn empty_account_balance(\n\n source: &AccountInfo,\n\n receiver: &AccountInfo,\n\n) -> Result<(), ProgramError> {\n\n let mut from = source.try_borrow_mut_lamports()?;\n\n let mut to = receiver.try_borrow_mut_lamports()?;\n\n **to += **from;\n\n **from = 0;\n\n Ok(())\n\n}\n\n\n", "file_path": "nft-packs/program/src/utils.rs", "rank": 32, "score": 136554.47112089093 }, { "content": "pub fn calculate_edition_number(\n\n mint_authority_info: &AccountInfo,\n\n reservation_list_info: Option<&AccountInfo>,\n\n edition_override: Option<u64>,\n\n me_supply: u64,\n\n) -> Result<u64, ProgramError> {\n\n let edition = match reservation_list_info {\n\n Some(account) => {\n\n extract_edition_number_from_deprecated_reservation_list(account, mint_authority_info)?\n\n }\n\n None => {\n\n if let Some(edit) = edition_override {\n\n edit\n\n } else {\n\n me_supply\n\n .checked_add(1)\n\n .ok_or(MetadataError::NumericalOverflowError)?\n\n }\n\n }\n\n };\n\n\n\n Ok(edition)\n\n}\n\n\n", "file_path": "token-metadata/program/src/utils.rs", "rank": 33, "score": 136554.47112089093 }, { "content": "// Todo deprecate this for assert derivation\n\npub fn assert_edition_valid(\n\n program_id: &Pubkey,\n\n mint: &Pubkey,\n\n edition_account_info: &AccountInfo,\n\n) -> ProgramResult {\n\n let edition_seeds = &[\n\n PREFIX.as_bytes(),\n\n program_id.as_ref(),\n\n &mint.as_ref(),\n\n EDITION.as_bytes(),\n\n ];\n\n let (edition_key, _) = Pubkey::find_program_address(edition_seeds, program_id);\n\n if edition_key != *edition_account_info.key {\n\n return Err(MetadataError::InvalidEditionKey.into());\n\n }\n\n\n\n Ok(())\n\n}\n\n\n", "file_path": "token-metadata/program/src/utils.rs", "rank": 34, "score": 136554.47112089093 }, { "content": "pub fn buy(\n\n context: &mut ProgramTestContext,\n\n ahkey: &Pubkey,\n\n ah: &AuctionHouse,\n\n test_metadata: &Metadata,\n\n owner: &Pubkey,\n\n buyer: &Keypair,\n\n sale_price: u64,\n\n) -> (\n\n (\n\n mpl_auction_house::accounts::Buy,\n\n mpl_auction_house::accounts::PrintBidReceipt,\n\n ),\n\n Transaction,\n\n) {\n\n let seller_token_account = get_associated_token_address(&owner, &test_metadata.mint.pubkey());\n\n let trade_state = find_trade_state_address(\n\n &buyer.pubkey(),\n\n &ahkey,\n\n &seller_token_account,\n", "file_path": "auction-house/program/tests/utils/setup_functions.rs", "rank": 35, "score": 136554.47112089093 }, { "content": "/// Create token `Mint` from `spl_token` program.\n\npub fn create_mint(\n\n client: &RpcClient,\n\n payer: &Keypair,\n\n mint: &Keypair,\n\n decimals: u8,\n\n) -> Result<(), error::Error> {\n\n let recent_blockhash = client.get_latest_blockhash()?;\n\n let lamports = client.get_minimum_balance_for_rent_exemption(spl_token::state::Mint::LEN)?;\n\n\n\n let tx = Transaction::new_signed_with_payer(\n\n &[\n\n system_instruction::create_account(\n\n &payer.pubkey(),\n\n &mint.pubkey(),\n\n lamports,\n\n spl_token::state::Mint::LEN as u64,\n\n &spl_token::id(),\n\n ),\n\n spl_token::instruction::initialize_mint(\n\n &spl_token::id(),\n", "file_path": "fixed-price-sale/cli/src/utils.rs", "rank": 36, "score": 136554.47112089093 }, { "content": "pub fn assert_supply_invariance(\n\n master_edition: &MasterEditionV1,\n\n printing_mint: &Mint,\n\n new_supply: u64,\n\n) -> ProgramResult {\n\n // The supply of printed tokens and the supply of the master edition should, when added, never exceed max supply.\n\n // Every time a printed token is burned, master edition.supply goes up by 1.\n\n if let Some(max_supply) = master_edition.max_supply {\n\n let current_supply = printing_mint\n\n .supply\n\n .checked_add(master_edition.supply)\n\n .ok_or(MetadataError::NumericalOverflowError)?;\n\n let new_proposed_supply = current_supply\n\n .checked_add(new_supply)\n\n .ok_or(MetadataError::NumericalOverflowError)?;\n\n if new_proposed_supply > max_supply {\n\n return Err(MetadataError::PrintingWouldBreachMaximumSupply.into());\n\n }\n\n }\n\n\n\n Ok(())\n\n}\n\n\n", "file_path": "token-metadata/program/src/utils.rs", "rank": 37, "score": 136554.47112089093 }, { "content": "pub fn assert_currently_holding(\n\n program_id: &Pubkey,\n\n owner_info: &AccountInfo,\n\n metadata_info: &AccountInfo,\n\n metadata: &Metadata,\n\n mint_info: &AccountInfo,\n\n token_account_info: &AccountInfo,\n\n) -> ProgramResult {\n\n assert_owned_by(metadata_info, program_id)?;\n\n assert_owned_by(mint_info, &spl_token::id())?;\n\n\n\n let token_account: Account = assert_initialized(token_account_info)?;\n\n\n\n assert_owned_by(token_account_info, &spl_token::id())?;\n\n\n\n if token_account.owner != *owner_info.key {\n\n return Err(MetadataError::InvalidOwner.into());\n\n }\n\n\n\n if token_account.mint != *mint_info.key {\n", "file_path": "token-metadata/program/src/utils.rs", "rank": 38, "score": 136554.47112089093 }, { "content": "pub fn deposit(\n\n context: &mut ProgramTestContext,\n\n ahkey: &Pubkey,\n\n ah: &AuctionHouse,\n\n test_metadata: &Metadata,\n\n buyer: &Keypair,\n\n sale_price: u64,\n\n) -> (mpl_auction_house::accounts::Deposit, Transaction) {\n\n let seller_token_account =\n\n get_associated_token_address(&test_metadata.token.pubkey(), &test_metadata.mint.pubkey());\n\n let (_buyer_trade_state, _sts_bump) = find_trade_state_address(\n\n &buyer.pubkey(),\n\n &ahkey,\n\n &seller_token_account,\n\n &ah.treasury_mint,\n\n &test_metadata.mint.pubkey(),\n\n sale_price,\n\n 1,\n\n );\n\n let (escrow, escrow_bump) = find_escrow_payment_address(&ahkey, &buyer.pubkey());\n", "file_path": "auction-house/program/tests/utils/setup_functions.rs", "rank": 39, "score": 136554.47112089093 }, { "content": "pub fn assert_data_valid(\n\n data: &Data,\n\n update_authority: &Pubkey,\n\n existing_metadata: &Metadata,\n\n allow_direct_creator_writes: bool,\n\n update_authority_is_signer: bool,\n\n is_updating: bool,\n\n) -> ProgramResult {\n\n if data.name.len() > MAX_NAME_LENGTH {\n\n return Err(MetadataError::NameTooLong.into());\n\n }\n\n\n\n if data.symbol.len() > MAX_SYMBOL_LENGTH {\n\n return Err(MetadataError::SymbolTooLong.into());\n\n }\n\n\n\n if data.uri.len() > MAX_URI_LENGTH {\n\n return Err(MetadataError::UriTooLong.into());\n\n }\n\n\n", "file_path": "token-metadata/program/src/utils.rs", "rank": 40, "score": 136554.47112089093 }, { "content": "/// get random value\n\npub fn get_random_value(\n\n recent_slothash: &[u8],\n\n proving_process: &ProvingProcess,\n\n clock: &Clock,\n\n) -> Result<u16, ProgramError> {\n\n // Hash slot, current timestamp and value from last slothash and proving process data and receive new random u16\n\n let mut hasher = DefaultHasher::new();\n\n\n\n // recent slothash\n\n hasher.write(recent_slothash);\n\n // slot\n\n hasher.write_u64(clock.slot);\n\n // timestamp\n\n hasher.write_i64(clock.unix_timestamp);\n\n // ProvingProcess(to make hash different for each instruction in the same slot)\n\n hasher.write(proving_process.try_to_vec()?.as_ref());\n\n\n\n let mut random_value: [u8; 2] = [0u8; 2];\n\n random_value.copy_from_slice(&hasher.finish().to_le_bytes()[..2]);\n\n\n\n Ok(u16::from_le_bytes(random_value))\n\n}\n", "file_path": "nft-packs/program/src/utils.rs", "rank": 41, "score": 136554.47112089093 }, { "content": "pub fn sell(\n\n context: &mut ProgramTestContext,\n\n ahkey: &Pubkey,\n\n ah: &AuctionHouse,\n\n test_metadata: &Metadata,\n\n sale_price: u64,\n\n) -> (\n\n (\n\n mpl_auction_house::accounts::Sell,\n\n mpl_auction_house::accounts::PrintListingReceipt,\n\n ),\n\n Transaction,\n\n) {\n\n let program_id = mpl_auction_house::id();\n\n let token =\n\n get_associated_token_address(&test_metadata.token.pubkey(), &test_metadata.mint.pubkey());\n\n let (seller_trade_state, sts_bump) = find_trade_state_address(\n\n &test_metadata.token.pubkey(),\n\n &ahkey,\n\n &token,\n", "file_path": "auction-house/program/tests/utils/setup_functions.rs", "rank": 42, "score": 136554.47112089093 }, { "content": "/// Cheap method to just grab amount from token account, instead of deserializing entire thing\n\npub fn get_amount_from_token_account(\n\n token_account_info: &AccountInfo,\n\n) -> Result<u64, ProgramError> {\n\n // TokeAccount layout: mint(32), owner(32), ...\n\n let data = token_account_info.try_borrow_data()?;\n\n let amount_data = array_ref![data, 64, 8];\n\n Ok(u64::from_le_bytes(*amount_data))\n\n}\n\n\n", "file_path": "metaplex/program/src/utils.rs", "rank": 43, "score": 136554.47112089093 }, { "content": "pub fn process_freeze_delegated_account(\n\n program_id: &Pubkey,\n\n accounts: &[AccountInfo],\n\n) -> ProgramResult {\n\n let account_info_iter = &mut accounts.iter();\n\n let delegate_info = next_account_info(account_info_iter)?;\n\n let token_account_info = next_account_info(account_info_iter)?;\n\n let edition_info = next_account_info(account_info_iter)?;\n\n let mint_info = next_account_info(account_info_iter)?;\n\n let token_program_account_info = next_account_info(account_info_iter)?;\n\n\n\n if *token_program_account_info.key != spl_token::id() {\n\n return Err(MetadataError::InvalidTokenProgram.into());\n\n }\n\n\n\n // assert that edition pda is the freeze authority of this mint\n\n let mint: Mint = assert_initialized(mint_info)?;\n\n assert_owned_by(edition_info, program_id)?;\n\n assert_freeze_authority_matches_mint(&mint.freeze_authority, edition_info)?;\n\n\n", "file_path": "token-metadata/program/src/processor.rs", "rank": 44, "score": 135440.04422396328 }, { "content": "pub fn process_thaw_delegated_account(\n\n program_id: &Pubkey,\n\n accounts: &[AccountInfo],\n\n) -> ProgramResult {\n\n let account_info_iter = &mut accounts.iter();\n\n let delegate_info = next_account_info(account_info_iter)?;\n\n let token_account_info = next_account_info(account_info_iter)?;\n\n let edition_info = next_account_info(account_info_iter)?;\n\n let mint_info = next_account_info(account_info_iter)?;\n\n let token_program_account_info = next_account_info(account_info_iter)?;\n\n if *token_program_account_info.key != spl_token::id() {\n\n return Err(MetadataError::InvalidTokenProgram.into());\n\n }\n\n\n\n // assert that edition pda is the freeze authority of this mint\n\n let mint: Mint = assert_initialized(mint_info)?;\n\n assert_owned_by(edition_info, program_id)?;\n\n assert_freeze_authority_matches_mint(&mint.freeze_authority, edition_info)?;\n\n\n\n // assert delegate is signer and delegated tokens\n", "file_path": "token-metadata/program/src/processor.rs", "rank": 45, "score": 135440.04422396328 }, { "content": "pub fn process_approve_use_authority(\n\n program_id: &Pubkey,\n\n accounts: &[AccountInfo],\n\n number_of_uses: u64,\n\n) -> ProgramResult {\n\n let account_info_iter = &mut accounts.iter();\n\n let use_authority_record_info = next_account_info(account_info_iter)?;\n\n let owner_info = next_account_info(account_info_iter)?;\n\n let payer = next_account_info(account_info_iter)?;\n\n let user_info = next_account_info(account_info_iter)?;\n\n let token_account_info = next_account_info(account_info_iter)?;\n\n let metadata_info = next_account_info(account_info_iter)?;\n\n let mint_info = next_account_info(account_info_iter)?;\n\n let program_as_burner = next_account_info(account_info_iter)?;\n\n let token_program_account_info = next_account_info(account_info_iter)?;\n\n let system_account_info = next_account_info(account_info_iter)?;\n\n let rent_info = next_account_info(account_info_iter)?;\n\n let metadata = Metadata::from_account_info(metadata_info)?;\n\n if metadata.uses.is_none() {\n\n return Err(MetadataError::Unusable.into());\n", "file_path": "token-metadata/program/src/processor.rs", "rank": 46, "score": 135362.3649641687 }, { "content": "pub fn process_revoke_use_authority(\n\n program_id: &Pubkey,\n\n accounts: &[AccountInfo],\n\n) -> ProgramResult {\n\n let account_info_iter = &mut accounts.iter();\n\n let use_authority_record_info = next_account_info(account_info_iter)?;\n\n let owner_info = next_account_info(account_info_iter)?;\n\n let user_info = next_account_info(account_info_iter)?;\n\n let token_account_info = next_account_info(account_info_iter)?;\n\n let mint_info = next_account_info(account_info_iter)?;\n\n let metadata_info = next_account_info(account_info_iter)?;\n\n let token_program_account_info = next_account_info(account_info_iter)?;\n\n let metadata = Metadata::from_account_info(metadata_info)?;\n\n if metadata.uses.is_none() {\n\n return Err(MetadataError::Unusable.into());\n\n }\n\n if *token_program_account_info.key != spl_token::id() {\n\n return Err(MetadataError::InvalidTokenProgram.into());\n\n }\n\n assert_signer(&owner_info)?;\n", "file_path": "token-metadata/program/src/processor.rs", "rank": 47, "score": 135362.3649641687 }, { "content": "pub fn assert_valid_bump(\n\n canonical_bump: u8,\n\n use_authority_record: &UseAuthorityRecord,\n\n) -> Result<(), ProgramError> {\n\n if canonical_bump != use_authority_record.bump {\n\n return Err(MetadataError::InvalidUseAuthorityRecord.into());\n\n }\n\n Ok(())\n\n}\n\n\n", "file_path": "token-metadata/program/src/assertions/uses.rs", "rank": 48, "score": 135362.3649641687 }, { "content": "pub fn assert_vault_authority_correct(\n\n vault: &Vault,\n\n vault_authority_info: &AccountInfo,\n\n) -> ProgramResult {\n\n if !vault_authority_info.is_signer {\n\n return Err(VaultError::AuthorityIsNotSigner.into());\n\n }\n\n\n\n if *vault_authority_info.key != vault.authority {\n\n return Err(VaultError::AuthorityDoesNotMatch.into());\n\n }\n\n Ok(())\n\n}\n\n\n", "file_path": "token-vault/program/src/utils.rs", "rank": 49, "score": 134652.89785526175 }, { "content": "pub fn assert_safety_deposit_config_valid(\n\n program_id: &Pubkey,\n\n auction_manager_info: &AccountInfo,\n\n safety_deposit_info: &AccountInfo,\n\n safety_deposit_config_info: Option<&AccountInfo>,\n\n auction_manager_key: &Key,\n\n) -> ProgramResult {\n\n // If using v2, you must have one and it must be the right address and type\n\n if let Some(config) = safety_deposit_config_info {\n\n if *auction_manager_key == Key::AuctionManagerV2 {\n\n assert_derivation(\n\n program_id,\n\n config,\n\n &[\n\n PREFIX.as_bytes(),\n\n program_id.as_ref(),\n\n auction_manager_info.key.as_ref(),\n\n safety_deposit_info.key.as_ref(),\n\n ],\n\n )?;\n", "file_path": "metaplex/program/src/utils.rs", "rank": 50, "score": 134652.89785526175 }, { "content": "pub fn get_supply_off_master_edition(\n\n master_edition_account_info: &AccountInfo,\n\n) -> Result<u64, ProgramError> {\n\n let data = master_edition_account_info.try_borrow_data()?;\n\n // this is an option, 9 bytes, first is 0 means is none\n\n\n\n let amount_data = array_ref![data, 1, 8];\n\n Ok(u64::from_le_bytes(*amount_data))\n\n}\n\n\n", "file_path": "token-metadata/program/src/utils.rs", "rank": 51, "score": 134652.89785526175 }, { "content": "pub fn sell_mint(\n\n context: &mut ProgramTestContext,\n\n ahkey: &Pubkey,\n\n ah: &AuctionHouse,\n\n test_metadata_mint: &Pubkey,\n\n seller: &Keypair,\n\n sale_price: u64,\n\n) -> (\n\n (\n\n mpl_auction_house::accounts::Sell,\n\n mpl_auction_house::accounts::PrintListingReceipt,\n\n ),\n\n Transaction,\n\n) {\n\n let token = get_associated_token_address(&seller.pubkey(), &test_metadata_mint);\n\n let (metadata, _) = find_metadata_account(test_metadata_mint);\n\n let (seller_trade_state, sts_bump) = find_trade_state_address(\n\n &seller.pubkey(),\n\n &ahkey,\n\n &token,\n", "file_path": "auction-house/program/tests/utils/setup_functions.rs", "rank": 52, "score": 134652.89785526175 }, { "content": "/// Create token `Account` from `spl_token` program.\n\npub fn create_token_account(\n\n client: &RpcClient,\n\n payer: &Keypair,\n\n account: &Keypair,\n\n mint: &Pubkey,\n\n owner: &Pubkey,\n\n) -> Result<(), error::Error> {\n\n let recent_blockhash = client.get_latest_blockhash()?;\n\n let lamports = client.get_minimum_balance_for_rent_exemption(spl_token::state::Account::LEN)?;\n\n\n\n let tx = Transaction::new_signed_with_payer(\n\n &[\n\n system_instruction::create_account(\n\n &payer.pubkey(),\n\n &account.pubkey(),\n\n lamports,\n\n spl_token::state::Account::LEN as u64,\n\n &spl_token::id(),\n\n ),\n\n spl_token::instruction::initialize_account(\n", "file_path": "fixed-price-sale/cli/src/utils.rs", "rank": 53, "score": 134652.89785526175 }, { "content": "pub fn public_buy(\n\n context: &mut ProgramTestContext,\n\n ahkey: &Pubkey,\n\n ah: &AuctionHouse,\n\n test_metadata: &Metadata,\n\n owner: &Pubkey,\n\n buyer: &Keypair,\n\n sale_price: u64,\n\n) -> (\n\n (\n\n mpl_auction_house::accounts::PublicBuy,\n\n mpl_auction_house::accounts::PrintBidReceipt,\n\n ),\n\n Transaction,\n\n) {\n\n let seller_token_account = get_associated_token_address(&owner, &test_metadata.mint.pubkey());\n\n let trade_state = find_public_bid_trade_state_address(\n\n &buyer.pubkey(),\n\n &ahkey,\n\n &ah.treasury_mint,\n", "file_path": "auction-house/program/tests/utils/setup_functions.rs", "rank": 54, "score": 134652.89785526175 }, { "content": "pub fn get_mint_freeze_authority(\n\n account_info: &AccountInfo,\n\n) -> Result<COption<Pubkey>, ProgramError> {\n\n let data = account_info.try_borrow_data().unwrap();\n\n let authority_bytes = array_ref![data, 36 + 8 + 1 + 1, 36];\n\n\n\n Ok(unpack_coption_key(&authority_bytes)?)\n\n}\n\n\n", "file_path": "token-metadata/program/src/utils.rs", "rank": 55, "score": 134652.89785526175 }, { "content": "/// Cheap method to just grab owner Pubkey from token account, instead of deserializing entire thing\n\npub fn get_owner_from_token_account(\n\n token_account_info: &AccountInfo,\n\n) -> Result<Pubkey, ProgramError> {\n\n // TokeAccount layout: mint(32), owner(32), ...\n\n let data = token_account_info.try_borrow_data()?;\n\n let owner_data = array_ref![data, 32, 32];\n\n Ok(Pubkey::new_from_array(*owner_data))\n\n}\n\n\n", "file_path": "token-metadata/program/src/utils.rs", "rank": 56, "score": 134652.89785526175 }, { "content": "pub fn assert_update_authority_is_correct(\n\n metadata: &Metadata,\n\n update_authority_info: &AccountInfo,\n\n) -> ProgramResult {\n\n if metadata.update_authority != *update_authority_info.key {\n\n return Err(MetadataError::UpdateAuthorityIncorrect.into());\n\n }\n\n\n\n if !update_authority_info.is_signer {\n\n return Err(MetadataError::UpdateAuthorityIsNotSigner.into());\n\n }\n\n\n\n Ok(())\n\n}\n\n\n", "file_path": "token-metadata/program/src/utils.rs", "rank": 57, "score": 134652.89785526175 }, { "content": "pub fn execute_sale(\n\n context: &mut ProgramTestContext,\n\n ahkey: &Pubkey,\n\n ah: &AuctionHouse,\n\n authority: &Keypair,\n\n test_metadata: &Metadata,\n\n buyer: &Pubkey,\n\n seller: &Pubkey,\n\n token_account: &Pubkey,\n\n seller_trade_state: &Pubkey,\n\n buyer_trade_state: &Pubkey,\n\n token_size: u64,\n\n buyer_price: u64,\n\n) -> (\n\n (\n\n mpl_auction_house::accounts::ExecuteSale,\n\n mpl_auction_house::accounts::PrintPurchaseReceipt,\n\n ),\n\n Transaction,\n\n) {\n", "file_path": "auction-house/program/tests/utils/setup_functions.rs", "rank": 58, "score": 134652.89785526175 }, { "content": "pub fn transfer_mint_authority<'a>(\n\n new_authority_seeds: &[&[u8]],\n\n new_authority_key: &Pubkey,\n\n new_authority_info: &AccountInfo<'a>,\n\n mint_info: &AccountInfo<'a>,\n\n mint_authority_info: &AccountInfo<'a>,\n\n token_program_info: &AccountInfo<'a>,\n\n) -> ProgramResult {\n\n msg!(\"Setting mint authority\");\n\n invoke_signed(\n\n &set_authority(\n\n token_program_info.key,\n\n mint_info.key,\n\n Some(new_authority_key),\n\n AuthorityType::MintTokens,\n\n mint_authority_info.key,\n\n &[&mint_authority_info.key],\n\n )\n\n .unwrap(),\n\n &[\n", "file_path": "metaplex/program/src/utils.rs", "rank": 59, "score": 134409.07932273124 }, { "content": "pub fn close_token_account<'a>(\n\n account: AccountInfo<'a>,\n\n destination: AccountInfo<'a>,\n\n owner: AccountInfo<'a>,\n\n signer_seeds: &[&[u8]],\n\n) -> ProgramResult {\n\n let ix = spl_token::instruction::close_account(\n\n &spl_token::id(),\n\n account.key,\n\n destination.key,\n\n owner.key,\n\n &[],\n\n )?;\n\n\n\n invoke_signed(&ix, &[account, destination, owner], &[signer_seeds])\n\n}\n\n\n\n/// TokenMintToParams\n\npub struct TokenCreateAccount<'a: 'b, 'b> {\n\n /// payer\n", "file_path": "auction/program/src/utils.rs", "rank": 60, "score": 134409.07932273124 }, { "content": "pub fn make_ata<'a>(\n\n ata: AccountInfo<'a>,\n\n wallet: AccountInfo<'a>,\n\n mint: AccountInfo<'a>,\n\n fee_payer: AccountInfo<'a>,\n\n ata_program: AccountInfo<'a>,\n\n token_program: AccountInfo<'a>,\n\n system_program: AccountInfo<'a>,\n\n rent: AccountInfo<'a>,\n\n fee_payer_seeds: &[&[u8]],\n\n) -> Result<()> {\n\n let seeds: &[&[&[u8]]];\n\n let as_arr = [fee_payer_seeds];\n\n\n\n if fee_payer_seeds.len() > 0 {\n\n seeds = &as_arr;\n\n } else {\n\n seeds = &[];\n\n }\n\n\n", "file_path": "auction-house/program/src/utils.rs", "rank": 61, "score": 134409.07932273124 }, { "content": "pub fn transfer_metadata_ownership<'a>(\n\n token_metadata_program: AccountInfo<'a>,\n\n metadata_info: AccountInfo<'a>,\n\n update_authority: AccountInfo<'a>,\n\n new_update_authority: AccountInfo<'a>,\n\n signer_seeds: &[&[u8]],\n\n) -> ProgramResult {\n\n invoke_signed(\n\n &update_metadata_accounts(\n\n *token_metadata_program.key,\n\n *metadata_info.key,\n\n *update_authority.key,\n\n Some(*new_update_authority.key),\n\n None,\n\n None,\n\n ),\n\n &[\n\n update_authority,\n\n new_update_authority,\n\n metadata_info,\n\n token_metadata_program,\n\n ],\n\n &[&signer_seeds],\n\n )?;\n\n\n\n Ok(())\n\n}\n\n\n", "file_path": "metaplex/program/src/utils.rs", "rank": 62, "score": 134409.07932273124 }, { "content": "pub fn assert_is_ata<'a>(\n\n ata: &AccountInfo,\n\n wallet: &Pubkey,\n\n mint: &Pubkey,\n\n) -> core::result::Result<spl_token::state::Account, ProgramError> {\n\n assert_owned_by(ata, &spl_token::id())?;\n\n let ata_account: spl_token::state::Account = assert_initialized(ata)?;\n\n assert_keys_equal(ata_account.owner, *wallet)?;\n\n assert_keys_equal(ata_account.mint, *mint)?;\n\n assert_keys_equal(get_associated_token_address(wallet, mint), *ata.key)?;\n\n Ok(ata_account)\n\n}\n\n\n", "file_path": "candy-machine/program/src/utils.rs", "rank": 63, "score": 134409.07932273124 }, { "content": "pub fn make_ata<'a>(\n\n ata: AccountInfo<'a>,\n\n wallet: AccountInfo<'a>,\n\n mint: AccountInfo<'a>,\n\n fee_payer: AccountInfo<'a>,\n\n ata_program: AccountInfo<'a>,\n\n token_program: AccountInfo<'a>,\n\n system_program: AccountInfo<'a>,\n\n rent: AccountInfo<'a>,\n\n fee_payer_seeds: &[&[u8]],\n\n) -> Result<()> {\n\n let seeds: &[&[&[u8]]];\n\n let as_arr = [fee_payer_seeds];\n\n\n\n if fee_payer_seeds.len() > 0 {\n\n seeds = &as_arr;\n\n } else {\n\n seeds = &[];\n\n }\n\n\n", "file_path": "token-entangler/program/src/utils.rs", "rank": 64, "score": 134409.07932273124 }, { "content": "/// Burn tokens\n\npub fn burn_tokens<'a>(\n\n account: AccountInfo<'a>,\n\n mint: AccountInfo<'a>,\n\n authority: AccountInfo<'a>,\n\n amount: u64,\n\n) -> ProgramResult {\n\n let ix = spl_token::instruction::burn(\n\n &spl_token::id(),\n\n account.key,\n\n mint.key,\n\n authority.key,\n\n &[],\n\n amount,\n\n )?;\n\n\n\n invoke(&ix, &[account, mint, authority])\n\n}\n\n\n", "file_path": "nft-packs/program/src/utils.rs", "rank": 65, "score": 134409.07932273124 }, { "content": "pub fn assert_is_collection_delegated_authority(\n\n authority_record: &AccountInfo,\n\n collection_authority: &Pubkey,\n\n mint: &Pubkey,\n\n) -> Result<u8, ProgramError> {\n\n let (pda, bump) = find_collection_authority_account(mint, collection_authority);\n\n if pda != *authority_record.key {\n\n return Err(MetadataError::DerivedKeyInvalid.into());\n\n }\n\n Ok(bump)\n\n}\n\n\n", "file_path": "token-metadata/program/src/assertions/collection.rs", "rank": 66, "score": 133592.95219652052 }, { "content": "pub fn assert_freeze_authority_matches_mint(\n\n freeze_authority: &COption<Pubkey>,\n\n freeze_authority_info: &AccountInfo,\n\n) -> ProgramResult {\n\n match freeze_authority {\n\n COption::None => {\n\n return Err(MetadataError::InvalidFreezeAuthority.into());\n\n }\n\n COption::Some(key) => {\n\n if freeze_authority_info.key != key {\n\n return Err(MetadataError::InvalidFreezeAuthority.into());\n\n }\n\n }\n\n }\n\n Ok(())\n\n}\n\n\n", "file_path": "token-metadata/program/src/utils.rs", "rank": 67, "score": 132820.02489495734 }, { "content": "pub fn assert_store_safety_vault_manager_match(\n\n vault_key: &Pubkey,\n\n safety_deposit_info: &AccountInfo,\n\n vault_info: &AccountInfo,\n\n token_vault_program: &Pubkey,\n\n) -> ProgramResult {\n\n if vault_key != vault_info.key {\n\n return Err(MetaplexError::AuctionManagerVaultMismatch.into());\n\n }\n\n\n\n let data = safety_deposit_info.data.borrow();\n\n let vault_key_on_deposit = Pubkey::new_from_array(*array_ref![data, 1, 32]);\n\n let token_mint_key = Pubkey::new_from_array(*array_ref![data, 33, 32]);\n\n\n\n assert_derivation(\n\n &token_vault_program,\n\n safety_deposit_info,\n\n &[\n\n mpl_token_vault::state::PREFIX.as_bytes(),\n\n vault_info.key.as_ref(),\n", "file_path": "metaplex/program/src/utils.rs", "rank": 68, "score": 132820.02489495734 }, { "content": "pub fn calculate_secondary_shares_for_creator(\n\n total_amount: u64,\n\n seller_fee_basis_points: u64,\n\n shares: u64,\n\n) -> Result<u64> {\n\n Ok((total_amount\n\n .checked_mul(seller_fee_basis_points)\n\n .ok_or(ErrorCode::MathOverflow)?\n\n .checked_div(10000)\n\n .ok_or(ErrorCode::MathOverflow)?)\n\n .checked_mul(shares)\n\n .ok_or(ErrorCode::MathOverflow)?\n\n .checked_div(100)\n\n .ok_or(ErrorCode::MathOverflow)?)\n\n}\n\n\n", "file_path": "fixed-price-sale/program/src/utils.rs", "rank": 69, "score": 132820.02489495734 }, { "content": "/// Create a new account instruction\n\npub fn process_create_metadata_accounts_logic(\n\n program_id: &Pubkey,\n\n accounts: CreateMetadataAccountsLogicArgs,\n\n data: DataV2,\n\n allow_direct_creator_writes: bool,\n\n mut is_mutable: bool,\n\n is_edition: bool,\n\n add_token_standard: bool,\n\n) -> ProgramResult {\n\n let CreateMetadataAccountsLogicArgs {\n\n metadata_account_info,\n\n mint_info,\n\n mint_authority_info,\n\n payer_account_info,\n\n update_authority_info,\n\n system_account_info,\n\n rent_info,\n\n } = accounts;\n\n\n\n let mut update_authority_key = *update_authority_info.key;\n", "file_path": "token-metadata/program/src/utils.rs", "rank": 70, "score": 132820.02489495734 }, { "content": "pub fn assert_mint_authority_matches_mint(\n\n mint_authority: &COption<Pubkey>,\n\n mint_authority_info: &AccountInfo,\n\n) -> ProgramResult {\n\n match mint_authority {\n\n COption::None => {\n\n return Err(MetadataError::InvalidMintAuthority.into());\n\n }\n\n COption::Some(key) => {\n\n if mint_authority_info.key != key {\n\n return Err(MetadataError::InvalidMintAuthority.into());\n\n }\n\n }\n\n }\n\n\n\n if !mint_authority_info.is_signer {\n\n return Err(MetadataError::NotMintAuthority.into());\n\n }\n\n\n\n Ok(())\n\n}\n\n\n", "file_path": "token-metadata/program/src/utils.rs", "rank": 71, "score": 132820.02489495734 }, { "content": "/// Return `treasury_owner` Pubkey and bump seed.\n\npub fn find_treasury_owner_address(\n\n treasury_mint: &Pubkey,\n\n selling_resource: &Pubkey,\n\n) -> (Pubkey, u8) {\n\n Pubkey::find_program_address(\n\n &[\n\n HOLDER_PREFIX.as_bytes(),\n\n treasury_mint.as_ref(),\n\n selling_resource.as_ref(),\n\n ],\n\n &id(),\n\n )\n\n}\n\n\n", "file_path": "fixed-price-sale/program/src/utils.rs", "rank": 72, "score": 132820.02489495734 }, { "content": "pub fn assert_auction_is_ended_or_valid_instant_sale(\n\n auction_info: &AccountInfo,\n\n auction_extended_info: Option<&AccountInfo>,\n\n bidder_metadata_info: &AccountInfo,\n\n win_index: Option<usize>,\n\n) -> ProgramResult {\n\n if AuctionData::get_state(auction_info)? == AuctionState::Ended {\n\n return Ok(());\n\n }\n\n\n\n let instant_sale_price = auction_extended_info\n\n .and_then(|info| AuctionDataExtended::get_instant_sale_price(&info.data.borrow()));\n\n\n\n match instant_sale_price {\n\n Some(instant_sale_price) => {\n\n let winner_bid_price = win_index\n\n .and_then(|i| AuctionData::get_winner_bid_amount_at(auction_info, i))\n\n // Possible case in an open auction\n\n .unwrap_or(BidderMetadata::from_account_info(bidder_metadata_info)?.last_bid);\n\n\n", "file_path": "metaplex/program/src/utils.rs", "rank": 73, "score": 132820.02489495734 }, { "content": "pub fn transfer_mint_authority<'a>(\n\n edition_key: &Pubkey,\n\n edition_account_info: &AccountInfo<'a>,\n\n mint_info: &AccountInfo<'a>,\n\n mint_authority_info: &AccountInfo<'a>,\n\n token_program_info: &AccountInfo<'a>,\n\n) -> ProgramResult {\n\n msg!(\"Setting mint authority\");\n\n let accounts = &[\n\n mint_authority_info.clone(),\n\n mint_info.clone(),\n\n token_program_info.clone(),\n\n edition_account_info.clone(),\n\n ];\n\n invoke_signed(\n\n &set_authority(\n\n token_program_info.key,\n\n mint_info.key,\n\n Some(edition_key),\n\n AuthorityType::MintTokens,\n", "file_path": "token-metadata/program/src/utils.rs", "rank": 74, "score": 132434.8694114109 }, { "content": "pub fn calculate_supply_change<'a>(\n\n master_edition_account_info: &AccountInfo<'a>,\n\n reservation_list_info: Option<&AccountInfo<'a>>,\n\n edition_override: Option<u64>,\n\n me_supply: u64,\n\n) -> ProgramResult {\n\n if reservation_list_info.is_none() {\n\n let new_supply: u64;\n\n if let Some(edition) = edition_override {\n\n if edition == 0 {\n\n return Err(MetadataError::EditionOverrideCannotBeZero.into());\n\n }\n\n\n\n if edition > me_supply {\n\n new_supply = edition;\n\n } else {\n\n new_supply = me_supply;\n\n }\n\n } else {\n\n new_supply = me_supply\n", "file_path": "token-metadata/program/src/utils.rs", "rank": 75, "score": 132434.8694114109 }, { "content": "pub fn assert_metadata_valid<'a>(\n\n metadata: &UncheckedAccount,\n\n edition: Option<&UncheckedAccount>,\n\n mint: &Pubkey,\n\n) -> Result<()> {\n\n assert_derivation(\n\n &mpl_token_metadata::id(),\n\n &metadata.to_account_info(),\n\n &[\n\n mpl_token_metadata::state::PREFIX.as_bytes(),\n\n mpl_token_metadata::id().as_ref(),\n\n mint.as_ref(),\n\n ],\n\n )?;\n\n if metadata.data_is_empty() {\n\n return Err(ErrorCode::MetadataDoesntExist.into());\n\n }\n\n\n\n if let Some(ed) = edition {\n\n assert_derivation(\n", "file_path": "token-entangler/program/src/utils.rs", "rank": 76, "score": 132434.8694114109 }, { "content": "#[inline(always)]\n\npub fn create_or_allocate_account_raw<'a>(\n\n program_id: Pubkey,\n\n new_account_info: &AccountInfo<'a>,\n\n rent_sysvar_info: &AccountInfo<'a>,\n\n system_program_info: &AccountInfo<'a>,\n\n payer_info: &AccountInfo<'a>,\n\n size: usize,\n\n signer_seeds: &[&[u8]],\n\n) -> Result<(), ProgramError> {\n\n let rent = &Rent::from_account_info(rent_sysvar_info)?;\n\n let required_lamports = rent\n\n .minimum_balance(size)\n\n .max(1)\n\n .saturating_sub(new_account_info.lamports());\n\n\n\n if required_lamports > 0 {\n\n msg!(\"Transfer {} lamports to the new account\", required_lamports);\n\n invoke(\n\n &system_instruction::transfer(&payer_info.key, new_account_info.key, required_lamports),\n\n &[\n", "file_path": "metaplex/program/src/utils.rs", "rank": 77, "score": 132434.8694114109 }, { "content": "#[allow(clippy::too_many_arguments)]\n\npub fn pay_creator_fees<'a>(\n\n remaining_accounts: &mut Iter<AccountInfo<'a>>,\n\n metadata_info: &AccountInfo<'a>,\n\n payment_account: &AccountInfo<'a>,\n\n payment_account_owner: &AccountInfo<'a>,\n\n fee_payer: &AccountInfo<'a>,\n\n treasury_mint: &AccountInfo<'a>,\n\n ata_program: &AccountInfo<'a>,\n\n token_program: &AccountInfo<'a>,\n\n system_program: &AccountInfo<'a>,\n\n rent: &AccountInfo<'a>,\n\n size: u64,\n\n is_native: bool,\n\n) -> Result<()> {\n\n let metadata = Metadata::from_account_info(metadata_info)?;\n\n let total_fee = size as u128;\n\n match metadata.data.creators {\n\n Some(creators) => {\n\n for creator in creators {\n\n let pct = creator.share as u128;\n", "file_path": "token-entangler/program/src/utils.rs", "rank": 78, "score": 132434.8694114109 }, { "content": "pub fn assert_metadata_valid<'a>(\n\n metadata: &UncheckedAccount,\n\n token_account: &anchor_lang::prelude::Account<'a, TokenAccount>,\n\n) -> Result<()> {\n\n assert_derivation(\n\n &mpl_token_metadata::id(),\n\n &metadata.to_account_info(),\n\n &[\n\n mpl_token_metadata::state::PREFIX.as_bytes(),\n\n mpl_token_metadata::id().as_ref(),\n\n token_account.mint.as_ref(),\n\n ],\n\n )?;\n\n\n\n if metadata.data_is_empty() {\n\n return Err(ErrorCode::MetadataDoesntExist.into());\n\n }\n\n Ok(())\n\n}\n\n\n", "file_path": "auction-house/program/src/utils.rs", "rank": 79, "score": 132434.8694114109 }, { "content": "#[allow(clippy::too_many_arguments)]\n\npub fn pay_creator_fees<'a>(\n\n remaining_accounts: &mut Iter<AccountInfo<'a>>,\n\n metadata_info: &AccountInfo<'a>,\n\n escrow_payment_account: &AccountInfo<'a>,\n\n payment_account_owner: &AccountInfo<'a>,\n\n fee_payer: &AccountInfo<'a>,\n\n treasury_mint: &AccountInfo<'a>,\n\n ata_program: &AccountInfo<'a>,\n\n token_program: &AccountInfo<'a>,\n\n system_program: &AccountInfo<'a>,\n\n rent: &AccountInfo<'a>,\n\n signer_seeds: &[&[u8]],\n\n fee_payer_seeds: &[&[u8]],\n\n size: u64,\n\n is_native: bool,\n\n) -> Result<u64> {\n\n let metadata = Metadata::from_account_info(metadata_info)?;\n\n let fees = metadata.data.seller_fee_basis_points;\n\n let total_fee = (fees as u128)\n\n .checked_mul(size as u128)\n", "file_path": "auction-house/program/src/utils.rs", "rank": 80, "score": 132434.8694114109 }, { "content": "#[allow(clippy::too_many_arguments)]\n\npub fn mint_limited_edition<'a>(\n\n program_id: &'a Pubkey,\n\n master_metadata: Metadata,\n\n new_metadata_account_info: &'a AccountInfo<'a>,\n\n new_edition_account_info: &'a AccountInfo<'a>,\n\n master_edition_account_info: &'a AccountInfo<'a>,\n\n mint_info: &'a AccountInfo<'a>,\n\n mint_authority_info: &'a AccountInfo<'a>,\n\n payer_account_info: &'a AccountInfo<'a>,\n\n update_authority_info: &'a AccountInfo<'a>,\n\n token_program_account_info: &'a AccountInfo<'a>,\n\n system_account_info: &'a AccountInfo<'a>,\n\n rent_info: &'a AccountInfo<'a>,\n\n // Only present with MasterEditionV1 calls, if present, use edition based off address in res list,\n\n // otherwise, pull off the top\n\n reservation_list_info: Option<&'a AccountInfo<'a>>,\n\n // Only present with MasterEditionV2 calls, if present, means\n\n // directing to a specific version, otherwise just pull off the top\n\n edition_override: Option<u64>,\n\n) -> ProgramResult {\n", "file_path": "token-metadata/program/src/utils.rs", "rank": 81, "score": 132434.8694114109 }, { "content": "/// SPL transfer instruction.\n\npub fn spl_token_transfer<'a>(\n\n source: AccountInfo<'a>,\n\n destination: AccountInfo<'a>,\n\n authority: AccountInfo<'a>,\n\n amount: u64,\n\n signers_seeds: &[&[&[u8]]],\n\n) -> Result<(), ProgramError> {\n\n let ix = spl_token::instruction::transfer(\n\n &spl_token::id(),\n\n source.key,\n\n destination.key,\n\n authority.key,\n\n &[],\n\n amount,\n\n )?;\n\n\n\n invoke_signed(&ix, &[source, destination, authority], signers_seeds)\n\n}\n\n\n\n/// Create account (PDA)\n", "file_path": "nft-packs/program/src/utils.rs", "rank": 82, "score": 132434.8694114109 }, { "content": "#[inline(always)]\n\npub fn sys_transfer<'a>(\n\n from: &AccountInfo<'a>,\n\n to: &AccountInfo<'a>,\n\n lamports: u64,\n\n signer_seeds: &[&[u8]],\n\n) -> Result<()> {\n\n invoke_signed(\n\n &system_instruction::transfer(from.key, to.key, lamports),\n\n &[from.clone(), to.clone()],\n\n &[&signer_seeds],\n\n )?;\n\n\n\n Ok(())\n\n}\n\n\n\n/// Wrapper of `mint_new_edition_from_master_edition_via_token` instruction from `mpl_token_metadata` program\n", "file_path": "fixed-price-sale/program/src/utils.rs", "rank": 83, "score": 132434.8694114109 }, { "content": "/// Initialize SPL mint instruction\n\npub fn spl_initialize_mint<'a>(\n\n mint: AccountInfo<'a>,\n\n mint_authority: AccountInfo<'a>,\n\n rent: AccountInfo<'a>,\n\n decimals: u8,\n\n) -> ProgramResult {\n\n let ix = spl_token::instruction::initialize_mint(\n\n &spl_token::id(),\n\n mint.key,\n\n mint_authority.key,\n\n None,\n\n decimals,\n\n )?;\n\n\n\n invoke(&ix, &[mint, rent])\n\n}\n\n\n", "file_path": "nft-packs/program/src/utils.rs", "rank": 84, "score": 132434.8694114109 }, { "content": "#[inline(always)]\n\npub fn create_or_allocate_account_raw<'a>(\n\n program_id: Pubkey,\n\n new_account_info: &AccountInfo<'a>,\n\n rent_sysvar_info: &AccountInfo<'a>,\n\n system_program_info: &AccountInfo<'a>,\n\n payer_info: &AccountInfo<'a>,\n\n size: usize,\n\n signer_seeds: &[&[u8]],\n\n) -> Result<(), ProgramError> {\n\n let rent = &Rent::from_account_info(rent_sysvar_info)?;\n\n let required_lamports = rent\n\n .minimum_balance(size)\n\n .max(1)\n\n .saturating_sub(new_account_info.lamports());\n\n\n\n if required_lamports > 0 {\n\n msg!(\"Transfer {} lamports to the new account\", required_lamports);\n\n invoke(\n\n &system_instruction::transfer(&payer_info.key, new_account_info.key, required_lamports),\n\n &[\n", "file_path": "auction/program/src/utils.rs", "rank": 85, "score": 132434.8694114109 }, { "content": "/// Initialize SPL account instruction.\n\npub fn spl_initialize_account<'a>(\n\n account: AccountInfo<'a>,\n\n mint: AccountInfo<'a>,\n\n authority: AccountInfo<'a>,\n\n rent: AccountInfo<'a>,\n\n) -> ProgramResult {\n\n let ix = spl_token::instruction::initialize_account(\n\n &spl_token::id(),\n\n account.key,\n\n mint.key,\n\n authority.key,\n\n )?;\n\n\n\n invoke(&ix, &[account, mint, authority, rent])\n\n}\n\n\n", "file_path": "nft-packs/program/src/utils.rs", "rank": 86, "score": 132434.8694114109 }, { "content": "/// Close token account\n\npub fn close_token_account<'a>(\n\n account: AccountInfo<'a>,\n\n destination: AccountInfo<'a>,\n\n owner: AccountInfo<'a>,\n\n) -> ProgramResult {\n\n let ix = spl_token::instruction::close_account(\n\n &spl_token::id(),\n\n account.key,\n\n destination.key,\n\n owner.key,\n\n &[],\n\n )?;\n\n\n\n invoke(&ix, &[account, destination, owner])\n\n}\n\n\n", "file_path": "nft-packs/program/src/utils.rs", "rank": 87, "score": 132434.8694114109 }, { "content": "/// Handles the bid logic for both private and public bids.\n\npub fn bid_logic<'info>(\n\n wallet: Signer<'info>,\n\n payment_account: UncheckedAccount<'info>,\n\n transfer_authority: UncheckedAccount<'info>,\n\n treasury_mint: Account<'info, Mint>,\n\n token_account: Account<'info, TokenAccount>,\n\n metadata: UncheckedAccount<'info>,\n\n escrow_payment_account: UncheckedAccount<'info>,\n\n authority: UncheckedAccount<'info>,\n\n auction_house: Account<'info, AuctionHouse>,\n\n auction_house_fee_account: UncheckedAccount<'info>,\n\n buyer_trade_state: UncheckedAccount<'info>,\n\n token_program: Program<'info, Token>,\n\n system_program: Program<'info, System>,\n\n rent: Sysvar<'info, Rent>,\n\n trade_state_bump: u8,\n\n escrow_payment_bump: u8,\n\n buyer_price: u64,\n\n token_size: u64,\n\n public: bool,\n", "file_path": "auction-house/program/src/bid/mod.rs", "rank": 88, "score": 131250.80565919713 }, { "content": "/// Create a private bid on a specific SPL token that is *held by a specific wallet*.\n\npub fn private_bid<'info>(\n\n ctx: Context<'_, '_, '_, 'info, Buy<'info>>,\n\n trade_state_bump: u8,\n\n escrow_payment_bump: u8,\n\n buyer_price: u64,\n\n token_size: u64,\n\n) -> Result<()> {\n\n bid_logic(\n\n ctx.accounts.wallet.to_owned(),\n\n ctx.accounts.payment_account.to_owned(),\n\n ctx.accounts.transfer_authority.to_owned(),\n\n ctx.accounts.treasury_mint.to_owned(),\n\n ctx.accounts.token_account.to_owned(),\n\n ctx.accounts.metadata.to_owned(),\n\n ctx.accounts.escrow_payment_account.to_owned(),\n\n ctx.accounts.authority.to_owned(),\n\n ctx.accounts.auction_house.to_owned(),\n\n ctx.accounts.auction_house_fee_account.to_owned(),\n\n ctx.accounts.buyer_trade_state.to_owned(),\n\n ctx.accounts.token_program.to_owned(),\n\n ctx.accounts.system_program.to_owned(),\n\n ctx.accounts.rent.to_owned(),\n\n trade_state_bump,\n\n escrow_payment_bump,\n\n buyer_price,\n\n token_size,\n\n false,\n\n )\n\n}\n\n\n", "file_path": "auction-house/program/src/bid/mod.rs", "rank": 89, "score": 131250.80565919713 }, { "content": "pub fn extract_edition_number_from_deprecated_reservation_list(\n\n account: &AccountInfo,\n\n mint_authority_info: &AccountInfo,\n\n) -> Result<u64, ProgramError> {\n\n let mut reservation_list = get_reservation_list(account)?;\n\n\n\n if let Some(supply_snapshot) = reservation_list.supply_snapshot() {\n\n let mut prev_total_offsets: u64 = 0;\n\n let mut offset: Option<u64> = None;\n\n let mut reservations = reservation_list.reservations();\n\n for i in 0..reservations.len() {\n\n let mut reservation = &mut reservations[i];\n\n\n\n if reservation.address == *mint_authority_info.key {\n\n offset = Some(\n\n prev_total_offsets\n\n .checked_add(reservation.spots_remaining)\n\n .ok_or(MetadataError::NumericalOverflowError)?,\n\n );\n\n // You get your editions in reverse order but who cares, saves a byte\n", "file_path": "token-metadata/program/src/utils.rs", "rank": 90, "score": 131052.19527820917 }, { "content": "pub fn calculate_secondary_shares_for_market_owner(\n\n total_amount: u64,\n\n seller_fee_basis_points: u64,\n\n) -> Result<u64> {\n\n Ok(total_amount\n\n .checked_sub(\n\n total_amount\n\n .checked_mul(seller_fee_basis_points)\n\n .ok_or(ErrorCode::MathOverflow)?\n\n .checked_div(10000)\n\n .ok_or(ErrorCode::MathOverflow)?,\n\n )\n\n .ok_or(ErrorCode::MathOverflow)?)\n\n}\n", "file_path": "fixed-price-sale/program/src/utils.rs", "rank": 91, "score": 131052.19527820917 }, { "content": "pub fn end_auction<'a: 'b, 'b>(\n\n resource: Pubkey,\n\n auction: AccountInfo<'a>,\n\n authority: AccountInfo<'a>,\n\n auction_program: AccountInfo<'a>,\n\n clock: AccountInfo<'a>,\n\n authority_signer_seeds: &'b [&'b [u8]],\n\n) -> ProgramResult {\n\n invoke_signed(\n\n &end_auction_instruction(\n\n *auction_program.key,\n\n *authority.key,\n\n EndAuctionArgs {\n\n resource,\n\n reveal: None,\n\n },\n\n ),\n\n &[auction, authority, auction_program, clock],\n\n &[authority_signer_seeds],\n\n )?;\n\n\n\n Ok(())\n\n}\n\n\n", "file_path": "metaplex/program/src/utils.rs", "rank": 92, "score": 130678.94556991468 }, { "content": "pub fn assert_valid_trade_state<'a>(\n\n wallet: &Pubkey,\n\n auction_house: &Account<AuctionHouse>,\n\n buyer_price: u64,\n\n token_size: u64,\n\n trade_state: &AccountInfo,\n\n mint: &Pubkey,\n\n token_holder: &Pubkey,\n\n ts_bump: u8,\n\n) -> Result<u8> {\n\n let ah_pubkey = &auction_house.key();\n\n let mint_bytes = mint.as_ref();\n\n let treasury_mint_bytes = auction_house.treasury_mint.as_ref();\n\n let buyer_price_bytes = buyer_price.to_le_bytes();\n\n let token_size_bytes = token_size.to_le_bytes();\n\n let wallet_bytes = wallet.as_ref();\n\n let auction_house_key_bytes = ah_pubkey.as_ref();\n\n let pfix = PREFIX.as_bytes();\n\n let token_holder_bytes = token_holder.as_ref();\n\n let canonical_bump = assert_derivation(\n", "file_path": "auction-house/program/src/utils.rs", "rank": 93, "score": 130533.29614578174 }, { "content": "#[allow(clippy::too_many_arguments)]\n\npub fn transfer_safety_deposit_box_items<'a>(\n\n token_vault_program: AccountInfo<'a>,\n\n destination: AccountInfo<'a>,\n\n safety_deposit_box: AccountInfo<'a>,\n\n safety_deposit_token_store: AccountInfo<'a>,\n\n vault: AccountInfo<'a>,\n\n fraction_mint: AccountInfo<'a>,\n\n vault_authority: AccountInfo<'a>,\n\n transfer_authority: AccountInfo<'a>,\n\n rent: AccountInfo<'a>,\n\n amount: u64,\n\n signer_seeds: &[&[u8]],\n\n) -> ProgramResult {\n\n invoke_signed(\n\n &create_withdraw_tokens_instruction(\n\n *token_vault_program.key,\n\n *destination.key,\n\n *safety_deposit_box.key,\n\n *safety_deposit_token_store.key,\n\n *vault.key,\n", "file_path": "metaplex/program/src/utils.rs", "rank": 94, "score": 130533.29614578174 }, { "content": "#[allow(clippy::too_many_arguments)]\n\npub fn pay_auction_house_fees<'a>(\n\n auction_house: &anchor_lang::prelude::Account<'a, AuctionHouse>,\n\n auction_house_treasury: &AccountInfo<'a>,\n\n escrow_payment_account: &AccountInfo<'a>,\n\n token_program: &AccountInfo<'a>,\n\n system_program: &AccountInfo<'a>,\n\n signer_seeds: &[&[u8]],\n\n size: u64,\n\n is_native: bool,\n\n) -> Result<u64> {\n\n let fees = auction_house.seller_fee_basis_points;\n\n let total_fee = (fees as u128)\n\n .checked_mul(size as u128)\n\n .ok_or(ErrorCode::NumericalOverflow)?\n\n .checked_div(10000)\n\n .ok_or(ErrorCode::NumericalOverflow)? as u64;\n\n if !is_native {\n\n invoke_signed(\n\n &spl_token::instruction::transfer(\n\n token_program.key,\n", "file_path": "auction-house/program/src/utils.rs", "rank": 95, "score": 130533.29614578174 }, { "content": "#[inline(always)]\n\npub fn create_or_allocate_account_raw<'a>(\n\n program_id: Pubkey,\n\n new_account_info: &AccountInfo<'a>,\n\n rent_sysvar_info: &AccountInfo<'a>,\n\n system_program_info: &AccountInfo<'a>,\n\n payer_info: &AccountInfo<'a>,\n\n size: usize,\n\n signer_seeds: &[&[u8]],\n\n new_acct_seeds: &[&[u8]],\n\n) -> Result<()> {\n\n let rent = &Rent::from_account_info(rent_sysvar_info)?;\n\n let required_lamports = rent\n\n .minimum_balance(size)\n\n .max(1)\n\n .saturating_sub(new_account_info.lamports());\n\n\n\n if required_lamports > 0 {\n\n msg!(\"Transfer {} lamports to the new account\", required_lamports);\n\n let seeds: &[&[&[u8]]];\n\n let as_arr = [signer_seeds];\n", "file_path": "auction-house/program/src/utils.rs", "rank": 96, "score": 130533.29614578174 }, { "content": "#[inline(always)]\n\npub fn sys_create_account<'a>(\n\n from: &AccountInfo<'a>,\n\n to: &AccountInfo<'a>,\n\n lamports: u64,\n\n space: usize,\n\n owner: &Pubkey,\n\n signer_seeds: &[&[u8]],\n\n) -> Result<()> {\n\n invoke_signed(\n\n &system_instruction::create_account(from.key, to.key, lamports, space as u64, owner),\n\n &[from.clone(), to.clone()],\n\n &[&signer_seeds],\n\n )?;\n\n\n\n Ok(())\n\n}\n\n\n\n/// Wrapper of `transfer` instruction from `system_program` program\n", "file_path": "fixed-price-sale/program/src/utils.rs", "rank": 97, "score": 130533.29614578174 }, { "content": "#[inline(always)]\n\npub fn create_or_allocate_account_raw<'a>(\n\n program_id: Pubkey,\n\n new_account_info: &AccountInfo<'a>,\n\n rent_sysvar_info: &AccountInfo<'a>,\n\n system_program_info: &AccountInfo<'a>,\n\n payer_info: &AccountInfo<'a>,\n\n size: usize,\n\n signer_seeds: &[&[u8]],\n\n new_acct_seeds: &[&[u8]],\n\n) -> Result<()> {\n\n let rent = &Rent::from_account_info(rent_sysvar_info)?;\n\n let required_lamports = rent\n\n .minimum_balance(size)\n\n .max(1)\n\n .saturating_sub(new_account_info.lamports());\n\n\n\n if required_lamports > 0 {\n\n msg!(\"Transfer {} lamports to the new account\", required_lamports);\n\n let seeds: &[&[&[u8]]];\n\n let as_arr = [signer_seeds];\n", "file_path": "token-entangler/program/src/utils.rs", "rank": 98, "score": 130533.29614578174 }, { "content": "#[allow(clippy::too_many_arguments)]\n\npub fn shift_authority_back_to_originating_user<'a>(\n\n program_id: &Pubkey,\n\n auction_manager: &dyn AuctionManager,\n\n auction_manager_info: &AccountInfo<'a>,\n\n master_metadata_info: &AccountInfo<'a>,\n\n original_authority: &AccountInfo<'a>,\n\n original_authority_lookup_info: &AccountInfo<'a>,\n\n printing_mint_info: &AccountInfo<'a>,\n\n token_program_info: &AccountInfo<'a>,\n\n authority_seeds: &[&[u8]],\n\n) -> ProgramResult {\n\n let auction_key = auction_manager.auction();\n\n let original_authority_lookup_seeds = &[\n\n PREFIX.as_bytes(),\n\n auction_key.as_ref(),\n\n master_metadata_info.key.as_ref(),\n\n ];\n\n\n\n let (expected_key, _) =\n\n Pubkey::find_program_address(original_authority_lookup_seeds, &program_id);\n", "file_path": "metaplex/program/src/utils.rs", "rank": 99, "score": 130533.29614578174 } ]
Rust
linkerd/proxy/api-resolve/src/resolve.rs
tegioz/linkerd2-proxy
8b6f9a09968ca844e5c7bcbf924c045d4797541b
use crate::api::destination as api; use crate::core::resolve::{self, Update}; use crate::metadata::Metadata; use crate::pb; use futures::{future, try_ready, Future, Poll, Stream}; use tower::Service; use tower_grpc::{self as grpc, generic::client::GrpcService, Body, BoxBody}; use tracing::{debug, trace}; #[derive(Clone)] pub struct Resolve<S> { service: api::client::Destination<S>, scheme: String, context_token: String, } pub struct Resolution<S: GrpcService<BoxBody>> { inner: grpc::Streaming<api::Update, S::ResponseBody>, } impl<S> Resolve<S> where S: GrpcService<BoxBody> + Clone + Send + 'static, S::ResponseBody: Send, <S::ResponseBody as Body>::Data: Send, S::Future: Send, { pub fn new<T>(svc: S) -> Self where Self: resolve::Resolve<T>, { Self { service: api::client::Destination::new(svc), scheme: "".into(), context_token: "".into(), } } pub fn with_scheme<T: ToString>(self, scheme: T) -> Self { Self { scheme: scheme.to_string(), ..self } } pub fn with_context_token<T: ToString>(self, context_token: T) -> Self { Self { context_token: context_token.to_string(), ..self } } } impl<T, S> Service<T> for Resolve<S> where T: ToString, S: GrpcService<BoxBody> + Clone + Send + 'static, S::ResponseBody: Send, <S::ResponseBody as Body>::Data: Send, S::Future: Send, { type Response = Resolution<S>; type Error = grpc::Status; type Future = future::Map< grpc::client::server_streaming::ResponseFuture<api::Update, S::Future>, fn(grpc::Response<grpc::Streaming<api::Update, S::ResponseBody>>) -> Resolution<S>, >; fn poll_ready(&mut self) -> Poll<(), Self::Error> { self.service.poll_ready() } fn call(&mut self, target: T) -> Self::Future { let path = target.to_string(); trace!("resolve {:?}", path); self.service .get(grpc::Request::new(api::GetDestination { path, scheme: self.scheme.clone(), context_token: self.context_token.clone(), })) .map(|rsp| { debug!(metadata = ?rsp.metadata()); Resolution { inner: rsp.into_inner(), } }) } } impl<S> resolve::Resolution for Resolution<S> where S: GrpcService<BoxBody>, { type Endpoint = Metadata; type Error = grpc::Status; fn poll(&mut self) -> Poll<Update<Self::Endpoint>, Self::Error> { loop { match try_ready!(self.inner.poll()) { Some(api::Update { update }) => match update { Some(api::update::Update::Add(api::WeightedAddrSet { addrs, metric_labels, })) => { let addr_metas = addrs .into_iter() .filter_map(|addr| pb::to_addr_meta(addr, &metric_labels)) .collect::<Vec<_>>(); if !addr_metas.is_empty() { return Ok(Update::Add(addr_metas).into()); } } Some(api::update::Update::Remove(api::AddrSet { addrs })) => { let sock_addrs = addrs .into_iter() .filter_map(pb::to_sock_addr) .collect::<Vec<_>>(); if !sock_addrs.is_empty() { return Ok(Update::Remove(sock_addrs).into()); } } Some(api::update::Update::NoEndpoints(api::NoEndpoints { exists })) => { let update = if exists { Update::Empty } else { Update::DoesNotExist }; return Ok(update.into()); } None => {} }, None => return Err(grpc::Status::new(grpc::Code::Ok, "end of stream")), }; } } }
use crate::api::destination as api; use crate::core::resolve::{self, Update}; use crate::metadata::Metadata; use crate::pb; use futures::{future, try_ready, Future, Poll, Stream}; use tower::Service; use tower_grpc::{self as grpc, generic::client::GrpcService, Body, BoxBody}; use tracing::{debug, trace}; #[derive(Clone)] pub struct Resolve<S> { service: api::client::Destination<S>, scheme: String, context_token: String, } pub struct Resolution<S: GrpcService<BoxBody>> { inner: grpc::Streaming<api::Update, S::ResponseBody>, } impl<S> Resolve<S> where S: GrpcService<BoxBody> + Clone + Send + 'static, S::ResponseBody: Send, <S::ResponseBody as Body>::Data: Send, S::Future: Send, { pub fn new<T>(svc: S) -> Self where Self: resolve::Resolve<T>, { Self { service: api::client::Destination::new(svc), scheme: "".into(), context_token: "".into(), } } pub fn with_scheme<T: ToString>(self, scheme: T) -> Self { Self { scheme: scheme.to_string(), ..self } } pub fn with_context_token<T: ToString>(self, context_token: T) -> Self { Self { context_token: context_token.to_string(), ..self } } } impl<T, S> Service<T> for Resolve<S> where T: ToString, S: GrpcService<BoxBody> + Clone + Send + 'static, S::ResponseBody: Send, <S::ResponseBody as Body>::Data: Send, S::Future: Send, { type Response = Resolution<S>; type Error = grpc::Status; type Future = future::Map< grpc::client::server_streaming::ResponseFuture<api::Update, S::Future>, fn(grpc::Response<grpc::Streaming<api::Update, S::ResponseBody>>) -> Resolution<S>, >; fn poll_ready(&mut self) -> Poll<(), Self::Error> { self.service.poll_ready() } fn call(&mut self, target: T) -> Self::Future { let path = target.to_string(); trace!("resolve {:?}", path); self.service .get(grpc::Request::new(api::GetDestination { path, scheme: self.scheme.clone(), context_token: self.context_token.clone(), })) .map(|rsp| { debug!(metadata = ?rsp.metadata()); Resolution { inner: rsp.into_inner(), } }) } } impl<S> resolve::Resolution for Resolution<S> where S: GrpcService<BoxBody>, { type Endpoint = Metadata; type Error = grpc::Status; fn poll(&mut self) -> Poll<Update<Self::Endpoint>, Self::Error> { loop { match try_ready!(self.inner.poll()) { Some(api::Update { update }) => match update { Some(api::update::Update::Add(api::WeightedAddrSet { addrs, metric_labels, })) => { let addr_metas = addrs .into_iter() .filter_map(|addr| pb::to_addr_meta(addr, &metric_labels)) .collect::<Vec<_>>(); if !addr_metas.is_empty() { return Ok(Update::Add(addr_metas).into()); } } Some(api::update::Update::Remove(api::AddrSet { addrs })) => { let sock_addrs = addrs .into_iter() .filter_map(pb::to_sock_addr) .collect::<Vec<_>>(); if !sock_addrs.is_empty() { return Ok(Update::Remove(sock_addrs).into()); } } Some(api::update::Update::NoEndpoints(api::NoEndpoints { exists })) => { let update = if exists { Update::Empty } else { Update::DoesNotExist }; return Ok(update.int
}
o()); } None => {} }, None => return Err(grpc::Status::new(grpc::Code::Ok, "end of stream")), }; } }
function_block-function_prefixed
[ { "content": "pub fn layer() -> map_target::Layer<impl Fn(Endpoint) -> Endpoint + Copy> {\n\n map_target::layer(|mut ep: Endpoint| {\n\n debug!(\"rewriting inbound address to loopback; addr={:?}\", ep.addr);\n\n ep.addr = SocketAddr::from(([127, 0, 0, 1], ep.addr.port()));\n\n ep\n\n })\n\n}\n", "file_path": "linkerd/app/inbound/src/rewrite_loopback_addr.rs", "rank": 0, "score": 401151.47503616643 }, { "content": "type ReqBody = Box<dyn Stream<Item = Bytes, Error = ()> + Send>;\n", "file_path": "linkerd/app/integration/src/server.rs", "rank": 1, "score": 339183.1004963318 }, { "content": "pub fn trace_labels() -> HashMap<String, String> {\n\n let mut l = HashMap::new();\n\n l.insert(\"direction\".to_string(), \"outbound\".to_string());\n\n l\n\n}\n", "file_path": "linkerd/app/outbound/src/lib.rs", "rank": 2, "score": 293820.3851806534 }, { "content": "pub fn trace_labels() -> HashMap<String, String> {\n\n let mut l = HashMap::new();\n\n l.insert(\"direction\".to_string(), \"inbound\".to_string());\n\n l\n\n}\n", "file_path": "linkerd/app/inbound/src/lib.rs", "rank": 3, "score": 293820.3851806534 }, { "content": "pub fn http_request_host_addr<B>(req: &http::Request<B>) -> Result<Addr, addr::Error> {\n\n use crate::proxy::http::h1;\n\n\n\n h1::authority_from_host(req)\n\n .ok_or(addr::Error::InvalidHost)\n\n .and_then(|a| Addr::from_authority_and_default_port(&a, DEFAULT_PORT))\n\n}\n\n\n", "file_path": "linkerd/app/core/src/lib.rs", "rank": 4, "score": 290965.14111250127 }, { "content": "pub fn http_request_authority_addr<B>(req: &http::Request<B>) -> Result<Addr, addr::Error> {\n\n req.uri()\n\n .authority_part()\n\n .ok_or(addr::Error::InvalidHost)\n\n .and_then(|a| Addr::from_authority_and_default_port(a, DEFAULT_PORT))\n\n}\n\n\n", "file_path": "linkerd/app/core/src/lib.rs", "rank": 5, "score": 290965.14111250127 }, { "content": "pub fn destination_exists_with_no_endpoints() -> pb::Update {\n\n pb::Update {\n\n update: Some(pb::update::Update::NoEndpoints(pb::NoEndpoints {\n\n exists: true,\n\n })),\n\n }\n\n}\n\n\n", "file_path": "linkerd/app/integration/src/controller.rs", "rank": 6, "score": 290549.039636834 }, { "content": "pub fn http_request_orig_dst_addr<B>(req: &http::Request<B>) -> Result<Addr, addr::Error> {\n\n use crate::transport::tls;\n\n\n\n req.extensions()\n\n .get::<tls::accept::Meta>()\n\n .and_then(|m| m.addrs.target_addr_if_not_local())\n\n .map(Addr::Socket)\n\n .ok_or(addr::Error::InvalidHost)\n\n}\n\n\n\n#[derive(Copy, Clone, Debug)]\n\npub struct DispatchDeadline(std::time::Instant);\n\n\n\nimpl DispatchDeadline {\n\n pub fn after(allowance: std::time::Duration) -> DispatchDeadline {\n\n DispatchDeadline(tokio_timer::clock::now() + allowance)\n\n }\n\n\n\n pub fn extract<A>(req: &http::Request<A>) -> Option<std::time::Instant> {\n\n req.extensions().get::<DispatchDeadline>().map(|d| d.0)\n", "file_path": "linkerd/app/core/src/lib.rs", "rank": 7, "score": 288855.3946015814 }, { "content": "pub fn http1<T: Into<String>>(addr: SocketAddr, auth: T) -> Client {\n\n Client::new(\n\n addr,\n\n auth.into(),\n\n Run::Http1 {\n\n absolute_uris: false,\n\n },\n\n None,\n\n )\n\n}\n\n\n", "file_path": "linkerd/app/integration/src/client.rs", "rank": 8, "score": 287925.53824587044 }, { "content": "pub fn new<T: Into<String>>(addr: SocketAddr, auth: T) -> Client {\n\n http2(addr, auth.into())\n\n}\n\n\n", "file_path": "linkerd/app/integration/src/client.rs", "rank": 9, "score": 287925.53824587044 }, { "content": "pub fn http2<T: Into<String>>(addr: SocketAddr, auth: T) -> Client {\n\n Client::new(addr, auth.into(), Run::Http2, None)\n\n}\n\n\n", "file_path": "linkerd/app/integration/src/client.rs", "rank": 10, "score": 287925.53824587044 }, { "content": "pub fn http_request_l5d_override_dst_addr<B>(req: &http::Request<B>) -> Result<Addr, addr::Error> {\n\n proxy::http::authority_from_header(req, DST_OVERRIDE_HEADER)\n\n .ok_or(addr::Error::InvalidHost)\n\n .and_then(|a| Addr::from_authority_and_default_port(&a, DEFAULT_PORT))\n\n}\n\n\n", "file_path": "linkerd/app/core/src/lib.rs", "rank": 11, "score": 286798.91890832625 }, { "content": "pub fn layer() -> Layer<&'static str, Endpoint, ResHeader> {\n\n add_header::response::layer(L5D_SERVER_ID, |endpoint: &Endpoint| {\n\n if let Conditional::Some(id) = endpoint.identity.as_ref() {\n\n match HeaderValue::from_str(id.as_ref()) {\n\n Ok(value) => {\n\n debug!(\"l5d-server-id enabled for {:?}\", endpoint);\n\n return Some(value);\n\n }\n\n Err(_err) => {\n\n warn!(\"l5d-server-id identity header is invalid: {:?}\", endpoint);\n\n }\n\n };\n\n }\n\n\n\n None\n\n })\n\n}\n", "file_path": "linkerd/app/outbound/src/add_server_id_on_rsp.rs", "rank": 12, "score": 286571.9569787495 }, { "content": "pub fn layer() -> Layer<&'static str, Endpoint, ResHeader> {\n\n add_header::response::layer(L5D_REMOTE_IP, |endpoint: &Endpoint| {\n\n HeaderValue::from_shared(Bytes::from(endpoint.addr.ip().to_string())).ok()\n\n })\n\n}\n", "file_path": "linkerd/app/outbound/src/add_remote_ip_on_rsp.rs", "rank": 13, "score": 286571.9569787495 }, { "content": "pub fn client_with_auth<T: Into<String>>(addr: SocketAddr, auth: T) -> Client {\n\n let api = pb::client::Tap::new(SyncSvc(client::http2(addr, auth)));\n\n Client { api }\n\n}\n\n\n\npub struct Client {\n\n api: pb::client::Tap<SyncSvc>,\n\n}\n\n\n\nimpl Client {\n\n pub fn observe(\n\n &mut self,\n\n req: ObserveBuilder,\n\n ) -> impl Stream<Item = pb::TapEvent, Error = tower_grpc::Status> {\n\n let req = tower_grpc::Request::new(req.0);\n\n self.api\n\n .observe(req)\n\n .wait()\n\n .expect(\"tap observe wait\")\n\n .into_inner()\n", "file_path": "linkerd/app/integration/src/tap.rs", "rank": 14, "score": 285478.0417639055 }, { "content": "/// This sends `GET http://foo.com/ HTTP/1.1` instead of just `GET / HTTP/1.1`.\n\npub fn http1_absolute_uris<T: Into<String>>(addr: SocketAddr, auth: T) -> Client {\n\n Client::new(\n\n addr,\n\n auth.into(),\n\n Run::Http1 {\n\n absolute_uris: true,\n\n },\n\n None,\n\n )\n\n}\n\n\n", "file_path": "linkerd/app/integration/src/client.rs", "rank": 15, "score": 283102.76867751725 }, { "content": "pub fn init_log_compat() -> Result<(), Error> {\n\n tracing_log::LogTracer::init().map_err(Error::from)\n\n}\n\n\n", "file_path": "linkerd/app/core/src/trace.rs", "rank": 16, "score": 280297.55019966845 }, { "content": "pub fn layer<G, Inner, RouteLayer, RouteBody, InnerBody>(\n\n get_routes: G,\n\n route_layer: RouteLayer,\n\n) -> Layer<G, Inner, RouteLayer, RouteBody, InnerBody>\n\nwhere\n\n G: GetRoutes + Clone,\n\n RouteLayer: Clone,\n\n{\n\n Layer {\n\n get_routes,\n\n route_layer,\n\n default_route: Route::default(),\n\n _p: ::std::marker::PhantomData,\n\n }\n\n}\n\n\n\n#[derive(Debug)]\n\npub struct Layer<G, Inner, RouteLayer, RouteBody, InnerBody> {\n\n get_routes: G,\n\n route_layer: RouteLayer,\n", "file_path": "linkerd/proxy/http/src/profiles/router.rs", "rank": 17, "score": 278977.35232435825 }, { "content": "pub fn destination_add(addr: SocketAddr) -> pb::Update {\n\n destination_add_hinted(addr, Hint::Unknown)\n\n}\n\n\n", "file_path": "linkerd/app/integration/src/controller.rs", "rank": 18, "score": 277980.53657826537 }, { "content": "/// Initialize tracing and logging with the value of the `ENV_LOG`\n\n/// environment variable as the verbosity-level filter.\n\npub fn init() -> Result<LevelHandle, Error> {\n\n let env = env::var(ENV_LOG).unwrap_or_default();\n\n let (dispatch, handle) = with_filter(env);\n\n\n\n // Set up log compatibility.\n\n init_log_compat()?;\n\n // Set the default subscriber.\n\n tracing::dispatcher::set_global_default(dispatch)?;\n\n Ok(handle)\n\n}\n\n\n", "file_path": "linkerd/app/core/src/trace.rs", "rank": 19, "score": 276027.83845695324 }, { "content": "type ShutdownSignal = Box<dyn Future<Item = (), Error = ()> + Send>;\n\n\n", "file_path": "linkerd/signal/src/lib.rs", "rank": 20, "score": 274363.5717917977 }, { "content": "pub fn http2_tls<T: Into<String>>(addr: SocketAddr, auth: T, tls: TlsConfig) -> Client {\n\n Client::new(addr, auth.into(), Run::Http2, Some(tls))\n\n}\n\n\n", "file_path": "linkerd/app/integration/src/client.rs", "rank": 21, "score": 271511.1854887792 }, { "content": "pub fn http1_tls<T: Into<String>>(addr: SocketAddr, auth: T, tls: TlsConfig) -> Client {\n\n Client::new(\n\n addr,\n\n auth.into(),\n\n Run::Http1 {\n\n absolute_uris: false,\n\n },\n\n Some(tls),\n\n )\n\n}\n\n\n", "file_path": "linkerd/app/integration/src/client.rs", "rank": 22, "score": 271511.1854887792 }, { "content": "pub trait MapEndpoint<Target, In> {\n\n type Out;\n\n fn map_endpoint(&self, target: &Target, addr: SocketAddr, in_ep: In) -> Self::Out;\n\n}\n\n\n\n#[derive(Clone, Debug)]\n\npub struct Resolve<M, R> {\n\n resolve: R,\n\n map: M,\n\n}\n\n\n\n#[derive(Debug)]\n\npub struct ResolveFuture<T, F, M> {\n\n future: F,\n\n target: Option<T>,\n\n map: Option<M>,\n\n}\n\n\n\n#[derive(Clone, Debug)]\n\npub struct Resolution<T, M, R> {\n", "file_path": "linkerd/proxy/resolve/src/map_endpoint.rs", "rank": 23, "score": 264802.6233987664 }, { "content": "pub fn destination_add_hinted(addr: SocketAddr, hint: Hint) -> pb::Update {\n\n destination_add_labeled(addr, hint, HashMap::new(), HashMap::new())\n\n}\n\n\n", "file_path": "linkerd/app/integration/src/controller.rs", "rank": 24, "score": 263489.9224162043 }, { "content": "pub fn destination_add_tls(addr: SocketAddr, local_id: &str) -> pb::Update {\n\n pb::Update {\n\n update: Some(pb::update::Update::Add(pb::WeightedAddrSet {\n\n addrs: vec![pb::WeightedAddr {\n\n addr: Some(net::TcpAddress {\n\n ip: Some(ip_conv(addr.ip())),\n\n port: u32::from(addr.port()),\n\n }),\n\n tls_identity: Some(pb::TlsIdentity {\n\n strategy: Some(pb::tls_identity::Strategy::DnsLikeIdentity(\n\n pb::tls_identity::DnsLikeIdentity {\n\n name: local_id.into(),\n\n },\n\n )),\n\n }),\n\n ..Default::default()\n\n }],\n\n ..Default::default()\n\n })),\n\n }\n\n}\n\n\n", "file_path": "linkerd/app/integration/src/controller.rs", "rank": 25, "score": 261108.61898326816 }, { "content": "pub fn with_filter(filter: impl AsRef<str>) -> (Dispatch, LevelHandle) {\n\n let filter = filter.as_ref();\n\n\n\n // Set up the subscriber\n\n let builder = subscriber_builder()\n\n .with_env_filter(filter)\n\n .with_filter_reloading();\n\n let handle = LevelHandle {\n\n inner: builder.reload_handle(),\n\n };\n\n let dispatch = Dispatch::new(builder.finish());\n\n\n\n (dispatch, handle)\n\n}\n\n\n", "file_path": "linkerd/app/core/src/trace.rs", "rank": 26, "score": 256973.97238013422 }, { "content": "fn h2_error(err: &Error) -> String {\n\n if let Some(reason) = err.h2_reason() {\n\n // This should output the error code in the same format as the spec,\n\n // for example: PROTOCOL_ERROR\n\n format!(\"h2({:?})\", reason)\n\n } else {\n\n trace!(\"classifying found non-h2 error: {:?}\", err);\n\n String::from(\"unclassified\")\n\n }\n\n}\n\n\n\n// === impl Class ===\n\n\n\nimpl Class {\n\n pub(super) fn is_failure(&self) -> bool {\n\n match self {\n\n Class::Default(SuccessOrFailure::Failure)\n\n | Class::Grpc(SuccessOrFailure::Failure, _)\n\n | Class::Stream(SuccessOrFailure::Failure, _) => true,\n\n _ => false,\n", "file_path": "linkerd/app/core/src/classify.rs", "rank": 27, "score": 251233.61464510323 }, { "content": "type BoxError = Box<dyn std::error::Error + Send + Sync>;\n\n\n", "file_path": "linkerd/app/integration/src/server.rs", "rank": 28, "score": 248481.8553754841 }, { "content": "fn response_labels<Body>(labels: &mut HashMap<String, String>, rsp: &http::Response<Body>) {\n\n labels.insert(\n\n \"http.status_code\".to_string(),\n\n rsp.status().as_str().to_string(),\n\n );\n\n}\n", "file_path": "linkerd/trace-context/src/layer.rs", "rank": 29, "score": 248002.02844120565 }, { "content": "fn request_labels<Body>(labels: &mut HashMap<String, String>, req: &http::Request<Body>) {\n\n labels.insert(\"http.method\".to_string(), format!(\"{}\", req.method()));\n\n let path = req\n\n .uri()\n\n .path_and_query()\n\n .map(|pq| pq.as_str().to_owned())\n\n .unwrap_or_default();\n\n labels.insert(\"http.path\".to_string(), path);\n\n if let Some(authority) = req.uri().authority_part() {\n\n labels.insert(\"http.authority\".to_string(), authority.as_str().to_string());\n\n }\n\n if let Some(host) = req.headers().get(\"host\") {\n\n if let Ok(host) = host.to_str() {\n\n labels.insert(\"http.host\".to_string(), host.to_string());\n\n }\n\n }\n\n}\n\n\n", "file_path": "linkerd/trace-context/src/layer.rs", "rank": 30, "score": 248002.02844120565 }, { "content": "pub fn destination_does_not_exist() -> pb::Update {\n\n pb::Update {\n\n update: Some(pb::update::Update::NoEndpoints(pb::NoEndpoints {\n\n exists: false,\n\n })),\n\n }\n\n}\n\n\n", "file_path": "linkerd/app/integration/src/controller.rs", "rank": 31, "score": 247967.0792086033 }, { "content": "pub fn parse_control_addr<S: Strings>(\n\n strings: &S,\n\n base: &str,\n\n) -> Result<Option<ControlAddr>, EnvError> {\n\n let a_env = format!(\"{}_ADDR\", base);\n\n let a = parse(strings, &a_env, parse_addr);\n\n let n_env = format!(\"{}_NAME\", base);\n\n let n = parse(strings, &n_env, parse_identity);\n\n match (a?, n?) {\n\n (None, None) => Ok(None),\n\n (Some(ref addr), _) if addr.is_loopback() => Ok(Some(ControlAddr {\n\n addr: addr.clone(),\n\n identity: tls::Conditional::None(tls::ReasonForNoPeerName::Loopback.into()),\n\n })),\n\n (Some(addr), Some(name)) => Ok(Some(ControlAddr {\n\n addr,\n\n identity: tls::Conditional::Some(name),\n\n })),\n\n (Some(_), None) => {\n\n error!(\"{} must be specified when {} is set\", n_env, a_env);\n\n Err(EnvError::InvalidEnvVar)\n\n }\n\n (None, Some(_)) => {\n\n error!(\"{} must be specified when {} is set\", a_env, n_env);\n\n Err(EnvError::InvalidEnvVar)\n\n }\n\n }\n\n}\n\n\n", "file_path": "linkerd/app/src/env.rs", "rank": 32, "score": 247770.5759506042 }, { "content": "/// The Rust test runner creates a thread per unit test, naming it after\n\n/// the function name. If still in that thread, this can be useful to allow\n\n/// associating test logs with a specific test, since tests *can* be run in\n\n/// parallel.\n\npub fn thread_name() -> String {\n\n ::std::thread::current()\n\n .name()\n\n .unwrap_or(\"<no-name>\")\n\n .to_owned()\n\n}\n\n\n", "file_path": "linkerd/app/integration/src/lib.rs", "rank": 33, "score": 243919.1548232244 }, { "content": "pub fn parse_control_addr_disable_identity<S: Strings>(\n\n strings: &S,\n\n base: &str,\n\n) -> Result<Option<ControlAddr>, EnvError> {\n\n let a = parse(strings, &format!(\"{}_ADDR\", base), parse_addr)?;\n\n let identity = tls::Conditional::None(tls::ReasonForNoIdentity::Disabled);\n\n Ok(a.map(|addr| ControlAddr { addr, identity }))\n\n}\n\n\n", "file_path": "linkerd/app/src/env.rs", "rank": 34, "score": 241858.55868895855 }, { "content": "pub fn client(addr: SocketAddr) -> Client {\n\n let api = pb::client::Tap::new(SyncSvc(client::http2(addr, \"localhost\")));\n\n Client { api }\n\n}\n\n\n", "file_path": "linkerd/app/integration/src/tap.rs", "rank": 35, "score": 241505.75848407776 }, { "content": "pub fn layer<M>() -> impl layer::Layer<M, Service = Stack<M>> + Copy {\n\n layer::mk(|inner| Stack { inner })\n\n}\n\n\n\n// === impl Stack ===\n\n\n\nimpl<T, M> tower::Service<T> for Stack<M>\n\nwhere\n\n T: HasSettings,\n\n M: tower::Service<T>,\n\n{\n\n type Response = tower::util::Either<Service<M::Response>, M::Response>;\n\n type Error = M::Error;\n\n type Future = MakeFuture<M::Future>;\n\n\n\n fn poll_ready(&mut self) -> Poll<(), M::Error> {\n\n self.inner.poll_ready()\n\n }\n\n\n\n fn call(&mut self, target: T) -> Self::Future {\n", "file_path": "linkerd/proxy/http/src/normalize_uri.rs", "rank": 36, "score": 240645.0500975478 }, { "content": "pub fn client(addr: SocketAddr) -> TcpClient {\n\n let tx = run_client(addr);\n\n TcpClient { addr, tx }\n\n}\n\n\n", "file_path": "linkerd/app/integration/src/tcp.rs", "rank": 37, "score": 239491.25308623802 }, { "content": "pub fn tcp(addr: SocketAddr) -> tcp::TcpClient {\n\n tcp::client(addr)\n\n}\n\n\n\npub struct Client {\n\n authority: String,\n\n /// This is a future that completes when the associated connection for\n\n /// this Client has been dropped.\n\n running: Running,\n\n tx: Sender,\n\n version: http::Version,\n\n tls: Option<TlsConfig>,\n\n}\n\n\n\nimpl Client {\n\n fn new(addr: SocketAddr, authority: String, r: Run, tls: Option<TlsConfig>) -> Client {\n\n let v = match r {\n\n Run::Http1 { .. } => http::Version::HTTP_11,\n\n Run::Http2 => http::Version::HTTP_2,\n\n };\n", "file_path": "linkerd/app/integration/src/client.rs", "rank": 38, "score": 233617.0346914087 }, { "content": "pub fn layer<T, G: GetSpan<T> + Clone>(get_span: G) -> Layer<T, G> {\n\n Layer::new(get_span)\n\n}\n", "file_path": "linkerd/app/core/src/trace.rs", "rank": 39, "score": 233321.0943159756 }, { "content": "/// Load a `App` by reading ENV variables.\n\npub fn parse_config<S: Strings>(strings: &S) -> Result<super::Config, EnvError> {\n\n // Parse all the environment variables. `parse` will log any errors so\n\n // defer returning any errors until all of them have been parsed.\n\n let outbound_listener_addr = parse(strings, ENV_OUTBOUND_LISTEN_ADDR, parse_socket_addr);\n\n let inbound_listener_addr = parse(strings, ENV_INBOUND_LISTEN_ADDR, parse_socket_addr);\n\n let admin_listener_addr = parse(strings, ENV_ADMIN_LISTEN_ADDR, parse_socket_addr);\n\n\n\n let inbound_dispatch_timeout = parse(strings, ENV_INBOUND_DISPATCH_TIMEOUT, parse_duration);\n\n let inbound_connect_timeout = parse(strings, ENV_INBOUND_CONNECT_TIMEOUT, parse_duration);\n\n\n\n let outbound_dispatch_timeout = parse(strings, ENV_OUTBOUND_DISPATCH_TIMEOUT, parse_duration);\n\n let outbound_connect_timeout = parse(strings, ENV_OUTBOUND_CONNECT_TIMEOUT, parse_duration);\n\n\n\n let inbound_accept_keepalive = parse(strings, ENV_INBOUND_ACCEPT_KEEPALIVE, parse_duration);\n\n let outbound_accept_keepalive = parse(strings, ENV_OUTBOUND_ACCEPT_KEEPALIVE, parse_duration);\n\n\n\n let inbound_connect_keepalive = parse(strings, ENV_INBOUND_CONNECT_KEEPALIVE, parse_duration);\n\n let outbound_connect_keepalive = parse(strings, ENV_OUTBOUND_CONNECT_KEEPALIVE, parse_duration);\n\n\n\n let inbound_disable_ports = parse(\n", "file_path": "linkerd/app/src/env.rs", "rank": 40, "score": 229522.21543907587 }, { "content": "struct RunningIo(pub Box<dyn Io + Send>, pub Option<oneshot::Sender<()>>);\n\n\n\nimpl Read for RunningIo {\n\n fn read(&mut self, buf: &mut [u8]) -> io::Result<usize> {\n\n self.0.read(buf)\n\n }\n\n}\n\n\n\nimpl Write for RunningIo {\n\n fn write(&mut self, buf: &[u8]) -> io::Result<usize> {\n\n self.0.write(buf)\n\n }\n\n\n\n fn flush(&mut self) -> io::Result<()> {\n\n self.0.flush()\n\n }\n\n}\n\n\n\nimpl AsyncRead for RunningIo {}\n\n\n\nimpl AsyncWrite for RunningIo {\n\n fn shutdown(&mut self) -> Poll<(), io::Error> {\n\n self.0.shutdown()\n\n }\n\n}\n\n\n", "file_path": "linkerd/app/integration/src/lib.rs", "rank": 41, "score": 228929.56510004657 }, { "content": "pub fn trace_init() -> (Dispatch, app::core::trace::LevelHandle) {\n\n use std::env;\n\n let log = env::var(\"LINKERD2_PROXY_LOG\")\n\n .or_else(|_| env::var(\"RUST_LOG\"))\n\n .unwrap_or_else(|_| DEFAULT_LOG.to_owned());\n\n env::set_var(\"RUST_LOG\", &log);\n\n env::set_var(\"LINKERD2_PROXY_LOG\", &log);\n\n // This may fail, since the global log compat layer may have been\n\n // initialized by another test.\n\n let _ = app::core::trace::init_log_compat();\n\n app::core::trace::with_filter(&log)\n\n}\n\n\n\n/// Retry an assertion up to a specified number of times, waiting\n\n/// `RUST_TEST_PATIENCE_MS` between retries.\n\n///\n\n/// If the assertion is successful after a retry, execution will continue\n\n/// normally. If all retries are exhausted and the assertion still fails,\n\n/// `assert_eventually!` will panic as though a regular `assert!` had failed.\n\n/// Note that other panics elsewhere in the code under test will not be\n", "file_path": "linkerd/app/integration/src/lib.rs", "rank": 42, "score": 228288.97850802803 }, { "content": "pub fn stack<S>(inner: S) -> Stack<S> {\n\n Stack(inner)\n\n}\n\n\n\n// Possibly unused, but useful during development.\n\n#[allow(dead_code)]\n\nimpl<L> Layers<L> {\n\n pub fn push<O>(self, outer: O) -> Layers<Pair<L, O>> {\n\n Layers(Pair::new(self.0, outer))\n\n }\n\n\n\n /// Buffer requests when when the next layer is out of capacity.\n\n pub fn push_pending(self) -> Layers<Pair<L, pending::Layer>> {\n\n self.push(pending::layer())\n\n }\n\n\n\n /// Buffer requests when when the next layer is out of capacity.\n\n pub fn push_buffer_pending<D, Req>(\n\n self,\n\n bound: usize,\n", "file_path": "linkerd/app/core/src/svc.rs", "rank": 43, "score": 220866.98007108422 }, { "content": "/// Determintes whether the given `input` looks like the start of a TLS\n\n/// connection that the proxy should terminate.\n\n///\n\n/// The determination is made based on whether the input looks like (the start\n\n/// of) a valid ClientHello that a reasonable TLS client might send, and the\n\n/// SNI matches the given identity.\n\n///\n\n/// XXX: Once the TLS record header is matched, the determination won't be\n\n/// made until the entire TLS record including the entire ClientHello handshake\n\n/// message is available. TODO: Reject non-matching inputs earlier.\n\n///\n\n/// This assumes that the ClientHello is small and is sent in a single TLS\n\n/// record, which is what all reasonable implementations do. (If they were not\n\n/// to, they wouldn't interoperate with picky servers.)\n\npub fn match_client_hello(input: &[u8], identity: &identity::Name) -> Match {\n\n let r = untrusted::Input::from(input).read_all(untrusted::EndOfInput, |input| {\n\n let r = extract_sni(input);\n\n input.skip_to_end(); // Ignore anything after what we parsed.\n\n r\n\n });\n\n match r {\n\n Ok(Some(sni)) => {\n\n let m = identity::Name::from_hostname(sni.as_slice_less_safe())\n\n .map(|sni| {\n\n if sni == *identity {\n\n Match::Matched\n\n } else {\n\n Match::NotMatched\n\n }\n\n })\n\n .unwrap_or(Match::NotMatched);\n\n trace!(\n\n \"match_client_hello: parsed correctly up to SNI; matches: {:?}\",\n\n m\n", "file_path": "linkerd/proxy/transport/src/tls/conditional_accept.rs", "rank": 44, "score": 219682.31434218242 }, { "content": "// A router which routes based on the \"route\" of the target.\n\ntype RouteRouter<Target, RouteTarget, Svc, Body> =\n\n rt::Router<http::Request<Body>, RouteRecognize<Target>, rt::FixedMake<RouteTarget, Svc>>;\n\n\n", "file_path": "linkerd/proxy/http/src/profiles/router.rs", "rank": 45, "score": 212819.97504805063 }, { "content": "pub fn layer<R: Recover + Clone>(recover: R) -> Layer<R> {\n\n recover.into()\n\n}\n", "file_path": "linkerd/reconnect/src/lib.rs", "rank": 46, "score": 212358.08365675292 }, { "content": "pub fn dst_override(authority: String, weight: u32) -> pb::WeightedDst {\n\n pb::WeightedDst { authority, weight }\n\n}\n\n\n", "file_path": "linkerd/app/integration/src/controller.rs", "rank": 47, "score": 211234.71301268585 }, { "content": "/// A mockable source for address info, i.e., for tests.\n\npub trait OrigDstAddr: Clone {\n\n fn orig_dst_addr(&self, socket: &TcpStream) -> Option<SocketAddr>;\n\n}\n\n\n\n#[derive(Clone, Debug)]\n\npub struct Bind<O: OrigDstAddr = NoOrigDstAddr> {\n\n bind_addr: SocketAddr,\n\n keepalive: Option<Duration>,\n\n orig_dst_addr: O,\n\n}\n\n\n\n#[derive(Debug)]\n\npub struct Listen<O: OrigDstAddr = NoOrigDstAddr> {\n\n listen_addr: SocketAddr,\n\n keepalive: Option<Duration>,\n\n orig_dst_addr: O,\n\n state: State,\n\n}\n\n\n\npub type Connection = (Addrs, TcpStream);\n", "file_path": "linkerd/proxy/transport/src/listen.rs", "rank": 48, "score": 210784.35589806823 }, { "content": "struct Inner<T, E: Recover, R: resolve::Resolve<T>> {\n\n target: T,\n\n resolve: R,\n\n recover: E,\n\n state: State<R::Future, R::Resolution, E::Backoff>,\n\n}\n\n\n\n// #[derive(Debug)]\n\n// struct Cache<T> {\n\n// active: IndexMap<SocketAddr, T>,\n\n// }\n\n\n", "file_path": "linkerd/proxy/resolve/src/recover.rs", "rank": 49, "score": 209303.72199252783 }, { "content": "/// Layer to map HTTP service errors into appropriate `http::Response`s.\n\npub fn layer() -> Layer {\n\n Layer\n\n}\n\n\n\n#[derive(Clone, Debug)]\n\npub struct Layer;\n\n\n\n#[derive(Clone, Debug)]\n\npub struct Stack<M> {\n\n inner: M,\n\n}\n\n\n\n#[derive(Clone, Debug)]\n\npub struct Service<S>(S);\n\n\n\n#[derive(Debug)]\n\npub struct ResponseFuture<F> {\n\n inner: F,\n\n is_http2: bool,\n\n}\n", "file_path": "linkerd/app/core/src/errors.rs", "rank": 50, "score": 208981.0354626343 }, { "content": "pub fn new<S>(\n\n service: S,\n\n suffixes: impl IntoIterator<Item = Suffix>,\n\n nets: impl IntoIterator<Item = IpNet>,\n\n token: &str,\n\n backoff: ExponentialBackoff,\n\n) -> Resolve<S>\n\nwhere\n\n S: GrpcService<BoxBody> + Clone + Send + 'static,\n\n S::ResponseBody: Send,\n\n <S::ResponseBody as Body>::Data: Send,\n\n S::Future: Send,\n\n{\n\n request_filter::Service::new::<DstAddr>(\n\n PermitConfiguredDsts::new(suffixes, nets),\n\n recover::Resolve::new::<DstAddr>(\n\n backoff.into(),\n\n api::Resolve::new::<DstAddr>(service).with_context_token(token),\n\n ),\n\n )\n", "file_path": "linkerd/app/src/dst/resolve.rs", "rank": 51, "score": 208891.53582354507 }, { "content": "// A router which routes based on the `dst_overrides` of the profile or, if\n\n// no `dst_overrdies` exist, on the router's target.\n\ntype ConcreteRouter<Target, Svc, Body> =\n\n rt::Router<http::Request<Body>, ConcreteDstRecognize<Target>, rt::FixedMake<Target, Svc>>;\n\n\n", "file_path": "linkerd/proxy/http/src/profiles/router.rs", "rank": 52, "score": 208721.23849936406 }, { "content": "fn parse_addr(s: &str) -> Result<Addr, ParseError> {\n\n Addr::from_str(s).map_err(|e| {\n\n error!(\"Not a valid address: {}\", s);\n\n ParseError::AddrError(e)\n\n })\n\n}\n\n\n", "file_path": "linkerd/app/src/env.rs", "rank": 53, "score": 207948.54912437673 }, { "content": "#[derive(Clone)]\n\nstruct Target(SocketAddr, Conditional<Name>);\n\n\n", "file_path": "linkerd/proxy/transport/tests/tls_accept.rs", "rank": 54, "score": 207830.7020852493 }, { "content": "pub fn parse_backoff<S: Strings>(\n\n strings: &S,\n\n base: &str,\n\n default: ExponentialBackoff,\n\n) -> Result<ExponentialBackoff, EnvError> {\n\n let min_env = format!(\"LINKERD2_PROXY_{}_EXP_BACKOFF_MIN\", base);\n\n let min = parse(strings, &min_env, parse_duration);\n\n let max_env = format!(\"LINKERD2_PROXY_{}_EXP_BACKOFF_MAX\", base);\n\n let max = parse(strings, &max_env, parse_duration);\n\n let jitter_env = format!(\"LINKERD2_PROXY_{}_EXP_BACKOFF_JITTER\", base);\n\n let jitter = parse(strings, &jitter_env, parse_number::<f64>);\n\n\n\n match (min?, max?, jitter?) {\n\n (None, None, None) => Ok(default),\n\n (Some(min), Some(max), jitter) => {\n\n ExponentialBackoff::new(min, max, jitter.unwrap_or_default()).map_err(|error| {\n\n error!(message=\"Invalid backoff\", %error, %min_env, ?min, %max_env, ?max, %jitter_env, ?jitter);\n\n EnvError::InvalidEnvVar\n\n })\n\n }\n\n _ => {\n\n error!(\"You need to specify either all of {} {} {} or none of them to use the default backoff\", min_env, max_env,jitter_env );\n\n Err(EnvError::InvalidEnvVar)\n\n }\n\n }\n\n}\n\n\n", "file_path": "linkerd/app/src/env.rs", "rank": 55, "score": 203651.88126244667 }, { "content": "pub fn layer() -> Layer<&'static str, tls::accept::Meta, ReqHeader> {\n\n add_header::request::layer(L5D_CLIENT_ID, |source: &tls::accept::Meta| {\n\n if let Conditional::Some(ref id) = source.peer_identity {\n\n if let Ok(value) = HeaderValue::from_str(id.as_ref()) {\n\n debug!(\"l5d-client-id enabled\");\n\n return Some(value);\n\n }\n\n\n\n warn!(\"l5d-client-id identity header is invalid\");\n\n }\n\n\n\n None\n\n })\n\n}\n", "file_path": "linkerd/app/inbound/src/set_client_id_on_req.rs", "rank": 56, "score": 202770.2638096423 }, { "content": "pub fn layer() -> Layer<&'static str, tls::accept::Meta, ReqHeader> {\n\n add_header::request::layer(L5D_REMOTE_IP, |source: &tls::accept::Meta| {\n\n HeaderValue::from_shared(Bytes::from(source.addrs.peer().ip().to_string())).ok()\n\n })\n\n}\n", "file_path": "linkerd/app/inbound/src/set_remote_ip_on_req.rs", "rank": 57, "score": 202770.2638096423 }, { "content": "fn convert_req_match(orig: api::RequestMatch) -> Option<profiles::RequestMatch> {\n\n let m = match orig.r#match? {\n\n api::request_match::Match::All(ms) => {\n\n let ms = ms.matches.into_iter().filter_map(convert_req_match);\n\n profiles::RequestMatch::All(ms.collect())\n\n }\n\n api::request_match::Match::Any(ms) => {\n\n let ms = ms.matches.into_iter().filter_map(convert_req_match);\n\n profiles::RequestMatch::Any(ms.collect())\n\n }\n\n api::request_match::Match::Not(m) => {\n\n let m = convert_req_match(*m)?;\n\n profiles::RequestMatch::Not(Box::new(m))\n\n }\n\n api::request_match::Match::Path(api::PathMatch { regex }) => {\n\n let regex = regex.trim();\n\n let re = match (regex.starts_with('^'), regex.ends_with('$')) {\n\n (true, true) => Regex::new(regex).ok()?,\n\n (hd_anchor, tl_anchor) => {\n\n let hd = if hd_anchor { \"\" } else { \"^\" };\n", "file_path": "linkerd/app/core/src/profiles.rs", "rank": 58, "score": 201902.15524156616 }, { "content": "fn convert_rsp_match(orig: api::ResponseMatch) -> Option<profiles::ResponseMatch> {\n\n let m = match orig.r#match? {\n\n api::response_match::Match::All(ms) => {\n\n let ms = ms\n\n .matches\n\n .into_iter()\n\n .filter_map(convert_rsp_match)\n\n .collect::<Vec<_>>();\n\n if ms.is_empty() {\n\n return None;\n\n }\n\n profiles::ResponseMatch::All(ms)\n\n }\n\n api::response_match::Match::Any(ms) => {\n\n let ms = ms\n\n .matches\n\n .into_iter()\n\n .filter_map(convert_rsp_match)\n\n .collect::<Vec<_>>();\n\n if ms.is_empty() {\n", "file_path": "linkerd/app/core/src/profiles.rs", "rank": 59, "score": 201902.15524156616 }, { "content": "pub fn parse_identity_config<S: Strings>(\n\n strings: &S,\n\n) -> Result<Option<(ControlAddr, identity::certify::Config)>, EnvError> {\n\n let control = parse_control_addr(strings, ENV_IDENTITY_SVC_BASE);\n\n let ta = parse(strings, ENV_IDENTITY_TRUST_ANCHORS, |ref s| {\n\n identity::TrustAnchors::from_pem(s).ok_or(ParseError::InvalidTrustAnchors)\n\n });\n\n let dir = parse(strings, ENV_IDENTITY_DIR, |ref s| Ok(PathBuf::from(s)));\n\n let tok = parse(strings, ENV_IDENTITY_TOKEN_FILE, |ref s| {\n\n identity::TokenSource::if_nonempty_file(s.to_string()).map_err(|e| {\n\n error!(\"Could not read {}: {}\", ENV_IDENTITY_TOKEN_FILE, e);\n\n ParseError::InvalidTokenSource\n\n })\n\n });\n\n let li = parse(strings, ENV_IDENTITY_IDENTITY_LOCAL_NAME, parse_identity);\n\n let min_refresh = parse(strings, ENV_IDENTITY_MIN_REFRESH, parse_duration);\n\n let max_refresh = parse(strings, ENV_IDENTITY_MAX_REFRESH, parse_duration);\n\n\n\n let disabled = strings\n\n .get(ENV_IDENTITY_DISABLED)?\n", "file_path": "linkerd/app/src/env.rs", "rank": 60, "score": 201327.61636174202 }, { "content": "pub fn svc<T: HasPeerAddr>(\n\n keepalive: Option<Duration>,\n\n) -> impl Service<T, Response = TcpStream, Error = io::Error, Future = ConnectFuture> + Clone {\n\n service_fn(move |target: T| {\n\n let addr = target.peer_addr();\n\n debug!(\"connecting to {}\", addr);\n\n ConnectFuture {\n\n addr,\n\n keepalive,\n\n future: TcpStream::connect(&addr),\n\n }\n\n })\n\n}\n\n\n\n#[derive(Debug)]\n\npub struct ConnectFuture {\n\n addr: SocketAddr,\n\n keepalive: Option<Duration>,\n\n future: tcp::ConnectFuture,\n\n}\n", "file_path": "linkerd/proxy/transport/src/connect.rs", "rank": 61, "score": 201265.15655407892 }, { "content": "pub fn layer<L: HasConfig + Clone>(l: super::Conditional<L>) -> Layer<L> {\n\n Layer(l)\n\n}\n\n\n\nimpl<L, C> tower::layer::Layer<C> for Layer<L>\n\nwhere\n\n L: HasConfig + Clone,\n\n{\n\n type Service = Connect<L, C>;\n\n\n\n fn layer(&self, inner: C) -> Self::Service {\n\n Connect {\n\n local: self.0.clone(),\n\n inner,\n\n }\n\n }\n\n}\n\n\n\n// === impl Connect ===\n\n\n", "file_path": "linkerd/proxy/transport/src/tls/client.rs", "rank": 62, "score": 200872.4730984196 }, { "content": "pub fn prefix_labels<'i, I>(prefix: &str, mut labels_iter: I) -> Option<String>\n\nwhere\n\n I: Iterator<Item = (&'i String, &'i String)>,\n\n{\n\n let (k0, v0) = labels_iter.next()?;\n\n let mut out = format!(\"{}_{}=\\\"{}\\\"\", prefix, k0, v0);\n\n\n\n for (k, v) in labels_iter {\n\n write!(out, \",{}_{}=\\\"{}\\\"\", prefix, k, v).expect(\"label concat must succeed\");\n\n }\n\n Some(out)\n\n}\n", "file_path": "linkerd/app/core/src/metric_labels.rs", "rank": 63, "score": 200700.4712375768 }, { "content": "fn rsp(status: StatusCode, body: impl Into<Body>) -> Response<Body> {\n\n Response::builder()\n\n .status(status)\n\n .body(body.into())\n\n .expect(\"builder with known status code must not fail\")\n\n}\n\n\n\n#[cfg(test)]\n\nmod tests {\n\n use super::*;\n\n use http::method::Method;\n\n use linkerd2_test_util::BlockOnFor;\n\n use std::time::Duration;\n\n use tokio::runtime::current_thread::Runtime;\n\n\n\n const TIMEOUT: Duration = Duration::from_secs(1);\n\n\n\n #[test]\n\n fn ready_when_latches_dropped() {\n\n let (r, l0) = Readiness::new();\n", "file_path": "linkerd/app/core/src/admin/mod.rs", "rank": 64, "score": 199464.566144462 }, { "content": "pub fn destination_remove_none() -> pb::Update {\n\n pb::Update {\n\n update: Some(pb::update::Update::Remove(pb::AddrSet {\n\n addrs: Vec::new(),\n\n ..Default::default()\n\n })),\n\n }\n\n}\n\n\n", "file_path": "linkerd/app/integration/src/controller.rs", "rank": 65, "score": 199136.7302268383 }, { "content": "pub fn destination_add_none() -> pb::Update {\n\n pb::Update {\n\n update: Some(pb::update::Update::Add(pb::WeightedAddrSet {\n\n addrs: Vec::new(),\n\n ..Default::default()\n\n })),\n\n }\n\n}\n\n\n", "file_path": "linkerd/app/integration/src/controller.rs", "rank": 66, "score": 199136.7302268383 }, { "content": "// FIXME the resolver should be abstracted to a trait so that this can be tested\n\n// without a real DNS service.\n\npub fn layer(resolver: dns::Resolver, timeout: Duration) -> Layer {\n\n Layer { resolver, timeout }\n\n}\n\n\n\nimpl<M> tower::layer::Layer<M> for Layer\n\nwhere\n\n M: tower::Service<Addr> + Clone,\n\n{\n\n type Service = Stack<M>;\n\n\n\n fn layer(&self, inner: M) -> Self::Service {\n\n Stack {\n\n inner,\n\n resolver: self.resolver.clone(),\n\n timeout: self.timeout,\n\n }\n\n }\n\n}\n\n\n\n// === impl Stack ===\n", "file_path": "linkerd/proxy/http/src/canonicalize.rs", "rank": 67, "score": 196471.71539805422 }, { "content": "pub fn layer<T, M>(map_target: M) -> Layer<M>\n\nwhere\n\n M: MapTarget<T>,\n\n{\n\n Layer(map_target)\n\n}\n\n\n", "file_path": "linkerd/stack/src/map_target.rs", "rank": 68, "score": 194767.08272756424 }, { "content": "pub fn unpack_trace_context<B>(request: &http::Request<B>) -> Option<TraceContext> {\n\n unpack_grpc_trace_context(request).or_else(|| unpack_http_trace_context(request))\n\n}\n\n\n", "file_path": "linkerd/trace-context/src/propagation.rs", "rank": 69, "score": 192905.10397765838 }, { "content": "pub fn layer<A, B>() -> Layer<A, B> {\n\n Layer(PhantomData)\n\n}\n\n\n\nimpl<M, A, B> svc::Layer<M> for Layer<A, B>\n\nwhere\n\n M: svc::MakeService<Endpoint, http::Request<A>, Response = http::Response<B>>,\n\n{\n\n type Service = MakeSvc<M, A, B>;\n\n\n\n fn layer(&self, inner: M) -> Self::Service {\n\n MakeSvc {\n\n inner,\n\n _marker: PhantomData,\n\n }\n\n }\n\n}\n\n\n\nimpl<A, B> Clone for Layer<A, B> {\n\n fn clone(&self) -> Self {\n", "file_path": "linkerd/app/outbound/src/require_identity_on_endpoint.rs", "rank": 70, "score": 189204.83116905237 }, { "content": "pub fn layer<H>(header: H) -> Layer<H>\n\nwhere\n\n H: IntoHeaderName + Clone,\n\n{\n\n Layer { header }\n\n}\n\n\n\nimpl<H, M> tower::layer::Layer<M> for Layer<H>\n\nwhere\n\n H: IntoHeaderName + Clone,\n\n{\n\n type Service = MakeSvc<H, M>;\n\n\n\n fn layer(&self, inner: M) -> Self::Service {\n\n MakeSvc {\n\n header: self.header.clone(),\n\n inner,\n\n }\n\n }\n\n}\n", "file_path": "linkerd/proxy/http/src/header_from_target.rs", "rank": 71, "score": 187278.7955043423 }, { "content": "/// A layer that adds distributed tracing instrumentation.\n\n///\n\n/// This layer reads the `traceparent` HTTP header from the request. If this\n\n/// header is absent, the request is fowarded unmodified. If the header is\n\n/// present, a new span will be started in the current trace by creating a new\n\n/// random span id setting it into the `traceparent` header before forwarding\n\n/// the request. If the sampled bit of the header was set, we emit metadata\n\n/// about the span to the given SpanSink when the span is complete, i.e. when\n\n/// we receive the response.\n\npub fn layer<S>(sink: Option<S>) -> Layer<S> {\n\n Layer { sink }\n\n}\n\n\n\n// === impl Layer ===\n\n\n\nimpl<M, S> tower::layer::Layer<M> for Layer<S>\n\nwhere\n\n S: Clone,\n\n{\n\n type Service = Stack<M, S>;\n\n\n\n fn layer(&self, inner: M) -> Self::Service {\n\n Stack {\n\n inner,\n\n sink: self.sink.clone(),\n\n }\n\n }\n\n}\n\n\n", "file_path": "linkerd/trace-context/src/layer.rs", "rank": 72, "score": 185018.80343416403 }, { "content": "fn parse_grpc_trace_context_field(\n\n buf: &mut Bytes,\n\n context: &mut TraceContext,\n\n) -> Result<(), Error> {\n\n let field_id = try_split_to(buf, 1)?[0];\n\n match field_id {\n\n GRPC_TRACE_FIELD_SPAN_ID => {\n\n let id = try_split_to(buf, 8)?;\n\n trace!(\n\n \"reading binary trace field {:?}: {:?}\",\n\n GRPC_TRACE_FIELD_SPAN_ID,\n\n id\n\n );\n\n context.parent_id = id.into();\n\n }\n\n GRPC_TRACE_FIELD_TRACE_ID => {\n\n let id = try_split_to(buf, 16)?;\n\n trace!(\n\n \"reading binary trace field {:?}: {:?}\",\n\n GRPC_TRACE_FIELD_TRACE_ID,\n", "file_path": "linkerd/trace-context/src/propagation.rs", "rank": 73, "score": 184517.96766427724 }, { "content": "fn convert_dst_override(orig: api::WeightedDst) -> Option<profiles::WeightedAddr> {\n\n if orig.weight == 0 {\n\n return None;\n\n }\n\n NameAddr::from_str(orig.authority.as_str())\n\n .ok()\n\n .map(|addr| profiles::WeightedAddr {\n\n addr,\n\n weight: orig.weight,\n\n })\n\n}\n\n\n", "file_path": "linkerd/app/core/src/profiles.rs", "rank": 74, "score": 184353.92177464245 }, { "content": "/// An infinite stream of endpoint updates.\n\npub trait Resolution {\n\n type Endpoint;\n\n type Error: Into<Error>;\n\n\n\n fn poll(&mut self) -> Poll<Update<Self::Endpoint>, Self::Error>;\n\n}\n\n\n\n#[derive(Clone, Debug)]\n\npub struct Service<S>(S);\n\n\n\n#[derive(Clone, Debug, PartialEq)]\n\npub enum Update<T> {\n\n Add(Vec<(SocketAddr, T)>),\n\n Remove(Vec<SocketAddr>),\n\n Empty,\n\n DoesNotExist,\n\n}\n\n\n\n// === impl Resolve ===\n\n\n", "file_path": "linkerd/proxy/core/src/resolve.rs", "rank": 75, "score": 182253.33769134973 }, { "content": "/// An error recovery strategy.\n\npub trait Recover<E: Into<Error> = Error> {\n\n type Error: Into<Error>;\n\n type Backoff: Stream<Item = (), Error = Self::Error>;\n\n\n\n /// Given an E-typed error, determine if the error is recoverable.\n\n ///\n\n /// If it is, a backoff stream is returned. When the backoff becomes ready,\n\n /// it signals that the caller should retry its operation. If the backoff is\n\n /// polled agian, it is assumed that the operation failed and a new (possibly\n\n /// longer) backoff is initated.\n\n ///\n\n /// If the error is not recoverable, it is returned immediately.\n\n fn recover(&self, err: E) -> Result<Self::Backoff, E>;\n\n}\n\n\n\n#[derive(Copy, Clone, Debug, Default)]\n\npub struct Immediately(());\n\n\n\n// === impl Recover ===\n\n\n", "file_path": "linkerd/error/src/recover.rs", "rank": 76, "score": 181997.99306722882 }, { "content": "struct Inner {\n\n server: TryLock<Option<OnUpgrade>>,\n\n client: TryLock<Option<OnUpgrade>>,\n\n upgrade_drain_signal: Option<drain::Watch>,\n\n}\n\n\n", "file_path": "linkerd/proxy/http/src/upgrade.rs", "rank": 77, "score": 181289.09329545376 }, { "content": "// Generates a new span id, writes it to the request in the appropriate\n\n// propagation format and returns the generated span id.\n\npub fn increment_span_id<B>(request: &mut http::Request<B>, context: &TraceContext) -> Id {\n\n match context.propagation {\n\n Propagation::Grpc => increment_grpc_span_id(request, context),\n\n Propagation::Http => increment_http_span_id(request),\n\n }\n\n}\n\n\n", "file_path": "linkerd/trace-context/src/propagation.rs", "rank": 78, "score": 180314.99489976693 }, { "content": "type ClientError = hyper::Error;\n", "file_path": "linkerd/app/integration/src/client.rs", "rank": 79, "score": 179970.03738947492 }, { "content": "struct InnerFuture<F, B> {\n\n future: F,\n\n _marker: std::marker::PhantomData<fn() -> B>,\n\n}\n\n\n\npub struct Payload {\n\n inner: Box<dyn hyper::body::Payload<Data = Data, Error = Error> + Send + 'static>,\n\n}\n\n\n", "file_path": "linkerd/proxy/http/src/boxed.rs", "rank": 80, "score": 178433.207615022 }, { "content": "#[derive(Clone, Default)]\n\nstruct Labels(Arc<IndexMap<String, String>>);\n\n\n\n// === impl Route ===\n\n\n\nimpl Route {\n\n pub fn new<I>(label_iter: I, response_classes: Vec<ResponseClass>) -> Self\n\n where\n\n I: Iterator<Item = (String, String)>,\n\n {\n\n let labels = {\n\n let mut pairs = label_iter.collect::<Vec<_>>();\n\n pairs.sort_by(|(k0, _), (k1, _)| k0.cmp(k1));\n\n Labels(Arc::new(IndexMap::from_iter(pairs)))\n\n };\n\n\n\n Self {\n\n labels,\n\n response_classes: ResponseClasses(response_classes.into()),\n\n retries: None,\n\n timeout: None,\n", "file_path": "linkerd/proxy/http/src/profiles/mod.rs", "rank": 81, "score": 178098.87468184473 }, { "content": "#[derive(Debug)]\n\nstruct Inner<T> {\n\n buf: BytesMut,\n\n io: T,\n\n}\n\n\n\n// === impl Peek ===\n\n\n\nimpl<T: AsyncRead + AsyncWrite> Peek<T> {\n\n pub fn with_capacity(capacity: usize, io: T) -> Self\n\n where\n\n Self: Sized + Future,\n\n {\n\n let buf = BytesMut::with_capacity(capacity);\n\n Peek(Some(Inner { buf, io }))\n\n }\n\n}\n\n\n\nimpl<T: AsyncRead + AsyncWrite> Future for Peek<T> {\n\n type Item = PrefixedIo<T>;\n\n type Error = io::Error;\n", "file_path": "linkerd/io/src/peek.rs", "rank": 82, "score": 177220.77429587554 }, { "content": "struct MakeFuture<K, F> {\n\n key: Option<K>,\n\n inner: F,\n\n canceled: oneshot::Receiver<()>,\n\n}\n\n\n", "file_path": "linkerd/proxy/discover/src/make_endpoint.rs", "rank": 83, "score": 175883.0516361363 }, { "content": "struct MakeFutures<K, F> {\n\n futures: FuturesUnordered<MakeFuture<K, F>>,\n\n cancelations: IndexMap<K, oneshot::Sender<()>>,\n\n}\n\n\n", "file_path": "linkerd/proxy/discover/src/make_endpoint.rs", "rank": 84, "score": 175883.0516361363 }, { "content": "fn grpc_no_results() -> grpc::Status {\n\n grpc::Status::new(\n\n grpc::Code::Unavailable,\n\n \"unit test controller has no results\",\n\n )\n\n}\n\n\n", "file_path": "linkerd/app/integration/src/controller.rs", "rank": 85, "score": 173681.41500764422 }, { "content": "fn grpc_unexpected_request() -> grpc::Status {\n\n grpc::Status::new(\n\n grpc::Code::Unavailable,\n\n \"unit test controller expected different request\",\n\n )\n\n}\n\n\n\nimpl Stream for DstReceiver {\n\n type Item = pb::Update;\n\n type Error = grpc::Status;\n\n fn poll(&mut self) -> Poll<Option<Self::Item>, Self::Error> {\n\n match try_ready!(self.0.poll().map_err(|_| grpc_internal_code())) {\n\n Some(res) => Ok(Async::Ready(Some(res?))),\n\n None => Ok(Async::Ready(None)),\n\n }\n\n }\n\n}\n\n\n\nimpl DstSender {\n\n pub fn send(&self, up: pb::Update) {\n", "file_path": "linkerd/app/integration/src/controller.rs", "rank": 86, "score": 172320.36032044323 }, { "content": "fn grpc_internal_code() -> grpc::Status {\n\n grpc::Status::new(grpc::Code::Internal, \"unit test controller internal error\")\n\n}\n\n\n", "file_path": "linkerd/app/integration/src/controller.rs", "rank": 87, "score": 172320.36032044323 }, { "content": "fn parse_socket_addr(s: &str) -> Result<SocketAddr, ParseError> {\n\n match parse_addr(s)? {\n\n Addr::Socket(a) => Ok(a),\n\n _ => {\n\n error!(\"Expected IP:PORT; found: {}\", s);\n\n Err(ParseError::HostIsNotAnIpAddress)\n\n }\n\n }\n\n}\n\n\n", "file_path": "linkerd/app/src/env.rs", "rank": 88, "score": 171344.66114384896 }, { "content": "fn parse_grpc_trace_context_fields(buf: &mut Bytes) -> Option<TraceContext> {\n\n trace!(message = \"reading binary trace context\", ?buf);\n\n\n\n let _version = try_split_to(buf, 1).ok()?;\n\n\n\n let mut context = TraceContext {\n\n propagation: Propagation::Grpc,\n\n trace_id: Default::default(),\n\n parent_id: Default::default(),\n\n flags: Default::default(),\n\n };\n\n\n\n while buf.len() > 0 {\n\n match parse_grpc_trace_context_field(buf, &mut context) {\n\n Ok(()) => {}\n\n Err(ref e) if e.is::<UnknownFieldId>() => break,\n\n Err(e) => {\n\n warn!(\"error parsing {} header: {}\", GRPC_TRACE_HEADER, e);\n\n return None;\n\n }\n\n };\n\n }\n\n Some(context)\n\n}\n\n\n", "file_path": "linkerd/trace-context/src/propagation.rs", "rank": 89, "score": 171206.8184315809 }, { "content": "// All of the events emitted from tap have a common set of metadata.\n\n// Build this once, without an `event`, so that it can be used to build\n\n// each HTTP event.\n\nfn base_event<B, I: Inspect>(req: &http::Request<B>, inspect: &I) -> api::TapEvent {\n\n api::TapEvent {\n\n proxy_direction: if inspect.is_outbound(req) {\n\n api::tap_event::ProxyDirection::Outbound.into()\n\n } else {\n\n api::tap_event::ProxyDirection::Inbound.into()\n\n },\n\n source: inspect.src_addr(req).as_ref().map(|a| a.into()),\n\n source_meta: {\n\n let mut m = api::tap_event::EndpointMeta::default();\n\n match inspect.src_tls(req) {\n\n Conditional::None(reason) => {\n\n m.labels.insert(\"tls\".to_owned(), reason.to_string());\n\n }\n\n Conditional::Some(id) => {\n\n m.labels.insert(\"tls\".to_owned(), \"true\".to_owned());\n\n m.labels\n\n .insert(\"client_id\".to_owned(), id.as_ref().to_owned());\n\n }\n\n }\n", "file_path": "linkerd/proxy/tap/src/grpc/server.rs", "rank": 90, "score": 170917.83781570423 }, { "content": "pub trait Make<Target> {\n\n type Value;\n\n\n\n fn make(&self, target: &Target) -> Self::Value;\n\n}\n\n\n\nimpl<F, Target, V> Make<Target> for F\n\nwhere\n\n F: Fn(&Target) -> V,\n\n{\n\n type Value = V;\n\n\n\n fn make(&self, target: &Target) -> Self::Value {\n\n (*self)(target)\n\n }\n\n}\n\n\n\n/// A map of known routes and services used when creating a fixed router.\n\n#[derive(Clone, Debug)]\n\npub struct FixedMake<T: Clone + Eq + Hash, Svc>(IndexMap<T, Svc>);\n", "file_path": "linkerd/router/src/lib.rs", "rank": 91, "score": 169192.27689645853 }, { "content": "#[derive(Copy, Clone, Debug, Eq, PartialEq, Hash)]\n\nstruct Direction(&'static str);\n\n\n", "file_path": "linkerd/app/core/src/transport/labels.rs", "rank": 92, "score": 168589.88209942967 }, { "content": "fn map_err_to_5xx(e: Error) -> StatusCode {\n\n use crate::proxy::buffer;\n\n use linkerd2_router::error as router;\n\n use tower::load_shed::error as shed;\n\n\n\n if let Some(ref c) = e.downcast_ref::<router::NoCapacity>() {\n\n warn!(\"router at capacity ({})\", c.0);\n\n http::StatusCode::SERVICE_UNAVAILABLE\n\n } else if let Some(_) = e.downcast_ref::<shed::Overloaded>() {\n\n warn!(\"server overloaded, max-in-flight reached\");\n\n http::StatusCode::SERVICE_UNAVAILABLE\n\n } else if let Some(_) = e.downcast_ref::<buffer::Aborted>() {\n\n warn!(\"request aborted because it reached the configured dispatch deadline\");\n\n http::StatusCode::SERVICE_UNAVAILABLE\n\n } else if let Some(_) = e.downcast_ref::<router::NotRecognized>() {\n\n error!(\"could not recognize request\");\n\n http::StatusCode::BAD_GATEWAY\n\n } else if let Some(err) = e.downcast_ref::<StatusError>() {\n\n error!(%err.status, %err.message);\n\n err.status\n", "file_path": "linkerd/app/core/src/errors.rs", "rank": 93, "score": 167816.88490405615 }, { "content": " pub trait Tap: Clone {\n\n type TapRequestPayload: TapPayload;\n\n type TapResponse: TapResponse<TapPayload = Self::TapResponsePayload>;\n\n type TapResponsePayload: TapPayload;\n\n\n\n /// Returns `true` as l\n\n fn can_tap_more(&self) -> bool;\n\n\n\n /// Initiate a tap, if it matches.\n\n ///\n\n /// If the tap cannot be initialized, for instance because the tap has\n\n /// completed or been canceled, then `None` is returned.\n\n fn tap<B: Payload, I: super::Inspect>(\n\n &mut self,\n\n req: &http::Request<B>,\n\n inspect: &I,\n\n ) -> Option<(Self::TapRequestPayload, Self::TapResponse)>;\n\n }\n\n\n", "file_path": "linkerd/proxy/tap/src/lib.rs", "rank": 94, "score": 167507.59856120928 }, { "content": "fn unpack_grpc_trace_context<B>(request: &http::Request<B>) -> Option<TraceContext> {\n\n get_header_str(request, GRPC_TRACE_HEADER)\n\n .and_then(|header_str| {\n\n base64::decode(header_str)\n\n .map_err(|e| {\n\n warn!(\n\n \"trace header {} is not base64 encoded: {}\",\n\n GRPC_TRACE_HEADER, e\n\n )\n\n })\n\n .ok()\n\n })\n\n .and_then(|vec| {\n\n let mut bytes = vec.into();\n\n parse_grpc_trace_context_fields(&mut bytes)\n\n })\n\n}\n\n\n", "file_path": "linkerd/trace-context/src/propagation.rs", "rank": 95, "score": 167415.31460814993 }, { "content": "struct Inner<S, A, B> {\n\n service: S,\n\n _marker: std::marker::PhantomData<fn(A) -> B>,\n\n}\n\n\n", "file_path": "linkerd/proxy/http/src/boxed.rs", "rank": 96, "score": 166785.04360505025 }, { "content": "struct Inner<Req, Rec, Mk>\n\nwhere\n\n Rec: Recognize<Req>,\n\n Mk: Make<Rec::Target>,\n\n Mk::Value: tower::Service<Req>,\n\n{\n\n recognize: Rec,\n\n make: Mk,\n\n cache: Lock<Cache<Rec::Target, LoadShed<Mk::Value>>>,\n\n}\n\n\n", "file_path": "linkerd/router/src/lib.rs", "rank": 97, "score": 166785.04360505025 }, { "content": "fn run_client(addr: SocketAddr) -> TcpSender {\n\n let (tx, rx) = mpsc::unbounded();\n\n let tname = format!(\"support tcp client (addr={})\", addr);\n\n ::std::thread::Builder::new()\n\n .name(tname)\n\n .spawn(move || {\n\n let mut core =\n\n runtime::current_thread::Runtime::new().expect(\"support tcp client runtime\");\n\n\n\n let work = rx\n\n .for_each(|cb: oneshot::Sender<_>| {\n\n let fut = TcpStream::connect(&addr)\n\n .map_err(|e| panic!(\"connect error: {}\", e))\n\n .and_then(move |tcp| {\n\n let (tx, rx) = mpsc::unbounded();\n\n cb.send(tx).unwrap();\n\n rx.fold(\n\n tcp,\n\n |tcp,\n\n (action, cb): (\n", "file_path": "linkerd/app/integration/src/tcp.rs", "rank": 98, "score": 166449.00995325105 }, { "content": "fn truncatable(value: String) -> oc::TruncatableString {\n\n oc::TruncatableString {\n\n value,\n\n truncated_byte_count: 0,\n\n }\n\n}\n", "file_path": "linkerd/app/core/src/spans.rs", "rank": 99, "score": 164977.43697164813 } ]
Rust
src/value.rs
basiliqio/messy_json
aa4f6dfbb5bb2a40ee03e7c1cac0b22c4893db59
use super::*; use serde_json::Value; use std::convert::From; use std::ops::Deref; #[derive(Clone, Debug, Eq, PartialEq, Default)] pub struct MessyJsonObjectValue<'a>(BTreeMap<ArcStr, MessyJsonValue<'a>>); #[derive(Clone, Debug, Eq, PartialEq)] pub enum MessyJsonNullType { Null, Absent, } impl<'a> Deref for MessyJsonObjectValue<'a> { type Target = BTreeMap<ArcStr, MessyJsonValue<'a>>; fn deref(&self) -> &Self::Target { &self.0 } } impl<'a> MessyJsonObjectValue<'a> { pub fn take(self) -> BTreeMap<ArcStr, MessyJsonValue<'a>> { self.0 } } impl<'a> From<BTreeMap<ArcStr, MessyJsonValue<'a>>> for MessyJsonObjectValue<'a> { fn from(obj: BTreeMap<ArcStr, MessyJsonValue<'a>>) -> Self { MessyJsonObjectValue(obj) } } impl<'a> From<Vec<MessyJsonValue<'a>>> for MessyJsonArrayValue<'a> { fn from(arr: Vec<MessyJsonValue<'a>>) -> Self { MessyJsonArrayValue(arr) } } impl<'a> MessyJsonArrayValue<'a> { pub fn take(self) -> Vec<MessyJsonValue<'a>> { self.0 } } #[derive(Clone, Debug, Eq, PartialEq)] pub struct MessyJsonArrayValue<'a>(Vec<MessyJsonValue<'a>>); impl<'a> Deref for MessyJsonArrayValue<'a> { type Target = Vec<MessyJsonValue<'a>>; fn deref(&self) -> &Self::Target { &self.0 } } #[derive(Clone, Debug, PartialEq, Eq)] pub enum MessyJsonValue<'a> { Array(MessyJsonArrayValue<'a>), Bool(bool), Number(u128), Obj(MessyJsonObjectValue<'a>), String(Cow<'a, str>), #[cfg(feature = "uuid")] Uuid(Cow<'a, feat_uuid::Uuid>), Null(MessyJsonNullType, MessyJsonExpected), } impl<'a> PartialEq<Value> for MessyJsonObjectValue<'a> { fn eq(&self, other: &Value) -> bool { match other { Value::Object(v_obj) => { for (k, v) in self.iter() { if let Some(x) = v_obj.get(k.as_str()) { if v != x { return false; } continue; } return false; } true } _ => false, } } } impl<'a> PartialEq<Value> for MessyJsonArrayValue<'a> { fn eq(&self, other: &Value) -> bool { match other { Value::Array(v_arr) => self.0.eq(v_arr), _ => false, } } } #[cfg(feature = "uuid")] impl<'a> PartialEq<feat_uuid::Uuid> for MessyJsonValue<'a> { fn eq(&self, other: &feat_uuid::Uuid) -> bool { match self { MessyJsonValue::Uuid(v_uuid) => *v_uuid == Cow::Borrowed(other), _ => false, } } } impl<'a> PartialEq<Value> for MessyJsonValue<'a> { fn eq(&self, other: &Value) -> bool { match (self, other) { (MessyJsonValue::Array(mj_arr), Value::Array(_)) => mj_arr.eq(other), (MessyJsonValue::Bool(mj_bool), Value::Bool(v_bool)) => mj_bool == v_bool, (MessyJsonValue::Number(mj_number), Value::Number(v_number)) => { let num = match v_number.as_u64() { Some(x) => x, None => return false, }; mj_number == &(num as u128) } (MessyJsonValue::Obj(mj_obj), Value::Object(_)) => mj_obj.eq(other), (MessyJsonValue::String(mj_str), Value::String(v_str)) => mj_str == v_str, (MessyJsonValue::Null(_, _), Value::Null) => true, _ => false, } } } #[derive(Clone, Debug, PartialEq, Eq)] pub struct MessyJsonValueContainer<'a> { val: MessyJsonValue<'a>, } impl<'a> std::ops::Deref for MessyJsonValueContainer<'a> { type Target = MessyJsonValue<'a>; #[inline] fn deref(&self) -> &Self::Target { self.inner() } } impl<'a> MessyJsonValueContainer<'a> { #[inline] pub fn new(val: MessyJsonValue<'a>) -> Self { MessyJsonValueContainer { val } } #[inline] pub fn inner(&self) -> &MessyJsonValue<'a> { &self.val } #[inline] pub fn take(self) -> MessyJsonValue<'a> { self.val } }
use super::*; use serde_json::Value; use std::convert::From; use std::ops::Deref; #[derive(Clone, Debug, Eq, PartialEq, Default)] pub struct MessyJsonObjectValue<'a>(BTreeMap<ArcStr, MessyJsonValue<'a>>); #[derive(Clone, Debug, Eq, PartialEq)] pub enum MessyJsonNullType { Null, Absent, } impl<'a> Deref for MessyJsonObjectValue<'a> { type Target = BTreeMap<ArcStr, MessyJsonValue<'a>>; fn deref(&self) -> &Self::Target { &self.0 } } impl<'a> MessyJsonObjectValue<'a> { pub fn take(self) -> BTreeMap<ArcStr, MessyJsonValue<'a>> { self.0 } } impl<'a> From<BTreeMap<ArcStr, MessyJsonValue<'a>>> for MessyJsonObjectValue<'a> { fn from(obj: BTreeMap<ArcStr, MessyJsonValue<'a>>) -> Self { MessyJsonObjectValue(obj) } } impl<'a> From<Vec<MessyJsonValue<'a>>> for MessyJsonArrayValue<'a> { fn from(arr: Vec<MessyJsonValue<'a>>) -> Self { MessyJsonArrayValue(arr) } } impl<'a> MessyJ
), Value::Object(_)) => mj_obj.eq(other), (MessyJsonValue::String(mj_str), Value::String(v_str)) => mj_str == v_str, (MessyJsonValue::Null(_, _), Value::Null) => true, _ => false, } } } #[derive(Clone, Debug, PartialEq, Eq)] pub struct MessyJsonValueContainer<'a> { val: MessyJsonValue<'a>, } impl<'a> std::ops::Deref for MessyJsonValueContainer<'a> { type Target = MessyJsonValue<'a>; #[inline] fn deref(&self) -> &Self::Target { self.inner() } } impl<'a> MessyJsonValueContainer<'a> { #[inline] pub fn new(val: MessyJsonValue<'a>) -> Self { MessyJsonValueContainer { val } } #[inline] pub fn inner(&self) -> &MessyJsonValue<'a> { &self.val } #[inline] pub fn take(self) -> MessyJsonValue<'a> { self.val } }
sonArrayValue<'a> { pub fn take(self) -> Vec<MessyJsonValue<'a>> { self.0 } } #[derive(Clone, Debug, Eq, PartialEq)] pub struct MessyJsonArrayValue<'a>(Vec<MessyJsonValue<'a>>); impl<'a> Deref for MessyJsonArrayValue<'a> { type Target = Vec<MessyJsonValue<'a>>; fn deref(&self) -> &Self::Target { &self.0 } } #[derive(Clone, Debug, PartialEq, Eq)] pub enum MessyJsonValue<'a> { Array(MessyJsonArrayValue<'a>), Bool(bool), Number(u128), Obj(MessyJsonObjectValue<'a>), String(Cow<'a, str>), #[cfg(feature = "uuid")] Uuid(Cow<'a, feat_uuid::Uuid>), Null(MessyJsonNullType, MessyJsonExpected), } impl<'a> PartialEq<Value> for MessyJsonObjectValue<'a> { fn eq(&self, other: &Value) -> bool { match other { Value::Object(v_obj) => { for (k, v) in self.iter() { if let Some(x) = v_obj.get(k.as_str()) { if v != x { return false; } continue; } return false; } true } _ => false, } } } impl<'a> PartialEq<Value> for MessyJsonArrayValue<'a> { fn eq(&self, other: &Value) -> bool { match other { Value::Array(v_arr) => self.0.eq(v_arr), _ => false, } } } #[cfg(feature = "uuid")] impl<'a> PartialEq<feat_uuid::Uuid> for MessyJsonValue<'a> { fn eq(&self, other: &feat_uuid::Uuid) -> bool { match self { MessyJsonValue::Uuid(v_uuid) => *v_uuid == Cow::Borrowed(other), _ => false, } } } impl<'a> PartialEq<Value> for MessyJsonValue<'a> { fn eq(&self, other: &Value) -> bool { match (self, other) { (MessyJsonValue::Array(mj_arr), Value::Array(_)) => mj_arr.eq(other), (MessyJsonValue::Bool(mj_bool), Value::Bool(v_bool)) => mj_bool == v_bool, (MessyJsonValue::Number(mj_number), Value::Number(v_number)) => { let num = match v_number.as_u64() { Some(x) => x, None => return false, }; mj_number == &(num as u128) } (MessyJsonValue::Obj(mj_obj
random
[ { "content": "#[cfg(test)]\n\npub fn gen_key(k: &str) -> super::object::KeyType {\n\n ArcStr::from(k)\n\n}\n", "file_path": "src/object.rs", "rank": 0, "score": 154589.97172367276 }, { "content": "#[test]\n\nfn null() {\n\n let nested_string = MessyJson::from(MessyJsonInner::String(MessyJsonScalar::new(true)));\n\n let schema = MessyJsonObject::from(MessyJsonObjectInner::new(\n\n vec![(gen_key(\"hello\"), nested_string)]\n\n .into_iter()\n\n .collect(),\n\n false,\n\n ));\n\n let value = r#\"\n\n\t{\n\n\t\t\"hello\": null\n\n\t}\n\n\t\"#;\n\n\n\n let mut deserializer = serde_json::Deserializer::from_str(value);\n\n let parsed = schema\n\n .builder(MessyJsonSettings::default())\n\n .deserialize(&mut deserializer)\n\n .unwrap();\n\n match parsed.inner() {\n\n MessyJsonValue::Obj(x) => assert_eq!(\n\n matches!(x.get(\"hello\").unwrap(), MessyJsonValue::Null(x, _y) if matches!(x, MessyJsonNullType::Null)),\n\n true\n\n ),\n\n _ => panic!(),\n\n }\n\n}\n\n\n", "file_path": "src/tests/null_vs_absent.rs", "rank": 1, "score": 144481.85438919393 }, { "content": "#[test]\n\nfn absent() {\n\n let nested_string = MessyJson::from(MessyJsonInner::String(MessyJsonScalar::new(true)));\n\n let schema = MessyJsonObject::from(MessyJsonObjectInner::new(\n\n vec![(gen_key(\"hello\"), nested_string)]\n\n .into_iter()\n\n .collect(),\n\n false,\n\n ));\n\n let value = r#\"\n\n\t{\n\n\t}\n\n\t\"#;\n\n\n\n let mut deserializer = serde_json::Deserializer::from_str(value);\n\n let parsed = schema\n\n .builder(MessyJsonSettings::default())\n\n .deserialize(&mut deserializer)\n\n .unwrap();\n\n match parsed.inner() {\n\n MessyJsonValue::Obj(x) => assert_eq!(\n\n matches!(x.get(\"hello\").unwrap(), MessyJsonValue::Null(x, _y) if matches!(x, MessyJsonNullType::Absent)),\n\n true\n\n ),\n\n _ => panic!(),\n\n }\n\n}\n", "file_path": "src/tests/null_vs_absent.rs", "rank": 2, "score": 144461.13012876682 }, { "content": "pub fn visit_array<'de, V>(\n\n array: Vec<MessyJsonValueRaw<'de>>,\n\n visitor: V,\n\n) -> Result<V::Value, serde::de::value::Error>\n\nwhere\n\n V: Visitor<'de>,\n\n{\n\n let len = array.len();\n\n let mut deserializer = MessyJsonRawSeqDeserializer::new(array);\n\n let seq = visitor.visit_seq(&mut deserializer)?;\n\n let remaining = deserializer.iter.len();\n\n if remaining == 0 {\n\n Ok(seq)\n\n } else {\n\n Err(serde::de::Error::invalid_length(\n\n len,\n\n &\"fewer elements in array\",\n\n ))\n\n }\n\n}\n", "file_path": "src/raw_value/deserializer/seq.rs", "rank": 3, "score": 87383.63434903216 }, { "content": "pub fn visit_object<'de, V>(\n\n object: BTreeMap<Cow<'de, str>, MessyJsonValueRaw<'de>>,\n\n visitor: V,\n\n) -> Result<V::Value, serde::de::value::Error>\n\nwhere\n\n V: Visitor<'de>,\n\n{\n\n let len = object.len();\n\n let mut deserializer = MessyJsonRawMapDeserializer::new(object);\n\n let map = visitor.visit_map(&mut deserializer)?;\n\n let remaining = deserializer.iter.len();\n\n if remaining == 0 {\n\n Ok(map)\n\n } else {\n\n Err(serde::de::Error::invalid_length(\n\n len,\n\n &\"fewer elements in map\",\n\n ))\n\n }\n\n}\n", "file_path": "src/raw_value/deserializer/map.rs", "rank": 4, "score": 87383.63434903216 }, { "content": "pub fn criterion_benchmark(c: &mut Criterion) {\n\n let mut group = c.benchmark_group(\"Simple object\");\n\n\n\n super::apply_criterion_group_settings(&mut group);\n\n group.bench_with_input(\n\n criterion::BenchmarkId::new(\"deser_serde_struct\", \"simple_obj\"),\n\n &SIMPLE_OBJ,\n\n |b, i| b.iter(|| parse_serde(i)),\n\n );\n\n group.bench_with_input(\n\n criterion::BenchmarkId::new(\"deser_serde_value\", \"simple_obj\"),\n\n &SIMPLE_OBJ,\n\n |b, i| b.iter(|| parse_serde_value(i)),\n\n );\n\n group.bench_with_input(\n\n criterion::BenchmarkId::new(\"deser_messy_json\", \"simple_obj\"),\n\n &SIMPLE_OBJ,\n\n |b, i| {\n\n let prepared = gen_messy_json_schema();\n\n b.iter(|| parse_messy_json(&prepared, i))\n\n },\n\n );\n\n group.bench_with_input(\n\n criterion::BenchmarkId::new(\"deser_messy_json_raw\", \"simple_obj\"),\n\n &SIMPLE_OBJ,\n\n |b, i| b.iter(|| parse_messy_json_raw(i)),\n\n );\n\n group.finish();\n\n}\n", "file_path": "src/benches/vs_serde_str.rs", "rank": 5, "score": 85023.91542501508 }, { "content": "pub fn criterion_benchmark(c: &mut Criterion) {\n\n vs_serde_dummy_obj::criterion_benchmark(c);\n\n vs_serde_optional_obj::criterion_benchmark(c);\n\n}\n", "file_path": "src/benches/vs_serde_obj.rs", "rank": 6, "score": 85023.91542501508 }, { "content": "pub fn criterion_benchmark(c: &mut Criterion) {\n\n let prepared_optional = gen_messy_json_schema_optional_obj();\n\n\n\n let mut group = c.benchmark_group(\"Partial object\");\n\n super::apply_criterion_group_settings(&mut group);\n\n group.bench_with_input(\n\n criterion::BenchmarkId::new(\"deser_serde_struct\", \"optional_obj\"),\n\n &OPTIONAL_OBJ,\n\n |b, i| b.iter(|| parse_serde_optional_obj::<DummySerdeStruct>(i)),\n\n );\n\n group.bench_with_input(\n\n criterion::BenchmarkId::new(\"deser_serde_value\", \"optional_obj\"),\n\n &OPTIONAL_OBJ,\n\n |b, i| b.iter(|| parse_serde_value_optional_obj(i)),\n\n );\n\n group.bench_with_input(\n\n criterion::BenchmarkId::new(\"deser_messy_json\", \"optional_obj\"),\n\n &prepared_optional,\n\n |b, _i| b.iter(|| parse_messy_json_optional_obj(&prepared_optional)),\n\n );\n\n group.bench_with_input(\n\n criterion::BenchmarkId::new(\"deser_messy_json_raw\", \"optional_obj\"),\n\n &OPTIONAL_OBJ,\n\n |b, i| b.iter(|| parse_messy_json_raw_optional_obj(i)),\n\n );\n\n group.finish()\n\n}\n", "file_path": "src/benches/vs_serde_optional_obj.rs", "rank": 7, "score": 83575.45954469376 }, { "content": "pub fn criterion_benchmark(c: &mut Criterion) {\n\n let prepared_dummy = gen_messy_json_schema_dummy_obj();\n\n\n\n let mut group = c.benchmark_group(\"Dummy object\");\n\n super::apply_criterion_group_settings(&mut group);\n\n group.bench_with_input(\n\n criterion::BenchmarkId::new(\"deser_serde_struct\", \"dummy_obj\"),\n\n &DUMMY_OBJ,\n\n |b, i| b.iter(|| parse_serde_dummy_obj::<DummySerdeStruct>(i)),\n\n );\n\n group.bench_with_input(\n\n criterion::BenchmarkId::new(\"deser_serde_value\", \"dummy_obj\"),\n\n &DUMMY_OBJ,\n\n |b, i| b.iter(|| parse_serde_value_dummy_obj(i)),\n\n );\n\n group.bench_with_input(\n\n criterion::BenchmarkId::new(\"deser_messy_json\", \"dummy_obj\"),\n\n &prepared_dummy,\n\n |b, _i| b.iter(|| parse_messy_json_dummy_obj(&prepared_dummy)),\n\n );\n\n group.bench_with_input(\n\n criterion::BenchmarkId::new(\"deser_messy_json_raw\", \"dummy_obj\"),\n\n &DUMMY_OBJ,\n\n |b, i| b.iter(|| parse_serde_raw_value_dummy_obj(i)),\n\n );\n\n group.finish();\n\n}\n", "file_path": "src/benches/vs_serde_dummy_obj.rs", "rank": 8, "score": 83575.45954469376 }, { "content": "#[test]\n\nfn all_absent() {\n\n let nested_string = MessyJson::from(MessyJsonInner::String(MessyJsonScalar::new(false)));\n\n let nested_schema: MessyJson = MessyJson::from(MessyJsonInner::Obj(MessyJsonObject::from(\n\n MessyJsonObjectInner::new(\n\n vec![(gen_key(\"the\"), nested_string)].into_iter().collect(),\n\n false,\n\n ),\n\n )));\n\n let schema: MessyJson = MessyJson::from(MessyJsonInner::Obj(MessyJsonObject::from(\n\n MessyJsonObjectInner::new(\n\n vec![(gen_key(\"hello\"), nested_schema)]\n\n .into_iter()\n\n .collect(),\n\n false,\n\n ),\n\n )));\n\n let value = r#\"\n\n\t{\n\n\t}\n\n\t\"#;\n", "file_path": "src/tests/all_optional.rs", "rank": 9, "score": 81014.23364791617 }, { "content": "fn main() {\n\n let prepared = gen_messy_json_schema();\n\n\n\n println!(\"Struct : {:#?}\", parse_serde_struct());\n\n println!(\"Value : {:#?}\", parse_serde_value());\n\n println!(\"MessyJsonValue : {:#?}\", parse_messy_json(&prepared));\n\n}\n", "file_path": "examples/simple_struct.rs", "rank": 10, "score": 80706.73417123074 }, { "content": "fn parse_serde_struct() -> DummySerdeStruct<'static> {\n\n serde_json::from_str(DUMMY_OBJ).unwrap()\n\n}\n\n\n", "file_path": "examples/simple_struct.rs", "rank": 11, "score": 80599.09270955625 }, { "content": "pub fn apply_criterion_group_settings<T: criterion::measurement::Measurement>(\n\n group: &mut criterion::BenchmarkGroup<T>,\n\n) {\n\n group.sample_size(1000);\n\n group.warm_up_time(Duration::from_secs(5));\n\n group.measurement_time(Duration::from_secs(20));\n\n}\n\n\n\ncriterion_group!(\n\n benches,\n\n vs_serde_obj::criterion_benchmark,\n\n vs_serde_str::criterion_benchmark\n\n);\n\ncriterion_main!(benches);\n", "file_path": "src/benches/mod.rs", "rank": 12, "score": 80153.87398339859 }, { "content": "#[test]\n\nfn mix_absent() {\n\n let nested_string = MessyJson::from(MessyJsonInner::String(MessyJsonScalar::new(false)));\n\n let nested_schema = MessyJson::from(MessyJsonInner::Obj(MessyJsonObject::from(\n\n MessyJsonObjectInner::new(\n\n vec![(gen_key(\"the\"), nested_string)].into_iter().collect(),\n\n false,\n\n ),\n\n )));\n\n let schema = MessyJson::from(MessyJsonInner::Obj(MessyJsonObject::from(\n\n MessyJsonObjectInner::new(\n\n vec![(gen_key(\"hello\"), nested_schema)]\n\n .into_iter()\n\n .collect(),\n\n false,\n\n ),\n\n )));\n\n let value = r#\"\n\n\t{\n\n\t\t\"hello\":\n\n\t\t{\n", "file_path": "src/tests/all_optional.rs", "rank": 13, "score": 78941.89386267193 }, { "content": "#[test]\n\nfn optional_uuid_absent() {\n\n let nested_string = MessyJson::from(MessyJsonInner::Uuid(MessyJsonScalar::new(true)));\n\n let schema = MessyJson::from(MessyJsonInner::Obj(MessyJsonObject::from(\n\n MessyJsonObjectInner::new(\n\n vec![(gen_key(\"hello\"), nested_string)]\n\n .into_iter()\n\n .collect(),\n\n false,\n\n ),\n\n )));\n\n let value = r#\"\n\n\t{\n\n\t\t\"hello\": null\n\n\t}\n\n\t\"#;\n\n let mut deserializer = serde_json::Deserializer::from_str(value);\n\n let parsed: MessyJsonValueContainer = schema\n\n .builder(MessyJsonSettings::default())\n\n .deserialize(&mut deserializer)\n\n .unwrap();\n", "file_path": "src/tests/uuid.rs", "rank": 14, "score": 76998.19353610682 }, { "content": "#[test]\n\nfn wrong_value_type() {\n\n let nested_string = MessyJson::from(MessyJsonInner::String(MessyJsonScalar::new(false)));\n\n let nested_schema = MessyJson::from(MessyJsonInner::Obj(MessyJsonObject::from(\n\n MessyJsonObjectInner::new(\n\n vec![(gen_key(\"the\"), nested_string)].into_iter().collect(),\n\n false,\n\n ),\n\n )));\n\n let schema = MessyJson::from(MessyJsonInner::Obj(MessyJsonObject::from(\n\n MessyJsonObjectInner::new(\n\n vec![(gen_key(\"hello\"), nested_schema)]\n\n .into_iter()\n\n .collect(),\n\n false,\n\n ),\n\n )));\n\n let value = r#\"\n\n\t{\n\n\t\t\"hello\": {\n\n\t\t\t\"the\": 61\n", "file_path": "src/tests/parse_nested_object.rs", "rank": 15, "score": 73549.56774250118 }, { "content": "fn parse_serde_value() -> Value {\n\n serde_json::from_str(DUMMY_OBJ).unwrap()\n\n}\n\n\n", "file_path": "examples/simple_struct.rs", "rank": 16, "score": 73432.96909093678 }, { "content": "fn gen_messy_json_schema() -> MessyJson {\n\n MessyJson::from(MessyJsonInner::Obj(MessyJsonObject::from(\n\n MessyJsonObjectInner::new(\n\n vec![(\n\n arcstr::literal!(\"hello\"),\n\n MessyJson::from(MessyJsonInner::Obj(MessyJsonObject::from(\n\n MessyJsonObjectInner::new(\n\n vec![(\n\n arcstr::literal!(\"hola\"),\n\n MessyJson::from(MessyJsonInner::String(MessyJsonScalar::new(false))),\n\n )]\n\n .into_iter()\n\n .collect(),\n\n false,\n\n ),\n\n ))),\n\n )]\n\n .into_iter()\n\n .collect(),\n\n false,\n\n ),\n\n )))\n\n}\n\n\n", "file_path": "examples/simple_struct.rs", "rank": 17, "score": 70106.69233082868 }, { "content": "#[derive(Debug, Serialize, Deserialize)]\n\nstruct DummySerdeStruct<'a> {\n\n hello: DummySerdeStructNested<'a>,\n\n}\n\n\n", "file_path": "examples/simple_struct.rs", "rank": 18, "score": 67772.36089762939 }, { "content": "#[derive(Debug, Serialize, Deserialize)]\n\nstruct DummySerdeStructNested<'a> {\n\n hola: Cow<'a, str>,\n\n}\n\n\n", "file_path": "examples/simple_struct.rs", "rank": 19, "score": 67158.84229918657 }, { "content": "#[derive(Clone, Debug, Deserialize)]\n\nstruct DummyStruct {\n\n person: DummyPerson,\n\n employment: DummyJob,\n\n friends: Vec<String>,\n\n}\n\n\n", "file_path": "src/raw_value/tests/deserializer.rs", "rank": 20, "score": 65568.99417388748 }, { "content": "fn parse_serde(input: &str) -> SimpleStruct {\n\n serde_json::from_str(input).unwrap()\n\n}\n\n\n", "file_path": "src/benches/vs_serde_str.rs", "rank": 21, "score": 64884.10390264829 }, { "content": "use super::*;\n\n\n\n#[test]\n", "file_path": "src/tests/null_vs_absent.rs", "rank": 22, "score": 64838.68620088232 }, { "content": "#[derive(Serialize, Deserialize)]\n\nstruct SimpleStruct<'a> {\n\n hello: Cow<'a, str>,\n\n}\n\n\n", "file_path": "src/benches/vs_serde_str.rs", "rank": 23, "score": 63157.109744354515 }, { "content": "#[derive(Serialize, Deserialize)]\n\nstruct DummySerdeStruct<'a> {\n\n hello: DummySerdeStructNested<'a>,\n\n}\n\n\n", "file_path": "src/benches/vs_serde_dummy_obj.rs", "rank": 24, "score": 61722.40485438425 }, { "content": "#[derive(Serialize, Deserialize)]\n\nstruct DummySerdeStruct<'a> {\n\n hello: DummySerdeStructNested<'a>,\n\n coucou: Option<Cow<'a, str>>,\n\n coucou1: Option<Cow<'a, str>>,\n\n coucou2: Option<Cow<'a, str>>,\n\n}\n\n\n", "file_path": "src/benches/vs_serde_optional_obj.rs", "rank": 25, "score": 61722.40485438425 }, { "content": "#[derive(Serialize, Deserialize)]\n\nstruct DummySerdeStructNested<'a> {\n\n hola: Cow<'a, str>,\n\n}\n\n\n", "file_path": "src/benches/vs_serde_optional_obj.rs", "rank": 26, "score": 61044.28800407096 }, { "content": "#[derive(Serialize, Deserialize)]\n\nstruct DummySerdeStructNested<'a> {\n\n hola: Cow<'a, str>,\n\n}\n\n\n", "file_path": "src/benches/vs_serde_dummy_obj.rs", "rank": 27, "score": 61044.28800407096 }, { "content": "fn parse_messy_json<'a>(schema: &MessyJson) -> MessyJsonValueContainer<'a> {\n\n let mut deserializer = serde_json::Deserializer::from_str(DUMMY_OBJ);\n\n schema\n\n .builder(MessyJsonSettings::default())\n\n .deserialize(&mut deserializer)\n\n .unwrap()\n\n}\n\n\n", "file_path": "examples/simple_struct.rs", "rank": 28, "score": 60557.98588895212 }, { "content": "#[derive(Clone, Debug, Deserialize)]\n\n#[serde(rename_all = \"snake_case\")]\n\nenum DummyJob {\n\n Unemployed,\n\n NotWorking,\n\n}\n\n\n", "file_path": "src/raw_value/tests/deserializer.rs", "rank": 29, "score": 58060.921728610774 }, { "content": "#[derive(Clone, Debug, Deserialize)]\n\nstruct DummyPerson {\n\n age: u16,\n\n isachild: bool,\n\n gender: char,\n\n name: Option<String>,\n\n surname: Option<String>,\n\n}\n\n\n", "file_path": "src/raw_value/tests/deserializer.rs", "rank": 30, "score": 57086.53044204219 }, { "content": "pub trait MessyJsonObjectTrait {\n\n type Input;\n\n\n\n /// Create a new builder from a [MessyJson](MessyJson)\n\n fn new(schema: &Self::Input, settings: MessyJsonSettings) -> Self;\n\n\n\n /// Get the inner [MessyJson](MessyJson)\n\n fn inner(&self) -> &Self::Input;\n\n\n\n /// Return the settings\n\n fn settings(&self) -> &MessyJsonSettings;\n\n\n\n /// Create a new nested schema providing the nested schema and self\n\n fn new_nested(&self, schema: &MessyJson, settings: MessyJsonSettings) -> MessyJsonBuilder;\n\n\n\n /// Compare that a deserialized object have all the required fields are available.\n\n ///\n\n /// Return a missing key if any, None otherwise\n\n fn compare_obj(\n\n schema: &MessyJsonObject,\n", "file_path": "src/schema.rs", "rank": 31, "score": 54951.204153412094 }, { "content": "struct MessyJsonRawMapKeyDeserializer<'de> {\n\n key: Cow<'de, str>,\n\n}\n\n\n\nimpl<'de> Deserializer<'de> for MessyJsonRawMapKeyDeserializer<'de> {\n\n type Error = serde::de::value::Error;\n\n\n\n fn deserialize_any<V>(self, visitor: V) -> Result<V::Value, Self::Error>\n\n where\n\n V: Visitor<'de>,\n\n {\n\n match self.key {\n\n Cow::Owned(x) => visitor.visit_string(x),\n\n Cow::Borrowed(x) => visitor.visit_borrowed_str(x),\n\n }\n\n }\n\n\n\n serde::forward_to_deserialize_any! {\n\n bool i8 i16 i32 i64 i128 u8 u16 u32 u64 u128 f32 f64 char str string\n\n bytes byte_buf option unit unit_struct newtype_struct seq tuple\n\n tuple_struct map struct enum identifier ignored_any\n\n }\n\n}\n\n\n", "file_path": "src/raw_value/deserializer/map.rs", "rank": 32, "score": 50730.74172833429 }, { "content": "#[test]\n\nfn all_present() {\n\n let nested_string = MessyJson::from(MessyJsonInner::String(MessyJsonScalar::new(false)));\n\n let nested_schema = MessyJson::from(MessyJsonInner::Obj(MessyJsonObject::from(\n\n MessyJsonObjectInner::new(\n\n vec![(gen_key(\"the\"), nested_string)].into_iter().collect(),\n\n false,\n\n ),\n\n )));\n\n let schema = MessyJson::from(MessyJsonInner::Obj(MessyJsonObject::from(\n\n MessyJsonObjectInner::new(\n\n vec![(gen_key(\"hello\"), nested_schema)]\n\n .into_iter()\n\n .collect(),\n\n false,\n\n ),\n\n )));\n\n let value = r#\"\n\n\t{\n\n\t\t\"hello\":\n\n\t\t{\n", "file_path": "src/tests/all_optional.rs", "rank": 33, "score": 47567.25665668535 }, { "content": "#[test]\n\nfn missing() {\n\n let nested_string = MessyJson::from(MessyJsonInner::String(MessyJsonScalar::new(false)));\n\n let schema = MessyJson::from(MessyJsonInner::Obj(MessyJsonObject::from(\n\n MessyJsonObjectInner::new(\n\n vec![(gen_key(\"hello\"), nested_string)]\n\n .into_iter()\n\n .collect(),\n\n false,\n\n ),\n\n )));\n\n let value = r#\"\n\n\t{\n\n\t}\n\n\t\"#;\n\n\n\n let mut deserializer = serde_json::Deserializer::from_str(value);\n\n let parsed = schema\n\n .builder(MessyJsonSettings::default())\n\n .deserialize(&mut deserializer)\n\n .unwrap_err();\n\n println!(\"{:#?}\", parsed);\n\n}\n\n\n", "file_path": "src/tests/unexact_obj.rs", "rank": 34, "score": 46566.27096522949 }, { "content": "#[test]\n\nfn uuid_simple() {\n\n let nested_string = MessyJson::from(MessyJsonInner::Uuid(MessyJsonScalar::new(false)));\n\n let test_uuid = feat_uuid::Uuid::parse_str(\"31ee8240-630b-416a-8c54-0e2a0d070488\").unwrap();\n\n let schema = MessyJson::from(MessyJsonInner::Obj(MessyJsonObject::from(\n\n MessyJsonObjectInner::new(\n\n vec![(gen_key(\"hello\"), nested_string)]\n\n .into_iter()\n\n .collect(),\n\n false,\n\n ),\n\n )));\n\n let value = r#\"\n\n\t{\n\n\t\t\"hello\": \"31ee8240-630b-416a-8c54-0e2a0d070488\"\n\n\t}\n\n\t\"#;\n\n let mut deserializer = serde_json::Deserializer::from_str(value);\n\n let parsed: MessyJsonValueContainer = schema\n\n .builder(MessyJsonSettings::default())\n\n .deserialize(&mut deserializer)\n", "file_path": "src/tests/uuid.rs", "rank": 35, "score": 46566.27096522949 }, { "content": "#[test]\n\nfn all_optional() {\n\n let nested_string_opt = MessyJson::from(MessyJsonInner::String(MessyJsonScalar::new(true)));\n\n let schema = MessyJson::from(MessyJsonInner::Obj(MessyJsonObject::from(\n\n MessyJsonObjectInner::new(\n\n vec![\n\n (gen_key(\"hello\"), nested_string_opt.clone()),\n\n (gen_key(\"whoami\"), nested_string_opt.clone()),\n\n (gen_key(\"hehe\"), nested_string_opt),\n\n ]\n\n .into_iter()\n\n .collect(),\n\n false,\n\n ),\n\n )));\n\n let value = r#\"\n\n\t{\n\n\t}\n\n\t\"#;\n\n\n\n let mut deserializer = serde_json::Deserializer::from_str(value);\n\n schema\n\n .builder(MessyJsonSettings::default())\n\n .deserialize(&mut deserializer)\n\n .unwrap();\n\n}\n\n\n", "file_path": "src/tests/unexact_obj.rs", "rank": 36, "score": 46566.27096522949 }, { "content": "#[test]\n\nfn bool() {\n\n let nested_string = MessyJson::from(MessyJsonInner::Bool(MessyJsonScalar::new(false)));\n\n let schema = MessyJson::from(MessyJsonInner::Obj(MessyJsonObject::from(\n\n MessyJsonObjectInner::new(\n\n vec![(gen_key(\"hello\"), nested_string)]\n\n .into_iter()\n\n .collect(),\n\n false,\n\n ),\n\n )));\n\n let value = r#\"\n\n\t{\n\n\t\t\"hello\": true\n\n\t}\n\n\t\"#;\n\n run_flat_test(&schema, value, MessyJsonValue::Bool(true));\n\n}\n\n\n", "file_path": "src/tests/parse_simple.rs", "rank": 37, "score": 46566.27096522949 }, { "content": "#[test]\n\nfn ok() {\n\n let parser = gen_parser();\n\n let mut deserializer = serde_json::Deserializer::from_str(VAL);\n\n let parsed_value: serde_json::Value = serde_json::from_str(VAL).unwrap();\n\n let parsed: MessyJsonValueContainer = parser\n\n .builder(MessyJsonSettings::default())\n\n .deserialize(&mut deserializer)\n\n .unwrap();\n\n\n\n assert_eq!(\n\n parsed.inner().eq(&parsed_value),\n\n true,\n\n \"obj comparaison problem\"\n\n );\n\n}\n\n\n", "file_path": "src/tests/cmp_value.rs", "rank": 38, "score": 46566.27096522949 }, { "content": "#[test]\n\nfn unkown_keys() {\n\n let nested_string = MessyJson::from(MessyJsonInner::String(MessyJsonScalar::new(false)));\n\n let nested_schema = MessyJson::from(MessyJsonInner::Obj(MessyJsonObject::from(\n\n MessyJsonObjectInner::new(\n\n vec![(gen_key(\"the\"), nested_string)].into_iter().collect(),\n\n false,\n\n ),\n\n )));\n\n let schema = MessyJson::from(MessyJsonInner::Obj(MessyJsonObject::from(\n\n MessyJsonObjectInner::new(\n\n vec![(gen_key(\"hello\"), nested_schema)]\n\n .into_iter()\n\n .collect(),\n\n false,\n\n ),\n\n )));\n\n let value = r#\"\n\n\t{\n\n\t\t\"coucou\": \"wassup\"\n\n\t}\n", "file_path": "src/tests/all_optional.rs", "rank": 39, "score": 46566.27096522949 }, { "content": "#[test]\n\nfn unknown() {\n\n let nested_string = MessyJson::from(MessyJsonInner::String(MessyJsonScalar::new(false)));\n\n let schema = MessyJson::from(MessyJsonInner::Obj(MessyJsonObject::from(\n\n MessyJsonObjectInner::new(\n\n vec![(gen_key(\"hello\"), nested_string)]\n\n .into_iter()\n\n .collect(),\n\n false,\n\n ),\n\n )));\n\n let value = r#\"\n\n\t{\n\n\t\t\"hello\": \"world\",\n\n\t\t\"whoami\": \"wellidk\"\n\n\t}\n\n\t\"#;\n\n\n\n let mut deserializer = serde_json::Deserializer::from_str(value);\n\n let parsed = schema\n\n .builder(MessyJsonSettings::default())\n\n .deserialize(&mut deserializer)\n\n .unwrap_err();\n\n println!(\"{:#?}\", parsed);\n\n}\n\n\n", "file_path": "src/tests/unexact_obj.rs", "rank": 40, "score": 46566.27096522949 }, { "content": "#[test]\n\nfn simple() {\n\n let nested_string = MessyJson::from(MessyJsonInner::String(MessyJsonScalar::new(false)));\n\n let schema = MessyJson::from(MessyJsonInner::Array(MessyJsonArray::new(\n\n nested_string,\n\n false,\n\n )));\n\n let value = r#\"\n\n\t[\n\n\t\t\"hello\",\n\n\t\t\"world\"\n\n\t]\n\n\t\"#;\n\n\n\n let mut deserializer = serde_json::Deserializer::from_str(value);\n\n let parsed: MessyJsonValueContainer = schema\n\n .builder(MessyJsonSettings::default())\n\n .deserialize(&mut deserializer)\n\n .unwrap();\n\n assert_eq!(\n\n matches!(parsed.inner(), MessyJsonValue::Array(_)),\n", "file_path": "src/tests/root_array.rs", "rank": 41, "score": 46566.27096522949 }, { "content": "#[test]\n\nfn string() {\n\n let nested_string = MessyJson::from(MessyJsonInner::String(MessyJsonScalar::new(false)));\n\n let schema = MessyJson::from(MessyJsonInner::Obj(MessyJsonObject::from(\n\n MessyJsonObjectInner::new(\n\n vec![(gen_key(\"hello\"), nested_string)]\n\n .into_iter()\n\n .collect(),\n\n false,\n\n ),\n\n )));\n\n let value = r#\"\n\n\t{\n\n\t\t\"hello\": \"world\"\n\n\t}\n\n\t\"#;\n\n\n\n run_flat_test(\n\n &schema,\n\n value,\n\n MessyJsonValue::String(Cow::Borrowed(\"world\")),\n\n );\n\n}\n\n\n", "file_path": "src/tests/parse_simple.rs", "rank": 42, "score": 46566.27096522949 }, { "content": "#[test]\n\nfn bad_uuid() {\n\n let nested_string = MessyJson::from(MessyJsonInner::Uuid(MessyJsonScalar::new(false)));\n\n let schema = MessyJson::from(MessyJsonInner::Obj(MessyJsonObject::from(\n\n MessyJsonObjectInner::new(\n\n vec![(gen_key(\"hello\"), nested_string)]\n\n .into_iter()\n\n .collect(),\n\n false,\n\n ),\n\n )));\n\n let value = r#\"\n\n\t{\n\n\t\t\"hello\": \"azaaaaaaaaaaaaaaaaa\"\n\n\t}\n\n\t\"#;\n\n let mut deserializer = serde_json::Deserializer::from_str(value);\n\n schema\n\n .builder(MessyJsonSettings::default())\n\n .deserialize(&mut deserializer)\n\n .unwrap_err();\n\n}\n\n\n", "file_path": "src/tests/uuid.rs", "rank": 43, "score": 46566.27096522949 }, { "content": "#[test]\n\nfn optional_uuid_present() {\n\n let nested_string = MessyJson::from(MessyJsonInner::Uuid(MessyJsonScalar::new(true)));\n\n let test_uuid = feat_uuid::Uuid::parse_str(\"31ee8240-630b-416a-8c54-0e2a0d070488\").unwrap();\n\n let schema = MessyJson::from(MessyJsonInner::Obj(MessyJsonObject::from(\n\n MessyJsonObjectInner::new(\n\n vec![(gen_key(\"hello\"), nested_string)]\n\n .into_iter()\n\n .collect(),\n\n false,\n\n ),\n\n )));\n\n let value = r#\"\n\n\t{\n\n\t\t\"hello\": \"31ee8240-630b-416a-8c54-0e2a0d070488\"\n\n\t}\n\n\t\"#;\n\n let mut deserializer = serde_json::Deserializer::from_str(value);\n\n let parsed: MessyJsonValueContainer = schema\n\n .builder(MessyJsonSettings::default())\n\n .deserialize(&mut deserializer)\n", "file_path": "src/tests/uuid.rs", "rank": 44, "score": 45627.420961372394 }, { "content": "#[test]\n\nfn complete_with_optional() {\n\n let nested_string = MessyJson::from(MessyJsonInner::String(MessyJsonScalar::new(false)));\n\n let nested_string_opt = MessyJson::from(MessyJsonInner::String(MessyJsonScalar::new(true)));\n\n let schema = MessyJson::from(MessyJsonInner::Obj(MessyJsonObject::from(\n\n MessyJsonObjectInner::new(\n\n vec![\n\n (gen_key(\"hello\"), nested_string.clone()),\n\n (gen_key(\"whoami\"), nested_string_opt),\n\n (gen_key(\"hehe\"), nested_string),\n\n ]\n\n .into_iter()\n\n .collect(),\n\n false,\n\n ),\n\n )));\n\n let value = r#\"\n\n\t{\n\n\t\t\"hello\": \"world\",\n\n\t\t\"whoami\": \"wellidk\",\n\n\t\t\"hehe\": \"hoho\"\n\n\t}\n\n\t\"#;\n\n\n\n let mut deserializer = serde_json::Deserializer::from_str(value);\n\n schema\n\n .builder(MessyJsonSettings::default())\n\n .deserialize(&mut deserializer)\n\n .unwrap();\n\n}\n\n\n", "file_path": "src/tests/unexact_obj.rs", "rank": 45, "score": 45627.420961372394 }, { "content": "#[test]\n\nfn mismatch_bool() {\n\n let parser = gen_parser();\n\n let mut deserializer = serde_json::Deserializer::from_str(VAL);\n\n let bogus_value = r#\"\n\n\t{\n\n\t\t\"hello\": \"world\",\n\n\t\t\"number\": 126354,\n\n\t\t\"bool\": false,\n\n\t\t\"array\": [\n\n\t\t\t\"hello\",\n\n\t\t\t\"hello\",\n\n\t\t\t\"world\",\n\n\t\t\t\"world\"\n\n\t\t],\n\n\t\t\"null\": null,\n\n\t\t\"obj\": {\n\n\t\t\t\"hello\": \"world\",\n\n\t\t\t\"number\": 128181684654,\n\n\t\t\t\"bool\": true,\n\n\t\t\t\"array\": [\n", "file_path": "src/tests/cmp_value.rs", "rank": 46, "score": 45627.420961372394 }, { "content": "#[test]\n\nfn simple() {\n\n let nested_string = MessyJson::from(MessyJsonInner::String(MessyJsonScalar::new(false)));\n\n let nested_schema: MessyJsonInner =\n\n MessyJsonInner::Array(MessyJsonArray::new(nested_string, false));\n\n let schema = MessyJson::from(MessyJsonInner::Obj(MessyJsonObject::from(\n\n MessyJsonObjectInner::new(\n\n vec![(gen_key(\"hello\"), MessyJson::from(nested_schema))]\n\n .into_iter()\n\n .collect(),\n\n false,\n\n ),\n\n )));\n\n let value = r#\"\n\n\t{\n\n\t\t\"hello\": [\n\n\t\t\t\"the\",\n\n\t\t\t\"world\"\n\n\t\t]\n\n\t}\n\n\t\"#;\n\n\n\n run_test(&schema, value);\n\n}\n\n\n", "file_path": "src/tests/parse_array_object.rs", "rank": 47, "score": 45627.420961372394 }, { "content": "#[test]\n\nfn number_huge() {\n\n let nested_string = MessyJson::from(MessyJsonInner::Number(MessyJsonNumeric::new(\n\n MessyJsonNumberType::U128,\n\n false,\n\n )));\n\n let schema = MessyJson::from(MessyJsonInner::Obj(MessyJsonObject::from(\n\n MessyJsonObjectInner::new(\n\n vec![(gen_key(\"hello\"), nested_string)]\n\n .into_iter()\n\n .collect(),\n\n false,\n\n ),\n\n )));\n\n let value = r#\"\n\n\t{\n\n\t\t\"hello\": 340282366920938463463374607431768211454\n\n\t}\n\n\t\"#;\n\n run_flat_test(\n\n &schema,\n\n value,\n\n MessyJsonValue::Number(340282366920938463463374607431768211454),\n\n );\n\n}\n", "file_path": "src/tests/parse_simple.rs", "rank": 48, "score": 45627.420961372394 }, { "content": "#[test]\n\nfn mismatch_obj() {\n\n let parser = gen_parser();\n\n let mut deserializer = serde_json::Deserializer::from_str(VAL);\n\n let bogus_value = r#\"\n\n\t{\n\n\t\t\"hello\": \"world\",\n\n\t\t\"number\": 126354,\n\n\t\t\"bool\": true,\n\n\t\t\"array\": [\n\n\t\t\t\"hello\",\n\n\t\t\t\"hello\",\n\n\t\t\t\"world\",\n\n\t\t\t\"world\"\n\n\t\t],\n\n\t\t\"null\": null,\n\n\t\t\"obj\": {\n\n\t\t\t\"hello\": \"worlde\",\n\n\t\t\t\"number\": 128181684654,\n\n\t\t\t\"bool\": true,\n\n\t\t\t\"array\": [\n", "file_path": "src/tests/cmp_value.rs", "rank": 49, "score": 45627.420961372394 }, { "content": "#[test]\n\nfn simple() {\n\n let nested_string = MessyJson::from(MessyJsonInner::String(MessyJsonScalar::new(false)));\n\n let nested_schema = MessyJson::from(MessyJsonInner::Obj(MessyJsonObject::from(\n\n MessyJsonObjectInner::new(\n\n vec![(gen_key(\"the\"), nested_string)].into_iter().collect(),\n\n false,\n\n ),\n\n )));\n\n let schema = MessyJson::from(MessyJsonInner::Obj(MessyJsonObject::from(\n\n MessyJsonObjectInner::new(\n\n vec![(gen_key(\"hello\"), nested_schema)]\n\n .into_iter()\n\n .collect(),\n\n false,\n\n ),\n\n )));\n\n let value = r#\"\n\n\t{\n\n\t\t\"hello\": {\n\n\t\t\t\"the\": \"world\"\n", "file_path": "src/tests/parse_nested_object.rs", "rank": 50, "score": 45627.420961372394 }, { "content": "#[test]\n\nfn mismatch_number() {\n\n let parser = gen_parser();\n\n let mut deserializer = serde_json::Deserializer::from_str(VAL);\n\n let bogus_value = r#\"\n\n\t{\n\n\t\t\"hello\": \"world\",\n\n\t\t\"number\": 1,\n\n\t\t\"bool\": true,\n\n\t\t\"array\": [\n\n\t\t\t\"hello\",\n\n\t\t\t\"hello\",\n\n\t\t\t\"world\",\n\n\t\t\t\"world\"\n\n\t\t],\n\n\t\t\"null\": null,\n\n\t\t\"obj\": {\n\n\t\t\t\"hello\": \"world\",\n\n\t\t\t\"number\": 128181684654,\n\n\t\t\t\"bool\": true,\n\n\t\t\t\"array\": [\n", "file_path": "src/tests/cmp_value.rs", "rank": 51, "score": 45627.420961372394 }, { "content": "#[test]\n\nfn incomplete_with_optional2() {\n\n let nested_string = MessyJson::from(MessyJsonInner::String(MessyJsonScalar::new(false)));\n\n let nested_string_opt = MessyJson::from(MessyJsonInner::String(MessyJsonScalar::new(true)));\n\n let schema = MessyJson::from(MessyJsonInner::Obj(MessyJsonObject::from(\n\n MessyJsonObjectInner::new(\n\n vec![\n\n (gen_key(\"hello\"), nested_string.clone()),\n\n (gen_key(\"whoami\"), nested_string),\n\n (gen_key(\"hehe\"), nested_string_opt),\n\n ]\n\n .into_iter()\n\n .collect(),\n\n false,\n\n ),\n\n )));\n\n let value = r#\"\n\n\t{\n\n\t\t\"hello\": \"world\",\n\n\t\t\"whoami\": \"hoho\"\n\n\t}\n\n\t\"#;\n\n\n\n let mut deserializer = serde_json::Deserializer::from_str(value);\n\n schema\n\n .builder(MessyJsonSettings::default())\n\n .deserialize(&mut deserializer)\n\n .unwrap();\n\n}\n\n\n", "file_path": "src/tests/unexact_obj.rs", "rank": 52, "score": 45627.420961372394 }, { "content": "#[test]\n\nfn nested_missing() {\n\n let nested_string = MessyJson::from(MessyJsonInner::String(MessyJsonScalar::new(false)));\n\n let schema = MessyJson::from(MessyJsonInner::Obj(MessyJsonObject::from(\n\n MessyJsonObjectInner::new(\n\n vec![\n\n (\n\n gen_key(\"hello\"),\n\n MessyJson::from(MessyJsonInner::Obj(MessyJsonObject::from(\n\n MessyJsonObjectInner::new(\n\n vec![(gen_key(\"world\"), nested_string.clone())]\n\n .into_iter()\n\n .collect(),\n\n false,\n\n ),\n\n ))),\n\n ),\n\n (gen_key(\"whoami\"), nested_string.clone()),\n\n (gen_key(\"hehe\"), nested_string),\n\n ]\n\n .into_iter()\n", "file_path": "src/tests/unexact_obj.rs", "rank": 53, "score": 45627.420961372394 }, { "content": "#[test]\n\nfn nested_optional() {\n\n let nested_string_opt = MessyJson::from(MessyJsonInner::String(MessyJsonScalar::new(true)));\n\n let nested_string = MessyJson::from(MessyJsonInner::String(MessyJsonScalar::new(false)));\n\n let schema = MessyJson::from(MessyJsonInner::Obj(MessyJsonObject::from(\n\n MessyJsonObjectInner::new(\n\n vec![\n\n (\n\n gen_key(\"hello\"),\n\n MessyJson::from(MessyJsonInner::Obj(MessyJsonObject::from(\n\n MessyJsonObjectInner::new(\n\n vec![(gen_key(\"world\"), nested_string_opt)]\n\n .into_iter()\n\n .collect(),\n\n false,\n\n ),\n\n ))),\n\n ),\n\n (gen_key(\"whoami\"), nested_string.clone()),\n\n (gen_key(\"hehe\"), nested_string),\n\n ]\n", "file_path": "src/tests/unexact_obj.rs", "rank": 54, "score": 45627.420961372394 }, { "content": "#[test]\n\nfn number_tiny() {\n\n let nested_string = MessyJson::from(MessyJsonInner::Number(MessyJsonNumeric::new(\n\n MessyJsonNumberType::U64,\n\n false,\n\n )));\n\n let schema = MessyJson::from(MessyJsonInner::Obj(MessyJsonObject::from(\n\n MessyJsonObjectInner::new(\n\n vec![(gen_key(\"hello\"), nested_string)]\n\n .into_iter()\n\n .collect(),\n\n false,\n\n ),\n\n )));\n\n let value = r#\"\n\n\t{\n\n\t\t\"hello\": 15\n\n\t}\n\n\t\"#;\n\n run_flat_test(&schema, value, MessyJsonValue::Number(15));\n\n}\n\n\n", "file_path": "src/tests/parse_simple.rs", "rank": 55, "score": 45627.420961372394 }, { "content": "#[test]\n\nfn mismatch_array() {\n\n let parser = gen_parser();\n\n let mut deserializer = serde_json::Deserializer::from_str(VAL);\n\n let bogus_value = r#\"\n\n\t{\n\n\t\t\"hello\": \"world\",\n\n\t\t\"number\": 126354,\n\n\t\t\"bool\": true,\n\n\t\t\"array\": [\n\n\t\t\t\"hello\",\n\n\t\t\t\"helloe\",\n\n\t\t\t\"world\",\n\n\t\t\t\"world\"\n\n\t\t],\n\n\t\t\"null\": null,\n\n\t\t\"obj\": {\n\n\t\t\t\"hello\": \"world\",\n\n\t\t\t\"number\": 128181684654,\n\n\t\t\t\"bool\": true,\n\n\t\t\t\"array\": [\n", "file_path": "src/tests/cmp_value.rs", "rank": 56, "score": 45627.420961372394 }, { "content": "#[test]\n\nfn nested_unknown() {\n\n let nested_string = MessyJson::from(MessyJsonInner::String(MessyJsonScalar::new(false)));\n\n let schema = MessyJson::from(MessyJsonInner::Obj(MessyJsonObject::from(\n\n MessyJsonObjectInner::new(\n\n vec![\n\n (\n\n gen_key(\"hello\"),\n\n MessyJson::from(MessyJsonInner::Obj(MessyJsonObject::from(\n\n MessyJsonObjectInner::new(\n\n vec![(gen_key(\"world\"), nested_string.clone())]\n\n .into_iter()\n\n .collect(),\n\n false,\n\n ),\n\n ))),\n\n ),\n\n (gen_key(\"whoami\"), nested_string.clone()),\n\n (gen_key(\"hehe\"), nested_string),\n\n ]\n\n .into_iter()\n", "file_path": "src/tests/unexact_obj.rs", "rank": 57, "score": 45627.420961372394 }, { "content": "#[test]\n\nfn mismatch_string() {\n\n let parser = gen_parser();\n\n let mut deserializer = serde_json::Deserializer::from_str(VAL);\n\n let bogus_value = r#\"\n\n\t{\n\n\t\t\"hello\": \"worlde\",\n\n\t\t\"number\": 126354,\n\n\t\t\"bool\": true,\n\n\t\t\"array\": [\n\n\t\t\t\"hello\",\n\n\t\t\t\"hello\",\n\n\t\t\t\"world\",\n\n\t\t\t\"world\"\n\n\t\t],\n\n\t\t\"null\": null,\n\n\t\t\"obj\": {\n\n\t\t\t\"hello\": \"world\",\n\n\t\t\t\"number\": 128181684654,\n\n\t\t\t\"bool\": true,\n\n\t\t\t\"array\": [\n", "file_path": "src/tests/cmp_value.rs", "rank": 58, "score": 45627.420961372394 }, { "content": "#[test]\n\nfn incomplete_with_optional() {\n\n let nested_string = MessyJson::from(MessyJsonInner::String(MessyJsonScalar::new(false)));\n\n let nested_string_opt = MessyJson::from(MessyJsonInner::String(MessyJsonScalar::new(true)));\n\n let schema = MessyJson::from(MessyJsonInner::Obj(MessyJsonObject::from(\n\n MessyJsonObjectInner::new(\n\n vec![\n\n (gen_key(\"hello\"), nested_string.clone()),\n\n (gen_key(\"whoami\"), nested_string_opt),\n\n (gen_key(\"hehe\"), nested_string),\n\n ]\n\n .into_iter()\n\n .collect(),\n\n false,\n\n ),\n\n )));\n\n let value = r#\"\n\n\t{\n\n\t\t\"hello\": \"world\",\n\n\t\t\"hehe\": \"hoho\"\n\n\t}\n\n\t\"#;\n\n\n\n let mut deserializer = serde_json::Deserializer::from_str(value);\n\n schema\n\n .builder(MessyJsonSettings::default())\n\n .deserialize(&mut deserializer)\n\n .unwrap();\n\n}\n\n\n", "file_path": "src/tests/unexact_obj.rs", "rank": 59, "score": 45627.420961372394 }, { "content": "#[test]\n\nfn complexe() {\n\n let val: MessyJsonValueRaw<'_> = serde_json::from_str(VAL).unwrap();\n\n let res: DummyStruct = DummyStruct::deserialize(val).unwrap();\n\n\n\n assert_eq!(res.person.age, 12);\n\n assert_eq!(res.person.isachild, true);\n\n assert_eq!(res.person.gender, 'O');\n\n assert_eq!(\n\n matches!(res.person.name, Some(x) if x == \"AAAAAAAAAAAAAA\"),\n\n true\n\n );\n\n assert_eq!(res.person.surname.is_none(), true);\n\n assert_eq!(\n\n res.friends,\n\n vec![\"Paul\", \"Paula\", \"Paulo\", \"Pau\", \"Potdeterrecuitemalcuite\"]\n\n .into_iter()\n\n .map(str::to_string)\n\n .collect::<Vec<String>>()\n\n );\n\n}\n", "file_path": "src/raw_value/tests/deserializer.rs", "rank": 60, "score": 45627.420961372394 }, { "content": "#[test]\n\nfn simple_deserialize() {\n\n const VAL: &str = r#\"\n\n\t{\n\n\t\t\"string\": \"world\",\n\n\t\t\"bool\": true,\n\n\t\t\"number\": 15,\n\n\t\t\"inumber\": -15,\n\n\t\t\"null\": null\n\n\t}\n\n\t\"#;\n\n\n\n let val: MessyJsonValueRaw<'_> = serde_json::from_str(VAL).unwrap();\n\n\n\n match val {\n\n MessyJsonValueRaw::Obj(obj) => {\n\n assert_eq!(\n\n matches!(obj.get(\"string\").unwrap(), MessyJsonValueRaw::String(x) if x == \"world\"),\n\n true\n\n );\n\n assert_eq!(\n", "file_path": "src/raw_value/tests/deserializing.rs", "rank": 61, "score": 44745.09524482113 }, { "content": "#[test]\n\nfn mismatch_obj_nested() {\n\n let parser = gen_parser();\n\n let mut deserializer = serde_json::Deserializer::from_str(VAL);\n\n let bogus_value = r#\"\n\n\t{\n\n\t\t\"hello\": \"world\",\n\n\t\t\"number\": 126354,\n\n\t\t\"bool\": true,\n\n\t\t\"array\": [\n\n\t\t\t\"hello\",\n\n\t\t\t\"hello\",\n\n\t\t\t\"world\",\n\n\t\t\t\"world\"\n\n\t\t],\n\n\t\t\"null\": null,\n\n\t\t\"obj\": {\n\n\t\t\t\"hello\": \"world\",\n\n\t\t\t\"number\": 128181684654,\n\n\t\t\t\"bool\": true,\n\n\t\t\t\"array\": [\n", "file_path": "src/tests/cmp_value.rs", "rank": 62, "score": 44745.09524482113 }, { "content": "#[test]\n\nfn wrong_key() {\n\n let nested_string = MessyJson::from(MessyJsonInner::String(MessyJsonScalar::new(false)));\n\n let nested_schema = MessyJson::from(MessyJsonInner::Obj(MessyJsonObject::from(\n\n MessyJsonObjectInner::new(\n\n vec![(gen_key(\"the\"), nested_string)].into_iter().collect(),\n\n false,\n\n ),\n\n )));\n\n let schema = MessyJson::from(MessyJsonInner::Obj(MessyJsonObject::from(\n\n MessyJsonObjectInner::new(\n\n vec![(gen_key(\"hello\"), nested_schema)]\n\n .into_iter()\n\n .collect(),\n\n false,\n\n ),\n\n )));\n\n let value = r#\"\n\n\t{\n\n\t\t\"hello\": {\n\n\t\t\t\"hola\": \"world\"\n", "file_path": "src/tests/parse_nested_object.rs", "rank": 63, "score": 44745.09524482113 }, { "content": "#[test]\n\nfn wrong_value() {\n\n let nested_string = MessyJson::from(MessyJsonInner::String(MessyJsonScalar::new(false)));\n\n let nested_schema = MessyJson::from(MessyJsonInner::Array(MessyJsonArray::new(\n\n nested_string,\n\n false,\n\n )));\n\n let schema = MessyJson::from(MessyJsonInner::Obj(MessyJsonObject::from(\n\n MessyJsonObjectInner::new(\n\n vec![(gen_key(\"hello\"), nested_schema)]\n\n .into_iter()\n\n .collect(),\n\n false,\n\n ),\n\n )));\n\n let value = r#\"\n\n\t{\n\n\t\t\"hello\": [\n\n\t\t\t1,\n\n\t\t\t2\n\n\t\t]\n\n\t}\n\n\t\"#;\n\n\n\n let mut deserializer = serde_json::Deserializer::from_str(value);\n\n schema\n\n .builder(MessyJsonSettings::default())\n\n .deserialize(&mut deserializer)\n\n .expect_err(\"the value type should produce an error\");\n\n}\n", "file_path": "src/tests/parse_array_object.rs", "rank": 64, "score": 44745.09524482113 }, { "content": "#[test]\n\nfn nested_array_deserialize() {\n\n const VAL: &str = r#\"\n\n\t{\n\n\t\t\"array\": [\n\n\t\t\t\"A string\",\n\n\t\t\t12,\n\n\t\t\tnull,\n\n\t\t\ttrue\n\n\t\t]\n\n\t}\n\n\t\"#;\n\n\n\n let val: MessyJsonValueRaw<'_> = serde_json::from_str(VAL).unwrap();\n\n\n\n match val {\n\n MessyJsonValueRaw::Obj(obj) => match obj.get(\"array\").unwrap() {\n\n MessyJsonValueRaw::Array(arr) => {\n\n assert_eq!(\n\n matches!(&arr[0], MessyJsonValueRaw::String(x) if x == \"A string\"),\n\n true\n", "file_path": "src/raw_value/tests/deserializing.rs", "rank": 65, "score": 43914.33834831632 }, { "content": "#[test]\n\nfn nested_obj_deserialize() {\n\n const VAL: &str = r#\"\n\n\t{\n\n\t\t\"object\": {\n\n\t\t\t\"hello\": \"world\",\n\n\t\t\t\"hello2\": \"world2\"\n\n\t\t}\n\n\t}\n\n\t\"#;\n\n\n\n let val: MessyJsonValueRaw<'_> = serde_json::from_str(VAL).unwrap();\n\n\n\n match val {\n\n MessyJsonValueRaw::Obj(obj) => match obj.get(\"object\").unwrap() {\n\n MessyJsonValueRaw::Obj(obj) => {\n\n assert_eq!(\n\n matches!(obj.get(\"hello\").unwrap(), MessyJsonValueRaw::String(x) if x == \"world\"),\n\n true\n\n );\n\n assert_eq!(\n\n matches!(obj.get(\"hello2\").unwrap(), MessyJsonValueRaw::String(x) if x == \"world2\"),\n\n true\n\n );\n\n }\n\n _ => panic!(\"Should've been an object\"),\n\n },\n\n _ => panic!(\"should've been an object\"),\n\n }\n\n}\n", "file_path": "src/raw_value/tests/deserializing.rs", "rank": 66, "score": 43914.33834831632 }, { "content": "#[test]\n\nfn nested_optional_parent_optional() {\n\n let nested_string_opt = MessyJson::from(MessyJsonInner::String(MessyJsonScalar::new(true)));\n\n let nested_string = MessyJson::from(MessyJsonInner::String(MessyJsonScalar::new(false)));\n\n let schema = MessyJson::from(MessyJsonInner::Obj(MessyJsonObject::from(\n\n MessyJsonObjectInner::new(\n\n vec![\n\n (\n\n gen_key(\"hello\"),\n\n MessyJson::from(MessyJsonInner::Obj(MessyJsonObject::from(\n\n MessyJsonObjectInner::new(\n\n vec![(gen_key(\"world\"), nested_string_opt)]\n\n .into_iter()\n\n .collect(),\n\n true, // Optional parent\n\n ),\n\n ))),\n\n ),\n\n (gen_key(\"whoami\"), nested_string.clone()),\n\n (gen_key(\"hehe\"), nested_string),\n\n ]\n", "file_path": "src/tests/unexact_obj.rs", "rank": 67, "score": 43914.33834831632 }, { "content": "fn gen_parser() -> MessyJson {\n\n let schema_nested2_obj = MessyJsonObject::from(MessyJsonObjectInner::new(\n\n vec![\n\n (\n\n gen_key(\"hello\"),\n\n MessyJson::from(MessyJsonInner::String(MessyJsonScalar::new(false))),\n\n ),\n\n (\n\n gen_key(\"number\"),\n\n MessyJson::from(MessyJsonInner::Number(MessyJsonNumeric::new(\n\n MessyJsonNumberType::U64,\n\n false,\n\n ))),\n\n ),\n\n (\n\n gen_key(\"bool\"),\n\n MessyJson::from(MessyJsonInner::Bool(MessyJsonScalar::new(false))),\n\n ),\n\n (\n\n gen_key(\"array\"),\n", "file_path": "src/tests/cmp_value.rs", "rank": 68, "score": 42455.52161150781 }, { "content": "fn gen_messy_json_schema() -> MessyJson {\n\n MessyJson::from(MessyJsonInner::Obj(MessyJsonObject::from(\n\n MessyJsonObjectInner::new(\n\n vec![(\n\n arcstr::literal!(\"hello\"),\n\n MessyJson::from(MessyJsonInner::String(MessyJsonScalar::new(false))),\n\n )]\n\n .into_iter()\n\n .collect(),\n\n false,\n\n ),\n\n )))\n\n}\n\n\n", "file_path": "src/benches/vs_serde_str.rs", "rank": 69, "score": 40231.09770376787 }, { "content": "fn messy_json_visit_map<'de, A, V>(\n\n mut seq: A,\n\n visitor: &V,\n\n obj: &MessyJsonObject,\n\n) -> Result<MessyJsonValueContainer<'de>, A::Error>\n\nwhere\n\n A: MapAccess<'de>,\n\n V: MessyJsonObjectTrait,\n\n{\n\n let mut res: BTreeMap<ArcStr, MessyJsonValue> = BTreeMap::new();\n\n while let Some(key_seed) = seq.next_key::<Cow<'de, str>>()? {\n\n let (key_str, val_schema) = obj\n\n .properties()\n\n .get_key_value(key_seed.as_ref())\n\n .ok_or_else(|| {\n\n serde::de::Error::custom(format!(\n\n \"The key `{}` is unknown. The expected keys were `[ {} ]`\",\n\n key_seed,\n\n obj.properties()\n\n .keys()\n", "file_path": "src/schema_visitor.rs", "rank": 70, "score": 39418.15097733158 }, { "content": "fn gen_messy_json_schema_dummy_obj() -> MessyJson {\n\n MessyJson::from(MessyJsonInner::Obj(MessyJsonObject::from(\n\n MessyJsonObjectInner::new(\n\n vec![(\n\n arcstr::literal!(\"hello\"),\n\n MessyJson::from(MessyJsonInner::Obj(MessyJsonObject::from(\n\n MessyJsonObjectInner::new(\n\n vec![(\n\n arcstr::literal!(\"hola\"),\n\n MessyJson::from(MessyJsonInner::String(MessyJsonScalar::new(false))),\n\n )]\n\n .into_iter()\n\n .collect(),\n\n false,\n\n ),\n\n ))),\n\n )]\n\n .into_iter()\n\n .collect(),\n\n false,\n\n ),\n\n )))\n\n}\n\n\n", "file_path": "src/benches/vs_serde_dummy_obj.rs", "rank": 71, "score": 38338.51764460929 }, { "content": "fn gen_messy_json_schema_optional_obj() -> MessyJson {\n\n MessyJson::from(MessyJsonInner::Obj(MessyJsonObject::from(\n\n MessyJsonObjectInner::new(\n\n vec![\n\n (\n\n arcstr::literal!(\"hello\"),\n\n MessyJson::from(MessyJsonInner::Obj(MessyJsonObject::from(\n\n MessyJsonObjectInner::new(\n\n vec![(\n\n arcstr::literal!(\"hola\"),\n\n MessyJson::from(MessyJsonInner::String(MessyJsonScalar::new(\n\n false,\n\n ))),\n\n )]\n\n .into_iter()\n\n .collect(),\n\n false,\n\n ),\n\n ))),\n\n ),\n", "file_path": "src/benches/vs_serde_optional_obj.rs", "rank": 72, "score": 38338.51764460929 }, { "content": "fn parse_serde_value(input: &str) -> Value {\n\n serde_json::from_str(input).unwrap()\n\n}\n\n\n", "file_path": "src/benches/vs_serde_str.rs", "rank": 73, "score": 37977.30780139516 }, { "content": "fn parse_messy_json_dummy_obj(schema: &MessyJson) {\n\n let mut deserializer = serde_json::Deserializer::from_str(DUMMY_OBJ);\n\n let _parsed: MessyJsonValueContainer = schema\n\n .builder(MessyJsonSettings::default())\n\n .deserialize(&mut deserializer)\n\n .unwrap();\n\n}\n\n\n", "file_path": "src/benches/vs_serde_dummy_obj.rs", "rank": 74, "score": 37119.141952748076 }, { "content": "fn parse_messy_json_optional_obj(schema: &MessyJson) {\n\n let mut deserializer = serde_json::Deserializer::from_str(OPTIONAL_OBJ);\n\n let _parsed: MessyJsonValueContainer = schema\n\n .builder(MessyJsonSettings::default())\n\n .deserialize(&mut deserializer)\n\n .unwrap();\n\n}\n\n\n", "file_path": "src/benches/vs_serde_optional_obj.rs", "rank": 75, "score": 37119.141952748076 }, { "content": "fn run_test(schema: &MessyJson, value: &str) {\n\n let mut deserializer = serde_json::Deserializer::from_str(value);\n\n let parsed: MessyJsonValueContainer = schema\n\n .builder(MessyJsonSettings::default())\n\n .deserialize(&mut deserializer)\n\n .unwrap();\n\n assert_eq!(\n\n matches!(parsed.inner(), MessyJsonValue::Obj(_)),\n\n true,\n\n \"The root should be an object\"\n\n );\n\n match parsed.inner() {\n\n MessyJsonValue::Obj(obj) => {\n\n assert_eq!(\n\n obj.len(),\n\n 1,\n\n \"The root object should only contain a single key\"\n\n );\n\n assert_eq!(\n\n obj.contains_key(\"hello\"),\n", "file_path": "src/tests/parse_array_object.rs", "rank": 76, "score": 36424.865273172676 }, { "content": "fn parse_serde_value_dummy_obj(input: &str) -> Value {\n\n serde_json::from_str(input).unwrap()\n\n}\n\n\n", "file_path": "src/benches/vs_serde_dummy_obj.rs", "rank": 77, "score": 36084.72774223659 }, { "content": "fn parse_serde_value_optional_obj(input: &str) -> Value {\n\n serde_json::from_str(input).unwrap()\n\n}\n\n\n", "file_path": "src/benches/vs_serde_optional_obj.rs", "rank": 78, "score": 36084.72774223659 }, { "content": "fn parse_messy_json(schema: &MessyJson, input: &str) {\n\n let mut deserializer = serde_json::Deserializer::from_str(input);\n\n let _parsed = schema\n\n .builder(MessyJsonSettings::default())\n\n .deserialize(&mut deserializer)\n\n .unwrap();\n\n}\n\n\n", "file_path": "src/benches/vs_serde_str.rs", "rank": 79, "score": 35794.84699612205 }, { "content": "fn parse_messy_json_raw(input: &str) -> MessyJsonValueRaw {\n\n serde_json::from_str(input).unwrap()\n\n}\n\n\n", "file_path": "src/benches/vs_serde_str.rs", "rank": 80, "score": 35515.08751761266 }, { "content": "extern crate messy_json;\n\nuse messy_json::*;\n\nuse serde::{de::DeserializeSeed, Deserialize, Serialize};\n\nuse serde_json::Value;\n\nuse std::borrow::Cow;\n\n\n\nconst DUMMY_OBJ: &str = r#\"\n\n{\n\n\t\"hello\": {\n\n\t\t\"hola\": \"world\"\n\n\t}\n\n}\n\n\"#;\n\n\n\n#[derive(Debug, Serialize, Deserialize)]\n", "file_path": "examples/simple_struct.rs", "rank": 81, "score": 34280.00887868655 }, { "content": "fn parse_messy_json_raw_optional_obj(input: &str) -> MessyJsonValueRaw {\n\n serde_json::from_str(input).unwrap()\n\n}\n\n\n", "file_path": "src/benches/vs_serde_optional_obj.rs", "rank": 82, "score": 33960.752628081565 }, { "content": "fn parse_serde_raw_value_dummy_obj(input: &str) -> MessyJsonValueRaw {\n\n serde_json::from_str(input).unwrap()\n\n}\n\n\n", "file_path": "src/benches/vs_serde_dummy_obj.rs", "rank": 83, "score": 33960.752628081565 }, { "content": "fn run_test(schema: &MessyJson, value: &str, expected: MessyJsonValue) {\n\n let mut deserializer = serde_json::Deserializer::from_str(value);\n\n let parsed: MessyJsonValueContainer = schema\n\n .builder(MessyJsonSettings::default())\n\n .deserialize(&mut deserializer)\n\n .unwrap();\n\n assert_eq!(\n\n matches!(parsed.inner(), MessyJsonValue::Obj(_)),\n\n true,\n\n \"The root should be an object\"\n\n );\n\n match parsed.inner() {\n\n MessyJsonValue::Obj(obj) => {\n\n assert_eq!(\n\n obj.len(),\n\n 1,\n\n \"The root object should only contain a single key\"\n\n );\n\n assert_eq!(\n\n obj.contains_key(\"hello\"),\n", "file_path": "src/tests/parse_nested_object.rs", "rank": 84, "score": 32636.123561729888 }, { "content": "fn run_flat_test(schema: &MessyJson, value: &str, expected: MessyJsonValue) {\n\n let mut deserializer = serde_json::Deserializer::from_str(value);\n\n let parsed: MessyJsonValueContainer = schema\n\n .builder(MessyJsonSettings::default())\n\n .deserialize(&mut deserializer)\n\n .unwrap();\n\n assert_eq!(\n\n matches!(parsed.inner(), MessyJsonValue::Obj(_)),\n\n true,\n\n \"The root should be an object\"\n\n );\n\n match parsed.inner() {\n\n MessyJsonValue::Obj(obj) => {\n\n assert_eq!(\n\n obj.len(),\n\n 1,\n\n \"The root object should only contain a single key\"\n\n );\n\n assert_eq!(\n\n obj.contains_key(\"hello\"),\n", "file_path": "src/tests/parse_simple.rs", "rank": 85, "score": 32636.123561729888 }, { "content": "use super::*;\n\n\n\nuse serde::de::IntoDeserializer;\n\n\n\n// This code has been **heavily** inspired by the code written in the [serde](serde) crate\n\n\n\npub struct MessyJsonRawEnumDeserializer<'a> {\n\n pub variant: Cow<'a, str>,\n\n pub value: Option<MessyJsonValueRaw<'a>>,\n\n}\n\n\n\npub struct MessyJsonRawVariantDeserializer<'a> {\n\n value: Option<MessyJsonValueRaw<'a>>,\n\n}\n\n\n\nimpl<'de> serde::de::EnumAccess<'de> for MessyJsonRawEnumDeserializer<'de> {\n\n type Error = serde::de::value::Error;\n\n type Variant = MessyJsonRawVariantDeserializer<'de>;\n\n\n\n fn variant_seed<V>(\n", "file_path": "src/raw_value/deserializer/enums.rs", "rank": 86, "score": 32386.093800709146 }, { "content": " Some(MessyJsonValueRaw::Array(v)) => {\n\n serde::Deserializer::deserialize_any(MessyJsonRawSeqDeserializer::new(v), visitor)\n\n }\n\n Some(other) => Err(serde::de::Error::invalid_type(\n\n other.into(),\n\n &\"tuple variant\",\n\n )),\n\n None => Err(serde::de::Error::invalid_type(\n\n serde::de::Unexpected::UnitVariant,\n\n &\"tuple variant\",\n\n )),\n\n }\n\n }\n\n\n\n fn struct_variant<V>(\n\n self,\n\n _fields: &'static [&'static str],\n\n visitor: V,\n\n ) -> Result<V::Value, Self::Error>\n\n where\n", "file_path": "src/raw_value/deserializer/enums.rs", "rank": 87, "score": 32380.399776545357 }, { "content": " }\n\n\n\n fn newtype_variant_seed<T>(self, seed: T) -> Result<T::Value, Self::Error>\n\n where\n\n T: DeserializeSeed<'de>,\n\n {\n\n match self.value {\n\n Some(value) => seed.deserialize(value),\n\n None => Err(serde::de::Error::invalid_type(\n\n serde::de::Unexpected::UnitVariant,\n\n &\"newtype variant\",\n\n )),\n\n }\n\n }\n\n\n\n fn tuple_variant<V>(self, _len: usize, visitor: V) -> Result<V::Value, Self::Error>\n\n where\n\n V: Visitor<'de>,\n\n {\n\n match self.value {\n", "file_path": "src/raw_value/deserializer/enums.rs", "rank": 88, "score": 32380.301063916813 }, { "content": " V: Visitor<'de>,\n\n {\n\n match self.value {\n\n Some(MessyJsonValueRaw::Obj(v)) => {\n\n serde::Deserializer::deserialize_any(MessyJsonRawMapDeserializer::new(v), visitor)\n\n }\n\n Some(other) => Err(serde::de::Error::invalid_type(\n\n other.into(),\n\n &\"struct variant\",\n\n )),\n\n None => Err(serde::de::Error::invalid_type(\n\n serde::de::Unexpected::UnitVariant,\n\n &\"struct variant\",\n\n )),\n\n }\n\n }\n\n}\n", "file_path": "src/raw_value/deserializer/enums.rs", "rank": 89, "score": 32378.696062318068 }, { "content": " self,\n\n seed: V,\n\n ) -> Result<(V::Value, MessyJsonRawVariantDeserializer<'de>), Self::Error>\n\n where\n\n V: DeserializeSeed<'de>,\n\n {\n\n let variant = self.variant.into_deserializer();\n\n let visitor = MessyJsonRawVariantDeserializer { value: self.value };\n\n seed.deserialize(variant).map(|v| (v, visitor))\n\n }\n\n}\n\n\n\nimpl<'de> serde::de::VariantAccess<'de> for MessyJsonRawVariantDeserializer<'de> {\n\n type Error = serde::de::value::Error;\n\n\n\n fn unit_variant(self) -> Result<(), Self::Error> {\n\n match self.value {\n\n Some(value) => serde::Deserialize::deserialize(value),\n\n None => Ok(()),\n\n }\n", "file_path": "src/raw_value/deserializer/enums.rs", "rank": 90, "score": 32378.134789372234 }, { "content": "fn parse_serde_optional_obj<T: serde::de::DeserializeOwned>(input: &str) -> T {\n\n serde_json::from_str(input).unwrap()\n\n}\n\n\n", "file_path": "src/benches/vs_serde_optional_obj.rs", "rank": 91, "score": 31026.939910337795 }, { "content": "fn parse_serde_dummy_obj<T: serde::de::DeserializeOwned>(input: &str) -> T {\n\n serde_json::from_str(input).unwrap()\n\n}\n\n\n", "file_path": "src/benches/vs_serde_dummy_obj.rs", "rank": 92, "score": 31026.939910337795 }, { "content": " type Target = MessyJsonObjectInner;\n\n\n\n fn deref(&self) -> &Self::Target {\n\n &self.0\n\n }\n\n}\n\n\n\nimpl From<MessyJsonObjectInner> for MessyJsonObject {\n\n fn from(x: MessyJsonObjectInner) -> Self {\n\n MessyJsonObject(Arc::new(x))\n\n }\n\n}\n\n\n\n/// ## JSON Object schema value\n\n///\n\n/// Describe a JSON Object at runtime\n\n#[derive(Clone, Debug, PartialEq, Eq, Hash, Default)]\n\npub struct MessyJsonObjectInner {\n\n optional: bool,\n\n properties: BTreeMap<KeyType, MessyJson>,\n", "file_path": "src/object.rs", "rank": 94, "score": 17.39319029615681 }, { "content": "use super::*;\n\nuse crate::schema::MessyJsonObjectTrait;\n\n\n\npub type KeyType = ArcStr;\n\n\n\n/// ## Wrapper for [MessyJsonObjectInner](MessyJsonObjectInner)\n\n///\n\n/// Wrapping it in an [Arc](std::sync::Arc)\n\n#[derive(Clone, Debug, PartialEq, Eq, Hash, Default)]\n\npub struct MessyJsonObject(Arc<MessyJsonObjectInner>);\n\n\n\nimpl MessyJsonObject {\n\n /// Create a builder object from the current object\n\n #[inline]\n\n pub fn builder(&self, settings: MessyJsonSettings) -> MessyJsonObjectBuilder {\n\n MessyJsonObjectBuilder::new(self, settings)\n\n }\n\n}\n\n\n\nimpl std::ops::Deref for MessyJsonObject {\n", "file_path": "src/object.rs", "rank": 96, "score": 15.536197858619234 }, { "content": "///\n\n/// Wrapping it in an [Arc](std::sync::Arc)\n\n#[derive(Clone, Debug, PartialEq, Eq, Hash)]\n\npub struct MessyJson(Arc<MessyJsonInner>);\n\n\n\nimpl std::ops::Deref for MessyJson {\n\n type Target = MessyJsonInner;\n\n\n\n fn deref(&self) -> &Self::Target {\n\n &self.0\n\n }\n\n}\n\n\n\nimpl MessyJson {\n\n #[inline]\n\n pub fn builder(&self, settings: MessyJsonSettings) -> MessyJsonBuilder {\n\n MessyJsonBuilder::new(self, settings)\n\n }\n\n}\n\n\n", "file_path": "src/schema.rs", "rank": 98, "score": 15.381266700532825 }, { "content": "/// ## JSON Number schema value\n\n///\n\n/// Describe a JSON Number at runtime. The type of number is to differentiate normal\n\n/// `u64` value from bigger `u128` (and more expensive) numbers.\n\n#[derive(Copy, Clone, Debug, PartialEq, Eq, Hash)]\n\npub struct MessyJsonNumeric {\n\n optional: bool,\n\n type_: MessyJsonNumberType,\n\n}\n\n\n\nimpl MessyJsonNumeric {\n\n /// Create a new [MessyJsonNumeric](MessyJsonNumeric)\n\n pub fn new(type_: MessyJsonNumberType, optional: bool) -> Self {\n\n MessyJsonNumeric { optional, type_ }\n\n }\n\n}\n\n\n\n/// ## JSON Number type schema\n\n#[derive(Copy, Clone, Debug, PartialEq, Eq, Hash)]\n\npub enum MessyJsonNumberType {\n", "file_path": "src/number.rs", "rank": 99, "score": 13.011887662876342 } ]
Rust
src/segment/data.rs
iFaceless/tinkv
b7f526ccfea53e82285891929bae177698947658
use crate::error::{Result, TinkvError}; use crate::util::{checksum, parse_file_id, BufReaderWithOffset, FileWithBufWriter}; use serde::{Deserialize, Serialize}; use log::{error, trace}; use std::fmt; use std::fs::{self, File}; use std::io::{copy, Read, Seek, SeekFrom, Write}; use std::path::{Path, PathBuf}; #[derive(Serialize, Deserialize, Debug)] struct InnerEntry { key: Vec<u8>, value: Vec<u8>, checksum: u32, } impl InnerEntry { fn new(key: &[u8], value: &[u8]) -> Self { let mut ent = InnerEntry { key: key.into(), value: value.into(), checksum: 0, }; ent.checksum = ent.fresh_checksum(); ent } fn fresh_checksum(&self) -> u32 { checksum(&self.value) } fn is_valid(&self) -> bool { self.checksum == self.fresh_checksum() } } impl fmt::Display for InnerEntry { fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { write!( f, "DataInnerEntry(key='{}', checksum={})", String::from_utf8_lossy(self.key.as_ref()), self.checksum, ) } } #[derive(Debug)] pub(crate) struct Entry { inner: InnerEntry, pub size: u64, pub offset: u64, pub file_id: u64, } impl Entry { fn new(file_id: u64, inner: InnerEntry, size: u64, offset: u64) -> Self { Self { inner, size, offset, file_id, } } pub(crate) fn is_valid(&self) -> bool { self.inner.is_valid() } pub(crate) fn key(&self) -> &[u8] { &self.inner.key } pub(crate) fn value(&self) -> &[u8] { &self.inner.value } } impl fmt::Display for Entry { fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { write!( f, "DataEntry(file_id={}, key='{}', offset={}, size={})", self.file_id, String::from_utf8_lossy(self.key().as_ref()), self.offset, self.size, ) } } #[derive(Debug)] pub(crate) struct DataFile { pub path: PathBuf, pub id: u64, writeable: bool, writer: Option<FileWithBufWriter>, reader: BufReaderWithOffset<File>, pub size: u64, } impl DataFile { pub(crate) fn new(path: &Path, writeable: bool) -> Result<Self> { let file_id = parse_file_id(path).expect("file id not found in file path"); let w = if writeable { let f = fs::OpenOptions::new() .create(true) .write(true) .append(true) .open(path)?; Some(FileWithBufWriter::from(f)?) } else { None }; let file = fs::File::open(path)?; let size = file.metadata()?.len(); let df = DataFile { path: path.to_path_buf(), id: file_id, writeable, reader: BufReaderWithOffset::new(file)?, writer: w, size, }; Ok(df) } pub(crate) fn write(&mut self, key: &[u8], value: &[u8]) -> Result<Entry> { let inner = InnerEntry::new(key, value); trace!("append {} to segement file {}", &inner, self.path.display()); let path = self.path.as_path(); let encoded = bincode::serialize(&inner)?; let w = self .writer .as_mut() .ok_or_else(|| TinkvError::FileNotWriteable(path.to_path_buf()))?; let offset = w.offset(); w.write_all(&encoded)?; w.flush()?; self.size = offset + encoded.len() as u64; let entry = Entry::new(self.id, inner, encoded.len() as u64, offset); trace!( "successfully append {} to data file {}", &entry, self.path.display() ); Ok(entry) } pub(crate) fn read(&mut self, offset: u64) -> Result<Entry> { trace!( "read key value with offset {} in data file {}", offset, self.path.display() ); let reader = &mut self.reader; reader.seek(SeekFrom::Start(offset))?; let inner: InnerEntry = bincode::deserialize_from(reader)?; let entry = Entry::new(self.id, inner, self.reader.offset() - offset, offset); trace!( "successfully read {} from data log file {}", &entry, self.path.display() ); Ok(entry) } pub(crate) fn copy_bytes_from( &mut self, src: &mut DataFile, offset: u64, size: u64, ) -> Result<u64> { let reader = &mut src.reader; if reader.offset() != offset { reader.seek(SeekFrom::Start(offset))?; } let mut r = reader.take(size); let w = self.writer.as_mut().expect("data file is not writeable"); let offset = w.offset(); let num_bytes = copy(&mut r, w)?; assert_eq!(num_bytes, size); self.size += num_bytes; Ok(offset) } pub(crate) fn entry_iter(&self) -> EntryIter { EntryIter { path: self.path.clone(), reader: fs::File::open(self.path.clone()).unwrap(), file_id: self.id, } } pub(crate) fn sync(&mut self) -> Result<()> { self.flush()?; if self.writer.is_some() { self.writer.as_mut().unwrap().sync()?; } Ok(()) } fn flush(&mut self) -> Result<()> { if self.writeable { self.writer.as_mut().unwrap().flush()?; } Ok(()) } } impl Drop for DataFile { fn drop(&mut self) { if let Err(e) = self.sync() { error!( "failed to sync data file: {}, got error: {}", self.path.display(), e ); } if self.writeable && self.size == 0 && fs::remove_file(self.path.as_path()).is_ok() { trace!("data file '{}' is empty, remove it.", self.path.display()); } } } #[derive(Debug)] pub(crate) struct EntryIter { path: PathBuf, reader: fs::File, file_id: u64, } impl Iterator for EntryIter { type Item = Entry; fn next(&mut self) -> Option<Self::Item> { let offset = self.reader.seek(SeekFrom::Current(0)).unwrap(); let inner: InnerEntry = bincode::deserialize_from(&self.reader).ok()?; let new_offset = self.reader.seek(SeekFrom::Current(0)).unwrap(); let entry = Entry::new(self.file_id, inner, new_offset - offset, offset); trace!( "iter read {} from data file {}", &entry, self.path.display() ); Some(entry) } } #[cfg(test)] mod tests { use super::*; #[test] fn test_new_entry() { let ent = InnerEntry::new(&b"key".to_vec(), &b"value".to_vec()); assert_eq!(ent.checksum, 494360628); } #[test] fn test_checksum_valid() { let ent = InnerEntry::new(&b"key".to_vec(), &b"value".to_vec()); assert_eq!(ent.is_valid(), true); } #[test] fn test_checksum_invalid() { let mut ent = InnerEntry::new(&b"key".to_vec(), &b"value".to_vec()); ent.value = b"value_changed".to_vec(); assert_eq!(ent.is_valid(), false); } }
use crate::error::{Result, TinkvError}; use crate::util::{checksum, parse_file_id, BufReaderWithOffset, FileWithBufWriter}; use serde::{Deserialize, Serialize}; use log::{error, trace}; use std::fmt; use std::fs::{self, File}; use std::io::{copy, Read, Seek, SeekFrom, Write}; use std::path::{Path, PathBuf}; #[derive(Serialize, Deserialize, Debug)] struct InnerEntry { key: Vec<u8>, value: Vec<u8>, checksum: u32, } impl InnerEntry { fn new(key: &[u8], value: &[u8]) -> Self { let mut ent = InnerEntry { key: key.into(), value: value.into(), checksum: 0, }; ent.checksum = ent.fresh_checksum(); ent } fn fresh_checksum(&self) -> u32 { checksum(&self.value) } fn is_valid(&self) -> bool { self.checksum == self.fresh_checksum() } } impl fmt::Display for InnerEntry { fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { write!( f, "DataInnerEntry(key='{}', checksum={})", String::from_utf8_lossy(self.key.as_ref()), self.checksum, ) } } #[derive(Debug)] pub(crate) struct Entry { inner: InnerEntry, pub size: u64, pub offset: u64, pub file_id: u64, } impl Entry { fn new(file_id: u64, inner: InnerEntry, size: u64, offset: u64) -> Self { Self { inner, size, offset, file_id, } } pub(crate) fn is_valid(&self) -> bool { self.inner.is_valid() } pub(crate) fn key(&self) -> &[u8] { &self.inner.key } pub(crate) fn value(&self) -> &[u8] { &self.inner.value } } impl fmt::Display for Entry { fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { write!( f, "DataEntry(file_id={}, key='{}', offset={}, size={})", self.file_id, String::from_utf8_lossy(self.key().as_ref()), self.offset, self.size, ) } } #[derive(Debug)] pub(crate) struct DataFile { pub path: PathBuf, pub id: u64, writeable: bool, writer: Option<FileWithBufWriter>, reader: BufReaderWithOffset<File>, pub size: u64, } impl DataFile { pub(crate) fn new(path: &Path, writeable: bool) -> Result<Self> { let file_id = parse_file_id(path).expect("file id not found in file path"); let w = if writeable { let f = fs::OpenOptions::new() .create(true) .write(true) .append(true) .open(path)?; Some(FileWithBufWriter::from(f)?) } else { None }; let file = fs::File::open(path)?; let size = file.metadata()?.len(); let df = DataFile { path: path.to_path_buf(), id: file_id, writeable, reader: BufReaderWithOffset::new(file)?, writer: w, size, }; Ok(df) } pub(crate) fn write(&mut self, key: &[u8], value: &[u8]) -> Result<Entry> { let inner = InnerEntry::new(key, value); trace!("append {} to segement file {}", &inner, self.path.display()); let path = self.path.as_path(); let encoded = bincode::serialize(&inner)?; let w = self .writer .as_mut() .ok_or_else(|| TinkvError::FileNotWriteable(path.to_path_buf()))?; let offset = w.offset(); w.write_all(&encoded)?; w.flush()?; self.size = offset + encoded.len() as u64; let entry = Entry::new(self.id, inner, encoded.len() as u64, offset); trace!( "successfully append {} to data file {}", &entry, self.path.display() ); Ok(entry) } pub(crate) fn read(&mut self, offset: u64) -> Result<Entry> { trace!( "read key value with offset {} in data file {}", offset, self.path.display() ); let reader = &mut self.reader; reader.seek(SeekFrom::Start(offset))?; let inner: InnerEntry = bincode::deserialize_from(reader)?; let entry = Entry::new(self.id, inner, self.reader.offset() - offset, offset); trace!( "successfully read {} from data log file {}", &entry, self.path.display() ); Ok(entry) } pub(crate) fn copy_bytes_from( &mut self, src: &mut DataFile, offset: u64, size: u64, ) -> Result<u64> { let reader = &mut src.reader; if reader.offset() != offset { reader.seek(SeekFrom::Start(offset))?; } let mut r = reader.take(size); let w = self.writer.as_mut().expect("data file is not writeable"); let offset = w.offset(); let num_bytes = copy(&mut r, w)?; assert_eq!(num_bytes, size); self.size += num_bytes; Ok(offset) } pub(crate) fn entry_iter(&self) -> EntryIter { EntryIter { path: self.path.clone(), reader: fs::File::open(self.path.clone()).unwrap(), file_id: self.id, } } pub(crate) fn sync(&mut self) -> Result<()> { self.flush()?; if self.writer.is_some() { self.writer.as_mut().unwrap().sync()?; } Ok(()) } fn flush(&mut self) -> Result<()> { if self.writeable { self.writer.as_mut().unwrap().flush()?; } Ok(()) } } impl Drop for DataFile { fn drop(&mut self) { if let Err(e) = self.sync() { error!( "failed to sync data file: {}, got error: {}", self.path.display(), e ); } if self.writeable && self.size == 0 && fs::remove_file(self.path.as_path()).is_ok() { trace!("data file '{}' is empty, remove it.", self.path.display()); } } } #[derive(Debug)] pub(crate) struct EntryIter { path: PathBuf, reader: fs::File, file_id: u64, } impl Iterator for EntryIter { type Item = Entry;
} #[cfg(test)] mod tests { use super::*; #[test] fn test_new_entry() { let ent = InnerEntry::new(&b"key".to_vec(), &b"value".to_vec()); assert_eq!(ent.checksum, 494360628); } #[test] fn test_checksum_valid() { let ent = InnerEntry::new(&b"key".to_vec(), &b"value".to_vec()); assert_eq!(ent.is_valid(), true); } #[test] fn test_checksum_invalid() { let mut ent = InnerEntry::new(&b"key".to_vec(), &b"value".to_vec()); ent.value = b"value_changed".to_vec(); assert_eq!(ent.is_valid(), false); } }
fn next(&mut self) -> Option<Self::Item> { let offset = self.reader.seek(SeekFrom::Current(0)).unwrap(); let inner: InnerEntry = bincode::deserialize_from(&self.reader).ok()?; let new_offset = self.reader.seek(SeekFrom::Current(0)).unwrap(); let entry = Entry::new(self.file_id, inner, new_offset - offset, offset); trace!( "iter read {} from data file {}", &entry, self.path.display() ); Some(entry) }
function_block-full_function
[ { "content": "pub fn checksum(data: &[u8]) -> u32 {\n\n crc::crc32::checksum_ieee(data)\n\n}\n\n\n", "file_path": "src/util/misc.rs", "rank": 0, "score": 211904.36433031445 }, { "content": "pub fn parse_file_id(path: &Path) -> Option<u64> {\n\n path.file_name()?\n\n .to_str()?\n\n .split('.')\n\n .next()?\n\n .parse::<u64>()\n\n .ok()\n\n}\n\n\n", "file_path": "src/util/misc.rs", "rank": 1, "score": 192109.78990192726 }, { "content": "fn segment_data_file_path(dir: &Path, segment_id: u64) -> PathBuf {\n\n segment_file_path(dir, segment_id, config::DATA_FILE_SUFFIX)\n\n}\n\n\n", "file_path": "src/store.rs", "rank": 2, "score": 171044.70669435634 }, { "content": "fn segment_hint_file_path(dir: &Path, segment_id: u64) -> PathBuf {\n\n segment_file_path(dir, segment_id, config::HINT_FILE_SUFFIX)\n\n}\n\n\n", "file_path": "src/store.rs", "rank": 3, "score": 153769.75628568587 }, { "content": "fn segment_file_path(dir: &Path, segment_id: u64, suffix: &str) -> PathBuf {\n\n let mut p = dir.to_path_buf();\n\n p.push(format!(\"{:012}{}\", segment_id, suffix));\n\n p\n\n}\n\n\n\n#[derive(Debug, Copy, Clone)]\n\npub(crate) struct Config {\n\n max_data_file_size: u64,\n\n max_key_size: u64,\n\n max_value_size: u64,\n\n // sync data to storage after each writting operation.\n\n // we should balance data reliability and writting performance.\n\n sync: bool,\n\n}\n\n\n\nimpl Default for Config {\n\n fn default() -> Self {\n\n Self {\n\n max_data_file_size: config::DEFAULT_MAX_DATA_FILE_SIZE,\n", "file_path": "src/store.rs", "rank": 4, "score": 144248.3363595627 }, { "content": "fn parse_length(value: &[u8]) -> Result<i64> {\n\n let s = String::from_utf8_lossy(value).to_string();\n\n s.parse().map_err(|_| {\n\n TinkvError::new_resp_common(\n\n \"INVALIDLENGTH\",\n\n &format!(\"protocol error, cannot parse length from {}\", s),\n\n )\n\n })\n\n}\n\n\n\n#[derive(Debug)]\n\npub(crate) struct ValueIter<B>\n\nwhere\n\n B: BufRead,\n\n{\n\n de: Deserializer<B>,\n\n}\n\n\n\nimpl<B> Iterator for ValueIter<B>\n\nwhere\n", "file_path": "src/resp.rs", "rank": 6, "score": 132524.9818952914 }, { "content": "pub fn to_utf8_string(value: &[u8]) -> String {\n\n String::from_utf8_lossy(value).to_string()\n\n}\n\n\n\n#[cfg(test)]\n\nmod tests {\n\n use super::*;\n\n\n\n #[test]\n\n fn test_parse_file_id() {\n\n let r = parse_file_id(Path::new(\"path/to/12345.tinkv.data\"));\n\n assert_eq!(r, Some(12345 as u64));\n\n\n\n let r = parse_file_id(Path::new(\"path/to/.tinkv.data\"));\n\n assert_eq!(r, None);\n\n\n\n let r = parse_file_id(Path::new(\"path/to\"));\n\n assert_eq!(r, None);\n\n }\n\n\n\n #[test]\n\n fn test_to_utf8_str() {\n\n assert_eq!(to_utf8_string(b\"hello, world\"), \"hello, world\".to_owned());\n\n }\n\n}\n", "file_path": "src/util/misc.rs", "rank": 7, "score": 128902.59470003915 }, { "content": "#[test]\n\nfn remove_key() -> Result<()> {\n\n let tmpdir = TempDir::new().expect(\"unable to create tmp dir\");\n\n let mut store = Store::open(&tmpdir.path())?;\n\n\n\n store.set(b\"version\", b\"1.0\")?;\n\n assert!(store.remove(b\"version\").is_ok());\n\n assert_eq!(store.get(b\"version\")?, None);\n\n\n\n Ok(())\n\n}\n\n\n", "file_path": "tests/store.rs", "rank": 8, "score": 127919.09281782487 }, { "content": "#[test]\n\nfn remove_non_existent_key() -> Result<()> {\n\n let tmpdir = TempDir::new().expect(\"unable to create tmp dir\");\n\n let mut store = Store::open(&tmpdir.path())?;\n\n\n\n assert!(store.remove(b\"version\").is_err());\n\n\n\n Ok(())\n\n}\n\n\n", "file_path": "tests/store.rs", "rank": 9, "score": 118498.86222466297 }, { "content": "#[derive(Debug, Clone, Copy)]\n\nstruct KeyDirEntry {\n\n /// data file id that stores key value pair.\n\n segment_id: u64,\n\n /// data entry offset in data file.\n\n offset: u64,\n\n /// data entry size.\n\n size: u64,\n\n}\n\n\n\nimpl KeyDirEntry {\n\n fn new(segment_id: u64, offset: u64, size: u64) -> Self {\n\n KeyDirEntry {\n\n segment_id,\n\n offset,\n\n size,\n\n }\n\n }\n\n}\n\n\n\n#[derive(Debug, Copy, Clone, Default)]\n", "file_path": "src/store.rs", "rank": 10, "score": 110224.64019383519 }, { "content": "struct Conn<W> {\n\n writer: W,\n\n}\n\n\n\nimpl<W> Conn<W>\n\nwhere\n\n W: Write,\n\n{\n\n fn new(writer: W) -> Self {\n\n Self { writer }\n\n }\n\n\n\n fn write_value(&mut self, value: Value) -> Result<()> {\n\n trace!(\"send value to client: {}\", value);\n\n serialize_to_writer(&mut self.writer, &value)?;\n\n Ok(())\n\n }\n\n\n\n fn flush(&mut self) -> std::io::Result<()> {\n\n self.writer.flush()\n\n }\n\n}\n", "file_path": "src/server.rs", "rank": 11, "score": 103125.67622343333 }, { "content": "#[test]\n\nfn overwrite_value() -> Result<()> {\n\n let tmpdir = TempDir::new().expect(\"unable to create tmp dir\");\n\n let mut store = Store::open(&tmpdir.path())?;\n\n\n\n store.set(b\"version\", b\"1.0\")?;\n\n assert_eq!(store.get(b\"version\")?, Some(b\"1.0\".to_vec()));\n\n\n\n store.set(b\"version\", b\"2.0\")?;\n\n assert_eq!(store.get(b\"version\")?, Some(b\"2.0\".to_vec()));\n\n\n\n store.close()?;\n\n\n\n // open again and check data\n\n let mut store = Store::open(&tmpdir.path())?;\n\n assert_eq!(store.get(b\"version\")?, Some(b\"2.0\".to_vec()));\n\n\n\n Ok(())\n\n}\n\n\n", "file_path": "tests/store.rs", "rank": 12, "score": 102888.81932260068 }, { "content": "#[test]\n\nfn get_stored_value() -> Result<()> {\n\n let tmpdir = TempDir::new().expect(\"unable to create tmp dir\");\n\n let mut store = Store::open(&tmpdir.path())?;\n\n\n\n store.set(b\"version\", b\"1.0\")?;\n\n store.set(b\"name\", b\"tinkv\")?;\n\n\n\n assert_eq!(store.get(b\"version\")?, Some(b\"1.0\".to_vec()));\n\n assert_eq!(store.get(b\"name\")?, Some(b\"tinkv\".to_vec()));\n\n assert_eq!(store.len(), 2);\n\n\n\n store.close()?;\n\n\n\n // open again, check persisted data.\n\n let mut store = Store::open(&tmpdir.path())?;\n\n assert_eq!(store.get(b\"version\")?, Some(b\"1.0\".to_vec()));\n\n assert_eq!(store.get(b\"name\")?, Some(b\"tinkv\".to_vec()));\n\n assert_eq!(store.len(), 2);\n\n\n\n Ok(())\n\n}\n\n\n", "file_path": "tests/store.rs", "rank": 13, "score": 99189.85002536375 }, { "content": "#[test]\n\nfn get_non_existent_key() -> Result<()> {\n\n let tmpdir = TempDir::new().expect(\"unable to create tmp dir\");\n\n let mut store = Store::open(&tmpdir.path())?;\n\n\n\n store.set(b\"version\", b\"1.0\")?;\n\n assert_eq!(store.get(b\"version_foo\")?, None);\n\n store.close()?;\n\n\n\n let mut store = Store::open(&tmpdir.path())?;\n\n assert_eq!(store.get(b\"version_foo\")?, None);\n\n\n\n Ok(())\n\n}\n\n\n", "file_path": "tests/store.rs", "rank": 14, "score": 95841.55764613264 }, { "content": "pub fn current_timestamp() -> u128 {\n\n SystemTime::now()\n\n .duration_since(UNIX_EPOCH)\n\n .expect(\"time went backwards\")\n\n .as_nanos()\n\n}\n\n\n", "file_path": "src/util/misc.rs", "rank": 15, "score": 85963.31440785844 }, { "content": "#[test]\n\nfn compaction() -> Result<()> {\n\n let tmpdir = TempDir::new().expect(\"unable to create tmp dir\");\n\n let mut store = Store::open(&tmpdir.path())?;\n\n\n\n for it in 0..100 {\n\n for id in 0..1000 {\n\n let k = format!(\"key_{}\", id);\n\n let v = format!(\"value_{}\", it);\n\n store.set(k.as_bytes(), v.as_bytes())?;\n\n }\n\n\n\n let stats = store.stats();\n\n if stats.total_stale_entries <= 10000 {\n\n continue;\n\n }\n\n\n\n // trigger compaction\n\n store.compact()?;\n\n\n\n let stats = store.stats();\n", "file_path": "tests/store.rs", "rank": 16, "score": 80646.64348364189 }, { "content": "fn main() -> tinkv::Result<()> {\n\n pretty_env_logger::init_timed();\n\n let mut store = Store::open(\".tinkv\")?;\n\n\n\n let begin = time::Instant::now();\n\n\n\n const TOTAL_KEYS: usize = 100000;\n\n for i in 0..TOTAL_KEYS {\n\n let k = format!(\"key_{}\", i);\n\n let v = format!(\n\n \"value_{}_{}_hello_world_this_is_a_bad_day\",\n\n i,\n\n tinkv::util::current_timestamp()\n\n );\n\n store.set(k.as_bytes(), v.as_bytes())?;\n\n store.set(k.as_bytes(), v.as_bytes())?;\n\n }\n\n\n\n let duration = time::Instant::now().duration_since(begin);\n\n let speed = (TOTAL_KEYS * 2) as f32 / duration.as_secs_f32();\n", "file_path": "examples/basic.rs", "rank": 17, "score": 74626.5407299347 }, { "content": "fn main() -> tinkv::Result<()> {\n\n pretty_env_logger::init_timed();\n\n let mut store = tinkv::OpenOptions::new()\n\n .max_data_file_size(1024 * 100)\n\n .open(\"/usr/local/var/tinkv\")?;\n\n\n\n let begin = time::Instant::now();\n\n\n\n const TOTAL_KEYS: usize = 1000;\n\n for i in 0..TOTAL_KEYS {\n\n let k = format!(\"hello_{}\", i);\n\n let v = format!(\"world_{}\", i);\n\n store.set(k.as_bytes(), v.as_bytes())?;\n\n store.set(k.as_bytes(), format!(\"{}_new\", v).as_bytes())?;\n\n }\n\n\n\n let duration = time::Instant::now().duration_since(begin);\n\n let speed = (TOTAL_KEYS * 2) as f32 / duration.as_secs_f32();\n\n println!(\n\n \"{} keys written in {} secs, {} keys/s\",\n", "file_path": "examples/hello.rs", "rank": 18, "score": 74626.5407299347 }, { "content": "fn set_benchmark(c: &mut Criterion) {\n\n let b = ParameterizedBenchmark::new(\n\n \"tinkv-store\",\n\n |b, _| {\n\n b.iter_batched(\n\n || {\n\n let tmpdir = TempDir::new().unwrap();\n\n (Store::open(&tmpdir.path()).unwrap(), tmpdir)\n\n },\n\n |(mut store, _tmpdir)| {\n\n for i in 1..(1 << 12) {\n\n store\n\n .set(format!(\"key_{}\", i).as_bytes(), b\"value\")\n\n .unwrap();\n\n }\n\n },\n\n BatchSize::SmallInput,\n\n )\n\n },\n\n iter::once(()),\n", "file_path": "benches/store_benchmark.rs", "rank": 19, "score": 68425.19405486064 }, { "content": "fn get_benchmark(c: &mut Criterion) {\n\n let b = ParameterizedBenchmark::new(\n\n \"tinkv-store\",\n\n |b, i| {\n\n let tempdir = TempDir::new().unwrap();\n\n let mut store = Store::open(&tempdir.path()).unwrap();\n\n for key_i in 1..(1 << i) {\n\n store\n\n .set(format!(\"key_{}\", key_i).as_bytes(), b\"value\")\n\n .unwrap();\n\n }\n\n\n\n let mut rng = SmallRng::from_seed([0; 16]);\n\n b.iter(|| {\n\n store\n\n .get(format!(\"key_{}\", rng.gen_range(1, 1 << i)).as_bytes())\n\n .unwrap();\n\n })\n\n },\n\n vec![8, 12, 16, 20],\n", "file_path": "benches/store_benchmark.rs", "rank": 20, "score": 68425.19405486064 }, { "content": "#[derive(Debug)]\n\nstruct Request {\n\n name: String,\n\n raw_argv: Vec<Value>,\n\n}\n\n\n\nimpl Request {\n\n fn argv(&self) -> Vec<&[u8]> {\n\n let mut res = vec![];\n\n for arg in self.raw_argv.iter() {\n\n if let Some(v) = arg.as_bulk_string() {\n\n res.push(v);\n\n }\n\n }\n\n res\n\n }\n\n}\n\n\n\nimpl fmt::Display for Request {\n\n fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {\n\n let mut argv_str = vec![];\n", "file_path": "src/server.rs", "rank": 21, "score": 65103.015054076626 }, { "content": " Pattern(#[from] glob::PatternError),\n\n #[error(transparent)]\n\n Codec(#[from] Box<bincode::ErrorKind>),\n\n /// Custom error definitions.\n\n #[error(\"crc check failed, data entry (key='{}', file_id={}, offset={}) was corrupted\", String::from_utf8_lossy(.key), .file_id, .offset)]\n\n DataEntryCorrupted {\n\n file_id: u64,\n\n key: Vec<u8>,\n\n offset: u64,\n\n },\n\n #[error(\"key '{}' not found\", String::from_utf8_lossy(.0))]\n\n KeyNotFound(Vec<u8>),\n\n #[error(\"file '{}' is not writeable\", .0.display())]\n\n FileNotWriteable(PathBuf),\n\n #[error(\"key is too large\")]\n\n KeyIsTooLarge,\n\n #[error(\"value is too large\")]\n\n ValueIsTooLarge,\n\n #[error(\"{}\", .0)]\n\n Custom(String),\n", "file_path": "src/error.rs", "rank": 22, "score": 49546.92131746261 }, { "content": "use std::io;\n\nuse std::num::ParseIntError;\n\nuse std::path::PathBuf;\n\nuse thiserror::Error;\n\n\n\n/// The result of any operation.\n\npub type Result<T> = ::std::result::Result<T, TinkvError>;\n\n\n\n/// The kind of error that could be produced during tinkv operation.\n\n#[derive(Error, Debug)]\n\npub enum TinkvError {\n\n #[error(transparent)]\n\n ParseInt(#[from] ParseIntError),\n\n #[error(\"parse resp value failed\")]\n\n ParseRespValue,\n\n #[error(transparent)]\n\n Io(#[from] io::Error),\n\n #[error(transparent)]\n\n Glob(#[from] glob::GlobError),\n\n #[error(transparent)]\n", "file_path": "src/error.rs", "rank": 23, "score": 49532.68615214516 }, { "content": " #[error(transparent)]\n\n Other(#[from] anyhow::Error),\n\n #[error(\"{} {}\", .name, .msg)]\n\n RespCommon { name: String, msg: String },\n\n #[error(\"wrong number of arguments for '{}' command\", .0)]\n\n RespWrongNumOfArgs(String),\n\n}\n\n\n\nimpl TinkvError {\n\n pub fn new_resp_common(name: &str, msg: &str) -> Self {\n\n Self::RespCommon {\n\n name: name.to_owned(),\n\n msg: msg.to_owned(),\n\n }\n\n }\n\n\n\n pub fn resp_wrong_num_of_args(name: &str) -> Self {\n\n Self::RespWrongNumOfArgs(name.to_owned())\n\n }\n\n}\n", "file_path": "src/error.rs", "rank": 24, "score": 49522.539285289386 }, { "content": "\n\n self.stats.total_active_entries -= 1;\n\n self.stats.total_stale_entries += 1;\n\n self.stats.size_of_all_data_files += entry.size;\n\n self.stats.size_of_stale_entries += old.size + entry.size;\n\n\n\n Ok(())\n\n } else {\n\n trace!(\n\n \"remove key '{}' failed, not found in datastore\",\n\n String::from_utf8_lossy(key)\n\n );\n\n Err(TinkvError::KeyNotFound(key.into()))\n\n }\n\n }\n\n\n\n fn write(&mut self, key: &[u8], value: &[u8]) -> Result<DataEntry> {\n\n let mut df = self\n\n .active_data_file\n\n .as_mut()\n", "file_path": "src/store.rs", "rank": 41, "score": 19896.736667319692 }, { "content": " Ok(())\n\n }\n\n\n\n fn build_keydir_from_data_file(&mut self, file_id: u64) -> Result<()> {\n\n let df = self.data_files.get(&file_id).unwrap();\n\n info!(\"build keydir from data file {}\", df.path.display());\n\n for entry in df.entry_iter() {\n\n if !entry.is_valid() {\n\n return Err(TinkvError::DataEntryCorrupted {\n\n file_id: df.id,\n\n key: entry.key().into(),\n\n offset: entry.offset,\n\n });\n\n }\n\n\n\n if entry.value() == config::REMOVE_TOMESTONE {\n\n trace!(\"{} is a remove tomestone\", &entry);\n\n self.stats.total_stale_entries += 1;\n\n self.stats.size_of_stale_entries += entry.size;\n\n\n", "file_path": "src/store.rs", "rank": 42, "score": 19896.193189270347 }, { "content": " if self.config.sync {\n\n // make sure data entry is persisted in storage.\n\n df.sync()?;\n\n }\n\n\n\n Ok(entry)\n\n }\n\n\n\n /// Get key value from database.\n\n pub fn get(&mut self, key: &[u8]) -> Result<Option<Vec<u8>>> {\n\n if let Some(keydir_ent) = self.keydir.get(key) {\n\n trace!(\n\n \"found key '{}' in keydir, got value {:?}\",\n\n String::from_utf8_lossy(key),\n\n &keydir_ent\n\n );\n\n let df = self\n\n .data_files\n\n .get_mut(&keydir_ent.segment_id)\n\n .unwrap_or_else(|| panic!(\"data file {} not found\", &keydir_ent.segment_id));\n", "file_path": "src/store.rs", "rank": 43, "score": 19894.08326434479 }, { "content": "\n\n // build data file path.\n\n let p = segment_data_file_path(&self.path, next_file_id);\n\n debug!(\"new data file at: {}\", &p.display());\n\n self.active_data_file = Some(DataFile::new(p.as_path(), true)?);\n\n\n\n // preapre a read-only data file with the same path.\n\n let df = DataFile::new(p.as_path(), false)?;\n\n self.data_files.insert(df.id, df);\n\n\n\n self.stats.total_data_files += 1;\n\n\n\n Ok(())\n\n }\n\n\n\n /// Save key & value pair to database.\n\n pub fn set(&mut self, key: &[u8], value: &[u8]) -> Result<()> {\n\n if key.len() as u64 > self.config.max_key_size {\n\n return Err(TinkvError::KeyIsTooLarge);\n\n }\n", "file_path": "src/store.rs", "rank": 44, "score": 19893.26077303368 }, { "content": " let entry = df.read(keydir_ent.offset)?;\n\n if !entry.is_valid() {\n\n Err(TinkvError::DataEntryCorrupted {\n\n file_id: df.id,\n\n key: entry.key().into(),\n\n offset: entry.offset,\n\n })\n\n } else {\n\n Ok(Some(entry.value().into()))\n\n }\n\n } else {\n\n Ok(None)\n\n }\n\n }\n\n\n\n /// Clear stale entries from data files and reclaim disk space.\n\n pub fn compact(&mut self) -> Result<()> {\n\n let begin_at = time::Instant::now();\n\n\n\n info!(\n", "file_path": "src/store.rs", "rank": 45, "score": 19892.073140833432 }, { "content": " self.stats.total_stale_entries += 1;\n\n }\n\n }\n\n\n\n self.stats.size_of_all_data_files += ent.size;\n\n\n\n Ok(())\n\n }\n\n\n\n /// Remove key value from database.\n\n pub fn remove(&mut self, key: &[u8]) -> Result<()> {\n\n if self.keydir.contains_key(key) {\n\n trace!(\n\n \"remove key '{}' from datastore\",\n\n String::from_utf8_lossy(key)\n\n );\n\n // write tomestone, will be removed on compaction.\n\n let entry = self.write(key, config::REMOVE_TOMESTONE)?;\n\n // remove key from in-memory index.\n\n let old = self.keydir.remove(key).expect(\"key not found\");\n", "file_path": "src/store.rs", "rank": 46, "score": 19888.89896542805 }, { "content": " .get_mut(&keydir_ent.segment_id)\n\n .expect(\"cannot find data file\");\n\n trace!(\n\n \"copy key '{}': original data file({}) -> compaction data file({})\",\n\n String::from_utf8_lossy(key),\n\n df.path.display(),\n\n compaction_df.path.display()\n\n );\n\n\n\n let offset = compaction_df.copy_bytes_from(df, keydir_ent.offset, keydir_ent.size)?;\n\n\n\n keydir_ent.segment_id = compaction_df.id;\n\n keydir_ent.offset = offset;\n\n\n\n hint_file.write(key, keydir_ent.offset, keydir_ent.size)?;\n\n }\n\n\n\n compaction_df.sync()?;\n\n hint_file.sync()?;\n\n\n", "file_path": "src/store.rs", "rank": 47, "score": 19887.40270499937 }, { "content": " B: BufRead,\n\n{\n\n type Item = Result<Value>;\n\n\n\n fn next(&mut self) -> Option<Self::Item> {\n\n match self.de.next() {\n\n Ok(None) => None,\n\n Ok(Some(v)) => Some(Ok(v)),\n\n Err(e) => Some(Err(e)),\n\n }\n\n }\n\n}\n\n\n\n#[allow(dead_code)]\n\npub(crate) fn serialize_to_bytes(value: &Value) -> Result<Vec<u8>> {\n\n let mut buf = Vec::new();\n\n let mut c = Cursor::new(&mut buf);\n\n serialize_to_writer(&mut c, value)?;\n\n c.flush()?;\n\n Ok(buf)\n", "file_path": "src/resp.rs", "rank": 48, "score": 19886.44028807023 }, { "content": "\n\n if value.len() as u64 > self.config.max_value_size {\n\n return Err(TinkvError::ValueIsTooLarge);\n\n }\n\n\n\n // save data to data file.\n\n let ent = self.write(key, value)?;\n\n\n\n // update keydir, the in-memory index.\n\n let old = self.keydir.insert(\n\n key.to_vec(),\n\n KeyDirEntry::new(ent.file_id, ent.offset, ent.size),\n\n );\n\n\n\n match old {\n\n None => {\n\n self.stats.total_active_entries += 1;\n\n }\n\n Some(entry) => {\n\n self.stats.size_of_stale_entries += entry.size;\n", "file_path": "src/store.rs", "rank": 49, "score": 19885.42285025441 }, { "content": " if let Some(old_ent) = self.keydir.remove(entry.key()) {\n\n self.stats.size_of_stale_entries += old_ent.size;\n\n self.stats.total_stale_entries += 1;\n\n }\n\n } else {\n\n let keydir_ent = KeyDirEntry::new(file_id, entry.offset, entry.size);\n\n let old = self.keydir.insert(entry.key().into(), keydir_ent);\n\n if let Some(old_ent) = old {\n\n self.stats.size_of_stale_entries += old_ent.size;\n\n self.stats.total_stale_entries += 1;\n\n }\n\n }\n\n }\n\n Ok(())\n\n }\n\n\n\n fn new_active_data_file(&mut self, file_id: Option<u64>) -> Result<()> {\n\n // default next file id should be `max_file_id` + 1\n\n let next_file_id: u64 =\n\n file_id.unwrap_or_else(|| self.data_files.keys().max().unwrap_or(&0) + 1);\n", "file_path": "src/store.rs", "rank": 50, "score": 19884.991378050032 }, { "content": " duration,\n\n self.keydir.len(),\n\n self.stats\n\n );\n\n Ok(())\n\n }\n\n\n\n fn build_keydir_from_hint_file(&mut self, path: &Path) -> Result<()> {\n\n trace!(\"build keydir from hint file {}\", path.display());\n\n let mut hint_file = HintFile::new(path, false)?;\n\n let hint_file_id = hint_file.id;\n\n\n\n for entry in hint_file.entry_iter() {\n\n let keydir_ent = KeyDirEntry::new(hint_file_id, entry.offset, entry.size);\n\n let old = self.keydir.insert(entry.key, keydir_ent);\n\n if let Some(old_ent) = old {\n\n self.stats.size_of_stale_entries += old_ent.size;\n\n self.stats.total_stale_entries += 1;\n\n }\n\n }\n", "file_path": "src/store.rs", "rank": 51, "score": 19884.849366769562 }, { "content": "}\n\n\n\n#[allow(dead_code)]\n\npub(crate) fn serialize_to_writer<W>(writer: &mut W, value: &Value) -> Result<()>\n\nwhere\n\n W: Write,\n\n{\n\n Serializer::new(writer).serialize(value)\n\n}\n\n\n\n#[derive(Debug)]\n\npub(crate) struct Serializer<W> {\n\n writer: W,\n\n}\n\n\n\nimpl<W> Serializer<W>\n\nwhere\n\n W: Write,\n\n{\n\n pub fn new(writer: W) -> Self {\n", "file_path": "src/resp.rs", "rank": 52, "score": 19884.497752034204 }, { "content": "}\n\n\n\n/// Deserialize RESP values from byte slice and return a value iterator.\n\n/// Ref: https://github.com/rust-lang/rust/issues/51282\n\n#[allow(dead_code)]\n\npub(crate) fn deserialize_from_slice(value: &[u8]) -> impl Iterator<Item = Result<Value>> + '_ {\n\n deserialize_from_reader(Cursor::new(value))\n\n}\n\n\n\n/// Deserialize RESP values from a stream reader and return a value iterator.\n\npub(crate) fn deserialize_from_reader<B: BufRead>(\n\n reader: B,\n\n) -> impl Iterator<Item = Result<Value>> {\n\n Deserializer::from_reader(reader).into_iter()\n\n}\n\n\n\n#[derive(Debug)]\n\npub(crate) struct Deserializer<B> {\n\n inner: ByteLineReader<B>,\n\n buf: Vec<u8>,\n", "file_path": "src/resp.rs", "rank": 53, "score": 19884.454152433696 }, { "content": " fn open_data_files(&mut self) -> Result<()> {\n\n let pattern = format!(\"{}/*{}\", self.path.display(), config::DATA_FILE_SUFFIX);\n\n trace!(\"read data files with pattern: {}\", &pattern);\n\n for path in glob(&pattern)? {\n\n let df = DataFile::new(path?.as_path(), false)?;\n\n\n\n self.stats.total_data_files += 1;\n\n self.stats.size_of_all_data_files += df.size;\n\n\n\n self.data_files.insert(df.id, df);\n\n }\n\n trace!(\"got {} immutable data files\", self.data_files.len());\n\n\n\n Ok(())\n\n }\n\n\n\n fn build_keydir(&mut self) -> Result<()> {\n\n let begin_at = time::Instant::now();\n\n\n\n // TODO: build keydir from index file.\n", "file_path": "src/store.rs", "rank": 54, "score": 19883.206972088185 }, { "content": "//! A simple key-value store.\n\nuse crate::config;\n\nuse crate::error::{Result, TinkvError};\n\nuse crate::segment::{DataEntry, DataFile, HintFile};\n\nuse glob::glob;\n\nuse log::{debug, info, trace};\n\nuse std::collections::{BTreeMap, HashMap};\n\nuse std::fs;\n\nuse std::fs::create_dir_all;\n\nuse std::time;\n\n\n\nuse std::path::{Path, PathBuf};\n\n\n\n/// The `Store` stores key/value pairs.\n\n///\n\n/// Key/value pairs are persisted in data files.\n\n#[derive(Debug)]\n\npub struct Store {\n\n // directory for database.\n\n path: PathBuf,\n", "file_path": "src/store.rs", "rank": 55, "score": 19883.099874706302 }, { "content": " // create a new hint file to store compaction file index.\n\n let hint_file_path = segment_hint_file_path(&self.path, compaction_data_file_id);\n\n\n\n debug!(\"create compaction hint file: {}\", hint_file_path.display());\n\n let mut hint_file = HintFile::new(&hint_file_path, true)?;\n\n\n\n let mut total_size_of_compaction_files = 0;\n\n\n\n // copy all the data entries into compaction data file.\n\n // TODO: check if data file size exceeds threshold, switch\n\n // to another one if nessesary.\n\n for (key, keydir_ent) in self.keydir.iter_mut() {\n\n if compaction_df.size > self.config.max_data_file_size {\n\n total_size_of_compaction_files += compaction_df.size;\n\n\n\n compaction_df.sync()?;\n\n hint_file.sync()?;\n\n\n\n compaction_data_file_id += 1;\n\n // switch to a new data file for compaction.\n", "file_path": "src/store.rs", "rank": 56, "score": 19882.691777831133 }, { "content": " .expect(\"active data file not found\");\n\n\n\n // check file size, switch to another one if nessesary.\n\n if df.size > self.config.max_data_file_size {\n\n info!(\"size of active data file '{}' exceeds maximum size of {} bytes, switch to another one.\", df.path.display(), self.config.max_data_file_size);\n\n\n\n // sync data to disk.\n\n let _ = df.sync();\n\n\n\n // create a new active data file.\n\n self.new_active_data_file(None)?;\n\n\n\n // get new active data file for writting.\n\n df = self\n\n .active_data_file\n\n .as_mut()\n\n .expect(\"active data file not found\");\n\n }\n\n\n\n let entry = df.write(key, value)?;\n", "file_path": "src/store.rs", "rank": 57, "score": 19882.433515604444 }, { "content": " }\n\n\n\n fn next_file_id(&self) -> u64 {\n\n self.active_data_file\n\n .as_ref()\n\n .expect(\"active data file not found\")\n\n .id\n\n + 1\n\n }\n\n\n\n /// Return current stats of datastore.\n\n pub fn stats(&self) -> &Stats {\n\n &self.stats\n\n }\n\n\n\n /// Return all keys in datastore.\n\n pub fn keys(&self) -> impl Iterator<Item = &Vec<u8>> {\n\n self.keydir.keys()\n\n }\n\n\n", "file_path": "src/store.rs", "rank": 58, "score": 19882.169976403737 }, { "content": "}\n\n\n\nimpl<B> Deserializer<B>\n\nwhere\n\n B: BufRead,\n\n{\n\n #[allow(dead_code)]\n\n pub fn from_reader(inner: B) -> Self {\n\n Self {\n\n inner: ByteLineReader::new(inner),\n\n buf: Vec::new(),\n\n }\n\n }\n\n\n\n #[allow(dead_code)]\n\n pub fn into_iter(self) -> ValueIter<B> {\n\n ValueIter { de: self }\n\n }\n\n\n\n pub fn next(&mut self) -> Result<Option<Value>> {\n", "file_path": "src/resp.rs", "rank": 59, "score": 19881.91609362608 }, { "content": "\n\nimpl OpenOptions {\n\n #[allow(dead_code)]\n\n pub fn new() -> Self {\n\n Self::default()\n\n }\n\n\n\n #[allow(dead_code)]\n\n pub fn max_data_file_size(&mut self, value: u64) -> &mut Self {\n\n self.config.max_data_file_size = value;\n\n self\n\n }\n\n\n\n #[allow(dead_code)]\n\n pub fn max_key_size(&mut self, value: u64) -> &mut Self {\n\n self.config.max_key_size = value;\n\n self\n\n }\n\n\n\n #[allow(dead_code)]\n", "file_path": "src/store.rs", "rank": 60, "score": 19881.736844105155 }, { "content": " ///\n\n /// You can continue iteration manually by returning `Ok(true)`,\n\n /// or stop iteration by returning `Ok(false)`.\n\n pub fn for_each<F>(&mut self, f: &mut F) -> Result<()>\n\n where\n\n F: FnMut(&[u8], &[u8]) -> Result<bool>,\n\n {\n\n // too stupid, just in order to pass borrow checking.\n\n // FIXME: find a better way to implement this feature?\n\n let mut keys = vec![];\n\n for key in self.keys() {\n\n keys.push(key.clone());\n\n }\n\n\n\n for key in keys {\n\n let r = self.get(&key)?;\n\n if let Some(value) = r {\n\n let contine = f(&key, &value)?;\n\n if !contine {\n\n break;\n", "file_path": "src/store.rs", "rank": 61, "score": 19881.208890043396 }, { "content": " total_size_of_compaction_files += compaction_df.size;\n\n\n\n // remove stale segments.\n\n let mut stale_segment_count = 0;\n\n for df in self.data_files.values() {\n\n if df.id <= next_file_id {\n\n if df.path.exists() {\n\n debug!(\"try to remove stale data file: {}\", df.path.display());\n\n fs::remove_file(&df.path)?;\n\n }\n\n\n\n let hint_file_path = segment_hint_file_path(&self.path, df.id);\n\n if hint_file_path.exists() {\n\n debug!(\n\n \"try to remove stale hint file: {}\",\n\n &hint_file_path.display()\n\n );\n\n fs::remove_file(&hint_file_path)?;\n\n }\n\n\n", "file_path": "src/store.rs", "rank": 62, "score": 19881.17292763868 }, { "content": " // holds a bunch of data files.\n\n data_files: HashMap<u64, DataFile>,\n\n // only active data file is writeable.\n\n active_data_file: Option<DataFile>,\n\n // keydir maintains key value index for fast query.\n\n keydir: BTreeMap<Vec<u8>, KeyDirEntry>,\n\n /// monitor tinkv store status, record statistics data.\n\n stats: Stats,\n\n /// store config.\n\n config: Config,\n\n}\n\n\n\nimpl Store {\n\n /// Initialize key value store with the given path.\n\n /// If the given path not found, a new one will be created.\n\n pub fn open<P: AsRef<Path>>(path: P) -> Result<Self> {\n\n Self::open_with_options(path, Config::default())\n\n }\n\n\n\n /// Open datasotre directory with custom options.\n", "file_path": "src/store.rs", "rank": 63, "score": 19881.164536813816 }, { "content": " Ok(stream) => {\n\n if let Err(e) = self.serve(stream) {\n\n error!(\"{}\", e);\n\n }\n\n }\n\n Err(e) => error!(\"{}\", e),\n\n }\n\n }\n\n Ok(())\n\n }\n\n\n\n fn serve(&mut self, stream: TcpStream) -> Result<()> {\n\n let peer_addr = stream.peer_addr()?;\n\n debug!(\"got connection from {}\", &peer_addr);\n\n let reader = BufReader::new(&stream);\n\n let writer = BufWriter::new(&stream);\n\n let mut conn = Conn::new(writer);\n\n\n\n for value in deserialize_from_reader(reader) {\n\n self.handle_request(&mut conn, Request::try_from(value?)?)?;\n", "file_path": "src/server.rs", "rank": 64, "score": 19880.707328668926 }, { "content": " pub fn max_value_size(&mut self, value: u64) -> &mut Self {\n\n self.config.max_value_size = value;\n\n self\n\n }\n\n\n\n #[allow(dead_code)]\n\n pub fn sync(&mut self, value: bool) -> &mut Self {\n\n self.config.sync = value;\n\n self\n\n }\n\n\n\n #[allow(dead_code)]\n\n pub fn open<P: AsRef<Path>>(&self, path: P) -> Result<Store> {\n\n Store::open_with_options(path, self.config)\n\n }\n\n}\n", "file_path": "src/store.rs", "rank": 65, "score": 19880.550316789795 }, { "content": " fn write(&mut self, value: &[u8]) -> Result<()> {\n\n self.writer.write_all(value)?;\n\n Ok(())\n\n }\n\n}\n\n\n\n#[cfg(test)]\n\nmod tests {\n\n use super::*;\n\n use std::io::Cursor;\n\n\n\n fn parse_value(value: &str) -> Result<Option<Value>> {\n\n let reader = Cursor::new(value.as_bytes());\n\n let mut de = Deserializer::from_reader(reader);\n\n let v = de.next()?;\n\n Ok(v)\n\n }\n\n\n\n #[test]\n\n fn test_parse_length() {\n", "file_path": "src/resp.rs", "rank": 66, "score": 19879.637607628723 }, { "content": " keys.push(key.clone());\n\n }\n\n\n\n for key in keys.iter() {\n\n self.store\n\n .remove(key.as_ref())\n\n .map_err(|e| TinkvError::new_resp_common(\"INTERNALERR\", &format!(\"{}\", e)))?;\n\n }\n\n\n\n Ok(Value::new_simple_string(\"OK\"))\n\n }\n\n\n\n fn handle_compact(&mut self, argv: &[&[u8]]) -> Result<Value> {\n\n if !argv.is_empty() {\n\n return Err(TinkvError::resp_wrong_num_of_args(\"compact\"));\n\n }\n\n\n\n match self.store.compact() {\n\n Ok(_) => Ok(Value::new_simple_string(\"OK\")),\n\n Err(e) => Err(TinkvError::new_resp_common(\n", "file_path": "src/server.rs", "rank": 67, "score": 19878.99578204447 }, { "content": "pub const REMOVE_TOMESTONE: &[u8] = b\"%TINKV_REMOVE_TOMESTOME%\";\n\npub const DATA_FILE_SUFFIX: &str = \".tinkv.data\";\n\npub const HINT_FILE_SUFFIX: &str = \".tinkv.hint\";\n\npub const DEFAULT_MAX_DATA_FILE_SIZE: u64 = 1024 * 1024 * 10; // 10MB\n\npub const DEFAULT_MAX_KEY_SIZE: u64 = 64;\n\npub const DEFAULT_MAX_VALUE_SIZE: u64 = 65536;\n", "file_path": "src/config.rs", "rank": 68, "score": 19878.643997546264 }, { "content": " /// Return total number of keys in datastore.\n\n pub fn len(&self) -> u64 {\n\n self.keydir.len() as u64\n\n }\n\n\n\n /// Check datastore is empty or not.\n\n pub fn is_empty(&self) -> bool {\n\n self.len() == 0\n\n }\n\n\n\n /// Return `true` if datastore contains the given key.\n\n pub fn contains_key(&self, key: &[u8]) -> bool {\n\n self.keydir.contains_key(key)\n\n }\n\n\n\n /// Iterate all keys in datastore and call function `f`\n\n /// for each entry.\n\n ///\n\n /// If function `f` returns an `Err`, it stops iteration\n\n /// and propgates the `Err` to the caller.\n", "file_path": "src/store.rs", "rank": 69, "score": 19877.872185909328 }, { "content": "\n\nimpl Drop for Store {\n\n fn drop(&mut self) {\n\n // ignore sync errors.\n\n trace!(\"sync all pending writes to disk.\");\n\n let _r = self.sync();\n\n }\n\n}\n\n\n\n/// Entry definition in the keydir (the in-memory index).\n\n#[derive(Debug, Clone, Copy)]\n", "file_path": "src/store.rs", "rank": 70, "score": 19877.77344159265 }, { "content": " }\n\n }\n\n }\n\n Ok(())\n\n }\n\n\n\n /// Force flushing any pending writes to disk.\n\n pub fn sync(&mut self) -> Result<()> {\n\n if self.active_data_file.is_some() {\n\n self.active_data_file.as_mut().unwrap().sync()?;\n\n }\n\n Ok(())\n\n }\n\n\n\n /// Close a tinkv data store, flush all pending writes to disk.\n\n pub fn close(&mut self) -> Result<()> {\n\n self.sync()?;\n\n Ok(())\n\n }\n\n}\n", "file_path": "src/store.rs", "rank": 71, "score": 19877.75704810742 }, { "content": " }\n\n\n\n debug!(\"connection disconnected from {}\", &peer_addr);\n\n\n\n Ok(())\n\n }\n\n\n\n fn handle_request<W: Write>(&mut self, conn: &mut Conn<W>, req: Request) -> Result<()> {\n\n trace!(\"handle {}\", &req);\n\n let argv = req.argv();\n\n\n\n macro_rules! send {\n\n () => {\n\n conn.write_value(Value::new_null_bulk_string())?\n\n };\n\n ($value:expr) => {\n\n match $value {\n\n Err(TinkvError::RespCommon { name, msg }) => {\n\n let err = Value::new_error(&name, &msg);\n\n conn.write_value(err)?;\n", "file_path": "src/server.rs", "rank": 72, "score": 19877.08343184787 }, { "content": "\n\n pub fn serialize_simple_string(&mut self, value: &str) -> Result<()> {\n\n self.write(WRITE_SIMPLE_STR_PREFIX)?;\n\n self.write(value.as_bytes())?;\n\n self.end()\n\n }\n\n\n\n pub fn serialize_error(&mut self, name: &str, msg: &str) -> Result<()> {\n\n self.write(WRITE_ERROR_PREFIX)?;\n\n if name == \"\" {\n\n self.write(b\"ERR\")?;\n\n } else {\n\n self.write(name.as_bytes())?;\n\n }\n\n self.write(b\" \")?;\n\n self.write(msg.as_bytes())?;\n\n self.end()\n\n }\n\n\n\n pub fn serialize_integer(&mut self, value: i64) -> Result<()> {\n", "file_path": "src/resp.rs", "rank": 73, "score": 19876.695966942323 }, { "content": "//! TinKV server is a redis-compatible key value server.\n\n\n\nuse crate::error::{Result, TinkvError};\n\n\n\nuse crate::store::Store;\n\n\n\nuse crate::resp::{deserialize_from_reader, serialize_to_writer, Value};\n\nuse lazy_static::lazy_static;\n\nuse log::{debug, error, info, trace};\n\n\n\nuse crate::util::to_utf8_string;\n\nuse std::convert::TryFrom;\n\nuse std::fmt;\n\nuse std::io::prelude::*;\n\nuse std::io::{BufReader, BufWriter};\n\nuse std::net::{TcpListener, TcpStream, ToSocketAddrs};\n\n\n\nlazy_static! {\n\n static ref COMMANDS: Vec<&'static str> = vec![\n\n \"ping\", \"get\", \"mget\", \"set\", \"mset\", \"del\", \"dbsize\", \"exists\", \"keys\", \"flushdb\",\n", "file_path": "src/server.rs", "rank": 74, "score": 19876.665820721908 }, { "content": " match self.store.remove(argv[0]) {\n\n Ok(()) => Ok(Value::new_simple_string(\"OK\")),\n\n Err(e) => Err(TinkvError::new_resp_common(\n\n \"INTERNALERR\",\n\n &format!(\"{}\", e),\n\n )),\n\n }\n\n }\n\n\n\n fn handle_dbsize(&mut self, argv: &[&[u8]]) -> Result<Value> {\n\n if !argv.is_empty() {\n\n return Err(TinkvError::resp_wrong_num_of_args(\"dbsize\"));\n\n }\n\n\n\n Ok(Value::new_integer(self.store.len() as i64))\n\n }\n\n\n\n fn handle_exists(&mut self, argv: &[&[u8]]) -> Result<Value> {\n\n if argv.is_empty() {\n\n return Err(TinkvError::resp_wrong_num_of_args(\"exists\"));\n", "file_path": "src/server.rs", "rank": 75, "score": 19876.630833623414 }, { "content": "pub struct Stats {\n\n /// size (bytes) of stale entries in data files, which can be\n\n /// deleted after a compaction.\n\n pub size_of_stale_entries: u64,\n\n /// total stale entries in data files.\n\n pub total_stale_entries: u64,\n\n /// total active key value pairs in database.\n\n pub total_active_entries: u64,\n\n /// total data files.\n\n pub total_data_files: u64,\n\n /// total size (bytes) of all data files.\n\n pub size_of_all_data_files: u64,\n\n}\n\n\n", "file_path": "src/store.rs", "rank": 76, "score": 19876.381076915717 }, { "content": "//! Implementation of serializer & deserializer of REdis Serialization Protocol (RESP).\n\n//! Ref: https://redis.io/topics/protocol\n\nuse crate::error::{Result, TinkvError};\n\nuse crate::util::ByteLineReader;\n\nuse std::fmt;\n\nuse std::io::{BufRead, Cursor, Write};\n\n\n\nmacro_rules! repr {\n\n ($bs:expr) => {\n\n format!(\"{}\", String::from_utf8_lossy($bs))\n\n };\n\n}\n\n\n\n/// Value type depends on the first byte.\n\nconst SIMPLE_STR_PREFIX: u8 = b'+';\n\nconst ERROR_PREFIX: u8 = b'-';\n\nconst INTEGER_PREFIX: u8 = b':';\n\nconst BULK_STR_PREFIX: u8 = b'$';\n\nconst ARRAY_PREFIX: u8 = b'*';\n\nconst CR: u8 = b'\\r';\n", "file_path": "src/resp.rs", "rank": 77, "score": 19876.378485347956 }, { "content": " Self { writer }\n\n }\n\n\n\n #[inline]\n\n #[allow(dead_code)]\n\n pub fn into_inner(self) -> W {\n\n self.writer\n\n }\n\n\n\n pub fn serialize(&mut self, value: &Value) -> Result<()> {\n\n match value {\n\n Value::SimpleString(s) => self.serialize_simple_string(s.as_ref()),\n\n Value::Integer(i) => self.serialize_integer(i.to_owned()),\n\n Value::Error { name, msg } => self.serialize_error(&name, &msg),\n\n Value::BulkString(s) => self.serialize_bulk_string(s.as_ref()),\n\n Value::Array(v) => self.serialize_array(v.as_ref()),\n\n Value::NullArray => self.serialize_null_array(),\n\n Value::NullBulkString => self.serialize_null_bulk_string(),\n\n }\n\n }\n", "file_path": "src/resp.rs", "rank": 78, "score": 19876.04088765468 }, { "content": " match self.next_line()? {\n\n None => Ok(None),\n\n Some(line) => {\n\n if line.is_empty() {\n\n Ok(None)\n\n } else {\n\n Ok(Some(self.next_value(&line)?))\n\n }\n\n }\n\n }\n\n }\n\n\n\n fn next_line(&mut self) -> Result<Option<Vec<u8>>> {\n\n match self.inner.next_line() {\n\n None => Ok(None),\n\n Some(Err(e)) => Err(e.into()),\n\n // TODO: optimize later, avoid copying\n\n Some(Ok(v)) => Ok(Some(v.to_vec())),\n\n }\n\n }\n", "file_path": "src/resp.rs", "rank": 79, "score": 19875.626381362858 }, { "content": " \"there are {} data files need to be compacted\",\n\n self.data_files.len()\n\n );\n\n\n\n let next_file_id = self.next_file_id();\n\n\n\n // switch to another active data file.\n\n self.new_active_data_file(Some(next_file_id + 1))?;\n\n let mut compaction_data_file_id = next_file_id + 2;\n\n\n\n // create a new data file for compaction.\n\n let data_file_path = segment_data_file_path(&self.path, compaction_data_file_id);\n\n\n\n debug!(\"create compaction data file: {}\", data_file_path.display());\n\n let mut compaction_df = DataFile::new(&data_file_path, true)?;\n\n\n\n // register read-only compaction data file.\n\n self.data_files\n\n .insert(compaction_df.id, DataFile::new(&compaction_df.path, false)?);\n\n\n", "file_path": "src/store.rs", "rank": 80, "score": 19875.215270252414 }, { "content": " // fallback to the original data file to rebuild keydir.\n\n let mut file_ids = self.data_files.keys().cloned().collect::<Vec<_>>();\n\n file_ids.sort();\n\n\n\n for file_id in file_ids {\n\n let hint_file_path = segment_hint_file_path(&self.path, file_id);\n\n if hint_file_path.exists() {\n\n self.build_keydir_from_hint_file(&hint_file_path)?;\n\n } else {\n\n self.build_keydir_from_data_file(file_id)?;\n\n }\n\n }\n\n\n\n // update stats.\n\n self.stats.total_active_entries = self.keydir.len() as u64;\n\n\n\n let duration = time::Instant::now().duration_since(begin_at);\n\n\n\n info!(\n\n \"build keydir in {:?}, got {} keys. current stats: {:?}\",\n", "file_path": "src/store.rs", "rank": 81, "score": 19874.622858718812 }, { "content": " self.write(WRITE_INTEGER_PREFIX)?;\n\n self.write(value.to_string().as_bytes())?;\n\n self.end()\n\n }\n\n\n\n pub fn serialize_bulk_string(&mut self, value: &[u8]) -> Result<()> {\n\n self.write(WRITE_BULK_STR_PREFIX)?;\n\n self.write(value.len().to_string().as_bytes())?;\n\n self.write(WRITE_CRLF_SUFFIX)?;\n\n self.write(value)?;\n\n self.end()\n\n }\n\n\n\n pub fn serialize_array(&mut self, value: &[Value]) -> Result<()> {\n\n self.write(WRITE_ARRAY_PREFIX)?;\n\n self.write(value.len().to_string().as_bytes())?;\n\n self.write(WRITE_CRLF_SUFFIX)?;\n\n for elem in value.iter() {\n\n self.serialize(elem)?;\n\n }\n", "file_path": "src/resp.rs", "rank": 82, "score": 19874.352213190563 }, { "content": " let data_file_path = segment_data_file_path(&self.path, compaction_data_file_id);\n\n debug!(\n\n \"file size exceeds limit, switch to another compaction data file: {}\",\n\n data_file_path.display()\n\n );\n\n compaction_df = DataFile::new(&data_file_path, true)?;\n\n\n\n self.data_files\n\n .insert(compaction_df.id, DataFile::new(&compaction_df.path, false)?);\n\n\n\n let hint_file_path = segment_hint_file_path(&self.path, compaction_data_file_id);\n\n debug!(\n\n \"switch to another compaction hint file: {}\",\n\n hint_file_path.display()\n\n );\n\n hint_file = HintFile::new(&hint_file_path, true)?;\n\n }\n\n\n\n let df = self\n\n .data_files\n", "file_path": "src/store.rs", "rank": 83, "score": 19873.949566473664 }, { "content": " max_key_size: config::DEFAULT_MAX_KEY_SIZE,\n\n max_value_size: config::DEFAULT_MAX_VALUE_SIZE,\n\n sync: false,\n\n }\n\n }\n\n}\n\n\n\n/// Build custom open options.\n\n#[derive(Debug)]\n\npub struct OpenOptions {\n\n config: Config,\n\n}\n\n\n\nimpl Default for OpenOptions {\n\n fn default() -> Self {\n\n Self {\n\n config: Config::default(),\n\n }\n\n }\n\n}\n", "file_path": "src/store.rs", "rank": 84, "score": 19873.243417642876 }, { "content": " stale_segment_count += 1;\n\n }\n\n }\n\n\n\n self.data_files.retain(|&k, _| k > next_file_id);\n\n debug!(\"cleaned {} stale segments\", stale_segment_count);\n\n\n\n info!(\n\n \"compaction progress done in {:?}\",\n\n time::Instant::now().duration_since(begin_at)\n\n );\n\n\n\n // update stats.\n\n self.stats.total_data_files = self.data_files.len() as u64;\n\n self.stats.total_active_entries = self.keydir.len() as u64;\n\n self.stats.total_stale_entries = 0;\n\n self.stats.size_of_stale_entries = 0;\n\n self.stats.size_of_all_data_files = total_size_of_compaction_files;\n\n\n\n Ok(())\n", "file_path": "src/store.rs", "rank": 85, "score": 19873.23789402004 }, { "content": " for arg in self.raw_argv.iter() {\n\n argv_str.push(format!(\"{}\", arg));\n\n }\n\n\n\n write!(\n\n f,\n\n \"Request(name=\\\"{}\\\", argc={}, argv={:?})\",\n\n &self.name,\n\n argv_str.len(),\n\n argv_str\n\n )\n\n }\n\n}\n\n\n\nimpl TryFrom<Value> for Request {\n\n type Error = TinkvError;\n\n\n\n fn try_from(value: Value) -> std::result::Result<Self, Self::Error> {\n\n match value {\n\n Value::Array(mut v) => {\n", "file_path": "src/server.rs", "rank": 86, "score": 19873.174605164462 }, { "content": "\n\n let pattern = pattern.map_err(|e| TinkvError::new_resp_common(\"ERR\", &format!(\"{}\", e)))?;\n\n for key in self.store.keys() {\n\n if pattern.matches(to_utf8_string(key).as_ref()) {\n\n keys.push(Value::new_bulk_string(key.to_vec()));\n\n };\n\n }\n\n\n\n Ok(Value::new_array(keys))\n\n }\n\n\n\n fn handle_flush(&mut self, cmd: &str, argv: &[&[u8]]) -> Result<Value> {\n\n if !argv.is_empty() {\n\n return Err(TinkvError::resp_wrong_num_of_args(cmd));\n\n }\n\n\n\n // too stupid, just in order to pass borrow checking.\n\n // FIXME: find a better way to implement this feature?\n\n let mut keys = vec![];\n\n for key in self.store.keys() {\n", "file_path": "src/server.rs", "rank": 87, "score": 19872.695242265596 }, { "content": " Ok(())\n\n }\n\n\n\n pub fn serialize_null_bulk_string(&mut self) -> Result<()> {\n\n self.write(WRITE_BULK_STR_PREFIX)?;\n\n self.write(b\"-1\")?;\n\n self.end()\n\n }\n\n\n\n pub fn serialize_null_array(&mut self) -> Result<()> {\n\n self.write(WRITE_ARRAY_PREFIX)?;\n\n self.write(b\"-1\")?;\n\n self.end()\n\n }\n\n\n\n fn end(&mut self) -> Result<()> {\n\n self.write(WRITE_CRLF_SUFFIX)?;\n\n Ok(())\n\n }\n\n\n", "file_path": "src/resp.rs", "rank": 88, "score": 19872.00551306788 }, { "content": " name = s[..idx].into();\n\n msg = s[idx + 1..].into();\n\n } else {\n\n msg = s\n\n }\n\n Value::Error { name, msg }\n\n }\n\n\n\n fn integer_from_slice(value: &[u8]) -> Result<Value> {\n\n let s = String::from_utf8_lossy(value).to_string();\n\n let v = s.parse::<i64>()?;\n\n Ok(Value::Integer(v))\n\n }\n\n\n\n fn bulk_string_from_slice<B: BufRead>(length: i64, reader: &mut B) -> Result<Value> {\n\n if length == -1 {\n\n return Ok(Value::NullBulkString);\n\n }\n\n\n\n let mut buf = vec![0u8; length as usize + 2]; // extra 2 bytes for `\\r\\n`\n", "file_path": "src/resp.rs", "rank": 89, "score": 19871.791738271193 }, { "content": " fn open_with_options<P: AsRef<Path>>(path: P, config: Config) -> Result<Self> {\n\n info!(\"open store path: {}\", path.as_ref().display());\n\n create_dir_all(&path)?;\n\n let mut store = Store {\n\n path: path.as_ref().to_path_buf(),\n\n data_files: HashMap::new(),\n\n active_data_file: None,\n\n keydir: BTreeMap::new(),\n\n stats: Stats::default(),\n\n config,\n\n };\n\n\n\n store.open_data_files()?;\n\n store.build_keydir()?;\n\n store.new_active_data_file(None)?;\n\n\n\n Ok(store)\n\n }\n\n\n\n /// Open data files (they are immutable).\n", "file_path": "src/store.rs", "rank": 90, "score": 19871.74414427614 }, { "content": " if v.is_empty() {\n\n return Err(TinkvError::ParseRespValue);\n\n }\n\n let name = to_utf8_string(v.remove(0).as_bulk_string().unwrap());\n\n Ok(Self {\n\n name: name.to_ascii_lowercase(),\n\n raw_argv: v,\n\n })\n\n }\n\n _ => Err(TinkvError::ParseRespValue),\n\n }\n\n }\n\n}\n\n\n", "file_path": "src/server.rs", "rank": 91, "score": 19871.345677156118 }, { "content": "const LF: u8 = b'\\n';\n\n\n\n/// For writes\n\nconst WRITE_SIMPLE_STR_PREFIX: &[u8] = b\"+\";\n\nconst WRITE_ERROR_PREFIX: &[u8] = b\"-\";\n\nconst WRITE_INTEGER_PREFIX: &[u8] = b\":\";\n\nconst WRITE_BULK_STR_PREFIX: &[u8] = b\"$\";\n\nconst WRITE_ARRAY_PREFIX: &[u8] = b\"*\";\n\nconst WRITE_CRLF_SUFFIX: &[u8] = b\"\\r\\n\";\n\n\n\n/// Generic RESP error.\n\npub(crate) struct Error<'s> {\n\n name: &'s str,\n\n msg: &'s str,\n\n}\n\n\n\nimpl<'s> Error<'s> {\n\n pub fn new(name: &'s str, msg: &'s str) -> Self {\n\n Self { name, msg }\n\n }\n", "file_path": "src/resp.rs", "rank": 92, "score": 19870.7185472018 }, { "content": " if argv.is_empty() {\n\n return Err(TinkvError::resp_wrong_num_of_args(\"mget\"));\n\n }\n\n\n\n let mut values = vec![];\n\n for arg in argv {\n\n let value = self\n\n .store\n\n .get(arg)?\n\n .map(Value::new_bulk_string)\n\n .unwrap_or_else(Value::new_null_bulk_string);\n\n values.push(value);\n\n }\n\n\n\n Ok(Value::new_array(values))\n\n }\n\n\n\n fn handle_set(&mut self, argv: &[&[u8]]) -> Result<Value> {\n\n if argv.len() < 2 {\n\n return Err(TinkvError::resp_wrong_num_of_args(\"set\"));\n", "file_path": "src/server.rs", "rank": 93, "score": 19870.714490138333 }, { "content": " }\n\n\n\n match self.store.set(argv[0], argv[1]) {\n\n Ok(()) => Ok(Value::new_simple_string(\"OK\")),\n\n Err(e) => Err(TinkvError::new_resp_common(\n\n \"INTERNALERR\",\n\n &format!(\"{}\", e),\n\n )),\n\n }\n\n }\n\n\n\n fn handle_mset(&mut self, argv: &[&[u8]]) -> Result<Value> {\n\n if argv.len() % 2 != 0 {\n\n return Err(TinkvError::resp_wrong_num_of_args(\"mset\"));\n\n }\n\n\n\n let mut i = 0;\n\n loop {\n\n if i + 1 >= argv.len() {\n\n break;\n", "file_path": "src/server.rs", "rank": 94, "score": 19870.678020981184 }, { "content": " }\n\n\n\n let mut exists = 0;\n\n for arg in argv {\n\n if self.store.contains_key(arg) {\n\n exists += 1;\n\n }\n\n }\n\n\n\n Ok(Value::new_integer(exists as i64))\n\n }\n\n\n\n fn handle_keys(&mut self, argv: &[&[u8]]) -> Result<Value> {\n\n let pattern = match argv.len() {\n\n 0 => glob::Pattern::new(\"*\"),\n\n 1 => glob::Pattern::new(to_utf8_string(argv[0]).as_ref()),\n\n _ => return Err(TinkvError::resp_wrong_num_of_args(\"exists\")),\n\n };\n\n\n\n let mut keys = vec![];\n", "file_path": "src/server.rs", "rank": 95, "score": 19870.58764835991 }, { "content": " }\n\n\n\n if let Err(e) = self.store.set(argv[i], argv[i + 1]) {\n\n return Err(TinkvError::new_resp_common(\n\n \"INTERNALERR\",\n\n &format!(\"{}\", e),\n\n ));\n\n }\n\n\n\n i += 2;\n\n }\n\n\n\n Ok(Value::new_simple_string(\"OK\"))\n\n }\n\n\n\n fn handle_del(&mut self, argv: &[&[u8]]) -> Result<Value> {\n\n if argv.len() != 1 {\n\n return Err(TinkvError::resp_wrong_num_of_args(\"del\"));\n\n }\n\n\n", "file_path": "src/server.rs", "rank": 96, "score": 19870.507336866554 }, { "content": " match argv.len() {\n\n 0 => Ok(Value::new_simple_string(\"PONG\")),\n\n 1 => Ok(Value::new_bulk_string(argv[0].to_vec())),\n\n _ => Err(TinkvError::resp_wrong_num_of_args(\"ping\")),\n\n }\n\n }\n\n\n\n fn handle_get(&mut self, argv: &[&[u8]]) -> Result<Value> {\n\n if argv.len() != 1 {\n\n return Err(TinkvError::resp_wrong_num_of_args(\"get\"));\n\n }\n\n\n\n Ok(self\n\n .store\n\n .get(argv[0])?\n\n .map(Value::new_bulk_string)\n\n .unwrap_or_else(Value::new_null_bulk_string))\n\n }\n\n\n\n fn handle_mget(&mut self, argv: &[&[u8]]) -> Result<Value> {\n", "file_path": "src/server.rs", "rank": 97, "score": 19870.44108532759 }, { "content": " \"exists\" => send!(self.handle_exists(&argv)),\n\n \"keys\" => send!(self.handle_keys(&argv)),\n\n \"flushall\" | \"flushdb\" => send!(self.handle_flush(req.name.as_ref(), &argv)),\n\n \"compact\" => send!(self.handle_compact(&argv)),\n\n \"info\" => send!(self.handle_info(&argv)),\n\n \"command\" => send!(self.handle_command(&argv)),\n\n _ => {\n\n conn.write_value(Value::new_error(\n\n \"ERR\",\n\n &format!(\"unknown command `{}`\", &req.name),\n\n ))?;\n\n }\n\n }\n\n\n\n conn.flush()?;\n\n\n\n Ok(())\n\n }\n\n\n\n fn handle_ping(&mut self, argv: &[&[u8]]) -> Result<Value> {\n", "file_path": "src/server.rs", "rank": 98, "score": 19870.144369378875 }, { "content": " fn test_invalid_array() {\n\n let r = parse_value(\"*3\\r\\n:1\\r\\n\");\n\n assert!(r.is_err());\n\n let r = parse_value(\"*3\\r\\n:1\\n\");\n\n assert!(r.is_err());\n\n }\n\n\n\n #[test]\n\n fn test_deserialize_from_slice() {\n\n let values: Vec<Result<Value>> =\n\n deserialize_from_slice(b\"+OK\\r\\n:100\\r\\n$5\\r\\nhello\\r\\n\").collect();\n\n assert_eq!(values.len(), 3);\n\n\n\n let mut it = values.into_iter();\n\n assert_eq!(\n\n it.next().unwrap().unwrap().as_simple_string().unwrap(),\n\n \"OK\"\n\n );\n\n assert_eq!(it.next().unwrap().unwrap().as_integer().unwrap(), 100);\n\n assert_eq!(\n", "file_path": "src/resp.rs", "rank": 99, "score": 19869.528985686225 } ]
Rust
artichoke-backend/src/extn/core/random/mruby.rs
Talljoe/artichoke
36ed5eba078a9fbf3cb4d5c8f7407d0a773d2d6e
use crate::extn::core::random::{self, trampoline}; use crate::extn::prelude::*; pub fn init(interp: &mut Artichoke) -> InitializeResult<()> { if interp.is_class_defined::<random::Random>() { return Ok(()); } let spec = class::Spec::new("Random", None, Some(def::box_unbox_free::<random::Random>))?; class::Builder::for_spec(interp, &spec) .value_is_rust_object() .add_self_method( "new_seed", artichoke_random_self_new_seed, sys::mrb_args_req(1), )? .add_self_method("srand", artichoke_random_self_srand, sys::mrb_args_opt(1))? .add_self_method( "urandom", artichoke_random_self_urandom, sys::mrb_args_req(1), )? .add_method( "initialize", artichoke_random_initialize, sys::mrb_args_opt(1), )? .add_method("==", artichoke_random_eq, sys::mrb_args_opt(1))? .add_method("bytes", artichoke_random_bytes, sys::mrb_args_req(1))? .add_method("rand", artichoke_random_rand, sys::mrb_args_opt(1))? .add_method("seed", artichoke_random_seed, sys::mrb_args_none())? .define()?; interp.def_class::<random::Random>(spec)?; let default = random::Random::interpreter_prng_delegate(); let default = random::Random::alloc_value(default, interp) .map_err(|_| NotDefinedError::class_constant("Random::DEFAULT"))?; interp.define_class_constant::<random::Random>("DEFAULT", default)?; let _ = interp.eval(&include_bytes!("random.rb")[..])?; trace!("Patched Random onto interpreter"); Ok(()) } #[no_mangle] unsafe extern "C" fn artichoke_random_initialize( mrb: *mut sys::mrb_state, slf: sys::mrb_value, ) -> sys::mrb_value { let seed = mrb_get_args!(mrb, optional = 1); let mut interp = unwrap_interpreter!(mrb); let mut guard = Guard::new(&mut interp); let slf = Value::from(slf); let seed = seed.map(Value::from); let result = trampoline::initialize(&mut guard, seed, slf); match result { Ok(value) => value.inner(), Err(exception) => exception::raise(guard, exception), } } #[no_mangle] unsafe extern "C" fn artichoke_random_eq( mrb: *mut sys::mrb_state, slf: sys::mrb_value, ) -> sys::mrb_value { let other = mrb_get_args!(mrb, required = 1); let mut interp = unwrap_interpreter!(mrb); let mut guard = Guard::new(&mut interp); let rand = Value::from(slf); let other = Value::from(other); let result = trampoline::equal(&mut guard, rand, other); match result { Ok(value) => value.inner(), Err(exception) => exception::raise(guard, exception), } } #[no_mangle] unsafe extern "C" fn artichoke_random_bytes( mrb: *mut sys::mrb_state, slf: sys::mrb_value, ) -> sys::mrb_value { let size = mrb_get_args!(mrb, required = 1); let mut interp = unwrap_interpreter!(mrb); let mut guard = Guard::new(&mut interp); let rand = Value::from(slf); let size = Value::from(size); let result = trampoline::bytes(&mut guard, rand, size); match result { Ok(value) => value.inner(), Err(exception) => exception::raise(guard, exception), } } #[no_mangle] unsafe extern "C" fn artichoke_random_rand( mrb: *mut sys::mrb_state, slf: sys::mrb_value, ) -> sys::mrb_value { let max = mrb_get_args!(mrb, optional = 1); let mut interp = unwrap_interpreter!(mrb); let mut guard = Guard::new(&mut interp); let rand = Value::from(slf); let max = max.map(Value::from); let result = trampoline::rand(&mut guard, rand, max); match result { Ok(value) => value.inner(), Err(exception) => exception::raise(guard, exception), } } #[no_mangle] unsafe extern "C" fn artichoke_random_seed( mrb: *mut sys::mrb_state, slf: sys::mrb_value, ) -> sys::mrb_value { mrb_get_args!(mrb, none); let mut interp = unwrap_interpreter!(mrb); let mut guard = Guard::new(&mut interp); let rand = Value::from(slf); let result = trampoline::seed(&mut guard, rand); match result { Ok(value) => value.inner(), Err(exception) => exception::raise(guard, exception), } } #[no_mangle] unsafe extern "C" fn artichoke_random_self_new_seed( mrb: *mut sys::mrb_state, _slf: sys::mrb_value, ) -> sys::mrb_value { mrb_get_args!(mrb, none); let mut interp = unwrap_interpreter!(mrb); let mut guard = Guard::new(&mut interp); let result = trampoline::new_seed(&mut guard); match result { Ok(value) => value.inner(), Err(exception) => exception::raise(guard, exception), } } #[no_mangle] unsafe extern "C" fn artichoke_random_self_srand( mrb: *mut sys::mrb_state, _slf: sys::mrb_value, ) -> sys::mrb_value { let number = mrb_get_args!(mrb, optional = 1); let mut interp = unwrap_interpreter!(mrb); let mut guard = Guard::new(&mut interp); let number = number.map(Value::from); let result = trampoline::srand(&mut guard, number); match result { Ok(value) => value.inner(), Err(exception) => exception::raise(guard, exception), } } #[no_mangle] unsafe extern "C" fn artichoke_random_self_urandom( mrb: *mut sys::mrb_state, _slf: sys::mrb_value, ) -> sys::mrb_value { let size = mrb_get_args!(mrb, required = 1); let mut interp = unwrap_interpreter!(mrb); let mut guard = Guard::new(&mut interp); let size = Value::from(size); let result = trampoline::urandom(&mut guard, size); match result { Ok(value) => value.inner(), Err(exception) => exception::raise(guard, exception), } }
use crate::extn::core::random::{self, trampoline}; use crate::extn::prelude::*; pub fn init(interp: &mut Artichoke) -> InitializeResult<()> { if interp.is_class_defined::<random::Random>() { return Ok(()); } let spec = class::Spec::new("Random", None, Some(def::box_unbox_free::<random::Random>))?; class::Builder::for_spec(interp, &spec) .value_is_rust_object() .add_self_method( "new_seed", artichoke_random_self_new_seed, sys::mrb_args_req(1), )? .add_self_method("srand", artichoke_random_self_srand, sys::mrb_args_opt(1))? .add_self_method( "urandom", artichoke_random_self_urandom, sys::mrb_args_req(1), )? .add_method( "initialize", artichoke_random_initialize, sys::mrb_args_opt(1), )? .add_method("==", artichoke_random_eq, sys::mrb_args_opt(1))? .add_method("bytes", artichoke_random_bytes, sys::mrb_args_req(1))? .add_method("rand", artichoke_random_rand, sys::mrb_args_opt(1))? .add_method("seed", artichoke_random_seed, sys::mrb_args_none())? .define()?; interp.def_class::<random::Random>(spec)?; let default = random::Random::interpreter_prng_delegate(); let default = random::Random::alloc_value(default, interp) .map_err(|_| NotDefinedError::class_constant("Random::DEFAULT"))?; interp.define_class_constant::<random::Random>("DEFAULT", default)?; let _ = interp.eval(&include_bytes!("random.rb")[..])?; trace!("Patched Random onto interpreter"); Ok(()) } #[no_mangle] unsafe extern "C" fn artichoke_random_initialize( mrb: *mut sys::mrb_state, slf: sys::mrb_value, ) -> sys::mrb_value { let seed = mrb_get_args!(mrb, optional = 1); let mut interp = unwrap_interpreter!(mrb); let mut guard = Guard::new(&mut interp); let slf = Value::from(slf); let seed = seed.map(Value::from); let result = trampoline::initialize(&mut guard, seed, slf); match result { Ok(value) => value.inner(), Err(exception) => exception::raise(guard, exception), } } #[no_mangle] unsafe extern "C" fn artichoke_random_eq( mrb: *mut sys::mrb_state, slf: sys::mrb_value, ) -> sys::mrb_value { let other = mrb_get_args!(mrb, required = 1); let mut interp = unwrap_interpreter!(mrb); let mut guard = Guard::new(&mut interp); let rand = Value::from(slf); let other = Value::from(other); let result = trampoline::equal(&mut guard, rand, other); match result { Ok(value) => value.inner(), Err(exception) => exception::raise(guard, exception), } } #[no_mangle] unsafe extern "C" fn artichoke_random_bytes( mrb: *mut sys::mrb_state, slf: sys::mrb_value, ) -> sys::mrb_value { let size = mrb_get_args!(mrb, required = 1); let mut interp = unwrap_interpreter!(mrb); let mut guard = Guard::new(&mut interp); let rand = Value::from(slf); let size = Value::from(size); let result = trampoline::bytes(&mut guard, rand, size); match result { Ok(value) => value.inner(), Err(exception) => exception::raise(guard, exception), } } #[no_mangle] unsafe extern "C" fn artichoke_random_rand( mrb: *mut sys::mrb_state, slf: sys::mrb_value, ) -> sys::mrb_value { let max = mrb_get_args!(mrb, optional = 1); let mut interp = unwrap_interpreter!(mrb); let mut guard = Guard::new(&mut interp); let rand = Value::from(slf); let max = max.map(Value::from); let result = trampoline::rand(&mut guard, rand, max); match result { Ok(value) => value.inner(), Err(exception) => exception::raise(guard, exception), } } #[no_mangle] unsafe extern "C" fn artichoke_random_seed( mrb: *mut sys::mrb_state, slf: sys::mrb_value, ) -> sys::mrb_value { mrb_get_args!(mrb, none); let mut interp = unwrap_interpreter!(mrb); let mut guard = Guard::new(&mut interp); let rand = Value::from(slf); let result = trampoline::seed(&mut guard, rand); match result { Ok(value) => value.inner(), Err(exception) => exception::raise(guard, exception), } } #[no_mangle] unsafe extern "C" fn artichoke_random_self_new_seed( mrb: *mut sys::mrb_state, _slf: sys::mrb_value, ) -> sys::mrb_value { mrb_get_args!(mrb, none); let mut interp = unwrap_interpreter!(mrb); let mut guard = Guard::new(&mut interp); let result = trampoline::new_seed(&mut guard); match result { Ok(value) => value.inner(), Err(exception) => exception::raise(guard, exception), } } #[no_mangle]
#[no_mangle] unsafe extern "C" fn artichoke_random_self_urandom( mrb: *mut sys::mrb_state, _slf: sys::mrb_value, ) -> sys::mrb_value { let size = mrb_get_args!(mrb, required = 1); let mut interp = unwrap_interpreter!(mrb); let mut guard = Guard::new(&mut interp); let size = Value::from(size); let result = trampoline::urandom(&mut guard, size); match result { Ok(value) => value.inner(), Err(exception) => exception::raise(guard, exception), } }
unsafe extern "C" fn artichoke_random_self_srand( mrb: *mut sys::mrb_state, _slf: sys::mrb_value, ) -> sys::mrb_value { let number = mrb_get_args!(mrb, optional = 1); let mut interp = unwrap_interpreter!(mrb); let mut guard = Guard::new(&mut interp); let number = number.map(Value::from); let result = trampoline::srand(&mut guard, number); match result { Ok(value) => value.inner(), Err(exception) => exception::raise(guard, exception), } }
function_block-full_function
[ { "content": "pub fn seed(interp: &mut Artichoke, mut rand: Value) -> Result<Value, Exception> {\n\n let rand = unsafe { Random::unbox_from_value(&mut rand, interp)? };\n\n let seed = rand.seed(interp)?;\n\n Ok(interp.convert(seed))\n\n}\n\n\n", "file_path": "artichoke-backend/src/extn/core/random/trampoline.rs", "rank": 0, "score": 616679.4482629988 }, { "content": "pub fn urandom(interp: &mut Artichoke, size: Value) -> Result<Value, Exception> {\n\n let size = size.implicitly_convert_to_int(interp)?;\n\n let buf = random::urandom(size)?;\n\n Ok(interp.convert_mut(buf))\n\n}\n", "file_path": "artichoke-backend/src/extn/core/random/trampoline.rs", "rank": 1, "score": 607452.5977258784 }, { "content": "pub fn srand(interp: &mut Artichoke, seed: Option<Value>) -> Result<Value, Exception> {\n\n let seed = interp.try_convert_mut(seed)?;\n\n let old_seed = random::srand(interp, seed)?;\n\n Ok(interp.convert(old_seed))\n\n}\n\n\n", "file_path": "artichoke-backend/src/extn/core/random/trampoline.rs", "rank": 2, "score": 592252.854743841 }, { "content": "pub fn bytes(interp: &mut Artichoke, mut rand: Value, size: Value) -> Result<Value, Exception> {\n\n let mut rand = unsafe { Random::unbox_from_value(&mut rand, interp)? };\n\n let size = size.implicitly_convert_to_int(interp)?;\n\n let buf = rand.bytes(interp, size)?;\n\n Ok(interp.convert_mut(buf))\n\n}\n\n\n", "file_path": "artichoke-backend/src/extn/core/random/trampoline.rs", "rank": 3, "score": 588885.1650669863 }, { "content": "#[inline]\n\npub fn random_number(interp: &mut Artichoke, max: Option<Value>) -> Result<Value, Exception> {\n\n let max = interp.try_convert_mut(max)?;\n\n let num = securerandom::random_number(max)?;\n\n Ok(interp.convert_mut(num))\n\n}\n\n\n", "file_path": "artichoke-backend/src/extn/stdlib/securerandom/trampoline.rs", "rank": 4, "score": 585295.3019420414 }, { "content": "pub fn new_seed(interp: &mut Artichoke) -> Result<Value, Exception> {\n\n let seed = Random::new_seed();\n\n Ok(interp.convert(seed))\n\n}\n\n\n", "file_path": "artichoke-backend/src/extn/core/random/trampoline.rs", "rank": 5, "score": 534924.7290321625 }, { "content": "pub fn equal(interp: &mut Artichoke, mut rand: Value, other: Value) -> Result<Value, Exception> {\n\n let rand = unsafe { Random::unbox_from_value(&mut rand, interp)? };\n\n let eql = rand.eql(interp, other)?;\n\n Ok(interp.convert(eql))\n\n}\n\n\n", "file_path": "artichoke-backend/src/extn/core/random/trampoline.rs", "rank": 6, "score": 533958.2650551713 }, { "content": "pub fn srand(interp: &mut Artichoke, seed: Seed) -> Result<Int, Exception> {\n\n let old_seed = interp.prng_seed()?;\n\n interp.prng_reseed(seed.to_reseed())?;\n\n #[allow(clippy::cast_possible_wrap)]\n\n Ok(old_seed as Int)\n\n}\n\n\n", "file_path": "artichoke-backend/src/extn/core/random/mod.rs", "rank": 7, "score": 526274.6059505544 }, { "content": "#[inline]\n\npub fn random_bytes(interp: &mut Artichoke, len: Option<Value>) -> Result<Value, Exception> {\n\n let bytes = if let Some(len) = len {\n\n let len = len.implicitly_convert_to_int(interp)?;\n\n securerandom::random_bytes(Some(len))?\n\n } else {\n\n securerandom::random_bytes(None)?\n\n };\n\n Ok(interp.convert_mut(bytes))\n\n}\n\n\n", "file_path": "artichoke-backend/src/extn/stdlib/securerandom/trampoline.rs", "rank": 8, "score": 521663.45189177315 }, { "content": "#[inline]\n\npub fn alphanumeric(interp: &mut Artichoke, len: Option<Value>) -> Result<Value, Exception> {\n\n let alpha = if let Some(len) = len {\n\n let len = len.implicitly_convert_to_int(interp)?;\n\n securerandom::alphanumeric(Some(len))?\n\n } else {\n\n securerandom::alphanumeric(None)?\n\n };\n\n Ok(interp.convert_mut(alpha))\n\n}\n\n\n", "file_path": "artichoke-backend/src/extn/stdlib/securerandom/trampoline.rs", "rank": 9, "score": 488716.6728017817 }, { "content": "#[inline]\n\npub fn hex(interp: &mut Artichoke, len: Option<Value>) -> Result<Value, Exception> {\n\n let hex = if let Some(len) = len {\n\n let len = len.implicitly_convert_to_int(interp)?;\n\n securerandom::hex(Some(len))?\n\n } else {\n\n securerandom::hex(None)?\n\n };\n\n Ok(interp.convert_mut(hex))\n\n}\n\n\n", "file_path": "artichoke-backend/src/extn/stdlib/securerandom/trampoline.rs", "rank": 10, "score": 488716.6728017817 }, { "content": "#[inline]\n\npub fn base64(interp: &mut Artichoke, len: Option<Value>) -> Result<Value, Exception> {\n\n let base64 = if let Some(len) = len {\n\n let len = len.implicitly_convert_to_int(interp)?;\n\n securerandom::base64(Some(len))?\n\n } else {\n\n securerandom::base64(None)?\n\n };\n\n Ok(interp.convert_mut(base64))\n\n}\n\n\n", "file_path": "artichoke-backend/src/extn/stdlib/securerandom/trampoline.rs", "rank": 11, "score": 488716.67280178174 }, { "content": "pub fn options(interp: &mut Artichoke, mut regexp: Value) -> Result<Value, Exception> {\n\n let regexp = unsafe { Regexp::unbox_from_value(&mut regexp, interp)? };\n\n let opts = regexp.options();\n\n Ok(interp.convert(opts))\n\n}\n\n\n", "file_path": "artichoke-backend/src/extn/core/regexp/trampoline.rs", "rank": 12, "score": 488110.2683557959 }, { "content": "/// Load ruby/spec sources into the Artichoke virtual filesystem.\n\n///\n\n/// # Errors\n\n///\n\n/// If an exception is raised on the Artichoke interpreter, it is returned.\n\npub fn init(interp: &mut Artichoke) -> Result<(), Exception> {\n\n for source in Specs::iter() {\n\n if let Some(content) = Specs::get(&source) {\n\n interp.def_rb_source_file(source.as_ref(), content)?;\n\n }\n\n }\n\n Ok(())\n\n}\n\n\n\n/// ruby/spec source code.\n\n#[derive(Debug, Clone, Copy, Hash, PartialEq, Eq, PartialOrd, Ord, RustEmbed)]\n\n#[folder = \"vendor/spec\"]\n\npub struct Specs;\n", "file_path": "spec-runner/src/rubyspec.rs", "rank": 13, "score": 483802.298514367 }, { "content": "/// Load `MSpec` sources into the Artichoke virtual filesystem.\n\n///\n\n/// # Errors\n\n///\n\n/// If an exception is raised on the Artichoke interpreter, it is returned.\n\npub fn init(interp: &mut Artichoke) -> Result<(), Exception> {\n\n for source in Sources::iter() {\n\n if let Some(content) = Sources::get(&source) {\n\n interp.def_rb_source_file(source.as_ref(), content)?;\n\n }\n\n }\n\n Ok(())\n\n}\n\n\n\n/// `MSpec` source code.\n\n#[derive(Debug, Clone, Copy, Hash, PartialEq, Eq, PartialOrd, Ord, RustEmbed)]\n\n#[folder = \"vendor/mspec/lib\"]\n\npub struct Sources;\n\n\n", "file_path": "spec-runner/src/mspec.rs", "rank": 14, "score": 483802.298514367 }, { "content": "pub fn post_match(interp: &mut Artichoke, mut value: Value) -> Result<Value, Exception> {\n\n let data = unsafe { MatchData::unbox_from_value(&mut value, interp)? };\n\n let post = data.post();\n\n Ok(interp.convert_mut(post))\n\n}\n\n\n", "file_path": "artichoke-backend/src/extn/core/matchdata/trampoline.rs", "rank": 15, "score": 482577.8486649936 }, { "content": "pub fn pre_match(interp: &mut Artichoke, mut value: Value) -> Result<Value, Exception> {\n\n let data = unsafe { MatchData::unbox_from_value(&mut value, interp)? };\n\n let pre = data.pre();\n\n Ok(interp.convert_mut(pre))\n\n}\n\n\n", "file_path": "artichoke-backend/src/extn/core/matchdata/trampoline.rs", "rank": 16, "score": 482577.84866499365 }, { "content": "pub fn init(interp: &mut Artichoke) -> InitializeResult<()> {\n\n let exception_spec = class::Spec::new(\"Exception\", None, None)?;\n\n class::Builder::for_spec(interp, &exception_spec).define()?;\n\n interp.def_class::<Exception>(exception_spec)?;\n\n\n\n let nomemory_spec = class::Spec::new(\"NoMemoryError\", None, None)?;\n\n class::Builder::for_spec(interp, &nomemory_spec)\n\n .with_super_class::<Exception, _>(\"Exception\")?\n\n .define()?;\n\n interp.def_class::<NoMemoryError>(nomemory_spec)?;\n\n\n\n let script_spec = class::Spec::new(\"ScriptError\", None, None)?;\n\n class::Builder::for_spec(interp, &script_spec)\n\n .with_super_class::<Exception, _>(\"Exception\")?\n\n .define()?;\n\n interp.def_class::<ScriptError>(script_spec)?;\n\n\n\n let load_spec = class::Spec::new(\"LoadError\", None, None)?;\n\n class::Builder::for_spec(interp, &load_spec)\n\n .with_super_class::<ScriptError, _>(\"ScriptError\")?\n", "file_path": "artichoke-backend/src/extn/core/exception/mod.rs", "rank": 18, "score": 481333.88414962596 }, { "content": "pub fn initialize(interp: &mut Artichoke, into: Value) -> Result<Value, Exception> {\n\n let environ = Environ::initialize();\n\n let result = Environ::box_into_value(environ, into, interp)?;\n\n Ok(result)\n\n}\n\n\n", "file_path": "artichoke-backend/src/extn/core/env/trampoline.rs", "rank": 19, "score": 481106.07825506094 }, { "content": "pub fn require(interp: &mut Artichoke, path: Value) -> Result<Value, Exception> {\n\n let success = kernel::require::require(interp, path, None)?;\n\n Ok(interp.convert(success))\n\n}\n\n\n", "file_path": "artichoke-backend/src/extn/core/kernel/trampoline.rs", "rank": 20, "score": 475232.23346086603 }, { "content": "pub fn size(interp: &Artichoke) -> Result<Value, Exception> {\n\n // This `as` cast is lossless because size_of::<Int> is guaranteed to be\n\n // less than `Int::MAX`.\n\n let size = Integer::size() as Int;\n\n Ok(interp.convert(size))\n\n}\n", "file_path": "artichoke-backend/src/extn/core/integer/trampoline.rs", "rank": 21, "score": 473332.0160519551 }, { "content": "pub fn require_relative(interp: &mut Artichoke, path: Value) -> Result<Value, Exception> {\n\n let relative_base = RelativePath::try_from_interp(interp)?;\n\n let success = kernel::require::require(interp, path, Some(relative_base))?;\n\n Ok(interp.convert(success))\n\n}\n", "file_path": "artichoke-backend/src/extn/core/kernel/trampoline.rs", "rank": 22, "score": 469438.17960499105 }, { "content": "pub fn all_symbols(interp: &mut Artichoke) -> Result<Value, Exception> {\n\n let all_symbols = Symbol::all_symbols(interp)?;\n\n Array::alloc_value(all_symbols, interp)\n\n}\n\n\n", "file_path": "artichoke-backend/src/extn/core/symbol/trampoline.rs", "rank": 23, "score": 459084.62001225934 }, { "content": "pub fn now(interp: &mut Artichoke) -> Result<Value, Exception> {\n\n let now = Time::now();\n\n let result = Time::alloc_value(now, interp)?;\n\n Ok(result)\n\n}\n\n\n", "file_path": "artichoke-backend/src/extn/core/time/trampoline.rs", "rank": 24, "score": 459084.62001225934 }, { "content": "#[inline]\n\npub fn uuid(interp: &mut Artichoke) -> Result<Value, Exception> {\n\n let uuid = securerandom::uuid();\n\n Ok(interp.convert_mut(uuid))\n\n}\n", "file_path": "artichoke-backend/src/extn/stdlib/securerandom/trampoline.rs", "rank": 25, "score": 459084.62001225934 }, { "content": "pub fn to_h(interp: &mut Artichoke, mut environ: Value) -> Result<Value, Exception> {\n\n let environ = unsafe { Environ::unbox_from_value(&mut environ, interp) }?;\n\n let result = environ.to_map()?;\n\n Ok(interp.convert_mut(result))\n\n}\n", "file_path": "artichoke-backend/src/extn/core/env/trampoline.rs", "rank": 26, "score": 453860.2568328903 }, { "content": "pub fn to_s(interp: &mut Artichoke, mut regexp: Value) -> Result<Value, Exception> {\n\n let regexp = unsafe { Regexp::unbox_from_value(&mut regexp, interp)? };\n\n let s = regexp.string();\n\n Ok(interp.convert_mut(s))\n\n}\n", "file_path": "artichoke-backend/src/extn/core/regexp/trampoline.rs", "rank": 27, "score": 453860.2568328902 }, { "content": "pub fn to_a(interp: &mut Artichoke, mut value: Value) -> Result<Value, Exception> {\n\n let data = unsafe { MatchData::unbox_from_value(&mut value, interp)? };\n\n if let Some(ary) = data.to_a()? {\n\n interp.try_convert_mut(ary)\n\n } else {\n\n Ok(Value::nil())\n\n }\n\n}\n\n\n", "file_path": "artichoke-backend/src/extn/core/matchdata/trampoline.rs", "rank": 28, "score": 453860.25683289027 }, { "content": "pub fn to_s(interp: &mut Artichoke, mut value: Value) -> Result<Value, Exception> {\n\n let data = unsafe { MatchData::unbox_from_value(&mut value, interp)? };\n\n let display = data.to_s()?;\n\n Ok(interp.convert_mut(display))\n\n}\n", "file_path": "artichoke-backend/src/extn/core/matchdata/trampoline.rs", "rank": 29, "score": 453860.25683289027 }, { "content": "pub fn urandom(size: Int) -> Result<Vec<u8>, Exception> {\n\n match usize::try_from(size) {\n\n Ok(0) => Ok(Vec::new()),\n\n Ok(len) => {\n\n let mut buf = vec![0; len];\n\n let mut rng = rand::thread_rng();\n\n rng.try_fill_bytes(&mut buf)\n\n .map_err(|err| RuntimeError::from(err.to_string()))?;\n\n Ok(buf)\n\n }\n\n Err(_) => Err(ArgumentError::from(\"negative string size (or size too big)\").into()),\n\n }\n\n}\n\n\n\npub struct Random(Box<dyn backend::RandType>);\n\n\n\nimpl fmt::Debug for Random {\n\n fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {\n\n f.debug_struct(\"Random\")\n\n .field(\"backend\", self.0.as_debug())\n", "file_path": "artichoke-backend/src/extn/core/random/mod.rs", "rank": 30, "score": 453771.56591924996 }, { "content": "pub fn nanosecond(interp: &mut Artichoke, mut time: Value) -> Result<Value, Exception> {\n\n let time = unsafe { Time::unbox_from_value(&mut time, interp)? };\n\n let nanosecond = time.inner().nanosecond();\n\n let result = interp.convert(nanosecond);\n\n Ok(result)\n\n}\n\n\n", "file_path": "artichoke-backend/src/extn/core/time/trampoline.rs", "rank": 31, "score": 448835.72887785983 }, { "content": "pub fn len(interp: &mut Artichoke, mut ary: Value) -> Result<usize, Exception> {\n\n let array = unsafe { Array::unbox_from_value(&mut ary, interp)? };\n\n Ok(array.len())\n\n}\n\n\n", "file_path": "artichoke-backend/src/extn/core/array/trampoline.rs", "rank": 32, "score": 448835.7288778599 }, { "content": "pub fn month(interp: &mut Artichoke, mut time: Value) -> Result<Value, Exception> {\n\n let time = unsafe { Time::unbox_from_value(&mut time, interp)? };\n\n let month = time.inner().month();\n\n let result = interp.convert(month);\n\n Ok(result)\n\n}\n\n\n", "file_path": "artichoke-backend/src/extn/core/time/trampoline.rs", "rank": 33, "score": 448835.72887785983 }, { "content": "pub fn second(interp: &mut Artichoke, mut time: Value) -> Result<Value, Exception> {\n\n let time = unsafe { Time::unbox_from_value(&mut time, interp)? };\n\n let second = time.inner().second();\n\n let result = interp.convert(second);\n\n Ok(result)\n\n}\n\n\n", "file_path": "artichoke-backend/src/extn/core/time/trampoline.rs", "rank": 34, "score": 448835.72887785983 }, { "content": "pub fn year(interp: &mut Artichoke, mut time: Value) -> Result<Value, Exception> {\n\n let time = unsafe { Time::unbox_from_value(&mut time, interp)? };\n\n let year = time.inner().year();\n\n let result = interp.convert(year);\n\n Ok(result)\n\n}\n", "file_path": "artichoke-backend/src/extn/core/time/trampoline.rs", "rank": 35, "score": 448835.72887785983 }, { "content": "pub fn names(interp: &mut Artichoke, mut value: Value) -> Result<Value, Exception> {\n\n let data = unsafe { MatchData::unbox_from_value(&mut value, interp)? };\n\n let names = data.names();\n\n interp.try_convert_mut(names)\n\n}\n\n\n", "file_path": "artichoke-backend/src/extn/core/matchdata/trampoline.rs", "rank": 36, "score": 448835.72887785983 }, { "content": "pub fn hash(interp: &mut Artichoke, mut regexp: Value) -> Result<Value, Exception> {\n\n let regexp = unsafe { Regexp::unbox_from_value(&mut regexp, interp)? };\n\n let hash = regexp.hash();\n\n #[allow(clippy::cast_possible_wrap)]\n\n Ok(interp.convert(hash as Int))\n\n}\n\n\n", "file_path": "artichoke-backend/src/extn/core/regexp/trampoline.rs", "rank": 37, "score": 448835.72887785983 }, { "content": "pub fn is_casefold(interp: &mut Artichoke, mut regexp: Value) -> Result<Value, Exception> {\n\n let regexp = unsafe { Regexp::unbox_from_value(&mut regexp, interp)? };\n\n let is_casefold = regexp.is_casefold();\n\n Ok(interp.convert(is_casefold))\n\n}\n\n\n", "file_path": "artichoke-backend/src/extn/core/regexp/trampoline.rs", "rank": 38, "score": 448835.72887785983 }, { "content": "pub fn pop(interp: &mut Artichoke, mut ary: Value) -> Result<Value, Exception> {\n\n if ary.is_frozen(interp) {\n\n return Err(FrozenError::from(\"can't modify frozen Array\").into());\n\n }\n\n let mut array = unsafe { Array::unbox_from_value(&mut ary, interp)? };\n\n let result = array.pop();\n\n Ok(interp.convert(result))\n\n}\n\n\n", "file_path": "artichoke-backend/src/extn/core/array/trampoline.rs", "rank": 39, "score": 448835.72887785983 }, { "content": "pub fn source(interp: &mut Artichoke, mut regexp: Value) -> Result<Value, Exception> {\n\n let regexp = unsafe { Regexp::unbox_from_value(&mut regexp, interp)? };\n\n let source = regexp.source();\n\n Ok(interp.convert_mut(source))\n\n}\n\n\n", "file_path": "artichoke-backend/src/extn/core/regexp/trampoline.rs", "rank": 40, "score": 448835.72887785983 }, { "content": "pub fn bytes(interp: &mut Artichoke, mut value: Value) -> Result<Value, Exception> {\n\n let symbol = unsafe { Symbol::unbox_from_value(&mut value, interp)? };\n\n // These bytes must be cloned because they are owned by the interpreter.\n\n let bytes = symbol.bytes(interp).to_vec();\n\n Ok(interp.convert_mut(bytes))\n\n}\n", "file_path": "artichoke-backend/src/extn/core/symbol/trampoline.rs", "rank": 41, "score": 448835.72887785983 }, { "content": "pub fn captures(interp: &mut Artichoke, mut value: Value) -> Result<Value, Exception> {\n\n let data = unsafe { MatchData::unbox_from_value(&mut value, interp)? };\n\n if let Some(captures) = data.captures()? {\n\n interp.try_convert_mut(captures)\n\n } else {\n\n Ok(Value::nil())\n\n }\n\n}\n\n\n", "file_path": "artichoke-backend/src/extn/core/matchdata/trampoline.rs", "rank": 42, "score": 448835.72887785983 }, { "content": "pub fn day(interp: &mut Artichoke, mut time: Value) -> Result<Value, Exception> {\n\n let time = unsafe { Time::unbox_from_value(&mut time, interp)? };\n\n let day = time.inner().day();\n\n let result = interp.convert(day);\n\n Ok(result)\n\n}\n\n\n", "file_path": "artichoke-backend/src/extn/core/time/trampoline.rs", "rank": 43, "score": 448835.72887785983 }, { "content": "pub fn clear(interp: &mut Artichoke, mut ary: Value) -> Result<Value, Exception> {\n\n if ary.is_frozen(interp) {\n\n return Err(FrozenError::from(\"can't modify frozen Array\").into());\n\n }\n\n let mut array = unsafe { Array::unbox_from_value(&mut ary, interp)? };\n\n array.clear();\n\n Ok(ary)\n\n}\n\n\n", "file_path": "artichoke-backend/src/extn/core/array/trampoline.rs", "rank": 44, "score": 448835.72887785983 }, { "content": "pub fn regexp(interp: &mut Artichoke, mut value: Value) -> Result<Value, Exception> {\n\n let data = unsafe { MatchData::unbox_from_value(&mut value, interp)? };\n\n let regexp = data.regexp();\n\n // TODO(GH-614): MatchData#regexp needs to return an identical Regexp to the\n\n // one used to create the match (same object ID).\n\n //\n\n // The `Regexp::alloc_value` here should be replaced with\n\n // `Regexp::box_into_value`.\n\n //\n\n // See: https://github.com/ruby/spec/pull/727\n\n let regexp = Regexp::alloc_value(regexp.clone(), interp)?;\n\n Ok(regexp)\n\n}\n\n\n", "file_path": "artichoke-backend/src/extn/core/matchdata/trampoline.rs", "rank": 45, "score": 448835.72887785983 }, { "content": "pub fn weekday(interp: &mut Artichoke, mut time: Value) -> Result<Value, Exception> {\n\n let time = unsafe { Time::unbox_from_value(&mut time, interp)? };\n\n let weekday = time.inner().weekday();\n\n let result = interp.convert(weekday);\n\n Ok(result)\n\n}\n\n\n", "file_path": "artichoke-backend/src/extn/core/time/trampoline.rs", "rank": 46, "score": 448835.72887785983 }, { "content": "pub fn length(interp: &mut Artichoke, mut value: Value) -> Result<Value, Exception> {\n\n let data = unsafe { MatchData::unbox_from_value(&mut value, interp)? };\n\n let len = data.len()?;\n\n if let Ok(len) = Int::try_from(len) {\n\n Ok(interp.convert(len))\n\n } else {\n\n Err(ArgumentError::from(\"input string too long\").into())\n\n }\n\n}\n\n\n", "file_path": "artichoke-backend/src/extn/core/matchdata/trampoline.rs", "rank": 47, "score": 448835.72887785983 }, { "content": "pub fn inspect(interp: &mut Artichoke, mut regexp: Value) -> Result<Value, Exception> {\n\n let regexp = unsafe { Regexp::unbox_from_value(&mut regexp, interp)? };\n\n let inspect = regexp.inspect();\n\n Ok(interp.convert_mut(inspect))\n\n}\n\n\n", "file_path": "artichoke-backend/src/extn/core/regexp/trampoline.rs", "rank": 48, "score": 448835.7288778599 }, { "content": "pub fn length(interp: &mut Artichoke, mut value: Value) -> Result<Value, Exception> {\n\n let symbol = unsafe { Symbol::unbox_from_value(&mut value, interp)? };\n\n let len = symbol.len(interp);\n\n interp.try_convert(len)\n\n}\n\n\n", "file_path": "artichoke-backend/src/extn/core/symbol/trampoline.rs", "rank": 49, "score": 448835.7288778599 }, { "content": "pub fn string(interp: &mut Artichoke, mut value: Value) -> Result<Value, Exception> {\n\n let data = unsafe { MatchData::unbox_from_value(&mut value, interp)? };\n\n let mut string = interp.convert_mut(data.string());\n\n string.freeze(interp)?;\n\n Ok(string)\n\n}\n\n\n", "file_path": "artichoke-backend/src/extn/core/matchdata/trampoline.rs", "rank": 50, "score": 448835.72887785983 }, { "content": "pub fn hour(interp: &mut Artichoke, mut time: Value) -> Result<Value, Exception> {\n\n let time = unsafe { Time::unbox_from_value(&mut time, interp)? };\n\n let hour = time.inner().hour();\n\n let result = interp.convert(hour);\n\n Ok(result)\n\n}\n\n\n", "file_path": "artichoke-backend/src/extn/core/time/trampoline.rs", "rank": 51, "score": 448835.7288778599 }, { "content": "pub fn microsecond(interp: &mut Artichoke, mut time: Value) -> Result<Value, Exception> {\n\n let time = unsafe { Time::unbox_from_value(&mut time, interp)? };\n\n let microsecond = time.inner().microsecond();\n\n let result = interp.convert(microsecond);\n\n Ok(result)\n\n}\n\n\n", "file_path": "artichoke-backend/src/extn/core/time/trampoline.rs", "rank": 52, "score": 448835.72887785983 }, { "content": "pub fn minute(interp: &mut Artichoke, mut time: Value) -> Result<Value, Exception> {\n\n let time = unsafe { Time::unbox_from_value(&mut time, interp)? };\n\n let minute = time.inner().minute();\n\n let result = interp.convert(minute);\n\n Ok(result)\n\n}\n\n\n", "file_path": "artichoke-backend/src/extn/core/time/trampoline.rs", "rank": 53, "score": 448835.72887785983 }, { "content": "pub fn names(interp: &mut Artichoke, mut regexp: Value) -> Result<Value, Exception> {\n\n let regexp = unsafe { Regexp::unbox_from_value(&mut regexp, interp)? };\n\n let names = regexp.names();\n\n interp.try_convert_mut(names)\n\n}\n\n\n", "file_path": "artichoke-backend/src/extn/core/regexp/trampoline.rs", "rank": 54, "score": 448835.72887785983 }, { "content": "pub fn is_empty(interp: &mut Artichoke, mut value: Value) -> Result<Value, Exception> {\n\n let symbol = unsafe { Symbol::unbox_from_value(&mut value, interp)? };\n\n let is_empty = symbol.is_empty(interp);\n\n Ok(interp.convert(is_empty))\n\n}\n\n\n", "file_path": "artichoke-backend/src/extn/core/symbol/trampoline.rs", "rank": 55, "score": 448835.72887785983 }, { "content": "pub fn init(interp: &mut Artichoke) -> InitializeResult<()> {\n\n abbrev::init(interp)?;\n\n base64::init(interp)?;\n\n cmath::init(interp)?;\n\n delegate::init(interp)?;\n\n forwardable::init(interp)?;\n\n json::init(interp)?;\n\n monitor::init(interp)?;\n\n ostruct::init(interp)?;\n\n #[cfg(feature = \"stdlib-securerandom\")]\n\n securerandom::mruby::init(interp)?;\n\n set::init(interp)?;\n\n shellwords::init(interp)?;\n\n strscan::init(interp)?;\n\n time::init(interp)?;\n\n uri::init(interp)?;\n\n Ok(())\n\n}\n", "file_path": "artichoke-backend/src/extn/stdlib/mod.rs", "rank": 56, "score": 444613.7106910174 }, { "content": "pub fn init(interp: &mut Artichoke) -> InitializeResult<()> {\n\n // These core classes are ordered according to the dependency DAG between\n\n // them.\n\n let _ = interp.eval(&include_bytes!(\"object.rb\")[..])?;\n\n enumerable::init(interp)?;\n\n // `Array` depends on: `Enumerable`\n\n array::mruby::init(interp)?;\n\n module::init(interp)?;\n\n // Some `Exception`s depend on: `attr_accessor` (defined in `Module`)\n\n exception::init(interp)?;\n\n comparable::init(interp)?;\n\n symbol::mruby::init(interp)?;\n\n artichoke::init(interp)?;\n\n enumerator::init(interp)?;\n\n env::mruby::init(interp)?;\n\n hash::init(interp)?;\n\n numeric::init(interp)?;\n\n integer::mruby::init(interp)?;\n\n float::init(interp)?;\n\n kernel::mruby::init(interp)?;\n", "file_path": "artichoke-backend/src/extn/core/mod.rs", "rank": 57, "score": 444613.71069101733 }, { "content": "pub fn named_captures(interp: &mut Artichoke, mut regexp: Value) -> Result<Value, Exception> {\n\n let regexp = unsafe { Regexp::unbox_from_value(&mut regexp, interp)? };\n\n let named_captures = regexp.named_captures()?;\n\n interp.try_convert_mut(named_captures)\n\n}\n\n\n", "file_path": "artichoke-backend/src/extn/core/regexp/trampoline.rs", "rank": 58, "score": 443970.1433987326 }, { "content": "pub fn named_captures(interp: &mut Artichoke, mut value: Value) -> Result<Value, Exception> {\n\n let data = unsafe { MatchData::unbox_from_value(&mut value, interp)? };\n\n let named_captures = data.named_captures()?;\n\n interp.try_convert_mut(named_captures)\n\n}\n\n\n", "file_path": "artichoke-backend/src/extn/core/matchdata/trampoline.rs", "rank": 59, "score": 443970.1433987326 }, { "content": "pub fn year_day(interp: &mut Artichoke, mut time: Value) -> Result<Value, Exception> {\n\n let time = unsafe { Time::unbox_from_value(&mut time, interp)? };\n\n let year_day = time.inner().year_day();\n\n let result = interp.convert(year_day);\n\n Ok(result)\n\n}\n\n\n", "file_path": "artichoke-backend/src/extn/core/time/trampoline.rs", "rank": 60, "score": 443970.1433987326 }, { "content": "pub fn reverse_bang(interp: &mut Artichoke, mut ary: Value) -> Result<Value, Exception> {\n\n if ary.is_frozen(interp) {\n\n return Err(FrozenError::from(\"can't modify frozen Array\").into());\n\n }\n\n let mut array = unsafe { Array::unbox_from_value(&mut ary, interp)? };\n\n array.reverse();\n\n Ok(ary)\n\n}\n\n\n", "file_path": "artichoke-backend/src/extn/core/array/trampoline.rs", "rank": 61, "score": 443970.1433987326 }, { "content": "pub fn is_fixed_encoding(interp: &mut Artichoke, mut regexp: Value) -> Result<Value, Exception> {\n\n let regexp = unsafe { Regexp::unbox_from_value(&mut regexp, interp)? };\n\n let is_fixed_encoding = regexp.is_fixed_encoding();\n\n Ok(interp.convert(is_fixed_encoding))\n\n}\n\n\n", "file_path": "artichoke-backend/src/extn/core/regexp/trampoline.rs", "rank": 62, "score": 443970.1433987326 }, { "content": "/// Load the Artichoke `MSpec` entry point end execute the specs.\n\n///\n\n/// # Errors\n\n///\n\n/// If an exception is raised on the Artichoke interpreter, it is returned.\n\npub fn run<'a, T>(interp: &mut Artichoke, specs: T) -> Result<bool, Exception>\n\nwhere\n\n T: IntoIterator<Item = &'a str>,\n\n{\n\n interp.def_rb_source_file(\"/src/lib/spec_helper.rb\", &b\"\"[..])?;\n\n interp.def_rb_source_file(\n\n \"/src/lib/test/spec_runner\",\n\n &include_bytes!(\"spec_runner.rb\")[..],\n\n )?;\n\n interp.eval_file(Path::new(\"/src/lib/test/spec_runner\"))?;\n\n let specs = interp.try_convert_mut(specs.into_iter().collect::<Vec<_>>())?;\n\n let result = interp\n\n .top_self()\n\n .funcall(interp, \"run_specs\", &[specs], None)?;\n\n interp.try_convert(result)\n\n}\n\n\n\n#[cfg(test)]\n\nmod tests {\n\n #[test]\n\n // TODO(GH-528): fix failing tests on Windows.\n\n #[cfg_attr(target_os = \"windows\", should_panic)]\n\n fn mspec_framework_loads() {\n\n let mut interp = artichoke::interpreter().unwrap();\n\n super::init(&mut interp).unwrap();\n\n // should not panic\n\n assert!(super::run(&mut interp, vec![]).unwrap());\n\n }\n\n}\n", "file_path": "spec-runner/src/mspec.rs", "rank": 63, "score": 440575.5096000759 }, { "content": "pub fn init(interp: &mut Artichoke) -> InitializeResult<()> {\n\n if interp.is_class_defined::<Float>() {\n\n return Ok(());\n\n }\n\n let spec = class::Spec::new(\"Float\", None, None)?;\n\n interp.def_class::<Float>(spec)?;\n\n let _ = interp.eval(&include_bytes!(\"float.rb\")[..])?;\n\n\n\n let dig = interp.convert(Float::DIG);\n\n interp.define_class_constant::<Float>(\"DIG\", dig)?;\n\n let epsilon = interp.convert_mut(Float::EPSILON);\n\n interp.define_class_constant::<Float>(\"EPSILON\", epsilon)?;\n\n let infinity = interp.convert_mut(Float::INFINITY);\n\n interp.define_class_constant::<Float>(\"INFINITY\", infinity)?;\n\n let mant_dig = interp.convert(Float::MANT_DIG);\n\n interp.define_class_constant::<Float>(\"MANT_DIG\", mant_dig)?;\n\n let max = interp.convert_mut(Float::MAX);\n\n interp.define_class_constant::<Float>(\"MAX\", max)?;\n\n let max_10_exp = interp.convert(Float::MAX_10_EXP);\n\n interp.define_class_constant::<Float>(\"MAX_10_EXP\", max_10_exp)?;\n", "file_path": "artichoke-backend/src/extn/core/float/mod.rs", "rank": 64, "score": 439520.4322288438 }, { "content": "pub fn init(interp: &mut Artichoke) -> InitializeResult<()> {\n\n let spec = module::Spec::new(interp, \"Abbrev\", None)?;\n\n interp.def_module::<Abbrev>(spec)?;\n\n interp.def_rb_source_file(\"abbrev.rb\", &include_bytes!(\"vendor/abbrev.rb\")[..])?;\n\n Ok(())\n\n}\n\n\n\n#[derive(Debug)]\n\npub struct Abbrev;\n\n\n\n#[cfg(test)]\n\nmod tests {\n\n use crate::test::prelude::*;\n\n\n\n #[test]\n\n fn integration_test() {\n\n let mut interp = crate::interpreter().unwrap();\n\n let _ = interp.eval(&include_bytes!(\"abbrev_test.rb\")[..]).unwrap();\n\n let result = interp.eval(b\"spec\");\n\n let result = result.unwrap().try_into::<bool>(&interp).unwrap();\n\n assert!(result);\n\n }\n\n}\n", "file_path": "artichoke-backend/src/extn/stdlib/abbrev/mod.rs", "rank": 65, "score": 439520.43222884386 }, { "content": "pub fn init(interp: &mut Artichoke) -> InitializeResult<()> {\n\n let spec = class::Spec::new(\"OpenStruct\", None, None)?;\n\n interp.def_class::<OpenStruct>(spec)?;\n\n interp.def_rb_source_file(\"ostruct.rb\", &include_bytes!(\"vendor/ostruct.rb\")[..])?;\n\n Ok(())\n\n}\n\n\n\n#[derive(Debug)]\n\npub struct OpenStruct;\n", "file_path": "artichoke-backend/src/extn/stdlib/ostruct/mod.rs", "rank": 66, "score": 439520.4322288438 }, { "content": "pub fn init(interp: &mut Artichoke) -> InitializeResult<()> {\n\n if interp.is_module_defined::<Comparable>() {\n\n return Ok(());\n\n }\n\n let spec = module::Spec::new(interp, \"Comparable\", None)?;\n\n module::Builder::for_spec(interp, &spec).define()?;\n\n interp.def_module::<Comparable>(spec)?;\n\n let _ = interp.eval(&include_bytes!(\"comparable.rb\")[..])?;\n\n trace!(\"Patched Comparable onto interpreter\");\n\n Ok(())\n\n}\n\n\n\n#[derive(Debug)]\n\npub struct Comparable;\n", "file_path": "artichoke-backend/src/extn/core/comparable/mod.rs", "rank": 67, "score": 439520.4322288438 }, { "content": "pub fn init(interp: &mut Artichoke) -> InitializeResult<()> {\n\n if interp.is_class_defined::<matchdata::MatchData>() {\n\n return Ok(());\n\n }\n\n let spec = class::Spec::new(\n\n \"MatchData\",\n\n None,\n\n Some(def::box_unbox_free::<matchdata::MatchData>),\n\n )?;\n\n class::Builder::for_spec(interp, &spec)\n\n .value_is_rust_object()\n\n .add_method(\"begin\", artichoke_matchdata_begin, sys::mrb_args_req(1))?\n\n .add_method(\n\n \"captures\",\n\n artichoke_matchdata_captures,\n\n sys::mrb_args_none(),\n\n )?\n\n .add_method(\n\n \"[]\",\n\n artichoke_matchdata_element_reference,\n", "file_path": "artichoke-backend/src/extn/core/matchdata/mruby.rs", "rank": 68, "score": 439520.43222884386 }, { "content": "pub fn init(interp: &mut Artichoke) -> InitializeResult<()> {\n\n let spec = class::Spec::new(\"IPSocket\", None, None)?;\n\n interp.def_class::<IpSocket>(spec)?;\n\n\n\n let spec = class::Spec::new(\"IPAddr\", None, None)?;\n\n interp.def_class::<IpAddr>(spec)?;\n\n\n\n let spec = module::Spec::new(interp, \"URI\", None)?;\n\n interp.def_module::<Uri>(spec)?;\n\n\n\n interp.def_rb_source_file(\"uri.rb\", &include_bytes!(\"vendor/uri.rb\")[..])?;\n\n interp.def_rb_source_file(\"uri/common.rb\", &include_bytes!(\"vendor/uri/common.rb\")[..])?;\n\n interp.def_rb_source_file(\"uri/file.rb\", &include_bytes!(\"vendor/uri/file.rb\")[..])?;\n\n interp.def_rb_source_file(\"uri/ftp.rb\", &include_bytes!(\"vendor/uri/ftp.rb\")[..])?;\n\n interp.def_rb_source_file(\n\n \"uri/generic.rb\",\n\n &include_bytes!(\"vendor/uri/generic.rb\")[..],\n\n )?;\n\n interp.def_rb_source_file(\"uri/http.rb\", &include_bytes!(\"vendor/uri/http.rb\")[..])?;\n\n interp.def_rb_source_file(\"uri/https.rb\", &include_bytes!(\"vendor/uri/https.rb\")[..])?;\n", "file_path": "artichoke-backend/src/extn/stdlib/uri/mod.rs", "rank": 69, "score": 439520.43222884386 }, { "content": "pub fn init(interp: &mut Artichoke) -> InitializeResult<()> {\n\n let spec = class::Spec::new(\"Delegator\", None, None)?;\n\n interp.def_class::<Delegator>(spec)?;\n\n let spec = class::Spec::new(\"SimpleDelegator\", None, None)?;\n\n interp.def_class::<SimpleDelegator>(spec)?;\n\n interp.def_rb_source_file(\"delegate.rb\", &include_bytes!(\"vendor/delegate.rb\")[..])?;\n\n Ok(())\n\n}\n\n\n\n#[derive(Debug)]\n\npub struct Delegator;\n\n\n\n#[derive(Debug)]\n\npub struct SimpleDelegator;\n", "file_path": "artichoke-backend/src/extn/stdlib/delegate/mod.rs", "rank": 70, "score": 439520.43222884386 }, { "content": "pub fn init(interp: &mut Artichoke) -> InitializeResult<()> {\n\n if interp.is_class_defined::<Module>() {\n\n return Ok(());\n\n }\n\n let spec = class::Spec::new(\"Module\", None, None)?;\n\n interp.def_class::<Module>(spec)?;\n\n let _ = interp.eval(&include_bytes!(\"module.rb\")[..])?;\n\n trace!(\"Patched Module onto interpreter\");\n\n Ok(())\n\n}\n\n\n\n#[derive(Debug)]\n\npub struct Module;\n", "file_path": "artichoke-backend/src/extn/core/module/mod.rs", "rank": 71, "score": 439520.43222884386 }, { "content": "pub fn init(interp: &mut Artichoke) -> InitializeResult<()> {\n\n if interp.is_module_defined::<Enumerable>() {\n\n return Ok(());\n\n }\n\n let spec = module::Spec::new(interp, \"Enumerable\", None)?;\n\n module::Builder::for_spec(interp, &spec).define()?;\n\n interp.def_module::<Enumerable>(spec)?;\n\n let _ = interp.eval(&include_bytes!(\"enumerable.rb\")[..])?;\n\n trace!(\"Patched Enumerable onto interpreter\");\n\n Ok(())\n\n}\n\n\n\n#[derive(Debug)]\n\npub struct Enumerable;\n", "file_path": "artichoke-backend/src/extn/core/enumerable/mod.rs", "rank": 72, "score": 439520.43222884386 }, { "content": "pub fn init(interp: &mut Artichoke) -> InitializeResult<()> {\n\n if interp.is_class_defined::<Method>() {\n\n return Ok(());\n\n }\n\n let spec = class::Spec::new(\"Method\", None, None)?;\n\n interp.def_class::<Method>(spec)?;\n\n let _ = interp.eval(&include_bytes!(\"method.rb\")[..])?;\n\n trace!(\"Patched Method onto interpreter\");\n\n Ok(())\n\n}\n\n\n\n#[derive(Debug)]\n\npub struct Method;\n", "file_path": "artichoke-backend/src/extn/core/method/mod.rs", "rank": 73, "score": 439520.43222884386 }, { "content": "pub fn init(interp: &mut Artichoke) -> InitializeResult<()> {\n\n if interp.is_module_defined::<math::Math>() {\n\n return Ok(());\n\n }\n\n let spec = module::Spec::new(interp, \"Math\", None)?;\n\n module::Builder::for_spec(interp, &spec)\n\n .add_module_method(\"acos\", artichoke_math_acos, sys::mrb_args_req(1))?\n\n .add_module_method(\"acosh\", artichoke_math_acosh, sys::mrb_args_req(1))?\n\n .add_module_method(\"asin\", artichoke_math_asin, sys::mrb_args_req(1))?\n\n .add_module_method(\"asinh\", artichoke_math_asinh, sys::mrb_args_req(1))?\n\n .add_module_method(\"atan\", artichoke_math_atan, sys::mrb_args_req(1))?\n\n .add_module_method(\"atan2\", artichoke_math_atan2, sys::mrb_args_req(2))?\n\n .add_module_method(\"atanh\", artichoke_math_atanh, sys::mrb_args_req(1))?\n\n .add_module_method(\"cbrt\", artichoke_math_cbrt, sys::mrb_args_req(1))?\n\n .add_module_method(\"cos\", artichoke_math_cos, sys::mrb_args_req(1))?\n\n .add_module_method(\"cosh\", artichoke_math_cosh, sys::mrb_args_req(1))?\n\n .add_module_method(\"erf\", artichoke_math_erf, sys::mrb_args_req(1))?\n\n .add_module_method(\"erfc\", artichoke_math_erfc, sys::mrb_args_req(1))?\n\n .add_module_method(\"exp\", artichoke_math_exp, sys::mrb_args_req(1))?\n\n .add_module_method(\"frexp\", artichoke_math_frexp, sys::mrb_args_req(1))?\n", "file_path": "artichoke-backend/src/extn/core/math/mruby.rs", "rank": 74, "score": 439520.4322288438 }, { "content": "pub fn init(interp: &mut Artichoke) -> InitializeResult<()> {\n\n let spec = class::Spec::new(\"Monitor\", None, None)?;\n\n interp.def_class::<Monitor>(spec)?;\n\n interp.def_rb_source_file(\"monitor.rb\", &include_bytes!(\"vendor/monitor.rb\")[..])?;\n\n Ok(())\n\n}\n\n\n\n#[derive(Debug)]\n\npub struct Monitor;\n\n\n\n#[cfg(test)]\n\nmod tests {\n\n use crate::test::prelude::*;\n\n\n\n #[test]\n\n fn integration_test() {\n\n let mut interp = crate::interpreter().unwrap();\n\n let _ = interp.eval(&include_bytes!(\"monitor_test.rb\")[..]).unwrap();\n\n let result = interp.eval(b\"spec\");\n\n let result = result.unwrap().try_into::<bool>(&interp).unwrap();\n\n assert!(result);\n\n }\n\n}\n", "file_path": "artichoke-backend/src/extn/stdlib/monitor/mod.rs", "rank": 75, "score": 439520.43222884386 }, { "content": "pub fn init(interp: &mut Artichoke) -> InitializeResult<()> {\n\n if interp.is_module_defined::<Warning>() {\n\n return Ok(());\n\n }\n\n let spec = module::Spec::new(interp, \"Warning\", None)?;\n\n module::Builder::for_spec(interp, &spec).define()?;\n\n interp.def_module::<Warning>(spec)?;\n\n let _ = interp.eval(&include_bytes!(\"warning.rb\")[..])?;\n\n trace!(\"Patched Warning onto interpreter\");\n\n Ok(())\n\n}\n\n\n\n#[derive(Debug)]\n\npub struct Warning;\n", "file_path": "artichoke-backend/src/extn/core/warning/mod.rs", "rank": 76, "score": 439520.43222884386 }, { "content": "pub fn init(interp: &mut Artichoke) -> InitializeResult<()> {\n\n if interp.is_class_defined::<Thread>() {\n\n return Ok(());\n\n }\n\n if interp.is_class_defined::<Mutex>() {\n\n return Ok(());\n\n }\n\n let spec = class::Spec::new(\"Thread\", None, None)?;\n\n interp.def_class::<Thread>(spec)?;\n\n let spec = class::Spec::new(\"Mutex\", None, None)?;\n\n interp.def_class::<Mutex>(spec)?;\n\n interp.def_rb_source_file(\"thread.rb\", &include_bytes!(\"thread.rb\")[..])?;\n\n // Thread is loaded by default, so eval it on interpreter initialization\n\n // https://www.rubydoc.info/gems/rubocop/RuboCop/Cop/Lint/UnneededRequireStatement\n\n let _ = interp.eval(&b\"require 'thread'\"[..])?;\n\n trace!(\"Patched Thread onto interpreter\");\n\n trace!(\"Patched Mutex onto interpreter\");\n\n Ok(())\n\n}\n\n\n", "file_path": "artichoke-backend/src/extn/core/thread/mod.rs", "rank": 77, "score": 439520.4322288438 }, { "content": "pub fn init(interp: &mut Artichoke) -> InitializeResult<()> {\n\n if interp.is_class_defined::<Numeric>() {\n\n return Ok(());\n\n }\n\n let spec = class::Spec::new(\"Numeric\", None, None)?;\n\n interp.def_class::<Numeric>(spec)?;\n\n let _ = interp.eval(&include_bytes!(\"numeric.rb\")[..])?;\n\n trace!(\"Patched Numeric onto interpreter\");\n\n Ok(())\n\n}\n\n\n\n#[derive(Debug)]\n\npub struct Numeric;\n\n\n\n#[derive(Debug, Clone, Copy, PartialEq, PartialOrd)]\n\npub enum Outcome {\n\n Float(Fp),\n\n Integer(Int),\n\n // TODO: Complex? Rational?\n\n}\n", "file_path": "artichoke-backend/src/extn/core/numeric/mod.rs", "rank": 78, "score": 439520.4322288438 }, { "content": "pub fn init(interp: &mut Artichoke) -> InitializeResult<()> {\n\n // time package does not define any additional types; it provides extension\n\n // methods on the `Time` core class.\n\n interp.def_rb_source_file(\"time.rb\", &include_bytes!(\"vendor/time.rb\")[..])?;\n\n Ok(())\n\n}\n", "file_path": "artichoke-backend/src/extn/stdlib/time/mod.rs", "rank": 79, "score": 439520.4322288438 }, { "content": "pub fn init(interp: &mut Artichoke) -> InitializeResult<()> {\n\n if interp.is_class_defined::<string::String>() {\n\n return Ok(());\n\n }\n\n let spec = class::Spec::new(\"String\", None, None)?;\n\n class::Builder::for_spec(interp, &spec)\n\n .add_method(\"ord\", artichoke_string_ord, sys::mrb_args_none())?\n\n .add_method(\"scan\", artichoke_string_scan, sys::mrb_args_req(1))?\n\n .define()?;\n\n interp.def_class::<string::String>(spec)?;\n\n let _ = interp.eval(&include_bytes!(\"string.rb\")[..])?;\n\n trace!(\"Patched String onto interpreter\");\n\n Ok(())\n\n}\n\n\n\nunsafe extern \"C\" fn artichoke_string_ord(\n\n mrb: *mut sys::mrb_state,\n\n slf: sys::mrb_value,\n\n) -> sys::mrb_value {\n\n let mut interp = unwrap_interpreter!(mrb);\n", "file_path": "artichoke-backend/src/extn/core/string/mruby.rs", "rank": 80, "score": 439520.43222884386 }, { "content": "pub fn init(interp: &mut Artichoke) -> InitializeResult<()> {\n\n if interp.is_class_defined::<env::Environ>() {\n\n return Ok(());\n\n }\n\n let scope = interp\n\n .module_spec::<artichoke::Artichoke>()?\n\n .map(EnclosingRubyScope::module)\n\n .ok_or_else(|| NotDefinedError::module(\"Artichoke\"))?;\n\n let spec = class::Spec::new(\n\n \"Environ\",\n\n Some(scope),\n\n Some(def::box_unbox_free::<env::Environ>),\n\n )?;\n\n class::Builder::for_spec(interp, &spec)\n\n .value_is_rust_object()\n\n .add_method(\"[]\", artichoke_env_element_reference, sys::mrb_args_req(1))?\n\n .add_method(\n\n \"[]=\",\n\n artichoke_env_element_assignment,\n\n sys::mrb_args_req(2),\n", "file_path": "artichoke-backend/src/extn/core/env/mruby.rs", "rank": 81, "score": 439520.43222884386 }, { "content": "pub fn init(interp: &mut Artichoke) -> InitializeResult<()> {\n\n let spec = module::Spec::new(interp, \"JSON\", None)?;\n\n interp.def_module::<Json>(spec)?;\n\n // NOTE(lopopolo): This setup of the JSON gem in the vfs does not include\n\n // any of the `json/add` sources for serializing \"extra\" types like `Time`\n\n // and `BigDecimal`, not all of which Artichoke supports.\n\n interp.def_rb_source_file(\"json.rb\", &include_bytes!(\"vendor/json.rb\")[..])?;\n\n interp.def_rb_source_file(\n\n \"json/common.rb\",\n\n &include_bytes!(\"vendor/json/common.rb\")[..],\n\n )?;\n\n interp.def_rb_source_file(\n\n \"json/generic_object.rb\",\n\n &include_bytes!(\"vendor/json/generic_object.rb\")[..],\n\n )?;\n\n interp.def_rb_source_file(\n\n \"json/version.rb\",\n\n &include_bytes!(\"vendor/json/version.rb\")[..],\n\n )?;\n\n interp.def_rb_source_file(\"json/pure.rb\", &include_bytes!(\"vendor/json/pure.rb\")[..])?;\n", "file_path": "artichoke-backend/src/extn/stdlib/json/mod.rs", "rank": 82, "score": 439520.4322288438 }, { "content": "pub fn init(interp: &mut Artichoke) -> InitializeResult<()> {\n\n let spec = class::Spec::new(\"StringScanner\", None, None)?;\n\n interp.def_class::<StringScanner>(spec)?;\n\n interp.def_rb_source_file(\"strscan.rb\", &include_bytes!(\"strscan.rb\")[..])?;\n\n Ok(())\n\n}\n\n\n\n#[derive(Debug)]\n\npub struct StringScanner;\n\n\n\n#[cfg(test)]\n\nmod tests {\n\n use crate::test::prelude::*;\n\n\n\n #[test]\n\n fn integration_test() {\n\n let mut interp = crate::interpreter().expect(\"init\");\n\n interp.eval(&include_bytes!(\"strscan_test.rb\")[..]).unwrap();\n\n let result = interp.eval(b\"spec\");\n\n let result = result.unwrap().try_into::<bool>(&interp).unwrap();\n\n assert!(result);\n\n }\n\n}\n", "file_path": "artichoke-backend/src/extn/stdlib/strscan/mod.rs", "rank": 83, "score": 439520.43222884386 }, { "content": "pub fn init(interp: &mut Artichoke) -> InitializeResult<()> {\n\n if interp.is_class_defined::<symbol::Symbol>() {\n\n return Ok(());\n\n }\n\n let spec = class::Spec::new(\"Symbol\", None, None)?;\n\n class::Builder::for_spec(interp, &spec)\n\n .add_self_method(\n\n \"all_symbols\",\n\n artichoke_symbol_all_symbols,\n\n sys::mrb_args_none(),\n\n )?\n\n .add_method(\"==\", artichoke_symbol_equal_equal, sys::mrb_args_req(1))?\n\n .add_method(\"empty?\", artichoke_symbol_empty, sys::mrb_args_none())?\n\n .add_method(\"length\", artichoke_symbol_length, sys::mrb_args_none())?\n\n .add_method(\"to_s\", artichoke_symbol_to_s, sys::mrb_args_none())?\n\n .define()?;\n\n interp.def_class::<symbol::Symbol>(spec)?;\n\n let _ = interp.eval(&include_bytes!(\"symbol.rb\")[..])?;\n\n trace!(\"Patched Symbol onto interpreter\");\n\n Ok(())\n", "file_path": "artichoke-backend/src/extn/core/symbol/mruby.rs", "rank": 84, "score": 439520.4322288438 }, { "content": "pub fn init(interp: &mut Artichoke) -> InitializeResult<()> {\n\n let spec = module::Spec::new(interp, \"Shellwords\", None)?;\n\n interp.def_module::<Shellwords>(spec)?;\n\n interp.def_rb_source_file(\"shellwords.rb\", &include_bytes!(\"vendor/shellwords.rb\")[..])?;\n\n Ok(())\n\n}\n\n\n\n#[derive(Debug)]\n\npub struct Shellwords;\n", "file_path": "artichoke-backend/src/extn/stdlib/shellwords/mod.rs", "rank": 85, "score": 439520.4322288438 }, { "content": "pub fn init(interp: &mut Artichoke) -> InitializeResult<()> {\n\n let spec = class::Spec::new(\"Set\", None, None)?;\n\n interp.def_class::<Set>(spec)?;\n\n let spec = class::Spec::new(\"SortedSet\", None, None)?;\n\n interp.def_class::<SortedSet>(spec)?;\n\n interp.def_rb_source_file(\"set.rb\", &include_bytes!(\"vendor/set.rb\")[..])?;\n\n Ok(())\n\n}\n\n\n\n#[derive(Debug)]\n\npub struct Set;\n\n\n\n#[derive(Debug)]\n\n#[allow(clippy::module_name_repetitions)]\n\npub struct SortedSet;\n", "file_path": "artichoke-backend/src/extn/stdlib/set/mod.rs", "rank": 86, "score": 439520.4322288438 }, { "content": "pub fn init(interp: &mut Artichoke) -> InitializeResult<()> {\n\n if interp.is_class_defined::<Hash>() {\n\n return Ok(());\n\n }\n\n let spec = class::Spec::new(\"Hash\", None, None)?;\n\n interp.def_class::<Hash>(spec)?;\n\n let _ = interp.eval(&include_bytes!(\"hash.rb\")[..])?;\n\n trace!(\"Patched Hash onto interpreter\");\n\n Ok(())\n\n}\n\n\n\n#[derive(Debug)]\n\npub struct Hash;\n", "file_path": "artichoke-backend/src/extn/core/hash/mod.rs", "rank": 87, "score": 439520.4322288438 }, { "content": "pub fn init(interp: &mut Artichoke) -> InitializeResult<()> {\n\n if interp.is_module_defined::<kernel::Kernel>() {\n\n return Ok(());\n\n }\n\n let spec = module::Spec::new(interp, \"Kernel\", None)?;\n\n module::Builder::for_spec(interp, &spec)\n\n .add_method(\"require\", artichoke_kernel_require, sys::mrb_args_rest())?\n\n .add_method(\n\n \"require_relative\",\n\n artichoke_kernel_require_relative,\n\n sys::mrb_args_rest(),\n\n )?\n\n .add_method(\"load\", artichoke_kernel_load, sys::mrb_args_rest())?\n\n .add_method(\"p\", artichoke_kernel_p, sys::mrb_args_rest())?\n\n .add_method(\"print\", artichoke_kernel_print, sys::mrb_args_rest())?\n\n .add_method(\"puts\", artichoke_kernel_puts, sys::mrb_args_rest())?\n\n .define()?;\n\n interp.def_module::<kernel::Kernel>(spec)?;\n\n let _ = interp.eval(&include_bytes!(\"kernel.rb\")[..])?;\n\n trace!(\"Patched Kernel onto interpreter\");\n", "file_path": "artichoke-backend/src/extn/core/kernel/mruby.rs", "rank": 88, "score": 439520.4322288438 }, { "content": "pub fn init(interp: &mut Artichoke) -> InitializeResult<()> {\n\n let spec = module::Spec::new(interp, \"Forwardable\", None)?;\n\n interp.def_module::<Forwardable>(spec)?;\n\n interp.def_rb_source_file(\n\n \"forwardable.rb\",\n\n &include_bytes!(\"vendor/forwardable.rb\")[..],\n\n )?;\n\n interp.def_rb_source_file(\n\n \"forwardable/impl.rb\",\n\n &include_bytes!(\"vendor/forwardable/impl.rb\")[..],\n\n )?;\n\n Ok(())\n\n}\n\n\n\n#[derive(Debug)]\n\npub struct Forwardable;\n\n\n\n#[cfg(test)]\n\nmod tests {\n\n use crate::test::prelude::*;\n", "file_path": "artichoke-backend/src/extn/stdlib/forwardable/mod.rs", "rank": 89, "score": 439520.43222884386 }, { "content": "pub fn init(interp: &mut Artichoke) -> InitializeResult<()> {\n\n if interp.is_class_defined::<array::Array>() {\n\n return Ok(());\n\n }\n\n let spec = class::Spec::new(\"Array\", None, Some(def::box_unbox_free::<array::Array>))?;\n\n class::Builder::for_spec(interp, &spec)\n\n .value_is_rust_object()\n\n .add_method(\"[]\", ary_element_reference, sys::mrb_args_req_and_opt(1, 1))?\n\n .add_method(\n\n \"[]=\",\n\n ary_element_assignment,\n\n sys::mrb_args_req_and_opt(2, 1),\n\n )?\n\n .add_method(\"concat\", ary_concat, sys::mrb_args_any())?\n\n .add_method(\n\n \"initialize\",\n\n ary_initialize,\n\n sys::mrb_args_opt(2) | sys::mrb_args_block(),\n\n )?\n\n .add_method(\"initialize_copy\", ary_initialize_copy, sys::mrb_args_req(1))?\n", "file_path": "artichoke-backend/src/extn/core/array/mruby.rs", "rank": 90, "score": 439520.4322288438 }, { "content": "pub fn init(interp: &mut Artichoke) -> InitializeResult<()> {\n\n if interp.is_class_defined::<Proc>() {\n\n return Ok(());\n\n }\n\n let spec = class::Spec::new(\"Proc\", None, None)?;\n\n interp.def_class::<Proc>(spec)?;\n\n let _ = interp.eval(&include_bytes!(\"proc.rb\")[..])?;\n\n trace!(\"Patched Proc onto interpreter\");\n\n Ok(())\n\n}\n\n\n\n#[derive(Debug)]\n\npub struct Proc;\n", "file_path": "artichoke-backend/src/extn/core/proc/mod.rs", "rank": 91, "score": 439520.4322288438 }, { "content": "pub fn init(interp: &mut Artichoke) -> InitializeResult<()> {\n\n let spec = module::Spec::new(interp, \"CMath\", None)?;\n\n interp.def_module::<CMath>(spec)?;\n\n interp.def_rb_source_file(\"cmath.rb\", &include_bytes!(\"vendor/cmath.rb\")[..])?;\n\n Ok(())\n\n}\n\n\n\n#[derive(Debug)]\n\npub struct CMath;\n", "file_path": "artichoke-backend/src/extn/stdlib/cmath/mod.rs", "rank": 92, "score": 439520.43222884386 }, { "content": "pub fn init(interp: &mut Artichoke) -> InitializeResult<()> {\n\n if interp.is_class_defined::<Range>() {\n\n return Ok(());\n\n }\n\n let spec = class::Spec::new(\"Range\", None, None)?;\n\n interp.def_class::<Range>(spec)?;\n\n let _ = interp.eval(&include_bytes!(\"range.rb\")[..])?;\n\n trace!(\"Patched Range onto interpreter\");\n\n Ok(())\n\n}\n\n\n\n#[derive(Debug)]\n\npub struct Range;\n", "file_path": "artichoke-backend/src/extn/core/range/mod.rs", "rank": 93, "score": 439520.4322288438 }, { "content": "pub fn init(interp: &mut Artichoke) -> InitializeResult<()> {\n\n if interp.is_class_defined::<Integer>() {\n\n return Ok(());\n\n }\n\n let spec = class::Spec::new(\"Integer\", None, None)?;\n\n class::Builder::for_spec(interp, &spec)\n\n .add_method(\"chr\", artichoke_integer_chr, sys::mrb_args_opt(1))?\n\n .add_method(\n\n \"[]\",\n\n artichoke_integer_element_reference,\n\n sys::mrb_args_req(1),\n\n )?\n\n .add_method(\"/\", artichoke_integer_div, sys::mrb_args_req(1))?\n\n .add_method(\"size\", artichoke_integer_size, sys::mrb_args_none())?\n\n .define()?;\n\n interp.def_class::<Integer>(spec)?;\n\n let _ = interp.eval(&include_bytes!(\"integer.rb\")[..])?;\n\n trace!(\"Patched Integer onto interpreter\");\n\n Ok(())\n\n}\n", "file_path": "artichoke-backend/src/extn/core/integer/mruby.rs", "rank": 94, "score": 439520.4322288438 }, { "content": "pub fn init(interp: &mut Artichoke) -> InitializeResult<()> {\n\n let spec = crate::module::Spec::new(interp, \"Base64\", None)?;\n\n interp.def_module::<Base64>(spec)?;\n\n interp.def_rb_source_file(\"base64.rb\", &include_bytes!(\"vendor/base64.rb\")[..])?;\n\n\n\n Ok(())\n\n}\n\n\n\n#[derive(Debug)]\n\npub struct Base64;\n", "file_path": "artichoke-backend/src/extn/stdlib/base64/mod.rs", "rank": 95, "score": 439520.4322288438 }, { "content": "pub fn init(interp: &mut Artichoke) -> InitializeResult<()> {\n\n if interp.is_class_defined::<regexp::Regexp>() {\n\n return Ok(());\n\n }\n\n let spec = class::Spec::new(\"Regexp\", None, Some(def::box_unbox_free::<regexp::Regexp>))?;\n\n class::Builder::for_spec(interp, &spec)\n\n .value_is_rust_object()\n\n .add_method(\"initialize\", initialize, sys::mrb_args_req_and_opt(1, 2))?\n\n .add_self_method(\"compile\", compile, sys::mrb_args_rest())?\n\n .add_self_method(\"escape\", escape, sys::mrb_args_req(1))?\n\n .add_self_method(\"quote\", escape, sys::mrb_args_req(1))?\n\n .add_self_method(\"union\", union, sys::mrb_args_rest())?\n\n .add_method(\"==\", eql, sys::mrb_args_req(1))?\n\n .add_method(\"===\", case_compare, sys::mrb_args_req(1))?\n\n .add_method(\"=~\", match_operator, sys::mrb_args_req(1))?\n\n .add_method(\"casefold?\", casefold, sys::mrb_args_none())?\n\n .add_method(\"eql?\", eql, sys::mrb_args_req(1))?\n\n .add_method(\"fixed_encoding?\", fixed_encoding, sys::mrb_args_none())?\n\n .add_method(\"hash\", hash, sys::mrb_args_none())?\n\n .add_method(\"inspect\", inspect, sys::mrb_args_none())?\n", "file_path": "artichoke-backend/src/extn/core/regexp/mruby.rs", "rank": 96, "score": 439520.4322288438 }, { "content": "pub fn init(interp: &mut Artichoke) -> InitializeResult<()> {\n\n if interp.is_class_defined::<Object>() {\n\n return Ok(());\n\n }\n\n let spec = class::Spec::new(\"Object\", None, None)?;\n\n interp.def_class::<Object>(spec)?;\n\n let _ = interp.eval(&include_bytes!(\"object.rb\")[..])?;\n\n trace!(\"Patched Object onto interpreter\");\n\n Ok(())\n\n}\n\n\n\n#[derive(Debug)]\n\npub struct Object;\n", "file_path": "artichoke-backend/src/extn/core/object/mod.rs", "rank": 97, "score": 439520.4322288438 }, { "content": "pub fn init(interp: &mut Artichoke) -> InitializeResult<()> {\n\n interp.def_file_for_type::<_, SecureRandomFile>(\"securerandom.rb\")?;\n\n Ok(())\n\n}\n\n\n\n#[derive(Debug)]\n\npub struct SecureRandomFile;\n\n\n\nimpl File for SecureRandomFile {\n\n type Artichoke = Artichoke;\n\n type Error = Exception;\n\n\n\n fn require(interp: &mut Self::Artichoke) -> Result<(), Self::Error> {\n\n if interp.is_module_defined::<securerandom::SecureRandom>() {\n\n return Ok(());\n\n }\n\n let spec = module::Spec::new(interp, \"SecureRandom\", None)?;\n\n module::Builder::for_spec(interp, &spec)\n\n .add_self_method(\n\n \"alphanumeric\",\n", "file_path": "artichoke-backend/src/extn/stdlib/securerandom/mruby.rs", "rank": 98, "score": 439520.4322288438 }, { "content": "pub fn init(interp: &mut Artichoke) -> InitializeResult<()> {\n\n if interp.is_class_defined::<time::Time>() {\n\n return Ok(());\n\n }\n\n let spec = class::Spec::new(\"Time\", None, Some(def::box_unbox_free::<time::Time>))?;\n\n class::Builder::for_spec(interp, &spec)\n\n .value_is_rust_object()\n\n .add_self_method(\"now\", artichoke_time_self_now, sys::mrb_args_none())?\n\n .add_method(\"day\", artichoke_time_day, sys::mrb_args_none())?\n\n .add_method(\"hour\", artichoke_time_hour, sys::mrb_args_none())?\n\n .add_method(\"min\", artichoke_time_minute, sys::mrb_args_none())?\n\n .add_method(\"mon\", artichoke_time_month, sys::mrb_args_none())?\n\n .add_method(\"month\", artichoke_time_month, sys::mrb_args_none())?\n\n .add_method(\"nsec\", artichoke_time_nanosecond, sys::mrb_args_none())?\n\n .add_method(\"sec\", artichoke_time_second, sys::mrb_args_none())?\n\n .add_method(\"tv_nsec\", artichoke_time_nanosecond, sys::mrb_args_none())?\n\n .add_method(\"tv_sec\", artichoke_time_second, sys::mrb_args_none())?\n\n .add_method(\"tv_usec\", artichoke_time_microsecond, sys::mrb_args_none())?\n\n .add_method(\"usec\", artichoke_time_microsecond, sys::mrb_args_none())?\n\n .add_method(\"wday\", artichoke_time_weekday, sys::mrb_args_none())?\n", "file_path": "artichoke-backend/src/extn/core/time/mruby.rs", "rank": 99, "score": 439520.43222884386 } ]
Rust
src/init.rs
dandyvica/clf
0774f971a973d89688a72f7283e251c7a429e946
use std::fs::OpenOptions; use std::path::PathBuf; use simplelog::*; use crate::configuration::{config::Config, script::Script}; use crate::logfile::snapshot::Snapshot; use crate::misc::extension::Expect; use crate::misc::nagios::Nagios; use crate::{args::CliOptions, configuration::vars::GlobalVars}; pub fn init_config(options: &CliOptions) -> Config { #[cfg(feature = "tera")] let _config = Config::from_path( &options.config_file, options.tera_context.as_deref(), options.show_rendered, ); #[cfg(not(feature = "tera"))] let _config = Config::from_path(&options.config_file); if let Err(ref e) = _config { Nagios::exit_critical(&format!( "error loading config file: {:?}, error: {}", &options.config_file, e )); } let mut config = _config.unwrap(); config.global.insert_process_vars(&options.config_file); config.global.insert_extra_vars(&options.extra_vars); let all_vars: Vec<_> = config .global .global_vars .iter() .map(|(k, v)| format!("{}='{}'", k, v)) .collect(); info!("global variables: {}", all_vars.join(" ")); config } pub fn init_log(options: &CliOptions) { let logger = &options.clf_logger; let writable = if options.reset_log { OpenOptions::new() .write(true) .truncate(true) .create(true) .open(logger) } else { OpenOptions::new().append(true).create(true).open(logger) }; if let Err(ref e) = writable { Nagios::exit_critical(&format!( "unable to open or create log file {:?}, error {}", logger, e )); } match WriteLogger::init( options.logger_level, simplelog::ConfigBuilder::new() .set_time_format("%Y-%b-%d %H:%M:%S.%f".to_string()) .build(), writable.unwrap(), ) { Ok(_) => (), Err(e) => { Nagios::exit_critical(&format!( "unable to create log file: {}, error: {}", logger.display(), e )); } }; let metadata = std::fs::metadata(&logger) .expect_critical(&format!("error on metadata() API, path {:?}", &logger)); debug!("current logger size is: {} bytes", metadata.len()); if metadata.len() > options.max_logger_size { if let Err(e) = std::fs::remove_file(&logger) { if e.kind() != std::io::ErrorKind::NotFound { error!("unable to delete logger file: {:?}, error: {}", &logger, e); } } else { info!("deleting logger file {:?}", &logger); } } info!( "=============================> using configuration file: {:?}", &options.config_file ); info!("options: {:?}", &options); } pub fn load_snapshot( options: &CliOptions, config_snapshot_file: &Option<PathBuf>, ) -> (Snapshot, PathBuf) { let snapfile = if options.snapshot_file.is_some() { options.snapshot_file.as_ref().unwrap().clone() } else if config_snapshot_file.is_some() { let conf_file_or_dir = config_snapshot_file.as_ref().unwrap(); if conf_file_or_dir.is_dir() { Snapshot::build_name(&options.config_file, Some(conf_file_or_dir)) } else { conf_file_or_dir.clone() } } else { Snapshot::build_name(&options.config_file, None) }; if options.delete_snapfile { if let Err(e) = std::fs::remove_file(&snapfile) { if e.kind() != std::io::ErrorKind::NotFound { error!( "unable to delete snapshot file: {:?}, error: {}", &snapfile, e ); } } else { info!("deleting snapshot file {:?}", &snapfile); } } info!("using snapshot file:{}", &snapfile.display()); let snapshot = Snapshot::load(&snapfile) .expect_critical(&format!("unable to load snapshot file: {:?},", &snapfile)); info!( "loaded snapshot file {:?}, data = {:#?}", &snapfile, &snapshot ); (snapshot, snapfile) } pub fn save_snapshot(snapshot: &mut Snapshot, snapfile: &PathBuf, retention: u64) { debug!("saving snapshot file {}", &snapfile.display()); if let Err(e) = snapshot.save(&snapfile, retention) { Nagios::exit_critical(&format!( "unable to save snapshot file: {:?}, error: {}", &snapfile, e )); } } pub fn spawn_prescript(prescript: &Script, vars: Option<&GlobalVars>) -> u32 { let result = prescript.spawn(vars); if let Err(e) = &result { error!("error: {} spawning prescript: {:?}", e, prescript.command); Nagios::exit_critical(&format!( "error: {} spawning prescript: {:?}", e, prescript.command )); } debug_assert!(result.is_ok()); result.unwrap() } pub fn spawn_postscript(postscript: &mut Script, pids: &[u32]) { for pid in pids { postscript.command.push(pid.to_string()); } trace!("postscript: {:?}", &postscript.command); let result = postscript.spawn(None); if let Err(e) = &result { error!("error: {} spawning command: {:?}", e, postscript.command); } else { info!( "postcript command successfully executed, pid={}", result.unwrap() ) } }
use std::fs::OpenOptions; use std::path::PathBuf; use simplelog::*; use crate::configuration::{config::Config, script::Script}; use crate::logfile::snapshot::Snapshot; use crate::misc::extension::Expect; use crate::misc::nagios::Nagios; use crate::{args::CliOptions, configuration::vars::GlobalVars}; pub fn init_config(options: &CliOptions) -> Config { #[cfg(feature = "tera")] let _config = Config::from_path( &options.config_file, options.tera_context.as_deref(), options.show_rendered, ); #[cfg(not(feature = "tera"))] let _config = Config::from_path(&options.config_file); if let Err(ref e) = _config { Nagios::exit_critical(&format!( "error loading config file: {:?}, error: {}", &options.config_file, e )); } let mut config = _config.unwrap(); config.global.insert_process_vars(&options.config_file); config.global.insert_extra_vars(&options.extra_vars); let all_vars: Vec<_> = config .global .global_vars .iter() .map(|(k, v)| format!("{}='{}'", k, v)) .collect(); info!("global variables: {}", all_vars.join(" ")); config } pub fn init_log(options: &CliOptions) { let logger = &options.clf_logger; let writable = if options.reset_log { OpenOptions::new() .write(true) .truncate(true) .create(true) .open(logger) } else { OpenOptions::new().append(true).create(true).open(logger) }; if let Err(ref e) = writable { Nagios::exit_critical(&format!( "unable to open or create log file {:?}, error {}", logger, e )); } match WriteLogger::init( options.logger_level, simplelog::ConfigBuilder::new() .set_time_format("%Y-%b-%d %H:%M:%S.%f".to_string()) .build(), writable.unwrap(), ) { Ok(_) => (),
ger size is: {} bytes", metadata.len()); if metadata.len() > options.max_logger_size { if let Err(e) = std::fs::remove_file(&logger) { if e.kind() != std::io::ErrorKind::NotFound { error!("unable to delete logger file: {:?}, error: {}", &logger, e); } } else { info!("deleting logger file {:?}", &logger); } } info!( "=============================> using configuration file: {:?}", &options.config_file ); info!("options: {:?}", &options); } pub fn load_snapshot( options: &CliOptions, config_snapshot_file: &Option<PathBuf>, ) -> (Snapshot, PathBuf) { let snapfile = if options.snapshot_file.is_some() { options.snapshot_file.as_ref().unwrap().clone() } else if config_snapshot_file.is_some() { let conf_file_or_dir = config_snapshot_file.as_ref().unwrap(); if conf_file_or_dir.is_dir() { Snapshot::build_name(&options.config_file, Some(conf_file_or_dir)) } else { conf_file_or_dir.clone() } } else { Snapshot::build_name(&options.config_file, None) }; if options.delete_snapfile { if let Err(e) = std::fs::remove_file(&snapfile) { if e.kind() != std::io::ErrorKind::NotFound { error!( "unable to delete snapshot file: {:?}, error: {}", &snapfile, e ); } } else { info!("deleting snapshot file {:?}", &snapfile); } } info!("using snapshot file:{}", &snapfile.display()); let snapshot = Snapshot::load(&snapfile) .expect_critical(&format!("unable to load snapshot file: {:?},", &snapfile)); info!( "loaded snapshot file {:?}, data = {:#?}", &snapfile, &snapshot ); (snapshot, snapfile) } pub fn save_snapshot(snapshot: &mut Snapshot, snapfile: &PathBuf, retention: u64) { debug!("saving snapshot file {}", &snapfile.display()); if let Err(e) = snapshot.save(&snapfile, retention) { Nagios::exit_critical(&format!( "unable to save snapshot file: {:?}, error: {}", &snapfile, e )); } } pub fn spawn_prescript(prescript: &Script, vars: Option<&GlobalVars>) -> u32 { let result = prescript.spawn(vars); if let Err(e) = &result { error!("error: {} spawning prescript: {:?}", e, prescript.command); Nagios::exit_critical(&format!( "error: {} spawning prescript: {:?}", e, prescript.command )); } debug_assert!(result.is_ok()); result.unwrap() } pub fn spawn_postscript(postscript: &mut Script, pids: &[u32]) { for pid in pids { postscript.command.push(pid.to_string()); } trace!("postscript: {:?}", &postscript.command); let result = postscript.spawn(None); if let Err(e) = &result { error!("error: {} spawning command: {:?}", e, postscript.command); } else { info!( "postcript command successfully executed, pid={}", result.unwrap() ) } }
Err(e) => { Nagios::exit_critical(&format!( "unable to create log file: {}, error: {}", logger.display(), e )); } }; let metadata = std::fs::metadata(&logger) .expect_critical(&format!("error on metadata() API, path {:?}", &logger)); debug!("current log
function_block-random_span
[ { "content": "/// Converts the error to string.\n\npub fn error_to_string<S>(value: &Option<AppError>, serializer: S) -> Result<S::Ok, S::Error>\n\nwhere\n\n S: Serializer,\n\n{\n\n if value.is_none() {\n\n \"None\".to_string().serialize(serializer)\n\n } else {\n\n format!(\"{}\", value.as_ref().unwrap()).serialize(serializer)\n\n }\n\n}\n\n\n\nimpl RunData {\n\n /// increment or decrement counters\n\n pub fn increment_counters(&mut self, pattern_type: &PatternType) {\n\n match pattern_type {\n\n PatternType::critical => self.counters.critical_count += 1,\n\n PatternType::warning => self.counters.warning_count += 1,\n\n PatternType::ok => self.counters.ok_count += 1,\n\n }\n\n }\n", "file_path": "src/logfile/rundata.rs", "rank": 5, "score": 116220.27036240642 }, { "content": "fn read_file<R: BufRead>(mut reader: R) {\n\n // our read buffer\n\n let mut buffer = Vec::with_capacity(1024);\n\n\n\n loop {\n\n let ret = reader.read_until(b'\\n', &mut buffer);\n\n if let Ok(bytes_read) = ret {\n\n if bytes_read == 0 {\n\n break;\n\n }\n\n }\n\n\n\n let line = String::from_utf8_lossy(&buffer);\n\n print!(\"{}\", line);\n\n\n\n buffer.clear();\n\n }\n\n}\n", "file_path": "src/uncompress.rs", "rank": 6, "score": 115515.90400778584 }, { "content": "/// Converts the timestamp to a human readable string in the snapshot.\n\npub fn timestamp_to_string<S>(value: &f64, serializer: S) -> Result<S::Ok, S::Error>\n\nwhere\n\n S: Serializer,\n\n{\n\n // exract integer part = number of seconds\n\n // frational part = number of nanoseconds\n\n let secs = value.trunc();\n\n let nanos = value.fract();\n\n let utc_tms = Utc.timestamp(secs as i64, (nanos * 1_000_000_000f64) as u32);\n\n format!(\"{}\", utc_tms.format(\"%Y-%m-%d %H:%M:%S.%f\")).serialize(serializer)\n\n}\n\n\n", "file_path": "src/logfile/rundata.rs", "rank": 8, "score": 105030.86432315195 }, { "content": "/// Replace the `logsource` YAML tag with the result of the script command\n\nfn fill_logdef<'de, D>(deserializer: D) -> Result<Vec<Search>, D::Error>\n\nwhere\n\n D: Deserializer<'de>,\n\n{\n\n // get the YAML `Value` from serde. See https://docs.serde.rs/serde_yaml/enum.Value.html\n\n let yaml_value: Value = Deserialize::deserialize(deserializer)?;\n\n\n\n // transform this value into our struct\n\n let vec_yaml: Result<Vec<Search>, _> =\n\n serde_yaml::from_value(yaml_value).map_err(de::Error::custom);\n\n if vec_yaml.is_err() {\n\n return vec_yaml;\n\n }\n\n let mut vec_search = vec_yaml.unwrap();\n\n\n\n // this vector wil hold new logfiles from the list returned from the script execution\n\n let mut vec_loglist: Vec<Search> = Vec::new();\n\n\n\n for search in &vec_search {\n\n match &search.logfile.path {\n", "file_path": "src/configuration/config.rs", "rank": 9, "score": 98774.85357198316 }, { "content": "fn main() {\n\n #[cfg(target_family = \"windows\")]\n\n {\n\n let path = std::env::var(\"PATH\").expect(\"unable to fetch %PATH%\");\n\n let new_path = format!(r\"{};.\\src\\windows\", path);\n\n std::env::set_var(\"PATH\", new_path);\n\n }\n\n}\n", "file_path": "build.rs", "rank": 10, "score": 98178.3037193997 }, { "content": "pub fn from_epoch_secs() -> AppResult<u64> {\n\n let from_epoch = from_epoch()?;\n\n Ok(from_epoch.as_secs())\n\n}\n", "file_path": "src/misc/util.rs", "rank": 11, "score": 93558.50707564664 }, { "content": "fn unwrap_failed(msg: &str, error: &dyn Debug) -> ! {\n\n Nagios::exit_critical(&format!(\"{}, error: {:?}\", msg, error))\n\n}\n\n\n\n#[cfg(test)]\n\nmod tests {\n\n use super::*;\n\n use std::path::PathBuf;\n\n\n\n #[test]\n\n #[cfg(target_family = \"unix\")]\n\n fn is_usable() {\n\n assert!(PathBuf::from(\"foo.txt\").is_usable().is_err());\n\n assert!(PathBuf::from(\"/var/log/foo.txt\").is_usable().is_err());\n\n assert!(PathBuf::from(\"/var/log\").is_usable().is_err());\n\n assert!(PathBuf::from(\"/etc/resolv.conf\").is_usable().is_ok());\n\n }\n\n\n\n #[test]\n\n #[cfg(target_family = \"windows\")]\n", "file_path": "src/misc/extension.rs", "rank": 12, "score": 88072.40913336136 }, { "content": "/// Returns the list of files from a spawned command.\n\npub trait ListFiles {\n\n fn get_file_list(&self) -> AppResult<Vec<PathBuf>>;\n\n}\n\n\n\nimpl ListFiles for String {\n\n // in this case, the command is started with either bash or cmd.exe\n\n fn get_file_list(&self) -> AppResult<Vec<PathBuf>> {\n\n // build the corresponding command\n\n #[cfg(target_family = \"unix\")]\n\n let output = Command::new(\"bash\")\n\n .args(&[\"-c\", self])\n\n .output()\n\n .map_err(|e| {\n\n context!(\n\n e,\n\n \"unable to read output from command: bash -c '{:?}'\",\n\n self,\n\n )\n\n })\n\n .unwrap();\n", "file_path": "src/misc/extension.rs", "rank": 13, "score": 85965.16348329233 }, { "content": "// manage error counters depending on options\n\nfn counters_calculation(counters: &mut PatternCounters, options: &SearchOptions) {\n\n // do we need to save our thresholds ?\n\n if options.savethresholds {\n\n // critical errors\n\n if options.criticalthreshold != 0 {\n\n if counters.critical_count < options.criticalthreshold {\n\n // nothing to do\n\n } else {\n\n // or just the delta\n\n counters.critical_count -= options.criticalthreshold;\n\n }\n\n }\n\n // warning errors\n\n if options.warningthreshold != 0 {\n\n // warning errors\n\n if counters.warning_count < options.warningthreshold {\n\n // nothing to do\n\n } else {\n\n // or just the delta\n\n counters.warning_count -= options.warningthreshold;\n", "file_path": "src/logfile/lookup.rs", "rank": 14, "score": 84597.18690021268 }, { "content": "/// A custom deserializer for the `exclude` field.\n\nfn to_regex<'de, D>(deserializer: D) -> Result<Option<Regex>, D::Error>\n\nwhere\n\n D: Deserializer<'de>,\n\n{\n\n let v: Value = Deserialize::deserialize(deserializer)?;\n\n //println!(\"v= {:?}\", v);\n\n let re = Regex::new(v.as_str().unwrap()).map_err(de::Error::custom)?;\n\n Ok(Some(re))\n\n}\n\n\n\n#[cfg(test)]\n\n#[cfg(target_family = \"unix\")]\n\nmod tests {\n\n use super::*;\n\n\n\n #[test]\n\n #[cfg(target_os = \"linux\")]\n\n fn logfiledef() {\n\n let mut yaml = r#\"\n\npath: /var/log/syslog\n", "file_path": "src/configuration/logfiledef.rs", "rank": 15, "score": 76489.70420801152 }, { "content": "// This method is common to all compression ad-hoc seek method.\n\nfn _set_offset<R>(mut reader: R, offset: u64) -> AppResult<u64>\n\nwhere\n\n R: Read,\n\n{\n\n // if 0, nothing to do\n\n if offset == 0 {\n\n return Ok(0);\n\n }\n\n\n\n let pos = match reader.by_ref().bytes().nth((offset - 1) as usize) {\n\n None => {\n\n return Err(AppError::new_custom(\n\n AppCustomErrorKind::SeekPosBeyondEof,\n\n &format!(\"tried to set offset beyond EOF, at offset: {}\", offset),\n\n ))\n\n }\n\n Some(x) => x,\n\n };\n\n Ok(pos.unwrap() as u64)\n\n}\n", "file_path": "src/logfile/seeker.rs", "rank": 16, "score": 76431.15520829981 }, { "content": "#!/usr/bin/perl\n\n\n\n# just fetch the relevant environment variable from arguments\n\n# and create a logfile\n\nuse strict;\n\nuse warnings;\n\n \n\n # create the file from fetch env variable\n\nmy $filename = '/tmp/concatenated.log.sh';\n\nopen(my $fh, '>', $filename) or die \"Could not open file '$filename' $!\";\n\nprint $ENV{'my_awesomescript'};\n\nprint $fh $ENV{'my_awesomescript'};\n\nclose $fh;\n\n\n\n# now just run file\n\nchmod 0744, $filename;\n\n\n\n# run it\n\nmy $exit_code = system($filename);\n\nexit($exit_code);\n\n\n\n\n\n\n", "file_path": "tests/integration/callbacks/create_file.pl", "rank": 17, "score": 66450.37037778817 }, { "content": "# a class for managing creating of YAML config file\n\nclass Config\n", "file_path": "tests/integration/ruby/testcase.rb", "rank": 18, "score": 58901.587557446066 }, { "content": " def create_log(append=false)\n\n FakeLogfile.create(@logfile)\n\n end\n\n\n", "file_path": "tests/integration/ruby/testcase.rb", "rank": 19, "score": 58835.5468160777 }, { "content": "/// The main entry point.\n\nfn main() {\n\n //---------------------------------------------------------------------------------------------------\n\n // set up variables\n\n //---------------------------------------------------------------------------------------------------\n\n\n\n // tick time\n\n let now = Instant::now();\n\n\n\n // create a vector of thread handles for keeping track of what we've created and\n\n // wait for them to finish\n\n let mut children_list: Vec<ChildData> = Vec::new();\n\n\n\n // manage arguments from command line\n\n let options = CliOptions::options();\n\n\n\n // store all logfile access errors\n\n let mut access_errors = LogFileAccessErrorList::default();\n\n\n\n //---------------------------------------------------------------------------------------------------\n\n // initialize logger\n", "file_path": "src/clf.rs", "rank": 20, "score": 58191.608009631906 }, { "content": "fn main() {\n\n println!(\"Hello, world!\");\n\n}\n", "file_path": "src/main.rs", "rank": 21, "score": 58191.608009631906 }, { "content": "fn main() {\n\n let matches = App::new(\"Uncompress gzip, bzip2, xz files\")\n\n .version(\"0.1\")\n\n .author(\"Alain Viguier [email protected]\")\n\n .about(r#\"An executable to read compressed files using compression methods defined in the crate\"#)\n\n .arg(\n\n Arg::new(\"file\")\n\n .long_about(\"Name of the file to read.\")\n\n .short('f')\n\n .long(\"file\")\n\n .required(true)\n\n .takes_value(true),\n\n ) .get_matches();\n\n\n\n // get file name\n\n let path = PathBuf::from(matches.value_of(\"file\").unwrap());\n\n let file = File::open(&path).expect(&format!(\"unable to open file {:?}\", &path));\n\n\n\n // get file extension\n\n let extension = path.extension().map(|x| x.to_string_lossy().to_string());\n", "file_path": "src/uncompress.rs", "rank": 22, "score": 58191.608009631906 }, { "content": "fn main() {\n\n let vars: Vec<(String, String)> = std::env::vars()\n\n .filter(|x| x.0.as_str().starts_with(\"CLF_\"))\n\n .collect();\n\n\n\n let args: Vec<String> = env::args().collect();\n\n\n\n let mut file = OpenOptions::new()\n\n .create(true)\n\n .write(true)\n\n .append(true)\n\n .open(&args[1])\n\n .unwrap();\n\n\n\n let _ = write!(file, \"{}-{:?}\\n\", std::process::id(), vars);\n\n}\n", "file_path": "tests/integration/echovars.rs", "rank": 23, "score": 56563.04405891852 }, { "content": "/// Used to defined functions to set a precise offset in a file, either being compressed or not.\n\npub trait Seeker {\n\n /// Simulates the `seek`method for all used `BufReader<R>`.\n\n fn set_offset(&mut self, offset: u64) -> AppResult<u64>;\n\n}\n\n\n\nimpl Seeker for BufReader<File> {\n\n #[inline(always)]\n\n fn set_offset(&mut self, offset: u64) -> AppResult<u64> {\n\n let pos = self\n\n .seek(SeekFrom::Start(offset))\n\n .map_err(|e| context!(e, \"error seeking file {:?} for offset {}\", self, offset))?;\n\n Ok(pos)\n\n }\n\n}\n\n\n\n/// Implementing for `R: Read` helps testing wuth `Cursor` type.\n\nimpl<R> Seeker for BufReader<GzDecoder<R>>\n\nwhere\n\n R: Read,\n\n{\n", "file_path": "src/logfile/seeker.rs", "rank": 24, "score": 55502.330402066116 }, { "content": "fn main() {\n\n // manage cli arguments\n\n let matches = App::new(\"Log files reader\")\n\n .version(\"0.1\")\n\n .author(\"Alain Viguier [email protected]\")\n\n .about(r#\"Run intergation tests with clf\"#)\n\n .arg(\n\n Arg::new(\"mode\")\n\n .short('m')\n\n .long(\"mode\")\n\n .required(false)\n\n .long_about(\"Debug or release\")\n\n .possible_values(&[\"debug\", \"release\"])\n\n .takes_value(true),\n\n )\n\n .arg(\n\n Arg::new(\"verbose\")\n\n .short('v')\n\n .long(\"verbose\")\n\n .required(false)\n", "file_path": "tests/integration/integration_test.rs", "rank": 25, "score": 55075.151286789915 }, { "content": "/// All `PathBuf` utility functions.\n\npub trait ReadFs {\n\n fn is_match(self, re: &Regex) -> bool;\n\n fn is_usable(&self) -> AppResult<()>;\n\n fn list_files(&self, regex: &str) -> AppResult<Vec<PathBuf>>;\n\n fn signature(&self, hash_buffer_size: usize) -> AppResult<Signature>;\n\n}\n\n\n\nimpl ReadFs for PathBuf {\n\n /// `true` if the path matches the regex\n\n fn is_match(self, re: &Regex) -> bool {\n\n // converts file name to a string\n\n let s = self.into_os_string();\n\n re.is_match(&s.to_string_lossy())\n\n }\n\n\n\n /// Tells whether a `PathBuf` is accessible i.e. it combines `has_root()`, `exists()` and `is_file()`. \n\n fn is_usable(&self) -> AppResult<()> {\n\n // first canonicalize path\n\n let canon = self\n\n .canonicalize()\n", "file_path": "src/misc/extension.rs", "rank": 26, "score": 54123.82263603198 }, { "content": "// helper functions to exit in case of error\n\npub trait Expect<T> {\n\n fn expect_critical(self, text: &str) -> T;\n\n}\n\n\n\nimpl<T, E: Debug> Expect<T> for std::result::Result<T, E> {\n\n fn expect_critical(self, msg: &str) -> T {\n\n match self {\n\n Ok(inner) => inner,\n\n Err(e) => unwrap_failed(msg, &e),\n\n }\n\n }\n\n}\n", "file_path": "src/misc/extension.rs", "rank": 27, "score": 52558.25964342141 }, { "content": "pub trait Lookup<T> {\n\n fn reader<R: BufRead + Seeker>(\n\n &mut self,\n\n reader: R,\n\n tag: &Tag,\n\n global_options: &GlobalOptions,\n\n ) -> AppResult<Vec<ChildData>>;\n\n}\n\n\n\n/// A unit struct to represent a reader which is not calling any script but just scans the logfile and outputs matched lines.\n\npub struct BypassReader;\n\n\n\n/// A unit struct to represent a reader which reads each line, tests for a match and called a callback.\n\npub struct FullReader;\n\n\n\n// this will call the relevant reader\n\n#[derive(Debug, PartialEq)]\n\npub enum ReaderCallType {\n\n BypassReaderCall,\n\n FullReaderCall,\n", "file_path": "src/logfile/lookup.rs", "rank": 28, "score": 52554.04789902897 }, { "content": "// utility functions to get the number of seconds from 1/1/1970\n\nfn from_epoch() -> AppResult<Duration> {\n\n SystemTime::now()\n\n .duration_since(SystemTime::UNIX_EPOCH)\n\n .map_err(|e| context!(e, \"duration_since() error\",))\n\n}\n\n\n", "file_path": "src/misc/util.rs", "rank": 29, "score": 49354.273618951505 }, { "content": "fn main() -> std::io::Result<()> {\n\n #[cfg(target_family = \"unix\")]\n\n {\n\n let args: Vec<String> = env::args().collect();\n\n let mut file: Option<File> = None;\n\n\n\n // one argument is mandatory: address and port\n\n let addr = &args[1];\n\n let _ = std::fs::remove_file(&addr);\n\n\n\n if args.len() == 3 {\n\n file = Some(File::create(&args[2]).unwrap());\n\n }\n\n\n\n let listener = std::os::unix::net::UnixListener::bind(addr).unwrap();\n\n println!(\"waiting on address: {}\", addr);\n\n match listener.accept() {\n\n Ok((mut socket, _addr)) => {\n\n // set short timeout\n\n // socket\n", "file_path": "tests/integration/echodomain.rs", "rank": 30, "score": 48108.87564967837 }, { "content": "fn main() -> std::io::Result<()> {\n\n let args: Vec<String> = env::args().collect();\n\n let mut file: Option<File> = None;\n\n\n\n // one argument is mandatory: address and port\n\n let addr = &args[1];\n\n\n\n if args.len() == 3 {\n\n file = Some(File::create(&args[2]).unwrap());\n\n }\n\n\n\n let listener = std::net::TcpListener::bind(addr).unwrap();\n\n println!(\"waiting on address: {}\", addr);\n\n match listener.accept() {\n\n Ok((mut socket, _addr)) => {\n\n // set short timeout\n\n // socket\n\n // .set_read_timeout(Some(std::time::Duration::new(3, 0)))\n\n // .expect(\"Couldn't set read timeout\");\n\n\n", "file_path": "tests/integration/echotcp.rs", "rank": 31, "score": 48108.87564967837 }, { "content": "/// Manage end of all started processes from clf.\n\nfn wait_children(children_list: Vec<ChildData>) {\n\n // just wait a little for all commands to finish. Otherwise, the last process will not be considered to be finished.\n\n if !children_list.is_empty() {\n\n let wait_timeout = std::time::Duration::from_millis(1000);\n\n thread::sleep(wait_timeout);\n\n }\n\n\n\n // as child can be None in case of Tcp or Domain socket, need to get rid of these\n\n for (i, started_child) in children_list\n\n .iter()\n\n .filter(|x| x.child.is_some())\n\n .enumerate()\n\n {\n\n // get a mutable reference\n\n let mut child = started_child.child.as_ref().unwrap().borrow_mut();\n\n\n\n // save pid & path\n\n let pid = child.id();\n\n let path = &started_child.path;\n\n\n", "file_path": "src/clf.rs", "rank": 32, "score": 45874.0691048235 }, { "content": "// send data through Tcp or Unix stream\n\nfn send_json_data<T: Write, U: Debug>(\n\n args: &Option<Vec<String>>,\n\n mut stream: T,\n\n global_vars: &GlobalVars,\n\n runtime_vars: &RuntimeVars,\n\n first_time: bool,\n\n addr: U,\n\n) -> AppResult<Option<ChildData>> {\n\n // create a dedicated JSON structure\n\n let mut json = match args {\n\n Some(args) => {\n\n if first_time {\n\n json!({\n\n \"args\": &args,\n\n \"global\": global_vars,\n\n \"vars\": runtime_vars\n\n })\n\n } else {\n\n json!({\n\n //\"args\": &args,\n", "file_path": "src/configuration/callback.rs", "rank": 33, "score": 43783.464121940066 }, { "content": " let mut logger_path = std::env::current_dir().unwrap_or_else(|_| std::env::temp_dir());\n\n logger_path.push(\"clf.log\");\n\n\n\n GlobalOptions {\n\n script_path: path_var,\n\n output_dir: std::env::temp_dir(),\n\n snapshot_file: None,\n\n snapshot_retention: DEFAULT_RETENTION,\n\n global_vars: HashMap::new(),\n\n prescript: None,\n\n postscript: None,\n\n }\n\n }\n\n}\n\n\n\n#[cfg(test)]\n\n#[cfg(target_family = \"unix\")]\n\nmod tests {\n\n use super::*;\n\n use std::str::FromStr;\n", "file_path": "src/configuration/global.rs", "rank": 34, "score": 36310.6947083626 }, { "content": "//! Contains the global configuration when processing logfiles. These values are independant from the ones solely related to a logfile when searching.\n\nuse std::collections::HashMap;\n\nuse std::path::{Path, PathBuf};\n\n\n\nuse serde::Deserialize;\n\n\n\nuse crate::configuration::{script::Script, vars::GlobalVars};\n\nuse crate::misc::util::*;\n\n\n\nuse crate::{fromstr, prefix_var};\n\n#[derive(Debug, Deserialize, Clone)]\n\n/// A list of global options, which apply globally for all searches.\n\n#[serde(default)]\n\n#[serde(deny_unknown_fields)]\n\npub struct GlobalOptions {\n\n /// A list of paths, separated by either ':' for unix, or ';' for Windows. This is\n\n /// where the script, if any, will be searched for. Default to PATH or Path depending on the platform.\n\n pub script_path: String,\n\n\n\n /// A directory where matched lines will be stored.\n", "file_path": "src/configuration/global.rs", "rank": 35, "score": 36308.65958122755 }, { "content": " /// Add variables like user, platform etc not dependant from a logfile\n\n pub fn insert_process_vars<P: AsRef<Path>>(&mut self, path: P) {\n\n // add config file name\n\n self.global_vars.insert(\n\n prefix_var!(\"CONFIG_FILE\").to_string(),\n\n path.as_ref().to_string_lossy().to_string(),\n\n );\n\n\n\n // now just add variables\n\n self.global_vars\n\n .insert(prefix_var!(\"USER\").to_string(), whoami::username());\n\n self.global_vars\n\n .insert(prefix_var!(\"HOSTNAME\").to_string(), whoami::hostname());\n\n self.global_vars.insert(\n\n prefix_var!(\"PLATFORM\").to_string(),\n\n whoami::platform().to_string(),\n\n );\n\n }\n\n\n\n /// Add optional extra global variables coming from the command line\n", "file_path": "src/configuration/global.rs", "rank": 36, "score": 36306.75516450528 }, { "content": " pub output_dir: PathBuf,\n\n\n\n /// The snapshot file name. Option<> is used because if not specified here,\n\n pub snapshot_file: Option<PathBuf>,\n\n\n\n /// Retention time for tags.\n\n pub snapshot_retention: u64,\n\n\n\n /// A list of user variables if any.\n\n #[serde(rename = \"vars\")]\n\n pub global_vars: GlobalVars,\n\n\n\n // A command called before starting reading\n\n pub prescript: Option<Vec<Script>>,\n\n\n\n // A command called before the end of clf\n\n pub postscript: Option<Script>,\n\n}\n\n\n\nimpl GlobalOptions {\n", "file_path": "src/configuration/global.rs", "rank": 37, "score": 36306.15765181085 }, { "content": "\n\n #[test]\n\n fn global_options() {\n\n let mut yaml = r#\"\n\nscript_path: /usr/foo1\n\nsnapshot_file: /usr/foo3/snap.foo\n\noutput_dir: /usr/foo2\n\n \"#;\n\n\n\n let mut opts = GlobalOptions::from_str(yaml).expect(\"unable to read YAML\");\n\n //println!(\"opts={:?}\", opts);\n\n\n\n assert_eq!(&opts.script_path, \"/usr/foo1\");\n\n assert_eq!(opts.output_dir, PathBuf::from(\"/usr/foo2\"));\n\n assert_eq!(\n\n opts.snapshot_file,\n\n Some(PathBuf::from(\"/usr/foo3/snap.foo\"))\n\n );\n\n\n\n yaml = r#\"\n", "file_path": "src/configuration/global.rs", "rank": 38, "score": 36304.98773603199 }, { "content": " pub fn insert_extra_vars(&mut self, vars: &Option<Vec<String>>) {\n\n if vars.is_some() {\n\n let vars = vars.as_ref().unwrap();\n\n\n\n // each var should have this form: 'var:value'\n\n for var in vars {\n\n // split at char ':'\n\n let splitted: Vec<&str> = var.split(':').collect();\n\n\n\n // if we don't find the equals sign just loop\n\n if splitted.len() != 2 {\n\n continue;\n\n }\n\n\n\n // now it's safe to insert\n\n self.global_vars\n\n .insert(splitted[0].to_string(), splitted[1].to_string());\n\n }\n\n }\n\n }\n", "file_path": "src/configuration/global.rs", "rank": 39, "score": 36304.19436697318 }, { "content": "script_path: /usr/foo1\n\n\n\n# a list of user variables, if any\n\nvars:\n\n first_name: Al\n\n last_name: Pacino\n\n city: 'Los Angeles'\n\n profession: actor \n\n \"#;\n\n\n\n opts = GlobalOptions::from_str(yaml).expect(\"unable to read YAML\");\n\n assert_eq!(&opts.script_path, \"/usr/foo1\");\n\n assert_eq!(opts.output_dir, PathBuf::from(\"/tmp\"));\n\n assert_eq!(opts.snapshot_file, None);\n\n\n\n let vars = opts.global_vars;\n\n assert_eq!(vars.get(\"first_name\").unwrap(), \"Al\");\n\n assert_eq!(vars.get(\"last_name\").unwrap(), \"Pacino\");\n\n assert_eq!(vars.get(\"city\").unwrap(), \"Los Angeles\");\n\n assert_eq!(vars.get(\"profession\").unwrap(), \"actor\");\n\n }\n\n}\n", "file_path": "src/configuration/global.rs", "rank": 40, "score": 36299.46000941698 }, { "content": "}\n\n\n\n// Auto-implement FromStr\n\nfromstr!(GlobalOptions);\n\n\n\n/// Default implementation, rather than serde default field attribute.\n\nimpl Default for GlobalOptions {\n\n fn default() -> Self {\n\n // default path\n\n let path_var = if cfg!(target_family = \"unix\") {\n\n std::env::var(\"PATH\").unwrap_or_else(|_| \"/usr/sbin:/usr/bin:/sbin:/bin\".to_string())\n\n } else if cfg!(target_family = \"windows\") {\n\n std::env::var(\"Path\").unwrap_or_else(|_| {\n\n r\"C:\\Windows\\system32;C:\\Windows;C:\\Windows\\System32\\Wbem;\".to_string()\n\n })\n\n } else {\n\n unimplemented!(\"unsupported OS, file: {}:{}\", file!(), line!());\n\n };\n\n\n\n // default logger path\n", "file_path": "src/configuration/global.rs", "rank": 41, "score": 36297.403123175696 }, { "content": " yaml.searches.len()\n\n );\n\n Ok(yaml)\n\n }\n\n\n\n /// Loads a YAML configuration file as a `Config` struct. Not using Tera\n\n #[cfg(not(feature = \"tera\"))]\n\n pub fn from_path<P: AsRef<Path> + std::fmt::Debug>(file_name: P) -> AppResult<Config> {\n\n // open YAML file\n\n let file = std::fs::File::open(&file_name)\n\n .map_err(|e| context!(e, \"unable to read configuration file: {:?}\", &file_name))?;\n\n\n\n // load YAML data\n\n let yaml: Config = serde_yaml::from_reader(file)\n\n .map_err(|e| context!(e, \"error reading configuration file {:?}\", file_name))?;\n\n debug!(\n\n \"sucessfully loaded YAML configuration file, nb_searches={}\",\n\n yaml.searches.len()\n\n );\n\n\n\n Ok(yaml)\n\n }\n\n}\n\n\n\n/// Replace the `logsource` YAML tag with the result of the script command\n", "file_path": "src/configuration/config.rs", "rank": 42, "score": 36219.393053973065 }, { "content": "fromstr!(Config);\n\n\n\nimpl Config {\n\n /// Loads a YAML configuration file as a `Config` struct, Tera version\n\n #[cfg(feature = \"tera\")]\n\n pub fn from_path<P: AsRef<Path> + std::fmt::Debug>(\n\n file_name: P,\n\n context: Option<&str>,\n\n show_rendered: bool,\n\n ) -> AppResult<Config> {\n\n use tera::{Context, Tera, Value};\n\n\n\n // read the whole file into a string\n\n let config = std::fs::read_to_string(&file_name)\n\n .map_err(|e| context!(e, \"unable to read configuration file: {:?}\", &file_name))?;\n\n\n\n // load context or create context if specified from arguments\n\n let context = if let Some(ctx) = context {\n\n let json: Value = serde_json::from_str(ctx)\n\n .map_err(|e| context!(e, \"unable to context from JSON string {}\", ctx))?;\n", "file_path": "src/configuration/config.rs", "rank": 43, "score": 36215.962522334084 }, { "content": "//! Holds the whole configuration data, loaded from a YAML file.\n\n//!\n\n//! This YAML file is divided into 2 parts:\n\n//!\n\n//! * a `global` YAML structure mapping the `Global` Rust structure which holds options which apply for each search\n\n//! * an array of searches (the `searches`) tag which describes which files to search for, and the patterns which might\n\n//! trigger a match.\n\n//!\n\n//! The logfile could either be an accessible file path, or a command which will be executed and gets back a list of files.\n\nuse std::path::Path;\n\n\n\nuse log::debug;\n\nuse serde::{de, Deserialize, Deserializer};\n\nuse serde_yaml::Value;\n\n\n\nuse super::{global::GlobalOptions, logsource::LogSource, search::Search};\n\n\n\nuse crate::misc::{\n\n error::{AppError, AppResult},\n\n extension::ListFiles,\n", "file_path": "src/configuration/config.rs", "rank": 44, "score": 36215.69472292969 }, { "content": "\n\n // create context from JSON string\n\n Context::from_value(json).expect(\"unable to add context\")\n\n } else {\n\n Context::new()\n\n };\n\n\n\n // render the config with Tera context\n\n let rendered = Tera::one_off(&config, &context, false).expect(\"error one_off\");\n\n if show_rendered {\n\n println!(\"{}\", rendered);\n\n std::process::exit(0);\n\n }\n\n\n\n // load YAML data\n\n let yaml: Config = serde_yaml::from_str(&rendered)\n\n .map_err(|e| context!(e, \"error in reading configuration file {:?}\", file_name))?;\n\n\n\n debug!(\n\n \"sucessfully loaded YAML configuration file, nb_searches={}\",\n", "file_path": "src/configuration/config.rs", "rank": 45, "score": 36213.99394287849 }, { "content": "\n\n // we found a logcommand tag: get the list of files using bash -c or cmd.exe /B, and for each one, copy everything\n\n LogSource::LogCommand(cmd) => {\n\n // get list of files from command or script\n\n let files = cmd.get_file_list().map_err(de::Error::custom)?;\n\n\n\n // create Search structure with the files we found, and a clone of all tags\n\n for file in &files {\n\n // clone search structure\n\n let mut cloned_search = search.clone();\n\n\n\n // assign file instead of list\n\n cloned_search.logfile.path = LogSource::LogFile(file.to_path_buf());\n\n\n\n // now use this structure and add it to config_pathbuf\n\n vec_loglist.push(cloned_search);\n\n }\n\n }\n\n }\n\n }\n", "file_path": "src/configuration/config.rs", "rank": 46, "score": 36213.65684179012 }, { "content": " // we found a logfile tag: just copy everything to the new structure\n\n LogSource::LogFile(_) => continue,\n\n\n\n // we found a logslist tag: get the list of files, and for each one, copy everything\n\n LogSource::LogList(cmd) => {\n\n // get list of files from command or script\n\n let files = cmd.get_file_list().map_err(de::Error::custom)?;\n\n\n\n // create Search structure with the files we found, and a clone of all tags\n\n for file in &files {\n\n // clone search structure\n\n let mut cloned_search = search.clone();\n\n\n\n // assign file instead of list\n\n cloned_search.logfile.path = LogSource::LogFile(file.to_path_buf());\n\n\n\n // now use this structure and add it to config_pathbuf\n\n vec_loglist.push(cloned_search);\n\n }\n\n }\n", "file_path": "src/configuration/config.rs", "rank": 47, "score": 36212.86388878376 }, { "content": "};\n\n\n\nuse crate::{context, fromstr};\n\n\n\n/// The main search configuration used to search patterns in a logfile. This is loaded from\n\n/// the YAML file found in the command line argument (or from stdin). This configuration can include a list\n\n/// of logfiles (given either by name or by starting an external command) to lookup and for each logfile, a list of regexes to match.\n\n#[derive(Debug, Deserialize, Default)]\n\n#[serde(deny_unknown_fields)]\n\npub struct Config {\n\n /// List of global options, which apply for all searches.\n\n #[serde(default = \"GlobalOptions::default\")]\n\n pub global: GlobalOptions,\n\n\n\n /// list of searches.\n\n #[serde(deserialize_with = \"fill_logdef\")]\n\n pub searches: Vec<Search>,\n\n}\n\n\n\n// Auto-implement FromStr\n", "file_path": "src/configuration/config.rs", "rank": 48, "score": 36212.482797302815 }, { "content": " exceptions: [\n\n '^\\d{2,3}\\.'\n\n ]\n\n } \n\n \"#;\n\n let config: Config = serde_yaml::from_str(yaml).expect(\"unable to read YAML\");\n\n\n\n assert_eq!(\n\n &config.global.script_path,\n\n \"/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin\"\n\n );\n\n assert_eq!(config.global.output_dir, PathBuf::from(\"/tmp/foo\"));\n\n assert_eq!(\n\n config.global.snapshot_file,\n\n Some(PathBuf::from(\"/tmp/my_snapshot.json\"))\n\n );\n\n assert_eq!(config.global.snapshot_retention, 5);\n\n assert_eq!(&config.global.global_vars.get(\"first_name\").unwrap(), &\"Al\");\n\n assert_eq!(\n\n &config.global.global_vars.get(\"last_name\").unwrap(),\n", "file_path": "src/configuration/config.rs", "rank": 49, "score": 36207.51754959538 }, { "content": " &\"Pacino\"\n\n );\n\n assert_eq!(\n\n &config.global.global_vars.get(\"city\").unwrap(),\n\n &\"Los Angeles\"\n\n );\n\n assert_eq!(\n\n &config.global.global_vars.get(\"profession\").unwrap(),\n\n &\"actor\"\n\n );\n\n assert_eq!(config.searches.len(), 1);\n\n\n\n let search = config.searches.first().unwrap();\n\n assert_eq!(\n\n search.logfile.path(),\n\n &PathBuf::from(\"tests/logfiles/small_access.log\")\n\n );\n\n assert_eq!(search.tags.len(), 1);\n\n\n\n let tag = search.tags.first().unwrap();\n", "file_path": "src/configuration/config.rs", "rank": 50, "score": 36204.64357176378 }, { "content": "\n\n // add all those new logfiles we found\n\n vec_search.extend(vec_loglist);\n\n\n\n // keep only valid logfiles, not logsources\n\n vec_search.retain(|x| x.logfile.path.is_path());\n\n Ok(vec_search)\n\n}\n\n\n\n#[cfg(test)]\n\n#[cfg(target_family = \"unix\")]\n\nmod tests {\n\n use super::*;\n\n use std::path::PathBuf;\n\n\n\n #[test]\n\n fn config() {\n\n dbg!(std::env::current_dir().unwrap());\n\n let yaml = r#\"\n\n global:\n", "file_path": "src/configuration/config.rs", "rank": 51, "score": 36202.433963680945 }, { "content": " script_path: \"/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin\"\n\n output_dir: /tmp/foo\n\n snapshot_file: /tmp/my_snapshot.json\n\n snapshot_retention: 5\n\n vars:\n\n first_name: Al\n\n last_name: Pacino\n\n city: 'Los Angeles'\n\n profession: actor\n\n \n\n searches:\n\n - logfile: \n\n path: tests/logfiles/small_access.log\n\n format: plain\n\n exclude: '^error'\n\n archive: \n\n dir: /var/log\n\n extension: gz\n\n tags: \n\n - name: http_access_get_or_post\n", "file_path": "src/configuration/config.rs", "rank": 52, "score": 36201.53541333638 }, { "content": " format: plain\n\n exclude: '^error'\n\n archive: \n\n dir: /var/log\n\n extension: gz\n\n tags: \n\n - name: http_access_get_or_post\n\n process: true\n\n options: \"warningthreshold=0\"\n\n callback: { script: \"tests/callbacks/echovars.py\", args: ['arg1', 'arg2', 'arg3'] }\n\n patterns:\n\n critical: {\n\n regexes: [\n\n 'GET\\s+([/\\w]+)\\s+HTTP/1\\.1\"\\s+(?P<code>\\d+)\\s+(?P<length>\\d+)',\n\n ],\n\n }\n\n warning: {\n\n regexes: [\n\n 'POST\\s+([/\\w\\.]+)\\s+HTTP/1\\.1\"\\s+(?P<code>\\d+)\\s+(?P<length>\\d+)'\n\n ],\n", "file_path": "src/configuration/config.rs", "rank": 53, "score": 36198.310569241235 }, { "content": " process: true\n\n options: \"warningthreshold=0\"\n\n callback: { script: \"tests/callbacks/echovars.py\", args: ['arg1', 'arg2', 'arg3'] }\n\n patterns:\n\n critical: {\n\n regexes: [\n\n 'GET\\s+([/\\w]+)\\s+HTTP/1\\.1\"\\s+(?P<code>\\d+)\\s+(?P<length>\\d+)',\n\n ],\n\n }\n\n warning: {\n\n regexes: [\n\n 'POST\\s+([/\\w\\.]+)\\s+HTTP/1\\.1\"\\s+(?P<code>\\d+)\\s+(?P<length>\\d+)'\n\n ],\n\n exceptions: [\n\n '^\\d{2,3}\\.'\n\n ]\n\n }\n\n\n\n - logfile: \n\n list: ['/usr/bin/find', '/var/log', '-type', '-f']\n", "file_path": "src/configuration/config.rs", "rank": 54, "score": 36195.48155291872 }, { "content": " assert_eq!(&tag.name, \"http_access_get_or_post\");\n\n assert!(tag.process);\n\n assert_eq!(tag.options.warningthreshold, 0);\n\n assert!(tag.callback.is_some());\n\n let script = PathBuf::from(\"tests/callbacks/echovars.py\");\n\n assert!(\n\n matches!(&tag.callback.as_ref().unwrap().callback, crate::configuration::callback::CallbackType::Script(Some(x)) if x == &script)\n\n );\n\n assert_eq!(\n\n tag.callback.as_ref().unwrap().args.as_ref().unwrap(),\n\n &[\"arg1\", \"arg2\", \"arg3\"]\n\n );\n\n assert!(tag.patterns.ok.is_none());\n\n assert!(tag.patterns.critical.is_some());\n\n assert!(tag.patterns.warning.is_some());\n\n }\n\n}\n", "file_path": "src/configuration/config.rs", "rank": 55, "score": 36194.96525326678 }, { "content": "//! All structures involved in error management. It combines a list a Rust standard library\n\n//! error types, used crates error types and a specific one to the application.\n\n//! Use `map_err` method to report errors with context (see examples in tests).\n\nuse std::clone::Clone;\n\nuse std::{fmt, io, num};\n\n\n\n/// A specific custom `Result` for all functions\n\npub type AppResult<T> = Result<T, AppError>;\n\n\n\n/// Error kind specific to an application error, different from standard errors.\n\n#[derive(Debug, PartialEq)]\n\npub enum AppCustomErrorKind {\n\n SeekPosBeyondEof,\n\n UnsupportedPatternType,\n\n FileNotUsable,\n\n FilePathNotAbsolute,\n\n UnsupportedSearchOption,\n\n OsStringConversionError,\n\n FileSizeIsLessThanHashWindow,\n\n PhantomCloneError,\n", "file_path": "src/misc/error.rs", "rank": 56, "score": 36183.833041591606 }, { "content": " let file = File::open(path).map_err(|e| context!(e, \"unable to open file {}\", path))?;\n\n Ok(file)\n\n }\n\n\n\n #[cfg(target_family = \"windows\")]\n\n fn file() -> AppResult<File> {\n\n let path = r\"c:\\foo\\foo.foo\";\n\n let file = File::open(path).map_err(|e| context!(e, \"unable to open file {}\", path))?;\n\n Ok(file)\n\n }\n\n\n\n fn regex() -> AppResult<Regex> {\n\n let s = \"foo(\";\n\n let re = Regex::new(s).map_err(|e| context!(e, \"unable to create regex {}\", s))?;\n\n Ok(re)\n\n }\n\n\n\n fn parse() -> AppResult<usize> {\n\n let s = \"18a\";\n\n let value = s\n", "file_path": "src/misc/error.rs", "rank": 57, "score": 36183.63906429993 }, { "content": " #[cfg(target_family = \"windows\")]\n\n WindowsApiError,\n\n}\n\n\n\nimpl fmt::Display for AppCustomErrorKind {\n\n fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {\n\n match self {\n\n AppCustomErrorKind::SeekPosBeyondEof => {\n\n write!(f, \"a seek operation was beyond end of file\")\n\n }\n\n AppCustomErrorKind::UnsupportedPatternType => {\n\n write!(f, \"the specified type of pattern is not supported\")\n\n }\n\n AppCustomErrorKind::FileNotUsable => {\n\n write!(f, \"file is not a file, probably a directory\")\n\n }\n\n AppCustomErrorKind::FilePathNotAbsolute => write!(f, \"the file path is not absolute\"),\n\n AppCustomErrorKind::UnsupportedSearchOption => write!(f, \"search option not supported\"),\n\n AppCustomErrorKind::FileSizeIsLessThanHashWindow => {\n\n write!(f, \"file size is lass than hash window\")\n", "file_path": "src/misc/error.rs", "rank": 58, "score": 36180.56599557414 }, { "content": "from_error!(num::ParseIntError, InternalError::Parse);\n\nfrom_error!(std::str::Utf8Error, InternalError::Utf8);\n\n\n\n/// Custom error which will be used for all errors conversions and throughout the code.\n\n#[derive(Debug)]\n\npub struct AppError {\n\n pub error_kind: InternalError,\n\n pub msg: String,\n\n}\n\n\n\nimpl AppError {\n\n /// A simple and convenient creation of a new application error\n\n pub fn new_custom(kind: AppCustomErrorKind, msg: &str) -> Self {\n\n AppError {\n\n error_kind: InternalError::Custom(kind),\n\n msg: msg.to_string(),\n\n }\n\n }\n\n\n\n /// Convert from an internal error\n", "file_path": "src/misc/error.rs", "rank": 59, "score": 36179.85041899998 }, { "content": " let err = systemtime().unwrap_err();\n\n assert!(matches!(err.error_kind, InternalError::SystemTime(_)));\n\n println!(\"{}\", err);\n\n\n\n let err = utf8().unwrap_err();\n\n assert!(matches!(err.error_kind, InternalError::Utf8(_)));\n\n println!(\"{}\", err);\n\n\n\n let err = custom();\n\n assert!(matches!(err.error_kind, InternalError::Custom(_)));\n\n println!(\"{}\", err);\n\n\n\n assert!(\n\n matches!(err.clone().error_kind, InternalError::Custom(x) if x == AppCustomErrorKind::PhantomCloneError)\n\n );\n\n }\n\n\n\n #[cfg(target_family = \"unix\")]\n\n fn file() -> AppResult<File> {\n\n let path = \"/foo/foo.foo\";\n", "file_path": "src/misc/error.rs", "rank": 60, "score": 36179.59488742774 }, { "content": " )\n\n\n\n };\n\n}\n\n\n\n#[cfg(test)]\n\nmod tests {\n\n use super::*;\n\n use std::fs::File;\n\n use std::time::{Duration, SystemTime};\n\n\n\n use regex::Regex;\n\n use serde::Deserialize;\n\n\n\n // dummy struct\n\n #[derive(Debug, Deserialize)]\n\n struct A;\n\n\n\n #[test]\n\n fn error() {\n", "file_path": "src/misc/error.rs", "rank": 61, "score": 36179.38604396623 }, { "content": " pub fn from_error<T: Into<InternalError>>(err: T, msg: &str) -> Self {\n\n AppError {\n\n error_kind: err.into(),\n\n msg: msg.to_string(),\n\n }\n\n }\n\n}\n\n\n\nimpl fmt::Display for AppError {\n\n fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {\n\n match &self.error_kind {\n\n InternalError::Io(ref err) => write!(f, \"I/O error: {} ({})\", self.msg, err),\n\n InternalError::Regex(ref err) => write!(f, \"regex error: {} ({})\", self.msg, err),\n\n InternalError::Parse(ref err) => write!(f, \"conversion error: {} ({})\", self.msg, err),\n\n InternalError::Yaml(ref err) => write!(f, \"YAML error: {} ({})\", self.msg, err),\n\n InternalError::Json(ref err) => write!(f, \"JSON error: {} ({})\", self.msg, err),\n\n InternalError::Utf8(ref err) => {\n\n write!(f, \"Utf8 conversion error: {} ({})\", self.msg, err)\n\n }\n\n InternalError::SystemTime(ref err) => {\n", "file_path": "src/misc/error.rs", "rank": 62, "score": 36179.370536859555 }, { "content": " let err = file().unwrap_err();\n\n assert!(matches!(err.error_kind, InternalError::Io(_)));\n\n println!(\"{}\", err);\n\n\n\n let err = regex().unwrap_err();\n\n assert!(matches!(err.error_kind, InternalError::Regex(_)));\n\n println!(\"{}\", err);\n\n\n\n let err = parse().unwrap_err();\n\n assert!(matches!(err.error_kind, InternalError::Parse(_)));\n\n println!(\"{}\", err);\n\n\n\n let err = yaml().unwrap_err();\n\n assert!(matches!(err.error_kind, InternalError::Yaml(_)));\n\n println!(\"{}\", err);\n\n\n\n let err = json().unwrap_err();\n\n assert!(matches!(err.error_kind, InternalError::Json(_)));\n\n println!(\"{}\", err);\n\n\n", "file_path": "src/misc/error.rs", "rank": 63, "score": 36177.22200398696 }, { "content": " .parse::<usize>()\n\n .map_err(|e| context!(e, \"unable to convert {} to integer\", s))?;\n\n Ok(value)\n\n }\n\n\n\n fn yaml() -> AppResult<A> {\n\n let s = \"-foo\";\n\n\n\n let yaml: A = serde_yaml::from_str(s)\n\n .map_err(|e| context!(e, \"unable to load YAML string '{}'\", s))?;\n\n Ok(yaml)\n\n }\n\n\n\n fn json() -> AppResult<A> {\n\n let s = \"{\";\n\n\n\n let json: A = serde_json::from_str(s)\n\n .map_err(|e| context!(e, \"unable to load JSON string '{}'\", s))?;\n\n Ok(json)\n\n }\n", "file_path": "src/misc/error.rs", "rank": 64, "score": 36176.27751231656 }, { "content": " }\n\n AppCustomErrorKind::OsStringConversionError => {\n\n write!(f, \"conversion from OsString failed\")\n\n }\n\n AppCustomErrorKind::PhantomCloneError => write!(f, \"no error\"),\n\n #[cfg(target_family = \"windows\")]\n\n AppCustomErrorKind::WindowsApiError => write!(f, \"Windows API error\"),\n\n }\n\n }\n\n}\n\n\n\n/// A specific error type combining all possible error types in the app.\n\n#[derive(Debug)]\n\npub enum InternalError {\n\n Io(io::Error),\n\n Regex(regex::Error),\n\n Parse(num::ParseIntError),\n\n Yaml(serde_yaml::Error),\n\n Json(serde_json::Error),\n\n SystemTime(std::time::SystemTimeError),\n", "file_path": "src/misc/error.rs", "rank": 65, "score": 36175.30085238781 }, { "content": " let s = str::from_utf8(&non_utf8)\n\n .map_err(|e| context!(e, \"{:?} in not an UTF8 string\", non_utf8))?;\n\n Ok(s.to_string())\n\n }\n\n\n\n fn custom() -> AppError {\n\n let path = \"/foo/foo.foo\";\n\n let custom_err = AppError::new_custom(\n\n AppCustomErrorKind::FileNotUsable,\n\n &format!(\"file '{}' not usable\", path),\n\n );\n\n custom_err\n\n }\n\n}\n", "file_path": "src/misc/error.rs", "rank": 66, "score": 36175.07714737357 }, { "content": "\n\n fn systemtime() -> AppResult<Duration> {\n\n let sys_time = SystemTime::now();\n\n let timeout = std::time::Duration::from_millis(10);\n\n std::thread::sleep(timeout);\n\n let new_sys_time = SystemTime::now();\n\n\n\n let difference = sys_time\n\n .duration_since(new_sys_time)\n\n .map_err(|e| context!(e, \"error in duration_since() call\",))?;\n\n\n\n Ok(difference)\n\n }\n\n\n\n fn utf8() -> AppResult<String> {\n\n use std::str;\n\n // some bytes, in a vector\n\n let non_utf8 = vec![240, 159, 146];\n\n\n\n // We know these bytes are valid, so just use `unwrap()`.\n", "file_path": "src/misc/error.rs", "rank": 67, "score": 36173.921950830656 }, { "content": " Utf8(std::str::Utf8Error),\n\n Custom(AppCustomErrorKind),\n\n}\n\n\n\n/// To simplify definition of all error conversions.\n\nmacro_rules! from_error {\n\n ($e:path, $f:path) => {\n\n impl From<$e> for InternalError {\n\n fn from(err: $e) -> InternalError {\n\n $f(err)\n\n }\n\n }\n\n };\n\n}\n\n\n\nfrom_error!(io::Error, InternalError::Io);\n\nfrom_error!(regex::Error, InternalError::Regex);\n\nfrom_error!(serde_yaml::Error, InternalError::Yaml);\n\nfrom_error!(serde_json::Error, InternalError::Json);\n\nfrom_error!(std::time::SystemTimeError, InternalError::SystemTime);\n", "file_path": "src/misc/error.rs", "rank": 68, "score": 36172.83616879763 }, { "content": " write!(f, \"system time error: {} ({})\", self.msg, err)\n\n }\n\n InternalError::Custom(ref err) => write!(f, \"custom error: {} ({})\", self.msg, err),\n\n }\n\n }\n\n}\n\n\n\nimpl Clone for AppError {\n\n fn clone(&self) -> Self {\n\n AppError::new_custom(AppCustomErrorKind::PhantomCloneError, \"fake clone error\")\n\n }\n\n}\n\n\n\n/// To simplify definition of all error conversions.\n\n#[macro_export]\n\nmacro_rules! context {\n\n ($err:ident, $fmt:expr, $($arg:tt)*) => {\n\n AppError::from_error(\n\n $err,\n\n &format!($fmt, $($arg)*)\n", "file_path": "src/misc/error.rs", "rank": 69, "score": 36172.61769254945 }, { "content": " def initialize(yaml_file)\n\n @yaml = YAML.load_file(yaml_file)\n\n pp @yaml\n\n end\n\n\n\n\n\nend\n\n\n", "file_path": "tests/integration/ruby/testcase.rb", "rank": 70, "score": 30571.47528808992 }, { "content": " def self.create(path, append=false)\n\n # open for writing or appending \n\n file = append ? File.open(path, \"a\") : File.open(path, \"w\")\n\n\n\n # write n lines\n\n n = 0\n\n 101.times do\n\n n += 1\n\n line = \"%03d\" % n\n\n\n\n if n == 51 then\n\n file.puts \"1970-01-01 00:00:00: ############# this is a fake ok pattern generated for tests, line number = #{line}\"\n\n next\n\n end\n\n\n\n random = rand(10000..99999)\n\n file.puts \"1970-01-01 00:00:00: ---- this is an error generated for tests, line number = #{line}, error id = #{random}\"\n\n\n\n n += 1\n\n line = \"%03d\" % n\n", "file_path": "tests/integration/ruby/testcase.rb", "rank": 71, "score": 28329.46338602813 }, { "content": "//! Collect all immediate logfile errors i.e. those related to opening or metadata.\n\nuse std::collections::{hash_map::Iter, HashMap};\n\nuse std::ops::Deref;\n\nuse std::path::PathBuf;\n\n\n\nuse crate::misc::{error::AppError, nagios::NagiosError};\n\n\n\n#[derive(Debug)]\n\n/// A structure to hold possible logfile errors and related Nagios errors.\n\npub struct LogFileAccessError {\n\n pub nagios_error: NagiosError,\n\n pub error: AppError,\n\n}\n\n\n\n/// A list of logfile errors.\n\npub struct LogFileAccessErrorList(HashMap<PathBuf, LogFileAccessError>);\n\n\n\nimpl Default for LogFileAccessErrorList {\n\n fn default() -> Self {\n\n LogFileAccessErrorList(HashMap::new())\n", "file_path": "src/logfile/logfileerror.rs", "rank": 73, "score": 30.98317893912543 }, { "content": " std::fs::create_dir(\"./tests/integration/tmp\").expect(\"unable to create tmp dir\");\n\n }\n\n // create logfiles directory if not present\n\n if !std::path::Path::new(\"./tests/integration/logfiles\").exists() {\n\n std::fs::create_dir(\"./tests/integration/logfiles\")\n\n .expect(\"unable to create logfiles dir\");\n\n }\n\n\n\n // create logger\n\n TestScenario::init_log();\n\n }\n\n\n\n /// Create new logger and optionally delete logfile is bigger than cli value\n\n fn init_log() {\n\n // initialize logger\n\n WriteLogger::init(\n\n LevelFilter::Trace,\n\n simplelog::ConfigBuilder::new()\n\n .set_time_format(\"%Y-%b-%d %H:%M:%S.%f\".to_string())\n\n .build(),\n", "file_path": "tests/integration/testcase.rs", "rank": 74, "score": 27.52203468489373 }, { "content": " yaml,\n\n }\n\n }\n\n}\n\n\n\nimpl Config {\n\n // load file data into a string\n\n #[allow(dead_code)]\n\n pub fn from_file(path: &str) -> Self {\n\n // load file data\n\n let yaml = read_to_string(path)\n\n .expect(&format!(\"unable to open alternate config file: {}\", &path));\n\n Config {\n\n config_file: path.to_string(),\n\n yaml,\n\n }\n\n }\n\n\n\n // modify a field in the YAML data: change its value\n\n pub fn set_tag(&mut self, tag: &str, value: &str) -> &mut Config {\n", "file_path": "tests/integration/testcase.rs", "rank": 75, "score": 26.688073646621703 }, { "content": "## Windows specifics\n\nIn order to emulate UNIX inode/dev features, a specific DLL has been developed (*signature.dll*) You need to put this DLL in one of the paths specified by the Windows *Path* environment variable.\n\n\n\n## Command line examples\n\n\n\n```zsh\n\n# mandatory argument: configuration file\n\n$ clf --config config.yml\n\n\n\n# delete snapshot first\n\n$ clf --config config.yml --delete-snapshot\n\n\n\n# use a specific snapshot file\n\n$ clf --config config.yml --snapshot /tmp/temp_snapshot.json\n\n\n\n# set the clf logger to a specific file\n\n$ clf --config config.yml --log /tmp/clf.log\n\n\n\n# don't run any callback, just output matching files for each tag\n\n$ clf --config config.yml --no-callback\n\n\n\n# check YAML syntax, print out internal representation and exit\n\n$ clf --config config.yml --syntax-check\n\n\n\n# show Tera/Jinaj2 rendered YAML and exit\n\n$ clf --config config.yml --show-rendered\n\n\n\n# add a global variable to any previously defined\n\n$ clf --config config.yml --var \"MY_VAR1:var1\" \"MY_VAR2:var2\"\n\n\n\n# override Tera context if the {{ path }} variable is not already set\n\n$ clf --config config.yml --context '{ \"path\": \"/var/sys/myapp.log\" }'\n\n\n\n# set log level\n\n$ clf --config config.yml --log-level Trace\n\n```\n\n\n\n## References\n\n* for a list of regex syntax: https://docs.rs/regex/1.4.3/regex/\n\n* for Tera syntax: https://tera.netlify.app/docs/\n\n\n\n\n\n\n\n\n", "file_path": "README.md", "rank": 76, "score": 26.61233042298684 }, { "content": " .required(false)\n\n .long_about(\"Overwrite clf log if specified\")\n\n .takes_value(false),\n\n )\n\n .get_matches();\n\n\n\n // save all cli options into a structure\n\n let mut options = CliOptions::default();\n\n\n\n // config file is mandatory. Try to canonicalize() at the same time.\n\n let config_file = PathBuf::from(matches.value_of(\"config\").unwrap());\n\n\n\n options.config_file = config_file.canonicalize().expect_critical(&format!(\n\n \"error trying to canonicalize config file: {}\",\n\n config_file.display()\n\n ));\n\n\n\n // optional log file\n\n if matches.is_present(\"log\") {\n\n options.clf_logger = PathBuf::from(matches.value_of(\"log\").unwrap());\n", "file_path": "src/args.rs", "rank": 77, "score": 26.53844671824076 }, { "content": " fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {\n\n match self {\n\n VarType::Str(s) => write!(f, \"{}\", s),\n\n VarType::Int(i) => write!(f, \"{}\", i),\n\n }\n\n }\n\n}\n\n\n\n#[derive(Debug, Serialize, Deserialize, Clone)]\n\n#[serde(deny_unknown_fields)]\n\n/// A generic variable structure.\n\npub struct Vars<K: Hash + Eq, V> {\n\n #[serde(flatten)]\n\n inner: HashMap<K, V>,\n\n}\n\n\n\n/// Runtime vars are created for each matched line. Using `Cow` minimizes string allocations.\n\npub type RuntimeVars<'a> = Vars<Cow<'a, str>, VarType<&'a str>>;\n\n\n\n/// user vars are optionally defined in the global configuration tag.\n", "file_path": "src/configuration/vars.rs", "rank": 78, "score": 25.96016928088911 }, { "content": "## List of command-line arguments\n\nA self-explanatory help can be used with:\n\n\n\n```console\n\nclf --help\n\n```\n\nor\n\n\n\n```console\n\nclf -h\n\n```\n\n\n\nFollowing is a list of cli arguments:\n\n\n\n```\n\nUSAGE:\n\n clf [FLAGS] [OPTIONS] --config <config>\n\n\n\nFLAGS:\n\n -d, --delete-snapshot\n\n Delete snapshot file before searching\n\n\n\n -h, --help\n\n Prints help information\n\n\n\n -a, --no-callback\n\n Don't run any callback, just read all logfiles in the configuration file and print out\n\n matching line. Used to check whether regexes are correct\n\n\n\n -r, --overwrite-log\n\n Overwrite clf log if specified\n\n\n\n -o, --show-options\n\n Just show the command line options passed and exit\n\n\n\n -w, --show-rendered\n\n Render the configuration file through Jinja2/Tera and exit. This is meant to check Tera\n\n substitutions\n\n\n\n -s, --syntax-check\n\n Check configuration file correctness, print it out and exit\n\n\n\n -V, --version\n\n Prints version information\n\n\n\n\n\nOPTIONS:\n\n -c, --config <config>\n\n Name of the YAML configuration file\n\n\n\n -x, --context <context>\n\n A JSON string used to set the Tera context. Only valid if the tera feature is enabled\n\n\n\n -l, --log <log>\n\n Name of the log file for logging information of this executable. Not to be confused with\n\n the logfile to search into\n\n\n\n -g, --log-level <log-level>\n\n When log is enabled, set the minimum log level. Defaults to 'Info'[possible values: Off,\n", "file_path": "README.md", "rank": 79, "score": 25.769869669818412 }, { "content": " }\n\n}\n\n\n\nimpl LogFileAccessErrorList {\n\n pub fn set_error(&mut self, path: &PathBuf, error: AppError, nagios_error: &NagiosError) {\n\n let logfile_error = LogFileAccessError {\n\n nagios_error: nagios_error.clone(),\n\n error,\n\n };\n\n self.0.insert(path.clone(), logfile_error);\n\n }\n\n\n\n pub fn iter(&self) -> Iter<'_, PathBuf, LogFileAccessError> {\n\n self.0.iter()\n\n }\n\n}\n\n\n\nimpl Deref for LogFileAccessErrorList {\n\n type Target = HashMap<PathBuf, LogFileAccessError>;\n\n\n\n fn deref(&self) -> &Self::Target {\n\n &self.0\n\n }\n\n}\n", "file_path": "src/logfile/logfileerror.rs", "rank": 80, "score": 25.42091566836485 }, { "content": " /// Builds a new snapshot file name from `path`.\n\n pub fn build_name<P: AsRef<Path> + Debug>(config_file: P, dir: Option<P>) -> PathBuf {\n\n let mut snapshot_file = PathBuf::new();\n\n let parent = config_file\n\n .as_ref()\n\n .parent()\n\n .unwrap_or_else(|| Path::new(\".\"));\n\n let file_name_without_ext = config_file\n\n .as_ref()\n\n .file_stem()\n\n .expect(\"fatal error: file_stem() is None\");\n\n\n\n // if dir is specified, use this dir to build the final snapshot file name\n\n // if not, use the same directory as path, and add .json as extension\n\n match dir {\n\n Some(dir) => {\n\n debug_assert!(dir.as_ref().is_dir());\n\n snapshot_file.push(dir);\n\n snapshot_file.push(file_name_without_ext);\n\n snapshot_file.set_extension(\"json\");\n", "file_path": "src/logfile/snapshot.rs", "rank": 81, "score": 25.389328264498868 }, { "content": " &mut writer,\n\n \"1970-01-01 00:00:00: * this is a warning generated for tests, line number = {:03}, warning id = {}\",\n\n line_number, warning_id\n\n )\n\n .unwrap();\n\n }\n\n }\n\n\n\n // create a log with japanese utf8 chars\n\n pub fn create_utf8(logfile: &str) {\n\n // open file in write or append mode\n\n let log = File::create(&logfile).expect(\"unable to create fake logfile\");\n\n let mut writer = BufWriter::new(&log);\n\n\n\n // initialize random seed\n\n let mut rng = thread_rng();\n\n\n\n // now write into our fake logfile\n\n let mut line_number = 0;\n\n\n", "file_path": "tests/integration/testcase.rs", "rank": 82, "score": 24.994482187396585 }, { "content": " 'error = 5'\n\n ]\n\n }\n\n warning: {\n\n regexes: [\n\n '^WARNING: opening file \"([a-z0-9/]*)\" from node ([\\w\\.]+), error = (\\d)',\n\n ],\n\n exceptions: [\n\n 'error = 5'\n\n ]\n\n }\n\n \"#;\n\n\n\n let mut tag = Tag::from_str(yaml).expect(\"unable to read YAML\");\n\n\n\n let mut def = LogFileDef::default();\n\n def.hash_window = 4096;\n\n\n\n let mut logfile = LogFile::from_path(\"tests/unittest/adhoc.txt\", Some(def)).unwrap();\n\n\n", "file_path": "src/logfile/logfile.rs", "rank": 84, "score": 24.12542352596435 }, { "content": " compression::CompressionScheme, logfileid::LogFileID, lookup::Lookup, rundata::RunData,\n\n};\n\nuse crate::misc::error::{AppCustomErrorKind, AppError, AppResult};\n\nuse crate::misc::extension::ReadFs;\n\n\n\n/// A wrapper to get logfile information and its related attributes.\n\n#[derive(Debug, Serialize, Deserialize, Clone, Default)]\n\npub struct LogFile {\n\n /// All fields depending on the declared path\n\n pub id: LogFileID,\n\n\n\n /// All other fields from the config file\n\n #[serde(skip)]\n\n pub definition: LogFileDef,\n\n\n\n /// Run time data that are stored each time a logfile is searched for patterns.\n\n pub run_data: HashMap<String, RunData>,\n\n}\n\n\n\nimpl LogFile {\n", "file_path": "src/logfile/logfile.rs", "rank": 85, "score": 23.19673288480808 }, { "content": " }\n\n None => {\n\n snapshot_file.push(parent);\n\n snapshot_file.push(file_name_without_ext);\n\n snapshot_file.set_extension(\"json\");\n\n }\n\n };\n\n\n\n snapshot_file\n\n }\n\n\n\n /// Deserialize a snapshot from a JSON file.\n\n pub fn load<P: AsRef<Path> + Debug>(snapshot_file: P) -> AppResult<Snapshot> {\n\n // open file, and create a new one if not found\n\n let json_file = match File::open(&snapshot_file) {\n\n Ok(file) => file,\n\n Err(e) => {\n\n if e.kind() == ErrorKind::NotFound {\n\n return Ok(Snapshot::default());\n\n } else {\n", "file_path": "src/logfile/snapshot.rs", "rank": 86, "score": 23.186739879888183 }, { "content": " pub logger_level: LevelFilter,\n\n pub max_logger_size: u64,\n\n pub show_options: bool,\n\n pub nagios_version: NagiosVersion,\n\n pub snapshot_file: Option<PathBuf>,\n\n pub reader_type: ReaderCallType,\n\n pub tera_context: Option<String>,\n\n pub extra_vars: Option<Vec<String>>,\n\n pub show_rendered: bool,\n\n pub reset_log: bool,\n\n}\n\n\n\n/// Implements `Default` trait for `CliOptions`.\n\nimpl Default for CliOptions {\n\n fn default() -> Self {\n\n // build a default logger file\n\n let mut default_logger = std::env::current_dir().unwrap_or_else(|_| std::env::temp_dir());\n\n default_logger.push(\"clf.log\");\n\n\n\n CliOptions {\n", "file_path": "src/args.rs", "rank": 87, "score": 23.05480776653374 }, { "content": "\n\n self\n\n }\n\n\n\n // save modified data to another file\n\n pub fn save_as(&self, name: &str) {\n\n let mut file = File::create(name).expect(&format!(\"unable to save config file: {}\", name));\n\n writeln!(&mut file, \"{}\", self.yaml).unwrap();\n\n }\n\n}\n\n\n\n// a struct for holding test case details\n\n#[derive(Debug)]\n\npub struct TestCase {\n\n pub tag: String,\n\n pub snap_file: String,\n\n pub config_file: String,\n\n pub json: HashMap<String, String>,\n\n pub logfile: String,\n\n pub logfile_gzip: String,\n", "file_path": "tests/integration/testcase.rs", "rank": 89, "score": 22.69448532598356 }, { "content": " .expect(&format!(\"unable to open file {}\", &tc.tmpfile));\n\n assert!(data.contains(&\"tests/integration/tmp/echotcp.log\"));\n\n }\n\n #[cfg(target_family = \"windows\")]\n\n if testcases.is_empty() || testcases.contains(&\"echotcp_win\") {\n\n let mut tc = TestCase::new(\"echotcp_win\", &mut nb_testcases);\n\n Config::from_file(r\".\\tests\\integration\\config\\echotcp_win.yml\")\n\n .set_tag(\"options\", \"runcallback\")\n\n .set_tag(\"path\", &tc.logfile)\n\n .save_as(&tc.config_file);\n\n let _ = tc.run(&opts, &[\"-d\"]);\n\n\n\n // check resulting file created from running script\n\n let data: String = std::fs::read_to_string(&tc.tmpfile)\n\n .expect(&format!(\"unable to open file {}\", &tc.tmpfile));\n\n assert!(data.contains(&r\"tests\\\\integration\\\\tmp\\\\echotcp_win.log\"));\n\n }\n\n\n\n println!(\"Number of test cases executed: {}\", nb_testcases - 1);\n\n}\n", "file_path": "tests/integration/integration_test.rs", "rank": 90, "score": 22.631014981836906 }, { "content": "pub type GlobalVars = HashMap<String, String>;\n\n\n\nimpl<K: Hash + Eq, V> Default for Vars<K, V> {\n\n fn default() -> Self {\n\n Vars {\n\n inner: HashMap::with_capacity(DEFAULT_CONTAINER_CAPACITY),\n\n }\n\n }\n\n}\n\n\n\n// Display is using when using the BypassReader to print out all capture groups\n\nimpl<K: Hash + Eq + Display, V: Display> Display for Vars<K, V> {\n\n fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {\n\n let mut output = String::with_capacity(80);\n\n\n\n for (k, v) in &self.inner {\n\n output += &format!(\"{}:{}\", k, v);\n\n }\n\n\n\n // write final output to formatter\n", "file_path": "src/configuration/vars.rs", "rank": 91, "score": 22.416216610603026 }, { "content": " }\n\n}\n\n\n\n// manage YAML configurations\n\nconst DEFAULT_CONFIG_FILE: &str = \"./tests/integration/config/generated.yml\";\n\n#[allow(dead_code)]\n\npub struct Config {\n\n config_file: String,\n\n yaml: String,\n\n}\n\n\n\nimpl Default for Config {\n\n fn default() -> Self {\n\n // load file data\n\n let yaml = read_to_string(DEFAULT_CONFIG_FILE).expect(&format!(\n\n \"unable to open default config file: {}\",\n\n &DEFAULT_CONFIG_FILE\n\n ));\n\n Config {\n\n config_file: DEFAULT_CONFIG_FILE.to_string(),\n", "file_path": "tests/integration/testcase.rs", "rank": 92, "score": 22.328452233990927 }, { "content": "\n\n let tag = self.run_data.get_mut(tag_name).unwrap();\n\n tag.counters = other.run_data.get(tag_name).unwrap().counters.clone();\n\n }\n\n\n\n ///Just a wrapper function for a file.\n\n pub fn lookup<T>(\n\n &mut self,\n\n tag: &Tag,\n\n global_options: &GlobalOptions,\n\n ) -> AppResult<Vec<ChildData>>\n\n where\n\n Self: Lookup<T>,\n\n {\n\n // open target file\n\n let file = File::open(&self.id.canon_path)\n\n .map_err(|e| context!(e, \"unable to open file:{:?}\", &self.id.canon_path))?;\n\n\n\n // if file is compressed, we need to call a specific reader\n\n // create a specific reader for each compression scheme\n", "file_path": "src/logfile/logfile.rs", "rank": 93, "score": 22.268713749660332 }, { "content": "//! Contains the configuration for a search.\n\nuse serde::Deserialize;\n\n\n\nuse super::{logfiledef::LogFileDef, tag::Tag};\n\n\n\n#[derive(Debug, Deserialize, Clone)]\n\n#[serde(deny_unknown_fields)]\n\n/// Contains the logfile attributes from the `LogFileDef` structure and all defined tags to search for patterns.\n\npub struct Search {\n\n /// the logfile name to check\n\n pub logfile: LogFileDef,\n\n\n\n /// a unique identifier for this search\n\n pub tags: Vec<Tag>,\n\n}\n\n\n\nimpl Search {\n\n /// Return the list of all tag names\n\n pub fn tag_names(&self) -> Vec<&str> {\n\n self.tags.iter().map(|x| x.name.as_str()).collect()\n", "file_path": "src/configuration/search.rs", "rank": 94, "score": 22.04335970772745 }, { "content": " .append(true)\n\n .open(logfile)\n\n .expect(&format!(\"unable to create fake logfile {}\", logfile))\n\n } else {\n\n File::create(logfile).expect(&format!(\"unable to create fake logfile {}\", logfile))\n\n };\n\n let mut writer = BufWriter::new(&log);\n\n\n\n // initialize random seed\n\n let mut rng = thread_rng();\n\n\n\n // now write into our fake logfile\n\n let mut line_number = 0;\n\n\n\n for _ in 1..102 {\n\n line_number += 1;\n\n\n\n // insert ok pattern once\n\n if line_number == 51 {\n\n writeln!(\n", "file_path": "tests/integration/testcase.rs", "rank": 95, "score": 22.013575023536976 }, { "content": "# example of a Windows command, which returns a list of files\n\n - logfile:\n\n list: ['cmd.exe', '/c', 'dir /B /S .\\tests\\integration\\tmp\\list_files.log.*']\n\n```\n\n\n\nOptionnaly, you can use the *cmd* tag to send a whole command:\n\n\n\n```yaml\n\n# example of a UNIX command, which returns a list of files using the bash shell. In case of Windows, cmd.exe will be used\n\n - logfile:\n\n cmd: find /var/log -maxdepth 2 -type f -name \"[a-d]*.log\" | grep foo\n\n```\n\n\n\n\n\n## Data provided to the callback\n\nWhenever a match is found when searching a logfile, if provided, a callback is called, with optional arguments. If the callback is a script, a list of environment variables is created and passed to the created process. If the callback is a TCP or UDS callback, all data are provided as a JSON string, with the JSON string length provided first. In case of a set of global variables, those are only provided during the first payload sent to the callback in case of a TCP or UDS callback, or each time in case of a script callback. It's the same process for optional \n\narguments: they're only provided once in case of a TCP or UDS callback, every call in case of a script.\n\n\n", "file_path": "README.md", "rank": 97, "score": 21.98764148547255 }, { "content": " return Err(AppError::from_error(\n\n e,\n\n &format!(\"error loading snapshot file: {:?}\", snapshot_file),\n\n ));\n\n }\n\n }\n\n };\n\n\n\n let reader = BufReader::new(json_file);\n\n\n\n // deserialize JSON\n\n let snapshot: Snapshot = serde_json::from_reader(reader)\n\n .map_err(|e| context!(e, \"unable load snapshot file: {:?}\", snapshot_file))?;\n\n Ok(snapshot)\n\n }\n\n\n\n /// Serialize snapshot data to a JSON file.\n\n pub fn save<P: AsRef<Path> + Debug>(\n\n &mut self,\n\n snapshot_file: P,\n", "file_path": "src/logfile/snapshot.rs", "rank": 98, "score": 21.949248230960123 }, { "content": " .map_err(|e| context!(e, \"unable to canonicalize file {:?}\", self))?;\n\n let _file =\n\n File::open(&canon).map_err(|e| context!(e, \"unable to open file {:?}\", self))?;\n\n\n\n // if not a file, it's not really usable\n\n if !self.is_file() {\n\n Err(AppError::new_custom(\n\n AppCustomErrorKind::FileNotUsable,\n\n &format!(\"path '{:?}' not usable\", self),\n\n ))\n\n } else {\n\n Ok(())\n\n }\n\n }\n\n\n\n // Gives the list of files from a directory, matching the given regex.\n\n fn list_files(&self, regex: &str) -> AppResult<Vec<PathBuf>> {\n\n // create compiled regex\n\n let re = regex::Regex::new(regex).map_err(|e| context!(e, \"error in regex {}\", regex))?;\n\n\n", "file_path": "src/misc/extension.rs", "rank": 99, "score": 21.905576349603333 } ]
Rust
src/test/spec/v2_runner/test_file.rs
dtolnay-contrib/mongo-rust-driver
1a096bd0d459c1bf6bc59a6a4dc930476043995f
use std::collections::HashMap; use bson::{doc, from_document}; use futures::TryStreamExt; use semver::VersionReq; use serde::{Deserialize, Deserializer}; use crate::{ bson::Document, options::{FindOptions, ReadPreference, SelectionCriteria, SessionOptions}, test::{spec::deserialize_uri_options_to_uri_string, EventClient, FailPoint, TestClient}, }; use super::{operation::Operation, test_event::CommandStartedEvent}; #[derive(Deserialize)] #[serde(deny_unknown_fields)] pub struct TestFile { #[serde(rename = "runOn")] pub run_on: Option<Vec<RunOn>>, pub database_name: Option<String>, pub collection_name: Option<String>, pub bucket_name: Option<String>, pub data: Option<TestData>, pub tests: Vec<Test>, } #[derive(Debug, Deserialize)] #[serde(rename_all = "camelCase")] pub struct RunOn { pub min_server_version: Option<String>, pub max_server_version: Option<String>, pub topology: Option<Vec<String>>, } impl RunOn { pub fn can_run_on(&self, client: &TestClient) -> bool { if let Some(ref min_version) = self.min_server_version { let req = VersionReq::parse(&format!(">= {}", &min_version)).unwrap(); if !req.matches(&client.server_version) { return false; } } if let Some(ref max_version) = self.max_server_version { let req = VersionReq::parse(&format!("<= {}", &max_version)).unwrap(); if !req.matches(&client.server_version) { return false; } } if let Some(ref topology) = self.topology { if !topology.contains(&client.topology_string()) { return false; } } true } } #[derive(Debug, Deserialize)] #[serde(untagged)] pub enum TestData { Single(Vec<Document>), Many(HashMap<String, Vec<Document>>), } #[derive(Deserialize)] #[serde(rename_all = "camelCase")] pub struct Test { pub description: String, pub skip_reason: Option<String>, pub use_multiple_mongoses: Option<bool>, #[serde( default, deserialize_with = "deserialize_uri_options_to_uri_string_option", rename = "clientOptions" )] pub client_uri: Option<String>, pub fail_point: Option<FailPoint>, pub session_options: Option<HashMap<String, SessionOptions>>, pub operations: Vec<Operation>, #[serde(default, deserialize_with = "deserialize_command_started_events")] pub expectations: Option<Vec<CommandStartedEvent>>, pub outcome: Option<Outcome>, } fn deserialize_uri_options_to_uri_string_option<'de, D>( deserializer: D, ) -> std::result::Result<Option<String>, D::Error> where D: Deserializer<'de>, { Ok(Some(deserialize_uri_options_to_uri_string(deserializer)?)) } #[derive(Debug, Deserialize)] pub struct Outcome { pub collection: CollectionOutcome, } impl Outcome { pub async fn matches_actual( self, db_name: String, coll_name: String, client: &EventClient, ) -> bool { let coll_name = match self.collection.name { Some(name) => name, None => coll_name, }; let coll = client.database(&db_name).collection(&coll_name); let selection_criteria = SelectionCriteria::ReadPreference(ReadPreference::Primary); let options = FindOptions::builder() .sort(doc! { "_id": 1 }) .selection_criteria(selection_criteria) .build(); let actual_data: Vec<Document> = coll .find(None, options) .await .unwrap() .try_collect() .await .unwrap(); actual_data == self.collection.data } } #[derive(Debug, Deserialize)] pub struct CollectionOutcome { pub name: Option<String>, pub data: Vec<Document>, } fn deserialize_command_started_events<'de, D>( deserializer: D, ) -> std::result::Result<Option<Vec<CommandStartedEvent>>, D::Error> where D: Deserializer<'de>, { let docs = Vec::<Document>::deserialize(deserializer)?; Ok(Some( docs.iter() .map(|doc| { let event = doc.get_document("command_started_event").unwrap(); from_document(event.clone()).unwrap() }) .collect(), )) }
use std::collections::HashMap; use bson::{doc, from_document}; use futures::TryStreamExt; use semver::VersionReq; use serde::{Deserialize, Deserializer}; use crate::{ bson::Document, options::{FindOptions, ReadPreference, SelectionCriteria, SessionOptions}, test::{spec::deserialize_uri_options_to_uri_string, EventClient, FailPoint, TestClient}, }; use super::{operation::Operation, test_event::CommandStartedEvent}; #[derive(Deserialize)] #[serde(deny_unknown_fields)] pub struct TestFile { #[serde(rename = "runOn")] pub run_on: Option<Vec<RunOn>>, pub database_name: Option<String>, pub collection_name: Option<String>, pub bucket_name: Option<String>, pub data: Option<TestData>, pub tests: Vec<Test>, } #[derive(Debug, Deserialize)] #[serde(rename_all = "camelCase")] pub struct RunOn { pub min_server_version: Option<String>, pub max_server_version: Option<String>, pub topology: Option<Vec<String>>, } impl RunOn { pub
} #[derive(Debug, Deserialize)] #[serde(untagged)] pub enum TestData { Single(Vec<Document>), Many(HashMap<String, Vec<Document>>), } #[derive(Deserialize)] #[serde(rename_all = "camelCase")] pub struct Test { pub description: String, pub skip_reason: Option<String>, pub use_multiple_mongoses: Option<bool>, #[serde( default, deserialize_with = "deserialize_uri_options_to_uri_string_option", rename = "clientOptions" )] pub client_uri: Option<String>, pub fail_point: Option<FailPoint>, pub session_options: Option<HashMap<String, SessionOptions>>, pub operations: Vec<Operation>, #[serde(default, deserialize_with = "deserialize_command_started_events")] pub expectations: Option<Vec<CommandStartedEvent>>, pub outcome: Option<Outcome>, } fn deserialize_uri_options_to_uri_string_option<'de, D>( deserializer: D, ) -> std::result::Result<Option<String>, D::Error> where D: Deserializer<'de>, { Ok(Some(deserialize_uri_options_to_uri_string(deserializer)?)) } #[derive(Debug, Deserialize)] pub struct Outcome { pub collection: CollectionOutcome, } impl Outcome { pub async fn matches_actual( self, db_name: String, coll_name: String, client: &EventClient, ) -> bool { let coll_name = match self.collection.name { Some(name) => name, None => coll_name, }; let coll = client.database(&db_name).collection(&coll_name); let selection_criteria = SelectionCriteria::ReadPreference(ReadPreference::Primary); let options = FindOptions::builder() .sort(doc! { "_id": 1 }) .selection_criteria(selection_criteria) .build(); let actual_data: Vec<Document> = coll .find(None, options) .await .unwrap() .try_collect() .await .unwrap(); actual_data == self.collection.data } } #[derive(Debug, Deserialize)] pub struct CollectionOutcome { pub name: Option<String>, pub data: Vec<Document>, } fn deserialize_command_started_events<'de, D>( deserializer: D, ) -> std::result::Result<Option<Vec<CommandStartedEvent>>, D::Error> where D: Deserializer<'de>, { let docs = Vec::<Document>::deserialize(deserializer)?; Ok(Some( docs.iter() .map(|doc| { let event = doc.get_document("command_started_event").unwrap(); from_document(event.clone()).unwrap() }) .collect(), )) }
fn can_run_on(&self, client: &TestClient) -> bool { if let Some(ref min_version) = self.min_server_version { let req = VersionReq::parse(&format!(">= {}", &min_version)).unwrap(); if !req.matches(&client.server_version) { return false; } } if let Some(ref max_version) = self.max_server_version { let req = VersionReq::parse(&format!("<= {}", &max_version)).unwrap(); if !req.matches(&client.server_version) { return false; } } if let Some(ref topology) = self.topology { if !topology.contains(&client.topology_string()) { return false; } } true }
function_block-function_prefixed
[ { "content": "#[derive(Debug, Deserialize)]\n\nstruct TestTopologyDescription {\n\n #[serde(rename = \"type\")]\n\n topology_type: TopologyType,\n\n servers: Vec<TestServerDescription>,\n\n}\n\n\n\nimpl TestTopologyDescription {\n\n fn into_topology_description(\n\n self,\n\n heartbeat_frequency: Option<Duration>,\n\n ) -> Option<TopologyDescription> {\n\n let servers: Option<Vec<ServerDescription>> = self\n\n .servers\n\n .into_iter()\n\n // The driver doesn't support server versions low enough not to support max staleness, so we\n\n // just manually filter them out here.\n\n .filter(|server| server.max_wire_version.map(|version| version >= 5).unwrap_or(true))\n\n .map(|sd| sd.into_server_description())\n\n .collect();\n\n\n", "file_path": "src/sdam/description/topology/server_selection/test/mod.rs", "rank": 0, "score": 170376.85173367898 }, { "content": "#[derive(Debug, Deserialize)]\n\nstruct TestFile {\n\n #[serde(rename = \"heartbeatFrequencyMS\")]\n\n heartbeat_frequency_ms: Option<u64>,\n\n topology_description: TestTopologyDescription,\n\n read_preference: TestReadPreference,\n\n suitable_servers: Option<Vec<TestServerDescription>>,\n\n in_latency_window: Option<Vec<TestServerDescription>>,\n\n error: Option<bool>,\n\n}\n\n\n\n#[derive(Debug, Deserialize)]\n\npub struct TestReadPreference {\n\n pub mode: Option<String>,\n\n pub tag_sets: Option<Vec<TagSet>>,\n\n #[serde(rename = \"maxStalenessSeconds\")]\n\n pub max_staleness_seconds: Option<u64>,\n\n}\n\n\n", "file_path": "src/sdam/description/topology/server_selection/test/logic.rs", "rank": 1, "score": 160595.9821335925 }, { "content": "#[derive(Debug, Deserialize)]\n\nstruct TestServer {\n\n address: ServerAddress,\n\n operation_count: u32,\n\n}\n\n\n\nasync fn run_test(test_file: TestFile) {\n\n println!(\"Running {}\", test_file.description);\n\n\n\n let mut tallies: HashMap<ServerAddress, u32> = HashMap::new();\n\n\n\n let servers: HashMap<ServerAddress, Arc<Server>> = test_file\n\n .mocked_topology_state\n\n .into_iter()\n\n .map(|desc| {\n\n (\n\n desc.address.clone(),\n\n Arc::new(Server::new_mocked(desc.address, desc.operation_count)),\n\n )\n\n })\n\n .collect();\n", "file_path": "src/sdam/description/topology/server_selection/test/in_window.rs", "rank": 2, "score": 160595.9821335925 }, { "content": "#[derive(Debug, Deserialize)]\n\nstruct TestOutcome {\n\n tolerance: f64,\n\n expected_frequencies: HashMap<ServerAddress, f64>,\n\n}\n\n\n", "file_path": "src/sdam/description/topology/server_selection/test/in_window.rs", "rank": 3, "score": 160595.9821335925 }, { "content": "#[derive(Debug, Deserialize)]\n\nstruct TestFile {\n\n description: String,\n\n topology_description: TestTopologyDescription,\n\n mocked_topology_state: Vec<TestServer>,\n\n iterations: u32,\n\n outcome: TestOutcome,\n\n}\n\n\n", "file_path": "src/sdam/description/topology/server_selection/test/in_window.rs", "rank": 4, "score": 160595.9821335925 }, { "content": "#[derive(Debug, Deserialize)]\n\n#[serde(rename_all = \"camelCase\")]\n\nstruct TestServerDescription {\n\n address: String,\n\n #[serde(rename = \"avg_rtt_ms\")]\n\n avg_rtt_ms: Option<f64>,\n\n #[serde(rename = \"type\")]\n\n server_type: TestServerType,\n\n tags: Option<TagSet>,\n\n last_update_time: Option<i32>,\n\n last_write: Option<LastWriteDate>,\n\n max_wire_version: Option<i32>,\n\n}\n\n\n\nimpl TestServerDescription {\n\n fn into_server_description(self) -> Option<ServerDescription> {\n\n let server_type = match self.server_type.into_server_type() {\n\n Some(server_type) => server_type,\n\n None => return None,\n\n };\n\n\n\n let mut command_response = is_master_response_from_server_type(server_type);\n", "file_path": "src/sdam/description/topology/server_selection/test/mod.rs", "rank": 5, "score": 157723.04382924084 }, { "content": "#[derive(Debug, Deserialize)]\n\n#[serde(rename_all = \"camelCase\")]\n\nstruct LastWriteDate {\n\n last_write_date: i64,\n\n}\n\n\n", "file_path": "src/sdam/description/topology/server_selection/test/mod.rs", "rank": 6, "score": 146034.5923501075 }, { "content": "pub fn deserialize_uri_options_to_uri_string<'de, D>(\n\n deserializer: D,\n\n) -> std::result::Result<String, D::Error>\n\nwhere\n\n D: Deserializer<'de>,\n\n{\n\n let uri_options = Document::deserialize(deserializer)?;\n\n\n\n let mut default_uri_parts = DEFAULT_URI.split('?');\n\n\n\n let mut uri = String::from(default_uri_parts.next().unwrap());\n\n // A connection string has two slashes before the host list and one slash before the auth db\n\n // name. If an auth db name is not provided the latter slash might not be present, so it needs\n\n // to be added manually.\n\n if uri.chars().filter(|c| *c == '/').count() < 3 {\n\n uri.push('/');\n\n }\n\n uri.push('?');\n\n\n\n if let Some(options) = default_uri_parts.next() {\n", "file_path": "src/test/spec/unified_runner/test_file.rs", "rank": 7, "score": 143871.54335298963 }, { "content": "#[derive(Debug, Deserialize)]\n\nstruct TestFile {\n\n pub tests: Vec<TestCase>,\n\n}\n\n\n", "file_path": "src/test/spec/auth.rs", "rank": 8, "score": 128014.32127754086 }, { "content": "#[derive(Debug, Deserialize)]\n\nstruct TestCredential {\n\n pub username: Option<String>,\n\n pub password: Option<String>,\n\n pub source: Option<String>,\n\n pub mechanism: Option<String>,\n\n pub mechanism_properties: Option<Document>,\n\n}\n\n\n\nimpl From<TestCredential> for Credential {\n\n fn from(test_credential: TestCredential) -> Self {\n\n Self {\n\n username: test_credential.username,\n\n password: test_credential.password,\n\n source: test_credential.source,\n\n mechanism: test_credential\n\n .mechanism\n\n .and_then(|s| AuthMechanism::from_str(s.as_str()).ok()),\n\n mechanism_properties: test_credential.mechanism_properties,\n\n }\n\n }\n\n}\n\n\n", "file_path": "src/test/spec/auth.rs", "rank": 9, "score": 128014.32127754086 }, { "content": "#[derive(Debug, Deserialize)]\n\nstruct TestFile {\n\n pub tests: Vec<TestCase>,\n\n}\n\n\n", "file_path": "src/client/options/test.rs", "rank": 10, "score": 128014.32127754086 }, { "content": "#[derive(Debug, Deserialize)]\n\n#[serde(rename_all = \"camelCase\")]\n\nstruct TestCase {\n\n pub description: String,\n\n pub uri: String,\n\n pub valid: bool,\n\n pub credential: Option<TestCredential>,\n\n}\n\n\n\n/// Tests connection string parsing of authentication options.\n\nasync fn run_auth_test(test_file: TestFile) {\n\n for mut test_case in test_file.tests {\n\n test_case.description = test_case.description.replace('$', \"%\");\n\n\n\n let skipped_mechanisms = [\n\n \"GSSAPI\",\n\n \"PLAIN\",\n\n \"MONGODB-CR\",\n\n #[cfg(not(feature = \"tokio-runtime\"))]\n\n \"MONGODB-AWS\",\n\n ];\n\n\n", "file_path": "src/test/spec/auth.rs", "rank": 11, "score": 128014.1392437199 }, { "content": "#[derive(Debug, Deserialize)]\n\n#[serde(rename_all = \"camelCase\")]\n\nstruct TestCase {\n\n pub description: String,\n\n pub uri: String,\n\n pub valid: bool,\n\n pub warning: Option<bool>,\n\n pub hosts: Option<Vec<Document>>,\n\n pub auth: Option<Document>,\n\n pub options: Option<Document>,\n\n}\n\n\n", "file_path": "src/client/options/test.rs", "rank": 12, "score": 128014.1392437199 }, { "content": "struct TestFixtures {\n\n op: Insert,\n\n documents: Vec<Document>,\n\n options: InsertManyOptions,\n\n}\n\n\n", "file_path": "src/operation/insert/test.rs", "rank": 13, "score": 128008.68873243852 }, { "content": "#[derive(Deserialize)]\n\nstruct TestFile {\n\n data: Vec<Document>,\n\n collection_name: String,\n\n database_name: String,\n\n tests: Vec<TestCase>,\n\n}\n\n\n", "file_path": "src/test/spec/command_monitoring/mod.rs", "rank": 14, "score": 123689.93289157828 }, { "content": "#[derive(Deserialize)]\n\nstruct TestCase {\n\n description: String,\n\n #[serde(rename = \"ignore_if_server_version_greater_than\", default)]\n\n max_version: Option<String>,\n\n #[serde(rename = \"ignore_if_server_version_less_than\", default)]\n\n min_version: Option<String>,\n\n operation: Document,\n\n expectations: Vec<TestEvent>,\n\n}\n\n\n\nasync fn run_command_monitoring_test(test_file: TestFile) {\n\n let _guard: RwLockWriteGuard<()> = LOCK.run_exclusively().await;\n\n\n\n let client = TestClient::new().await;\n\n\n\n let skipped_tests = vec![\n\n // uses old count\n\n \"A successful command\",\n\n \"A failed command event\",\n\n \"A successful command with a non-primary read preference\",\n", "file_path": "src/test/spec/command_monitoring/mod.rs", "rank": 15, "score": 123689.93289157828 }, { "content": "#[derive(Debug, Deserialize)]\n\nstruct Metadata {\n\n #[serde(rename = \"clientMetadata\")]\n\n pub client: ClientMetadata,\n\n}\n\n\n", "file_path": "src/test/client.rs", "rank": 16, "score": 122590.62083166515 }, { "content": "#[derive(Debug, Serialize, Deserialize)]\n\nstruct Book {\n\n title: String,\n\n author: String,\n\n}\n\n\n\n#[cfg(not(feature = \"sync\"))]\n\nasync fn _inserting_documents_into_a_typed_collection(db: mongodb::Database) -> Result<()> {\n\n // Get a handle to a collection of `Book`.\n\n let typed_collection = db.collection::<Book>(\"books\");\n\n\n\n let books = vec![\n\n Book {\n\n title: \"The Grapes of Wrath\".to_string(),\n\n author: \"John Steinbeck\".to_string(),\n\n },\n\n Book {\n\n title: \"To Kill a Mockingbird\".to_string(),\n\n author: \"Harper Lee\".to_string(),\n\n },\n\n ];\n", "file_path": "tests/readme_examples.rs", "rank": 17, "score": 122590.57419274481 }, { "content": "struct Err {}\n\nimpl From<mongodb::error::Error> for Err {\n\n fn from(_error: mongodb::error::Error) -> Self {\n\n Err {}\n\n }\n\n}\n", "file_path": "tests/readme_examples.rs", "rank": 18, "score": 122584.9882865628 }, { "content": "#[derive(Debug, Deserialize)]\n\nstruct TestFile {\n\n uri: String,\n\n seeds: Vec<String>,\n\n hosts: Vec<String>,\n\n options: Option<ResolvedOptions>,\n\n parsed_options: Option<ParsedOptions>,\n\n error: Option<bool>,\n\n comment: Option<String>,\n\n}\n\n\n", "file_path": "src/test/spec/initial_dns_seedlist_discovery.rs", "rank": 19, "score": 121673.60885002978 }, { "content": "#[derive(Debug, Deserialize)]\n\nstruct TestFile {\n\n pub tests: Vec<TestCase>,\n\n}\n\n\n", "file_path": "src/test/spec/read_write_concern/document.rs", "rank": 20, "score": 121673.60885002978 }, { "content": "#[derive(Debug, Deserialize)]\n\n#[serde(rename_all = \"camelCase\")]\n\nstruct TestCase {\n\n pub description: String,\n\n pub valid: bool,\n\n pub write_concern: Option<Document>,\n\n pub write_concern_document: Option<Document>,\n\n pub read_concern: Option<Document>,\n\n pub read_concern_document: Option<Document>,\n\n pub is_acknowledged: Option<bool>,\n\n}\n\n\n", "file_path": "src/test/spec/read_write_concern/document.rs", "rank": 21, "score": 121673.42681620881 }, { "content": "#[derive(Debug)]\n\nstruct TopologyState {\n\n http_client: HttpClient,\n\n description: TopologyDescription,\n\n servers: HashMap<ServerAddress, Arc<Server>>,\n\n #[cfg(test)]\n\n mocked: bool,\n\n}\n\n\n\nimpl Topology {\n\n /// Creates a new TopologyDescription with the set of servers initialized to the addresses\n\n /// specified in `hosts` and each other field set to its default value. No monitoring threads\n\n /// will be started for the servers in the topology that's returned.\n\n #[cfg(test)]\n\n pub(super) fn new_mocked(options: ClientOptions) -> Self {\n\n let description = TopologyDescription::new(options.clone()).unwrap();\n\n\n\n let common = Common {\n\n is_alive: Arc::new(AtomicBool::new(true)),\n\n message_manager: TopologyMessageManager::new(),\n\n options: options.clone(),\n", "file_path": "src/sdam/state/mod.rs", "rank": 22, "score": 120706.70958383173 }, { "content": "#[derive(Deserialize)]\n\nstruct IsMasterReply {\n\n ismaster: bool,\n\n ok: f64,\n\n}\n\n\n\nasync fn get_coll_info(db: &Database, filter: Option<Document>) -> Vec<CollectionSpecification> {\n\n let mut colls: Vec<CollectionSpecification> = db\n\n .list_collections(filter, None)\n\n .await\n\n .unwrap()\n\n .try_collect()\n\n .await\n\n .unwrap();\n\n colls.sort_by(|c1, c2| c1.name.cmp(&c2.name));\n\n\n\n colls\n\n}\n\n\n\n#[cfg_attr(feature = \"tokio-runtime\", tokio::test)]\n\n#[cfg_attr(feature = \"async-std-runtime\", async_std::test)]\n", "file_path": "src/test/db.rs", "rank": 23, "score": 119835.03704296565 }, { "content": "#[derive(Debug, Deserialize)]\n\nstruct DriverMetadata {\n\n pub name: String,\n\n pub version: String,\n\n}\n\n\n", "file_path": "src/test/client.rs", "rank": 24, "score": 119834.98961867468 }, { "content": "#[derive(Debug, Deserialize)]\n\nstruct ClientMetadata {\n\n pub driver: DriverMetadata,\n\n pub os: OsMetadata,\n\n}\n\n\n", "file_path": "src/test/client.rs", "rank": 25, "score": 119834.98961867468 }, { "content": "#[derive(Debug, Deserialize)]\n\nstruct OsMetadata {\n\n #[serde(rename = \"type\")]\n\n pub os_type: String,\n\n pub architecture: String,\n\n}\n\n\n\n// This test currently doesn't pass on replica sets and sharded clusters consistently due to\n\n// `currentOp` sometimes detecting heartbeats between the server. Eventually we can test this using\n\n// APM or coming up with something more clever, but for now, we're just disabling it.\n\n//\n\n// #[cfg_attr(feature = \"tokio-runtime\", tokio::test)]\n\n// #[cfg_attr(feature = \"async-std-runtime\", async_std::test)]\n\n#[allow(unused)]\n\nasync fn metadata_sent_in_handshake() {\n\n let client = TestClient::new().await;\n\n let db = client.database(\"admin\");\n\n let result = db.run_command(doc! { \"currentOp\": 1 }, None).await.unwrap();\n\n\n\n let in_prog = match result.get(\"inprog\") {\n\n Some(Bson::Array(in_prog)) => in_prog,\n", "file_path": "src/test/client.rs", "rank": 26, "score": 119834.98961867468 }, { "content": "#[derive(Clone, Serialize, Deserialize, PartialEq, Debug)]\n\nstruct UserType {\n\n x: i32,\n\n str: String,\n\n}\n\n\n\n#[cfg_attr(feature = \"tokio-runtime\", tokio::test)]\n\n#[cfg_attr(feature = \"async-std-runtime\", async_std::test)]\n\n#[function_name::named]\n\nasync fn typed_insert_one() {\n\n let _guard: RwLockReadGuard<()> = LOCK.run_concurrently().await;\n\n let client = TestClient::new().await;\n\n\n\n let coll = client\n\n .init_db_and_typed_coll(function_name!(), function_name!())\n\n .await;\n\n let insert_data = UserType {\n\n x: 1,\n\n str: \"a\".into(),\n\n };\n\n insert_one_and_find(&coll, insert_data).await;\n", "file_path": "src/test/coll.rs", "rank": 27, "score": 119834.80758485371 }, { "content": "#[derive(Debug)]\n\nstruct Executor {\n\n description: String,\n\n operations: Vec<ThreadedOperation>,\n\n error: Option<self::file::Error>,\n\n events: Vec<Event>,\n\n state: Arc<State>,\n\n ignored_event_names: Vec<String>,\n\n pool_options: ConnectionPoolOptions,\n\n}\n\n\n", "file_path": "src/cmap/test/mod.rs", "rank": 28, "score": 119829.35707357233 }, { "content": "#[derive(Debug)]\n\nstruct State {\n\n handler: Arc<EventHandler>,\n\n connections: RwLock<HashMap<String, Connection>>,\n\n unlabeled_connections: Mutex<Vec<Connection>>,\n\n threads: RwLock<HashMap<String, CmapThread>>,\n\n\n\n // In order to drop the pool when performing a `close` operation, we use an `Option` so that we\n\n // can replace it with `None`. Since none of the tests should use the pool after its closed\n\n // (besides the ones we manually skip over), it's fine for us to `unwrap` the pool during these\n\n // tests, as panicking is sufficient to exit any aberrant test with a failure.\n\n pool: RwLock<Option<ConnectionPool>>,\n\n}\n\n\n\nimpl State {\n\n // Counts the number of events of the given type that have occurred so far.\n\n fn count_events(&self, event_type: &str) -> usize {\n\n self.handler\n\n .events\n\n .read()\n\n .unwrap()\n\n .iter()\n\n .filter(|cmap_event| cmap_event.name() == event_type)\n\n .count()\n\n }\n\n}\n\n\n", "file_path": "src/cmap/test/mod.rs", "rank": 29, "score": 119829.35707357233 }, { "content": "#[derive(Debug, Deserialize)]\n\nstruct TestFile {\n\n pub tests: Vec<TestCase>,\n\n}\n\n\n", "file_path": "src/test/spec/read_write_concern/connection_string.rs", "rank": 30, "score": 119745.71722321826 }, { "content": "#[derive(Debug, Deserialize)]\n\n#[serde(rename_all = \"camelCase\")]\n\nstruct TestCase {\n\n pub description: String,\n\n pub uri: String,\n\n pub valid: bool,\n\n pub read_concern: Option<Document>,\n\n pub write_concern: Option<Document>,\n\n}\n\n\n", "file_path": "src/test/spec/read_write_concern/connection_string.rs", "rank": 31, "score": 119745.5351893973 }, { "content": "#[async_trait]\n\npub trait TestOperation: Debug {\n\n async fn execute_on_collection(\n\n &self,\n\n collection: &Collection,\n\n session: Option<&mut ClientSession>,\n\n ) -> Result<Option<Bson>>;\n\n\n\n async fn execute_on_database(\n\n &self,\n\n database: &Database,\n\n session: Option<&mut ClientSession>,\n\n ) -> Result<Option<Bson>>;\n\n\n\n async fn execute_on_client(&self, client: &TestClient) -> Result<Option<Bson>>;\n\n\n\n async fn execute_on_session(&self, session: &mut ClientSession) -> Result<Option<Bson>>;\n\n}\n\n\n\n#[derive(Debug)]\n\npub struct Operation {\n", "file_path": "src/test/spec/v2_runner/operation.rs", "rank": 32, "score": 118046.85920896058 }, { "content": "#[async_trait]\n\npub trait TestOperation: Debug {\n\n async fn execute_test_runner_operation(&self, test_runner: &mut TestRunner);\n\n\n\n async fn execute_entity_operation(\n\n &self,\n\n id: &str,\n\n test_runner: &mut TestRunner,\n\n ) -> Result<Option<Entity>>;\n\n\n\n /// Whether or not this operation returns an array of root documents. This information is\n\n /// necessary to determine how the return value of an operation should be compared to the\n\n /// expected value.\n\n fn returns_root_documents(&self) -> bool {\n\n false\n\n }\n\n}\n\n\n\n#[derive(Debug)]\n\npub struct Operation {\n\n operation: Box<dyn TestOperation>,\n", "file_path": "src/test/spec/unified_runner/operation.rs", "rank": 33, "score": 118046.85920896058 }, { "content": "#[derive(Debug, Deserialize)]\n\nstruct BuildInfo {\n\n version: String,\n\n}\n\n\n\n// Copy of the internal isMaster struct; fix this later.\n\n#[derive(Clone, Debug, Default, Deserialize, PartialEq)]\n\n#[serde(rename_all = \"camelCase\")]\n\npub struct IsMasterCommandResponse {\n\n #[serde(rename = \"ismaster\")]\n\n pub is_master: Option<bool>,\n\n pub ok: Option<f32>,\n\n pub hosts: Option<Vec<String>>,\n\n pub passives: Option<Vec<String>>,\n\n pub arbiters: Option<Vec<String>>,\n\n pub msg: Option<String>,\n\n pub me: Option<String>,\n\n pub set_version: Option<i32>,\n\n pub set_name: Option<String>,\n\n pub hidden: Option<bool>,\n\n pub secondary: Option<bool>,\n", "file_path": "src/test/util/mod.rs", "rank": 34, "score": 117237.89583893189 }, { "content": "#[derive(Debug, Deserialize)]\n\nstruct DatabaseEntry {\n\n name: String,\n\n}\n\n\n\n#[cfg_attr(feature = \"tokio-runtime\", tokio::test)]\n\n#[cfg_attr(feature = \"async-std-runtime\", async_std::test)]\n\nasync fn acquire_connection_and_send_command() {\n\n let _guard: RwLockReadGuard<()> = LOCK.run_concurrently().await;\n\n\n\n let client_options = CLIENT_OPTIONS.clone();\n\n let mut pool_options = ConnectionPoolOptions::from_client_options(&client_options);\n\n pool_options.ready = Some(true);\n\n\n\n let pool = ConnectionPool::new(\n\n client_options.hosts[0].clone(),\n\n Default::default(),\n\n ServerUpdateSender::channel().0,\n\n Some(pool_options),\n\n );\n\n let mut connection = pool.check_out().await.unwrap();\n", "file_path": "src/cmap/test/integration.rs", "rank": 35, "score": 117237.89583893189 }, { "content": "#[derive(Debug)]\n\nstruct CmapThread {\n\n handle: AsyncJoinHandle<Result<()>>,\n\n dispatcher: tokio::sync::mpsc::UnboundedSender<Operation>,\n\n}\n\n\n\nimpl CmapThread {\n\n fn start(state: Arc<State>) -> Self {\n\n let (sender, mut receiver) = tokio::sync::mpsc::unbounded_channel::<Operation>();\n\n let handle = RUNTIME\n\n .spawn(async move {\n\n while let Some(operation) = receiver.recv().await {\n\n operation.execute(state.clone()).await?;\n\n }\n\n Ok(())\n\n })\n\n .unwrap();\n\n\n\n Self {\n\n dispatcher: sender,\n\n handle,\n", "file_path": "src/cmap/test/mod.rs", "rank": 36, "score": 117232.26329382954 }, { "content": "#[derive(Debug, Deserialize)]\n\nstruct ListDatabasesResponse {\n\n databases: Vec<DatabaseEntry>,\n\n}\n\n\n", "file_path": "src/cmap/test/integration.rs", "rank": 37, "score": 114786.04054801294 }, { "content": "#[derive(Debug, Deserialize)]\n\nstruct Arguments {\n\n pub filter: Option<Document>,\n\n pub skip: Option<u64>,\n\n pub limit: Option<u64>,\n\n pub collation: Option<Collation>,\n\n}\n\n\n\n#[function_name::named]\n\nasync fn run_count_test(test_file: TestFile) {\n\n let _guard: RwLockReadGuard<()> = LOCK.run_concurrently().await;\n\n\n\n let client = TestClient::new().await;\n\n let data = test_file.data;\n\n\n\n for mut test_case in test_file.tests {\n\n let lower_description = test_case.description.to_lowercase();\n\n\n\n // old `count` not implemented, collation not implemented\n\n if !test_case.operation.name.contains(\"count\") || lower_description.contains(\"deprecated\") {\n\n continue;\n", "file_path": "src/test/spec/crud_v1/count.rs", "rank": 38, "score": 114786.04054801294 }, { "content": "#[derive(Debug, Deserialize)]\n\n#[serde(rename_all = \"camelCase\")]\n\nstruct Arguments {\n\n pub filter: Option<Document>,\n\n pub field_name: String,\n\n pub collation: Option<Collation>,\n\n}\n\n\n\n#[function_name::named]\n\nasync fn run_distinct_test(test_file: TestFile) {\n\n let _guard: RwLockReadGuard<()> = LOCK.run_concurrently().await;\n\n\n\n let client = TestClient::new().await;\n\n let data = test_file.data;\n\n\n\n for mut test_case in test_file.tests {\n\n if test_case.operation.name != \"distinct\" {\n\n continue;\n\n }\n\n\n\n test_case.description = test_case.description.replace('$', \"%\");\n\n\n", "file_path": "src/test/spec/crud_v1/distinct.rs", "rank": 39, "score": 114785.85851419198 }, { "content": "#[derive(Debug, Deserialize)]\n\n#[serde(rename_all = \"camelCase\")]\n\nstruct Arguments {\n\n pub pipeline: Vec<Document>,\n\n pub batch_size: Option<u32>,\n\n pub collation: Option<Collation>,\n\n}\n\n\n\n#[function_name::named]\n\nasync fn run_aggregate_test(test_file: TestFile) {\n\n let _guard: RwLockReadGuard<()> = LOCK.run_concurrently().await;\n\n let client = TestClient::new().await;\n\n\n\n let data = test_file.data;\n\n\n\n for test_case in test_file.tests {\n\n if test_case.operation.name != \"aggregate\" {\n\n continue;\n\n }\n\n\n\n let coll = client\n\n .init_db_and_coll(\n", "file_path": "src/test/spec/crud_v1/aggregate.rs", "rank": 40, "score": 114785.85851419198 }, { "content": "#[derive(Debug, Deserialize)]\n\n#[serde(rename_all = \"camelCase\")]\n\nstruct Arguments {\n\n pub filter: Document,\n\n pub skip: Option<u64>,\n\n pub limit: Option<i64>,\n\n pub batch_size: Option<u32>,\n\n pub collation: Option<Collation>,\n\n}\n\n\n\n#[function_name::named]\n\nasync fn run_find_test(test_file: TestFile) {\n\n let _guard: RwLockReadGuard<()> = LOCK.run_concurrently().await;\n\n\n\n let client = TestClient::new().await;\n\n let data = test_file.data;\n\n\n\n for mut test_case in test_file.tests {\n\n if test_case.operation.name != \"find\" {\n\n continue;\n\n }\n\n\n", "file_path": "src/test/spec/crud_v1/find.rs", "rank": 41, "score": 114785.85851419198 }, { "content": "#[derive(Debug, Deserialize)]\n\nstruct Arguments {\n\n pub document: Document,\n\n}\n\n\n", "file_path": "src/test/spec/crud_v1/insert_one.rs", "rank": 42, "score": 112467.5717874236 }, { "content": "#[derive(Debug, Deserialize)]\n\nstruct Arguments {\n\n pub documents: Vec<Document>,\n\n pub options: Options,\n\n}\n\n\n", "file_path": "src/test/spec/crud_v1/insert_many.rs", "rank": 43, "score": 112467.5717874236 }, { "content": "#[derive(Debug, Deserialize)]\n\nstruct ConnectionCheckoutFailedHelper {\n\n pub reason: CheckoutFailedReasonHelper,\n\n}\n\n\n", "file_path": "src/cmap/test/event.rs", "rank": 44, "score": 112467.5717874236 }, { "content": "#[derive(Debug, Deserialize)]\n\nstruct Options {\n\n pub ordered: bool,\n\n}\n\n\n", "file_path": "src/test/spec/crud_v1/insert_many.rs", "rank": 45, "score": 112467.5717874236 }, { "content": "#[derive(Debug, Deserialize)]\n\nstruct PoolCreatedEventHelper {\n\n #[serde(default)]\n\n pub options: Option<PoolOptionsHelper>,\n\n}\n\n\n", "file_path": "src/cmap/test/event.rs", "rank": 46, "score": 112467.5717874236 }, { "content": "#[derive(Debug, Deserialize, Default)]\n\nstruct FindModifiers {\n\n #[serde(rename = \"$comment\", default)]\n\n comment: Option<String>,\n\n #[serde(rename = \"$hint\", default)]\n\n hint: Option<Hint>,\n\n #[serde(\n\n rename = \"$maxTimeMS\",\n\n deserialize_with = \"bson_util::deserialize_duration_from_u64_millis\",\n\n default\n\n )]\n\n max_time: Option<Duration>,\n\n #[serde(rename = \"$min\", default)]\n\n min: Option<Document>,\n\n #[serde(rename = \"$max\", default)]\n\n max: Option<Document>,\n\n #[serde(rename = \"$returnKey\", default)]\n\n return_key: Option<bool>,\n\n #[serde(rename = \"$showDiskLoc\", default)]\n\n show_disk_loc: Option<bool>,\n\n}\n", "file_path": "src/test/spec/command_monitoring/operation.rs", "rank": 47, "score": 112467.52514850326 }, { "content": "#[derive(Debug, Deserialize)]\n\n#[serde(rename_all = \"camelCase\")]\n\nstruct Arguments {\n\n pub filter: Document,\n\n pub replacement: Document,\n\n pub upsert: Option<bool>,\n\n pub collation: Option<Collation>,\n\n}\n\n\n", "file_path": "src/test/spec/crud_v1/replace_one.rs", "rank": 48, "score": 112467.38975360263 }, { "content": "#[derive(Debug, Deserialize)]\n\n#[serde(rename_all = \"camelCase\")]\n\nstruct Arguments {\n\n pub filter: Document,\n\n pub update: Document,\n\n pub upsert: Option<bool>,\n\n pub array_filters: Option<Vec<Document>>,\n\n pub collation: Option<Collation>,\n\n}\n\n\n", "file_path": "src/test/spec/crud_v1/update_one.rs", "rank": 49, "score": 112467.38975360263 }, { "content": "#[derive(Debug, Deserialize)]\n\n#[serde(rename_all = \"camelCase\")]\n\nstruct Arguments {\n\n pub filter: Document,\n\n pub collation: Option<Collation>,\n\n}\n\n\n", "file_path": "src/test/spec/crud_v1/delete_many.rs", "rank": 50, "score": 112467.38975360263 }, { "content": "#[derive(Debug, Deserialize)]\n\n#[serde(rename_all = \"camelCase\")]\n\nstruct Arguments {\n\n pub filter: Document,\n\n pub update: Document,\n\n pub upsert: Option<bool>,\n\n pub array_filters: Option<Vec<Document>>,\n\n pub collation: Option<Collation>,\n\n}\n\n\n", "file_path": "src/test/spec/crud_v1/update_many.rs", "rank": 51, "score": 112467.38975360263 }, { "content": "#[derive(Debug, Deserialize)]\n\n#[serde(rename_all = \"camelCase\")]\n\nstruct Arguments {\n\n pub filter: Document,\n\n pub collation: Option<Collation>,\n\n}\n\n\n", "file_path": "src/test/spec/crud_v1/delete_one.rs", "rank": 52, "score": 112467.38975360263 }, { "content": "pub fn results_match(\n\n actual: Option<&Bson>,\n\n expected: &Bson,\n\n returns_root_documents: bool,\n\n entities: Option<&EntityMap>,\n\n) -> bool {\n\n results_match_inner(actual, expected, returns_root_documents, true, entities)\n\n}\n\n\n", "file_path": "src/test/spec/unified_runner/matcher.rs", "rank": 53, "score": 111016.77304334262 }, { "content": "#[derive(Debug, Deserialize, Default, PartialEq)]\n\nstruct ParsedOptions {\n\n user: Option<String>,\n\n password: Option<String>,\n\n db: Option<String>,\n\n}\n\n\n\n#[cfg_attr(feature = \"tokio-runtime\", tokio::test)]\n\n#[cfg_attr(feature = \"async-std-runtime\", async_std::test)]\n\nasync fn run() {\n\n async fn run_test(mut test_file: TestFile) {\n\n // TODO DRIVERS-796: unskip this test\n\n if test_file.uri == \"mongodb+srv://test5.test.build.10gen.cc/?authSource=otherDB\" {\n\n return;\n\n }\n\n\n\n // \"encoded-userinfo-and-db.json\" specifies a database name with a question mark which is\n\n // disallowed on Windows. See\n\n // https://docs.mongodb.com/manual/reference/limits/#restrictions-on-db-names\n\n if let Some(ref mut options) = test_file.parsed_options {\n\n if options.db.as_deref() == Some(\"mydb?\") && cfg!(target_os = \"windows\") {\n", "file_path": "src/test/spec/initial_dns_seedlist_discovery.rs", "rank": 54, "score": 110271.75536021664 }, { "content": "#[derive(Debug, Deserialize)]\n\n#[serde(rename_all = \"camelCase\")]\n\nstruct ResultDoc {\n\n pub deleted_count: u64,\n\n}\n\n\n\n#[function_name::named]\n\nasync fn run_delete_one_test(test_file: TestFile) {\n\n let _guard: RwLockReadGuard<()> = LOCK.run_concurrently().await;\n\n\n\n let client = TestClient::new().await;\n\n let data = test_file.data;\n\n\n\n for mut test_case in test_file.tests {\n\n if test_case.operation.name != \"deleteOne\" {\n\n continue;\n\n }\n\n\n\n test_case.description = test_case.description.replace('$', \"%\");\n\n\n\n let coll = client\n\n .init_db_and_coll(function_name!(), &test_case.description)\n", "file_path": "src/test/spec/crud_v1/delete_one.rs", "rank": 55, "score": 110271.7109638104 }, { "content": "#[derive(Debug, Deserialize)]\n\n#[serde(rename_all = \"camelCase\")]\n\nstruct Arguments {\n\n pub filter: Document,\n\n pub update: Document,\n\n pub array_filters: Option<Vec<Document>>,\n\n pub bypass_document_validation: Option<bool>,\n\n pub projection: Option<Document>,\n\n pub return_document: Option<String>,\n\n pub sort: Option<Document>,\n\n pub upsert: Option<bool>,\n\n pub collation: Option<Collation>,\n\n}\n\n\n\n#[function_name::named]\n\nasync fn run_find_one_and_update_test(test_file: TestFile) {\n\n let _guard: RwLockReadGuard<()> = LOCK.run_concurrently().await;\n\n\n\n let client = TestClient::new().await;\n\n let data = test_file.data;\n\n\n\n for mut test_case in test_file.tests {\n", "file_path": "src/test/spec/crud_v1/find_one_and_update.rs", "rank": 56, "score": 110271.7109638104 }, { "content": "#[derive(Debug, Deserialize)]\n\n#[serde(rename_all = \"camelCase\")]\n\nstruct Arguments {\n\n pub filter: Document,\n\n pub replacement: Document,\n\n pub bypass_document_validation: Option<bool>,\n\n pub projection: Option<Document>,\n\n pub return_document: Option<String>,\n\n pub sort: Option<Document>,\n\n pub upsert: Option<bool>,\n\n pub collation: Option<Collation>,\n\n}\n\n\n\n#[function_name::named]\n\nasync fn run_find_one_and_replace_test(test_file: TestFile) {\n\n let _guard: RwLockReadGuard<()> = LOCK.run_concurrently().await;\n\n\n\n let client = TestClient::new().await;\n\n let data = test_file.data;\n\n\n\n for mut test_case in test_file.tests {\n\n if test_case.operation.name != \"findOneAndReplace\" {\n", "file_path": "src/test/spec/crud_v1/find_one_and_replace.rs", "rank": 57, "score": 110271.7109638104 }, { "content": "#[derive(Debug, Deserialize)]\n\n#[serde(rename_all = \"camelCase\")]\n\nstruct ResultDoc {\n\n inserted_ids: Option<Document>,\n\n}\n\n\n\n#[function_name::named]\n\nasync fn run_insert_many_test(test_file: TestFile) {\n\n let _guard: RwLockReadGuard<()> = LOCK.run_concurrently().await;\n\n\n\n let client = TestClient::new().await;\n\n let data = test_file.data;\n\n\n\n for test_case in test_file.tests {\n\n if test_case.operation.name != \"insertMany\" {\n\n continue;\n\n }\n\n\n\n let coll = client\n\n .init_db_and_coll(function_name!(), &test_case.description)\n\n .await;\n\n coll.insert_many(data.clone(), None)\n", "file_path": "src/test/spec/crud_v1/insert_many.rs", "rank": 58, "score": 110271.7109638104 }, { "content": "#[derive(Debug, Deserialize)]\n\n#[serde(rename_all = \"camelCase\")]\n\nstruct Arguments {\n\n pub filter: Document,\n\n pub projection: Option<Document>,\n\n pub sort: Option<Document>,\n\n pub collation: Option<Collation>,\n\n}\n\n\n\n#[function_name::named]\n\nasync fn run_find_one_and_delete_test(test_file: TestFile) {\n\n let _guard: RwLockReadGuard<()> = LOCK.run_concurrently().await;\n\n\n\n let client = TestClient::new().await;\n\n let data = test_file.data;\n\n\n\n for mut test_case in test_file.tests {\n\n if test_case.operation.name != \"findOneAndDelete\" {\n\n continue;\n\n }\n\n\n\n test_case.description = test_case.description.replace('$', \"%\");\n", "file_path": "src/test/spec/crud_v1/find_one_and_delete.rs", "rank": 59, "score": 110271.7109638104 }, { "content": "#[derive(Debug, Deserialize)]\n\n#[serde(rename_all = \"camelCase\")]\n\nstruct ResultDoc {\n\n pub matched_count: u64,\n\n pub modified_count: u64,\n\n pub upserted_count: Option<u64>,\n\n pub upserted_id: Option<Bson>,\n\n}\n\n\n\n#[function_name::named]\n\nasync fn run_update_many_test(test_file: TestFile) {\n\n let _guard: RwLockReadGuard<()> = LOCK.run_concurrently().await;\n\n\n\n let client = TestClient::new().await;\n\n let data = test_file.data;\n\n\n\n for mut test_case in test_file.tests {\n\n if test_case.operation.name != \"updateMany\" {\n\n continue;\n\n }\n\n\n\n test_case.description = test_case.description.replace('$', \"%\");\n", "file_path": "src/test/spec/crud_v1/update_many.rs", "rank": 60, "score": 110271.7109638104 }, { "content": "#[derive(Debug, Deserialize)]\n\n#[serde(rename_all = \"camelCase\")]\n\nstruct ResultDoc {\n\n pub deleted_count: u64,\n\n}\n\n\n\n#[function_name::named]\n\nasync fn run_delete_many_test(test_file: TestFile) {\n\n let _guard: RwLockReadGuard<()> = LOCK.run_concurrently().await;\n\n\n\n let client = TestClient::new().await;\n\n let data = test_file.data;\n\n\n\n for mut test_case in test_file.tests {\n\n if test_case.operation.name != \"deleteMany\" {\n\n continue;\n\n }\n\n\n\n test_case.description = test_case.description.replace('$', \"%\");\n\n\n\n let coll = client\n\n .init_db_and_coll(function_name!(), &test_case.description)\n", "file_path": "src/test/spec/crud_v1/delete_many.rs", "rank": 61, "score": 110271.7109638104 }, { "content": "#[derive(Debug, Deserialize)]\n\n#[serde(rename_all = \"camelCase\")]\n\nstruct ResultDoc {\n\n pub matched_count: u64,\n\n pub modified_count: u64,\n\n pub upserted_count: Option<u64>,\n\n pub upserted_id: Option<Bson>,\n\n}\n\n\n\n#[function_name::named]\n\nasync fn run_update_one_test(test_file: TestFile) {\n\n let _guard: RwLockReadGuard<()> = LOCK.run_concurrently().await;\n\n\n\n let client = TestClient::new().await;\n\n let data = test_file.data;\n\n\n\n for mut test_case in test_file.tests {\n\n if test_case.operation.name != \"updateOne\" {\n\n continue;\n\n }\n\n\n\n test_case.description = test_case.description.replace('$', \"%\");\n", "file_path": "src/test/spec/crud_v1/update_one.rs", "rank": 62, "score": 110271.7109638104 }, { "content": "#[derive(Debug, Deserialize)]\n\n#[serde(rename_all = \"camelCase\")]\n\nstruct ResultDoc {\n\n inserted_id: Bson,\n\n}\n\n\n\n#[function_name::named]\n\nasync fn run_insert_one_test(test_file: TestFile) {\n\n let _guard: RwLockReadGuard<()> = LOCK.run_concurrently().await;\n\n\n\n let client = TestClient::new().await;\n\n let data = test_file.data;\n\n\n\n for mut test_case in test_file.tests {\n\n if test_case.operation.name != \"insertOne\" {\n\n continue;\n\n }\n\n\n\n test_case.description = test_case.description.replace('$', \"%\");\n\n\n\n let coll = client\n\n .init_db_and_coll(function_name!(), &test_case.description)\n", "file_path": "src/test/spec/crud_v1/insert_one.rs", "rank": 63, "score": 110271.7109638104 }, { "content": "#[derive(Debug, Deserialize)]\n\n#[serde(rename_all = \"camelCase\")]\n\nstruct ResultDoc {\n\n pub matched_count: u64,\n\n pub modified_count: u64,\n\n pub upserted_count: Option<u64>,\n\n pub upserted_id: Option<Bson>,\n\n}\n\n\n\n#[function_name::named]\n\nasync fn run_replace_one_test(test_file: TestFile) {\n\n let _guard: RwLockReadGuard<()> = LOCK.run_concurrently().await;\n\n\n\n let client = TestClient::new().await;\n\n let data = test_file.data;\n\n\n\n for test_case in test_file.tests {\n\n if test_case.operation.name != \"replaceOne\" {\n\n continue;\n\n }\n\n\n\n let coll = client\n", "file_path": "src/test/spec/crud_v1/replace_one.rs", "rank": 64, "score": 110271.7109638104 }, { "content": "#[derive(Debug, Deserialize, PartialEq)]\n\n#[serde(rename_all = \"camelCase\")]\n\nstruct ResolvedOptions {\n\n replica_set: Option<String>,\n\n auth_source: Option<String>,\n\n ssl: bool,\n\n}\n\n\n", "file_path": "src/test/spec/initial_dns_seedlist_discovery.rs", "rank": 65, "score": 110271.62428899211 }, { "content": "pub trait Matchable: Sized + 'static {\n\n fn is_placeholder(&self) -> bool {\n\n false\n\n }\n\n\n\n fn content_matches(&self, expected: &Self) -> bool;\n\n\n\n fn matches<T: Matchable + Any>(&self, expected: &T) -> bool {\n\n if expected.is_placeholder() {\n\n return true;\n\n }\n\n if let Some(expected) = <dyn Any>::downcast_ref::<Self>(expected) {\n\n self.content_matches(expected)\n\n } else {\n\n false\n\n }\n\n }\n\n}\n\n\n\nimpl Matchable for Bson {\n", "file_path": "src/test/util/matchable.rs", "rank": 66, "score": 108707.1446602038 }, { "content": "pub fn events_match(actual: &TestEvent, expected: &TestEvent) -> bool {\n\n match (actual, expected) {\n\n (\n\n TestEvent::CommandStartedEvent {\n\n command_name: actual_command_name,\n\n database_name: actual_database_name,\n\n command: actual_command,\n\n },\n\n TestEvent::CommandStartedEvent {\n\n command_name: expected_command_name,\n\n database_name: expected_database_name,\n\n command: expected_command,\n\n },\n\n ) => {\n\n if expected_command_name.is_some() && actual_command_name != expected_command_name {\n\n return false;\n\n }\n\n if expected_database_name.is_some() && actual_database_name != expected_database_name {\n\n return false;\n\n }\n", "file_path": "src/test/spec/unified_runner/matcher.rs", "rank": 67, "score": 107539.36127030994 }, { "content": "pub fn get_default_name(description: &str) -> String {\n\n let mut db_name = description\n\n .replace('$', \"%\")\n\n .replace(' ', \"_\")\n\n .replace('.', \"_\");\n\n // database names must have fewer than 64 characters\n\n db_name.truncate(63);\n\n db_name\n\n}\n", "file_path": "src/test/util/mod.rs", "rank": 68, "score": 100651.50059019958 }, { "content": "pub fn assert_matches<A: Matchable + Debug, E: Matchable + Debug>(\n\n actual: &A,\n\n expected: &E,\n\n description: Option<&str>,\n\n) {\n\n assert!(\n\n actual.matches(expected),\n\n \"{}\\n{:?}\\n did not MATCH \\n{:?}\",\n\n description.unwrap_or(\"\"),\n\n actual,\n\n expected\n\n );\n\n}\n\n\n", "file_path": "src/test/util/matchable.rs", "rank": 69, "score": 94649.53674131306 }, { "content": "fn verify_max_staleness(max_staleness: Option<Duration>) -> crate::error::Result<()> {\n\n verify_max_staleness_inner(max_staleness)\n\n .map_err(|s| crate::error::ErrorKind::InvalidArgument { message: s }.into())\n\n}\n\n\n", "file_path": "src/sdam/description/topology/mod.rs", "rank": 70, "score": 93728.92685187301 }, { "content": "use bson::{doc, Document};\n\nuse serde::{Deserialize, Serialize, Serializer};\n\nuse std::time::Duration;\n\nuse typed_builder::TypedBuilder;\n\n\n\nuse crate::{\n\n error::Result,\n\n operation::append_options,\n\n selection_criteria::SelectionCriteria,\n\n Client,\n\n RUNTIME,\n\n};\n\n\n\n#[derive(Clone, Debug, Deserialize)]\n\npub struct FailPoint {\n\n #[serde(flatten)]\n\n command: Document,\n\n}\n\n\n\nimpl FailPoint {\n", "file_path": "src/test/util/failpoint.rs", "rank": 71, "score": 93319.3848083099 }, { "content": " \"data\": data,\n\n };\n\n FailPoint { command }\n\n }\n\n\n\n pub async fn enable(\n\n self,\n\n client: &Client,\n\n criteria: impl Into<Option<SelectionCriteria>>,\n\n ) -> Result<FailPointGuard> {\n\n let criteria = criteria.into();\n\n client\n\n .database(\"admin\")\n\n .run_command(self.command.clone(), criteria.clone())\n\n .await?;\n\n Ok(FailPointGuard {\n\n failpoint_name: self.name().to_string(),\n\n client: client.clone(),\n\n criteria,\n\n })\n", "file_path": "src/test/util/failpoint.rs", "rank": 72, "score": 93313.16986199729 }, { "content": " fn name(&self) -> &str {\n\n self.command.get_str(\"configureFailPoint\").unwrap()\n\n }\n\n\n\n /// Create a failCommand failpoint.\n\n /// See https://github.com/mongodb/mongo/wiki/The-%22failCommand%22-fail-point for more info.\n\n pub fn fail_command(\n\n fail_commands: &[&str],\n\n mode: FailPointMode,\n\n options: impl Into<Option<FailCommandOptions>>,\n\n ) -> FailPoint {\n\n let options = options.into();\n\n let mut data = doc! {\n\n \"failCommands\": fail_commands.iter().map(|s| s.to_string()).collect::<Vec<String>>(),\n\n };\n\n append_options(&mut data, options.as_ref()).unwrap();\n\n\n\n let command = doc! {\n\n \"configureFailPoint\": \"failCommand\",\n\n \"mode\": bson::to_bson(&mode).unwrap(),\n", "file_path": "src/test/util/failpoint.rs", "rank": 73, "score": 93310.4349933499 }, { "content": " }\n\n}\n\n\n\npub struct FailPointGuard {\n\n client: Client,\n\n failpoint_name: String,\n\n criteria: Option<SelectionCriteria>,\n\n}\n\n\n\nimpl Drop for FailPointGuard {\n\n fn drop(&mut self) {\n\n let client = self.client.clone();\n\n let name = self.failpoint_name.clone();\n\n\n\n let result = RUNTIME.block_on(async move {\n\n client\n\n .database(\"admin\")\n\n .run_command(\n\n doc! { \"configureFailPoint\": name, \"mode\": \"off\" },\n\n self.criteria.clone(),\n", "file_path": "src/test/util/failpoint.rs", "rank": 74, "score": 93308.79932539728 }, { "content": " )\n\n .await\n\n });\n\n\n\n if let Err(e) = result {\n\n println!(\"failed disabling failpoint: {:?}\", e);\n\n }\n\n }\n\n}\n\n\n\n#[derive(Serialize)]\n\n#[serde(rename_all = \"camelCase\")]\n\n#[allow(unused)]\n\npub enum FailPointMode {\n\n AlwaysOn,\n\n Times(i32),\n\n Skip(i32),\n\n Off,\n\n ActivationProbability(f32),\n\n}\n", "file_path": "src/test/util/failpoint.rs", "rank": 75, "score": 93304.38954191582 }, { "content": "\n\n#[serde_with::skip_serializing_none]\n\n#[derive(Debug, TypedBuilder, Serialize)]\n\n#[builder(field_defaults(default, setter(strip_option)))]\n\n#[serde(rename_all = \"camelCase\")]\n\npub struct FailCommandOptions {\n\n /// The appName that a client must use in order to hit this fail point.\n\n app_name: Option<String>,\n\n\n\n /// If non-null, how long the server should block the affected commands.\n\n /// Only available in 4.2.9+.\n\n #[serde(serialize_with = \"serialize_block_connection\")]\n\n #[serde(flatten)]\n\n block_connection: Option<Duration>,\n\n\n\n /// Whether the server should hang up when the client sends an affected command\n\n close_connection: Option<bool>,\n\n\n\n /// The error code to include in the server's reply to an affected command.\n\n error_code: Option<i64>,\n", "file_path": "src/test/util/failpoint.rs", "rank": 76, "score": 93301.82260737183 }, { "content": "\n\n /// Array of error labels to be included in the server's reply to an affected command. Passing\n\n /// in an empty array suppresses all error labels that would otherwise be returned by the\n\n /// server. The existence of the \"errorLabels\" field in the failCommand failpoint completely\n\n /// overrides the server's normal error labels adding behaviors for the affected commands.\n\n /// Only available in 4.4+.\n\n error_labels: Option<Vec<String>>,\n\n\n\n /// Document to be returned as a write concern error.\n\n write_concern_error: Option<Document>,\n\n}\n\n\n", "file_path": "src/test/util/failpoint.rs", "rank": 77, "score": 93299.16932848588 }, { "content": "#[derive(Clone, Copy, Debug, Deserialize)]\n\nenum TestServerType {\n\n Standalone,\n\n Mongos,\n\n #[serde(rename = \"RSPrimary\")]\n\n RsPrimary,\n\n #[serde(rename = \"RSSecondary\")]\n\n RsSecondary,\n\n #[serde(rename = \"RSArbiter\")]\n\n RsArbiter,\n\n #[serde(rename = \"RSOther\")]\n\n RsOther,\n\n #[serde(rename = \"RSGhost\")]\n\n RsGhost,\n\n Unknown,\n\n PossiblePrimary,\n\n}\n\n\n\nimpl TestServerType {\n\n fn into_server_type(self) -> Option<ServerType> {\n\n match self {\n", "file_path": "src/sdam/description/topology/server_selection/test/mod.rs", "rank": 78, "score": 88302.28873956113 }, { "content": "fn deserialize_schema_version<'de, D>(deserializer: D) -> std::result::Result<Version, D::Error>\n\nwhere\n\n D: Deserializer<'de>,\n\n{\n\n let mut schema_version = String::deserialize(deserializer)?;\n\n // If the schema version does not contain a minor or patch version, append as necessary to\n\n // ensure the String parses correctly into a semver::Version.\n\n let count = schema_version.split('.').count();\n\n if count == 1 {\n\n schema_version.push_str(\".0.0\");\n\n } else if count == 2 {\n\n schema_version.push_str(\".0\");\n\n }\n\n Version::parse(&schema_version).map_err(|e| serde::de::Error::custom(format!(\"{}\", e)))\n\n}\n\n\n\n#[derive(Debug, Deserialize)]\n\n#[serde(rename_all = \"camelCase\", deny_unknown_fields)]\n\npub struct RunOnRequirement {\n\n min_server_version: Option<String>,\n", "file_path": "src/test/spec/unified_runner/test_file.rs", "rank": 79, "score": 88153.4458231847 }, { "content": "#[test]\n\nfn write_concern_deserialize() {\n\n let w_1 = doc! { \"w\": 1 };\n\n let wc: WriteConcern = bson::from_bson(Bson::Document(w_1)).unwrap();\n\n assert_eq!(\n\n wc,\n\n WriteConcern {\n\n w: Acknowledgment::Nodes(1).into(),\n\n w_timeout: None,\n\n journal: None\n\n }\n\n );\n\n\n\n let w_majority = doc! { \"w\": \"majority\" };\n\n let wc: WriteConcern = bson::from_bson(Bson::Document(w_majority)).unwrap();\n\n assert_eq!(\n\n wc,\n\n WriteConcern {\n\n w: Acknowledgment::Majority.into(),\n\n w_timeout: None,\n\n journal: None\n", "file_path": "src/concern/test.rs", "rank": 80, "score": 87935.69252868078 }, { "content": "use std::collections::HashMap;\n\n\n\nuse serde::Deserialize;\n\n\n\nuse crate::{\n\n sdam::description::{\n\n server::ServerDescription,\n\n topology::{test::f64_ms_as_duration, TopologyDescription, TopologyType},\n\n },\n\n test::run_spec_test,\n\n};\n\n\n\n#[derive(Debug, Deserialize)]\n\npub struct TestFile {\n\n pub avg_rtt_ms: AverageRtt,\n\n pub new_rtt_ms: f64,\n\n pub new_avg_rtt: f64,\n\n}\n\n\n\n#[derive(Debug, Deserialize)]\n", "file_path": "src/sdam/description/topology/test/rtt.rs", "rank": 81, "score": 87660.19681473494 }, { "content": "use std::{collections::HashMap, sync::Arc, time::Duration};\n\n\n\nuse serde::Deserialize;\n\nuse tokio::sync::RwLockReadGuard;\n\n\n\nuse crate::{\n\n bson::{doc, oid::ObjectId},\n\n client::Client,\n\n error::{BulkWriteFailure, CommandError, Error, ErrorKind},\n\n is_master::{IsMasterCommandResponse, IsMasterReply},\n\n options::{ClientOptions, ReadPreference, SelectionCriteria, ServerAddress},\n\n sdam::{\n\n description::{\n\n server::{ServerDescription, ServerType},\n\n topology::TopologyType,\n\n },\n\n HandshakePhase,\n\n Topology,\n\n },\n\n test::{run_spec_test, TestClient, CLIENT_OPTIONS, LOCK},\n", "file_path": "src/sdam/description/topology/test/sdam.rs", "rank": 82, "score": 87650.69739034031 }, { "content": "};\n\n\n\n#[derive(Debug, Deserialize)]\n\npub struct TestFile {\n\n description: String,\n\n uri: String,\n\n phases: Vec<Phase>,\n\n}\n\n\n\n#[derive(Debug, Deserialize)]\n\n#[serde(rename_all = \"camelCase\")]\n\npub struct Phase {\n\n description: Option<String>,\n\n #[serde(default)]\n\n responses: Vec<Response>,\n\n #[serde(default)]\n\n application_errors: Vec<ApplicationError>,\n\n outcome: Outcome,\n\n}\n\n\n", "file_path": "src/sdam/description/topology/test/sdam.rs", "rank": 83, "score": 87641.92130507837 }, { "content": "mod rtt;\n\nmod sdam;\n\n\n\nuse std::time::Duration;\n\n\n\npub(crate) fn f64_ms_as_duration(f: f64) -> Duration {\n\n Duration::from_micros((f * 1000.0) as u64)\n\n}\n", "file_path": "src/sdam/description/topology/test/mod.rs", "rank": 84, "score": 87641.70705006502 }, { "content": "#[derive(Debug, Deserialize)]\n\n#[serde(rename_all = \"camelCase\")]\n\npub struct Outcome {\n\n topology_type: TopologyType,\n\n set_name: Option<String>,\n\n servers: HashMap<String, Server>,\n\n logical_session_timeout_minutes: Option<i32>,\n\n compatible: Option<bool>,\n\n}\n\n\n\n#[derive(Debug, Deserialize)]\n\n#[serde(rename_all = \"camelCase\")]\n\npub struct Server {\n\n #[serde(rename = \"type\")]\n\n server_type: String,\n\n set_name: Option<String>,\n\n set_version: Option<i32>,\n\n election_id: Option<ObjectId>,\n\n logical_session_timeout_minutes: Option<i32>,\n\n min_wire_version: Option<i32>,\n\n max_wire_version: Option<i32>,\n\n}\n\n\n", "file_path": "src/sdam/description/topology/test/sdam.rs", "rank": 85, "score": 87641.27070809448 }, { "content": "#[derive(Debug, Deserialize)]\n\npub struct Response(String, IsMasterCommandResponse);\n\n\n\n#[derive(Debug, Deserialize)]\n\n#[serde(rename_all = \"camelCase\")]\n\npub struct ApplicationError {\n\n address: ServerAddress,\n\n generation: Option<u32>,\n\n max_wire_version: i32,\n\n when: ErrorHandshakePhase,\n\n #[serde(rename = \"type\")]\n\n error_type: ErrorType,\n\n response: Option<ServerError>,\n\n}\n\n\n\nimpl ApplicationError {\n\n fn to_error(&self) -> Error {\n\n match self.error_type {\n\n ErrorType::Command => self.response.clone().unwrap().into(),\n\n ErrorType::Network => {\n", "file_path": "src/sdam/description/topology/test/sdam.rs", "rank": 86, "score": 87640.73947261958 }, { "content": "\n\n let test_description = &test_file.description;\n\n\n\n // TODO: RUST-360 unskip tests that rely on topology version\n\n if test_description.contains(\"topologyVersion\") {\n\n println!(\"Skipping {} (RUST-360)\", test_description);\n\n return;\n\n }\n\n\n\n let topology = Topology::new_mocked(options.clone());\n\n let mut servers = topology.get_servers().await;\n\n\n\n for (i, phase) in test_file.phases.into_iter().enumerate() {\n\n for Response(address, command_response) in phase.responses {\n\n let is_master_reply = if command_response == Default::default() {\n\n Err(\"dummy error\".to_string())\n\n } else {\n\n Ok(IsMasterReply {\n\n command_response,\n\n round_trip_time: Some(Duration::from_millis(1234)), // Doesn't matter for tests.\n", "file_path": "src/sdam/description/topology/test/sdam.rs", "rank": 87, "score": 87639.50365631333 }, { "content": "#[serde(untagged)]\n\npub enum AverageRtt {\n\n F(f64),\n\n I(i32),\n\n S(String),\n\n}\n\n\n\nasync fn run_test(test_file: TestFile) {\n\n let avg_rtt_ms = match test_file.avg_rtt_ms {\n\n AverageRtt::F(f) => Some(f),\n\n AverageRtt::S(ref s) if s == \"NULL\" => None,\n\n AverageRtt::I(i) => Some(i as f64),\n\n AverageRtt::S(ref s) => panic!(\"invalid average round trip time: {}\", s),\n\n };\n\n\n\n // The address is not used, so it doesn't matter.\n\n let mut old_server_desc = ServerDescription::new(Default::default(), None);\n\n let mut new_server_desc = old_server_desc.clone();\n\n\n\n old_server_desc.average_round_trip_time = avg_rtt_ms.map(f64_ms_as_duration);\n", "file_path": "src/sdam/description/topology/test/rtt.rs", "rank": 88, "score": 87639.05141055757 }, { "content": " Network,\n\n Timeout,\n\n}\n\n\n\n#[derive(Clone, Debug, Deserialize)]\n\n#[serde(untagged)]\n\npub enum ServerError {\n\n CommandError(CommandError),\n\n WriteError(BulkWriteFailure),\n\n}\n\n\n\nimpl From<ServerError> for Error {\n\n fn from(server_error: ServerError) -> Self {\n\n match server_error {\n\n ServerError::CommandError(command_error) => ErrorKind::Command(command_error).into(),\n\n ServerError::WriteError(bwf) => ErrorKind::BulkWrite(bwf).into(),\n\n }\n\n }\n\n}\n\n\n", "file_path": "src/sdam/description/topology/test/sdam.rs", "rank": 89, "score": 87638.69388765388 }, { "content": " generation: error_generation,\n\n max_wire_version: application_error.max_wire_version,\n\n }\n\n }\n\n };\n\n\n\n topology\n\n .handle_application_error(error, handshake_phase, &server)\n\n .await;\n\n }\n\n }\n\n\n\n let topology_description = topology.description().await;\n\n let phase_description = phase.description.unwrap_or_else(|| format!(\"{}\", i));\n\n assert_eq!(\n\n topology_description.topology_type, phase.outcome.topology_type,\n\n \"{}: {}\",\n\n &test_file.description, phase_description\n\n );\n\n\n", "file_path": "src/sdam/description/topology/test/sdam.rs", "rank": 90, "score": 87637.60679221756 }, { "content": " if let Some(compatible) = phase.outcome.compatible {\n\n assert_eq!(\n\n topology_description.compatibility_error.is_none(),\n\n compatible,\n\n \"{}: {}\",\n\n &test_file.description,\n\n phase_description,\n\n );\n\n }\n\n\n\n assert_eq!(\n\n topology_description.servers.len(),\n\n phase.outcome.servers.len(),\n\n \"{}: {}\",\n\n &test_file.description,\n\n phase_description\n\n );\n\n\n\n for (address, server) in phase.outcome.servers {\n\n let address = ServerAddress::parse(&address).unwrap_or_else(|_| {\n", "file_path": "src/sdam/description/topology/test/sdam.rs", "rank": 91, "score": 87637.58970083126 }, { "content": " assert_eq!(\n\n topology_description.set_name, phase.outcome.set_name,\n\n \"{}: {}\",\n\n &test_file.description, phase_description,\n\n );\n\n\n\n let expected_timeout = phase\n\n .outcome\n\n .logical_session_timeout_minutes\n\n .map(|mins| Duration::from_secs((mins as u64) * 60));\n\n assert_eq!(\n\n topology_description\n\n .session_support_status\n\n .logical_session_timeout(),\n\n expected_timeout,\n\n \"{}: {}\",\n\n &test_file.description,\n\n phase_description\n\n );\n\n\n", "file_path": "src/sdam/description/topology/test/sdam.rs", "rank": 92, "score": 87637.50506438107 }, { "content": " ErrorKind::Io(Arc::new(std::io::ErrorKind::UnexpectedEof.into())).into()\n\n }\n\n ErrorType::Timeout => {\n\n ErrorKind::Io(Arc::new(std::io::ErrorKind::TimedOut.into())).into()\n\n }\n\n }\n\n }\n\n}\n\n\n\n#[derive(Debug, Deserialize)]\n\n#[serde(rename_all = \"camelCase\")]\n\npub enum ErrorHandshakePhase {\n\n BeforeHandshakeCompletes,\n\n AfterHandshakeCompletes,\n\n}\n\n\n\n#[derive(Debug, Deserialize)]\n\n#[serde(rename_all = \"camelCase\")]\n\npub enum ErrorType {\n\n Command,\n", "file_path": "src/sdam/description/topology/test/sdam.rs", "rank": 93, "score": 87637.26513532776 }, { "content": " };\n\n\n\n topology.update_round_trip_time(&mut new_server_desc);\n\n\n\n assert_eq!(\n\n new_server_desc.average_round_trip_time,\n\n Some(f64_ms_as_duration(test_file.new_avg_rtt))\n\n );\n\n}\n\n\n\n#[cfg_attr(feature = \"tokio-runtime\", tokio::test)]\n\n#[cfg_attr(feature = \"async-std-runtime\", async_std::test)]\n\nasync fn server_selection_rtt() {\n\n run_spec_test(&[\"server-selection\", \"rtt\"], run_test).await;\n\n}\n", "file_path": "src/sdam/description/topology/test/rtt.rs", "rank": 94, "score": 87637.0440432263 }, { "content": "}\n\n\n\n#[cfg_attr(feature = \"tokio-runtime\", tokio::test)]\n\n#[cfg_attr(feature = \"async-std-runtime\", async_std::test)]\n\n#[function_name::named]\n\nasync fn direct_connection() {\n\n let _guard: RwLockReadGuard<_> = LOCK.run_concurrently().await;\n\n\n\n let test_client = TestClient::new().await;\n\n if !test_client.is_replica_set() {\n\n println!(\"Skipping due to non-replica set topology\");\n\n return;\n\n }\n\n\n\n let criteria = SelectionCriteria::ReadPreference(ReadPreference::Secondary {\n\n options: Default::default(),\n\n });\n\n let secondary_address = test_client\n\n .test_select_server(Some(&criteria))\n\n .await\n", "file_path": "src/sdam/description/topology/test/sdam.rs", "rank": 95, "score": 87636.93093213666 }, { "content": " panic!(\n\n \"{}: couldn't parse address \\\"{:?}\\\"\",\n\n test_description, address\n\n )\n\n });\n\n let actual_server = &topology_description\n\n .servers\n\n .get(&address)\n\n .unwrap_or_else(|| panic!(\"{} (phase {})\", test_description, phase_description));\n\n\n\n let server_type = server_type_from_str(&server.server_type)\n\n .unwrap_or_else(|| panic!(\"{} (phase {})\", test_description, phase_description));\n\n\n\n assert_eq!(\n\n actual_server.server_type, server_type,\n\n \"{} (phase {}, address: {})\",\n\n &test_file.description, phase_description, address,\n\n );\n\n\n\n assert_eq!(\n", "file_path": "src/sdam/description/topology/test/sdam.rs", "rank": 96, "score": 87636.7791736292 }, { "content": " new_server_desc.average_round_trip_time = Some(f64_ms_as_duration(test_file.new_rtt_ms));\n\n\n\n let topology = TopologyDescription {\n\n single_seed: false,\n\n topology_type: TopologyType::ReplicaSetNoPrimary,\n\n set_name: None,\n\n max_set_version: None,\n\n max_election_id: None,\n\n compatibility_error: None,\n\n session_support_status: Default::default(),\n\n transaction_support_status: Default::default(),\n\n cluster_time: None,\n\n local_threshold: None,\n\n heartbeat_freq: None,\n\n servers: {\n\n let mut servers = HashMap::new();\n\n servers.insert(Default::default(), old_server_desc);\n\n\n\n servers\n\n },\n", "file_path": "src/sdam/description/topology/test/rtt.rs", "rank": 97, "score": 87636.25765715196 }, { "content": " cluster_time: None,\n\n })\n\n };\n\n\n\n let address = ServerAddress::parse(&address).unwrap_or_else(|_| {\n\n panic!(\n\n \"{}: couldn't parse address \\\"{:?}\\\"\",\n\n test_description.as_str(),\n\n address\n\n )\n\n });\n\n\n\n // only update server if we have strong reference to it like the monitors do\n\n if let Some(server) = servers.get(&address).and_then(|s| s.upgrade()) {\n\n let new_sd = ServerDescription::new(address.clone(), Some(is_master_reply));\n\n if topology.update(&server, new_sd).await {\n\n servers = topology.get_servers().await\n\n }\n\n }\n\n }\n", "file_path": "src/sdam/description/topology/test/sdam.rs", "rank": 98, "score": 87636.21013723164 }, { "content": "async fn single() {\n\n run_spec_test(&[\"server-discovery-and-monitoring\", \"single\"], run_test).await;\n\n}\n\n\n\n#[cfg_attr(feature = \"tokio-runtime\", tokio::test)]\n\n#[cfg_attr(feature = \"async-std-runtime\", async_std::test)]\n\nasync fn rs() {\n\n run_spec_test(&[\"server-discovery-and-monitoring\", \"rs\"], run_test).await;\n\n}\n\n\n\n#[cfg_attr(feature = \"tokio-runtime\", tokio::test)]\n\n#[cfg_attr(feature = \"async-std-runtime\", async_std::test)]\n\nasync fn sharded() {\n\n run_spec_test(&[\"server-discovery-and-monitoring\", \"sharded\"], run_test).await;\n\n}\n\n\n\n#[cfg_attr(feature = \"tokio-runtime\", tokio::test)]\n\n#[cfg_attr(feature = \"async-std-runtime\", async_std::test)]\n\nasync fn errors() {\n\n run_spec_test(&[\"server-discovery-and-monitoring\", \"errors\"], run_test).await;\n", "file_path": "src/sdam/description/topology/test/sdam.rs", "rank": 99, "score": 87633.52264003578 } ]
Rust
src/io.rs
pajamapants3000/red
79292885d1dc6efe7ef98c27a9ec25622cfc12ac
/* * File : io.rs * Purpose: handles input/output functionality * Program: red * About : What does this program do? * Authors: Tommy Lincoln <[email protected]> * License: MIT; See LICENSE! * Notes : Notes on successful compilation * Created: 10/26/2016 */ use std::fs::{File, OpenOptions}; use std::path::Path; use std::process::{Command, Output}; use std::io::{self, BufRead, Write}; use std::ffi::OsStr; use regex::Regex; use error::*; use ::{EditorState, EditorMode}; const PROMPT_CONTINUE: &'static str = ">"; const PROMPT_INSERT: &'static str = "!"; #[derive(Default)] pub struct FileMode { pub f_write: bool, pub f_read: bool, pub f_append: bool, pub f_truncate: bool, pub f_create: bool, pub f_create_new: bool, } /* struct FileCoordinate { line: usize, col: usize, } */ /* /// Return next occurrence of regular expression regex_search( needle: &str, from: FileCoordinate ) -> FileCoordinate { } */ pub fn file_opener<S: AsRef<OsStr> + ?Sized>( name: &S, mode: FileMode ) -> Result<File, RedError> { OpenOptions::new() .read(mode.f_read) .write(mode.f_write) .append(mode.f_append) .truncate(mode.f_truncate) .create(mode.f_create) .create_new(mode.f_create_new) .open( Path::new(name) ).map_err(|err| RedError::FileOpen( err ) ) } pub fn get_input( mut input_buffer: String, state: &EditorState ) -> Result<String, RedError> { let stdin = io::stdin(); let stdout = io::stdout(); let mut stdin_handle = stdin.lock(); let mut stdout_handle = stdout.lock(); let mut prompt: &str; match state.mode { EditorMode::Command => prompt = &state.prompt, EditorMode::Insert => prompt = PROMPT_INSERT, } lazy_static! { static ref RE: Regex = Regex::new( r#".*\\"# ) .expect("get_input: failed to compile regex"); } loop { match input_buffer.pop() { Some(x) => { assert_eq!( x, '\\' ); input_buffer.push( '\n' ); }, None => {}, } try!( stdout_handle.write( prompt.as_bytes() ) .map_err( |_| RedError::Stdout )); try!( stdout_handle.flush().map_err( |_| RedError::Stdout )); try!( stdin_handle.read_line( &mut input_buffer ) .map_err( |_| RedError::Stdin )); match input_buffer.pop() { Some(x) => assert_eq!( x, '\n' ), None => {}, } if !RE.is_match( &mut input_buffer ) { break; } prompt = PROMPT_CONTINUE; } Ok( input_buffer ) } pub fn command_output( _full_stdin: &str ) -> String { let command: String; let arguments: Vec<String>; match compose_command( _full_stdin ) { ( cmd, args ) => { command = cmd; arguments = args; }, } let output: Output; if arguments[0].len() == 0 { output = Command::new( &command ) .output().expect("command failed"); } else { output = Command::new( &command ).args( &arguments ) .output().expect("command failed"); } let output_stdout = output.stdout; String::from_utf8( output_stdout ) .expect("Failed to get output") } fn compose_command( _full_stdin: &str ) -> ( String, Vec<String> ) { let arguments: Vec<String>; match split_cmd_args( _full_stdin ) { ( cmd, arg ) => { arguments = split_args( &arg ); ( cmd, arguments ) }, } } fn split_cmd_args( _full_stdin: &str ) -> ( String, String ) { let input = _full_stdin.trim(); let mut arguments = String::new(); let command: String; let first_space = input.find( char::is_whitespace ); match first_space { Some(x) => { match input.split_at( x ) { (zi, zf) => { command = zi.trim().to_string(); arguments = zf.trim().to_string(); }, } }, None => { command = input.trim().to_string(); }, } ( command, arguments ) } fn split_args( stringed: &str ) -> Vec<String> { let mut input = stringed.trim(); let mut argument = String::new(); let mut arguments: Vec<String> = Vec::new(); loop { let next_space = input.trim().find( char::is_whitespace ); match next_space { Some(x) => { match input.split_at( x ) { (zi, zf) => { input = zf.trim(); argument = argument + zi.trim(); if !is_quoted( stringed, x ) { arguments.push( argument ); argument = String::new(); } }, } }, None => { assert!( argument.is_empty(), "command_output: unterminated quote" ); arguments.push( input.to_string() ); break; }, } } arguments } pub fn is_quoted( text: &str, indx: usize ) -> bool { let bra: Vec<char> = vec!('(', '[', '{'); let ket: Vec<char> = vec!(')', ']', '}'); let quot: Vec<char> = vec!('"', '\'', '`'); let mut c_braket: Vec<isize> = vec!( 0; bra.len() ); let mut c_quote: Vec<isize> = vec!( 0; quot.len() ); let mut escaped: bool = false; let mut move_on: bool; let (left, _) = text.split_at( indx ); for ch in left.chars() { move_on = false; if ch == '\\' { escaped = !escaped; continue } for i in 0 .. quot.len() { if ch == quot[i] { if !escaped { c_quote[i] = 1 - c_quote[i]; } move_on = true; escaped = false; } } if move_on { continue } for i in 0 .. bra.len() { if ch == bra[i] { if c_quote == vec!( 0; c_quote.len() ) { if !escaped { c_braket[i] += 1; } move_on = true; escaped = false; } } } if move_on { continue } for i in 0 .. ket.len() { if ch == ket[i] { if c_quote == vec!( 0; c_quote.len() ) { if !escaped { c_braket[i] -= 1; } } } } escaped = false; } for sum in &c_braket { assert!( *sum >= 0, "is_quoted: too many closing brackets" ); } if c_quote == vec!( 0; c_quote.len() ) && c_braket == vec!( 0; c_braket.len() ) { false } else { true } }
/* * File : io.rs * Purpose: handles input/output functionality * Program: red * About : What does this program do? * Authors: Tommy Lincoln <[email protected]> * License: MIT; See LICENSE! * Notes : Notes on successful compilation * Created: 10/26/2016 */ use std::fs::{File, OpenOptions}; use std::path::Path; use std::process::{Command, Output}; use std::io::{self, BufRead, Write};
sum in &c_braket { assert!( *sum >= 0, "is_quoted: too many closing brackets" ); } if c_quote == vec!( 0; c_quote.len() ) && c_braket == vec!( 0; c_braket.len() ) { false } else { true } }
use std::ffi::OsStr; use regex::Regex; use error::*; use ::{EditorState, EditorMode}; const PROMPT_CONTINUE: &'static str = ">"; const PROMPT_INSERT: &'static str = "!"; #[derive(Default)] pub struct FileMode { pub f_write: bool, pub f_read: bool, pub f_append: bool, pub f_truncate: bool, pub f_create: bool, pub f_create_new: bool, } /* struct FileCoordinate { line: usize, col: usize, } */ /* /// Return next occurrence of regular expression regex_search( needle: &str, from: FileCoordinate ) -> FileCoordinate { } */ pub fn file_opener<S: AsRef<OsStr> + ?Sized>( name: &S, mode: FileMode ) -> Result<File, RedError> { OpenOptions::new() .read(mode.f_read) .write(mode.f_write) .append(mode.f_append) .truncate(mode.f_truncate) .create(mode.f_create) .create_new(mode.f_create_new) .open( Path::new(name) ).map_err(|err| RedError::FileOpen( err ) ) } pub fn get_input( mut input_buffer: String, state: &EditorState ) -> Result<String, RedError> { let stdin = io::stdin(); let stdout = io::stdout(); let mut stdin_handle = stdin.lock(); let mut stdout_handle = stdout.lock(); let mut prompt: &str; match state.mode { EditorMode::Command => prompt = &state.prompt, EditorMode::Insert => prompt = PROMPT_INSERT, } lazy_static! { static ref RE: Regex = Regex::new( r#".*\\"# ) .expect("get_input: failed to compile regex"); } loop { match input_buffer.pop() { Some(x) => { assert_eq!( x, '\\' ); input_buffer.push( '\n' ); }, None => {}, } try!( stdout_handle.write( prompt.as_bytes() ) .map_err( |_| RedError::Stdout )); try!( stdout_handle.flush().map_err( |_| RedError::Stdout )); try!( stdin_handle.read_line( &mut input_buffer ) .map_err( |_| RedError::Stdin )); match input_buffer.pop() { Some(x) => assert_eq!( x, '\n' ), None => {}, } if !RE.is_match( &mut input_buffer ) { break; } prompt = PROMPT_CONTINUE; } Ok( input_buffer ) } pub fn command_output( _full_stdin: &str ) -> String { let command: String; let arguments: Vec<String>; match compose_command( _full_stdin ) { ( cmd, args ) => { command = cmd; arguments = args; }, } let output: Output; if arguments[0].len() == 0 { output = Command::new( &command ) .output().expect("command failed"); } else { output = Command::new( &command ).args( &arguments ) .output().expect("command failed"); } let output_stdout = output.stdout; String::from_utf8( output_stdout ) .expect("Failed to get output") } fn compose_command( _full_stdin: &str ) -> ( String, Vec<String> ) { let arguments: Vec<String>; match split_cmd_args( _full_stdin ) { ( cmd, arg ) => { arguments = split_args( &arg ); ( cmd, arguments ) }, } } fn split_cmd_args( _full_stdin: &str ) -> ( String, String ) { let input = _full_stdin.trim(); let mut arguments = String::new(); let command: String; let first_space = input.find( char::is_whitespace ); match first_space { Some(x) => { match input.split_at( x ) { (zi, zf) => { command = zi.trim().to_string(); arguments = zf.trim().to_string(); }, } }, None => { command = input.trim().to_string(); }, } ( command, arguments ) } fn split_args( stringed: &str ) -> Vec<String> { let mut input = stringed.trim(); let mut argument = String::new(); let mut arguments: Vec<String> = Vec::new(); loop { let next_space = input.trim().find( char::is_whitespace ); match next_space { Some(x) => { match input.split_at( x ) { (zi, zf) => { input = zf.trim(); argument = argument + zi.trim(); if !is_quoted( stringed, x ) { arguments.push( argument ); argument = String::new(); } }, } }, None => { assert!( argument.is_empty(), "command_output: unterminated quote" ); arguments.push( input.to_string() ); break; }, } } arguments } pub fn is_quoted( text: &str, indx: usize ) -> bool { let bra: Vec<char> = vec!('(', '[', '{'); let ket: Vec<char> = vec!(')', ']', '}'); let quot: Vec<char> = vec!('"', '\'', '`'); let mut c_braket: Vec<isize> = vec!( 0; bra.len() ); let mut c_quote: Vec<isize> = vec!( 0; quot.len() ); let mut escaped: bool = false; let mut move_on: bool; let (left, _) = text.split_at( indx ); for ch in left.chars() { move_on = false; if ch == '\\' { escaped = !escaped; continue } for i in 0 .. quot.len() { if ch == quot[i] { if !escaped { c_quote[i] = 1 - c_quote[i]; } move_on = true; escaped = false; } } if move_on { continue } for i in 0 .. bra.len() { if ch == bra[i] { if c_quote == vec!( 0; c_quote.len() ) { if !escaped { c_braket[i] += 1; } move_on = true; escaped = false; } } } if move_on { continue } for i in 0 .. ket.len() { if ch == ket[i] { if c_quote == vec!( 0; c_quote.len() ) { if !escaped { c_braket[i] -= 1; } } } } escaped = false; } for
random
[ { "content": "/// Print help, warnings, other output depending on setting\n\n///\n\n/// TODO: Change first arg to just boolean: state.help?\n\npub fn print_help<T: Display>( state: &EditorState, output: T ) {// {{{\n\n if state.show_help {\n\n println!( \"{}\", output );\n\n } else {\n\n println!( \"?\" );\n\n }\n\n}// }}}\n\n\n", "file_path": "src/main.rs", "rank": 0, "score": 28162.41677026876 }, { "content": "/// Print standard messages\n\n///\n\n/// TODO: Change first arg to just boolean: state.help?\n\npub fn print_msg<T: Display>( state: &EditorState, output: T ) {// {{{\n\n if state.show_messages {\n\n println!( \"{}\", output );\n\n }\n\n}// }}}\n\n\n", "file_path": "src/main.rs", "rank": 1, "score": 28159.235117928267 }, { "content": "/// Print help, warnings, other output depending on setting\n\n///\n\n/// TODO: Change first arg to just boolean: state.help?\n\npub fn print_help_debug<T: Debug>( state: &EditorState, output: T ) {// {{{\n\n if state.show_help {\n\n println!( \"{:?}\", output );\n\n } else {\n\n println!( \"?\" );\n\n }\n\n}// }}}\n\n\n\n// ^^^ Functions ^^^ }}}\n\n#[cfg(test)]\n\nmod tests {\n\n\n\n}\n\n\n", "file_path": "src/main.rs", "rank": 2, "score": 27489.4687085655 }, { "content": "/// Write state.buffer to file// {{{\n\nfn write_to_disk( state: &mut EditorState,//{{{\n\n command: Command ) -> Result<(), RedError> {\n\n assert_eq!( 'w', command.operation );\n\n // TODO: Drop this? Or Keep to avoid unused warnings?\n\n state.mode = EditorMode::Command;\n\n let ( _initial, _final ) = default_addrs( state, &command );\n\n state.buffer.write_to_disk( command.parameters, false, _initial, _final )\n\n}// }}}\n", "file_path": "src/ops.rs", "rank": 5, "score": 19485.150839658894 }, { "content": "// *** Functions *** {{{\n\n/// Return error code for given error type {{{\n\n///\n\npub fn error_code( _error: RedError ) -> u32 {\n\n match _error {\n\n RedError::FileOpen(_) => 280,\n\n RedError::FileRename(_) => 281,\n\n RedError::FileWrite(_) => 282,\n\n RedError::FileRemove(_) => 283,\n\n// RedError::FileCopy(_) => 284,\n\n// RedError::FileExist(_) => 285,\n\n// RedError::FileClose(_) => 286,\n\n RedError::SetLineOutOfBounds{ address: _ } => 290,\n\n RedError::GetLineOutOfBounds{ address: _ } => 291,\n\n RedError::Stdin => 297,\n\n RedError::Stdout => 298,\n\n// RedError::Stderr => 299,\n\n// RedError::ParseCommand => 300,\n\n RedError::OpCharIndex => 301,\n\n RedError::AddressSyntax{ address: _} => 302,\n\n RedError::ParameterSyntax{ parameter: _} => 303,\n\n RedError::InvalidOperation{ operation: _ } => 304,\n\n RedError::NoDestruct => 305,\n\n RedError::CriticalError(_) => 99,\n\n RedError::Quit => 0,\n\n }\n\n}\n", "file_path": "src/error.rs", "rank": 7, "score": 18448.141242412774 }, { "content": "# RustEd\n\ned implementation in rust\n\n\n\nI have recently discovered that \"red\" is a synonym for ed, I believe with\n\nthe \"-r\" (restricted) flag. So... I may want to change the name at some\n\npoint.\n\n\n\nUPDATE: So I renamed the project to the oh-so-creative \"RustEd\". Hey, when\n\nyou're rewriting an application that already exists, with no innovations\n\nor improvements or added features of any kind, a way too on-the-nose\n\nname is probably appropriate. Save the creative, clever names for a\n\nproject that is actually somewhat original.\n\n\n\nI have endeavored to implement the functionality of ed as described in the\n\nOpenBSD ed man page.\n\n\n\nThe project is almost complete! Just some minor changes and improvements\n\nI would still like to accomplish.\n\n\n\nFor usage information, see the OpenBSD ed man page. It can be found at:\n\n\n\n http://man.openbsd.org/ed.1\n\n\n\nUPDATE: I tried running this on a Windows machine and it didn't work very\n\nwell. Should work pretty well on a \\*Nix machine, I think.\n\nThis project is hardly complete, and I just don't have the time to follow\n\nthrough at this point. Some day, perhaps, when I am able to start doing\n\nsome more work in Rust, I will come back and finish this as a way to get\n\nback into the language. It was certainly a fun and challenging little\n\nproject.\n", "file_path": "README.md", "rank": 8, "score": 16021.465828078351 }, { "content": "// }}}\n\n/// Find index of operation code in string\n\n///\n\n/// Parses full command and finds the index of the operation character;\n\n/// The trick here is that the operation character may appear any number\n\n/// of times as part of a regular expression used to specify an address\n\n/// range that matches;\n\n/// What this function does is simply locates the first alphabetic character\n\n/// that is not wrapped in either /.../ or ?...?\n\n///\n\n/// Trims white space on the left as well - does not count these characters\n\n///\n\n/// # Examples\n\n/// See tests in tests module below\n\nfn get_opchar_index( _cmd_input: &str ) -> Result<(usize, char), RedError> {\n\n let mut current_indx: usize = 0;\n\n let mut bytes_iter: Bytes = _cmd_input.trim().bytes();\n\n loop {\n\n match bytes_iter.next() {\n\n Some( x ) => {\n\n if _cmd_input.is_char_boundary( current_indx ) {\n\n match x {\n\n b'a'...b'z' | b'A'...b'Z' => {\n\n if !is_in_addr( _cmd_input.trim(), current_indx ) {\n\n return Ok( (current_indx, x as char ) );\n\n }\n\n },\n\n _ => {},\n\n }\n\n }\n\n },\n\n None => break,\n\n }\n\n current_indx += 1;\n\n }\n\n Result::Err( RedError::OpCharIndex )\n\n}\n", "file_path": "src/parse.rs", "rank": 9, "score": 15351.297592344656 }, { "content": "/// Produce name for temporary buffer storage// {{{\n\n///\n\n/// # Panics\n\n/// # Errors\n\n/// We don't want any errors to be possible here - whatever the case,\n\n/// return something to use as a temp file name for storing the buffer\n\n/// # Safety\n\n/// # Examples\n\nfn temp_file_name<S: AsRef<OsStr> + ?Sized>( path_str: Option<&S> )\n\n -> OsString {//{{{\n\n // only way to conflict is by choosing the same eight alphanumeric\n\n // characters in less than a second!\n\n let _random_string = random_string();\n\n let mut path: PathBuf = Path::new( path_str.map( |s| s.as_ref() )\n\n .unwrap_or(OsStr::new(\"temp\")) )\n\n .to_path_buf();\n\n let mut _temp_file_name = OsStr::new(\".red.\").to_os_string();\n\n _temp_file_name.push( path.file_name().unwrap_or(\n\n OsStr::new( (\"temp.\".to_string() + _random_string.as_str() + \".\" +\n\n &get_timestamp()).as_str() )));\n\n\n\n path.pop();\n\n match path.canonicalize() {\n\n Ok(p) => {\n\n path = p;\n\n path.push( _temp_file_name );\n\n },\n\n Err(_) => path = Path::new( &_temp_file_name ).to_path_buf(),\n", "file_path": "src/buf.rs", "rank": 10, "score": 14744.490590240748 }, { "content": "console.log('This would be the main JS file.');\n", "file_path": "docs/javascripts/main.js", "rank": 11, "score": 14726.342485512781 }, { "content": "/*\n\n * File : test/mod.rs\n\n * Purpose: test module\n\n * Program: red\n\n * About : command-line text editor\n\n * Authors: Tommy Lincoln <[email protected]>\n\n * License: MIT; See LICENSE!\n\n * Notes : Notes on successful compilation\n\n * Created: 10/26/2016\n\n */\n\n\n\n// *** Bring in to namespace *** {{{\n\n//use super::*;\n\n//use parse::*;\n\n//use error::*;\n\n\n\n// ^^^ Bring in to namespace ^^^ }}}\n\n// *** Attributes *** {{{\n\n// ^^^ Attributes ^^^ }}}\n\n// *** Constants *** {{{\n\n// ^^^ Constants ^^^ }}}\n\n// *** Data Structures *** {{{\n\n// ^^^ Data Structures ^^^ }}}\n\n// *** Functions *** {{{\n\n\n\n\n\n#[cfg(not(test))]\n", "file_path": "src/tests/mod.rs", "rank": 13, "score": 31.335181840652353 }, { "content": "/*\n\n * File : parse.rs\n\n * Purpose: routines for parsing using input into useful data\n\n * Program: red\n\n * About : command-line text editor\n\n * Authors: Tommy Lincoln <[email protected]>\n\n * License: MIT; See LICENSE!\n\n * Notes : Notes on successful compilation\n\n * Created: 10/26/2016\n\n */\n\n\n\n// Bring in to namespace {{{\n\nuse std::str::Bytes;\n\n\n\nuse ::regex::{Regex, Captures};\n\n\n\nuse error::*;\n\nuse io::*;\n\nuse buf::*;\n\nuse ops::Operations;\n", "file_path": "src/parse.rs", "rank": 14, "score": 29.650174213887272 }, { "content": "/*\n\n * File : error.rs\n\n * Purpose: structures and routines related to error processing\n\n * Program: red\n\n * About : command-line text editor\n\n * Authors: Tommy Lincoln <[email protected]>\n\n * License: MIT; See LICENSE!\n\n * Notes : Notes on successful compilation\n\n * Created: 10/26/2016\n\n */\n\n\n\n// Bring in to namespace {{{\n\nuse std::io;\n\n// }}}\n\n\n\n// *** Data Structures *** {{{\n\n#[derive(Debug)]\n\npub enum RedError {\n\n FileOpen(io::Error),\n\n FileRename(io::Error),\n", "file_path": "src/error.rs", "rank": 15, "score": 29.564836264356156 }, { "content": "/*\n\n * File : main.rs\n\n * Purpose: reimplementation of the classic `ed` in Rust\n\n * Program: red\n\n * About : command-line text editor\n\n * Authors: Tommy Lincoln <[email protected]>\n\n * License: MIT; See LICENSE!\n\n * Notes : Notes on successful compilation\n\n * Created: 10/16/2016\n\n */\n\n\n\n//! A re-implementation, in Rust, of the classic `ed` program\n\n//!\n\n// Bring in to namespace {{{\n\n//extern crate clap;\n\nextern crate chrono;\n\nextern crate regex;\n\nextern crate rand;\n\n#[macro_use]\n\nextern crate lazy_static;\n", "file_path": "src/main.rs", "rank": 16, "score": 27.002088538681775 }, { "content": "/*\n\n * File : buf.rs\n\n * Purpose: read/write buffer during user interaction\n\n * Program: red\n\n * About : command-line text editor\n\n * Authors: Tommy Lincoln <[email protected]>\n\n * License: MIT; See LICENSE!\n\n * Notes : Notes on successful compilation\n\n * Created: 10/26/2016 */\n\n// *** Bring in to namespace *** {{{\n\n\n\n// Use LineWriter instead of, or in addition to, BufWriter?\n\nuse std::io::prelude::*;\n\nuse std::io::{BufReader, BufWriter, stdout};\n\nuse std::fs::{self, File, rename};\n\nuse std::path::{Path, PathBuf};\n\nuse std::collections::LinkedList;\n\nuse std::collections::linked_list::{self, Iter};\n\nuse std::iter::{IntoIterator, FromIterator, Iterator, Take, Skip};\n\nuse std::{thread, time};\n", "file_path": "src/buf.rs", "rank": 17, "score": 25.348205233488617 }, { "content": "/*\n\n * File : command.rs\n\n * Purpose: defines functions which carry out possible user commands\n\n * Program: red\n\n * About : command-line text editor\n\n * Authors: Tommy Lincoln <[email protected]>\n\n * License: MIT; See LICENSE!\n\n * Notes : All operation functions have same signature\n\n * Created: 11/05/2016\n\n */\n\n\n\n//! Operations callable by the user during program execution\n\n//!\n\n//! All operations take as arguments the current state.buffer, editor state, and\n\n//! command (these may eventually be condensed into editor state) and return\n\n//! Result<(), RedError>\n\n//!\n\n//! All operations assume that the addresses passed through the command have\n\n//! already been checked for validity and range. This is handled when the\n\n//! command is parsed, and so is a safe assumption.\n", "file_path": "src/ops.rs", "rank": 18, "score": 20.904226074992483 }, { "content": " }\n\n }// }}}\n\n// }}}\n\n */\n\n /// Write buffer contents to temp file// {{{\n\n ///\n\n /// TODO: Delete on buffer destruct or at least on program exit\n\n pub fn store_buffer( &mut self ) -> Result<(), RedError> {// {{{\n\n let file_mode = FileMode { f_write: true, f_create: true,\n\n ..Default::default() };\n\n let temp_file_opened = try!( file_opener(\n\n &self.buffer_file, file_mode ) );\n\n let mut writer = BufWriter::new( temp_file_opened );\n\n {\n\n let mut _lines_iterator = self.lines_iterator();\n\n loop {\n\n match _lines_iterator.next() {\n\n Some(x) => {\n\n try!( writer.write( x.as_bytes() )\n\n .map_err( |e| RedError::FileWrite(e) ) );\n", "file_path": "src/buf.rs", "rank": 19, "score": 13.214866026180527 }, { "content": " }\n\n path.into_os_string()\n\n}// }}}\n\n// }}}\n\n// ^^^ Functions ^^^ }}}\n\n\n\n#[cfg(test)]\n\nmod tests {// {{{\n\n // *** *** Bring into namespace *** *** //// {{{\n\n use std::process;\n\n use std::io::Write;\n\n use std::ffi::OsStr;\n\n use std::default::Default;\n\n\n\n use super::*;\n\n use io::*;\n\n use parse::*;\n\n // ^^^ ^^^ Bring into namespace ^^^ ^^^ //// }}}\n\n // *** *** Constants *** *** //// {{{\n\n const TEST_FILE: &'static str = \"red_filetest\";\n", "file_path": "src/buf.rs", "rank": 20, "score": 13.073337055886675 }, { "content": " }// }}}\n\n// }}}\n\n /// Prep and return buffer for use in \"file buffer\" test functions// {{{\n\n ///\n\n /// uses test_lines function to create file with which buffer\n\n /// is initialized\n\n fn open_file_buffer_test_gen( test_num: u8, file_content_line: &str )\n\n -> Buffer {// {{{\n\n let num_lines: usize = 21; // number of lines to have in buffer\n\n // generate test file of known content\n\n let command = process::Command::new( \"echo\" )\n\n .arg( \"-e\" )\n\n .arg( &test_lines( file_content_line, num_lines ) )\n\n .output()\n\n .expect( \"Failed to execute command\" );\n\n let file_mode = FileMode{ f_write: true, f_create: true,\n\n ..Default::default() };\n\n let test_file: String = TEST_FILE.to_string() + \".\" +\n\n random_string().as_str() +\n\n FILE_FILE_SUFFIX + test_num.to_string().as_str();\n", "file_path": "src/buf.rs", "rank": 21, "score": 11.282079319421497 }, { "content": " },\n\n None => break,\n\n }\n\n try!( writer.write( b\"\\n\" )\n\n .map_err( |e| RedError::FileWrite(e) ));\n\n }\n\n }\n\n try!( writer.flush().map_err( |e| RedError::FileWrite(e) ));\n\n let new_buffer_file = match &self.file {\n\n &Some(ref x) => temp_file_name( Some(x) ),\n\n &None => temp_file_name( None::<&OsString> ),\n\n };\n\n try!( rename( &self.buffer_file, &new_buffer_file )\n\n .map_err(|e| RedError::FileRename(e) )\n\n );\n\n self.buffer_file = new_buffer_file;\n\n self.last_temp_write = UTC::now();\n\n Ok( () )\n\n }// }}}\n\n// }}}\n", "file_path": "src/buf.rs", "rank": 22, "score": 11.078497679422426 }, { "content": " let mut file_opened = file_opener( &test_file, file_mode )\n\n .expect( \"Failed to open test file\" );\n\n file_opened.write( &command.stdout )\n\n .expect( \"Failed to write to file\" );\n\n // create new buffer from this file\n\n Buffer::new( BufferInput::File( test_file )).unwrap()\n\n }// }}}\n\n// }}}\n\n /// Call file test buffer generator//{{{\n\n fn open_file_buffer_test( test_num: u8 ) -> Buffer {// {{{\n\n open_file_buffer_test_gen( test_num, FILE_CONTENT_LINE )\n\n }// }}}\n\n// }}}\n\n /// Prep and return buffer for use in \"command buffer\" test functions// {{{\n\n ///\n\n /// uses test_lines function to create file with which buffer\n\n /// is initialized\n\n pub fn open_command_buffer_test_gen( test_num: u8, cmd_content_line: &str )// {{{\n\n -> Buffer {\n\n //\n", "file_path": "src/buf.rs", "rank": 23, "score": 10.421790585485251 }, { "content": " Ok( () )\n\n }//}}}\n\n// }}}\n\n /// Deconstruct buffer// {{{\n\n /// I'm not sure we need this function, since opening a new\n\n /// file or command just creates a new Buffer instance and the\n\n /// old one should be deleted automatically; use on_close to\n\n /// check for unsaved changes and ensure the buffer temp file\n\n /// is deleted.\n\n /// Until I can determine if this is needed, I will keep it and\n\n /// just comment it out.\n\n #[cfg(test)]\n\n pub fn destruct( &mut self ) {// {{{\n\n match self.get_file_path() {\n\n // RedError::FileRemove?\n\n Some(f) => { let _ = fs::remove_file(f).is_ok(); }\n\n None => {},\n\n\n\n }\n\n let _ = fs::remove_file( &self.buffer_file ).is_ok();\n", "file_path": "src/buf.rs", "rank": 25, "score": 9.086782219480893 }, { "content": " use ::EditorState;\n\n\n\n const COMMAND_CONTENT_LINE: &'static str = \"this is a test; number\";\n\n const COMMAND_FILE_SUFFIX: &'static str = \".cmd\";\n\n const TEST_FILE: &'static str = \"red_filetest\";\n\n\n\n /// Prep and return buffer for use in \"command buffer\" test functions\n\n ///\n\n /// uses test_lines function to create file with which buffer\n\n /// is initialized\n\n pub fn open_command_buffer_test( test_num: u8 ) -> EditorState {// {{{\n\n //\n\n let num_lines: usize = 7; // number of lines to have in buffer\n\n let command_content_line = COMMAND_CONTENT_LINE;\n\n let test_file: String = TEST_FILE.to_string() +\n\n COMMAND_FILE_SUFFIX + test_num.to_string().as_str();\n\n let test_command = \"echo -e \".to_string() +\n\n &test_lines( command_content_line,\n\n num_lines );\n\n let mut buffer = Buffer::new( BufferInput::Command( test_command ))\n", "file_path": "src/parse.rs", "rank": 26, "score": 8.85780531791207 }, { "content": " markers: _markers,\n\n _is_modified: self._is_modified,\n\n current_line: self.current_line,\n\n total_lines: self.total_lines,\n\n last_write: _last_write,\n\n last_temp_write: _last_temp_write,\n\n }\n\n }\n\n}\n\n\n\n// ^^^ Data Structures ^^^ }}}\n\n\n\n// *** Functions *** {{{\n\n/// Get timestamp to use for buffer filename// {{{\n\n///\n\n/// # Panics\n\n/// # Errors\n\n/// # Safety\n\n/// # Examples\n", "file_path": "src/buf.rs", "rank": 27, "score": 8.795597192915706 }, { "content": " try!( file_opened.write( line.as_bytes() )\n\n .map_err(|e| RedError::FileWrite(e) ));\n\n try!( file_opened.write( &[b'\\n'] )\n\n .map_err(|e| RedError::FileWrite(e) ));\n\n }\n\n if file_name.as_ref().is_empty() && address_initial == 1 &&\n\n address_final == self.total_lines {\n\n self.last_write = UTC::now();\n\n self._is_modified = false;\n\n }\n\n Ok( () )\n\n\n\n }// }}}\n\n// }}}\n\n /// Pattern match predicate // {{{\n\n ///\n\n /// Returns true if line has pattern match, false otherwise\n\n pub fn does_match( &self, regex: &str, address: usize ) -> bool {// {{{\n\n let re = Regex::new( regex ).unwrap();\n\n re.is_match( self.get_line_content( address ).unwrap_or(\"\") )\n", "file_path": "src/buf.rs", "rank": 28, "score": 8.746584102789939 }, { "content": " thread::sleep(half_second);\n\n handle.write( b\".\" )\n\n .expect(\"buf::Buffer::new: fail to write to stdout\");\n\n handle.flush()\n\n .expect(\"buf::Buffer::new: fail to write to stdout\");\n\n thread::sleep(half_second);\n\n handle.write( b\".\" )\n\n .expect(\"buf::Buffer::new: fail to write to stdout\");\n\n handle.flush()\n\n .expect(\"buf::Buffer::new: fail to write to stdout\");\n\n thread::sleep(half_second);\n\n handle.write( b\".\\n\" )\n\n .expect(\"buf::Buffer::new: fail to write to stdout\");\n\n handle.flush()\n\n .expect(\"buf::Buffer::new: fail to write to stdout\");\n\n if attempt == SAVE_RETRIES {\n\n return Err( e );\n\n }\n\n },\n\n }\n", "file_path": "src/buf.rs", "rank": 30, "score": 8.111388572393235 }, { "content": " Ok( () )\n\n }// }}}\n\n} //}}}\n\nimpl Clone for Buffer {\n\n fn clone( &self ) -> Self {\n\n let _lines = self.lines.clone();\n\n let _file = match &self.file {\n\n &Some(ref f) => Some(f.clone()),\n\n &None => None,\n\n };\n\n let mut _markers: Vec<usize> = Vec::new();\n\n for marker in &self.markers {\n\n _markers.push( *marker );\n\n }\n\n let _last_temp_write = self.last_temp_write.clone();\n\n let _last_write = self.last_write.clone();\n\n Buffer{\n\n lines: _lines,\n\n buffer_file: self.buffer_file.clone(),\n\n file: _file,\n", "file_path": "src/buf.rs", "rank": 31, "score": 7.3329882404620985 }, { "content": " Some( line ) => {\n\n if re.is_match( line.as_str() ) {\n\n return Some( index );\n\n }\n\n },\n\n None => return None,\n\n }\n\n index -= 1;\n\n }\n\n None\n\n }// }}}\n\n// }}}\n\n /// Prepare for closing buffer// {{{\n\n pub fn on_close( &mut self )\n\n -> Result<(), RedError> {// {{{\n\n if self.is_modified() {\n\n return Err( RedError::NoDestruct );\n\n }\n\n try!( fs::remove_file( &self.buffer_file ).map_err(|e|\n\n RedError::FileRemove(e) ));\n", "file_path": "src/buf.rs", "rank": 32, "score": 7.236956035955071 }, { "content": " FileWrite(io::Error),\n\n FileRemove(io::Error),\n\n// FileCopy(io::Error),\n\n// FileExist(io::Error),\n\n// FileClose(io::Error),\n\n SetLineOutOfBounds{ address: usize },\n\n GetLineOutOfBounds{ address: usize },\n\n// ParseCommand,\n\n OpCharIndex,\n\n AddressSyntax{ address: String },\n\n ParameterSyntax{ parameter: String },\n\n InvalidOperation{ operation: char },\n\n Stdin,\n\n Stdout,\n\n// Stderr,\n\n NoDestruct,\n\n CriticalError(String),\n\n Quit,\n\n}\n\n// ^^^ Data Structures ^^^ }}}\n\n\n\n// *** Functions *** {{{\n\n/// Return error code for given error type {{{\n\n///\n", "file_path": "src/error.rs", "rank": 33, "score": 7.206660938735009 }, { "content": "extern crate term_size;\n\n\n\nmod io;\n\nmod parse;\n\nmod error;\n\nmod buf;\n\nmod ops;\n\n\n\nuse std::env;\n\nuse std::fmt::{Debug, Display};\n\n\n\nuse parse::*;\n\nuse buf::*;\n\nuse io::*;\n\n//use error::*;\n\nuse ops::Operations;\n\n\n\n//use io::FileMode;\n\n\n\n// }}}\n", "file_path": "src/main.rs", "rank": 34, "score": 6.680474883645956 }, { "content": " Err(_) => {},\n\n },\n\n _ => {},\n\n };\n\n let half_second: time::Duration = time::Duration::from_millis(500);\n\n for attempt in 1 .. ( SAVE_RETRIES + 1 ) {\n\n match result.store_buffer() {\n\n Ok(_) => {\n\n return Ok( result );\n\n },\n\n Err(e) => {\n\n println!( \"Attempt {}/{}: unable to store buffer\",\n\n attempt, SAVE_RETRIES );\n\n let _stdout = stdout();\n\n let mut handle = _stdout.lock();\n\n thread::sleep(half_second);\n\n handle.write( b\".\" )\n\n .expect(\"buf::Buffer::new: fail to write to stdout\");\n\n handle.flush()\n\n .expect(\"buf::Buffer::new: fail to write to stdout\");\n", "file_path": "src/buf.rs", "rank": 35, "score": 6.668357519041047 }, { "content": "// *** Functions *** {{{\n\n/// Get timestamp to use for buffer filename// {{{\n\n///\n\n/// # Panics\n\n/// # Errors\n\n/// # Safety\n\n/// # Examples\n\nfn get_timestamp() -> String {// {{{\n\n let dt = UTC::now();\n\n dt.format(\"%Y%m%d%H%M%S\").to_string()\n\n\n\n}// }}}\n", "file_path": "src/buf.rs", "rank": 36, "score": 6.665267723592926 }, { "content": " },\n\n */\n\n last_temp_write: match &content {\n\n &BufferInput::File(_) => UTC::now(),\n\n _ => get_null_time(),\n\n },\n\n last_write: get_null_time(),\n\n file: None,\n\n };\n\n\n\n match content {\n\n BufferInput::File( file_name ) =>\n\n match result.set_file( &file_name ) {\n\n Ok( () ) => {},\n\n Err(_) => {},\n\n },\n\n BufferInput::Command( command ) =>\n\n match result.set_file( &command.split_whitespace().next()\n\n .unwrap_or(\"command_stdout\") ) {\n\n Ok( () ) => {},\n", "file_path": "src/buf.rs", "rank": 37, "score": 6.448167698576203 }, { "content": " /// Save work to permanent file; behavior depends on do_append argument// {{{\n\n ///\n\n /// TODO: move to io.rs? I don't think so, it's a part of the\n\n /// functionality of the buffer\n\n /// TODO: set up default filename?\n\n /// # Panics\n\n /// # Errors\n\n /// # Safety\n\n /// # Examples\n\n pub fn write_to_disk<S: AsRef<OsStr> + ?Sized>( &mut self,// {{{\n\n file_name: &S, do_append: bool, address_initial: usize,\n\n address_final: usize ) -> Result<(), RedError> {\n\n // Make sure caller did their job!\n\n assert_addresses( address_initial, address_final, self.total_lines );\n\n // now let's do ours...\n\n let file_mode = FileMode{ f_write: !do_append, f_truncate: !do_append,\n\n f_append: do_append, f_create: true, ..Default::default() };\n\n // set as default file if one provided but not previously set\n\n if !file_name.as_ref().is_empty() && self.file == None {\n\n self.file = Some( file_name.as_ref().to_os_string() );\n", "file_path": "src/buf.rs", "rank": 38, "score": 6.41509585753411 }, { "content": " Ok(mut pb) => {\n\n pb.push(file_name);\n\n Some( pb.into_os_string() )\n\n },\n\n Err(_) => Some( file_name.to_os_string() ),\n\n }\n\n },\n\n };\n\n self.file = result.clone();\n\n let _ = fs::remove_file( &self.buffer_file ).is_ok();\n\n self.buffer_file = temp_file_name( Some( &result.unwrap() ));\n\n try!( self.store_buffer() );\n\n Ok( () )\n\n }// }}}\n\n// }}}\n\n /// Delete line// {{{\n\n ///\n\n /// TODO: Add error handling, Result<> return?\n\n /// actually, I think I should remove error handling here; only error\n\n /// would be line doesn't exist, in which case we can just do nothing.\n", "file_path": "src/buf.rs", "rank": 39, "score": 6.394279470555779 }, { "content": "/// Return true if character at indx is part of address// {{{\n\n///\n\n/// first, checks to see if character is preceded by a single-quote, which\n\n/// would indicate that it is a marker;\n\n/// then, checks to see if character is part of a regular expression via\n\n/// the is_in_regex function;\n\nfn is_in_addr( text: &str, indx: usize ) -> bool {// {{{\n\n is_marker( text, indx ) || is_in_regex( text, indx )\n\n}// }}}\n", "file_path": "src/parse.rs", "rank": 40, "score": 6.351650419049613 }, { "content": " for address in _initial .. _final + 1 {\n\n let line = state.buffer.get_line_content( address ).unwrap_or(\"\");\n\n try!( writer.write( line_prefix.as_bytes() )\n\n .map_err(|_| RedError::Stdout));\n\n ch_written += line_prefix.len();\n\n for ch in line.chars() {\n\n for _ch in ch.escape_default() {\n\n try!( writer.write( &[_ch as u8] )\n\n .map_err(|_| RedError::Stdout));\n\n ch_written += 1;\n\n if line_prefix.len() == 0 && ch_written ==\n\n ( term_width - line_prefix.len() ) * ( term_height - 1 ) {\n\n try!( writer.flush().map_err(|_| RedError::Stdout));\n\n prompt_for_more( &mut writer );\n\n }\n\n }\n\n }\n\n try!( writer.write( \"$\\n\".as_bytes() ).map_err(|_| RedError::Stdout));\n\n ch_written += 1;\n\n ch_written += term_width - ( ch_written % term_width );\n\n try!( writer.flush().map_err(|_| RedError::Stdout));\n\n }\n\n Ok( () )\n\n}//}}}\n", "file_path": "src/ops.rs", "rank": 41, "score": 6.100650320900069 }, { "content": "// *** Bring in to namespace *** {{{\n\nuse std::collections::hash_map::HashMap;\n\nuse std::process::exit;\n\nuse std::io::{Write, BufRead, BufWriter, stdout, StdoutLock, stdin};\n\nuse std::ffi::OsStr;\n\n\n\nuse buf::*;\n\nuse error::*;\n\nuse parse::*;\n\nuse io::get_input;\n\nuse ::{EditorState, EditorMode, print_help, print_msg, term_size, Change};\n\nuse self::NotableLine::*;\n\n// ^^^ Bring in to namespace ^^^ }}}\n\n\n\n// *** Attributes *** {{{\n\nconst NUM_OPERATIONS: usize = 27;\n\nconst COMMAND_PREFIX: &'static str = \"@\";\n\n// ^^^ Attributes ^^^ }}}\n\n\n\n// *** Constants *** {{{\n\n// ^^^ Constants ^^^ }}}\n\n\n\n// *** Data Structures *** {{{\n", "file_path": "src/ops.rs", "rank": 42, "score": 5.936739199080927 }, { "content": "/// Execute a set of commands on lines matching pattern\n\n///\n\n/// TODO:\n\n/// * current address handling is a bit simplified for now\n\n/// * creating new operations object may be costly (?)\n\nfn global( state: &mut EditorState, command: Command )\n\n -> Result<(), RedError> {// {{{\n\n assert_eq!( 'g', command.operation );\n\n let ( _initial, _final ) = default_addrs( state, &command );\n\n let ( pattern, commands ) = try!(parse_global_op(command.parameters));\n\n for address in _initial .. _final + 1 {\n\n if state.buffer.does_match( pattern, address ) {\n\n try!( command.operations.execute_list( state, commands, address ));\n\n }\n\n }\n\n Ok( () )\n\n}//}}}\n", "file_path": "src/ops.rs", "rank": 43, "score": 5.890486969446993 }, { "content": " close_file_buffer_test( &mut buffer );\n\n }// }}}\n\n// }}}\n\n /// Test get_file_path() and set_file() functions// {{{\n\n #[test]\n\n fn file_buffer_test_4() {// {{{\n\n // set contstants\n\n let test_num: u8 = 4;\n\n let alt_file_name = \"red_anothertest\".to_string();\n\n let mut buffer = open_file_buffer_test( test_num );\n\n buffer.move_file( &(TEST_FILE.to_string() + FILE_FILE_SUFFIX +\n\n test_num.to_string().as_str() )).unwrap();\n\n //\n\n\n\n // Apply actual test(s)\n\n {\n\n assert_eq!( buffer.get_file_name().unwrap_or(OsStr::new(\"\")),\n\n &OsStr::new( &(TEST_FILE.to_string() + FILE_FILE_SUFFIX +\n\n test_num.to_string().as_str()) ).to_os_string() );\n\n buffer.set_file( &alt_file_name ).unwrap();\n", "file_path": "src/buf.rs", "rank": 44, "score": 5.769655857660899 }, { "content": " match &self.file {\n\n &Some( ref file_path ) => Some( file_path ),\n\n &None => None,\n\n }\n\n }// }}}\n\n// }}}\n\n /// Set new working file name; remove file at old name// {{{\n\n #[cfg(test)]\n\n pub fn move_file( &mut self, path: &str )\n\n -> Result<(), RedError> {// {{{\n\n match &self.file {\n\n &Some(ref f) => { let _ = fs::remove_file(f).is_ok(); },\n\n &None => {},\n\n };\n\n try!( self.set_file( path ) );\n\n Ok( () )\n\n }//}}}\n\n//}}}\n\n\n\n /// Set new working file name// {{{\n", "file_path": "src/buf.rs", "rank": 45, "score": 5.426603899362602 }, { "content": " }\n\n // use provided file, or default if one not provided\n\n let file_to_use: &OsStr = match file_name.as_ref().is_empty() {\n\n true => {\n\n match &self.file {\n\n &Some(ref f) => {\n\n f\n\n },\n\n &None => {\n\n println!(\"No file name chosen for save\");\n\n return Err(\n\n RedError::ParameterSyntax{\n\n parameter: \"\".to_string() });\n\n },\n\n }\n\n },\n\n false => file_name.as_ref(),\n\n };\n\n let mut file_opened = try!( file_opener( file_to_use, file_mode ));\n\n for line in self.range_iterator( address_initial, address_final ) {\n", "file_path": "src/buf.rs", "rank": 46, "score": 5.290532367436693 }, { "content": " let num_lines: usize = 21; // number of lines to have in buffer\n\n let test_file: String = TEST_FILE.to_string() + \".\" +\n\n random_string().as_str() +\n\n COMMAND_FILE_SUFFIX + test_num.to_string().as_str();\n\n let test_command = \"echo -e \".to_string() +\n\n &test_lines( cmd_content_line,\n\n num_lines );\n\n let mut buffer = Buffer::new( BufferInput::Command( test_command ))\n\n .unwrap();\n\n buffer.move_file( &test_file ).unwrap();\n\n buffer\n\n }// }}}\n\n// }}}\n\n /// Call command test buffer generator//{{{\n\n pub fn open_command_buffer_test( test_num: u8 )// {{{\n\n -> Buffer {\n\n open_command_buffer_test_gen( test_num, COMMAND_CONTENT_LINE )\n\n }// }}}\n\n// }}}\n\n /// Prep and return buffer for use in \"empty buffer\" test functions// {{{\n", "file_path": "src/buf.rs", "rank": 47, "score": 4.928850245328562 }, { "content": "impl Buffer { //{{{\n\n /// Initialize new Buffer instance// {{{\n\n pub fn new( content: BufferInput ) -> Result<Buffer, RedError> {//{{{\n\n let mut _lines = Buffer::init_lines( &content );\n\n let _total_lines = _lines.len();\n\n let mut result = Buffer {\n\n lines: _lines,\n\n buffer_file: match &content {\n\n &BufferInput::File( ref file_name ) =>\n\n temp_file_name( Some( file_name.as_str() )),\n\n _ => temp_file_name( None::<&str> ),\n\n },\n\n markers: vec!( 0; NUM_LC ),\n\n current_line: _total_lines, // usize; should be Copy\n\n total_lines: _total_lines,\n\n _is_modified: false,\n\n /* Comment until it becomes relevant\n\n last_update: match &content {\n\n &BufferInput::File(_) => UTC::now(),\n\n _ => get_null_time(),\n", "file_path": "src/buf.rs", "rank": 48, "score": 4.896856377414094 }, { "content": " /// timestamped path of file where buffer is stored regularly\n\n buffer_file: OsString, // convert to Path later\n\n /// collection of markers set for lines in lines\n\n markers: Vec<usize>,\n\n /// line number of \"cursor\"\n\n ///\n\n /// By default, searches start from here, inserts go here, etc.\n\n current_line: usize,\n\n /// current total number of lines in lines\n\n total_lines: usize,\n\n /// true if file has been modified since last write\n\n _is_modified: bool,\n\n /// Date and time of last read of source file\n\n //last_update: DateTime<UTC>,\n\n /// Date and time of last write to disk under temporary file name\n\n last_temp_write: DateTime<UTC>,\n\n /// Date and time of last write to disk under permanent file name\n\n last_write: DateTime<UTC>,\n\n} //}}}\n\n// }}}\n", "file_path": "src/buf.rs", "rank": 49, "score": 4.868376291962824 }, { "content": " const FILE_CONTENT_LINE: &'static str = \"testfile line number\";\n\n const COMMAND_CONTENT_LINE: &'static str = \"testcmd line number\";\n\n const FILE_FILE_SUFFIX: &'static str = \".file\";\n\n const COMMAND_FILE_SUFFIX: &'static str = \".cmd\";\n\n // ^^^ ^^^ Constants ^^^ ^^^ //// }}}\n\n // begin prep functions// {{{\n\n /// Generate and return string containing lines for testing// {{{\n\n ///\n\n /// Takes string to use as base for text on each line\n\n /// This string will have the line number appended\n\n /// Also takes a single u8 integer, the number of lines to generate\n\n fn test_lines( line_str: &str, num_lines: usize ) -> String {// {{{\n\n let mut file_content = \"\".to_string();\n\n let mut next: String;\n\n for i in 1 .. ( num_lines + 1 ) {\n\n next = line_str.to_string() + i.to_string().as_str();\n\n next = next + r\"\\n\";\n\n file_content.push_str( &next );\n\n }\n\n file_content\n", "file_path": "src/buf.rs", "rank": 50, "score": 4.493096239300613 }, { "content": "/// Type of input for starting buffer// {{{\n\n///\n\n/// File - read from existing file\n\n/// Command - read output of specified command\n\n/// None - no input\n\npub enum BufferInput {// {{{\n\n File(String), // box it?\n\n Command(String), // OsString? box it?\n\n None,\n\n}// }}}\n\n// }}}\n\n/// Stores collection of lines containing current working text// {{{\n\n///\n\npub struct Buffer { //{{{\n\n /// the current working buffer content as a list of lines\n\n lines: LinkedList<String>,\n\n /// the optional path of file being worked on\n\n ///\n\n /// Is None if no exising file was loaded and not yet saved\n\n file: Option<OsString>,\n", "file_path": "src/buf.rs", "rank": 51, "score": 4.482045661002188 }, { "content": " }// }}}\n\n// }}}\n\n /// Test get_line_content() values// {{{\n\n #[test]\n\n fn file_buffer_test_2() {// {{{\n\n // set contstants\n\n let test_num: u8 = 2;\n\n //\n\n let mut buffer = open_file_buffer_test( test_num );\n\n let mut expectation: String;\n\n //\n\n\n\n // Apply actual test(s)\n\n {\n\n // NOTE: We don't iterate to num_lines+1 because the last line\n\n // is blank and won't match the expectation value\n\n for test_line in 1 .. buffer.num_lines() {\n\n expectation = FILE_CONTENT_LINE.to_string() +\n\n test_line.to_string().as_str();\n\n assert_eq!( *buffer.get_line_content( test_line ).unwrap(),\n", "file_path": "src/buf.rs", "rank": 52, "score": 4.411262587630281 }, { "content": " self.total_lines += 1;\n\n }// }}}\n\n// }}}\n\n /// Replace line with new string// {{{\n\n ///\n\n /// TODO: Add error handling; panics if address > len\n\n /// I don't think that will be necessary\n\n pub fn set_line_content( &mut self, address: usize, new_line: &str )// {{{\n\n -> Result<(), RedError> {\n\n if address > self.lines.len() {\n\n return Err( RedError::SetLineOutOfBounds{ address: address } );\n\n }\n\n let mut back_list = self.lines.split_off( address - 1 );\n\n let _ = back_list.pop_front();\n\n self.lines.push_back( new_line.to_string() );\n\n self.lines.append( &mut back_list );\n\n self._is_modified = true;\n\n Ok( () )\n\n }// }}}\n\n// }}}\n", "file_path": "src/buf.rs", "rank": 53, "score": 4.40875869798159 }, { "content": " // restore all values to defaults - necessary?\n\n self.lines.clear();\n\n self.file = None;\n\n self.buffer_file = OsStr::new( \"\" ).to_os_string();\n\n self.markers = Vec::new();\n\n self.current_line = 0;\n\n self.total_lines = 0;\n\n self._is_modified = false;\n\n //XXX: self.last_update = get_null_time();\n\n self.last_temp_write = get_null_time();\n\n self.last_write = get_null_time();\n\n }// }}}\n\n /// Keep markers valid after inserting new line\n\n ///\n\n /// I can't think of any errors that might go here\n\n fn insert_update_markers( &mut self, address: usize ) {\n\n for marker in &mut self.markers {\n\n if *marker > address {\n\n *marker += 1;\n\n }\n", "file_path": "src/buf.rs", "rank": 54, "score": 4.345455985847009 }, { "content": "use std::ffi::{OsStr,OsString};\n\n\n\nuse ::chrono::*;\n\nuse ::regex::{Regex, Captures};\n\nuse ::rand::{thread_rng, Rng};\n\n\n\nuse io::*;\n\nuse error::*;\n\nuse parse::*;\n\n\n\n// ^^^ Bring in to namespace ^^^ }}}\n\n// *** Attributes *** {{{\n\n// ^^^ Attributes ^^^ }}}\n\n\n\n// *** Constants *** {{{\n\npub const NUM_LC: usize = 26;\n\nconst SAVE_RETRIES: usize = 3;\n\n// ^^^ Constants ^^^ }}}\n\n\n\n// *** Data Structures *** {{{\n", "file_path": "src/buf.rs", "rank": 55, "score": 4.338482488325623 }, { "content": "// }}}\n\n/// Parse parameter for g, v operations// {{{\n\n///\n\n/// Confirms that a properly formatted regex leads\n\n/// a set of commands, one on each line; possibly one\n\n/// on the same line as the regex.\n\n/// Returns Result::Err( RedError::ParameterSyntax ) if\n\n/// no regex is found;\n\n/// Otherwise, returns tuple - pattern, list of commands\n\n/// # Panics\n\n/// * unable to compile regular expression pattern\n\n/// from ADDR_REGEX_FWDSEARCH - should never happen\n\n/// * Finds match but somehow there is no capture\n\npub fn parse_global_op<'a>( g_op: &'a str )// {{{\n\n -> Result<(&'a str, &'a str), RedError> {\n\n let re_pattern: Regex = Regex::new( ADDR_REGEX_FWDSEARCH ).unwrap();\n\n let pattern: &'a str = match &re_pattern.captures( g_op ) {\n\n &Some(ref s) => s.at(1)\n\n .expect(\"already confirmed match; capture expected\"),\n\n &None => return Err( RedError::ParameterSyntax{ parameter:\n\n \"parse_global_op: \".to_string() + g_op }),\n\n };\n\n let (_, right) = re_pattern.find( g_op )\n\n .expect(\"parse_global_op: already proved match, now not matching\");\n\n let commands: &'a str = &g_op[right ..];\n\n Ok( (pattern, commands) )\n\n}// }}}\n\n// }}}\n\n// ^^^ Functions ^^^ }}}\n\n#[cfg(test)]\n\nmod tests {\n\n use super::{get_opchar_index, is_in_regex, parse_address_field, parse_address_list, get_address_range, is_address_separator};\n\n use buf::*;\n", "file_path": "src/parse.rs", "rank": 56, "score": 4.212970940071606 }, { "content": "// *** Functions *** {{{\n\n/// Avoid `unused` warnings for functions that don't modify mode// {{{\n\nfn mode_noop( mode: &mut EditorMode ) -> EditorMode {// {{{\n\n match mode {\n\n &mut EditorMode::Command => EditorMode::Command,\n\n &mut EditorMode::Insert => EditorMode::Insert,\n\n }\n\n}// }}}\n", "file_path": "src/ops.rs", "rank": 57, "score": 4.168102591011746 }, { "content": " buffer: Buffer,\n\n /// file name or command from which our initial text originates\n\n source: String,\n\n /// most recent help, warning, or error message\n\n last_help: String,\n\n /// last regex used in address search\n\n last_regex: String,\n\n /// structure containing enough information to roll back latest change\n\n undo: Undo,\n\n}\n\nimpl EditorState {\n\n /// Initialize new editor state// {{{\n\n ///\n\n /// This will be used when program first loads, and any time we open\n\n /// a new file or command using e.g. the edit operation\n\n pub fn new( _buffer: Buffer ) -> EditorState {// {{{\n\n EditorState { mode: DEFAULT_MODE, show_help: DEFAULT_HELP,\n\n show_messages: DEFAULT_MESSAGES, prompt: DEFAULT_PROMPT.to_string(),\n\n buffer: _buffer, source: String::new(), last_help: String::new(),\n\n last_regex: String::new(), undo: Undo::new(), }\n", "file_path": "src/main.rs", "rank": 58, "score": 4.1185028380731925 }, { "content": " // Apply actual test(s)\n\n {\n\n let mut lines_iter = buffer.lines_iterator();\n\n // NOTE: We don't iterate to num_lines+1 because the last line\n\n // is blank and won't match the expectation value\n\n for test_line in 1 .. buffer.num_lines() {\n\n expectation = FILE_CONTENT_LINE.to_string() +\n\n test_line.to_string().as_str();\n\n match lines_iter.next() {\n\n Some( line ) => {\n\n assert_eq!( *line, expectation );\n\n },\n\n None => break,\n\n }\n\n }\n\n }\n\n\n\n //\n\n\n\n // Common test close routine\n", "file_path": "src/buf.rs", "rank": 59, "score": 4.033372424886246 }, { "content": " assert_eq!( buffer.get_file_path().unwrap_or(OsStr::new(\"\")),\n\n OsStr::new( &alt_file_name ) );\n\n buffer.set_file( &(TEST_FILE.to_string() +\n\n FILE_FILE_SUFFIX + test_num.to_string().as_str() )).unwrap();\n\n }\n\n\n\n //\n\n\n\n // Common test close routine\n\n close_file_buffer_test( &mut buffer );\n\n }// }}}\n\n// }}}\n\n /// Test modifying buffer// {{{\n\n #[test]\n\n fn file_buffer_test_5() {// {{{\n\n // set contstants\n\n let test_num: u8 = 5;\n\n let test_line: usize = 2;\n\n let new_line_content: String = \"This is the new line!\".to_string();\n\n let mut buffer = open_file_buffer_test( test_num );\n", "file_path": "src/buf.rs", "rank": 60, "score": 3.964327150293144 }, { "content": "// *** Functions *** {{{\n\nfn main() {// {{{\n\n // initialize buffer\n\n let _buffer = Buffer::new( BufferInput::None )\n\n .expect( \"main: failed to create initial empty buffer\" );\n\n // Construct operations hashmap\n\n let operations: Operations = Operations::new();\n\n // initialize editor state\n\n let mut state = EditorState::new( _buffer );\n\n // Collect invocation arguments\n\n let args: Vec<String> = env::args().collect();\n\n parse_invocation( args, &mut state );\n\n if state.source.len() > 0 {\n\n // generate and execute edit operation for requested file or command\n\n let command = Command{ address_initial: 0, address_final: 0,\n\n operation: 'e', parameters: &state.source.clone(),\n\n operations: &operations };\n\n operations.execute( &mut state, command )\n\n .expect( \"main: failed to initialize buffer\" );\n\n } else {\n\n state.buffer.set_file( \"untitled\" )\n", "file_path": "src/main.rs", "rank": 61, "score": 3.9350289017251767 }, { "content": " .unwrap();\n\n buffer.move_file( &test_file ).unwrap();\n\n buffer.set_current_address( 1 );\n\n EditorState::new(buffer)\n\n }// }}}\n\n /// deconstruct buffer from \"command buffer\" test;\n\n /// any other necessary closing actions\n\n pub fn close_command_buffer_test( state: &mut EditorState ) {// {{{\n\n state.buffer.destruct();\n\n }// }}}\n\n // begin prep functions\n\n /// Generate and return string containing lines for testing\n\n ///\n\n /// Takes string to use as base for text on each line\n\n /// This string will have the line number appended\n\n /// Also takes a single u8 integer, the number of lines to generate\n\n fn test_lines( line_str: &str, num_lines: usize ) -> String {// {{{\n\n let mut file_content = \"\".to_string();\n\n let mut next: String;\n\n for i in 1 .. ( num_lines + 1 ) {\n", "file_path": "src/parse.rs", "rank": 62, "score": 3.8535962853704717 }, { "content": " BufferInput::File( ref file_name ) => {\n\n let file_path = Path::new( &file_name );\n\n let _file = file_path;\n\n let file_mode = FileMode{ f_read: true, ..Default::default() };\n\n if !_file.exists() {\n\n return Buffer::init_lines( &BufferInput::None );\n\n }\n\n let file_opened: File;\n\n match file_opener( file_name, file_mode ) {\n\n Ok( _file_opened ) => {\n\n file_opened = _file_opened;\n\n },\n\n Err(_) => {\n\n return Buffer::init_lines( &BufferInput::None );\n\n },\n\n }\n\n let reader = BufReader::new( file_opened );\n\n LinkedList::from_iter( reader.lines()\n\n .map(|result| result.unwrap() ) )\n\n // reader.lines() returns an iterator (Lines type) over\n", "file_path": "src/buf.rs", "rank": 63, "score": 3.8087107983888915 }, { "content": "// *** Functions *** {{{\n\n/// Parses invocation {{{\n\npub fn parse_invocation( invoc_input: Vec<String>, state: &mut EditorState ) {//{{{\n\n let mut indx: usize = 1;\n\n while indx < invoc_input.len() {\n\n if invoc_input[indx] == \"-s\" || invoc_input[indx] == \"-\" {\n\n state.show_help = false;\n\n state.show_messages = false;\n\n //println!( \"help and messages turned off (except this one)\" );\n\n println!( \"SILENT MODE ACTIVE\" );\n\n } else if invoc_input[indx] == \"-p\" {\n\n if indx + 1 < invoc_input.len() {\n\n indx += 1;\n\n state.prompt = invoc_input[indx].clone();\n\n println!( \"prompt set to {}\", &state.prompt );\n\n } else {\n\n println!( \"no prompt provided to \\\"-p\\\" flag\" );\n\n }\n\n } else if &invoc_input[indx][0..1] == \"-\" {\n\n println!( \"unrecognized flag: {}\", invoc_input[indx] );\n\n } else {\n\n if state.source.len() == 0 {\n\n state.source = invoc_input[indx].clone();\n\n } else {\n\n println!( \"only the first commnand or file name accepted\" );\n\n }\n\n }\n\n indx += 1;\n\n }\n\n}//}}}\n", "file_path": "src/parse.rs", "rank": 64, "score": 3.7903299021678873 }, { "content": " ///\n\n /// At some point, need to test for existing file and ask user if overwrite\n\n pub fn set_file<S: AsRef<OsStr> + ?Sized>( &mut self, path: &S )\n\n -> Result<(), RedError> {// {{{\n\n let result: Option<OsString>;\n\n let file_path = Path::new( path );\n\n // abort if no valid file name provided\n\n let file_name = match file_path.file_name() {\n\n Some(f) => f,\n\n None => return Err( RedError::ParameterSyntax{ parameter:\n\n \"file_name: \".to_string() +\n\n path.as_ref().to_str().unwrap_or(\"<invalid UTF-8>\") } ),\n\n };\n\n result = match file_path.canonicalize() {\n\n Ok(pb) => Some( pb.into_os_string() ),\n\n Err(_) => {\n\n let mut file_pathbuf = file_path.to_path_buf();\n\n file_pathbuf.pop();\n\n let parent = file_pathbuf.as_path();\n\n match parent.canonicalize() {\n", "file_path": "src/buf.rs", "rank": 65, "score": 3.6944228771923657 }, { "content": " } else if x == \"\" {\n\n WhichMatch::Number(1)\n\n } else {\n\n WhichMatch::Number( try!( x.parse().map_err(|_|\n\n RedError::ParameterSyntax{\n\n parameter: sub_parm.to_string() })))\n\n }\n\n },\n\n None => return Err( RedError::ParameterSyntax{\n\n parameter: sub_parm.to_string() }),\n\n }\n\n })\n\n },\n\n None => return Err( RedError::ParameterSyntax{\n\n parameter: sub_parm.to_string() }),\n\n }\n\n}// }}}\n", "file_path": "src/parse.rs", "rank": 66, "score": 3.659883519345503 }, { "content": "// }}}\n\n/// A simple placeholder function for unimplemented features// {{{\n\nfn placeholder( state: &mut EditorState, command: Command)//{{{\n\n -> Result<(), RedError> {\n\n print_msg( state, &format!(\n\n \"Operation not yet implemented: {}\", command.operation ));\n\n state.mode = mode_noop( &mut state.mode );\n\n match state.buffer.get_file_name() {\n\n Some( file_name ) => {\n\n print_msg( state, &format!(\n\n \"Continuing work on {}\", file_name.to_str()\n\n .unwrap_or(\"<invalid UTF-8>\")) );\n\n return Err(\n\n RedError::InvalidOperation{ operation: command.operation } );\n\n }\n\n None => {\n\n return Err(\n\n RedError::InvalidOperation{ operation: command.operation } );\n\n }\n\n }\n\n}// }}}\n", "file_path": "src/ops.rs", "rank": 67, "score": 3.655895214829214 }, { "content": "// XXX: write built-in implementation in Buffer?\n\nfn print_numbered( state: &mut EditorState,//{{{\n\n command: Command ) -> Result<(), RedError> {\n\n assert_eq!( 'n', command.operation );\n\n let ( _initial, _final ) = default_addrs( state, &command );\n\n let num_lines_f: f64 = state.buffer.num_lines() as f64 + 1.0_f64;\n\n let _width = num_lines_f.log10().ceil() as usize;\n\n for ( _num, _line ) in state.buffer.lines_iterator().enumerate()\n\n .skip( _initial - 1 )\n\n .take(( _final + 1 ) - _initial )\n\n .map( |(x, y)| ( x+1, y )) {\n\n print!( \"{:width$}|\", _num, width = _width );\n\n println!(\"{}\", _line );\n\n }\n\n state.buffer.set_current_address( _final );\n\n Ok( () )\n\n}//}}}\n", "file_path": "src/ops.rs", "rank": 68, "score": 3.620708907337984 }, { "content": "// XXX: write built-in implementation in Buffer?\n\nfn lines_list( state: &mut EditorState, command: Command )\n\n -> Result<(), RedError> {// {{{\n\n assert_eq!( 'l', command.operation );\n\n let ( _initial, _final ) = default_addrs( state, &command );\n\n let stdout = stdout();\n\n let handle = stdout.lock();\n\n let mut writer = BufWriter::new( handle );\n\n let mut ch_written: usize = 0;\n\n let line_prefix: &str; // ! to indicate unknown screen size\n\n let term_width: usize;\n\n let term_height: usize;\n\n if let Some((w, h)) = term_size::dimensions() {\n\n line_prefix = \"\";\n\n term_width = w;\n\n term_height = h;\n\n } else {\n\n line_prefix = \"!\";\n\n term_width = 0;\n\n term_height = 0;\n\n }\n", "file_path": "src/ops.rs", "rank": 69, "score": 3.620708907337984 }, { "content": " OpData{ function: Box::new(write_to_disk),\n\n default_initial_address: FirstLine,\n\n default_final_address: LastLine,\n\n }\n\n );// }}}\n\n _operation_map.insert( 'W',// {{{\n\n OpData{ function: Box::new(append_to_disk),\n\n default_initial_address: FirstLine,\n\n default_final_address: LastLine,\n\n }\n\n );// }}}\n\n //}}}\n\n Operations { operation_map: _operation_map }\n\n }// }}}\n\n// }}}\n\n /// Execute command// {{{\n\n pub fn execute( &self, state: &mut EditorState, command: Command )//{{{\n\n -> Result<(), RedError> {\n\n match self.operation_map.contains_key( &command.operation ) {\n\n true => {\n", "file_path": "src/ops.rs", "rank": 70, "score": 3.518619967570777 }, { "content": " let lines_ref: &LinkedList<String> = &self.lines;\n\n lines_ref.into_iter()\n\n }// }}}\n\n// }}}\n\n /// Return reference to working file name string// {{{\n\n pub fn get_file_name( &self ) -> Option<&OsStr> {// {{{\n\n match self.file {\n\n Some( ref _file ) => {\n\n let file_path = Path::new( _file );\n\n Some( file_path.file_name()\n\n .expect(\"path does not have a file name\")\n\n )\n\n },\n\n None => None,\n\n }\n\n }// }}}\n\n// }}}\n\n /// Return reference to working file name string// {{{\n\n #[cfg(test)]\n\n pub fn get_file_path( &self ) -> Option<&OsStr> {// {{{\n", "file_path": "src/buf.rs", "rank": 71, "score": 3.4765221812839577 }, { "content": " }\n\n // not reached due to `if attempt == (SAVE_RETRIES - 1)`\n\n Err( RedError::CriticalError( \"reached unreachable line\".to_string() ))\n\n }//}}}\n\n// }}}\n\n /// Return total number of lines in buffer// {{{\n\n pub fn num_lines( &self ) -> usize {// {{{\n\n self.total_lines\n\n }// }}}\n\n// }}}\n\n /// Return true if buffer modified since last write// {{{\n\n pub fn is_modified( &self ) -> bool {// {{{\n\n self._is_modified\n\n }// }}}\n\n// }}}\n\n // later, change approach to homogenize file/stdout source\n\n // generate iterator over BufRead object, either file, stdout, or empty\n\n /// Return the linked-list of lines to store in buffer// {{{\n\n fn init_lines( content: &BufferInput ) -> LinkedList<String> {// {{{\n\n match *content {\n", "file_path": "src/buf.rs", "rank": 72, "score": 3.429457586221699 }, { "content": "// }}}\n\n/// Exit program// {{{\n\n///\n\n/// Make sure all state.buffers have been saved\n\n///\n\n/// Delete all temprary storage\n\nfn quit( state: &mut EditorState, command: Command )//{{{\n\n -> Result<(), RedError> {\n\n assert_eq!( 'q', command.operation );\n\n match state.buffer.on_close() {\n\n Ok( _ ) => exit( error_code( RedError::Quit ) as i32),\n\n Err( _ ) => exit( error_code( RedError::NoDestruct ) as i32),\n\n }\n\n}// }}}\n", "file_path": "src/ops.rs", "rank": 73, "score": 3.378834831589887 }, { "content": " } else {\n\n ( 1, command.address_final )\n\n }\n\n } else {\n\n ( command.address_initial, command.address_final )\n\n }\n\n}// }}}\n\n// }}}\n\n// ^^^ Functions ^^^ }}}\n\n\n", "file_path": "src/ops.rs", "rank": 74, "score": 3.3581313343565546 }, { "content": "// *** Constants *** {{{\n\nconst DEFAULT_MODE: EditorMode = EditorMode::Command;\n\nconst DEFAULT_HELP: bool = true;\n\nconst DEFAULT_MESSAGES: bool = true;\n\nconst DEFAULT_PROMPT: &'static str = \"%\";\n\n// ^^^ Constants ^^^ }}}\n\n// *** Data Structures *** {{{\n\n/// Contain state values for the program during execution\n\n///\n\n/// TODO: include buffer and command structures?\n\n#[derive(Clone)]\n\npub struct EditorState {\n\n /// enum indicating current mode: Command (aka Normal) or Insert\n\n mode: EditorMode,\n\n /// whether to show or hide informational output\n\n show_messages: bool,\n\n /// whether to show or hide help, warnings, and error messages\n\n show_help: bool,\n\n prompt: String,\n\n /// structure containing all text and plenty of logic for manipulating it\n", "file_path": "src/main.rs", "rank": 75, "score": 3.31343972004066 }, { "content": "// }}}\n\n/// Get DateTime to use as Null value// {{{\n\n///\n\n/// # Panics\n\n/// # Errors\n\n/// # Safety\n\n/// # Examples\n\nfn get_null_time() -> datetime::DateTime<UTC> {// {{{\n\n let utc_instance: UTC = UTC {};\n\n utc_instance.timestamp( 0, 0 )\n\n}// }}}\n", "file_path": "src/buf.rs", "rank": 76, "score": 3.307136389236372 }, { "content": " pub fn delete_line( &mut self, address: usize )\n\n -> Result<(), RedError> {// {{{\n\n if address > self.lines.len() {\n\n return Err( RedError::GetLineOutOfBounds{ address: address } );\n\n }\n\n let mut back = self.lines.split_off( address );\n\n match self.lines.pop_back() {\n\n Some(_) => {},\n\n None => {\n\n return Err(\n\n RedError::GetLineOutOfBounds{ address: address } );\n\n },\n\n }\n\n self.lines.append( &mut back );\n\n self.delete_update_markers( address );\n\n self.total_lines -= 1; // previous tests preclude underflow here?\n\n self._is_modified = true;\n\n Ok( () )\n\n }// }}}\n\n// }}}\n", "file_path": "src/buf.rs", "rank": 77, "score": 3.265179289172674 }, { "content": " expectation );\n\n }\n\n }\n\n\n\n //\n\n\n\n // Common test close routine\n\n close_file_buffer_test( &mut buffer );\n\n }// }}}\n\n// }}}\n\n /// Test lines_iterator() values// {{{\n\n #[test]\n\n fn file_buffer_test_3() {// {{{\n\n // set contstants\n\n let test_num: u8 = 3;\n\n //\n\n let mut buffer = open_file_buffer_test( test_num );\n\n let mut expectation: String;\n\n //\n\n\n", "file_path": "src/buf.rs", "rank": 78, "score": 3.133353966776742 }, { "content": " /// read line from buffer// {{{\n\n #[test]\n\n fn file_buffer_test_1() {// {{{\n\n // Common test start routine\n\n // set contstants\n\n let test_num: u8 = 1;\n\n let test_line: usize = 2;\n\n //\n\n let mut buffer = open_file_buffer_test( test_num );\n\n let expectation =\n\n FILE_CONTENT_LINE.to_string() + test_line.to_string().as_str();\n\n //\n\n\n\n // Apply actual test(s)\n\n assert_eq!( buffer.get_line_content( test_line ).unwrap(),\n\n &expectation );\n\n //\n\n\n\n // Common test close routine\n\n close_file_buffer_test( &mut buffer );\n", "file_path": "src/buf.rs", "rank": 79, "score": 3.12391863208451 }, { "content": " match Buffer::new(BufferInput::File( content.to_string() )) {\n\n Ok( _buffer ) => {\n\n state.buffer = _buffer;\n\n },\n\n Err(e) => {\n\n return Err(e);\n\n },\n\n };\n\n print_msg( &state, &format!( \"Now editing file: {}\",\n\n state.buffer.get_file_name()\n\n .unwrap_or( OsStr::new(\"<untitled>\") )\n\n .to_str()\n\n .unwrap_or( \"<invalid UTF-8>\" ) ));\n\n }\n\n Ok( () )\n\n}//}}}\n", "file_path": "src/ops.rs", "rank": 80, "score": 3.084364421770138 }, { "content": "//}}}\n\n/// Return true if index is contained in regex// {{{\n\n///\n\n/// Is regex if wrapped in /.../ or ?...? within larger string\n\n/// In some functions, we need to know this so we know how to treat the\n\n/// character\n\nfn is_in_regex( text: &str, indx: usize ) -> bool {// {{{\n\n let regex: Vec<u8> = vec!(b'/', b'?');\n\n let mut c_regex: Vec<bool> = vec!( false; regex.len() );\n\n let mut c_indx: usize = 0;\n\n let mut escaped: bool = false;\n\n //\n\n let (left, _) = text.split_at( indx );\n\n //\n\n for ch in left.bytes() {\n\n if left.is_char_boundary( c_indx ) {\n\n if ch == b'\\\\' {\n\n escaped = !escaped;\n\n c_indx += 1;\n\n continue\n\n }\n\n for i in 0 .. regex.len() {\n\n if ch == regex[i] {\n\n if !escaped && !is_quoted( text, c_indx ) &&\n\n c_regex[1-i] == false { // can't have both\n\n c_regex[i] = !c_regex[i]; // switch on/off\n", "file_path": "src/parse.rs", "rank": 81, "score": 3.059139828511065 }, { "content": " \"-\" => {\n\n operand_subs += match operand_str {\n\n \"\" => 1,\n\n _ => try!( operand_str.parse()\n\n .map_err(|_| RedError::AddressSyntax{\n\n address: \"calc3:\".to_string() + address } )),\n\n };\n\n },\n\n _ => {\n\n return Err( RedError::AddressSyntax{\n\n address: \"calc4:\".to_string() + address });\n\n },\n\n }\n\n\n\n match next_step_caps.at(4) {\n\n Some( \"\" ) => break,\n\n Some( x ) => next_step_str = x,\n\n None => return Err( RedError::AddressSyntax{\n\n address: \"calc5:\".to_string() + address }),\n\n }\n\n next_step_caps = re_addorsubt.captures( next_step_str ).unwrap();\n\n }\n\n\n\n if operand_subs > operand_adds {\n\n Ok( Some( 1 ))\n\n } else {\n\n Ok( Some( normalize_address( &buffer, operand_adds - operand_subs ) ))\n\n }\n\n}// }}}\n", "file_path": "src/parse.rs", "rank": 82, "score": 3.0512843286760827 }, { "content": " match lines_iter.next() {\n\n Some( line ) => {\n\n assert_eq!( *line, expectation );\n\n },\n\n None => break,\n\n }\n\n }\n\n }\n\n\n\n //\n\n\n\n // Common test close routine\n\n close_file_buffer_test( &mut buffer );\n\n }// }}}\n\n #[test]\n\n fn substitute_test_1() {// {{{\n\n let test_num: u8 = 1;\n\n let mut buffer = open_file_buffer_test( test_num );\n\n let num_lines = buffer.num_lines() - 1;\n\n let expectation: String = \"line testfile number\".to_string();\n", "file_path": "src/buf.rs", "rank": 84, "score": 2.8816225049523814 }, { "content": " /// Unlock undo structure//{{{\n\n pub fn u_unlock( &mut self ) {// {{{\n\n self.undo.unlock()\n\n }// }}}\n\n // }}}\n\n /// Unlock undo structure//{{{\n\n pub fn u_get_wascurrent_address( &self ) -> usize {// {{{\n\n self.undo.get_wascurrent_address()\n\n }// }}}\n\n // }}}\n\n}\n\n#[derive(Clone)]\n\npub enum EditorMode {\n\n Command,\n\n Insert,\n\n}\n\n/// Lines to add, lines to remove, to be used by the undo operation\n\n///\n\n/// Perhaps not the most space-efficient approach, but probably faster and\n\n/// definitely simple; Inspired by diff;\n\n/// This could easily be extended to infinite undo by using a Vec of these.\n\n#[derive(Clone)]\n", "file_path": "src/main.rs", "rank": 85, "score": 2.8410767919507305 }, { "content": "/// Return pair of lines, either original or the specified defaults// {{{\n\n///\n\n/// Defaults are used if both original integers are 0;\n\n/// Also fixes lower address to be 1 instead of zero if an otherwise\n\n/// suitable range is provided;\n\nfn default_addrs( state: &EditorState, command: &Command ) -> (usize, usize) {// {{{\n\n let default_i = match command.operations.operation_map\n\n .get( &command.operation ).unwrap().default_initial_address {\n\n FirstLine => 1,\n\n LastLine => state.buffer.num_lines(),\n\n CurrentLine => state.buffer.get_current_address(),\n\n CurrentPlusOneLine => state.buffer.get_current_address() + 1,\n\n LineNotApplicable => 1,\n\n };\n\n let default_f = match command.operations.operation_map\n\n .get( &command.operation ).unwrap().default_final_address {\n\n FirstLine => 1,\n\n LastLine => state.buffer.num_lines(),\n\n CurrentLine => state.buffer.get_current_address(),\n\n CurrentPlusOneLine => state.buffer.get_current_address() + 1,\n\n LineNotApplicable => 1,\n\n };\n\n if command.address_initial == 0 {\n\n if command.address_final == 0 {\n\n ( default_i, default_f )\n", "file_path": "src/ops.rs", "rank": 86, "score": 2.804595710137049 }, { "content": "// }}}\n\n/// Turn address list into two address expressions// {{{\n\n///\n\n/// Returns the latter-two non-empty elements in a list\n\n/// elements are separated according to is_address_separator()\n\n/// separators inside /.../ or ?...? are ignored using is_in_regex()\n\nfn parse_address_list( address_string: &str ) -> (&str, &str) {// {{{\n\n let mut right: &str = address_string;\n\n let mut left: &str = \"\";\n\n\n\n loop {\n\n match right.find( is_address_separator ) {\n\n Some(indx) => {\n\n if !is_in_regex( address_string, indx ) {\n\n match right.split_at( indx ) {\n\n (x, y) => {\n\n if x.len() > 0 {\n\n left = x.trim();\n\n }\n\n right = &y[ 1 .. ].trim();\n\n }\n\n }\n\n }\n\n }\n\n None => {\n\n return ( left, right );\n\n },\n\n }\n\n }\n\n}// }}}\n", "file_path": "src/parse.rs", "rank": 87, "score": 2.729192371508262 }, { "content": " let ref op_to_execute = self.operation_map\n\n .get( &command.operation ).unwrap().function;\n\n op_to_execute( state, command )\n\n },\n\n false => {\n\n Err(RedError::InvalidOperation{ operation: command.operation })\n\n },\n\n }\n\n }// }}}\n\n // }}}\n\n /// Execute list of commands at address// {{{\n\n fn execute_list( &self, state: &mut EditorState,// {{{\n\n commands: &str, address: usize ) -> Result<(), RedError> {\n\n for cmd in commands.lines() {\n\n let mut _command: Command;\n\n if cmd.trim().is_empty() {\n\n _command = Command {\n\n address_initial: address,\n\n address_final: address,\n\n operation: 'p',\n", "file_path": "src/ops.rs", "rank": 88, "score": 2.71075513050371 }, { "content": " let test_num: u8 = 6;\n\n let mut buffer = open_file_buffer_test( test_num );\n\n let regex_str: &str = r#\"e\"#;\n\n let to_sub: &str = r#\"x\"#;\n\n let expectation: String = \"txstfilx linx numbxr8\".to_string();\n\n\n\n // Apply actual test(s)\n\n buffer.substitute( regex_str, to_sub, WhichMatch::Global, 8, 8 );\n\n assert_eq!( expectation, buffer.get_line_content(8).unwrap() );\n\n close_file_buffer_test( &mut buffer );\n\n }// }}}\n\n// }}}\n\n /*\n\n #[test]\n\n fn empty_buffer_test() {// {{{\n\n let buffer = open_empty_buffer_test();\n\n }// }}}\n\n */\n\n // end test functions }}}\n\n}// }}}\n\n\n", "file_path": "src/buf.rs", "rank": 89, "score": 2.6673310015626397 }, { "content": " 1, num_lines );\n\n let mut count = 0_usize;\n\n for line in buffer.lines_iterator() {\n\n count += 1;\n\n if count > num_lines {\n\n break;\n\n }\n\n _expectation = expectation.clone();\n\n _expectation.push_str( &count.to_string() );\n\n assert_eq!( _expectation, *line );\n\n }\n\n close_file_buffer_test( &mut buffer );\n\n }// }}}\n\n #[test]\n\n fn substitute_test_5() {// {{{\n\n let test_num: u8 = 5;\n\n let mut buffer = open_file_buffer_test( test_num );\n\n let num_lines = buffer.num_lines() - 1;\n\n let mut _expectation: String;\n\n let regex_str: &str = r#\"e\"#;\n", "file_path": "src/buf.rs", "rank": 90, "score": 2.6673310015626397 }, { "content": " let mut expectation: String;\n\n //\n\n\n\n // Apply actual test(s)\n\n {\n\n expectation = FILE_CONTENT_LINE.to_string() +\n\n test_line.to_string().as_str();\n\n assert_eq!( *buffer.get_line_content( test_line ).unwrap(),\n\n expectation );\n\n buffer.set_line_content( test_line, &new_line_content ).unwrap();\n\n expectation = new_line_content;\n\n assert_eq!( *buffer.get_line_content( test_line ).unwrap(),\n\n expectation );\n\n }\n\n\n\n //\n\n\n\n // Common test close routine\n\n close_file_buffer_test( &mut buffer );\n\n }// }}}\n", "file_path": "src/buf.rs", "rank": 91, "score": 2.631747442457119 }, { "content": " break;\n\n }\n\n _expectation = expectation.clone();\n\n _expectation.push_str( &count.to_string() );\n\n assert_eq!( _expectation, *line );\n\n }\n\n close_file_buffer_test( &mut buffer );\n\n }// }}}\n\n #[test]\n\n fn substitute_test_4() {// {{{\n\n let test_num: u8 = 4;\n\n let mut buffer = open_file_buffer_test( test_num );\n\n let num_lines = buffer.num_lines() - 1;\n\n let mut _expectation: String;\n\n let regex_str: &str = r#\"e\"#;\n\n let to_sub: &str = r#\"x\"#;\n\n let expectation: String = \"testfile linx number\".to_string();\n\n\n\n // Apply actual test(s)\n\n buffer.substitute( regex_str, to_sub, WhichMatch::Number(3),\n", "file_path": "src/buf.rs", "rank": 92, "score": 2.5801173165123954 }, { "content": " }\n\n close_file_buffer_test( &mut buffer );\n\n }// }}}\n\n #[test]\n\n fn substitute_test_3() {// {{{\n\n let test_num: u8 = 3;\n\n let mut buffer = open_file_buffer_test( test_num );\n\n let num_lines = buffer.num_lines() - 1;\n\n let mut _expectation: String;\n\n let regex_str: &str = r#\"e\"#;\n\n let to_sub: &str = r#\"x\"#;\n\n let expectation: String = \"txstfile line number\".to_string();\n\n\n\n // Apply actual test(s)\n\n buffer.substitute( regex_str, to_sub, WhichMatch::Number(1),\n\n 1, num_lines );\n\n let mut count = 0_usize;\n\n for line in buffer.lines_iterator() {\n\n count += 1;\n\n if count > num_lines {\n", "file_path": "src/buf.rs", "rank": 93, "score": 2.5801173165123954 }, { "content": " /// Insert new line at current position// {{{\n\n ///\n\n /// TODO: Add error handling, Result<> return?\n\n /// I don't think that will be necessary\n\n pub fn append_here( &mut self, new_line: &str ) {// {{{\n\n let address = self.current_line;\n\n self.append_line( address, new_line );\n\n }// }}}\n\n// }}}\n\n /// Insert new line// {{{\n\n ///\n\n /// TODO: Add error handling, Result<> return?\n\n /// I don't think that will be necessary\n\n pub fn append_line( &mut self, address: usize, new_line: &str ) {// {{{\n\n let mut back = self.lines.split_off( address );\n\n self.lines.push_back( new_line.to_string() );\n\n self.lines.append( &mut back );\n\n self.current_line = address + 1; // next line\n\n self.insert_update_markers( address );\n\n self._is_modified = true;\n", "file_path": "src/buf.rs", "rank": 94, "score": 2.538390541965744 }, { "content": " }\n\n },\n\n None => {\n\n print_help( state, \"failed to parse mark character\" );\n\n return Err( RedError::ParameterSyntax{\n\n parameter: command.parameters.to_string() });\n\n },\n\n };\n\n // if given a section of lines, mark the beginning\n\n state.buffer.set_marker( mark_char, _final );\n\n Ok( () )\n\n\n\n}//}}}\n", "file_path": "src/ops.rs", "rank": 95, "score": 2.4799599219673816 }, { "content": " pub address_initial: usize,\n\n pub address_final: usize,\n\n pub operation: char,\n\n pub parameters: &'a str,\n\n pub operations: &'b Operations, // tagging along for the ride\n\n}// }}}\n\npub struct Substitution {// {{{\n\n pub to_match: String,\n\n pub to_sub: String,\n\n pub which: WhichMatch,\n\n}// }}}\n\npub enum WhichMatch {\n\n Number( usize ),\n\n Global,\n\n}\n\n// ^^^ Data Structures ^^^ }}}\n\n\n\n// *** Functions *** {{{\n\n/// Parses invocation {{{\n", "file_path": "src/parse.rs", "rank": 98, "score": 2.2557693670832157 }, { "content": "/// Display range of lines of state.buffer in terminal // {{{\n\n///\n\n/// Caller will choose the start and finish addresses to fit\n\n/// the range of the state.buffer; For example, if the user tries\n\n/// to print beyond the end of the state.buffer, address_final will\n\n/// be the address of the last line of the state.buffer (in other\n\n/// words, the lines number of the last line)\n\n///\n\n/// # Panics\n\n/// if println! panics, which happens if it fails to write\n\n/// to io::stdout()\n\n///\n\nfn print( state: &mut EditorState, command: Command )//{{{\n\n -> Result<(), RedError> {\n\n assert_eq!( 'p', command.operation );\n\n let ( _initial, _final ) = default_addrs( state, &command );\n\n for indx in _initial .. ( _final + 1 ) {\n\n println!(\"{}\", state.buffer.get_line_content( indx ).expect(\n\n \"ops::print: called get_line_content on out-of-range line\" ) );\n\n }\n\n state.buffer.set_current_address( _final );\n\n // TODO: Drop this? Or Keep to avoid unused warnings?\n\n state.mode = EditorMode::Command;\n\n Ok( () )\n\n}// }}}\n", "file_path": "src/ops.rs", "rank": 99, "score": 2.1181711909279977 } ]
Rust
oracle/src/connection.rs
foundation-rs/backend
cc16dff0879314dd05494581aa580c23c74d282f
#[allow(dead_code)] #[allow(non_snake_case)] #[allow(non_camel_case_types)] use crate::oci; use crate::environment::Environment; use crate::{statement, OracleResult, SQLParams, ParamsProvider, SQLResults}; /* pub struct Connection { env: &'static Environment, srvhp: *mut oci::OCIServer, authp: *mut oci::OCISession, pub(crate) errhp: *mut oci::OCIError, pub(crate) svchp: *mut oci::OCISvcCtx, } */ pub struct SessionPool { env: &'static Environment, pub(crate) errhp: *const oci::OCIError, poolhp: *const oci::OCISPool, poolname: String, } unsafe impl Sync for SessionPool {} unsafe impl Send for SessionPool {} pub struct Connection { env: &'static Environment, pub(crate) errhp: *mut oci::OCIError, pub(crate) svchp: *mut oci::OCISvcCtx, } pub fn create_pool(db: &str, username: &str, passwd: &str) -> OracleResult<SessionPool> { let env = Environment::get()?; let errhp = env.errhp; let (poolhp, poolname) = oci::create_session_pool(env.envhp, errhp, 1,2, db, username, passwd)?; Ok(SessionPool{env, errhp, poolhp, poolname }) } impl SessionPool { pub fn connect(&self) -> OracleResult<Connection> { let svchp = oci::session_get(self.env.envhp, self.errhp as *mut oci::OCIError, &self.poolname)?; Ok( Connection::new(self.env, self.errhp as *mut oci::OCIError, svchp) ) } } impl Drop for SessionPool { fn drop(&mut self) { oci::destroy_session_pool(self.poolhp as *mut oci::OCISPool, self.errhp as *mut oci::OCIError).unwrap(); } } impl Drop for Connection { fn drop(&mut self) { oci::session_release(self.svchp, self.errhp); } } /* pub fn connect(db: &str, username: &str, passwd: &str) -> OracleResult<Connection> { let env = Environment::get()?; let srvhp = oci::handle_alloc(env.envhp, oci::OCI_HTYPE_SERVER)? as *mut oci::OCIServer; let svchp = oci::handle_alloc(env.envhp, oci::OCI_HTYPE_SVCCTX)? as *mut oci::OCISvcCtx; let errhp = env.errhp; let res = oci::server_attach(srvhp, errhp, db); if let Err(err) = res { free_server_handlers(srvhp, svchp); return Err(err); }; // set attribute server context in the service context oci::attr_set(svchp as *mut oci::c_void, oci::OCI_HTYPE_SVCCTX, srvhp as *mut oci::c_void, 0, oci::OCI_ATTR_SERVER, errhp)?; let authp = oci::prepare_auth(env.envhp, errhp, username, passwd)?; let res = oci::session_begin(svchp, errhp, authp); if let Err(err) = res { free_session_handler(authp); free_server_handlers(srvhp, svchp); return Err(err); }; // set session context in the service context oci::attr_set(svchp as *mut oci::c_void, oci::OCI_HTYPE_SVCCTX, authp as *mut oci::c_void, 0, oci::OCI_ATTR_SESSION, errhp)?; return Ok( Connection::new(env, srvhp, authp, errhp, svchp ) ); } */ impl Connection { fn new(env: &'static Environment, errhp: *mut oci::OCIError, svchp: *mut oci::OCISvcCtx) -> Connection { Connection { env, errhp, svchp } } pub fn commit(&self) -> OracleResult<()> { oci::commit(self.svchp, self.env.errhp) } pub fn rollback(&self) -> OracleResult<()> { oci::rollback(self.svchp, self.env.errhp) } pub fn execute<'conn,'s>(&'conn self, sql: &'s str) -> OracleResult<()> { let st = statement::Statement::new(self, sql, Box::new(()))?; st.execute(()) } pub fn prepare<P>(&self, sql: &str) -> OracleResult<statement::Statement<P>> where P: SQLParams { let provider = P::provider(); statement::Statement::new(self, sql, provider) } pub fn prepare_dynamic<P>(&self, sql: &str, provider: Box<dyn ParamsProvider<P>>) -> OracleResult<statement::Statement<P>> { statement::Statement::new(self, sql, provider) } pub fn query<'conn, P, R: 'conn>(&'conn self, sql: &str) -> OracleResult<statement::Query<'conn, P,R>> where P: SQLParams, R: SQLResults { let provider = P::provider(); statement::Statement::new(self, sql, provider)?.query() } pub fn query_one<'conn, P,R: 'conn>(&'conn self, sql: &str) -> OracleResult<statement::Query<'conn, P,R>> where P: SQLParams, R: SQLResults { let provider = P::provider(); statement::Statement::new(self, sql, provider)?.query_one() } } /* impl Drop for Connection { fn drop(&mut self) { oci::session_end(self.svchp, self.env.errhp, self.authp); oci::server_detach(self.srvhp, self.env.errhp); free_session_handler(self.authp); free_server_handlers(self.srvhp, self.svchp); } } */ fn free_session_handler(authp: *mut oci::OCISession) { if !authp.is_null() { oci::handle_free(authp as *mut oci::c_void, oci::OCI_HTYPE_SESSION); } } fn free_server_handlers(srvhp: *mut oci::OCIServer, svchp: *mut oci::OCISvcCtx) { if !svchp.is_null() { oci::handle_free(svchp as *mut oci::c_void, oci::OCI_HTYPE_SVCCTX); } if !srvhp.is_null() { oci::handle_free(srvhp as *mut oci::c_void, oci::OCI_HTYPE_SERVER); } }
#[allow(dead_code)] #[allow(non_snake_case)] #[allow(non_camel_case_types)] use crate::oci; use crate::environment::Environment; use crate::{statement, OracleResult, SQLParams, ParamsProvider, SQLResults}; /* pub struct Connection { env: &'static Environment, srvhp: *mut oci::OCIServer, authp: *mut oci::OCISession, pub(crate) errhp: *mut oci::OCIError, pub(crate) svchp: *mut oci::OCISvcCtx, } */ pub struct SessionPool { env: &'static Environment, pub(crate) errhp: *const oci::OCIError, poolhp: *const oci::OCISPool, poolname: String, } unsafe impl Sync for SessionPool {} unsafe impl Send for SessionPool {} pub struct Connection { env: &'static Environment, pub(crate) errhp: *mut oci::OCIError, pub(crate) svchp: *mut oci::OCISvcCtx, } pub fn create_pool(db: &str, username: &str, passwd: &str) -> OracleResult<SessionPool> { let env = Environment::get()?; let errhp = env.errhp; let (poolhp, poolname) = oci::create_session_pool(env.envhp, errhp, 1,2, db, username, passwd)?; Ok(SessionPool{env, errhp, poolhp, poolname }) } impl SessionPool { pub fn connect(&self) -> OracleResult<Connection> { let svchp = oci::session_get(self.env.envhp, self.errhp as *mut oci::OCIError, &self.poolname)?; Ok( Connection::new(self.env, self.errhp as *mut oci::OCIError, svchp) ) } } impl Drop for SessionPool { fn drop(&mut self) { oci::destroy_session_pool(self.poolhp as *mut oci::OCISPool, self.errhp as *mut oci::OCIError).unwrap(); } } impl Drop for Connection { fn drop(&mut self) { oci::session_release(self.svchp, self.errhp); } } /* pub fn connect(db: &str, username: &str, passwd: &str) -> OracleResult<Connection> { let env = Environment::get()?; let srvhp
one() } } /* impl Drop for Connection { fn drop(&mut self) { oci::session_end(self.svchp, self.env.errhp, self.authp); oci::server_detach(self.srvhp, self.env.errhp); free_session_handler(self.authp); free_server_handlers(self.srvhp, self.svchp); } } */ fn free_session_handler(authp: *mut oci::OCISession) { if !authp.is_null() { oci::handle_free(authp as *mut oci::c_void, oci::OCI_HTYPE_SESSION); } } fn free_server_handlers(srvhp: *mut oci::OCIServer, svchp: *mut oci::OCISvcCtx) { if !svchp.is_null() { oci::handle_free(svchp as *mut oci::c_void, oci::OCI_HTYPE_SVCCTX); } if !srvhp.is_null() { oci::handle_free(srvhp as *mut oci::c_void, oci::OCI_HTYPE_SERVER); } }
= oci::handle_alloc(env.envhp, oci::OCI_HTYPE_SERVER)? as *mut oci::OCIServer; let svchp = oci::handle_alloc(env.envhp, oci::OCI_HTYPE_SVCCTX)? as *mut oci::OCISvcCtx; let errhp = env.errhp; let res = oci::server_attach(srvhp, errhp, db); if let Err(err) = res { free_server_handlers(srvhp, svchp); return Err(err); }; // set attribute server context in the service context oci::attr_set(svchp as *mut oci::c_void, oci::OCI_HTYPE_SVCCTX, srvhp as *mut oci::c_void, 0, oci::OCI_ATTR_SERVER, errhp)?; let authp = oci::prepare_auth(env.envhp, errhp, username, passwd)?; let res = oci::session_begin(svchp, errhp, authp); if let Err(err) = res { free_session_handler(authp); free_server_handlers(srvhp, svchp); return Err(err); }; // set session context in the service context oci::attr_set(svchp as *mut oci::c_void, oci::OCI_HTYPE_SVCCTX, authp as *mut oci::c_void, 0, oci::OCI_ATTR_SESSION, errhp)?; return Ok( Connection::new(env, srvhp, authp, errhp, svchp ) ); } */ impl Connection { fn new(env: &'static Environment, errhp: *mut oci::OCIError, svchp: *mut oci::OCISvcCtx) -> Connection { Connection { env, errhp, svchp } } pub fn commit(&self) -> OracleResult<()> { oci::commit(self.svchp, self.env.errhp) } pub fn rollback(&self) -> OracleResult<()> { oci::rollback(self.svchp, self.env.errhp) } pub fn execute<'conn,'s>(&'conn self, sql: &'s str) -> OracleResult<()> { let st = statement::Statement::new(self, sql, Box::new(()))?; st.execute(()) } pub fn prepare<P>(&self, sql: &str) -> OracleResult<statement::Statement<P>> where P: SQLParams { let provider = P::provider(); statement::Statement::new(self, sql, provider) } pub fn prepare_dynamic<P>(&self, sql: &str, provider: Box<dyn ParamsProvider<P>>) -> OracleResult<statement::Statement<P>> { statement::Statement::new(self, sql, provider) } pub fn query<'conn, P, R: 'conn>(&'conn self, sql: &str) -> OracleResult<statement::Query<'conn, P,R>> where P: SQLParams, R: SQLResults { let provider = P::provider(); statement::Statement::new(self, sql, provider)?.query() } pub fn query_one<'conn, P,R: 'conn>(&'conn self, sql: &str) -> OracleResult<statement::Query<'conn, P,R>> where P: SQLParams, R: SQLResults { let provider = P::provider(); statement::Statement::new(self, sql, provider)?.query_
random
[]
Rust
src/systems/cursor_system.rs
csherratt/everpuzzle
6ac83fa7652d1e2d51f23a6f78ef16e27f11a94d
use amethyst::{ ecs::*, core::Transform, renderer::*, input::* }; use components::{ block::Block, cursor::Cursor, kind_generator::KindGenerator, playfield::stack::Stack, }; use block_states::swap::SWAP_TIME; use block_states::block_state::change_state; use data::block_data::*; use std::collections::HashMap; pub struct CursorSystem { key_presses: HashMap<String, i32> } impl CursorSystem { pub fn new() -> CursorSystem { let mut key_presses: HashMap<String, i32> = HashMap::new(); key_presses.insert(String::from("up"), 0); key_presses.insert(String::from("down"), 0); key_presses.insert(String::from("right"), 0); key_presses.insert(String::from("left"), 0); key_presses.insert(String::from("swap"), 0); key_presses.insert(String::from("space"), 0); key_presses.insert(String::from("raise"), 0); CursorSystem { key_presses } } pub fn hold(&mut self, input: &mut Read<InputHandler<String, String>>, name: &str) -> bool { if input.action_is_down(name).unwrap() { let result = *self.key_presses.get(name).unwrap(); if result == 0 || result > 16 { *self.key_presses.get_mut(name).unwrap() += 1; return true; } *self.key_presses.get_mut(name).unwrap() += 1; } else { *self.key_presses.get_mut(name).unwrap() = 0; } return false; } pub fn press(&mut self, input: &mut Read<InputHandler<String, String>>, name: &str) -> bool { if input.action_is_down(name).unwrap() { if *self.key_presses.get(name).unwrap() == 0 { *self.key_presses.get_mut(name).unwrap() = 1; return true; } } else { *self.key_presses.get_mut(name).unwrap() = 0; } return false; } } impl<'a> System<'a> for CursorSystem { type SystemData = ( WriteStorage<'a, SpriteRender>, WriteStorage<'a, Transform>, WriteStorage<'a, Cursor>, Read<'a, InputHandler<String, String>>, Write<'a, KindGenerator>, WriteStorage<'a, Block>, ReadStorage<'a, Stack>, ); fn run(&mut self, ( mut sprites, mut transforms, mut cursors, mut input, mut kind_gen, mut blocks, stacks, ): Self::SystemData) { if self.hold(&mut input, "up") { for cursor in (&mut cursors).join() { if cursor.y < (ROWS - 1) as f32 { cursor.y += 1.0; } } } if self.hold(&mut input, "down") { for cursor in (&mut cursors).join() { if cursor.y > 1.0 { cursor.y -= 1.0; } } } if self.hold(&mut input, "left") { for cursor in (&mut cursors).join() { if cursor.x > 0.0 { cursor.x -= 1.0; } } } if self.hold(&mut input, "right") { for cursor in (&mut cursors).join() { if cursor.x < (COLS - 2) as f32 { cursor.x += 1.0; } } } if self.press(&mut input, "space") { let kinds = kind_gen.create_stack(5, 8); for stack in (&stacks).join() { for i in 0..BLOCKS { blocks.get_mut(stack.from_i(i)).unwrap().kind = kinds[i]; } } } if self.press(&mut input, "swap") { for cursor in (cursors).join() { for stack in (&stacks).join() { swap(cursor.x, cursor.y, &stack, &mut blocks); } } } if self.press(&mut input, "raise") { for cursor in cursors.join() { for stack in (&stacks).join() { } } } for (sprite, transform, cursor) in (&mut sprites, &mut transforms, &mut cursors).join() { cursor.set_position(transform); sprite.sprite_number = cursor.anim_offset as usize; if cursor.anim_offset < 7.0 { cursor.anim_offset += 1.0 / 4.0; } else { cursor.anim_offset = 0.0; } } } } fn swap( x: f32, y: f32, stack: &Stack, blocks: &mut WriteStorage<'_, Block>) { let i = Stack::xy2i(x as usize, y as usize); let mut can_swap: bool = false; { let b1 = blocks.get(stack.from_i(i)).unwrap(); let b2 = blocks.get(stack.from_i(i + 1)).unwrap(); let mut b1_above_block: Option<&Block> = None; let mut b2_above_block: Option<&Block> = None; if i < BLOCKS - COLS { b1_above_block = blocks.get(stack.from_i(i + COLS)); b2_above_block = blocks.get(stack.from_i(i + 1 + COLS)); } if b1.is_swappable(b2, b1_above_block) && b2.is_swappable(b1, b2_above_block) { if b1.is_empty() && b2.is_empty() { return; } can_swap = true; } } if can_swap { set_swap_variables(blocks.get_mut(stack.from_i(i)).unwrap(), 1.0); set_swap_variables(blocks.get_mut(stack.from_i(i + 1)).unwrap(), -1.0); let mut left_block = Block::default(); let mut right_block = Block::default(); left_block = blocks.get(stack.from_i(i)) .unwrap() .clone(); right_block = blocks.get(stack.from_i(i + 1)) .unwrap() .clone(); { blocks.get_mut(stack.from_i(i + 1)) .unwrap() .set_properties(left_block); } { blocks.get_mut(stack.from_i(i)) .unwrap() .set_properties(right_block); } } } fn set_swap_variables (b: &mut Block, dir: f32) { b.offset.0 = 16.0 * dir; b.counter = SWAP_TIME as u32; b.move_dir = dir; change_state(b, "SWAP"); }
use amethyst::{ ecs::*, core::Transform, renderer::*, input::* }; use components::{ block::Block, cursor::Cursor, kind_generator::KindGenerator, playfield::stack::Stack, }; use block_states::swap::SWAP_TIME; use block_states::block_state::change_state; use data::block_data::*; use std::collections::HashMap; pub struct CursorSystem { key_presses: HashMap<String, i32> } impl CursorSystem { pub fn new() -> CursorSystem { let mut key_presses: HashMap<String, i32> = HashMap::new(); key_presses.insert(String::from("up"), 0); key_presses.insert(String::from("down"), 0); key_presses.insert(String::from("right"), 0); key_presses.insert(String::from("left"), 0); key_presses.insert(String::from("swap"), 0); key_presses.insert(String::from("space"), 0); key_presses.insert(String::from("raise"), 0); CursorSystem { key_presses } } pub fn hold(&mut self, input: &mut Read<InputHandler<String, String>>, name: &str) -> bool { if input.action_is_down(name).unwrap() { let result = *self.key_presses.get(name).unwrap(); if result == 0 || result > 16 { *self.key_presses.get_mut(name).unwrap() += 1; return true; } *self.key_presses.get_mut(name).unwrap() += 1; } else { *self.key_presses.get_mut(name).unwrap() = 0; } return false; } pub fn press(&mut self, input: &mut Read<InputHandler<String, String>>, name: &str) -> bool { if input.action_is_down(name).unwrap() { if *self.key_presses.get(name).unwrap() == 0 { *self.key_presses.get_mut(name).unwrap() = 1; return true; } } else { *self.key_presses.get_mut(name).unwrap() = 0; } return false; } } impl<'a> System<'a> for CursorSystem { type SystemData = ( WriteStorage<'a, SpriteRender>, WriteStorage<'a, Transform>, WriteStorage<'a, Cursor>, Read<'a, InputHandler<String, String>>, Write<'a, KindGenerator>, WriteStorage<'a, Block>, ReadStorage<'a, Stack>, ); fn run(&mut self, ( mut sprites, mut transforms, mut cursors, mut input, mut kind_gen, mut blocks, stacks, ): Self::SystemData) { if self.hold(&mut input, "up") { for cursor in (&mut cursors).join() { if cursor.y < (ROWS - 1) as f32 { cursor.y += 1.0; } } } if self.hold(&mut input, "down") { for cursor in (&mut cursors).join() { if cursor.y > 1.0 { cursor.y -= 1.0; } } } if self.hold(&mut input, "left") { for cursor in (&mut cursors).join() { if cursor.x > 0.0 { cursor.x -= 1.0; } } } if self.hold(&mut input, "right") { for cursor in (&mut cursors).join() { if cursor.x < (COLS - 2) as f32 { cursor.x += 1.0; } } } if self.press(&mut input, "space") { let kinds = kind_gen.create_stack(5, 8); for stack in (&stacks).join() { for i in 0..BLOCKS { blocks.get_mut(stack.from_i(i)).unwrap().kind = kinds[i]; } } } if self.press(&mut input, "swap") { for cursor in (cursors).join() { for stack in (&stacks).join() { swap(cursor.x, cursor.y, &stack, &mut blocks); } } } if self.press(&mut input, "raise") { for cursor in cursors.join() { for stack in (&stacks).join() { } } } for (sprite, transform, cursor) in (&mut sprites, &mut transforms, &mut cursors).join() { cursor.set_position(transform); sprite.sprite_number = cursor.anim_offset as usize; if cursor.anim_offset < 7.0 { cursor.anim_offset += 1.0 / 4.0; } else { cursor.anim_offset = 0.0; } } } } fn swap( x: f32, y: f32, stack: &Stack, blocks: &mut WriteStorage<'_, Block>) { let i = Stack::xy2i(x as usize, y as usize); let mut can_swap: bool = false; { let b1 = blocks.get(stack.from_i(i)).unwrap(); let b2 = blocks.get(stack.from_i(i + 1)).unwrap(); let mut b1_above_block: Option<&Block> = None; let mut b2_above_block: Option<&Block> = None; if i < BLOCKS - COLS { b1_above_block = blocks.get(stack.from_i(i + COLS)); b2_above_block = blocks.get(stack.from_i(i + 1 + COLS)); } if b1.is_swappable(b2, b1_above_block) && b2.is_swappable(b1, b2_above_block) { if b1.is_empty() && b2.is_empty() { return; } can_swap = true; } } if can_swap { set_swap_variables(blocks.get_mut(stack.from_i(i)).unwrap(), 1.0); set_swap_variables(blocks.get_mut(stack.from_i(i + 1)).unwrap(), -1.0); let mut left_block = Block::default(); let mut right_block = Block::default(); left_block = blocks.get(stack.from_i(i)) .unwrap() .clone(); right_block = blocks.get(stack.from_i(i + 1)) .unwrap() .clone(); { blocks.get_mut(stack.from_i(i + 1)) .unwrap() .set_properties(left_block); } { blocks.get_mut(stack.from_i(i)) .unwrap() .set_properties(right_block); } } }
fn set_swap_variables (b: &mut Block, dir: f32) { b.offset.0 = 16.0 * dir; b.counter = SWAP_TIME as u32; b.move_dir = dir; change_state(b, "SWAP"); }
function_block-full_function
[ { "content": "// checks wether the block below is empty or falling, also checks wether this block is empty\n\npub fn check_for_hang(i: usize, stack: &Stack, blocks: &mut WriteStorage<'_, Block>) -> bool {\n\n // condition based on another block in a different lifetime\n\n let mut down_condition: bool = false;\n\n\n\n // check if is in vec boundary\n\n if i > COLS {\n\n let down = blocks.get_mut(stack.from_i(i - COLS)).unwrap();\n\n down_condition = down.is_empty() || down.state == \"HANG\";\n\n }\n\n\n\n !blocks.get_mut(stack.from_i(i)).unwrap().is_empty() && down_condition\n\n}", "file_path": "src/systems/block_system.rs", "rank": 0, "score": 174062.30242112177 }, { "content": "pub fn load_sprite_sheet(world: &mut World, name: &str, filename: &str) -> SpriteSheetHandle {\n\n let loader = world.read_resource::<Loader>();\n\n\n\n // link texture with spritesheet\n\n // TODO: Texture id should be unique\n\n let texture_id = 1;\n\n world.write_resource::<MaterialTextureSet>()\n\n .insert(texture_id, {\n\n loader.load(\n\n name,\n\n PngFormat,\n\n TextureMetadata::srgb_scale(),\n\n (),\n\n &world.read_resource::<AssetStorage<Texture>>()\n\n ) \n\n });\n\n \n\n // spritesheet_handle return\n\n let sprite_sheethandle = {\n\n loader.load(\n", "file_path": "src/components/spritesheet_loader.rs", "rank": 1, "score": 162549.34327708278 }, { "content": "// changes the current blocks state to a new one\n\npub fn change_state(b: &mut Block, new_state: &'static str) {\n\n if b.state == new_state {\n\n return;\n\n }\n\n\n\n // call the currents state exit function\n\n match b.state {\n\n \"LAND\" => Land::exit(b),\n\n \"CLEAR\" => Clear::exit(b),\n\n _ => ()\n\n } \n\n \n\n b.state = new_state;\n\n\n\n // call the currents state enter function\n\n match b.state {\n\n \"HANG\" => Hang::enter(b),\n\n \"LAND\" => Land::enter(b),\n\n \"CLEAR\" => Clear::enter(b),\n\n _ => ()\n\n }\n\n}", "file_path": "src/block_states/block_state.rs", "rank": 2, "score": 153251.8738216344 }, { "content": "fn set_chainables(i: usize, stack: &Stack, blocks: &mut WriteStorage<'_, Block>) {\n\n\tlet x = blocks.get(stack.from_i(i)).unwrap().x as usize;\n\n\tlet y = blocks.get(stack.from_i(i)).unwrap().y as usize;\n\n\t\n\n\tfor i in y..ROWS {\n\n\t\tlet above = blocks.get_mut(stack.from_xy(x, i)).unwrap();\t\n\n\n\n\t\t// look for non invisible blocks\n\n\t\tif above.kind != -1 {\n\n\t\t\tif above.state == \"IDLE\" && !above.chainable {\n\n\t\t\t\tabove.chainable = true;\n\n\t\t\t}\t\n\n\t\t}\n\n\t\telse {\n\n\t\t\t// otherwhise just stop the for loop completly\n\n\t\t\treturn;\n\n\t\t}\n\n\t}\n\n}\n", "file_path": "src/block_states/clear.rs", "rank": 4, "score": 134174.0437715316 }, { "content": "// returns true if any \"real\" block is at the top of the grid\n\nfn check_blocks_at_top(stack: &Stack, blocks: &WriteStorage<'_, Block>) -> bool {\n\n\tfor x in 0..COLS {\n\n\t\tlet b = blocks.get(stack.from_xy(x, ROWS - 1)).unwrap();\n\n\n\n\t\tif b.kind != -1 && b.state == \"IDLE\" { // or garbage \n\n\t\t\treturn true;\n\n\t\t}\n\n\t}\n\n\n\n\treturn false;\n\n}\n\n\n", "file_path": "src/systems/playfield_system.rs", "rank": 5, "score": 121672.1181978988 }, { "content": "// returns true when any block was found that is currently in clear state\n\nfn check_blocks_clearing(stack: &Stack, blocks: &WriteStorage<'_, Block>) -> bool {\n\n\tfor i in 0..BLOCKS {\n\n\t\tlet b = blocks.get(stack.from_i(i)).unwrap();\n\n\n\n\t\tif b.state == \"CLEAR\" {// or garbage clear\n\n\t\t\treturn true;\n\n\t\t}\n\n\t}\n\n\n\n\treturn false;\n\n}\n\n\n", "file_path": "src/systems/playfield_system.rs", "rank": 6, "score": 121671.96142578393 }, { "content": "// checks through eachs block right, right_right and up, up_up to see if they are performing a combo\n\n// returns an array of block ids to identify them\n\nfn check_clear(x: usize, y: usize, stack: &Stack, blocks: &WriteStorage<'_, Block>) -> Vec<u32> {\n\n\tlet mut checks: Vec<u32> = Vec::new();\n\n\n\n\tlet r_rr = check_similar_block(x, y, 1, 0, stack, blocks);\n\n\tlet u_uu = check_similar_block(x, y, 0, 1, stack, blocks);\n\n\n\n\tif let Some(mut right_vec) = r_rr {\n\n\t\tchecks.append(&mut right_vec);\n\n\t}\n\n\n\n\tif let Some(mut up_vec) = u_uu {\n\n\t\tchecks.append(&mut up_vec);\n\n\t}\n\n\n\n\tchecks\n\n}\n\n\n", "file_path": "src/systems/playfield_system.rs", "rank": 7, "score": 113652.16990954836 }, { "content": "fn ease_out_quad(t: f32, b: f32, c: f32, d: f32) -> f32 {\n\n\tlet new = t / d;\t\n\n\t-c * new * (new - 2.0) + b\n\n}", "file_path": "src/block_states/swap.rs", "rank": 8, "score": 112818.62100888195 }, { "content": "fn main() -> amethyst::Result<()> {\n\n // log only warnings to create less logs\n\n let mut log = amethyst::LoggerConfig::default();\n\n log.level_filter = amethyst::LogLevelFilter::Warn;\n\n amethyst::start_logger(log);\n\n\n\n // necessary to get users path on each seperate device\n\n let app_root = application_root_dir();\n\n // path to display settings\n\n let path = format!(\n\n \"{}/src/configs/display_config.ron\",\n\n app_root\n\n );\n\n let display_config = DisplayConfig::load(&path);\n\n\n\n // start pipeline that clears to white background \n\n // and lets sprites exist with transparency\n\n let pipe = Pipeline::build().with_stage(\n\n Stage::with_backbuffer()\n\n .clear_target([1.0, 1.0, 1.0, 1.0], 1.0)\n", "file_path": "src/main.rs", "rank": 9, "score": 107163.71191180058 }, { "content": "// visibility is on when the blocks kind isnt -1\n\n// also sets the frame of the sprite by its kind * 9 and an additional \n\n// animation offset used to stay at specific horizontal sprites\n\nfn update_sprites(\n\n stack: &Stack, \n\n blocks: &mut WriteStorage<'_, Block>,\n\n sprites: &mut WriteStorage<'_, SpriteRender>,\n\n hiddens: &mut WriteStorage<'_, Hidden>) {\n\n for i in 0..BLOCKS {\n\n let b = blocks.get_mut(stack.from_i(i)).unwrap();\n\n\n\n // decrease all the time\n\n if b.anim_counter > 0 {\n\n b.anim_counter -= 1;\n\n }\n\n\n\n // render sprite with kind when its not -1\n\n if b.kind != -1 && !b.clearing {\n\n if hiddens.contains(stack.from_i(i)) {\n\n hiddens.remove(stack.from_i(i));\n\n }\n\n\n\n if b.y == 0 {\n", "file_path": "src/systems/block_system.rs", "rank": 11, "score": 72088.99912690536 }, { "content": "// A trait that all Block states should expand on\n\npub trait BlockState {\n\n // happens if loaded into another state\n\n fn enter(b: &mut Block);\n\n\n\n // happens when leaving to another state\n\n fn exit(b: &mut Block);\n\n\n\n // happens each frame,\n\n // takes an iterator - to know which block youre looking at right now\n\n // takes a stack of block entities that you can access\n\n // takes the whole stack of blocks - get ref or mut out of this\n\n fn execute(usize, &Stack, &mut WriteStorage<'_, Block>);\n\n\n\n // gets called once the blocks counter runs down to 0\n\n // mostly used to switch states\n\n fn counter_end(usize, &Stack, &mut WriteStorage<'_, Block>);\n\n}\n\n\n", "file_path": "src/block_states/block_state.rs", "rank": 12, "score": 65917.1462787966 }, { "content": " }\n\n}\n\n\n\nimpl Cursor {\n\n pub fn new(x: f32, y: f32) -> Cursor {\n\n Cursor { x, y, ..Default::default() }\n\n }\n\n\n\n pub fn set_position(&self, transform: &mut Transform) {\n\n transform.translation.x = self.x * 32.0 * transform.scale.x + self.offset.0;\n\n transform.translation.y = self.y * 32.0 * transform.scale.y + self.offset.1;\n\n }\n\n}\n\n\n\nimpl Component for Cursor {\n\n type Storage = DenseVecStorage<Self>;\n\n}\n", "file_path": "src/components/cursor.rs", "rank": 13, "score": 50065.9312144284 }, { "content": "use amethyst::{\n\n core::Transform,\n\n ecs::{Component, DenseVecStorage},\n\n};\n\n\n\npub struct Cursor {\n\n pub x: f32,\n\n pub y: f32, \n\n pub anim_offset: f32,\n\n pub offset: (f32, f32),\n\n}\n\n\n\nimpl Default for Cursor {\n\n fn default() -> Cursor {\n\n Cursor {\n\n x: 0.0, \n\n y: 0.0,\n\n anim_offset: 0.0,\n\n offset: (0.0, 0.0),\n\n }\n", "file_path": "src/components/cursor.rs", "rank": 14, "score": 50065.59753124167 }, { "content": "#![allow(dead_code, unused_imports)]\n\nuse amethyst::ecs::prelude::{Component, DenseVecStorage};\n\nuse std::marker::Copy;\n\nuse std::clone::Clone;\n\nuse block_states::land::LAND_TIME;\n\n\n\n#[derive(Debug, Copy, Clone)]\n\npub struct Block {\n\n pub kind: i32, // sprite_number or -1 meaning invisible\n\n pub id: u32, \n\n pub x: i32,\n\n pub y: i32,\n\n pub offset: (f32, f32),\n\n pub move_dir: f32,\n\n pub state: &'static str,\n\n pub counter: u32,\n\n\n\n // clear variables\n\n pub chainable: bool,\n\n pub clearing: bool,\n", "file_path": "src/components/block.rs", "rank": 15, "score": 48250.21053137394 }, { "content": "\n\n // wether this block is comboable with another kind being given in\n\n pub fn is_comboable_with(&self, other_kind: i32) -> bool {\n\n self.is_comboable() && other_kind != -1 && other_kind == self.kind\n\n }\n\n\n\n // set properties from another block\n\n // THIS SHOULD BE CHANGED WHENEVER DATA SHOULD PERSIST AFTER A FALL OR A SWAP!!!\n\n pub fn set_properties(&mut self, other: Block) {\n\n self.kind = other.kind;\n\n self.state = other.state;\n\n self.chainable = other.chainable;\n\n }\n\n\n\n // reset distinct values \n\n pub fn reset(&mut self) {\n\n self.kind = -1; \n\n self.state = \"IDLE\";\n\n self.chainable = false;\n\n }\n\n}\n\n\n\nimpl Component for Block {\n\n type Storage = DenseVecStorage<Self>;\n\n}", "file_path": "src/components/block.rs", "rank": 16, "score": 48244.38814991662 }, { "content": " }\n\n\n\n // a block is empty when its kind is -1 so it turns invisible and\n\n // its state is always idle \n\n pub fn is_empty(&self) -> bool {\n\n self.kind == -1 && self.state == \"IDLE\"\n\n }\n\n\n\n // a block is swappable when: \n\n // its state isnt idle or its invisible,\n\n // other block isnt empty and currently in fall,\n\n // its state is land and its counter still below land time \n\n // valid blocks are currently swapping \n\n pub fn is_swappable(&self, other: &Block, above_block: Option<&Block>) -> bool {\n\n if let Some(above) = above_block {\n\n if above.state == \"HANG\" {\n\n return true;\n\n }\n\n } \n\n\n", "file_path": "src/components/block.rs", "rank": 17, "score": 48238.09081384529 }, { "content": " counter: 0,\n\n \n\n // clear variables\n\n chainable: false,\n\n clearing: false,\n\n clear_counter: 0,\n\n clear_anim_counter: 0,\n\n clear_time: 0,\n\n clear_start_counter: 0,\n\n\n\n // anim counters\n\n anim_counter: 0,\n\n anim_offset: 0,\n\n }\n\n }\n\n}\n\n\n\nimpl Block {\n\n pub fn new(id: u32, kind: i32, x: i32, y: i32) -> Block {\n\n Block { id, kind, x, y, ..Default::default() }\n", "file_path": "src/components/block.rs", "rank": 18, "score": 48237.85179152114 }, { "content": " pub clear_counter: i32,\n\n pub clear_anim_counter: i32,\n\n pub clear_time: i32,\n\n pub clear_start_counter: i32,\n\n\n\n // anim counters\n\n pub anim_counter: u32,\n\n pub anim_offset: u32,\n\n}\n\n\n\nimpl Default for Block {\n\n fn default() -> Block {\n\n Block {\n\n kind: 0,\n\n id: 0,\n\n x: 0,\n\n y: 0,\n\n offset: (0.0, 0.0),\n\n move_dir: 1.0,\n\n state: \"IDLE\",\n", "file_path": "src/components/block.rs", "rank": 19, "score": 48236.99765934709 }, { "content": " // y isnt at the bottom of the blocks - darkened column,\n\n // kind isnt invisible and its state is idle\n\n // currently landing \n\n pub fn is_comboable(&self) -> bool {\n\n if self.y == 0 {\n\n return false;\n\n }\n\n\n\n // garbage\n\n\n\n if self.kind != -1 && self.state == \"IDLE\" {\n\n return true;\n\n }\n\n\n\n if self.state == \"LAND\" && self.counter < LAND_TIME {\n\n return true;\n\n }\n\n\n\n return false;\n\n }\n", "file_path": "src/components/block.rs", "rank": 20, "score": 48236.06075586532 }, { "content": " if !other.is_empty() && self.state == \"FALL\" {\n\n return true;\n\n }\n\n\n\n if self.state == \"LAND\" && self.counter < LAND_TIME {\n\n return true;\n\n }\n\n\n\n if self.state == \"IDLE\" || self.kind == -1 {\n\n return true;\n\n }\n\n\n\n if other.kind != -1 && other.state == \"MOVE\" && self.state == \"MOVE\" {\n\n return true;\n\n }\n\n\n\n return false;\n\n }\n\n \n\n // a block is comboable when its:\n", "file_path": "src/components/block.rs", "rank": 21, "score": 48232.89450796824 }, { "content": "#![allow(dead_code)]\n\nuse amethyst::ecs::prelude::{Entity, Component, DenseVecStorage};\n\nuse data::block_data::COLS;\n\n\n\npub struct Stack {\n\n\tblock_entities: Vec<Entity>,\n\n\tpub cursor_entity: Entity,\n\n}\n\n\n\nimpl Stack {\n\n\tpub fn new(block_entities: Vec<Entity>, cursor_entity: Entity) -> Stack {\n\n\t\tStack {\n\n\t\t\tblock_entities,\n\n\t\t\tcursor_entity,\n\n\t\t}\n\n\t}\n\n\n\n\t// simple way to get an entity back\n\n\tpub fn from_i(&self, i: usize) -> Entity {\n\n\t\tself.block_entities[i]\n", "file_path": "src/components/playfield/stack.rs", "rank": 22, "score": 47955.07200546861 }, { "content": " }\n\n}\n\n\n\n// returns a stack of blocks where no nzmbers are the same next to each other\n\n// also nulls kinds randomly and creates holes throughout the stack\n\n// also has zones in which all blocks will definitely be nulled\n\n// and a safe zone where no nulling happens\n\nimpl KindGenerator {\n\n pub fn create_stack(&mut self, safe: usize, nulling: usize) -> Vec<i32> {\n\n let safe_zone: usize = safe * COLS;\n\n let nulling_zone: usize = nulling * COLS;\n\n\n\n // empty array to destined length\n\n let size: usize = BLOCKS; //TODO: ROWS_VIS data\n\n let mut nums: Vec<i32> = Vec::new();\n\n nums.resize(size, -1);\n\n\n\n // scoped previous number that saves the newest generated number \n\n let mut prev_before = -1;\n\n\n", "file_path": "src/components/kind_generator.rs", "rank": 23, "score": 47951.61686911797 }, { "content": "\t\t(\n\n\t\t\ti % COLS,\n\n\t\t\t((i / COLS) as f64).floor() as usize\n\n\t\t\t// f32 floor changes to f64,\n\n\t\t\t// so why not go to f64 instantly\n\n\t\t)\t\n\n\t}\n\n}\n\n\n\nimpl Component for Stack {\n\n type Storage = DenseVecStorage<Self>;\n\n}\n", "file_path": "src/components/playfield/stack.rs", "rank": 24, "score": 47948.16171375863 }, { "content": " for i in 0..size {\n\n let mut new_num: i32 = 0;\n\n let mut bot_num: i32 = -1; // by default -1\n\n let mut skip: bool = false;\n\n\n\n // set bot_num once it respects the boundaries\n\n if i > COLS {\n\n bot_num = nums[i - COLS];\n\n\n\n // if bot_num is -1, just set new_num to -1 and skip\n\n if bot_num == -1 {\n\n skip = true;\n\n new_num = -1;\n\n }\n\n }\n\n\n\n if !skip {\n\n // when over start to go through\n\n if i != 0 {\n\n // if the right wall is hit (after i * 6) then be true\n", "file_path": "src/components/kind_generator.rs", "rank": 25, "score": 47947.66842330346 }, { "content": " // the generated vector will not have any numbers that match neighboring\n\n // numbers\n\n pub fn create_rows(&mut self, dimensions: (usize, usize)) -> Vec<i32> {\n\n // empty array to destined length\n\n let size: usize = dimensions.0 * dimensions.1; \n\n let mut nums: Vec<i32> = Vec::new();\n\n nums.resize(size, -1);\n\n\n\n // scoped previous number that saves the newest generated number \n\n let mut prev_before = -1;\n\n\n\n for i in 0..size {\n\n let mut new_num: i32 = 0;\n\n let mut bot_num: i32 = -1; // by default -1\n\n\n\n // set bot_num once it respects the boundaries\n\n if i > COLS {\n\n bot_num = nums[i - COLS];\n\n }\n\n\n", "file_path": "src/components/kind_generator.rs", "rank": 26, "score": 47946.64323236654 }, { "content": "\t}\n\n\n\n\t// shouldnt be used too often, rather use i2xy to get the iterator calculated once\n\n\tpub fn from_xy(&self, x: usize, y: usize) -> Entity {\n\n\t\tself.block_entities[Stack::xy2i(x, y)]\n\n\t}\n\n\n\n\t// convert an x and y coordinate to i\n\n\t// use this if you want to back convert from an x and y\n\n\t// this is most often used when only one parameter changes and the other one stays\n\n\t// example: for x in 0..10 {\n\n\t// \t\txy2i(x, 0) // searches through 0 until 10 from y at 0\t\n\n\t// }\n\n\tpub fn xy2i(x: usize, y: usize) -> usize {\n\n\t\ty * COLS + x\t\n\n\t}\n\n\n\n\t// use this instead of calling from_xy multiple times\n\n\t// converts an iterator i back to x and y\n\n\tpub fn i2xy(i: usize) -> (usize, usize) {\n", "file_path": "src/components/playfield/stack.rs", "rank": 27, "score": 47944.603931112106 }, { "content": "#![allow(unused_variables)]\n\nuse rand::prelude::*;\n\nuse data::block_data::{\n\n COLS, \n\n BLOCKS,\n\n};\n\n\n\n// resource that stores the rng generator that will be global\n\n// accessed via the world\n\n#[derive(Debug)]\n\npub struct KindGenerator {\n\n pub rng: SmallRng,\n\n}\n\n\n\nimpl Default for KindGenerator {\n\n // default so it can be fetched by systems\n\n fn default() -> KindGenerator {\n\n KindGenerator {\n\n rng: SmallRng::from_seed([0, 1, 2, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16])\n\n }\n", "file_path": "src/components/kind_generator.rs", "rank": 28, "score": 47944.06096823867 }, { "content": " // if the right wall is hit (after i * 6) then be true\n\n if i % COLS + 1 != 0 {\n\n new_num = self.get_number(prev_before, bot_num);\n\n }\n\n else {\n\n new_num = self.get_number(-1, bot_num);\n\n }\n\n\n\n prev_before = new_num; \n\n nums[i] = new_num;\n\n }\n\n \n\n nums\n\n }\n\n\n\n // returns a randomly chosen number out of an array\n\n // you can erase contents inside by specifying them in the parameters\n\n // otherwhise theyll remain available to the chosen randomly\n\n fn get_number_in_zone(\n\n &mut self,\n", "file_path": "src/components/kind_generator.rs", "rank": 29, "score": 47941.00699324869 }, { "content": " cond1: i32, \n\n cond2: i32, \n\n iterator: usize, \n\n safe_zone: usize, \n\n null_zone: usize\n\n ) -> i32 {\n\n let mut numbers: Vec<i32> = vec![-1, 0, 1, 2, 3, 4];\n\n \n\n if iterator >= null_zone {\n\n return -1; \n\n }\n\n\n\n if safe_zone >= iterator {\n\n numbers.retain(|x| x != &-1); // leave everything but -1\n\n }\n\n\n\n if cond1 != -1 {\n\n numbers.retain(|x| x != &cond1);\n\n }\n\n\n", "file_path": "src/components/kind_generator.rs", "rank": 30, "score": 47939.45198488713 }, { "content": " if i % COLS + 1 != 0 {\n\n new_num = self.get_number_in_zone(prev_before, bot_num, i, safe_zone, nulling_zone);\n\n }\n\n else {\n\n new_num = self.get_number_in_zone(-1, bot_num, i, safe_zone, nulling_zone);\n\n }\n\n }\n\n else {\n\n new_num = self.get_number_in_zone(-1, -1, i, safe_zone, nulling_zone);\n\n }\n\n }\n\n\n\n prev_before = new_num; \n\n nums[i] = new_num;\n\n }\n\n \n\n nums\n\n }\n\n\n\n // create rows defined by the size of the dimensions parameter,\n", "file_path": "src/components/kind_generator.rs", "rank": 31, "score": 47937.86703583904 }, { "content": " if cond2 != -1 {\n\n numbers.retain(|x| x != &cond2);\n\n }\n\n\n\n return numbers[self.rng.gen_range(0, numbers.len())];\n\n }\n\n\n\n // returns a randomly chosen number out of an array\n\n // you can erase contents inside by specifying them in the parameters\n\n // otherwhise theyll remain available to the chosen randomly\n\n fn get_number(\n\n &mut self,\n\n cond1: i32, \n\n cond2: i32, \n\n ) -> i32 {\n\n let mut numbers: Vec<i32> = vec![-1, 0, 1, 2, 3, 4];\n\n \n\n if cond1 != -1 {\n\n numbers.retain(|x| x != &cond1);\n\n }\n\n\n\n if cond2 != -1 {\n\n numbers.retain(|x| x != &cond2);\n\n }\n\n\n\n return numbers[self.rng.gen_range(0, numbers.len())];\n\n }\n\n}\n", "file_path": "src/components/kind_generator.rs", "rank": 32, "score": 47936.27298139179 }, { "content": "// checks for similar blocks from the current block to 2 others\n\n// checks if they all exist, are comboable, and also if their kinds match with the first\n\n// returns an array of u32 ids of the blocks that are comboable or nothing\n\n// to save on cpu -> not creating empty vecs\n\nfn check_similar_block(\n\n\tx: usize, y: usize,\n\n\tx_offset: usize, y_offset: usize,\n\n\tstack: &Stack, \n\n\tblocks: &WriteStorage<'_, Block>\n\n) -> Option<Vec<u32>> {\n\n\tlet b1 = blocks.get(stack.from_xy(x, y)).unwrap();\n\n\n\n\tlet check_boundary = |x: usize, y: usize| -> Option<&Block> {\n\n\t\tif x < COLS && y < ROWS {\n\n\t\t\tblocks.get(stack.from_xy(x, y))\n\n\t\t}\n\n\t\telse {\n\n\t\t\tNone\n\n\t\t}\n\n\t};\n\n\n\n\tlet b2 = check_boundary(x + x_offset, y + y_offset);\n\n\tlet b3 = check_boundary(x + x_offset * 2, y + y_offset * 2);\n\n\n", "file_path": "src/systems/playfield_system.rs", "rank": 33, "score": 47535.68655495213 }, { "content": "#![allow(unused_variables)]\n\nuse amethyst::ecs::prelude::WriteStorage;\n\nuse components::block::Block;\n\nuse components::playfield::stack::Stack;\n\nuse block_states::block_state::{BlockState, change_state};\n\nuse systems::block_system::check_for_hang;\n\n\n\npub const SWAP_TIME: f32 = 5.0;\n\n\n\n// animates movement of the block to a direction - either left or right\n\npub struct Swap;\n\nimpl BlockState for Swap {\n\n fn enter(b: &mut Block) {}\n\n fn exit(b: &mut Block) {}\n\n\n\n fn execute(i: usize, stack: &Stack, blocks: &mut WriteStorage<'_, Block>) {\n\n\t\tlet b = blocks.get_mut(stack.from_i(i)).unwrap();\n\n\n\n\t\tb.offset.0 = b.move_dir * 16.0 + -b.move_dir * ease_out_quad(\n\n\t\t\tSWAP_TIME - b.counter as f32,\n", "file_path": "src/block_states/swap.rs", "rank": 34, "score": 47364.054716111 }, { "content": "\t\t\t0.0, 16.0,\n\n\t\t\tSWAP_TIME\n\n\t\t);\n\n\t}\n\n\n\n fn counter_end(i: usize, stack: &Stack, blocks: &mut WriteStorage<'_, Block>) {\n\n\t\tlet can_fall = {\n\n\t\t\tcheck_for_hang(i, stack, blocks)\n\n\t\t};\n\n\n\n\t\tlet b = blocks.get_mut(stack.from_i(i)).unwrap();\n\n\t\tif can_fall {\n\n\t\t\tchange_state(b, \"HANG\");\n\n\t\t}\n\n\t\telse {\n\n\t\t\tb.state = \"IDLE\";\n\n\t\t\tb.offset.0 = 0.0;\n\n\t\t}\n\n }\n\n}\n\n\n", "file_path": "src/block_states/swap.rs", "rank": 35, "score": 47350.60598594057 }, { "content": "fn visual_offset(\n\n\tp_push: &mut PlayfieldPush,\n\n\tstack: &Stack,\t\n\n\tblocks: &mut WriteStorage<'_, Block>,\n\n\tcursor: &mut Cursor,\n\n) {\n\n\t// if any cursor signal comes through do smooth increase thats faster and stops\n\n\tif p_push.signal_raise {\n\n\t\tp_push.smooth_raise = true;\n\n\t}\n\n\n\n\t// stop any raise, even smooth call\n\n\tif p_push.any_clears || p_push.any_top_blocks {\n\n\t\tp_push.smooth_raise = false; // deletes all smooth_raise signals\n\n\t\treturn;\n\n\t}\n\n\n\n\t// if anything blocks raise by setting its time all raise stops until it counts down\n\n\t// used to block the amount of time it takes until another raise triggers\n\n\tif p_push.raised_blocked_counter > 0 {\n", "file_path": "src/systems/playfield_system.rs", "rank": 36, "score": 28912.864466419374 }, { "content": "fn any_chainable_exists(\n\n\tclear_ids: &Vec<u32>,\n\n\tstack: &Stack, \n\n\tblocks: &WriteStorage<'_, Block>,\n\n\t) -> bool {\n\n\tfor id in clear_ids {\n\n\t\tif blocks.get(stack.from_i(*id as usize)).unwrap().chainable {\n\n\t\t\treturn true;\n\n\t\t}\n\n\t}\n\n\n\n\treturn false;\n\n}", "file_path": "src/systems/playfield_system.rs", "rank": 37, "score": 28912.864466419374 }, { "content": "use amethyst::ecs::prelude::WriteStorage;\n\nuse components::block::Block;\n\nuse components::playfield::stack::Stack;\n\nuse block_states::{\n\n hang::Hang,\n\n land::Land,\n\n clear::Clear,\n\n};\n\n\n\n// A trait that all Block states should expand on\n", "file_path": "src/block_states/block_state.rs", "rank": 38, "score": 28386.209495361993 }, { "content": "fn set_visual_offsets(\n\n\tvalue: f32, \n\n\tstack: &Stack,\n\n\tblocks: &mut WriteStorage<'_, Block>,\n\n\tcursor: &mut Cursor,\n\n\t) {\n\n\tfor i in 0..BLOCKS {\n\n\t\tblocks.get_mut(stack.from_i(i)).unwrap().offset.1 = value;\n\n\t}\n\n\n\n\tcursor.offset.1 = value;\n\n}\n\n\n", "file_path": "src/systems/playfield_system.rs", "rank": 39, "score": 27953.78509359792 }, { "content": "pub mod block;\n\npub mod spritesheet_loader;\n\npub mod cursor;\n\npub mod kind_generator;\n\npub mod playfield;", "file_path": "src/components/mod.rs", "rank": 40, "score": 24521.96661218149 }, { "content": "use amethyst::prelude::*;\n\nuse amethyst::renderer::*;\n\nuse amethyst::assets::*;\n\n\n\npub struct SpriteSheetLoader {\n\n pub block_handle: SpriteSheetHandle\n\n}\n\n\n\nimpl SpriteSheetLoader {\n\n pub fn new(world: &mut World) -> SpriteSheetLoader {\n\n SpriteSheetLoader {\n\n block_handle: SpriteSheetLoader::load_blocks_sprite_sheet(world)\n\n }\n\n }\n\n\n\n pub fn load_blocks_sprite_sheet(world: &mut World) -> SpriteSheetHandle {\n\n let loader = world.read_resource::<Loader>();\n\n\n\n let texture_handle = {\n\n let texture_storage = world.read_resource::<AssetStorage<Texture>>();\n", "file_path": "src/components/spritesheet_loader.rs", "rank": 52, "score": 23300.27553804912 }, { "content": " // 0.0 and 1.0, so they must be divided by the width or height.\n\n //\n\n // In addition, on the Y axis, texture coordinates are 0.0 at the bottom of the sprite sheet and\n\n // 1.0 at the top, which is the opposite direction of pixel coordinates, so we have to invert\n\n // the value by subtracting the pixel proportion from 1.0.\n\n let mut all_sprites: Vec<Sprite> = Vec::new();\n\n for y in 0..9 {\n\n for x in 0..8 {\n\n all_sprites.push(Sprite {\n\n width: 16.0,\n\n height: 16.0,\n\n offsets: [-8.0, -8.0],\n\n tex_coords: TextureCoordinates {\n\n left: x as f32 * 16.0 / SPRITESHEET_SIZE.0,\n\n right: (x as f32 + 1.0) * 16.0 / SPRITESHEET_SIZE.0,\n\n bottom: 1.0 - (y as f32 + 1.0) * 16.0 / SPRITESHEET_SIZE.1,\n\n top: 1.0 - y as f32 * 16.0 / SPRITESHEET_SIZE.1,\n\n }\n\n })\n\n }\n", "file_path": "src/components/spritesheet_loader.rs", "rank": 53, "score": 23293.598047500498 }, { "content": " loader.load(\n\n \"blocks_orig.png\",\n\n PngFormat,\n\n TextureMetadata::srgb_scale(),\n\n (),\n\n &texture_storage,\n\n )\n\n };\n\n\n\n // `texture_id` is a application defined ID given to the texture to store in the `World`.\n\n // This is needed to link the texture to the sprite_sheet.\n\n let texture_id = 0;\n\n world.write_resource::<MaterialTextureSet>()\n\n .insert(texture_id, texture_handle);\n\n\n\n const SPRITESHEET_SIZE: (f32, f32) = (128.0, 144.0);\n\n\n\n // Create the sprite for the paddles.\n\n //\n\n // Texture coordinates are expressed as a proportion of the sprite sheet's dimensions between\n", "file_path": "src/components/spritesheet_loader.rs", "rank": 54, "score": 23287.451796029578 }, { "content": "pub mod playfield_clear;\n\npub mod playfield_push;\n\npub mod stack;\n", "file_path": "src/components/playfield/mod.rs", "rank": 55, "score": 23287.139395771545 }, { "content": " }\n\n\n\n // Collate the sprite layout information into a sprite sheet\n\n let sprite_sheet = SpriteSheet {\n\n texture_id,\n\n sprites: all_sprites,\n\n };\n\n\n\n let sprite_sheet_handle = {\n\n let loader = world.read_resource::<Loader>();\n\n let sprite_sheet_store = world.read_resource::<AssetStorage<SpriteSheet>>();\n\n loader.load_from_data(sprite_sheet, (), &sprite_sheet_store)\n\n };\n\n\n\n sprite_sheet_handle\n\n }\n\n}\n\n\n", "file_path": "src/components/spritesheet_loader.rs", "rank": 56, "score": 23285.02565477063 }, { "content": " filename,\n\n SpriteSheetFormat,\n\n texture_id,\n\n (),\n\n &world.read_resource::<AssetStorage<SpriteSheet>>(),\n\n )\n\n };\n\n\n\n sprite_sheethandle\n\n}\n", "file_path": "src/components/spritesheet_loader.rs", "rank": 57, "score": 23284.67363567656 }, { "content": "#![allow(unused_variables)]\n\nuse amethyst::ecs::prelude::WriteStorage;\n\nuse components::block::Block;\n\nuse components::playfield::stack::Stack;\n\nuse block_states::block_state::{BlockState, change_state};\n\nuse data::block_data::{BLOCKS, COLS, ROWS};\n\n\n\nconst FLASH_ANIM: [u32; 4] = [6, 6, 0, 0];\n\nconst FLASH_TIME: i32 = 44; \n\n\n\npub struct Clear;\n\nimpl BlockState for Clear {\n\n\t// for safety of animating set the counter back\n\n fn enter(b: &mut Block) {\n\n\t\tb.anim_counter = 0\n\n }\n\n\n\n fn exit(b: &mut Block) {\n\n\t\tb.kind = -1;\n\n\t\tb.counter = 0;\n", "file_path": "src/block_states/clear.rs", "rank": 58, "score": 22546.316512946472 }, { "content": "#![allow(unused_variables)]\n\nuse amethyst::ecs::prelude::WriteStorage;\n\nuse components::block::Block;\n\nuse components::playfield::stack::Stack;\n\nuse block_states::block_state::{BlockState, change_state};\n\n\n\npub struct Hang;\n\nimpl BlockState for Hang {\n\n fn enter(b: &mut Block) {\n\n b.counter = 10;\n\n }\n\n\n\n fn exit(b: &mut Block) {}\n\n fn execute(i: usize, stack: &Stack, blocks: &mut WriteStorage<'_, Block>) {}\n\n\n\n fn counter_end(i: usize, stack: &Stack, blocks: &mut WriteStorage<'_, Block>) {\n\n change_state(blocks.get_mut(stack.from_i(i)).unwrap(), \"FALL\");\n\n }\n\n}", "file_path": "src/block_states/hang.rs", "rank": 59, "score": 22545.145835860756 }, { "content": "#![allow(unused_variables)]\n\nuse amethyst::ecs::prelude::WriteStorage;\n\nuse components::block::Block;\n\nuse components::playfield::stack::Stack;\n\nuse block_states::block_state::{BlockState, change_state};\n\nuse data::block_data::COLS;\n\n\n\n// falls to one block below IN 1 FRAME\n\n// sets the block below to this current one\n\n// resets this blocks data to default\n\npub struct Fall;\n\nimpl BlockState for Fall {\n\n fn enter(b: &mut Block) {}\n\n fn exit(b: &mut Block) {}\n\n\n\n fn execute(i: usize, stack: &Stack, blocks: &mut WriteStorage<'_, Block>) {\n\n let mut is_empty: bool = false;\n\n let mut state_hang: bool = false;\n\n let mut down_counter: u32 = 0;\n\n\n", "file_path": "src/block_states/fall.rs", "rank": 60, "score": 22545.09433590653 }, { "content": "use amethyst::{\n\n ecs::*,\n\n renderer::*,\n\n core::Transform,\n\n};\n\n\n\nuse components::{\n\n block::Block,\n\n playfield::stack::Stack,\n\n};\n\nuse data::block_data::{COLS, BLOCKS};\n\nuse block_states::{\n\n block_state::BlockState,\n\n idle::Idle,\n\n hang::Hang,\n\n fall::Fall,\n\n land::Land,\n\n clear::Clear,\n\n swap::Swap,\n\n};\n", "file_path": "src/systems/block_system.rs", "rank": 61, "score": 22544.916065351837 }, { "content": "\n\n// handles everything a block should do itself or based on others\n\npub struct BlockSystem;\n\nimpl<'a> System<'a> for BlockSystem {\n\n type SystemData = (\n\n ReadStorage<'a, Stack>,\n\n WriteStorage<'a, SpriteRender>,\n\n WriteStorage<'a, Transform>,\n\n WriteStorage<'a, Block>,\n\n WriteStorage<'a, Hidden>,\n\n );\n\n\n\n fn run(&mut self, (\n\n stacks,\n\n mut sprites, \n\n mut transforms, \n\n mut blocks,\n\n mut hiddens,\n\n ): Self::SystemData)\n\n {\n", "file_path": "src/systems/block_system.rs", "rank": 62, "score": 22542.411663580435 }, { "content": "#![allow(unused_variables)]\n\nuse amethyst::ecs::prelude::WriteStorage;\n\nuse components::block::Block;\n\nuse components::playfield::stack::Stack;\n\nuse block_states::block_state::{BlockState, change_state};\n\nuse systems::block_system::check_for_hang;\n\n\n\n// only detects if this block can fall and sets the state to hang\n\n// resets chainable to false if this block cant fall\n\npub struct Idle;\n\nimpl BlockState for Idle {\n\n fn enter(b: &mut Block) {}\n\n fn exit(b: &mut Block) {}\n\n\n\n fn execute(i: usize, stack: &Stack, blocks: &mut WriteStorage<'_, Block>) {\n\n let can_hang: bool = {\n\n check_for_hang(i, stack, blocks)\n\n };\n\n\n\n // change the block to state if it isnt empty and the block below is empty / or falling\n", "file_path": "src/block_states/idle.rs", "rank": 63, "score": 22542.33925255742 }, { "content": "#![allow(unused_variables)]\n\nuse amethyst::ecs::prelude::WriteStorage;\n\nuse components::block::Block;\n\nuse components::playfield::stack::Stack;\n\nuse block_states::block_state::{BlockState, change_state};\n\nuse data::block_data::{COLS, BLOCKS};\n\n\n\nconst LAND_ANIM: [u32; 10] = [2, 2, 2, 3, 3, 3, 4, 4, 4, 0];\n\npub const LAND_TIME: u32 = 10;\n\n\n\n// STOPS THE BLOCK FROM BEING CHAINABLE after animating that is\n\n//\n\n// used for animating the land state \n\n// just sets sprite offset to the current animation frames\n\npub struct Land;\n\nimpl BlockState for Land {\n\n // set length of how long the fall will last\n\n fn enter(b: &mut Block) {\n\n b.counter = LAND_TIME;\n\n b.anim_counter = LAND_TIME;\n", "file_path": "src/block_states/land.rs", "rank": 64, "score": 22541.51434146328 }, { "content": " _ => ()\n\n }\n\n\n\n // if the counter is at 0, call current states counter end function\n\n if blocks.get(stack.from_i(i)).unwrap().counter <= 0 {\n\n match blocks.get(stack.from_i(i)).unwrap().state {\n\n \"HANG\" => Hang::counter_end(i, &stack, &mut blocks),\n\n \"FALL\" => Fall::counter_end(i, &stack, &mut blocks),\n\n \"LAND\" => Land::counter_end(i, &stack, &mut blocks),\n\n \"CLEAR\" => Clear::counter_end(i, &stack, &mut blocks),\n\n \"SWAP\" => Swap::counter_end(i, &stack, &mut blocks),\n\n _ => ()\n\n } \n\n }\n\n }\n\n\n\n // translation\n\n for (b, transform) in (&blocks, &mut transforms).join() {\n\n transform.translation.x = b.x as f32 * transform.scale.x * 16.0 + b.offset.0;\n\n transform.translation.y = b.y as f32 * transform.scale.y * 16.0 + b.offset.1;\n", "file_path": "src/systems/block_system.rs", "rank": 65, "score": 22540.66774468112 }, { "content": " }\n\n\n\n // rendering\n\n update_sprites(\n\n &stack, \n\n &mut blocks,\n\n &mut sprites,\n\n &mut hiddens,\n\n );\n\n }\n\n }\n\n}\n\n\n\n// visibility is on when the blocks kind isnt -1\n\n// also sets the frame of the sprite by its kind * 9 and an additional \n\n// animation offset used to stay at specific horizontal sprites\n", "file_path": "src/systems/block_system.rs", "rank": 66, "score": 22540.254362874726 }, { "content": " b.anim_offset = 1;\n\n }\n\n\n\n sprites.get_mut(stack.from_i(i)).unwrap().sprite_number = b.kind as usize * 8 + b.anim_offset as usize;\n\n }\n\n else {\n\n if !hiddens.contains(stack.from_i(i)) {\n\n hiddens.insert(stack.from_i(i), Hidden::default()).expect(\"add hide component\");\n\n }\n\n }\n\n }\n\n}\n\n\n", "file_path": "src/systems/block_system.rs", "rank": 67, "score": 22539.748660881283 }, { "content": " // if in boundary for down blocks to exist\n\n if i > COLS {\n\n let down = blocks.get_mut(stack.from_i(i - COLS)).unwrap();\n\n is_empty = down.is_empty();\n\n state_hang = down.state == \"HANG\";\n\n down_counter = down.counter;\n\n }\n\n else {\n\n let b = blocks.get_mut(stack.from_i(i)).unwrap();\n\n b.state = \"IDLE\";\n\n return;\n\n }\n\n\n\n if is_empty {\n\n let mut temp_block = Block::default();\n\n\n\n // store data from the current to a temp\n\n temp_block = blocks.get(stack.from_i(i))\n\n .unwrap()\n\n .clone();\n", "file_path": "src/block_states/fall.rs", "rank": 68, "score": 22537.508370357154 }, { "content": "\n\n // store data into the down block\n\n blocks.get_mut(stack.from_i(i - COLS))\n\n .unwrap()\n\n .set_properties(temp_block);\n\n\n\n // reset data in the current one to default\n\n blocks.get_mut(stack.from_i(i))\n\n .unwrap()\n\n .reset();\n\n }\n\n else if state_hang {\n\n let b = blocks.get_mut(stack.from_i(i)).unwrap();\n\n b.state = \"HANG\";\n\n b.counter = down_counter;\n\n }\n\n else {\n\n change_state(blocks.get_mut(stack.from_i(i)).unwrap(), \"LAND\");\n\n }\n\n }\n\n\n\n fn counter_end(i: usize, stack: &Stack, blocks: &mut WriteStorage<'_, Block>) {}\n\n}", "file_path": "src/block_states/fall.rs", "rank": 69, "score": 22537.45863666832 }, { "content": "\t\tb.anim_offset = 0;\n\n\n\n\t\t// clear variable resets\n\n\t\tb.clearing = false;\n\n\t\tb.clear_counter = 0;\n\n\t\tb.clear_anim_counter = 0;\n\n\t}\n\n\n\n\t// just the animation part of the whole clearing\n\n fn execute(i: usize, stack: &Stack, blocks: &mut WriteStorage<'_, Block>) {\n\n\t\tlet b = blocks.get_mut(stack.from_i(i)).unwrap();\n\n\n\n\t\t// clear at the end of the animation\n\n\t\tlet test = b.clear_time as i32 - b.clear_counter as i32;\n\n\t\tif test <= 0 && !b.clearing {\n\n\t\t\t// particles spawn\n\n\t\t\tb.clearing = true;\n\n\t\t}\n\n\t\telse {\n\n\t\t\tb.clear_counter += 1;\n", "file_path": "src/block_states/clear.rs", "rank": 70, "score": 22537.079781976518 }, { "content": " // run through all existing block stacks\n\n for stack in (&stacks).join() {\n\n // run through all states from a block\n\n for i in 0..BLOCKS {\n\n // decrease the counter if its over 0\n\n {\n\n let mut b = blocks.get_mut(stack.from_i(i)).unwrap();\n\n \n\n if b.counter > 0 {\n\n b.counter -= 1;\n\n }\n\n } \n\n\n\n // match all on the blocks state - run all execute functions\n\n match blocks.get(stack.from_i(i)).unwrap().state {\n\n \"IDLE\" => Idle::execute(i, &stack, &mut blocks),\n\n \"FALL\" => Fall::execute(i, &stack, &mut blocks),\n\n \"LAND\" => Land::execute(i, &stack, &mut blocks),\n\n \"CLEAR\" => Clear::execute(i, &stack, &mut blocks),\n\n \"SWAP\" => Swap::execute(i, &stack, &mut blocks),\n", "file_path": "src/systems/block_system.rs", "rank": 71, "score": 22536.23994949117 }, { "content": " }\n\n\n\n // set anim to 0 for safety, blocks arent chainable once the land is finished\n\n // being chainable finally stops here!\n\n fn exit(b: &mut Block) {\n\n b.anim_offset = 0;\n\n b.chainable = false;\n\n }\n\n\n\n // simply animate\n\n fn execute(i: usize, stack: &Stack, blocks: &mut WriteStorage<'_, Block>) {\n\n let b = blocks.get_mut(stack.from_i(i)).unwrap();\n\n b.anim_offset = LAND_ANIM[(LAND_TIME - b.anim_counter - 1) as usize];\n\n }\n\n\n\n // change to idle on default\n\n // if above isnt null and hanging, set the counter to the aboves counter\n\n fn counter_end(i: usize, stack: &Stack, blocks: &mut WriteStorage<'_, Block>) {\n\n let mut above_hanging: bool = false;\n\n let mut above_counter: u32 = 0;\n", "file_path": "src/block_states/land.rs", "rank": 72, "score": 22536.092763186527 }, { "content": " let b = blocks.get_mut(stack.from_i(i)).unwrap();\n\n if can_hang {\n\n change_state(b, \"HANG\");\n\n }\n\n else {\n\n b.chainable = false;\n\n }\n\n }\n\n\n\n fn counter_end(i: usize, stack: &Stack, blocks: &mut WriteStorage<'_, Block>) {}\n\n}", "file_path": "src/block_states/idle.rs", "rank": 73, "score": 22535.61395279439 }, { "content": "\n\n if i < BLOCKS - COLS {\n\n let above = blocks.get(stack.from_i(i + COLS)).unwrap();\n\n above_hanging = above.state == \"HANG\";\n\n above_counter = above.counter;\n\n }\n\n \n\n let b = blocks.get_mut(stack.from_i(i)).unwrap();\n\n if above_hanging {\n\n change_state(b, \"HANG\"); \n\n b.counter = above_counter;\n\n }\n\n else {\n\n change_state(b, \"IDLE\"); \n\n }\n\n }\n\n}", "file_path": "src/block_states/land.rs", "rank": 74, "score": 22535.5672357188 }, { "content": "\t\t\tb.clear_anim_counter += 1;\n\n\t\t\t\n\n\t\t\t// split animation in 2 parts\n\n\t\t\tif b.clear_anim_counter < FLASH_TIME {\n\n\t\t\t\t// flashy animation\n\n\t\t\t\tif b.anim_counter == 0 {\n\n\t\t\t\t\tb.anim_counter = 4;\n\n\t\t\t\t}\n\n\t\t\t\telse {\n\n\t\t\t\t\tb.anim_offset = FLASH_ANIM[b.anim_counter as usize];\n\n\t\t\t\t}\n\n\t\t\t}\n\n\t\t\telse {\n\n\t\t\t\t// just the face sprite\n\n\t\t\t\tb.anim_offset = 5;\n\n\t\t\t}\n\n\t\t}\n\n\t}\n\n\n\n\t// set this block to idle, also set chainable on all above that are real!\n\n fn counter_end(i: usize, stack: &Stack, blocks: &mut WriteStorage<'_, Block>) {\n\n\t\tset_chainables(i, &stack, blocks);\n\n change_state(blocks.get_mut(stack.from_i(i)).unwrap(), \"IDLE\");\n\n }\n\n}\n\n\n", "file_path": "src/block_states/clear.rs", "rank": 75, "score": 22535.066603000385 }, { "content": "pub mod block_state;\n\npub mod idle;\n\npub mod hang;\n\npub mod fall;\n\npub mod land;\n\npub mod clear;\n\npub mod swap;", "file_path": "src/block_states/mod.rs", "rank": 76, "score": 22530.415751069642 }, { "content": "use amethyst::ecs::{Component, DenseVecStorage};\n\n\n\npub struct PlayfieldPush {\n\n\tpub any_clears: bool,\n\n\tpub any_top_blocks: bool,\n\n\tpub smooth_raise: bool,\n\n\tpub offset_counter: f32,\n\n\tpub raised_blocked_counter: u32,\n\n\tpub signal_raise: bool,\n\n}\n\n\n\nimpl Default for PlayfieldPush {\n\n\tfn default() -> PlayfieldPush {\n\n\t\tPlayfieldPush {\n\n\t\t\tany_clears: false,\n\n\t\t\tany_top_blocks: false,\n\n\t\t\tsmooth_raise: false,\n\n\t\t\toffset_counter: 0.0,\n\n\t\t\traised_blocked_counter: 0,\n\n\t\t\tsignal_raise: false,\n\n\t\t}\n\n\t}\n\n}\n\n\n\nimpl Component for PlayfieldPush {\n\n type Storage = DenseVecStorage<Self>;\n\n}\n", "file_path": "src/components/playfield/playfield_push.rs", "rank": 77, "score": 22187.647966308996 }, { "content": "use amethyst::ecs::{Component, DenseVecStorage};\n\n\n\npub struct PlayfieldClear {\n\n\tpub clear_queue: Vec<u32>,\n\n\tpub combo_counter: u32, \n\n\tpub chain: u32,\n\n\tpub last_chain: u32,\n\n\tpub blocks_cleared: u32,\n\n}\n\n\n\nimpl Default for PlayfieldClear {\n\n\tfn default() -> PlayfieldClear {\n\n\t\tPlayfieldClear {\n\n\t\t\tclear_queue: Vec::new(),\n\n\t\t\tcombo_counter: 0,\n\n\t\t\tchain: 1,\n\n\t\t\tlast_chain: 1,\n\n\t\t\tblocks_cleared: 0,\n\n\t\t}\n\n\t}\n\n}\n\n\n\nimpl Component for PlayfieldClear {\n\n type Storage = DenseVecStorage<Self>;\n\n}\n", "file_path": "src/components/playfield/playfield_clear.rs", "rank": 78, "score": 22185.07750244031 }, { "content": "use amethyst::{\n\n prelude::*,\n\n renderer::*,\n\n core::{Transform, GlobalTransform, cgmath::Vector3},\n\n utils::fps_counter::FPSCounter,\n\n ecs::prelude::Entity,\n\n};\n\nuse rand::prelude::*;\n\n\n\nuse components::{\n\n block::Block,\n\n playfield::stack::Stack,\n\n cursor::Cursor,\n\n spritesheet_loader::{\n\n SpriteSheetLoader,\n\n load_sprite_sheet\n\n },\n\n kind_generator::KindGenerator,\n\n playfield::{\n\n playfield_clear::PlayfieldClear,\n", "file_path": "src/game_modes/game_mode.rs", "rank": 79, "score": 23.252231936150537 }, { "content": " pub fn create_blocks(world: &mut World, kinds: Vec<i32>) -> Vec<Entity> {\n\n world.register::<Block>();\n\n let mut block_entities: Vec<Entity> = Vec::new();\n\n\n\n for i in 0..BLOCKS {\n\n let mut trans = Transform::default();\n\n trans.scale = Vector3::new(4.0, 4.0, 4.0);\n\n\n\n // set position instantly so no weird spawn flash happens\n\n let (x, y) = Stack::i2xy(i);\n\n let mut b = Block::new(i as u32, kinds[i], x as i32, y as i32);\n\n\n\n let sprite_render_block = SpriteRender {\n\n sprite_sheet: SpriteSheetLoader::load_blocks_sprite_sheet(world),\n\n sprite_number: 0,\n\n flip_horizontal: false,\n\n flip_vertical: false,\n\n };\n\n\n\n block_entities.push(world.create_entity()\n", "file_path": "src/game_modes/game_mode.rs", "rank": 80, "score": 20.749934884414973 }, { "content": "use amethyst::ecs::*;\n\nuse components::{\n\n\tblock::Block,\n\n\tplayfield::stack::Stack,\n\n\tcursor::Cursor,\n\n\tplayfield::{\n\n\t\tplayfield_clear::PlayfieldClear,\n\n\t\tplayfield_push::PlayfieldPush,\n\n\t},\n\n};\n\nuse block_states::block_state::change_state;\n\nuse data::block_data::{BLOCKS, COLS, ROWS};\n\nuse std::cmp::max;\n\n\n\npub struct PlayfieldSystem;\n\n\n\nimpl<'a> System<'a> for PlayfieldSystem {\n\n type SystemData = (\n\n\t\tWriteStorage<'a, PlayfieldClear>,\n\n\t\tWriteStorage<'a, PlayfieldPush>,\n", "file_path": "src/systems/playfield_system.rs", "rank": 81, "score": 20.676239700216207 }, { "content": " world.add_resource::<KindGenerator>(kind_gen);\n\n\n\n // load the cursor sprite and attach its data component\n\n let sprite_sheet = SpriteRender {\n\n sprite_sheet: load_sprite_sheet(\n\n world,\n\n \"cursor.png\",\n\n \"cursor_spritesheet.ron\"\n\n ),\n\n sprite_number: 0,\n\n flip_horizontal: false,\n\n flip_vertical: false,\n\n };\n\n\n\n // cursor transform\n\n let mut trans = Transform::default();\n\n trans.scale = Vector3::new(2.0, 2.0, 2.0);\n\n\n\n let cursor = Cursor::new(2.0, 5.0);\n\n cursor.set_position(&mut trans);\n", "file_path": "src/game_modes/game_mode.rs", "rank": 82, "score": 18.81827713001964 }, { "content": " }\n\n };\n\n\n\n // load input settings\n\n let input_bundle = InputBundle::<String, String>::new().with_bindings_from_file(&binding_path)?;\n\n\n\n // build with all bundles and custom systems \n\n let game_data = GameDataBuilder::default()\n\n .with_bundle(TransformBundle::new())?\n\n .with_bundle(RenderBundle::new(pipe, Some(display_config))\n\n .with_sprite_sheet_processor()\n\n .with_sprite_visibility_sorting(&[\"transform_system\"])\n\n )?\n\n .with_bundle(input_bundle)?\n\n //.with(FPSSystem, \"fps_system\", &[])\n\n .with(BlockSystem{}, \"block_system\", &[])\n\n .with(CursorSystem::new(), \"cursor_system\", &[\"input_system\"])\n\n .with(PlayfieldSystem{}, \"playfield_system\", &[]);\n\n\n\n // set the assets dir where all sprites will be loaded from\n", "file_path": "src/main.rs", "rank": 83, "score": 17.471878482657253 }, { "content": " .with(sprite_render_block)\n\n .with(b)\n\n .with(GlobalTransform::default())\n\n .with(trans)\n\n .build());\n\n }\n\n\n\n block_entities\n\n }\n\n\n\n // create a camera that should have the same dimensions as the\n\n // display_config.ron. TODO: use the dimensions\n\n fn initialise_camera(&mut self, world: &mut World) {\n\n let mut transform = Transform::default();\n\n transform.translation.z = 1.0;\n\n\n\n world.create_entity()\n\n .with(Camera::from(Projection::orthographic(\n\n 0.0,\n\n self.config.dimensions.unwrap().0 as f32,\n", "file_path": "src/game_modes/game_mode.rs", "rank": 84, "score": 16.803564615498427 }, { "content": "pub mod block_data {\n\n pub const ROWS: usize = 12;\n\n pub const COLS: usize = 6;\n\n pub const BLOCKS: usize = ROWS * COLS;\n\n}", "file_path": "src/data.rs", "rank": 85, "score": 16.035045405432818 }, { "content": " self.config.dimensions.unwrap().1 as f32,\n\n 0.0\n\n )))\n\n .with(transform)\n\n .build();\n\n }\n\n}\n\n\n\nimpl<'a, 'b> SimpleState<'a, 'b> for GameMode {\n\n fn on_start(&mut self, data: StateData<GameData>) {\n\n let world = data.world;\n\n\n\n // create random generator for random seeded numbers\n\n let mut kind_gen: KindGenerator = KindGenerator { \n\n rng: SmallRng::from_seed(self.rng_seed) \n\n };\n\n let kinds = kind_gen.create_stack(5, 8);\n\n\n\n let block_entities = GameMode::create_blocks(world, kinds);\n\n // add the random number generator as a global resource to be used\n", "file_path": "src/game_modes/game_mode.rs", "rank": 86, "score": 15.626374503864195 }, { "content": "\t\t\t\tp_push.any_top_blocks = check_blocks_at_top(&stack, &blocks); \n\n\t\t\t}\n\n\n\n\t\t\t{\n\n\t\t\t\t// actually offset things based on time\n\n\t\t\t\tvisual_offset(\n\n\t\t\t\t\tplayfield_pushes.get_mut(entity).unwrap(), \n\n\t\t\t\t\t&stack, \n\n\t\t\t\t\t&mut blocks, \n\n\t\t\t\t\tcursors.get_mut(stack.cursor_entity).unwrap(),\n\n\t\t\t\t);\n\n\t\t\t}\n\n\t\t}\n\n\t\n\n\t\t// block clear detection\n\n\t\t// counts the amount of clears each frame, passes them uniquely to an array holding their ids\n\n\t\t// sets a lot of playfield_clear values and then sets the blocks to animate with given times\n\n\t\tfor (p_clear, p_push, stack) in (&mut playfield_clears, &mut playfield_pushes, &stacks).join() {\n\n\t\t\tfor x in 0..COLS {\n\n\t\t\t\tfor y in 0..ROWS {\n", "file_path": "src/systems/playfield_system.rs", "rank": 87, "score": 15.102725697898176 }, { "content": "extern crate amethyst;\n\nextern crate rand;\n\n\n\nuse amethyst::{\n\n prelude::*,\n\n renderer::*,\n\n core::{TransformBundle, frame_limiter::FrameRateLimitStrategy},\n\n input::InputBundle,\n\n utils::application_root_dir,\n\n};\n\nuse std::time::Duration;\n\n\n\nmod data;\n\nmod components;\n\nmod game_modes;\n\nmod systems;\n\nmod block_states;\n\nuse systems::{\n\n block_system::BlockSystem,\n\n cursor_system::CursorSystem,\n\n playfield_system::PlayfieldSystem,\n\n};\n\nuse game_modes::game_mode::GameMode;\n\n\n\n// static seed for rand crate that can be used to have the same rand seed - good for debugging\n\nconst SOME_SEED: [u8; 16] = [0, 1, 2, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16];\n\n\n", "file_path": "src/main.rs", "rank": 88, "score": 14.693583362012212 }, { "content": "\t\tWriteStorage<'a, Block>,\n\n\t\tReadStorage<'a, Stack>,\n\n\t\tWriteStorage<'a, Cursor>,\n\n\t\tEntities<'a>,\n\n );\n\n\n\n fn run(&mut self, (\n\n\t\tmut playfield_clears,\n\n\t\tmut playfield_pushes,\n\n\t\tmut blocks, \n\n\t\tstacks, \n\n\t\tmut cursors,\n\n\t\tentities,\n\n\t): Self::SystemData) {\n\n\t\t// playfield push info / push animation WIP\n\n\t\tfor (entity, stack) in (&entities, &stacks).join() {\n\n\t\t\t{\n\n\t\t\t\t// store info in p_push\n\n\t\t\t\tlet mut p_push = playfield_pushes.get_mut(entity).unwrap();\n\n\t\t\t\tp_push.any_clears = check_blocks_clearing(&stack, &blocks);\n", "file_path": "src/systems/playfield_system.rs", "rank": 89, "score": 13.697126324427513 }, { "content": " playfield_push::PlayfieldPush,\n\n },\n\n};\n\n\n\nuse data::block_data::BLOCKS;\n\n\n\npub struct GameMode {\n\n rng_seed: [u8; 16],\n\n config: DisplayConfig\n\n}\n\n\n\nimpl GameMode {\n\n pub fn new(rng_seed: [u8; 16], config: DisplayConfig) -> GameMode {\n\n GameMode {\n\n rng_seed,\n\n config\n\n }\n\n }\n\n\n\n // creates all entities with block components attached, spritesheet data with sprite_number\n", "file_path": "src/game_modes/game_mode.rs", "rank": 90, "score": 12.99469289708134 }, { "content": "\n\n // generate a cursor entity\n\n world.register::<Cursor>();\n\n let cursor_entity = world.create_entity()\n\n .with(sprite_sheet)\n\n .with(Transparent::default())\n\n .with(cursor)\n\n .with(GlobalTransform::default())\n\n .with(trans)\n\n .build();\n\n\n\n world.add_resource::<FPSCounter>(Default::default());\n\n\n\n // Create a Playfield with a stack, clear, push component,\n\n // STACK gives access to blocks and cursor dependant on the general storages\n\n world.register::<Stack>();\n\n world.register::<PlayfieldClear>();\n\n world.register::<PlayfieldPush>();\n\n world.create_entity()\n\n .with(PlayfieldClear::default())\n\n .with(PlayfieldPush::default())\n\n .with(Stack::new(block_entities, cursor_entity))\n\n .build();\n\n\n\n self.initialise_camera(world);\n\n }\n\n}\n\n\n", "file_path": "src/game_modes/game_mode.rs", "rank": 91, "score": 12.539091818093146 }, { "content": "use amethyst::{\n\n utils::fps_counter::FPSCounter,\n\n core::timing::{duration_to_nanos, Time},\n\n ecs::*,\n\n};\n\n\n\npub struct FPSSystem;\n\n\n\nimpl<'a> System<'a> for FPSSystem {\n\n type SystemData = (\n\n Read<'a, Time>,\n\n Write<'a, FPSCounter>,\n\n );\n\n\n\n fn run(&mut self, (time, mut counter): Self::SystemData) {\n\n counter.push(duration_to_nanos(time.delta_real_time())); \n\n\n\n println!(\"fps: {}, sampled: {}\", counter.frame_fps(), counter.sampled_fps());\n\n }\n\n}\n", "file_path": "src/systems/fps_system.rs", "rank": 92, "score": 11.542511800915348 }, { "content": "\t\t\t\tlet had_chainable: bool = any_chainable_exists(&p_clear.clear_queue, stack, &blocks);\n\n\n\n\t\t\t\t// max the chain and save data in a last chain\n\n\t\t\t\tif had_chainable {\n\n\t\t\t\t\tp_clear.chain += 1;\n\n\t\t\t\t\tp_clear.last_chain = max(p_clear.chain, p_clear.last_chain);\n\n\t\t\t\t}\n\n\t\t\t\t// otherwhise reset the chain\n\n\t\t\t\telse {\n\n\t\t\t\t\tp_clear.chain = 1;\n\n\t\t\t\t}\n\n\n\n\t\t\t\t// set all animation times and general time it will take all blocks that are \n\n\t\t\t\t// comboing to finish their animation\n\n\t\t\t\tfor id in &p_clear.clear_queue {\n\n\t\t\t\t\tlet b = blocks.get_mut(stack.from_i(*id as usize)).unwrap();\n\n\t\t\t\t\tlet set_time = flash + face + pop * p_clear.combo_counter;\n\n\t\t\t\t\tb.clear_time = set_time as i32;\n\n\t\t\t\t\tp_clear.combo_counter += 1;\n\n\n", "file_path": "src/systems/playfield_system.rs", "rank": 93, "score": 10.475313766136603 }, { "content": "\tif b1.is_comboable() {\n\n\t\tif let Some(block2) = b2 {\n\n\t\t\tif let Some(block3) = b3 {\n\n\t\t\t\tif block2.is_comboable_with(b1.kind) && block3.is_comboable_with(b1.kind) {\n\n\t\t\t\t\treturn Some(vec! [\n\n\t\t\t\t\t\tb1.id,\n\n\t\t\t\t\t\tblock2.id,\n\n\t\t\t\t\t\tblock3.id,\n\n\t\t\t\t\t])\n\n\t\t\t\t}\n\n\t\t\t}\n\n\t\t}\n\n\t}\t\n\n\n\n\t// just return nothing to save up on cpu\n\n\t// we could just return an empty vec but since this happens around 72 * 2 times its expensive to do so\n\n\tNone\n\n}\n\n\n", "file_path": "src/systems/playfield_system.rs", "rank": 94, "score": 10.22062943583356 }, { "content": " .with_pass(DrawSprite::new().with_transparency(\n\n ColorMask::all(),\n\n ALPHA,\n\n Some(DepthMode::LessEqualWrite),\n\n ))\n\n );\n\n\n\n // create some randomized seed to be shared\n\n let mut rand_seed: [u8; 16] = [0; 16];\n\n for x in &mut rand_seed {\n\n *x = rand::random::<u8>();\n\n }\n\n\n\n // testing different inputs for keyboard/controller\n\n let binding_path = {\n\n if cfg!(feature = \"sdl_controller\") {\n\n format!(\"{}/src/configs/input_controller.ron\", app_root)\n\n }\n\n else {\n\n format!(\"{}/src/configs/input.ron\", app_root)\n", "file_path": "src/main.rs", "rank": 95, "score": 8.010032370439074 }, { "content": "pub mod block_system;\n\npub mod cursor_system;\n\npub mod fps_system;\n\npub mod playfield_system;", "file_path": "src/systems/mod.rs", "rank": 96, "score": 7.903357520430347 }, { "content": "![screenshot](https://github.com/Skytrias/everpuzzle/blob/master/everpuzzle-04.gif \"preview\")\n\n\n\n# Everpuzzle\n\n**Tetris Attack/Pokemon Puzzle esque game written in Rust with Ametyhst**\n\n\n\nTalk / Code Walkthrough on this project https://www.youtube.com/watch?v=P_9A7P0uNpY\n\n\n\n## Goal\n\nBuild a clone similar to Tetris Attack and Pokémon Puzzle. This game needs to abide by the original rules of the game, so for example hit right frame times to feel exactly like the old games.\n\n\n\n## Rust\n\nI've tried many languages and rust's vision of safe multithreading is something I believe is important for games. So the goal is to also make this game run as fast as possible. If you have any ideas on how to improve the speed of the game, hit me up. \n\n\n\nThis is also a way for me to learn Rust more and to help it grow.\n\n\n\n## [Amethyst Game Engine](https://github.com/amethyst/amethyst)\n\nI've tried out most game engines there are right now for rust and all of them are heavily in development. Some are unmaintained or just don't have any visions for the future. As well it's important to me that the engine I'm using tries to achieve multithreading. And thats what Amethyst tries! So even if it's harder to make games with it, I'll use it. \n\n\n\n## How to Build\n\nIf you're new to Rust: [Download Rust](https://www.rust-lang.org/en-US/install.html)\n\n\n\n1. Clone/Download this repository into a folder\n\n2. Open a Command Line inside the folder and run: cargo run (Downloading all crates will take some time...)\n\n3. If you get errors make sure to update your Rust Version before creating issues here! Run: rustup update\n\n\n\nIf any steps were unclear or you had any issues, please open an issue. \n\n\n\n## How to Play\n\n| Action | Keyboard | Controller |\n\n| ------------ | ------------ | ------------ |\n\n| Move | WASD / Arrows | Analog Arrows |\n\n| Swap | X / Y | A / B |\n\n| Raise | C / V | L / R |\n\n| Reset | Space | Select |\n\n| Menu | Enter | Start |\n\n\n", "file_path": "README.md", "rank": 97, "score": 7.713265607396817 }, { "content": "\t\tp_push.raised_blocked_counter -= 1; \n\n\t\tp_push.smooth_raise = false; // deletes all smooth_raise signals \n\n\t\treturn;\n\n\t}\n\n\n\n\t// until counter is at 16 (the block sprite size)\n\n\tif p_push.offset_counter > 16.0 {\n\n\t\t// reset all offsets and reset smoothing\n\n\t\tp_push.offset_counter = 0.0; \n\n\t\tset_visual_offsets(0.0, stack, blocks, cursor);\n\n\t\tp_push.smooth_raise = false;\n\n\t\tp_push.raised_blocked_counter = 5; // TODO: GET TIME FROM FILE\n\n\t}\n\n\telse {\n\n\t\t// if smooth - increase faster\n\n\t\tif p_push.smooth_raise {\n\n\t\t\tp_push.offset_counter += 4.0;\n\n\t\t}\n\n\t\t// else slowly increase\n\n\t\telse {\n\n\t\t\tp_push.offset_counter += 0.025; // TODO: TIMES LEVEL DEPENDANT\n\n\t\t}\n\n\n\n\t\tset_visual_offsets(p_push.offset_counter, stack, blocks, cursor);\n\n\t}\n\n}\t\n\n\n", "file_path": "src/systems/playfield_system.rs", "rank": 98, "score": 7.572433830916056 }, { "content": "## About me\n\n*Skytrias #8787 on Discord*\n\n\n\nWhenever I try out new game engines/frameworks I start to make a clone of Tetris Attack just to get started. In the past I've done this a lot and I tried many ways to program parts of the logic. The old games are very logic intensive to it takes time until something you get something that works and is expandable.\n\n\n\nI've worked on [swap'n'pop](https://github.com/omenking/swap-n-pop) but the project seems to be dead which is sad. But it also had problems imo.\n\n\n\n## Contributing\n\nIf you are interested in helping out you can take a look at the [issues](https://github.com/Skytrias/rust-attack/issues) and work on anything you'd want. Otherwhise you can contact me on Discord ***Skytrias #8787***.\n\n\n\n## Links\n\n[Spread sheet for frame times](https://docs.google.com/spreadsheets/d/1SsVXHad0z7Dbsqfj-UTd4HZSGCslujkbh7vOan61D1g/edit#gid=1601136205) \n\n[Tetris Attack Discord](https://discordapp.com/invite/CxJwFFX)\n\n\n\n## License\n\nRust-Attack is free and open source software distributed under the terms of both the [MIT License](https://github.com/Skytrias/rust-attack/blob/master/LICENSE).\n\n\n\nThe rights to the original Tetris Attack sprites belong to Nintendo. In the future I'd like to use new art.\n", "file_path": "README.md", "rank": 99, "score": 6.221900980855624 } ]
Rust
AoC_2021/Day08_SevenSegmentSearch_Rust/src/main.rs
jgpr-code/AdventOfCode
f529af8d7cb74348405679b76062807827b35a29
use itertools::Itertools; use std::collections::{HashMap, HashSet}; use std::io::{self, Read}; fn main() -> io::Result<()> { let mut stdin = io::stdin(); let mut buffer = String::new(); stdin.read_to_string(&mut buffer)?; part_one(&buffer); part_two(&buffer); Ok(()) } fn parse_input(buffer: &str) -> Vec<(Vec<&str>, Vec<&str>)> { let mut output = Vec::new(); for line in buffer.lines() { let mut pipe_split = line.split("|"); let digits: Vec<&str> = pipe_split .nth(0) .unwrap() .split_whitespace() .filter(|s| s.len() > 0) .collect(); let output_digits: Vec<&str> = pipe_split .nth(0) .unwrap() .split_whitespace() .filter(|s| s.len() > 0) .collect(); output.push((digits, output_digits)); } output } fn part_one(buffer: &str) { let input = parse_input(buffer); let sum = input.iter().fold(0, |acc, (_, out)| { acc + out.iter().filter(|x| is_simple_digit(x)).count() }); println!("Part 1: {}", sum); } fn is_simple_digit(digit: &str) -> bool { let len = digit.len(); len == 2 || len == 4 || len == 3 || len == 7 } fn part_two(buffer: &str) { let input = parse_input(buffer); let answer = input.iter().fold(0, |acc, (d, od)| acc + decode(d, od)); println!("Part 2: {}", answer); } fn decode(digits: &Vec<&str>, output_digits: &Vec<&str>) -> i32 { let decodings = possible_decodings(); for decoding in decodings.iter() { if let Some(mapping) = digit_mapping(digits, decoding) { let mut thousands_chars: Vec<char> = output_digits[0].chars().collect(); thousands_chars.sort(); let thousands = mapping[&thousands_chars]; let mut hundreds_chars: Vec<char> = output_digits[1].chars().collect(); hundreds_chars.sort(); let hundreds = mapping[&hundreds_chars]; let mut tens_chars: Vec<char> = output_digits[2].chars().collect(); tens_chars.sort(); let tens = mapping[&tens_chars]; let mut ones_chars: Vec<char> = output_digits[3].chars().collect(); ones_chars.sort(); let ones = mapping[&ones_chars]; return 1000 * thousands + 100 * hundreds + 10 * tens + ones; } } 0 } fn possible_decodings() -> Vec<HashMap<char, i32>> { let perms: Vec<Vec<i32>> = (0..7).permutations(7).collect(); let chars = vec!['a', 'b', 'c', 'd', 'e', 'f', 'g']; let mut mappings = Vec::new(); for perm in perms.iter() { let mut mapping = HashMap::new(); for (c, i) in chars.iter().zip(perm) { mapping.insert(*c, *i); } mappings.push(mapping); } mappings } fn digit_mapping<'a>( digits: &Vec<&'a str>, decoding: &HashMap<char, i32>, ) -> Option<HashMap<Vec<char>, i32>> { let mut digit_mapping = HashMap::new(); for digit in digits.iter() { let segments = digit_to_segments(digit, decoding); if let Some(int_digit) = segments_to_digit(&segments) { let mut sorted_chars: Vec<char> = digit.chars().collect(); sorted_chars.sort(); digit_mapping.insert(sorted_chars, int_digit); } } if is_valid_mapping(&digit_mapping) { Some(digit_mapping) } else { None } } fn is_valid_mapping(digit_mapping: &HashMap<Vec<char>, i32>) -> bool { let values_set: HashSet<&i32> = digit_mapping.values().collect(); for i in 0..10 { if !values_set.contains(&i) { return false; } } if values_set.iter().count() != 10 { return false; } true } fn digit_to_segments(digit: &str, decoding: &HashMap<char, i32>) -> Vec<i32> { let mut segment_vec: Vec<i32> = digit.chars().map(|c| decoding[&c]).collect(); segment_vec.sort(); segment_vec } fn segments_to_digit(segments: &Vec<i32>) -> Option<i32> { match segments[..] { [0, 1, 2, 4, 5, 6] => Some(0), [2, 5] => Some(1), [0, 2, 3, 4, 6] => Some(2), [0, 2, 3, 5, 6] => Some(3), [1, 2, 3, 5] => Some(4), [0, 1, 3, 5, 6] => Some(5), [0, 1, 3, 4, 5, 6] => Some(6), [0, 2, 5] => Some(7), [0, 1, 2, 3, 4, 5, 6] => Some(8), [0, 1, 2, 3, 5, 6] => Some(9), _ => None, } }
use itertools::Itertools; use std::collections::{HashMap, HashSet}; use std::io::{self, Read}; fn main() -> io::Result<()> { let mut stdin = io::stdin(); let mut buffer = String::new(); stdin.read_to_string(&mut buffer)?; part_one(&buffer); part_two(&buffer); Ok(()) } fn parse_input(buffer: &str) -> Vec<(Vec<&str>, Vec<&str>)> { let mut output = Vec::new(); for line in buffer.lines() { let mut pipe_split = line.split("|"); let digits: Vec<&str> = pipe_split .nth(0) .unwrap() .split_whitespace() .filter(|s| s.len() > 0) .collect(); let output_digits: Vec<&str> = pipe_split .nth(0) .unwrap() .split_whitespace() .filter(|s| s.len() > 0) .collect(); output.push((digits, output_digits)); } output } fn part_one(buffer: &str) { let input = parse_input(buffer); let sum = input.iter().fold(0, |acc, (_, out)| { acc + out.iter().filter(|x| is_simple_digit(x)).count() }); println!("Part 1: {}", sum); } fn is_simple_digit(digit: &str) -> bool { let len = digit.len(); len == 2 || len == 4 || len == 3 || len == 7 } fn part_two(buffer: &str) { let input = parse_input(buffer); let answer = input.iter().fold(0, |acc, (d, od)| acc + decode(d, od)); println!("Part 2: {}", answer); } fn decode(digits: &Vec<&str>, output_digits: &Vec<&str>) -> i32 { let decodings = possible_decodings(); for decoding in decodings.iter() { if let Some(mapping) = digit_mapping(digits, decoding) { let mut thousands_chars: Vec<char> = output_digits[0].chars().collect(); thousands_chars.sort(); let thousands = mapping[&thousands_chars]; let mut hundreds_chars: Vec<char> = output_digits[1].chars().collect(); hundreds_chars.sort(); let hundreds = mapping[&hundreds_chars]; let mut tens_chars: Vec<char> = output_digits[2].chars().collect(); tens_chars.sort(); let tens = mapping[&tens_chars]; let mut ones_chars: Vec<char> = output_digits[3].chars().collect(); ones_chars.sort(); let ones = mapping[&ones_chars]; return 1000 * thousands + 100 * hundreds + 10 * tens + ones; } } 0 } fn possible_decodings() -> Vec<HashMap<char, i32>> { let perms: Vec<Vec<i32>> = (0..7).permutations(7).collect(); let chars = vec!['a', 'b', 'c', 'd', 'e', 'f', 'g']; let mut mappings = Vec::new(); for perm in perms.iter() { let mut mapping = HashMap::new(); for (c, i) in chars.iter().zip(perm) { mapping.insert(*c, *i); } mappings.push(mapping); } mappings } fn digit_mapping<'a>( digits: &Vec<&'a str>, decoding: &HashMap<char, i32>, ) -> Option<HashMap<Vec<char>, i32>> { let mut digit_mapping = HashMap::new(); for digit in digits.iter() { let segments = digit_to_segments(digit, decoding);
} if is_valid_mapping(&digit_mapping) { Some(digit_mapping) } else { None } } fn is_valid_mapping(digit_mapping: &HashMap<Vec<char>, i32>) -> bool { let values_set: HashSet<&i32> = digit_mapping.values().collect(); for i in 0..10 { if !values_set.contains(&i) { return false; } } if values_set.iter().count() != 10 { return false; } true } fn digit_to_segments(digit: &str, decoding: &HashMap<char, i32>) -> Vec<i32> { let mut segment_vec: Vec<i32> = digit.chars().map(|c| decoding[&c]).collect(); segment_vec.sort(); segment_vec } fn segments_to_digit(segments: &Vec<i32>) -> Option<i32> { match segments[..] { [0, 1, 2, 4, 5, 6] => Some(0), [2, 5] => Some(1), [0, 2, 3, 4, 6] => Some(2), [0, 2, 3, 5, 6] => Some(3), [1, 2, 3, 5] => Some(4), [0, 1, 3, 5, 6] => Some(5), [0, 1, 3, 4, 5, 6] => Some(6), [0, 2, 5] => Some(7), [0, 1, 2, 3, 4, 5, 6] => Some(8), [0, 1, 2, 3, 5, 6] => Some(9), _ => None, } }
if let Some(int_digit) = segments_to_digit(&segments) { let mut sorted_chars: Vec<char> = digit.chars().collect(); sorted_chars.sort(); digit_mapping.insert(sorted_chars, int_digit); }
if_condition
[ { "content": "fn parse_input(buffer: &str) -> Vec<LineSegment> {\n\n buffer.lines().map(|line| LineSegment::new(line)).collect()\n\n}\n\n\n", "file_path": "AoC_2021/Day05_HydrothermalVenture_Rust/src/main.rs", "rank": 4, "score": 217899.7567314388 }, { "content": "fn parse_input(buffer: &str) -> (Vec<i32>, Vec<BingoCard>) {\n\n let mut iter = buffer.split_terminator(\"\\r\\n\\r\\n\");\n\n\n\n let guesses: Vec<i32> = iter\n\n .nth(0)\n\n .expect(\"there was no guesses line\")\n\n .split(\",\")\n\n .map(|x| x.parse::<i32>().expect(\"failed to parse a guess as i32\"))\n\n .collect();\n\n\n\n let bingo_cards: Vec<BingoCard> = iter.map(|x| BingoCard::new(x)).collect();\n\n\n\n (guesses, bingo_cards)\n\n}\n\n\n", "file_path": "AoC_2021/Day04_GiantSquid_Rust/src/main.rs", "rank": 7, "score": 201337.3602398571 }, { "content": "fn part_one(buffer: &str) {\n\n let initial_timers: Vec<i64> = buffer\n\n .split(\",\")\n\n .map(|s| s.parse().expect(\"couldn't parse as i64\"))\n\n .collect();\n\n let amount_fishes = fishes_for_days(&initial_timers, 80);\n\n\n\n println!(\"Part 1: {}\", amount_fishes);\n\n}\n\n\n", "file_path": "AoC_2021/Day06_Lanternfish_Rust/src/main.rs", "rank": 9, "score": 185067.97021923328 }, { "content": "fn filter_by_pos(pos: usize, required_in_pos: char, lines: Vec<&str>) -> Vec<&str> {\n\n lines\n\n .into_iter()\n\n .filter(|slice| (*slice).chars().nth(pos).unwrap() == required_in_pos)\n\n .collect()\n\n}\n\n\n\n#[cfg(test)]\n\nmod tests {\n\n // TODO common setup which loads the Strings from the files (test.txt, input.txt)\n\n #[test]\n\n fn part_one_test() {}\n\n #[test]\n\n fn part_one_input() {}\n\n #[test]\n\n fn part_two_test() {}\n\n #[test]\n\n fn part_two_input() {}\n\n}\n", "file_path": "AoC_2021/Day03_BinaryDiagnostic_Rust/src/main.rs", "rank": 10, "score": 183756.8224529486 }, { "content": "fn parse_buffer(buffer: &str) -> Packet {\n\n // convert hex to binary\n\n let binary: String = buffer\n\n .chars()\n\n .flat_map(|c| hex_to_binary(c).chars().collect::<Vec<_>>())\n\n .collect();\n\n\n\n let mut reader = PacketReader::new(&binary[..]);\n\n let (_, top_level_packet) = reader.read_packet();\n\n top_level_packet\n\n}\n\n\n", "file_path": "AoC_2021/Day16_PacketDecoder_Rust/src/main.rs", "rank": 11, "score": 183756.07238718364 }, { "content": "fn part_one(buffer: &str) {\n\n let syntax_error_score: i64 = buffer.lines().map(|l| score_line(l)).sum();\n\n println!(\"Part 1: {}\", syntax_error_score);\n\n}\n\n\n", "file_path": "AoC_2021/Day10_SyntaxScoring_Rust/src/main.rs", "rank": 12, "score": 182403.6217843959 }, { "content": "fn part_one(buffer: &str) {\n\n let mut crab_positions: Vec<i32> = buffer.split(\",\").map(|x| x.parse().unwrap()).collect();\n\n let align_to = median(&mut crab_positions);\n\n let cost = crab_positions\n\n .iter()\n\n .fold(0, |acc, x| acc + (align_to - x).abs());\n\n println!(\"Part 1: {}\", cost);\n\n}\n\n\n", "file_path": "AoC_2021/Day07_TheTreacheryOfWhales_Rust/src/main.rs", "rank": 13, "score": 182403.6217843959 }, { "content": "fn part_one(buffer: &str) {\n\n let (guesses, mut bingo_cards) = parse_input(buffer);\n\n\n\n let (last_guess, first_winner) =\n\n play_until_first_winner(&guesses, &mut bingo_cards).expect(\"no first winner\");\n\n\n\n println!(\"Part 1: {}\", last_guess * first_winner.sum_of_unmarked());\n\n}\n\n\n", "file_path": "AoC_2021/Day04_GiantSquid_Rust/src/main.rs", "rank": 14, "score": 182403.6217843959 }, { "content": "fn part_one(buffer: &str) {\n\n let grid = Grid::new(buffer);\n\n let risk_levels_sum: i32 = grid\n\n .low_points()\n\n .iter()\n\n .map(|(r, c)| grid.grid[*r as usize][*c as usize] + 1)\n\n .sum();\n\n\n\n println!(\"Part 1: {}\", risk_levels_sum);\n\n}\n\n\n", "file_path": "AoC_2021/Day09_SmokeBasin_Rust/src/main.rs", "rank": 15, "score": 182403.6217843959 }, { "content": "fn part_one(buffer: &str) {\n\n let line_segments = parse_input(buffer);\n\n let mut line_counts: HashMap<(i32, i32), i32> = HashMap::new();\n\n for line_segment in line_segments.iter().filter(|s| s.is_axis_aligned()) {\n\n if line_segment.is_vertical() {\n\n let (x, (y_begin, y_end)) = line_segment.vertical_range().unwrap();\n\n for y in y_begin..y_end + 1 {\n\n let entry = line_counts.entry((x, y)).or_insert(0);\n\n *entry += 1;\n\n }\n\n } else {\n\n let (y, (x_begin, x_end)) = line_segment.horizontal_range().unwrap();\n\n for x in x_begin..x_end + 1 {\n\n let entry = line_counts.entry((x, y)).or_insert(0);\n\n *entry += 1;\n\n }\n\n }\n\n }\n\n let intersections = line_counts.iter().filter(|(_, val)| **val > 1).count();\n\n\n\n println!(\"Part 1: {}\", intersections);\n\n}\n\n\n", "file_path": "AoC_2021/Day05_HydrothermalVenture_Rust/src/main.rs", "rank": 16, "score": 182403.6217843959 }, { "content": "fn is_opening(c: char) -> bool {\n\n match c {\n\n '(' | '[' | '{' | '<' => true,\n\n _ => false,\n\n }\n\n}\n\n\n", "file_path": "AoC_2021/Day10_SyntaxScoring_Rust/src/main.rs", "rank": 17, "score": 182182.81575271618 }, { "content": "fn parse_buffer(buffer: &str) -> EnhanceableGrid {\n\n EnhanceableGrid::from(buffer)\n\n}\n\n\n", "file_path": "AoC_2021/Day20_TrenchMap_Rust/src/main.rs", "rank": 18, "score": 181592.12163262058 }, { "content": "fn part_one(input: &mut DumboOctopusGrid) -> usize {\n\n let mut flashes_total = 0;\n\n for _ in 0..100 {\n\n flashes_total += input.simulate_day();\n\n }\n\n flashes_total\n\n}\n\n\n", "file_path": "AoC_2021/Day11_DumboOctopus_Rust/src/main.rs", "rank": 21, "score": 169034.76873823462 }, { "content": "fn median(nums: &mut Vec<i32>) -> i32 {\n\n nums.sort_unstable();\n\n let idx = nums.len() / 2;\n\n nums[idx]\n\n}\n\n\n", "file_path": "AoC_2021/Day07_TheTreacheryOfWhales_Rust/src/main.rs", "rank": 22, "score": 160461.27599142064 }, { "content": "fn score_line(line: &str) -> i64 {\n\n let mut stack = Vec::new();\n\n for c in line.chars() {\n\n if is_opening(c) {\n\n stack.push(c);\n\n } else {\n\n match stack.last() {\n\n Some(open) if is_corresponding_closing(*open, c) => stack.pop(),\n\n _ => return score_illegal(c),\n\n };\n\n }\n\n }\n\n 0\n\n}\n\n\n", "file_path": "AoC_2021/Day10_SyntaxScoring_Rust/src/main.rs", "rank": 23, "score": 159923.71796091524 }, { "content": "fn parse_buffer(buffer: &str) -> Grid {\n\n let content: Vec<Vec<i32>> = buffer\n\n .lines()\n\n .map(|l| l.chars().map(|c| c.to_digit(10).unwrap() as i32).collect())\n\n .collect();\n\n let rows = content.len();\n\n let cols = content[0].len();\n\n Grid {\n\n content,\n\n rows,\n\n cols,\n\n }\n\n}\n\n\n", "file_path": "AoC_2021/Day15_Chiton_Rust/src/main.rs", "rank": 24, "score": 159759.37506910673 }, { "content": "fn is_corresponding_closing(open: char, close: char) -> bool {\n\n match (open, close) {\n\n ('(', ')') | ('[', ']') | ('{', '}') | ('<', '>') => true,\n\n _ => false,\n\n }\n\n}\n\n\n", "file_path": "AoC_2021/Day10_SyntaxScoring_Rust/src/main.rs", "rank": 25, "score": 159063.58125395514 }, { "content": "fn parse_buffer(buffer: &str) -> Origami {\n\n Origami {}\n\n}\n\n\n", "file_path": "AoC_2021/Day13_TransparentOrigami_Rust/src/main.rs", "rank": 26, "score": 157868.84253726527 }, { "content": "fn part_two(buffer: &str) {\n\n let initial_timers: Vec<i64> = buffer\n\n .split(\",\")\n\n .map(|s| s.parse().expect(\"couldn't parse as i64\"))\n\n .collect();\n\n let amount_fishes = fishes_for_days(&initial_timers, 256);\n\n\n\n println!(\"Part 2: {}\", amount_fishes);\n\n}\n\n\n", "file_path": "AoC_2021/Day06_Lanternfish_Rust/src/main.rs", "rank": 27, "score": 157824.04706968053 }, { "content": "fn parse_buffer(buffer: &str) -> CaveGraph {\n\n lazy_static! {\n\n static ref RE: Regex = Regex::new(\"^(?P<A>.*)-(?P<B>.*)$\").unwrap();\n\n }\n\n\n\n let mut cave_graph = CaveGraph {\n\n adjacency: HashMap::new(),\n\n start_label: String::from(\"start\"),\n\n end_label: String::from(\"end\"),\n\n };\n\n for line in buffer.lines() {\n\n let caps = RE.captures(line).unwrap();\n\n let node_a = caps.name(\"A\").unwrap().as_str().to_string();\n\n let node_b = caps.name(\"B\").unwrap().as_str().to_string();\n\n\n\n let adjacent_node_a = cave_graph\n\n .adjacency\n\n .entry(node_a.clone())\n\n .or_insert(HashMultiSet::new());\n\n adjacent_node_a.insert(node_b.clone());\n\n\n\n let adjacent_node_b = cave_graph\n\n .adjacency\n\n .entry(node_b.clone())\n\n .or_insert(HashMultiSet::new());\n\n adjacent_node_b.insert(node_a.clone());\n\n }\n\n cave_graph\n\n}\n\n\n", "file_path": "AoC_2021/Day12_PassagePathing_Rust/src/main.rs", "rank": 28, "score": 156051.60953514284 }, { "content": "fn part_two(buffer: &str) {\n\n let mut crab_positions: Vec<i32> = buffer.split(\",\").map(|x| x.parse().unwrap()).collect();\n\n crab_positions.sort_unstable();\n\n let min = crab_positions.first().unwrap();\n\n let max = crab_positions.last().unwrap();\n\n let mut cost_min = i32::MAX;\n\n for i in *min..*max + 1 {\n\n let cost = crab_positions\n\n .iter()\n\n .fold(0, |acc, x| acc + gauss_distance(i, *x));\n\n cost_min = cmp::min(cost_min, cost);\n\n }\n\n println!(\"Part 2: {}\", cost_min);\n\n}\n\n\n", "file_path": "AoC_2021/Day07_TheTreacheryOfWhales_Rust/src/main.rs", "rank": 29, "score": 155764.31460374352 }, { "content": "fn part_two(buffer: &str) {\n\n let line_segments = parse_input(buffer);\n\n let mut line_counts: HashMap<(i32, i32), i32> = HashMap::new();\n\n let (axis_aligned, diagonal): (Vec<LineSegment>, Vec<LineSegment>) =\n\n line_segments.iter().partition(|s| s.is_axis_aligned());\n\n for line_segment in axis_aligned {\n\n if line_segment.is_vertical() {\n\n let (x, (y_begin, y_end)) = line_segment.vertical_range().unwrap();\n\n for y in y_begin..y_end + 1 {\n\n let entry = line_counts.entry((x, y)).or_insert(0);\n\n *entry += 1;\n\n }\n\n } else {\n\n let (y, (x_begin, x_end)) = line_segment.horizontal_range().unwrap();\n\n for x in x_begin..x_end + 1 {\n\n let entry = line_counts.entry((x, y)).or_insert(0);\n\n *entry += 1;\n\n }\n\n }\n\n }\n", "file_path": "AoC_2021/Day05_HydrothermalVenture_Rust/src/main.rs", "rank": 30, "score": 155764.31460374352 }, { "content": "fn part_two(buffer: &str) {\n\n let incomplete_lines: Vec<&str> = buffer.lines().filter(|l| score_line(l) == 0).collect();\n\n let mut line_scores: Vec<i64> = incomplete_lines\n\n .iter()\n\n .map(|l| score_completion(l))\n\n .collect();\n\n line_scores.sort_unstable();\n\n let middle: usize = line_scores.len() / 2;\n\n println!(\"Part 2: {}\", line_scores[middle]);\n\n}\n\n\n", "file_path": "AoC_2021/Day10_SyntaxScoring_Rust/src/main.rs", "rank": 31, "score": 155764.31460374352 }, { "content": "fn part_two(buffer: &str) {\n\n let (guesses, mut bingo_cards) = parse_input(buffer);\n\n\n\n let (last_guess, last_winner) =\n\n play_until_last_winner(&guesses, &mut bingo_cards).expect(\"no last winner\");\n\n\n\n println!(\"Part 2: {}\", last_guess * last_winner.sum_of_unmarked());\n\n}\n\n\n", "file_path": "AoC_2021/Day04_GiantSquid_Rust/src/main.rs", "rank": 32, "score": 155764.31460374352 }, { "content": "fn part_two(buffer: &str) {\n\n let grid = Grid::new(buffer);\n\n let low_points = grid.low_points();\n\n let mut basin_sizes: Vec<usize> = low_points.iter().map(|lp| grid.basin_size(*lp)).collect();\n\n basin_sizes.sort();\n\n\n\n println!(\"low_points: {:?}\", low_points);\n\n println!(\"basin_sizes: {:?}\", basin_sizes);\n\n let answer: usize = basin_sizes.iter().rev().take(3).product();\n\n println!(\"Part 2: {}\", answer);\n\n}\n\n\n", "file_path": "AoC_2021/Day09_SmokeBasin_Rust/src/main.rs", "rank": 33, "score": 155764.31460374352 }, { "content": "// there is probably a function for this but I couldn't find one fast enough so here is my thingy\n\nfn hex_to_binary(c: char) -> String {\n\n String::from(match c {\n\n '0' => \"0000\",\n\n '1' => \"0001\",\n\n '2' => \"0010\",\n\n '3' => \"0011\",\n\n '4' => \"0100\",\n\n '5' => \"0101\",\n\n '6' => \"0110\",\n\n '7' => \"0111\",\n\n '8' => \"1000\",\n\n '9' => \"1001\",\n\n 'A' => \"1010\",\n\n 'B' => \"1011\",\n\n 'C' => \"1100\",\n\n 'D' => \"1101\",\n\n 'E' => \"1110\",\n\n 'F' => \"1111\",\n\n _ => \"\",\n\n })\n\n}\n\n\n", "file_path": "AoC_2021/Day16_PacketDecoder_Rust/src/main.rs", "rank": 34, "score": 155394.89514257933 }, { "content": "fn part_one(lines: &Vec<&str>) {\n\n let num_reports = lines.len();\n\n let line_length = lines.first().unwrap().len();\n\n let mut count_ones: Vec<usize> = vec![0; line_length];\n\n\n\n for line in lines {\n\n for (i, _) in line.match_indices(\"1\") {\n\n count_ones[i] += 1;\n\n }\n\n }\n\n\n\n let gamma_rate_binary: Vec<char> = count_ones\n\n .iter()\n\n .map(|c| if *c > num_reports / 2 { '1' } else { '0' })\n\n .collect();\n\n println!(\"{:?}\", gamma_rate_binary);\n\n\n\n let gamma_rate_string: String = gamma_rate_binary.iter().collect();\n\n let epsilon_rate_string: String = gamma_rate_binary\n\n .iter()\n\n .map(|c| if *c == '1' { '0' } else { '1' })\n\n .collect();\n\n\n\n let gamma_rate = u32::from_str_radix(&gamma_rate_string, 2).unwrap();\n\n let epsilon_rate = u32::from_str_radix(&epsilon_rate_string, 2).unwrap();\n\n\n\n println!(\"Part 1: {}\", gamma_rate * epsilon_rate);\n\n}\n\n\n", "file_path": "AoC_2021/Day03_BinaryDiagnostic_Rust/src/main.rs", "rank": 35, "score": 153415.47110949925 }, { "content": "fn score_completion(line: &str) -> i64 {\n\n let mut stack = Vec::new();\n\n for c in line.chars() {\n\n if is_opening(c) {\n\n stack.push(c);\n\n } else {\n\n match stack.last() {\n\n Some(open) if is_corresponding_closing(*open, c) => stack.pop(),\n\n _ => panic!(\"please no illegal lines anymore\"),\n\n };\n\n }\n\n }\n\n score_remaining(&mut stack)\n\n}\n\n\n", "file_path": "AoC_2021/Day10_SyntaxScoring_Rust/src/main.rs", "rank": 36, "score": 151580.46892878902 }, { "content": "fn required_in_pos(pos: usize, lines: &Vec<&str>, rating: Rating) -> char {\n\n let num_reports = lines.len();\n\n let ones = lines\n\n .iter()\n\n .map(|slice| slice.chars().nth(pos).unwrap())\n\n .filter(|c| *c == '1')\n\n .count();\n\n let zeros = num_reports - ones;\n\n\n\n match rating {\n\n Rating::OxygenGenerator => {\n\n if ones >= zeros {\n\n '1'\n\n } else {\n\n '0'\n\n }\n\n }\n\n Rating::Co2Scrubber => {\n\n if zeros <= ones {\n\n '0'\n\n } else {\n\n '1'\n\n }\n\n }\n\n }\n\n}\n\n\n", "file_path": "AoC_2021/Day03_BinaryDiagnostic_Rust/src/main.rs", "rank": 37, "score": 151196.2799621261 }, { "content": "fn parse_buffer(buffer: &str) -> Result<DumboOctopusGrid> {\n\n let parsed = buffer\n\n .lines()\n\n .map(|l| {\n\n l.chars()\n\n .map(|c| c.to_digit(10).context(\"char was not a valid digit\"))\n\n .collect::<Result<Vec<u32>>>()\n\n })\n\n .collect::<Result<Vec<Vec<u32>>>>()?;\n\n\n\n Ok(DumboOctopusGrid { grid: parsed })\n\n}\n\n\n", "file_path": "AoC_2021/Day11_DumboOctopus_Rust/src/main.rs", "rank": 38, "score": 149010.6325462509 }, { "content": "fn part_one(grid: &mut EnhanceableGrid) -> i64 {\n\n println!(\"{:?} {:?}\", grid.rows(), grid.cols());\n\n grid.print_content();\n\n grid.enhance();\n\n grid.print_content();\n\n grid.enhance();\n\n grid.print_content();\n\n println!(\"{:?} {:?}\", grid.rows(), grid.cols());\n\n grid.count_hashes()\n\n}\n\n\n", "file_path": "AoC_2021/Day20_TrenchMap_Rust/src/main.rs", "rank": 39, "score": 148366.16154871613 }, { "content": "fn part_two(input: &mut DumboOctopusGrid) -> usize {\n\n let mut day = 0;\n\n loop {\n\n day += 1;\n\n let amount = input.simulate_day();\n\n if amount == (input.rows() * input.cols()) as usize {\n\n break day;\n\n }\n\n }\n\n}\n\n\n\n#[cfg(test)]\n\nmod tests {\n\n use super::*;\n\n use std::fs;\n\n use std::sync::Once;\n\n\n\n static INIT: Once = Once::new();\n\n static mut TEST: DumboOctopusGrid = DumboOctopusGrid { grid: Vec::new() };\n\n static mut INPUT: DumboOctopusGrid = DumboOctopusGrid { grid: Vec::new() };\n", "file_path": "AoC_2021/Day11_DumboOctopus_Rust/src/main.rs", "rank": 40, "score": 144567.44461588515 }, { "content": "fn gauss_distance(a: i32, b: i32) -> i32 {\n\n (a - b).abs() * ((a - b).abs() + 1) / 2\n\n}\n\n\n\n// sum 1 to n = (n * (n+1)) / 2\n\n// (a, b, c)\n\n// determine x such that min |a-x| + |b-x| + |c-x|\n\n// d(a, x) = sum k=1 to |a-x|: k => gauss |a-x| * (|a-x| + 1) / 2 => (x-a)^2 + |x-a| => 2(x-a) + sign(x-a)\n\n//\n\n\n\n// how can this be solved mathematically:\n\n// min_x sum i=1 to n: d( |crab_i - x| )\n\n// d(x) = x * (x+1) / 2\n\n// reformulate to:\n\n// min_z sum i=1 to n: d( z )\n\n// s.t. z_i >= +(crab_i - x)\n\n// z_i >= -(crab_i - x)\n\n// constrained quadratic optimization problem\n", "file_path": "AoC_2021/Day07_TheTreacheryOfWhales_Rust/src/main.rs", "rank": 41, "score": 144533.85379970563 }, { "content": "fn score_remaining(stack: &mut Vec<char>) -> i64 {\n\n let mut score = 0;\n\n while let Some(c) = stack.pop() {\n\n score *= 5;\n\n score += bracket_score(c);\n\n }\n\n score\n\n}\n\n\n", "file_path": "AoC_2021/Day10_SyntaxScoring_Rust/src/main.rs", "rank": 42, "score": 142498.75907017195 }, { "content": "fn parse_buffer(buffer: &str) -> Result<Vec<i64>, Box<dyn Error>> {\n\n let parsed = buffer\n\n .lines()\n\n .map(|l| l.parse::<i64>())\n\n .collect::<Result<Vec<i64>, ParseIntError>>()?;\n\n Ok(parsed)\n\n}\n\n\n", "file_path": "AoC_2021/Day01_SonarSweep_Rust/src/main.rs", "rank": 44, "score": 134844.79206616408 }, { "content": "fn part_one(grid: &Grid) -> i32 {\n\n let mut dist: HashMap<(i32, i32), i32> = HashMap::new();\n\n let mut priority_queue: BinaryHeap<Node> = BinaryHeap::new();\n\n\n\n dist.insert((0, 0), grid.at_pos(&(0, 0)));\n\n\n\n let target = ((grid.rows - 1) as i32, (grid.cols - 1) as i32);\n\n\n\n priority_queue.push(Node {\n\n pos: (0, 0),\n\n distance: 0, // start node doesn't count towards cost\n\n });\n\n\n\n while let Some(node) = priority_queue.pop() {\n\n //println!(\"{:?}\", node);\n\n if node.pos == target {\n\n return node.distance;\n\n }\n\n let old_dist = dist.entry(node.pos).or_insert(i32::MAX);\n\n if node.distance > *old_dist {\n", "file_path": "AoC_2021/Day15_Chiton_Rust/src/main.rs", "rank": 45, "score": 131436.24822327332 }, { "content": "fn part_two(lines: &Vec<&str>) {\n\n let mut oxygen_generator_rating = lines.clone();\n\n let mut co2_scrubber_rating = lines.clone();\n\n for pos in 0..lines.first().unwrap().len() {\n\n if oxygen_generator_rating.len() != 1 {\n\n let required_in_pos =\n\n required_in_pos(pos, &oxygen_generator_rating, Rating::OxygenGenerator);\n\n oxygen_generator_rating = filter_by_pos(pos, required_in_pos, oxygen_generator_rating);\n\n }\n\n if co2_scrubber_rating.len() != 1 {\n\n let required_in_pos = required_in_pos(pos, &co2_scrubber_rating, Rating::Co2Scrubber);\n\n co2_scrubber_rating = filter_by_pos(pos, required_in_pos, co2_scrubber_rating);\n\n }\n\n }\n\n\n\n let oxygen_generator_rating =\n\n u32::from_str_radix(oxygen_generator_rating.first().unwrap(), 2).unwrap();\n\n let co2_scrubber_rating = u32::from_str_radix(co2_scrubber_rating.first().unwrap(), 2).unwrap();\n\n\n\n println!(\"Part 2: {}\", oxygen_generator_rating * co2_scrubber_rating);\n\n}\n\n\n", "file_path": "AoC_2021/Day03_BinaryDiagnostic_Rust/src/main.rs", "rank": 46, "score": 127354.52642223859 }, { "content": "fn part_one(input: &Vec<i64>) -> usize {\n\n input.windows(2).filter(|w| w[0] < w[1]).count()\n\n}\n\n\n", "file_path": "AoC_2021/Day01_SonarSweep_Rust/src/main.rs", "rank": 47, "score": 125603.18277995009 }, { "content": "fn part_one(origami: &mut Origami) -> i64 {\n\n 0\n\n}\n\n\n", "file_path": "AoC_2021/Day13_TransparentOrigami_Rust/src/main.rs", "rank": 48, "score": 125187.4883477843 }, { "content": "fn part_two(grid: &mut EnhanceableGrid) -> i64 {\n\n for _ in 0..48 {\n\n grid.enhance();\n\n }\n\n grid.count_hashes()\n\n}\n", "file_path": "AoC_2021/Day20_TrenchMap_Rust/src/main.rs", "rank": 49, "score": 123389.73661295621 }, { "content": "fn part_one(cave_graph: &mut CaveGraph) -> i64 {\n\n let allow_twice = false;\n\n cave_graph.eliminate_big_caves(allow_twice);\n\n println!(\"{:?}\", cave_graph);\n\n\n\n cave_graph.count_paths(allow_twice)\n\n}\n\n\n", "file_path": "AoC_2021/Day12_PassagePathing_Rust/src/main.rs", "rank": 50, "score": 121601.29196955936 }, { "content": "fn main() {\n\n let mut stdin = io::stdin();\n\n let mut buffer = String::new();\n\n stdin\n\n .read_to_string(&mut buffer)\n\n .expect(\"failed to read file\");\n\n let input = parse_buffer(&buffer);\n\n println!(\"{:?}\", input);\n\n println!(\"Part 1: {}\", part_one(&input));\n\n println!(\"Part 2: {}\", part_two(&input));\n\n}\n\n\n", "file_path": "AoC_2021/Day16_PacketDecoder_Rust/src/main.rs", "rank": 51, "score": 119905.62519125098 }, { "content": "fn main() -> anyhow::Result<()> {\n\n let mut stdin = io::stdin();\n\n let mut buffer = String::new();\n\n stdin.read_to_string(&mut buffer)?;\n\n let mut input = parse_buffer(&buffer);\n\n println!(\"Part 1: {}\", part_one(&mut input));\n\n println!(\"Part 2: {}\", part_two(&mut input));\n\n Ok(())\n\n}\n\n\n", "file_path": "AoC_2021/Day20_TrenchMap_Rust/src/main.rs", "rank": 52, "score": 110543.16842491366 }, { "content": "fn part_two(grid: &Grid) -> i32 {\n\n let enlarged_grid = grid.enlarged_grid(5);\n\n part_one(&enlarged_grid)\n\n}\n", "file_path": "AoC_2021/Day15_Chiton_Rust/src/main.rs", "rank": 54, "score": 104796.94104262095 }, { "content": "fn score_illegal(illegal: char) -> i64 {\n\n match illegal {\n\n ')' => 3,\n\n ']' => 57,\n\n '}' => 1197,\n\n '>' => 25137,\n\n _ => 0,\n\n }\n\n}\n\n\n", "file_path": "AoC_2021/Day10_SyntaxScoring_Rust/src/main.rs", "rank": 55, "score": 103289.14153076954 }, { "content": "fn bracket_score(bracket: char) -> i64 {\n\n match bracket {\n\n '(' => 1,\n\n '[' => 2,\n\n '{' => 3,\n\n '<' => 4,\n\n _ => 0,\n\n }\n\n}\n", "file_path": "AoC_2021/Day10_SyntaxScoring_Rust/src/main.rs", "rank": 56, "score": 103289.14153076954 }, { "content": "fn part_one(top_level_packet: &Packet) -> u32 {\n\n println!(\"{:?}\", parse_buffer(\"D2FE28\"));\n\n let mut version_sum: u32 = 0;\n\n let mut packet_queue: VecDeque<&Packet> = VecDeque::new();\n\n packet_queue.push_back(top_level_packet);\n\n while let Some(packet) = packet_queue.pop_front() {\n\n version_sum += packet.version as u32;\n\n for contained_packet in packet.packets.iter() {\n\n packet_queue.push_back(contained_packet);\n\n }\n\n }\n\n version_sum\n\n}\n\n\n", "file_path": "AoC_2021/Day16_PacketDecoder_Rust/src/main.rs", "rank": 57, "score": 101567.80870975624 }, { "content": "fn part_two(input: &Vec<i64>) -> usize {\n\n input.windows(4).filter(|w| w[0] < w[3]).count()\n\n}\n\n\n\n#[cfg(test)]\n\nmod tests {\n\n use super::*;\n\n use std::fs;\n\n use std::sync::Once;\n\n\n\n static INIT: Once = Once::new();\n\n static mut TEST: Vec<i64> = Vec::new();\n\n static mut INPUT: Vec<i64> = Vec::new();\n\n\n\n fn init() {\n\n unsafe {\n\n INIT.call_once(|| {\n\n TEST = read_from_file(\"test.txt\");\n\n INPUT = read_from_file(\"input.txt\");\n\n });\n", "file_path": "AoC_2021/Day01_SonarSweep_Rust/src/main.rs", "rank": 58, "score": 100096.0207320548 }, { "content": "fn part_two(origami: &mut Origami) -> i64 {\n\n 0\n\n}\n", "file_path": "AoC_2021/Day13_TransparentOrigami_Rust/src/main.rs", "rank": 59, "score": 99680.32629988901 }, { "content": "fn part_two(cave_graph: &mut CaveGraph) -> i64 {\n\n let allow_twice = true;\n\n cave_graph.eliminate_big_caves(allow_twice);\n\n cave_graph.count_paths(allow_twice)\n\n}\n\n// build graph\n\n// replace big Nodes by connecting all its neigbours with each other\n\n// run dfs from start and count finish encounters\n", "file_path": "AoC_2021/Day12_PassagePathing_Rust/src/main.rs", "rank": 60, "score": 97133.96784720989 }, { "content": "fn main() {\n\n let mut stdin = io::stdin();\n\n let mut buffer = String::new();\n\n stdin\n\n .read_to_string(&mut buffer)\n\n .expect(\"failed to read file\");\n\n let mut input_part_one = parse_buffer(&buffer);\n\n let mut input_part_two = input_part_one.clone();\n\n println!(\"{:?}\", input_part_one);\n\n println!(\"Part 1: {}\", part_one(&mut input_part_one));\n\n println!(\"Part 2: {}\", part_two(&mut input_part_two));\n\n}\n\n\n", "file_path": "AoC_2021/Day15_Chiton_Rust/src/main.rs", "rank": 61, "score": 92520.93033542532 }, { "content": "fn main() {\n\n let mut stdin = io::stdin();\n\n let mut buffer = String::new();\n\n stdin\n\n .read_to_string(&mut buffer)\n\n .expect(\"failed to read file\");\n\n let mut input_part_one = parse_buffer(&buffer);\n\n let mut input_part_two = input_part_one.clone();\n\n println!(\"{:?}\", input_part_one);\n\n println!(\"Part 1: {}\", part_one(&mut input_part_one));\n\n println!(\"Part 2: {}\", part_two(&mut input_part_two));\n\n}\n\n\n", "file_path": "AoC_2021/Day13_TransparentOrigami_Rust/src/main.rs", "rank": 62, "score": 91556.45491710921 }, { "content": "fn main() {\n\n let mut stdin = io::stdin();\n\n let mut buffer = String::new();\n\n stdin\n\n .read_to_string(&mut buffer)\n\n .expect(\"failed to read file\");\n\n let mut input_part_one = parse_buffer(&buffer);\n\n let mut input_part_two = input_part_one.clone();\n\n println!(\"{:?}\", input_part_one);\n\n println!(\"Part 1: {}\", part_one(&mut input_part_one));\n\n println!(\"Part 2: {}\", part_two(&mut input_part_two));\n\n}\n\n\n", "file_path": "AoC_2021/Day12_PassagePathing_Rust/src/main.rs", "rank": 63, "score": 91556.45491710921 }, { "content": "fn main() {\n\n println!(\"Hello, world!\");\n\n}\n", "file_path": "AoC_2021/Day14_ExtendedPolymerization_Rust/src/main.rs", "rank": 64, "score": 91556.45491710921 }, { "content": "fn main() -> Result<()> {\n\n let mut stdin = io::stdin();\n\n let mut buffer = String::new();\n\n stdin.read_to_string(&mut buffer)?;\n\n let mut input_part_one = parse_buffer(&buffer)?;\n\n let mut input_part_two = input_part_one.clone();\n\n println!(\"Part 1: {}\", part_one(&mut input_part_one));\n\n println!(\"Part 2: {}\", part_two(&mut input_part_two));\n\n Ok(())\n\n}\n\n\n", "file_path": "AoC_2021/Day11_DumboOctopus_Rust/src/main.rs", "rank": 65, "score": 87156.53899155068 }, { "content": "fn main() -> io::Result<()> {\n\n let mut stdin = io::stdin();\n\n let mut buffer = String::new();\n\n stdin.read_to_string(&mut buffer)?;\n\n part_one(&buffer);\n\n part_two(&buffer);\n\n Ok(())\n\n}\n\n\n", "file_path": "AoC_2021/Day06_Lanternfish_Rust/src/main.rs", "rank": 66, "score": 84146.39996303944 }, { "content": "fn main() -> io::Result<()> {\n\n let mut stdin = io::stdin();\n\n let mut buffer = String::new();\n\n stdin.read_to_string(&mut buffer)?;\n\n\n\n let commands: Vec<Command> = buffer.lines().map(|x| Command::new(x)).collect();\n\n\n\n part_one(&commands);\n\n part_two(&commands);\n\n Ok(())\n\n}\n\n\n", "file_path": "AoC_2021/Day02_Dive_Rust/src/main.rs", "rank": 67, "score": 84146.39996303944 }, { "content": "fn main() -> io::Result<()> {\n\n let mut stdin = io::stdin();\n\n let mut buffer = String::new();\n\n stdin.read_to_string(&mut buffer)?;\n\n let lines: Vec<&str> = buffer.lines().collect();\n\n\n\n part_one(&lines);\n\n part_two(&lines);\n\n Ok(())\n\n}\n\n\n", "file_path": "AoC_2021/Day03_BinaryDiagnostic_Rust/src/main.rs", "rank": 68, "score": 83263.6244490945 }, { "content": "fn main() -> io::Result<()> {\n\n let mut stdin = io::stdin();\n\n let mut buffer = String::new();\n\n stdin.read_to_string(&mut buffer)?;\n\n part_one(&buffer);\n\n part_two(&buffer);\n\n Ok(())\n\n}\n\n\n", "file_path": "AoC_2021/Day10_SyntaxScoring_Rust/src/main.rs", "rank": 69, "score": 83263.6244490945 }, { "content": "fn main() -> io::Result<()> {\n\n let mut stdin = io::stdin();\n\n let mut buffer = String::new();\n\n stdin.read_to_string(&mut buffer)?;\n\n part_one(&buffer);\n\n part_two(&buffer);\n\n Ok(())\n\n}\n\n\n", "file_path": "AoC_2021/Day05_HydrothermalVenture_Rust/src/main.rs", "rank": 70, "score": 83263.6244490945 }, { "content": "fn main() -> io::Result<()> {\n\n let mut stdin = io::stdin();\n\n let mut buffer = String::new();\n\n stdin.read_to_string(&mut buffer)?;\n\n part_one(&buffer);\n\n part_two(&buffer);\n\n Ok(())\n\n}\n\n\n", "file_path": "AoC_2021/Day07_TheTreacheryOfWhales_Rust/src/main.rs", "rank": 71, "score": 83263.6244490945 }, { "content": "fn main() -> io::Result<()> {\n\n let mut stdin = io::stdin();\n\n let mut buffer = String::new();\n\n stdin.read_to_string(&mut buffer)?;\n\n part_one(&buffer);\n\n part_two(&buffer);\n\n Ok(())\n\n}\n\n\n", "file_path": "AoC_2021/Day04_GiantSquid_Rust/src/main.rs", "rank": 72, "score": 83263.6244490945 }, { "content": "fn main() -> io::Result<()> {\n\n let mut stdin = io::stdin();\n\n let mut buffer = String::new();\n\n stdin.read_to_string(&mut buffer)?;\n\n part_one(&buffer);\n\n part_two(&buffer);\n\n Ok(())\n\n}\n\n\n", "file_path": "AoC_2021/Day09_SmokeBasin_Rust/src/main.rs", "rank": 73, "score": 83263.6244490945 }, { "content": "fn part_one(commands: &Vec<Command>) {\n\n let mut location = Location {\n\n horizontal: 0,\n\n depth: 0,\n\n };\n\n location = commands.iter().fold(location, |l, c| l.execute_command(c));\n\n println!(\"Part 1: {}\", location.multiply());\n\n}\n\n\n", "file_path": "AoC_2021/Day02_Dive_Rust/src/main.rs", "rank": 74, "score": 80817.09331118144 }, { "content": "fn main() -> Result<(), Box<dyn Error>> {\n\n let mut stdin = io::stdin();\n\n let mut buffer = String::new();\n\n stdin.read_to_string(&mut buffer)?;\n\n let input = parse_buffer(&buffer)?;\n\n println!(\"Part 1: {}\", part_one(&input));\n\n println!(\"Part 2: {}\", part_two(&input));\n\n Ok(())\n\n}\n\n\n", "file_path": "AoC_2021/Day01_SonarSweep_Rust/src/main.rs", "rank": 75, "score": 76656.47444287474 }, { "content": "fn part_two(top_level_packet: &Packet) -> u128 {\n\n top_level_packet.evaluate()\n\n}\n\n\n\n#[cfg(test)]\n\nmod tests {\n\n use super::*;\n\n\n\n #[test]\n\n fn operator_operator_operator_literal() {\n\n let packet = \"8A004A801A8002F478\";\n\n let input = parse_buffer(packet);\n\n assert_eq!(part_one(&input), 16);\n\n }\n\n\n\n #[test]\n\n fn operator_2operator_4literal_example_one() {\n\n let packet = \"620080001611562C8802118E34\";\n\n let input = parse_buffer(packet);\n\n assert_eq!(part_one(&input), 12);\n", "file_path": "AoC_2021/Day16_PacketDecoder_Rust/src/main.rs", "rank": 76, "score": 76591.3837739963 }, { "content": "#[derive(Clone, Copy)]\n\nstruct LineSegment {\n\n start_point: (i32, i32),\n\n end_point: (i32, i32),\n\n}\n\n\n\nimpl LineSegment {\n\n fn new(line: &str) -> LineSegment {\n\n lazy_static! {\n\n static ref RE: Regex =\n\n Regex::new(r\"(?P<x1>\\d+),(?P<y1>\\d+) -> (?P<x2>\\d+),(?P<y2>\\d+)\")\n\n .expect(\"failed to parse regex\");\n\n }\n\n let captures = RE.captures(line).expect(\"line didn't match\");\n\n let x1 = LineSegment::match_to_i32(captures.name(\"x1\"));\n\n let y1 = LineSegment::match_to_i32(captures.name(\"y1\"));\n\n let x2 = LineSegment::match_to_i32(captures.name(\"x2\"));\n\n let y2 = LineSegment::match_to_i32(captures.name(\"y2\"));\n\n LineSegment {\n\n start_point: (x1, y1),\n\n end_point: (x2, y2),\n", "file_path": "AoC_2021/Day05_HydrothermalVenture_Rust/src/main.rs", "rank": 77, "score": 71467.65283155652 }, { "content": "fn play_until_last_winner(\n\n guesses: &[i32],\n\n bingo_cards: &mut [BingoCard],\n\n) -> Option<(i32, BingoCard)> {\n\n let required_winners = bingo_cards.len();\n\n let mut current_winners = 0;\n\n for guess in guesses.iter() {\n\n for bingo_card in bingo_cards.iter_mut() {\n\n if bingo_card.is_winning {\n\n continue;\n\n }\n\n bingo_card.play_guess(guess);\n\n if bingo_card.is_winning {\n\n current_winners += 1;\n\n if current_winners == required_winners {\n\n return Some((*guess, bingo_card.clone()));\n\n }\n\n }\n\n }\n\n }\n\n None\n\n}\n\n\n", "file_path": "AoC_2021/Day04_GiantSquid_Rust/src/main.rs", "rank": 78, "score": 58727.47967744272 }, { "content": "fn play_until_first_winner(\n\n guesses: &[i32],\n\n bingo_cards: &mut [BingoCard],\n\n) -> Option<(i32, BingoCard)> {\n\n for guess in guesses.iter() {\n\n for bingo_card in bingo_cards.iter_mut() {\n\n bingo_card.play_guess(guess);\n\n if bingo_card.is_winning {\n\n return Some((*guess, bingo_card.clone()));\n\n }\n\n }\n\n }\n\n None\n\n}\n\n\n", "file_path": "AoC_2021/Day04_GiantSquid_Rust/src/main.rs", "rank": 79, "score": 58727.47967744272 }, { "content": "fn part_two(commands: &Vec<Command>) {\n\n let mut submarine_state = SubmarineState {\n\n location: Location {\n\n horizontal: 0,\n\n depth: 0,\n\n },\n\n aim: 0,\n\n };\n\n submarine_state = commands\n\n .iter()\n\n .fold(submarine_state, |s, c| s.execute_command(c));\n\n println!(\"Part 2: {}\", submarine_state.location.multiply());\n\n}\n\n\n", "file_path": "AoC_2021/Day02_Dive_Rust/src/main.rs", "rank": 80, "score": 54177.78613052907 }, { "content": "fn fishes_for_days(initial_timers: &Vec<i64>, days: i64) -> i64 {\n\n let mut swarm = Lanternfishes {\n\n memo: HashMap::new(),\n\n };\n\n let amount_fishes = initial_timers\n\n .iter()\n\n .fold(0, |acc, t| acc + swarm.how_many_fish(*t, days));\n\n amount_fishes\n\n}\n\n\n", "file_path": "AoC_2021/Day06_Lanternfish_Rust/src/main.rs", "rank": 81, "score": 48538.58371815644 }, { "content": " EnhanceableGrid {\n\n enhanced_mapping,\n\n content,\n\n amount_enhanced: 0,\n\n is_swapping,\n\n }\n\n }\n\n}\n\n\n\nimpl EnhanceableGrid {\n\n fn rows(&self) -> i32 {\n\n self.content.len() as i32\n\n }\n\n fn cols(&self) -> i32 {\n\n self.content.get(0).map_or(0, |v| v.len()) as i32\n\n }\n\n fn is_inside(&self, row: i32, col: i32) -> bool {\n\n 0 <= row && row < self.rows() && 0 <= col && col < self.cols()\n\n }\n\n fn get_at(&self, row: i32, col: i32) -> char {\n", "file_path": "AoC_2021/Day20_TrenchMap_Rust/src/main.rs", "rank": 82, "score": 45424.74406525312 }, { "content": "use anyhow;\n\nuse std::io::{self, Read};\n\n\n", "file_path": "AoC_2021/Day20_TrenchMap_Rust/src/main.rs", "rank": 83, "score": 45420.650227493556 }, { "content": " index += value;\n\n }\n\n value *= 2;\n\n }\n\n self.enhanced_mapping[index]\n\n }\n\n\n\n fn enhance(&mut self) {\n\n let new_rows = self.rows() as usize + 2;\n\n let new_cols = self.cols() as usize + 2;\n\n let mut new_content: Vec<Vec<char>> = vec![vec!['.'; new_cols]; new_rows];\n\n let delta = vec![\n\n (-1, -1),\n\n (-1, 0),\n\n (-1, 1),\n\n (0, -1),\n\n (0, 0),\n\n (0, 1),\n\n (1, -1),\n\n (1, 0),\n", "file_path": "AoC_2021/Day20_TrenchMap_Rust/src/main.rs", "rank": 84, "score": 45420.09453791675 }, { "content": " if !self.is_inside(row, col) {\n\n if self.is_swapping {\n\n if self.amount_enhanced % 2 == 0 {\n\n '.'\n\n } else {\n\n '#'\n\n }\n\n } else {\n\n '.'\n\n }\n\n } else {\n\n self.content[row as usize][col as usize]\n\n }\n\n }\n\n\n\n fn kernel_replacement(&self, kernel: &Vec<char>) -> char {\n\n let mut index = 0;\n\n let mut value = 1;\n\n for elem in kernel.iter().rev() {\n\n if *elem == '#' {\n", "file_path": "AoC_2021/Day20_TrenchMap_Rust/src/main.rs", "rank": 85, "score": 45419.54193147662 }, { "content": " (1, 1),\n\n ];\n\n for row in 0..new_rows as i32 {\n\n for col in 0..new_cols as i32 {\n\n let mut kernel = Vec::new();\n\n for (drow, dcol) in delta.iter() {\n\n kernel.push(self.get_at(row - 1 + drow, col - 1 + dcol));\n\n }\n\n new_content[row as usize][col as usize] = self.kernel_replacement(&kernel);\n\n }\n\n }\n\n self.content = new_content;\n\n self.amount_enhanced += 1;\n\n }\n\n\n\n fn count_hashes(&self) -> i64 {\n\n let mut amount = 0;\n\n for row in 0..self.rows() {\n\n for col in 0..self.cols() {\n\n if self.content[row as usize][col as usize] == '#' {\n", "file_path": "AoC_2021/Day20_TrenchMap_Rust/src/main.rs", "rank": 86, "score": 45418.30423859685 }, { "content": " amount += 1;\n\n }\n\n }\n\n }\n\n amount\n\n }\n\n\n\n fn print_content(&self) {\n\n for row in 0..self.rows() {\n\n println!(\n\n \"{:?}\",\n\n self.content[row as usize].iter().collect::<String>()\n\n );\n\n }\n\n println!();\n\n }\n\n}\n\n\n", "file_path": "AoC_2021/Day20_TrenchMap_Rust/src/main.rs", "rank": 87, "score": 45417.00669467764 }, { "content": " type_id,\n\n literal: 0,\n\n packets,\n\n },\n\n )\n\n }\n\n }\n\n\n\n fn read(&mut self, amount: usize, total: &mut usize) -> &str {\n\n let (read, rest) = self.buffer.split_at(amount);\n\n self.buffer = rest;\n\n *total += amount;\n\n read\n\n }\n\n}\n\n\n", "file_path": "AoC_2021/Day16_PacketDecoder_Rust/src/main.rs", "rank": 88, "score": 45191.46428280657 }, { "content": " let length = usize::from_str_radix(self.read(15, &mut total_read), 2).unwrap();\n\n let mut sub_read = 0;\n\n while sub_read < length {\n\n let (sub_read_inc, packet) = self.read_packet();\n\n sub_read += sub_read_inc;\n\n packets.push(packet);\n\n }\n\n total_read += sub_read\n\n } else {\n\n let num_packets = usize::from_str_radix(self.read(11, &mut total_read), 2).unwrap();\n\n for _ in 0..num_packets {\n\n let (read_inc, packet) = self.read_packet();\n\n total_read += read_inc;\n\n packets.push(packet);\n\n }\n\n }\n\n (\n\n total_read,\n\n Packet {\n\n version,\n", "file_path": "AoC_2021/Day16_PacketDecoder_Rust/src/main.rs", "rank": 89, "score": 45190.37765989786 }, { "content": "use std::collections::VecDeque;\n\nuse std::io::{self, Read};\n\n\n", "file_path": "AoC_2021/Day16_PacketDecoder_Rust/src/main.rs", "rank": 90, "score": 45189.60226690033 }, { "content": " }\n\n\n\n #[test]\n\n fn operator_2operator_4literal_example_two() {\n\n let packet = \"C0015000016115A2E0802F182340\";\n\n let input = parse_buffer(packet);\n\n assert_eq!(part_one(&input), 23);\n\n }\n\n\n\n #[test]\n\n fn operator_operator_operator_5literal() {\n\n let packet = \"A0016C880162017C3686B18A3D4780\";\n\n let input = parse_buffer(packet);\n\n assert_eq!(part_one(&input), 31);\n\n }\n\n\n\n #[test]\n\n fn evaluate_sum() {\n\n let packet = \"C200B40A82\";\n\n let input = parse_buffer(packet);\n", "file_path": "AoC_2021/Day16_PacketDecoder_Rust/src/main.rs", "rank": 91, "score": 45189.55765458807 }, { "content": " let (leading, content) = part.split_at(1);\n\n binary_literal.push_str(content);\n\n if leading == \"0\" {\n\n break;\n\n }\n\n }\n\n let literal = u128::from_str_radix(&binary_literal, 2).unwrap();\n\n (\n\n total_read,\n\n Packet {\n\n version,\n\n type_id,\n\n literal,\n\n packets: Vec::new(),\n\n },\n\n )\n\n } else {\n\n let mut packets = Vec::new();\n\n let length_type_id = self.read(1, &mut total_read);\n\n if length_type_id == \"0\" {\n", "file_path": "AoC_2021/Day16_PacketDecoder_Rust/src/main.rs", "rank": 92, "score": 45189.25349061014 }, { "content": "\n\n fn sum(&self) -> u128 {\n\n self.packets.iter().map(|p| p.evaluate()).sum()\n\n }\n\n\n\n fn product(&self) -> u128 {\n\n self.packets.iter().map(|p| p.evaluate()).product()\n\n }\n\n\n\n fn minimum(&self) -> u128 {\n\n self.packets.iter().map(|p| p.evaluate()).min().unwrap()\n\n }\n\n\n\n fn maximum(&self) -> u128 {\n\n self.packets.iter().map(|p| p.evaluate()).max().unwrap()\n\n }\n\n\n\n fn literal(&self) -> u128 {\n\n self.literal\n\n }\n", "file_path": "AoC_2021/Day16_PacketDecoder_Rust/src/main.rs", "rank": 93, "score": 45189.062895148694 }, { "content": " let packet = \"9C005AC2F8F0\";\n\n let input = parse_buffer(packet);\n\n assert_eq!(part_two(&input), 0);\n\n }\n\n\n\n #[test]\n\n fn evaluate_sum_equal_product() {\n\n let packet = \"9C0141080250320F1802104A08\";\n\n let input = parse_buffer(packet);\n\n assert_eq!(part_two(&input), 1);\n\n }\n\n}\n", "file_path": "AoC_2021/Day16_PacketDecoder_Rust/src/main.rs", "rank": 94, "score": 45188.556066707926 }, { "content": " let input = parse_buffer(packet);\n\n assert_eq!(part_two(&input), 9);\n\n }\n\n\n\n #[test]\n\n fn evaluate_less_than() {\n\n let packet = \"D8005AC2A8F0\";\n\n let input = parse_buffer(packet);\n\n assert_eq!(part_two(&input), 1);\n\n }\n\n\n\n #[test]\n\n fn evaluate_greater_than() {\n\n let packet = \"F600BC2D8F\";\n\n let input = parse_buffer(packet);\n\n assert_eq!(part_two(&input), 0);\n\n }\n\n\n\n #[test]\n\n fn evaluate_equal() {\n", "file_path": "AoC_2021/Day16_PacketDecoder_Rust/src/main.rs", "rank": 95, "score": 45187.212247054005 }, { "content": " assert_eq!(part_two(&input), 3);\n\n }\n\n\n\n #[test]\n\n fn evaluate_product() {\n\n let packet = \"04005AC33890\";\n\n let input = parse_buffer(packet);\n\n assert_eq!(part_two(&input), 54);\n\n }\n\n\n\n #[test]\n\n fn evaluate_minimum() {\n\n let packet = \"880086C3E88112\";\n\n let input = parse_buffer(packet);\n\n assert_eq!(part_two(&input), 7);\n\n }\n\n\n\n #[test]\n\n fn evaluate_maximum() {\n\n let packet = \"CE00C43D881120\";\n", "file_path": "AoC_2021/Day16_PacketDecoder_Rust/src/main.rs", "rank": 96, "score": 45186.74353133187 }, { "content": "\n\n fn equal_to(&self) -> u128 {\n\n let a = self.packets[0].evaluate();\n\n let b = self.packets[1].evaluate();\n\n if a == b {\n\n 1\n\n } else {\n\n 0\n\n }\n\n }\n\n}\n\n\n", "file_path": "AoC_2021/Day16_PacketDecoder_Rust/src/main.rs", "rank": 97, "score": 45181.7817257706 }, { "content": "\n\n fn greater_than(&self) -> u128 {\n\n let a = self.packets[0].evaluate();\n\n let b = self.packets[1].evaluate();\n\n if a > b {\n\n 1\n\n } else {\n\n 0\n\n }\n\n }\n\n\n\n fn less_than(&self) -> u128 {\n\n let a = self.packets[0].evaluate();\n\n let b = self.packets[1].evaluate();\n\n if a < b {\n\n 1\n\n } else {\n\n 0\n\n }\n\n }\n", "file_path": "AoC_2021/Day16_PacketDecoder_Rust/src/main.rs", "rank": 98, "score": 45181.7817257706 } ]
Rust
src/api/boblight.rs
vtavernier/hyperion.rs
18cf772ffb649edff4445361741659760e084393
use std::sync::Arc; use thiserror::Error; use crate::{ global::{InputMessage, InputMessageData, InputSourceHandle, Message, PriorityGuard}, instance::{InstanceHandle, InstanceHandleError}, models::Color, }; pub mod message; use message::{BoblightRequest, BoblightResponse}; #[derive(Debug, Error)] pub enum BoblightApiError { #[error("error broadcasting update: {0}")] Broadcast(#[from] tokio::sync::mpsc::error::SendError<InputMessage>), #[error("missing command data in protobuf frame")] MissingCommand, #[error("invalid instance")] InvalidInstance(#[from] InstanceHandleError), } pub struct ClientConnection { handle: InputSourceHandle<InputMessage>, priority_guard: PriorityGuard, led_colors: Vec<Color>, priority: i32, instance: InstanceHandle, } impl ClientConnection { pub fn new( handle: InputSourceHandle<InputMessage>, led_count: usize, instance: InstanceHandle, ) -> Self { let priority_guard = PriorityGuard::new_mpsc(instance.input_channel().clone(), &handle); Self { handle, priority_guard, led_colors: vec![Color::default(); led_count], priority: 128, instance, } } async fn set_priority(&mut self, priority: i32) { let new_priority = if priority < 128 || priority >= 254 { self.instance .current_priorities() .await .map(|priorities| { let mut used_priorities = priorities .iter() .map(|p| p.priority) .skip_while(|p| *p <= 128) .peekable(); for i in 128..255 { loop { match used_priorities.peek().cloned() { Some(used) if used == i => { used_priorities.next(); break; } Some(used) if used < i => { used_priorities.next(); continue; } _ => { return i; } } } } 128 }) .unwrap_or(128) } else { priority }; self.priority = new_priority; self.priority_guard.set_priority(Some(new_priority)); } async fn sync(&self) -> Result<(), BoblightApiError> { Ok(self .instance .send(InputMessage::new( self.handle.id(), crate::component::ComponentName::BoblightServer, InputMessageData::LedColors { priority: self.priority, duration: None, led_colors: Arc::new(self.led_colors.clone()), }, )) .await?) } #[instrument(skip(request))] pub async fn handle_request( &mut self, request: BoblightRequest, ) -> Result<Option<BoblightResponse>, BoblightApiError> { match request { BoblightRequest::Hello => Ok(Some(BoblightResponse::Hello)), BoblightRequest::Ping => Ok(Some(BoblightResponse::Ping)), BoblightRequest::Get(get) => match get { message::GetArg::Version => Ok(Some(BoblightResponse::Version)), message::GetArg::Lights => Ok(Some(BoblightResponse::Lights { leds: self.instance.config().await?.leds.leds.clone(), })), }, BoblightRequest::Set(set) => { match set { message::SetArg::Light(message::LightParam { index, data }) => match data { message::LightParamData::Color(color) => { if let Some(color_mut) = self.led_colors.get_mut(index) { *color_mut = color; if index == self.led_colors.len() - 1 { self.sync().await?; } } } _ => {} }, message::SetArg::Priority(priority) => { self.set_priority(priority).await; } } Ok(None) } BoblightRequest::Sync => { self.sync().await?; Ok(None) } } } } impl std::fmt::Debug for ClientConnection { fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { f.debug_struct("ClientConnection") .field("instance", &self.instance.id()) .field("source", &format!("{}", &*self.handle)) .finish() } }
use std::sync::Arc; use thiserror::Error; use crate::{ global::{InputMessage, InputMessageData, InputSourceHandle, Message, PriorityGuard}, instance::{InstanceHandle, InstanceHandleError}, models::Color, }; pub mod message; use message::{BoblightRequest, BoblightResponse}; #[derive(Debug, Error)] pub enum BoblightApiError { #[error("error broadcasting update: {0}")] Broadcast(#[from] tokio::sync::mpsc::error::SendError<InputMessage>), #[error("missing command data in protobuf frame")] MissingCommand, #[error("invalid instance")] InvalidInstance(#[from] InstanceHandleError), } pub struct ClientConnection { handle: InputSourceHandle<InputMessage>, priority_guard: PriorityGuard, led_colors: Vec<Color>, priority: i32, instance: InstanceHandle, } impl ClientConnection { pub fn new( handle: InputSourceHandle<InputMessage>, led_count: usize, instance: InstanceHandle, ) -> Self { let priority_guard = PriorityGuard::new_mpsc(instance.input_channel().clone(), &handle); Self {
async fn set_priority(&mut self, priority: i32) { let new_priority = if priority < 128 || priority >= 254 { self.instance .current_priorities() .await .map(|priorities| { let mut used_priorities = priorities .iter() .map(|p| p.priority) .skip_while(|p| *p <= 128) .peekable(); for i in 128..255 { loop { match used_priorities.peek().cloned() { Some(used) if used == i => { used_priorities.next(); break; } Some(used) if used < i => { used_priorities.next(); continue; } _ => { return i; } } } } 128 }) .unwrap_or(128) } else { priority }; self.priority = new_priority; self.priority_guard.set_priority(Some(new_priority)); } async fn sync(&self) -> Result<(), BoblightApiError> { Ok(self .instance .send(InputMessage::new( self.handle.id(), crate::component::ComponentName::BoblightServer, InputMessageData::LedColors { priority: self.priority, duration: None, led_colors: Arc::new(self.led_colors.clone()), }, )) .await?) } #[instrument(skip(request))] pub async fn handle_request( &mut self, request: BoblightRequest, ) -> Result<Option<BoblightResponse>, BoblightApiError> { match request { BoblightRequest::Hello => Ok(Some(BoblightResponse::Hello)), BoblightRequest::Ping => Ok(Some(BoblightResponse::Ping)), BoblightRequest::Get(get) => match get { message::GetArg::Version => Ok(Some(BoblightResponse::Version)), message::GetArg::Lights => Ok(Some(BoblightResponse::Lights { leds: self.instance.config().await?.leds.leds.clone(), })), }, BoblightRequest::Set(set) => { match set { message::SetArg::Light(message::LightParam { index, data }) => match data { message::LightParamData::Color(color) => { if let Some(color_mut) = self.led_colors.get_mut(index) { *color_mut = color; if index == self.led_colors.len() - 1 { self.sync().await?; } } } _ => {} }, message::SetArg::Priority(priority) => { self.set_priority(priority).await; } } Ok(None) } BoblightRequest::Sync => { self.sync().await?; Ok(None) } } } } impl std::fmt::Debug for ClientConnection { fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { f.debug_struct("ClientConnection") .field("instance", &self.instance.id()) .field("source", &format!("{}", &*self.handle)) .finish() } }
handle, priority_guard, led_colors: vec![Color::default(); led_count], priority: 128, instance, } }
function_block-function_prefixed
[ { "content": "fn error_response(peer_addr: SocketAddr, error: impl std::fmt::Display) -> message::HyperionReply {\n\n let mut reply = message::HyperionReply::default();\n\n reply.r#type = message::hyperion_reply::Type::Reply.into();\n\n reply.success = Some(false);\n\n reply.error = Some(error.to_string());\n\n\n\n trace!(\"({}) sending error: {:?}\", peer_addr, reply);\n\n reply\n\n}\n\n\n\npub async fn handle_client(\n\n (socket, peer_addr): (TcpStream, SocketAddr),\n\n global: Global,\n\n) -> Result<(), ProtoServerError> {\n\n debug!(\"accepted new connection from {}\", peer_addr);\n\n\n\n let (mut writer, mut reader) = Framed::new(socket, ProtoCodec::new()).split();\n\n\n\n // unwrap: cannot fail because the priority is None\n\n let source = global\n", "file_path": "src/servers/proto.rs", "rank": 0, "score": 165669.9898177544 }, { "content": "#[instrument(skip(request, source, priority_guard))]\n\npub fn handle_request(\n\n peer_addr: SocketAddr,\n\n request: HyperionRequest,\n\n source: &InputSourceHandle<InputMessage>,\n\n priority_guard: &mut PriorityGuard,\n\n) -> Result<(), ProtoApiError> {\n\n match request.command() {\n\n message::hyperion_request::Command::Clearall => {\n\n // Update state\n\n source.send(ComponentName::ProtoServer, InputMessageData::ClearAll)?;\n\n }\n\n\n\n message::hyperion_request::Command::Clear => {\n\n let clear_request = request\n\n .clear_request\n\n .ok_or_else(|| ProtoApiError::MissingCommand)?;\n\n\n\n // Update state\n\n source.send(\n\n ComponentName::ProtoServer,\n", "file_path": "src/api/proto.rs", "rank": 1, "score": 159070.16649951183 }, { "content": "pub fn i32_to_duration(d: Option<i32>) -> Option<chrono::Duration> {\n\n if let Some(d) = d {\n\n if d <= 0 {\n\n None\n\n } else {\n\n Some(chrono::Duration::milliseconds(d as _))\n\n }\n\n } else {\n\n None\n\n }\n\n}\n", "file_path": "src/api/types.rs", "rank": 2, "score": 156004.65076669466 }, { "content": "#[derive(Debug)]\n\nenum InstanceMessage {\n\n PriorityInfo(oneshot::Sender<Vec<PriorityInfo>>),\n\n Config(oneshot::Sender<Arc<InstanceConfig>>),\n\n Stop(oneshot::Sender<()>),\n\n}\n\n\n\n#[derive(Clone)]\n\npub struct InstanceHandle {\n\n id: i32,\n\n tx: mpsc::Sender<InstanceMessage>,\n\n local_tx: mpsc::Sender<InputMessage>,\n\n}\n\n\n\n#[derive(Debug, Error)]\n\npub enum InstanceHandleError {\n\n #[error(\"the corresponding instance is no longer running\")]\n\n Dropped,\n\n}\n\n\n\nimpl<T> From<tokio::sync::mpsc::error::SendError<T>> for InstanceHandleError {\n", "file_path": "src/instance.rs", "rank": 3, "score": 154212.4952397655 }, { "content": "enum ImplState {\n\n Pending(models::Ws2812Spi),\n\n Ready(Spidev),\n\n}\n\n\n\nimpl ImplState {\n\n fn as_dev(&self) -> Option<&Spidev> {\n\n match self {\n\n ImplState::Ready(dev) => Some(dev),\n\n _ => None,\n\n }\n\n }\n\n\n\n fn try_init(&mut self) -> Result<&Spidev, DeviceError> {\n\n match self {\n\n ImplState::Pending(config) => {\n\n // Initialize SPI device\n\n let mut dev = Spidev::open(&config.output)?;\n\n let options = SpidevOptions::new()\n\n .bits_per_word(8)\n", "file_path": "src/instance/device/ws2812spi.rs", "rank": 4, "score": 139181.51723470198 }, { "content": "/// Verifies, with the given options, that a buffer of bytes\n\n/// contains a `Reply` and returns it.\n\n/// Note that verification is still experimental and may not\n\n/// catch every error, or be maximally performant. For the\n\n/// previous, unchecked, behavior use\n\n/// `root_as_reply_unchecked`.\n\npub fn root_as_reply_with_opts<'b, 'o>(\n\n opts: &'o flatbuffers::VerifierOptions,\n\n buf: &'b [u8],\n\n) -> Result<Reply<'b>, flatbuffers::InvalidFlatbuffer> {\n\n flatbuffers::root_with_opts::<Reply<'b>>(opts, buf)\n\n}\n\n#[inline]\n", "file_path": "src/api/flat/message/hyperion_reply_generated.rs", "rank": 5, "score": 135555.4537759084 }, { "content": "/// Verifies, with the given options, that a buffer of bytes\n\n/// contains a `Request` and returns it.\n\n/// Note that verification is still experimental and may not\n\n/// catch every error, or be maximally performant. For the\n\n/// previous, unchecked, behavior use\n\n/// `root_as_request_unchecked`.\n\npub fn root_as_request_with_opts<'b, 'o>(\n\n opts: &'o flatbuffers::VerifierOptions,\n\n buf: &'b [u8],\n\n) -> Result<Request<'b>, flatbuffers::InvalidFlatbuffer> {\n\n flatbuffers::root_with_opts::<Request<'b>>(opts, buf)\n\n}\n\n#[inline]\n", "file_path": "src/api/flat/message/hyperion_request_generated.rs", "rank": 6, "score": 135555.4537759084 }, { "content": "#[inline]\n\npub fn finish_reply_buffer<'a, 'b>(\n\n fbb: &'b mut flatbuffers::FlatBufferBuilder<'a>,\n\n root: flatbuffers::WIPOffset<Reply<'a>>) {\n\n fbb.finish(root, None);\n\n}\n\n\n", "file_path": "src/api/flat/message/hyperion_reply_generated.rs", "rank": 7, "score": 135548.07855787734 }, { "content": "#[inline]\n\npub fn finish_request_buffer<'a, 'b>(\n\n fbb: &'b mut flatbuffers::FlatBufferBuilder<'a>,\n\n root: flatbuffers::WIPOffset<Request<'a>>) {\n\n fbb.finish(root, None);\n\n}\n\n\n", "file_path": "src/api/flat/message/hyperion_request_generated.rs", "rank": 8, "score": 135548.07855787734 }, { "content": "/// Verifies, with the given verifier options, that a buffer of\n\n/// bytes contains a size prefixed `Reply` and returns\n\n/// it. Note that verification is still experimental and may not\n\n/// catch every error, or be maximally performant. For the\n\n/// previous, unchecked, behavior use\n\n/// `root_as_reply_unchecked`.\n\npub fn size_prefixed_root_as_reply_with_opts<'b, 'o>(\n\n opts: &'o flatbuffers::VerifierOptions,\n\n buf: &'b [u8],\n\n) -> Result<Reply<'b>, flatbuffers::InvalidFlatbuffer> {\n\n flatbuffers::size_prefixed_root_with_opts::<Reply<'b>>(opts, buf)\n\n}\n\n#[inline]\n\n/// Assumes, without verification, that a buffer of bytes contains a Reply and returns it.\n\n/// # Safety\n\n/// Callers must trust the given bytes do indeed contain a valid `Reply`.\n\npub unsafe fn root_as_reply_unchecked(buf: &[u8]) -> Reply {\n\n flatbuffers::root_unchecked::<Reply>(buf)\n\n}\n\n#[inline]\n\n/// Assumes, without verification, that a buffer of bytes contains a size prefixed Reply and returns it.\n\n/// # Safety\n\n/// Callers must trust the given bytes do indeed contain a valid size prefixed `Reply`.\n\npub unsafe fn size_prefixed_root_as_reply_unchecked(buf: &[u8]) -> Reply {\n\n flatbuffers::size_prefixed_root_unchecked::<Reply>(buf)\n\n}\n", "file_path": "src/api/flat/message/hyperion_reply_generated.rs", "rank": 9, "score": 130681.13212091202 }, { "content": "/// Verifies, with the given verifier options, that a buffer of\n\n/// bytes contains a size prefixed `Request` and returns\n\n/// it. Note that verification is still experimental and may not\n\n/// catch every error, or be maximally performant. For the\n\n/// previous, unchecked, behavior use\n\n/// `root_as_request_unchecked`.\n\npub fn size_prefixed_root_as_request_with_opts<'b, 'o>(\n\n opts: &'o flatbuffers::VerifierOptions,\n\n buf: &'b [u8],\n\n) -> Result<Request<'b>, flatbuffers::InvalidFlatbuffer> {\n\n flatbuffers::size_prefixed_root_with_opts::<Request<'b>>(opts, buf)\n\n}\n\n#[inline]\n\n/// Assumes, without verification, that a buffer of bytes contains a Request and returns it.\n\n/// # Safety\n\n/// Callers must trust the given bytes do indeed contain a valid `Request`.\n\npub unsafe fn root_as_request_unchecked(buf: &[u8]) -> Request {\n\n flatbuffers::root_unchecked::<Request>(buf)\n\n}\n\n#[inline]\n\n/// Assumes, without verification, that a buffer of bytes contains a size prefixed Request and returns it.\n\n/// # Safety\n\n/// Callers must trust the given bytes do indeed contain a valid size prefixed `Request`.\n\npub unsafe fn size_prefixed_root_as_request_unchecked(buf: &[u8]) -> Request {\n\n flatbuffers::size_prefixed_root_unchecked::<Request>(buf)\n\n}\n", "file_path": "src/api/flat/message/hyperion_request_generated.rs", "rank": 10, "score": 130681.13212091202 }, { "content": "pub fn run(\n\n full_path: &Path,\n\n args: serde_json::Value,\n\n methods: impl RuntimeMethods + 'static,\n\n) -> Result<(), PyErr> {\n\n do_run(methods, args, |py| {\n\n // Run script\n\n py.run(std::fs::read_to_string(&full_path)?.as_str(), None, None)?;\n\n\n\n Ok(())\n\n })\n\n}\n\n\n\n#[cfg(test)]\n\nmod tests;\n", "file_path": "src/effects/runtime.rs", "rank": 11, "score": 124438.57716491917 }, { "content": "/// Decode a base64-encoded value\n\n///\n\n/// # Parameters\n\n///\n\n/// `deserializer`: Serde deserializer\n\npub fn from_base64<'de, D>(deserializer: D) -> std::result::Result<Vec<u8>, D::Error>\n\nwhere\n\n D: serde::Deserializer<'de>,\n\n{\n\n deserializer.deserialize_str(Base64Visitor {})\n\n}\n", "file_path": "src/serde/base64.rs", "rank": 12, "score": 122681.30117066007 }, { "content": "fn default_ws_spi_rate() -> i32 {\n\n 3000000\n\n}\n\n\n", "file_path": "src/models/devices.rs", "rank": 13, "score": 120053.29773553113 }, { "content": "#[inline]\n\n#[deprecated(since=\"2.0.0\", note=\"Deprecated in favor of `root_as...` methods.\")]\n\npub fn get_root_as_reply<'a>(buf: &'a [u8]) -> Reply<'a> {\n\n unsafe { flatbuffers::root_unchecked::<Reply<'a>>(buf) }\n\n}\n\n\n", "file_path": "src/api/flat/message/hyperion_reply_generated.rs", "rank": 14, "score": 118936.57235515324 }, { "content": "#[inline]\n\n#[deprecated(since=\"2.0.0\", note=\"Deprecated in favor of `root_as...` methods.\")]\n\npub fn get_root_as_request<'a>(buf: &'a [u8]) -> Request<'a> {\n\n unsafe { flatbuffers::root_unchecked::<Request<'a>>(buf) }\n\n}\n\n\n", "file_path": "src/api/flat/message/hyperion_request_generated.rs", "rank": 15, "score": 118936.57235515324 }, { "content": "fn register_response(builder: &mut flatbuffers::FlatBufferBuilder, priority: i32) -> bytes::Bytes {\n\n let mut reply = message::ReplyBuilder::new(builder);\n\n reply.add_registered(priority);\n\n\n\n let reply = reply.finish();\n\n\n\n builder.finish(reply, None);\n\n bytes::Bytes::copy_from_slice(builder.finished_data())\n\n}\n\n\n", "file_path": "src/servers/flat.rs", "rank": 16, "score": 117674.13954791959 }, { "content": "#[derive(Debug, Clone, Copy, PartialEq)]\n\nenum InstanceControl {\n\n Continue,\n\n Break,\n\n}\n\n\n", "file_path": "src/instance.rs", "rank": 17, "score": 116201.30231625204 }, { "content": "/// Get the sRGB whitepoint\n\npub fn srgb_white() -> Color16 {\n\n Color16::new(u16::MAX, u16::MAX, u16::MAX)\n\n}\n\n\n", "file_path": "src/color/utils.rs", "rank": 18, "score": 115905.47259023486 }, { "content": "/// A wrapper for a device that may have failed initializing\n\nstruct InstanceDevice {\n\n inner: Result<Device, DeviceError>,\n\n}\n\n\n\nimpl InstanceDevice {\n\n async fn update(&mut self) -> Result<(), DeviceError> {\n\n if let Ok(device) = &mut self.inner {\n\n device.update().await\n\n } else {\n\n futures::future::pending::<()>().await;\n\n Ok(())\n\n }\n\n }\n\n\n\n async fn set_led_data(&mut self, led_data: &[Color]) -> Result<(), DeviceError> {\n\n if let Ok(device) = &mut self.inner {\n\n device.set_led_data(led_data).await\n\n } else {\n\n Ok(())\n\n }\n\n }\n\n}\n\n\n\nimpl From<Result<Device, DeviceError>> for InstanceDevice {\n\n fn from(inner: Result<Device, DeviceError>) -> Self {\n\n Self { inner }\n\n }\n\n}\n\n\n", "file_path": "src/instance.rs", "rank": 19, "score": 115468.55081491727 }, { "content": "#[inline]\n\n#[deprecated(since=\"2.0.0\", note=\"Deprecated in favor of `root_as...` methods.\")]\n\npub fn get_size_prefixed_root_as_reply<'a>(buf: &'a [u8]) -> Reply<'a> {\n\n unsafe { flatbuffers::size_prefixed_root_unchecked::<Reply<'a>>(buf) }\n\n}\n\n\n\n#[inline]\n", "file_path": "src/api/flat/message/hyperion_reply_generated.rs", "rank": 20, "score": 114758.03467696854 }, { "content": "#[inline]\n\n#[deprecated(since=\"2.0.0\", note=\"Deprecated in favor of `root_as...` methods.\")]\n\npub fn get_size_prefixed_root_as_request<'a>(buf: &'a [u8]) -> Request<'a> {\n\n unsafe { flatbuffers::size_prefixed_root_unchecked::<Request<'a>>(buf) }\n\n}\n\n\n\n#[inline]\n", "file_path": "src/api/flat/message/hyperion_request_generated.rs", "rank": 21, "score": 114758.03467696854 }, { "content": "/// Verifies that a buffer of bytes contains a `Request`\n\n/// and returns it.\n\n/// Note that verification is still experimental and may not\n\n/// catch every error, or be maximally performant. For the\n\n/// previous, unchecked, behavior use\n\n/// `root_as_request_unchecked`.\n\npub fn root_as_request(buf: &[u8]) -> Result<Request, flatbuffers::InvalidFlatbuffer> {\n\n flatbuffers::root::<Request>(buf)\n\n}\n\n#[inline]\n", "file_path": "src/api/flat/message/hyperion_request_generated.rs", "rank": 22, "score": 112823.70914096091 }, { "content": "/// Verifies that a buffer of bytes contains a `Reply`\n\n/// and returns it.\n\n/// Note that verification is still experimental and may not\n\n/// catch every error, or be maximally performant. For the\n\n/// previous, unchecked, behavior use\n\n/// `root_as_reply_unchecked`.\n\npub fn root_as_reply(buf: &[u8]) -> Result<Reply, flatbuffers::InvalidFlatbuffer> {\n\n flatbuffers::root::<Reply>(buf)\n\n}\n\n#[inline]\n", "file_path": "src/api/flat/message/hyperion_reply_generated.rs", "rank": 23, "score": 112823.70914096091 }, { "content": "pub fn criterion_benchmark(c: &mut Criterion) {\n\n let width = 1920 / 16;\n\n let height = 1080 / 16;\n\n let leds = classic_led_config(40);\n\n let mut colors = vec![Color16::default(); leds.leds.len()];\n\n\n\n c.bench_function(\n\n &format!(\"{} px {} leds\", width * height, leds.leds.len()),\n\n |b| {\n\n let mut reducer = Reducer::default();\n\n let image = random_image(width, height);\n\n\n\n b.iter(|| reducer.reduce(&image, &leds.leds, &mut colors))\n\n },\n\n );\n\n}\n\n\n\ncriterion_group!(benches, criterion_benchmark);\n\ncriterion_main!(benches);\n", "file_path": "benches/reducer.rs", "rank": 24, "score": 109732.70683445115 }, { "content": "/// Verifies that a buffer of bytes contains a size prefixed\n\n/// `Request` and returns it.\n\n/// Note that verification is still experimental and may not\n\n/// catch every error, or be maximally performant. For the\n\n/// previous, unchecked, behavior use\n\n/// `size_prefixed_root_as_request_unchecked`.\n\npub fn size_prefixed_root_as_request(buf: &[u8]) -> Result<Request, flatbuffers::InvalidFlatbuffer> {\n\n flatbuffers::size_prefixed_root::<Request>(buf)\n\n}\n\n#[inline]\n", "file_path": "src/api/flat/message/hyperion_request_generated.rs", "rank": 25, "score": 109201.56373294666 }, { "content": "/// Verifies that a buffer of bytes contains a size prefixed\n\n/// `Reply` and returns it.\n\n/// Note that verification is still experimental and may not\n\n/// catch every error, or be maximally performant. For the\n\n/// previous, unchecked, behavior use\n\n/// `size_prefixed_root_as_reply_unchecked`.\n\npub fn size_prefixed_root_as_reply(buf: &[u8]) -> Result<Reply, flatbuffers::InvalidFlatbuffer> {\n\n flatbuffers::size_prefixed_root::<Reply>(buf)\n\n}\n\n#[inline]\n", "file_path": "src/api/flat/message/hyperion_reply_generated.rs", "rank": 26, "score": 109201.56373294666 }, { "content": "/// Validate the bounds of a scan range\n\nfn validate_scan_range(led: &Led) -> Result<(), validator::ValidationError> {\n\n if led.hmin > led.hmax {\n\n return Err(validator::ValidationError::new(\"invalid_range\"));\n\n }\n\n\n\n if led.vmin > led.vmax {\n\n return Err(validator::ValidationError::new(\"invalid_range\"));\n\n }\n\n\n\n Ok(())\n\n}\n\n\n\n#[derive(Debug, Clone, PartialEq, Validate)]\n\npub struct Leds {\n\n #[validate]\n\n pub leds: Vec<Led>,\n\n}\n\n\n\nimpl Default for Leds {\n\n fn default() -> Self {\n", "file_path": "src/models/instance.rs", "rank": 27, "score": 109191.35744870323 }, { "content": "pub fn kelvin_to_rgb16(t: u32) -> Color16 {\n\n let (r, g, b) = kelvin_to_rgbf32(t as f32).into_components();\n\n Color16::new(\n\n (r * (u16::MAX as f32)) as u16,\n\n (g * (u16::MAX as f32)) as u16,\n\n (b * (u16::MAX as f32)) as u16,\n\n )\n\n}\n\n\n", "file_path": "src/color/utils.rs", "rank": 28, "score": 107617.05505060445 }, { "content": "#[derive(Debug, Clone, Copy, PartialEq, Eq)]\n\nenum ActiveState {\n\n Inactive,\n\n Active,\n\n Deactivating,\n\n}\n\n\n\nimpl Default for ActiveState {\n\n fn default() -> Self {\n\n Self::Inactive\n\n }\n\n}\n\n\n\npub struct Instance {\n\n config: Arc<InstanceConfig>,\n\n device: InstanceDevice,\n\n handle_rx: mpsc::Receiver<InstanceMessage>,\n\n receiver: broadcast::Receiver<InputMessage>,\n\n local_receiver: mpsc::Receiver<InputMessage>,\n\n event_tx: broadcast::Sender<Event>,\n\n muxer: PriorityMuxer,\n", "file_path": "src/instance.rs", "rank": 29, "score": 107091.51301015995 }, { "content": "pub fn color_to16(color: Color) -> Color16 {\n\n let (r, g, b) = color.into_components();\n\n Color16::new(\n\n (r as u16) * FACTOR,\n\n (g as u16) * FACTOR,\n\n (b as u16) * FACTOR,\n\n )\n\n}\n", "file_path": "src/color/utils.rs", "rank": 30, "score": 105624.01262977389 }, { "content": "pub fn color_to8(color: Color16) -> Color {\n\n let (r, g, b) = color.into_components();\n\n Color::new((r / FACTOR) as u8, (g / FACTOR) as u8, (b / FACTOR) as u8)\n\n}\n\n\n", "file_path": "src/color/utils.rs", "rank": 31, "score": 105624.01262977389 }, { "content": "#[derive(Debug, Clone, Copy)]\n\nstruct ColorAdjustmentData {\n\n black: RgbChannelAdjustment,\n\n white: RgbChannelAdjustment,\n\n red: RgbChannelAdjustment,\n\n green: RgbChannelAdjustment,\n\n blue: RgbChannelAdjustment,\n\n cyan: RgbChannelAdjustment,\n\n magenta: RgbChannelAdjustment,\n\n yellow: RgbChannelAdjustment,\n\n transform: RgbTransform,\n\n}\n\n\n\nimpl ColorAdjustmentData {\n\n pub fn apply(&self, color: Color) -> Color {\n\n let (ored, ogreen, oblue) = self.transform.apply(color).into_components();\n\n let brightness_components = self.transform.brightness_components();\n\n\n\n // Upgrade to u32\n\n let (ored, ogreen, oblue) = (ored as u32, ogreen as u32, oblue as u32);\n\n\n", "file_path": "src/color.rs", "rank": 32, "score": 105317.62051740347 }, { "content": "#[derive(Debug)]\n\nstruct InputEntry {\n\n input_id: usize,\n\n message: InputMessage,\n\n expires: Option<Instant>,\n\n effect_key: Option<RunningEffectKey>,\n\n}\n\n\n\npub struct PriorityMuxer {\n\n global: Global,\n\n inputs: BTreeMap<i32, InputEntry>,\n\n input_id: usize,\n\n timeouts: HashMap<\n\n usize,\n\n Box<dyn Fn() -> Pin<Box<dyn Future<Output = (usize, i32)> + Send + Sync>> + Send + Sync>,\n\n >,\n\n effect_runner: EffectRunner,\n\n}\n\n\n\npub const MAX_PRIORITY: i32 = 256;\n\nconst MUXER_ID: usize = 0;\n", "file_path": "src/instance/muxer.rs", "rank": 33, "score": 103824.45514585522 }, { "content": "enum SendingChannel {\n\n Mpsc(mpsc::Sender<InputMessage>),\n\n Broadcast(broadcast::Sender<InputMessage>),\n\n}\n\n\n\nimpl SendingChannel {\n\n pub async fn send(&self, message: InputMessage) {\n\n match self {\n\n SendingChannel::Mpsc(tx) => tx.send(message).await.ok(),\n\n SendingChannel::Broadcast(tx) => tx.send(message).ok().map(|_| ()),\n\n };\n\n }\n\n}\n\n\n\nimpl From<mpsc::Sender<InputMessage>> for SendingChannel {\n\n fn from(tx: mpsc::Sender<InputMessage>) -> Self {\n\n Self::Mpsc(tx)\n\n }\n\n}\n\n\n", "file_path": "src/global/priority_guard.rs", "rank": 34, "score": 103604.13366336588 }, { "content": "fn error_response(\n\n builder: &mut flatbuffers::FlatBufferBuilder,\n\n error: impl std::fmt::Display,\n\n) -> bytes::Bytes {\n\n let error = builder.create_string(error.to_string().as_str());\n\n\n\n let mut reply = message::ReplyBuilder::new(builder);\n\n reply.add_error(error);\n\n\n\n let reply = reply.finish();\n\n\n\n builder.finish(reply, None);\n\n bytes::Bytes::copy_from_slice(builder.finished_data())\n\n}\n\n\n\nasync fn handle_request(\n\n peer_addr: SocketAddr,\n\n request_bytes: bytes::BytesMut,\n\n source: &mut Option<InputSourceHandle<InputMessage>>,\n\n global: &Global,\n", "file_path": "src/servers/flat.rs", "rank": 35, "score": 101820.39437121016 }, { "content": "fn validate_priority(\n\n priority: i32,\n\n source: &InputSourceHandle<InputMessage>,\n\n priority_guard: &mut PriorityGuard,\n\n) -> Result<i32, ProtoApiError> {\n\n if priority < 100 || priority >= 200 {\n\n return Err(ProtoApiError::InvalidPriority(priority));\n\n }\n\n\n\n // Re-creating the priority guard drops the old value, thus clearing the previous priority\n\n *priority_guard = PriorityGuard::new_broadcast(source);\n\n\n\n Ok(priority)\n\n}\n\n\n", "file_path": "src/api/proto.rs", "rank": 36, "score": 101801.29066090859 }, { "content": "#[derive(Default)]\n\nstruct TestMethodData {\n\n abort: bool,\n\n leds: Vec<Color>,\n\n}\n\n\n", "file_path": "src/effects/runtime/tests.rs", "rank": 37, "score": 100624.87184916832 }, { "content": "pub fn serialize_color_as_array<S: serde::ser::Serializer>(\n\n color: &Color,\n\n s: S,\n\n) -> Result<S::Ok, S::Error> {\n\n let mut seq = s.serialize_seq(Some(3))?;\n\n seq.serialize_element(&color.red)?;\n\n seq.serialize_element(&color.green)?;\n\n seq.serialize_element(&color.blue)?;\n\n seq.end()\n\n}\n", "file_path": "src/serde/color.rs", "rank": 38, "score": 99473.2533217051 }, { "content": "struct InstanceConfigCreator {\n\n instance: Instance,\n\n background_effect: Option<BackgroundEffect>,\n\n black_border_detector: Option<BlackBorderDetector>,\n\n boblight_server: Option<BoblightServer>,\n\n color: Option<ColorAdjustment>,\n\n device: Option<Device>,\n\n effects: Option<Effects>,\n\n foreground_effect: Option<ForegroundEffect>,\n\n instance_capture: Option<InstanceCapture>,\n\n led_config: Option<LedConfig>,\n\n leds: Option<Leds>,\n\n smoothing: Option<Smoothing>,\n\n}\n\n\n\nimpl From<InstanceConfigCreator> for InstanceConfig {\n\n fn from(creator: InstanceConfigCreator) -> Self {\n\n Self {\n\n instance: creator.instance,\n\n background_effect: creator.background_effect.unwrap_or_default(),\n", "file_path": "src/models/backend/db.rs", "rank": 39, "score": 99223.56405835687 }, { "content": "pub trait Message: Sized {\n\n type Data;\n\n\n\n fn new(source_id: usize, component: ComponentName, data: Self::Data) -> Self;\n\n\n\n fn source_id(&self) -> usize;\n\n\n\n fn component(&self) -> ComponentName;\n\n\n\n fn data(&self) -> &Self::Data;\n\n\n\n fn unregister_source(global: &mut GlobalData, input_source: &InputSource<Self>);\n\n}\n\n\n\n#[derive(Clone)]\n\npub struct Global(Arc<RwLock<GlobalData>>);\n\n\n\n#[derive(Display, Debug)]\n\npub enum InputSourceName {\n\n #[display(\"Boblight({peer_addr})\")]\n", "file_path": "src/global.rs", "rank": 40, "score": 97820.01964899564 }, { "content": "fn hostname() -> String {\n\n hostname::get()\n\n .map(|s| s.to_string_lossy().to_string())\n\n .unwrap_or_else(|_| \"<unknown hostname>\".to_owned())\n\n}\n\n\n", "file_path": "src/api/json/message.rs", "rank": 41, "score": 95785.07682507561 }, { "content": "fn version() -> String {\n\n git_version::git_version!(prefix = \"hyperion.rs-\", args = [\"--always\", \"--tags\"]).to_owned()\n\n}\n", "file_path": "src/api/json/message.rs", "rank": 42, "score": 95785.07682507561 }, { "content": "pub fn run<X: std::fmt::Debug + Clone + Send + 'static>(\n\n effect: &EffectDefinition,\n\n args: serde_json::Value,\n\n led_count: usize,\n\n duration: Option<chrono::Duration>,\n\n priority: i32,\n\n tx: Sender<EffectMessage<X>>,\n\n extra: X,\n\n) -> Result<EffectRunHandle, RunEffectError> {\n\n // Resolve path\n\n let full_path = effect.script_path()?;\n\n\n\n // Create control channel\n\n let (ctx, crx) = channel(1);\n\n\n\n // Create instance methods\n\n let methods = InstanceMethods::new(\n\n tx.clone(),\n\n crx,\n\n led_count,\n", "file_path": "src/effects.rs", "rank": 43, "score": 93605.9764160234 }, { "content": "#[inline]\n\npub fn finish_size_prefixed_request_buffer<'a, 'b>(fbb: &'b mut flatbuffers::FlatBufferBuilder<'a>, root: flatbuffers::WIPOffset<Request<'a>>) {\n\n fbb.finish_size_prefixed(root, None);\n\n}\n\n} // pub mod hyperionnet\n\n\n", "file_path": "src/api/flat/message/hyperion_request_generated.rs", "rank": 44, "score": 92247.99406281361 }, { "content": "#[inline]\n\npub fn finish_size_prefixed_reply_buffer<'a, 'b>(fbb: &'b mut flatbuffers::FlatBufferBuilder<'a>, root: flatbuffers::WIPOffset<Reply<'a>>) {\n\n fbb.finish_size_prefixed(root, None);\n\n}\n\n} // pub mod hyperionnet\n\n\n", "file_path": "src/api/flat/message/hyperion_reply_generated.rs", "rank": 45, "score": 92247.99406281361 }, { "content": "/// Transforms the given color to fix its white balance\n\n///\n\n/// # Parameters\n\n///\n\n/// * `c`: color to transform\n\n/// * `src_white`: whitepoint of the current space of `c`\n\n/// * `dst_white`: whitepoint of the destination space of `c`\n\npub fn whitebalance(c: Color16, src_white: Color16, dst_white: Color16) -> Color16 {\n\n let (cr, cg, cb) = c.into_components();\n\n let (sr, sg, sb) = src_white.into_components();\n\n let (dr, dg, db) = dst_white.into_components();\n\n\n\n Color16::new(\n\n ((cr as u32 * dr as u32) / sr as u32).min(u16::MAX as u32) as u16,\n\n ((cg as u32 * dg as u32) / sg as u32).min(u16::MAX as u32) as u16,\n\n ((cb as u32 * db as u32) / sb as u32).min(u16::MAX as u32) as u16,\n\n )\n\n}\n\n\n\nconst FACTOR: u16 = 65535 / 255;\n\n\n", "file_path": "src/color/utils.rs", "rank": 46, "score": 90327.42780636894 }, { "content": "#[pyfunction]\n\n#[pyo3(name = \"setImage\")]\n\nfn set_image(width: u16, height: u16, data: &PyByteArray) -> Result<(), PyErr> {\n\n Context::with_current(|m| {\n\n // unwrap: we did all the necessary checks already\n\n m.set_image(\n\n RawImage::try_from((data.to_vec(), width as u32, height as u32))\n\n .map_err(|err| RuntimeMethodError::InvalidImageData(err))?,\n\n )?;\n\n\n\n Ok(())\n\n })\n\n}\n\n\n", "file_path": "src/effects/runtime.rs", "rank": 47, "score": 87593.10115252025 }, { "content": "#[async_trait]\n\npub trait WritingDevice: Send + Sized {\n\n type Config: DeviceConfig;\n\n\n\n fn new(config: &Self::Config) -> Result<Self, DeviceError>;\n\n\n\n async fn set_let_data(\n\n &mut self,\n\n config: &Self::Config,\n\n led_data: &[models::Color],\n\n ) -> Result<(), DeviceError>;\n\n\n\n async fn write(&mut self) -> Result<(), DeviceError>;\n\n}\n\n\n\npub struct Rewriter<D: WritingDevice> {\n\n inner: D,\n\n config: D::Config,\n\n last_write_time: Option<Instant>,\n\n next_write_time: Option<Instant>,\n\n}\n", "file_path": "src/instance/device/common.rs", "rank": 48, "score": 87409.15736612555 }, { "content": "#[derive(Default, Clone)]\n\nstruct TestMethods(Arc<Mutex<TestMethodData>>);\n\n\n\nimpl TestMethods {\n\n pub fn new() -> Self {\n\n Self::default()\n\n }\n\n\n\n pub fn with_led_count(led_count: usize) -> Self {\n\n Self(Arc::new(Mutex::new(TestMethodData {\n\n abort: false,\n\n leds: vec![Color::default(); led_count],\n\n })))\n\n }\n\n\n\n pub fn set_abort(&self, abort: bool) {\n\n self.0.lock().unwrap().abort = abort;\n\n }\n\n}\n\n\n\nimpl RuntimeMethods for TestMethods {\n", "file_path": "src/effects/runtime/tests.rs", "rank": 49, "score": 86368.7986618743 }, { "content": "fn success_response(peer_addr: SocketAddr) -> message::HyperionReply {\n\n let mut reply = message::HyperionReply::default();\n\n reply.r#type = message::hyperion_reply::Type::Reply.into();\n\n reply.success = Some(true);\n\n\n\n trace!(\"({}) sending success: {:?}\", peer_addr, reply);\n\n reply\n\n}\n\n\n", "file_path": "src/servers/proto.rs", "rank": 50, "score": 79378.87488014632 }, { "content": "fn install_tracing(opts: &Opts) -> Result<(), tracing_subscriber::util::TryInitError> {\n\n use tracing_error::ErrorLayer;\n\n use tracing_subscriber::{fmt, prelude::*, EnvFilter};\n\n\n\n let fmt_layer = fmt::layer();\n\n\n\n let filter_layer = EnvFilter::try_from_env(\"HYPERION_LOG\").unwrap_or_else(|_| {\n\n EnvFilter::new(match opts.verbose {\n\n 0 => \"hyperion=warn,hyperiond=warn\",\n\n 1 => \"hyperion=info,hyperiond=info\",\n\n 2 => \"hyperion=debug,hyperiond=debug\",\n\n _ => \"hyperion=trace,hyperiond=trace\",\n\n })\n\n });\n\n\n\n tracing_subscriber::registry()\n\n .with(filter_layer)\n\n .with(fmt_layer)\n\n .with(ErrorLayer::default())\n\n .try_init()\n\n}\n\n\n", "file_path": "src/main.rs", "rank": 51, "score": 76670.85933061973 }, { "content": "use std::{convert::TryFrom, sync::Arc};\n\n\n\nuse super::InputMessageData;\n\nuse crate::{image::RawImage, models::Color};\n\n\n\n#[derive(Debug, Clone)]\n\npub struct MuxedMessage {\n\n data: MuxedMessageData,\n\n}\n\n\n\nimpl MuxedMessage {\n\n pub fn new(data: MuxedMessageData) -> Self {\n\n Self { data }\n\n }\n\n\n\n pub fn data(&self) -> &MuxedMessageData {\n\n &self.data\n\n }\n\n}\n\n\n", "file_path": "src/instance/muxer/muxed_message.rs", "rank": 52, "score": 73503.83374921876 }, { "content": "impl std::ops::Deref for MuxedMessage {\n\n type Target = MuxedMessageData;\n\n\n\n fn deref(&self) -> &Self::Target {\n\n &self.data\n\n }\n\n}\n\n\n\n#[derive(Debug, Clone)]\n\npub enum MuxedMessageData {\n\n SolidColor {\n\n priority: i32,\n\n duration: Option<chrono::Duration>,\n\n color: Color,\n\n },\n\n Image {\n\n priority: i32,\n\n duration: Option<chrono::Duration>,\n\n image: Arc<RawImage>,\n\n },\n", "file_path": "src/instance/muxer/muxed_message.rs", "rank": 53, "score": 73497.85795530622 }, { "content": " }\n\n }\n\n}\n\n\n\nimpl TryFrom<InputMessageData> for MuxedMessageData {\n\n type Error = ();\n\n\n\n fn try_from(value: InputMessageData) -> Result<Self, Self::Error> {\n\n match value {\n\n InputMessageData::ClearAll\n\n | InputMessageData::Clear { .. }\n\n | InputMessageData::Effect { .. } => Err(()),\n\n InputMessageData::SolidColor {\n\n priority,\n\n duration,\n\n color,\n\n } => Ok(Self::SolidColor {\n\n priority,\n\n duration,\n\n color,\n", "file_path": "src/instance/muxer/muxed_message.rs", "rank": 54, "score": 73497.06109049718 }, { "content": " LedColors {\n\n priority: i32,\n\n duration: Option<chrono::Duration>,\n\n led_colors: Arc<Vec<Color>>,\n\n },\n\n}\n\n\n\nimpl MuxedMessageData {\n\n pub fn priority(&self) -> i32 {\n\n match self {\n\n MuxedMessageData::SolidColor { priority, .. } => *priority,\n\n MuxedMessageData::Image { priority, .. } => *priority,\n\n MuxedMessageData::LedColors { priority, .. } => *priority,\n\n }\n\n }\n\n\n\n pub fn color(&self) -> Option<Color> {\n\n match self {\n\n MuxedMessageData::SolidColor { color, .. } => Some(*color),\n\n _ => None,\n", "file_path": "src/instance/muxer/muxed_message.rs", "rank": 55, "score": 73496.70925472332 }, { "content": " }),\n\n InputMessageData::Image {\n\n priority,\n\n duration,\n\n image,\n\n } => Ok(Self::Image {\n\n priority,\n\n duration,\n\n image,\n\n }),\n\n InputMessageData::LedColors {\n\n priority,\n\n duration,\n\n led_colors,\n\n } => Ok(Self::LedColors {\n\n priority,\n\n duration,\n\n led_colors,\n\n }),\n\n }\n\n }\n\n}\n", "file_path": "src/instance/muxer/muxed_message.rs", "rank": 56, "score": 73489.11914717828 }, { "content": "#[async_trait]\n\ntrait DeviceImpl: Send {\n\n /// Set the device implementation's view of the LED data to the given values\n\n ///\n\n /// # Panics\n\n ///\n\n /// Implementations are allowed to panic if led_data.len() != hardware_led_count. The [Device]\n\n /// wrapper is responsible for ensuring the given slice is the right size.\n\n async fn set_led_data(&mut self, led_data: &[models::Color]) -> Result<(), DeviceError>;\n\n\n\n /// Update the device implementation's temporal data. For devices that require regular rewrites\n\n /// (regardless of actual changes in the LED data), this should return a future that performs\n\n /// the required work.\n\n async fn update(&mut self) -> Result<(), DeviceError>;\n\n}\n\n\n\npub struct Device {\n\n name: String,\n\n inner: Box<dyn DeviceImpl>,\n\n led_data: Vec<models::Color>,\n\n notified_inconsistent_led_data: bool,\n", "file_path": "src/instance/device.rs", "rank": 57, "score": 72544.86129243621 }, { "content": "#[derive(Debug, StructOpt)]\n\nstruct Opts {\n\n /// Log verbosity. Overrides logger level in config, but is overridden by HYPERION_LOG\n\n #[structopt(short, long, parse(from_occurrences))]\n\n verbose: u32,\n\n /// Path to the configuration database\n\n #[structopt(\n\n short,\n\n long = \"db-path\",\n\n default_value = \"$ROOT/hyperion.db\",\n\n env = \"DATABASE_URL\"\n\n )]\n\n database_path: PathBuf,\n\n /// Path to a TOML config file. Overrides the configuration database\n\n #[structopt(short, long = \"config\")]\n\n config_path: Option<PathBuf>,\n\n /// Dump the loaded configuration\n\n #[structopt(long)]\n\n dump_config: bool,\n\n /// Path to the user root folder. Defaults to .config/hyperion.rs (Linux) or\n\n /// %APPDATA%\\hyperion.rs (Windows)\n", "file_path": "src/main.rs", "rank": 58, "score": 69795.63489435377 }, { "content": "#[derive(Default, Debug, Clone, Copy)]\n\nstruct BrightnessComponents {\n\n pub rgb: u8,\n\n pub cmy: u8,\n\n pub w: u8,\n\n}\n\n\n\nimpl RgbTransform {\n\n fn gamma(x: u8, gamma: f32) -> u8 {\n\n ((x as f32 / 255.0).powf(gamma) * 255.0) as u8\n\n }\n\n\n\n pub fn brightness_components(&self) -> BrightnessComponents {\n\n let fw = self.brightness_compensation as f32 * 2.0 / 100.0 + 1.0;\n\n let fcmy = self.brightness_compensation as f32 / 100.0 + 1.0;\n\n\n\n if self.brightness > 0 {\n\n let b_in = if self.brightness < 50 {\n\n -0.09 * self.brightness as f32 + 7.5\n\n } else {\n\n -0.04 * self.brightness as f32 + 5.0\n", "file_path": "src/color.rs", "rank": 59, "score": 68409.91327886749 }, { "content": "#[derive(Debug, Clone, Copy)]\n\nstruct RgbTransform {\n\n backlight_enabled: bool,\n\n backlight_colored: bool,\n\n sum_brightness_low: f32,\n\n gamma_r: f32,\n\n gamma_g: f32,\n\n gamma_b: f32,\n\n brightness: u8,\n\n brightness_compensation: u8,\n\n}\n\n\n\nimpl From<&crate::models::ChannelAdjustment> for RgbTransform {\n\n fn from(settings: &crate::models::ChannelAdjustment) -> Self {\n\n Self {\n\n backlight_enabled: false,\n\n backlight_colored: settings.backlight_colored,\n\n sum_brightness_low: 765.0\n\n * ((2.0f32.powf(settings.backlight_threshold as f32 / 100.0 * 2.0) - 1.0) / 3.0),\n\n gamma_r: settings.gamma_red,\n\n gamma_g: settings.gamma_green,\n\n gamma_b: settings.gamma_blue,\n\n brightness: settings.brightness as _,\n\n brightness_compensation: settings.brightness_compensation as _,\n\n }\n\n }\n\n}\n\n\n", "file_path": "src/color.rs", "rank": 60, "score": 68409.91327886749 }, { "content": "#[derive(Debug, Clone, Copy)]\n\nenum ResolvedPaths {\n\n Production,\n\n Development,\n\n}\n\n\n\nconst ROOT_MARKER: &str = \"$ROOT\";\n\nconst SYSTEM_MARKER: &str = \"$SYSTEM\";\n\n\n\n#[derive(Clone)]\n\npub struct Paths {\n\n mode: ResolvedPaths,\n\n system_root: PathBuf,\n\n user_root: PathBuf,\n\n}\n\n\n\nimpl Paths {\n\n fn find_dev_root(first_root: &Path) -> Option<PathBuf> {\n\n let bn = first_root.file_name().and_then(std::ffi::OsStr::to_str);\n\n\n\n if bn == Some(\"release\") || bn == Some(\"debug\") || bn == Some(\"deps\") {\n", "file_path": "src/global/paths.rs", "rank": 61, "score": 67848.59231203968 }, { "content": "fn main() {\n\n let src_path = \"src/api/proto/message.proto\";\n\n prost_build::compile_protos(&[src_path], &[\"src/api/proto\"]).unwrap();\n\n}\n", "file_path": "build.rs", "rank": 62, "score": 67730.69426211824 }, { "content": "#[derive(Default, Debug, Clone, Copy)]\n\nstruct RgbChannelAdjustment {\n\n adjust: Color,\n\n}\n\n\n\nimpl RgbChannelAdjustment {\n\n pub fn apply(&self, input: u8, brightness: u8) -> Color {\n\n Color::new(\n\n ((brightness as u32 * input as u32 * self.adjust.red as u32) / 65025) as _,\n\n ((brightness as u32 * input as u32 * self.adjust.green as u32) / 65025) as _,\n\n ((brightness as u32 * input as u32 * self.adjust.blue as u32) / 65025) as _,\n\n )\n\n }\n\n}\n\n\n\nimpl From<Color> for RgbChannelAdjustment {\n\n fn from(color: Color) -> Self {\n\n Self { adjust: color }\n\n }\n\n}\n\n\n", "file_path": "src/color.rs", "rank": 63, "score": 67119.40553494774 }, { "content": "#[derive(Debug)]\n\nstruct LedSpec {\n\n lxmin: u16,\n\n lxmax: u16,\n\n lymin: u16,\n\n lymax: u16,\n\n}\n\n\n\nimpl LedSpec {\n\n pub fn new(spec: &Led, width: u16, height: u16, fwidth: f32, fheight: f32) -> Self {\n\n let lxmin = spec.hmin * fwidth;\n\n let lxmax = spec.hmax * fwidth;\n\n let lymin = spec.vmin * fheight;\n\n let lymax = spec.vmax * fheight;\n\n\n\n Self {\n\n lxmin: lxmin.floor() as u16,\n\n lxmax: (lxmax.ceil() as u16).min(width - 1),\n\n lymin: lymin.floor() as u16,\n\n lymax: (lymax.ceil() as u16).min(height - 1),\n\n }\n", "file_path": "src/image/reducer.rs", "rank": 64, "score": 67119.40553494774 }, { "content": "/// Serde visitor for deserializing Base64-encoded values\n\nstruct Base64Visitor;\n\n\n\nimpl<'a> serde::de::Visitor<'a> for Base64Visitor {\n\n type Value = Vec<u8>;\n\n\n\n fn expecting(&self, formatter: &mut fmt::Formatter) -> fmt::Result {\n\n formatter.write_str(\"base64 image\")\n\n }\n\n\n\n fn visit_str<A>(self, string: &str) -> Result<Self::Value, A>\n\n where\n\n A: serde::de::Error,\n\n {\n\n base64::decode(string).map_err(|err| serde::de::Error::custom(err.to_string()))\n\n }\n\n}\n\n\n", "file_path": "src/serde/base64.rs", "rank": 65, "score": 67119.40553494774 }, { "content": "struct ClassicLedParams {\n\n ledstop: u32,\n\n ledsbottom: u32,\n\n ledsleft: u32,\n\n ledsright: u32,\n\n ledsglength: u32,\n\n ledsgpos: u32,\n\n position: i32,\n\n reverse: bool,\n\n ledsvdepth: f32,\n\n ledshdepth: f32,\n\n edgehgap: f32,\n\n edgevgap: f32,\n\n overlap: f32,\n\n ptblh: f32,\n\n ptblv: f32,\n\n ptbrh: f32,\n\n ptbrv: f32,\n\n pttlh: f32,\n\n pttlv: f32,\n", "file_path": "src/models/layouts.rs", "rank": 66, "score": 65910.80763273605 }, { "content": "#[derive(Deserialize)]\n\nstruct DeserializableConfig {\n\n instances: BTreeMap<String, InstanceConfig>,\n\n #[serde(default, flatten)]\n\n global: GlobalConfig,\n\n #[serde(default = \"default_meta\")]\n\n meta: Vec<Meta>,\n\n #[serde(default = \"default_users\")]\n\n users: Vec<User>,\n\n}\n\n\n\nimpl TryFrom<DeserializableConfig> for Config {\n\n type Error = ConfigError;\n\n\n\n fn try_from(value: DeserializableConfig) -> Result<Self, Self::Error> {\n\n Ok(Self {\n\n instances: value\n\n .instances\n\n .into_iter()\n\n .map(|(k, v)| {\n\n k.parse()\n", "file_path": "src/models/backend/file.rs", "rank": 67, "score": 65910.80763273605 }, { "content": "#[derive(Default)]\n\nstruct GlobalConfigCreator {\n\n flatbuffers_server: Option<FlatbuffersServer>,\n\n forwarder: Option<Forwarder>,\n\n framegrabber: Option<Framegrabber>,\n\n general: Option<General>,\n\n grabber_v4l2: Option<GrabberV4L2>,\n\n json_server: Option<JsonServer>,\n\n logger: Option<Logger>,\n\n network: Option<Network>,\n\n proto_server: Option<ProtoServer>,\n\n web_config: Option<WebConfig>,\n\n hooks: Option<Hooks>,\n\n}\n", "file_path": "src/models/backend/db.rs", "rank": 68, "score": 64776.56109273522 }, { "content": "struct HookBuilder<'s> {\n\n variables: BTreeMap<&'static str, String>,\n\n command: &'s Vec<String>,\n\n}\n\n\n\nimpl<'s> HookBuilder<'s> {\n\n pub fn new(command: &'s Vec<String>) -> Self {\n\n Self {\n\n variables: Default::default(),\n\n command,\n\n }\n\n }\n\n\n\n pub fn arg(mut self, k: &'static str, v: impl Display) -> Self {\n\n self.variables.insert(k, v.to_string());\n\n self\n\n }\n\n\n\n pub async fn run(self) -> Option<Result<(), std::io::Error>> {\n\n if self.command.is_empty() {\n", "file_path": "src/global/hook_runner.rs", "rank": 69, "score": 63404.057326841474 }, { "content": "#[derive(Serialize)]\n\nstruct SerializableConfig<'c> {\n\n instances: BTreeMap<String, &'c InstanceConfig>,\n\n #[serde(flatten)]\n\n global: &'c GlobalConfig,\n\n meta: &'c Vec<Meta>,\n\n users: &'c Vec<User>,\n\n}\n\n\n\nimpl<'c> From<&'c Config> for SerializableConfig<'c> {\n\n fn from(config: &'c Config) -> Self {\n\n Self {\n\n instances: config\n\n .instances\n\n .iter()\n\n .map(|(k, v)| (k.to_string(), v))\n\n .collect(),\n\n global: &config.global,\n\n meta: &config.meta,\n\n users: &config.users,\n\n }\n\n }\n\n}\n\n\n", "file_path": "src/models/backend/file.rs", "rank": 70, "score": 63404.057326841474 }, { "content": "/// Trait for converting a LED configuration to LEDs\n\npub trait ToLeds {\n\n fn to_leds(&self) -> Leds;\n\n}\n\n\n", "file_path": "src/models/layouts.rs", "rank": 71, "score": 63056.42690294293 }, { "content": "pub trait ServerConfig {\n\n fn port(&self) -> u16;\n\n}\n\n\n", "file_path": "src/models.rs", "rank": 72, "score": 63056.42690294293 }, { "content": "fn run_string(\n\n source: &str,\n\n args: serde_json::Value,\n\n methods: impl RuntimeMethods + 'static,\n\n) -> Result<Py<PyDict>, PyErr> {\n\n do_run(methods, args, |py| {\n\n let locals = pyo3::types::PyDict::new(py);\n\n let result = py.run(source, None, Some(locals));\n\n result.map(|_| locals.into())\n\n })\n\n}\n\n\n", "file_path": "src/effects/runtime/tests.rs", "rank": 73, "score": 62426.52218172868 }, { "content": "#[async_trait]\n\npub trait ConfigBackend {\n\n async fn load(&mut self) -> Result<Config, ConfigError>;\n\n}\n\n\n\npub use db::DbBackend;\n\npub use file::{ConfigExt, FileBackend};\n", "file_path": "src/models/backend.rs", "rank": 74, "score": 61854.66357559415 }, { "content": "pub trait RuntimeMethods {\n\n fn get_led_count(&self) -> usize;\n\n fn abort(&self) -> bool;\n\n\n\n fn set_color(&self, color: Color) -> Result<(), RuntimeMethodError>;\n\n fn set_led_colors(&self, colors: Vec<Color>) -> Result<(), RuntimeMethodError>;\n\n fn set_image(&self, image: RawImage) -> Result<(), RuntimeMethodError>;\n\n}\n\n\n\n/// Check if the effect should abort execution\n", "file_path": "src/effects/runtime.rs", "rank": 75, "score": 61854.66357559415 }, { "content": "#[pyfunction]\n\nfn abort() -> bool {\n\n Context::with_current(|m| m.abort())\n\n}\n\n\n\n/// Set a new color for the leds\n", "file_path": "src/effects/runtime.rs", "rank": 76, "score": 61382.15026197625 }, { "content": "fn default_true() -> bool {\n\n true\n\n}\n\n\n", "file_path": "src/models.rs", "rank": 77, "score": 61382.15026197625 }, { "content": "fn default_false() -> bool {\n\n false\n\n}\n\n\n\n#[derive(Debug, Clone, PartialEq, Deserialize)]\n\npub struct Setting {\n\n pub hyperion_inst: Option<i32>,\n\n pub config: SettingData,\n\n pub updated_at: chrono::DateTime<chrono::Utc>,\n\n}\n\n\n\n#[derive(Debug, Clone, PartialEq, EnumDiscriminants, Deserialize)]\n\n#[strum_discriminants(name(SettingKind), derive(EnumString))]\n\npub enum SettingData {\n\n // hyperion.ng settings\n\n BackgroundEffect(BackgroundEffect),\n\n BlackBorderDetector(BlackBorderDetector),\n\n BoblightServer(BoblightServer),\n\n ColorAdjustment(ColorAdjustment),\n\n Device(Device),\n", "file_path": "src/models.rs", "rank": 78, "score": 61382.15026197625 }, { "content": "fn do_run<T>(\n\n methods: impl RuntimeMethods + 'static,\n\n args: serde_json::Value,\n\n f: impl FnOnce(Python) -> Result<T, PyErr>,\n\n) -> Result<T, PyErr> {\n\n Context::with(methods, |ctx| {\n\n // Run the given code\n\n Python::with_gil(|py| {\n\n ctx.run(py, || {\n\n // Register arguments\n\n let hyperion_mod = py.import(\"hyperion\")?;\n\n hyperion_mod.add(\"args\", pythonize(py, &args)?)?;\n\n\n\n f(py)\n\n })\n\n })\n\n })\n\n}\n\n\n", "file_path": "src/effects/runtime.rs", "rank": 79, "score": 61382.15026197625 }, { "content": "#[test]\n\nfn test_led_count() {\n\n let led_count = 12;\n\n let tm = TestMethods::with_led_count(led_count);\n\n\n\n let result = run_string(\n\n \"import hyperion\n\nleds = hyperion.ledCount\n\n\",\n\n Default::default(),\n\n tm,\n\n )\n\n .expect(\"failed to run effect code\");\n\n\n\n Python::with_gil(|py| {\n\n assert_eq!(\n\n led_count,\n\n result\n\n .as_ref(py)\n\n .get_item(\"leds\")\n\n .unwrap()\n", "file_path": "src/effects/runtime/tests.rs", "rank": 80, "score": 61304.42024227118 }, { "content": "pub trait Image: Sized {\n\n /// Get the width of the image, in pixels\n\n fn width(&self) -> u16;\n\n\n\n /// Get the height of the image, in pixels\n\n fn height(&self) -> u16;\n\n\n\n /// Get the color at the given coordinates\n\n fn color_at(&self, x: u16, y: u16) -> Option<Color>;\n\n\n\n /// Get the color at the given coordinates skipping bound checks\n\n unsafe fn color_at_unchecked(&self, x: u16, y: u16) -> Color;\n\n\n\n /// Convert this image trait object to a raw image\n\n fn to_raw_image(&self) -> RawImage;\n\n}\n\n\n\n#[derive(Debug, Error)]\n\npub enum RawImageError {\n\n #[error(\"invalid data ({data} bytes) for the given dimensions ({width} x {height} x {channels} = {expected})\")]\n", "file_path": "src/image.rs", "rank": 81, "score": 61054.668733129554 }, { "content": "pub trait ConfigExt {\n\n fn to_string(&self) -> Result<String, toml::ser::Error>;\n\n}\n\n\n\nimpl ConfigExt for Config {\n\n fn to_string(&self) -> Result<String, toml::ser::Error> {\n\n toml::to_string_pretty(&SerializableConfig::from(self))\n\n }\n\n}\n\n\n\npub struct FileBackend {\n\n path: PathBuf,\n\n}\n\n\n\nimpl FileBackend {\n\n pub fn new(path: &Path) -> Self {\n\n Self {\n\n path: path.to_owned(),\n\n }\n\n }\n", "file_path": "src/models/backend/file.rs", "rank": 82, "score": 60726.83115634967 }, { "content": "pub trait ImageViewExt: Image {\n\n fn wrap(&self, x: std::ops::Range<u16>, y: std::ops::Range<u16>) -> ImageView<Self>;\n\n}\n\n\n\nimpl<T: Image> ImageViewExt for T {\n\n fn wrap(&self, x: std::ops::Range<u16>, y: std::ops::Range<u16>) -> ImageView<Self> {\n\n ImageView {\n\n inner: self,\n\n xmin: x.start,\n\n xmax: x.end,\n\n ymin: y.start,\n\n ymax: y.end,\n\n }\n\n }\n\n}\n\n\n\npub mod prelude {\n\n pub use super::{Image, ImageViewExt};\n\n}\n", "file_path": "src/image.rs", "rank": 83, "score": 58725.072986536296 }, { "content": "pub trait AnsiDisplayExt: Sized {\n\n fn to_ansi_truecolor(self, buffer: &mut String);\n\n}\n\n\n\nimpl<T> AnsiDisplayExt for T\n\nwhere\n\n T: IntoIterator<Item = Color>,\n\n{\n\n fn to_ansi_truecolor(self, buffer: &mut String) {\n\n use std::fmt::Write;\n\n\n\n // Push colors\n\n for led in self {\n\n write!(\n\n buffer,\n\n \"\\x1B[38;2;{red};{green};{blue}m█\",\n\n red = led.red,\n\n green = led.green,\n\n blue = led.blue\n\n )\n", "file_path": "src/color.rs", "rank": 84, "score": 58725.072986536296 }, { "content": "fn default_ws_spi_rewrite_time() -> u32 {\n\n 1000\n\n}\n\n\n\n#[derive(Debug, Clone, PartialEq, Serialize, Deserialize, Validate)]\n\n#[serde(rename_all = \"camelCase\", deny_unknown_fields)]\n\npub struct Ws2812Spi {\n\n #[serde(default = \"Default::default\")]\n\n pub color_order: ColorOrder,\n\n #[validate(range(min = 1))]\n\n pub hardware_led_count: u32,\n\n #[serde(default = \"default_false\")]\n\n pub invert: bool,\n\n #[serde(default = \"Default::default\")]\n\n pub latch_time: u32,\n\n pub output: String,\n\n #[serde(default = \"default_ws_spi_rate\")]\n\n pub rate: i32,\n\n #[serde(default = \"default_ws_spi_rewrite_time\")]\n\n pub rewrite_time: u32,\n", "file_path": "src/models/devices.rs", "rank": 85, "score": 57015.27634115533 }, { "content": "fn not_positive(x: &i64) -> bool {\n\n !(*x > 0)\n\n}\n\n\n", "file_path": "src/api/types.rs", "rank": 86, "score": 56695.91224287386 }, { "content": "fn default_meta() -> Vec<Meta> {\n\n vec![Meta::new()]\n\n}\n\n\n", "file_path": "src/models/backend/file.rs", "rank": 87, "score": 56125.26794588404 }, { "content": "fn default_users() -> Vec<User> {\n\n vec![User::hyperion()]\n\n}\n\n\n", "file_path": "src/models/backend/file.rs", "rank": 88, "score": 56125.26794588404 }, { "content": "#[delegatable_trait]\n\npub trait DeviceConfig: Sync + Send {\n\n fn hardware_led_count(&self) -> usize;\n\n\n\n fn rewrite_time(&self) -> Option<std::time::Duration> {\n\n None\n\n }\n\n\n\n fn latch_time(&self) -> std::time::Duration {\n\n Default::default()\n\n }\n\n}\n\n\n\nmacro_rules! impl_device_config {\n\n ($t:ty) => {\n\n impl DeviceConfig for $t {\n\n fn hardware_led_count(&self) -> usize {\n\n self.hardware_led_count as _\n\n }\n\n\n\n fn rewrite_time(&self) -> Option<std::time::Duration> {\n", "file_path": "src/models/devices.rs", "rank": 89, "score": 55957.53707129199 }, { "content": "fn default_none<T>() -> Option<T> {\n\n None\n\n}\n\n\n\n#[derive(Debug, Error)]\n\npub enum ConfigError {\n\n #[error(\"i/o error\")]\n\n Io(#[from] std::io::Error),\n\n #[error(\"error querying the database\")]\n\n Sqlx(#[from] sqlx::Error),\n\n #[error(\"error loading instance\")]\n\n Instance(#[from] InstanceError),\n\n #[error(\"error loading setting\")]\n\n Setting(#[from] SettingError),\n\n #[error(\"error loading meta\")]\n\n Meta(#[from] MetaError),\n\n #[error(\"error loading user\")]\n\n User(#[from] UserError),\n\n #[error(\"missing hyperion_inst field on instance setting {0}\")]\n\n MissingHyperionInst(&'static str),\n", "file_path": "src/models.rs", "rank": 90, "score": 55573.81030341635 }, { "content": "fn classic_led_config(leds: u32) -> Leds {\n\n let classic_led_config = ClassicLedConfig {\n\n top: leds / 4,\n\n bottom: leds / 4,\n\n left: leds / 4,\n\n right: leds / 4,\n\n ..Default::default()\n\n };\n\n\n\n classic_led_config.to_leds()\n\n}\n\n\n", "file_path": "benches/reducer.rs", "rank": 91, "score": 54518.67864560183 }, { "content": "/// Return the whitepoint for a given color temperature\n\n///\n\n/// # Parameters\n\n///\n\n/// * `t`: temperature in Kelvin\n\nfn kelvin_to_rgbf32(t: f32) -> LinSrgb {\n\n let t = f64::from(t);\n\n\n\n // http://www.tannerhelland.com/4435/convert-temperature-rgb-algorithm-code/\n\n //\n\n // Check bounds on temperature\n\n let t = if t > 40000.0 { 40000.0 } else { t };\n\n let t = if t < 1000.0 { 1000.0 } else { t };\n\n\n\n // Scale\n\n let t = t / 100.0;\n\n\n\n let r = if t <= 66.0 {\n\n 255.0\n\n } else {\n\n 329.698_727_446 * (t - 60.0).powf(-0.133_204_759_2)\n\n };\n\n\n\n let g = if t <= 66.0 {\n\n 99.470_802_586_1 * t.ln() - 161.119_568_166_1\n", "file_path": "src/color/utils.rs", "rank": 92, "score": 54518.67864560183 }, { "content": "fn color_to_hsl(color: Color) -> palette::Hsl {\n\n let (r, g, b) = color.into_components();\n\n palette::Hsl::from(palette::LinSrgb::new(\n\n r as f32 / 255.0,\n\n g as f32 / 255.0,\n\n b as f32 / 255.0,\n\n ))\n\n}\n\n\n\n#[derive(Debug, Serialize)]\n\npub struct PriorityInfo {\n\n pub priority: i32,\n\n #[serde(skip_serializing_if = \"not_positive\")]\n\n pub duration_ms: i64,\n\n #[serde(skip_serializing_if = \"Option::is_none\")]\n\n pub owner: Option<String>,\n\n pub component_id: ComponentName,\n\n pub origin: String,\n\n pub active: bool,\n\n pub visible: bool,\n", "file_path": "src/api/types.rs", "rank": 93, "score": 52138.441944180566 }, { "content": "#[paw::main]\n\nfn main(opts: Opts) -> color_eyre::eyre::Result<()> {\n\n color_eyre::install()?;\n\n install_tracing(&opts)?;\n\n\n\n // Create tokio runtime\n\n let thd_count = opts\n\n .core_threads\n\n .and_then(|n| if n > 0 { Some(n) } else { None })\n\n .unwrap_or_else(|| num_cpus::get().max(2).min(4));\n\n let rt = Builder::new_multi_thread()\n\n .worker_threads(thd_count)\n\n .enable_all()\n\n .build()?;\n\n rt.block_on(run(opts))\n\n}\n", "file_path": "src/main.rs", "rank": 94, "score": 50930.10587889988 }, { "content": "#[pyfunction(args = \"*\")]\n\n#[pyo3(name = \"setColor\")]\n\nfn set_color(args: &PyTuple) -> Result<(), PyErr> {\n\n Context::with_current(|m| {\n\n if let Result::<(u8, u8, u8), _>::Ok((r, g, b)) = args.extract() {\n\n m.set_color(Color::new(r, g, b))?;\n\n } else if let Result::<(&PyByteArray,), _>::Ok((bytearray,)) = args.extract() {\n\n if bytearray.len() == 3 * m.get_led_count() {\n\n // Safety: we are not modifying bytearray while accessing it\n\n unsafe {\n\n m.set_led_colors(\n\n bytearray\n\n .as_bytes()\n\n .chunks_exact(3)\n\n .map(|rgb| Color::new(rgb[0], rgb[1], rgb[2]))\n\n .collect(),\n\n )?;\n\n }\n\n } else {\n\n return Err(RuntimeMethodError::InvalidByteArray.into());\n\n }\n\n } else {\n\n return Err(RuntimeMethodError::InvalidArguments { name: \"setColor\" }.into());\n\n }\n\n\n\n Ok(())\n\n })\n\n}\n\n\n\n/// Set a new image to process and determine new led colors\n", "file_path": "src/effects/runtime.rs", "rank": 95, "score": 50313.82345579295 }, { "content": "#[pymodule]\n\nfn hyperion(_py: Python, m: &PyModule) -> PyResult<()> {\n\n m.add_function(wrap_pyfunction!(abort, m)?)?;\n\n m.add_function(wrap_pyfunction!(set_color, m)?)?;\n\n m.add_function(wrap_pyfunction!(set_image, m)?)?;\n\n\n\n m.add(\"ledCount\", Context::with_current(|m| m.get_led_count()))?;\n\n\n\n Ok(())\n\n}\n\n\n\nextern \"C\" fn hyperion_init() -> *mut pyo3::ffi::PyObject {\n\n unsafe { PyInit_hyperion() }\n\n}\n\n\n", "file_path": "src/effects/runtime.rs", "rank": 96, "score": 49992.10534113074 }, { "content": "fn random_image(width: u16, height: u16) -> RawImage {\n\n let mut data = vec![0u8; width as usize * height as usize * RawImage::CHANNELS as usize];\n\n\n\n let mut rng = rand::thread_rng();\n\n rng.fill_bytes(&mut data);\n\n\n\n RawImage::try_from((data, width as u32, height as u32)).unwrap()\n\n}\n\n\n", "file_path": "benches/reducer.rs", "rank": 97, "score": 49992.10534113074 }, { "content": "use std::sync::Arc;\n\n\n\nuse thiserror::Error;\n\nuse tokio::{\n\n select,\n\n sync::{broadcast, mpsc, oneshot},\n\n};\n\n\n\nuse crate::{\n\n api::types::PriorityInfo,\n\n global::{Event, Global, InputMessage, InstanceEventKind},\n\n models::{Color, InstanceConfig},\n\n servers::{self, ServerHandle},\n\n};\n\n\n\nmod black_border_detector;\n\nuse black_border_detector::*;\n\n\n\nmod core;\n\nuse self::core::*;\n", "file_path": "src/instance.rs", "rank": 98, "score": 40741.662802368046 }, { "content": " fn from(_: tokio::sync::mpsc::error::SendError<T>) -> Self {\n\n Self::Dropped\n\n }\n\n}\n\n\n\nimpl From<tokio::sync::oneshot::error::RecvError> for InstanceHandleError {\n\n fn from(_: tokio::sync::oneshot::error::RecvError) -> Self {\n\n Self::Dropped\n\n }\n\n}\n\n\n\nimpl InstanceHandle {\n\n pub fn id(&self) -> i32 {\n\n self.id\n\n }\n\n\n\n pub fn input_channel(&self) -> &mpsc::Sender<InputMessage> {\n\n &self.local_tx\n\n }\n\n\n", "file_path": "src/instance.rs", "rank": 99, "score": 40740.7358479986 } ]
Rust
src/proxy/sessions/session_manager.rs
iffyio/quilkin
d5e1024b057c7de11e403c2e942ce51b25ae846d
/* * Copyright 2021 Google LLC * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ use std::collections::HashMap; use std::sync::Arc; use std::time::{Duration, SystemTime, UNIX_EPOCH}; use slog::{debug, warn, Logger}; use tokio::sync::{watch, RwLock, RwLockReadGuard, RwLockWriteGuard}; use crate::proxy::sessions::{Session, SessionKey}; type SessionsMap = HashMap<SessionKey, Session>; type Sessions = Arc<RwLock<SessionsMap>>; pub const SESSION_TIMEOUT_SECONDS: u64 = 60; const SESSION_EXPIRY_POLL_INTERVAL: u64 = 60; #[derive(Clone)] pub struct SessionManager(Sessions); impl SessionManager { pub fn new(log: Logger, shutdown_rx: watch::Receiver<()>) -> Self { let poll_interval = Duration::from_secs(SESSION_EXPIRY_POLL_INTERVAL); let sessions: Sessions = Arc::new(RwLock::new(HashMap::new())); Self::run_prune_sessions(log.clone(), sessions.clone(), poll_interval, shutdown_rx); Self(sessions) } pub async fn get_sessions(&self) -> RwLockReadGuard<'_, SessionsMap> { self.0.read().await } pub async fn get_sessions_mut(&self) -> RwLockWriteGuard<'_, SessionsMap> { self.0.write().await } fn run_prune_sessions( log: Logger, mut sessions: Sessions, poll_interval: Duration, mut shutdown_rx: watch::Receiver<()>, ) { let mut interval = tokio::time::interval(poll_interval); tokio::spawn(async move { loop { tokio::select! { _ = shutdown_rx.changed() => { debug!(log, "Exiting Prune Sessions due to shutdown signal."); break; } _ = interval.tick() => { debug!(log, "Attempting to Prune Sessions"); Self::prune_sessions(&log, &mut sessions).await; } } } }); } async fn prune_sessions(log: &Logger, sessions: &mut Sessions) { let now = if let Ok(now) = SystemTime::now().duration_since(UNIX_EPOCH) { now.as_secs() } else { warn!(log, "Failed to get current time when pruning sessions"); return; }; let expired_keys = (*sessions.read().await) .iter() .filter(|(_, session)| session.expiration() <= now) .count(); if expired_keys != 0 { sessions .write() .await .retain(|_, session| session.expiration() > now); } } } #[cfg(test)] mod tests { use std::collections::HashMap; use std::net::SocketAddr; use std::ops::Add; use std::sync::Arc; use std::time::Duration; use prometheus::Registry; use tokio::sync::{mpsc, watch, RwLock}; use crate::cluster::Endpoint; use crate::filters::{manager::FilterManager, FilterChain}; use crate::proxy::sessions::metrics::Metrics; use crate::proxy::sessions::session_manager::Sessions; use crate::proxy::sessions::{Packet, Session, SessionKey}; use crate::test_utils::TestHelper; use super::SessionManager; #[tokio::test] async fn run_prune_sessions() { let t = TestHelper::default(); let sessions = Arc::new(RwLock::new(HashMap::new())); let from: SocketAddr = "127.0.0.1:7000".parse().unwrap(); let to: SocketAddr = "127.0.0.1:7001".parse().unwrap(); let (send, _recv) = mpsc::channel::<Packet>(1); let (_shutdown_tx, shutdown_rx) = watch::channel(()); let endpoint = Endpoint::from_address(to); let ttl = Duration::from_secs(1); let poll_interval = Duration::from_millis(1); SessionManager::run_prune_sessions( t.log.clone(), sessions.clone(), poll_interval, shutdown_rx, ); let key = SessionKey::from((from, to)); { let registry = Registry::default(); let mut sessions = sessions.write().await; sessions.insert( key.clone(), Session::new( &t.log, Metrics::new(&registry).unwrap(), FilterManager::fixed(Arc::new(FilterChain::new(vec![], &registry).unwrap())), from, endpoint.clone(), send, ttl, ) .await .unwrap(), ); } { let map = sessions.read().await; assert!(map.contains_key(&key)); assert_eq!(1, map.len()); } tokio::time::sleep_until(tokio::time::Instant::now().add(ttl)).await; for _ in 1..10000 { tokio::time::sleep(Duration::from_millis(1)).await; let map = sessions.read().await; if !map.contains_key(&key) && map.len() == 0 { break; } } { let map = sessions.read().await; assert!( !map.contains_key(&key), "should not contain the key after prune" ); assert_eq!(0, map.len(), "len should be 0, bit is {}", map.len()); } } #[tokio::test] async fn prune_sessions() { let t = TestHelper::default(); let mut sessions: Sessions = Arc::new(RwLock::new(HashMap::new())); let from: SocketAddr = "127.0.0.1:7000".parse().unwrap(); let to: SocketAddr = "127.0.0.1:7001".parse().unwrap(); let (send, _recv) = mpsc::channel::<Packet>(1); let endpoint = Endpoint::from_address(to); let key = SessionKey::from((from, to)); let ttl = Duration::from_secs(1); { let registry = Registry::default(); let mut sessions = sessions.write().await; sessions.insert( key.clone(), Session::new( &t.log, Metrics::new(&registry).unwrap(), FilterManager::fixed(Arc::new(FilterChain::new(vec![], &registry).unwrap())), from, endpoint.clone(), send, ttl, ) .await .unwrap(), ); } { let map = sessions.read().await; assert!(map.contains_key(&key)); assert_eq!(1, map.len()); } SessionManager::prune_sessions(&t.log, &mut sessions).await; { let map = sessions.read().await; assert!(map.contains_key(&key)); assert_eq!(1, map.len()); } tokio::time::sleep_until(tokio::time::Instant::now().add(ttl)).await; SessionManager::prune_sessions(&t.log, &mut sessions).await; { let map = sessions.read().await; assert!( !map.contains_key(&key), "should not contain the key after prune" ); assert_eq!(0, map.len(), "len should be 0, bit is {}", map.len()); } } }
/* * Copyright 2021 Google LLC * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this
p.len()); } } }
file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ use std::collections::HashMap; use std::sync::Arc; use std::time::{Duration, SystemTime, UNIX_EPOCH}; use slog::{debug, warn, Logger}; use tokio::sync::{watch, RwLock, RwLockReadGuard, RwLockWriteGuard}; use crate::proxy::sessions::{Session, SessionKey}; type SessionsMap = HashMap<SessionKey, Session>; type Sessions = Arc<RwLock<SessionsMap>>; pub const SESSION_TIMEOUT_SECONDS: u64 = 60; const SESSION_EXPIRY_POLL_INTERVAL: u64 = 60; #[derive(Clone)] pub struct SessionManager(Sessions); impl SessionManager { pub fn new(log: Logger, shutdown_rx: watch::Receiver<()>) -> Self { let poll_interval = Duration::from_secs(SESSION_EXPIRY_POLL_INTERVAL); let sessions: Sessions = Arc::new(RwLock::new(HashMap::new())); Self::run_prune_sessions(log.clone(), sessions.clone(), poll_interval, shutdown_rx); Self(sessions) } pub async fn get_sessions(&self) -> RwLockReadGuard<'_, SessionsMap> { self.0.read().await } pub async fn get_sessions_mut(&self) -> RwLockWriteGuard<'_, SessionsMap> { self.0.write().await } fn run_prune_sessions( log: Logger, mut sessions: Sessions, poll_interval: Duration, mut shutdown_rx: watch::Receiver<()>, ) { let mut interval = tokio::time::interval(poll_interval); tokio::spawn(async move { loop { tokio::select! { _ = shutdown_rx.changed() => { debug!(log, "Exiting Prune Sessions due to shutdown signal."); break; } _ = interval.tick() => { debug!(log, "Attempting to Prune Sessions"); Self::prune_sessions(&log, &mut sessions).await; } } } }); } async fn prune_sessions(log: &Logger, sessions: &mut Sessions) { let now = if let Ok(now) = SystemTime::now().duration_since(UNIX_EPOCH) { now.as_secs() } else { warn!(log, "Failed to get current time when pruning sessions"); return; }; let expired_keys = (*sessions.read().await) .iter() .filter(|(_, session)| session.expiration() <= now) .count(); if expired_keys != 0 { sessions .write() .await .retain(|_, session| session.expiration() > now); } } } #[cfg(test)] mod tests { use std::collections::HashMap; use std::net::SocketAddr; use std::ops::Add; use std::sync::Arc; use std::time::Duration; use prometheus::Registry; use tokio::sync::{mpsc, watch, RwLock}; use crate::cluster::Endpoint; use crate::filters::{manager::FilterManager, FilterChain}; use crate::proxy::sessions::metrics::Metrics; use crate::proxy::sessions::session_manager::Sessions; use crate::proxy::sessions::{Packet, Session, SessionKey}; use crate::test_utils::TestHelper; use super::SessionManager; #[tokio::test] async fn run_prune_sessions() { let t = TestHelper::default(); let sessions = Arc::new(RwLock::new(HashMap::new())); let from: SocketAddr = "127.0.0.1:7000".parse().unwrap(); let to: SocketAddr = "127.0.0.1:7001".parse().unwrap(); let (send, _recv) = mpsc::channel::<Packet>(1); let (_shutdown_tx, shutdown_rx) = watch::channel(()); let endpoint = Endpoint::from_address(to); let ttl = Duration::from_secs(1); let poll_interval = Duration::from_millis(1); SessionManager::run_prune_sessions( t.log.clone(), sessions.clone(), poll_interval, shutdown_rx, ); let key = SessionKey::from((from, to)); { let registry = Registry::default(); let mut sessions = sessions.write().await; sessions.insert( key.clone(), Session::new( &t.log, Metrics::new(&registry).unwrap(), FilterManager::fixed(Arc::new(FilterChain::new(vec![], &registry).unwrap())), from, endpoint.clone(), send, ttl, ) .await .unwrap(), ); } { let map = sessions.read().await; assert!(map.contains_key(&key)); assert_eq!(1, map.len()); } tokio::time::sleep_until(tokio::time::Instant::now().add(ttl)).await; for _ in 1..10000 { tokio::time::sleep(Duration::from_millis(1)).await; let map = sessions.read().await; if !map.contains_key(&key) && map.len() == 0 { break; } } { let map = sessions.read().await; assert!( !map.contains_key(&key), "should not contain the key after prune" ); assert_eq!(0, map.len(), "len should be 0, bit is {}", map.len()); } } #[tokio::test] async fn prune_sessions() { let t = TestHelper::default(); let mut sessions: Sessions = Arc::new(RwLock::new(HashMap::new())); let from: SocketAddr = "127.0.0.1:7000".parse().unwrap(); let to: SocketAddr = "127.0.0.1:7001".parse().unwrap(); let (send, _recv) = mpsc::channel::<Packet>(1); let endpoint = Endpoint::from_address(to); let key = SessionKey::from((from, to)); let ttl = Duration::from_secs(1); { let registry = Registry::default(); let mut sessions = sessions.write().await; sessions.insert( key.clone(), Session::new( &t.log, Metrics::new(&registry).unwrap(), FilterManager::fixed(Arc::new(FilterChain::new(vec![], &registry).unwrap())), from, endpoint.clone(), send, ttl, ) .await .unwrap(), ); } { let map = sessions.read().await; assert!(map.contains_key(&key)); assert_eq!(1, map.len()); } SessionManager::prune_sessions(&t.log, &mut sessions).await; { let map = sessions.read().await; assert!(map.contains_key(&key)); assert_eq!(1, map.len()); } tokio::time::sleep_until(tokio::time::Instant::now().add(ttl)).await; SessionManager::prune_sessions(&t.log, &mut sessions).await; { let map = sessions.read().await; assert!( !map.contains_key(&key), "should not contain the key after prune" ); assert_eq!(0, map.len(), "len should be 0, bit is {}", ma
random
[ { "content": "# Using Quilkin\n\n\n\nThere are two choices for running Quilkin:\n\n\n\n* Binary\n\n* Container image\n\n\n\nFor each version there is both a release version, which is optimised for production usage, and a debug version that \n\nhas debug level logging enabled.\n\n\n\n## Binary\n\n\n\nThe release binary can be downloaded from the \n\n[Github releases page](https://github.com/googleforgames/quilkin/releases).\n\n\n\nQuilkin needs to be run with an accompanying [configuration file](./proxy-configuration.md), like so:\n\n\n\n`quilkin --config=\"configuration.yaml\"`\n\n\n\nTo view debug output, run the same command with the `quilkin-debug` binary.\n\n\n\nYou can also use the shorthand of `-c` instead of `--config` if you so desire.\n\n\n\n## Container Image\n\n\n\nFor each release, there are both a release and debug container image built and hosted on Google Cloud \n\n[Artifact Registry](https://cloud.google.com/artifact-registry) listed for \n\neach [release](https://github.com/googleforgames/quilkin/releases).\n\n\n\nThe production release can be found under the tag: \n\n\n\n`us-docker.pkg.dev/quilkin/release/quilkin:{version}`\n\n\n\nWhereas, if you need debugging logging, use the following tag:\n\n\n\n`us-docker.pkg.dev/quilkin/release/quilkin:{version}-debug`\n\n\n\nMount your [configuration file](./proxy-configuration.md) at `/etc/quilkin/quilkin.yaml` to configure the Quilkin \n\ninstance inside the container.\n\n\n\nA [default configuration](https://github.com/googleforgames/quilkin/blob/examples/agones-sidecar/build/release/quilkin.yaml)\n\nis provided, such the container will start without a new configuration file, but it is configured to point to \n\n`127.0.0.1:0` as a no-op configuration.\n\n\n\nWhat's next:\n\n\n\n* Run through the [netcat with Quilkin quickstart](./quickstart-netcat.md)\n\n* Review our [example integration architectures](./integrations.md)\n", "file_path": "docs/src/using.md", "rank": 0, "score": 29462.870166724457 }, { "content": "/*\n\n * Copyright 2020 Google LLC\n\n *\n\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n\n * you may not use this file except in compliance with the License.\n\n * You may obtain a copy of the License at\n\n *\n\n * http://www.apache.org/licenses/LICENSE-2.0\n\n *\n\n * Unless required by applicable law or agreed to in writing, software\n\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n\n * See the License for the specific language governing permissions and\n\n * limitations under the License.\n\n */\n\n\n\nuse std::sync::Arc;\n\n\n\nconst VERSION: &str = env!(\"CARGO_PKG_VERSION\");\n\n\n", "file_path": "src/main.rs", "rank": 1, "score": 28.109729893143378 }, { "content": "/*\n\n * Copyright 2020 Google LLC\n\n *\n\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n\n * you may not use this file except in compliance with the License.\n\n * You may obtain a copy of the License at\n\n *\n\n * http://www.apache.org/licenses/LICENSE-2.0\n\n *\n\n * Unless required by applicable law or agreed to in writing, software\n\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n\n * See the License for the specific language governing permissions and\n\n * limitations under the License.\n\n */\n\n\n\nuse super::{Config, Filter};\n\nuse crate::config::{Admin, EndPoint, Proxy, Source, Version};\n\n\n\n/// Builder for a [`Config`]\n", "file_path": "src/config/builder.rs", "rank": 2, "score": 27.501866129889507 }, { "content": "/*\n\n * Copyright 2021 Google LLC\n\n *\n\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n\n * you may not use this file except in compliance with the License.\n\n * You may obtain a copy of the License at\n\n *\n\n * http://www.apache.org/licenses/LICENSE-2.0\n\n *\n\n * Unless required by applicable law or agreed to in writing, software\n\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n\n * See the License for the specific language governing permissions and\n\n * limitations under the License.\n\n */\n\n\n\nuse std::convert::TryFrom;\n\n\n\nuse bytes::Bytes;\n\n\n", "file_path": "src/config/config_type.rs", "rank": 3, "score": 27.39115914664894 }, { "content": "/*\n\n * Copyright 2021 Google LLC\n\n *\n\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n\n * you may not use this file except in compliance with the License.\n\n * You may obtain a copy of the License at\n\n *\n\n * http://www.apache.org/licenses/LICENSE-2.0\n\n *\n\n * Unless required by applicable law or agreed to in writing, software\n\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n\n * See the License for the specific language governing permissions and\n\n * limitations under the License.\n\n */\n\n\n\nuse std::iter::FromIterator;\n\n\n\nuse slog::Logger;\n\n\n", "file_path": "src/filters/set.rs", "rank": 4, "score": 27.39115914664894 }, { "content": "/*\n\n * Copyright 2021 Google LLC\n\n *\n\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n\n * you may not use this file except in compliance with the License.\n\n * You may obtain a copy of the License at\n\n *\n\n * http://www.apache.org/licenses/LICENSE-2.0\n\n *\n\n * Unless required by applicable law or agreed to in writing, software\n\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n\n * See the License for the specific language governing permissions and\n\n * limitations under the License.\n\n */\n\n\n\nuse std::convert::TryFrom;\n\n\n\nuse serde::{Deserialize, Serialize};\n\n\n", "file_path": "src/filters/compress/config.rs", "rank": 5, "score": 27.264173966777147 }, { "content": "/*\n\n * Copyright 2021 Google LLC\n\n *\n\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n\n * you may not use this file except in compliance with the License.\n\n * You may obtain a copy of the License at\n\n *\n\n * http://www.apache.org/licenses/LICENSE-2.0\n\n *\n\n * Unless required by applicable law or agreed to in writing, software\n\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n\n * See the License for the specific language governing permissions and\n\n * limitations under the License.\n\n */\n\n\n\nuse std::sync::Arc;\n\n\n\nuse slog::{info, o};\n\nuse tokio::{signal, sync::watch};\n", "file_path": "src/runner.rs", "rank": 6, "score": 27.08716886942441 }, { "content": "/*\n\n * Copyright 2020 Google LLC\n\n *\n\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n\n * you may not use this file except in compliance with the License.\n\n * You may obtain a copy of the License at\n\n *\n\n * http://www.apache.org/licenses/LICENSE-2.0\n\n *\n\n * Unless required by applicable law or agreed to in writing, software\n\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n\n * See the License for the specific language governing permissions and\n\n * limitations under the License.\n\n */\n\n\n\nuse std::any::Any;\n\nuse std::collections::HashMap;\n\nuse std::convert::TryFrom;\n\nuse std::fmt;\n", "file_path": "src/extensions/filter_registry.rs", "rank": 7, "score": 27.065874769638988 }, { "content": "/*\n\n * Copyright 2021 Google LLC\n\n *\n\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n\n * you may not use this file except in compliance with the License.\n\n * You may obtain a copy of the License at\n\n *\n\n * http://www.apache.org/licenses/LICENSE-2.0\n\n *\n\n * Unless required by applicable law or agreed to in writing, software\n\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n\n * See the License for the specific language governing permissions and\n\n * limitations under the License.\n\n */\n\n\n\nmod include;\n\n\n\nuse quote::ToTokens;\n\nuse syn::parse_macro_input;\n", "file_path": "macros/src/lib.rs", "rank": 8, "score": 27.013931771474194 }, { "content": "/*\n\n * Copyright 2021 Google LLC All Rights Reserved.\n\n *\n\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n\n * you may not use this file except in compliance with the License.\n\n * You may obtain a copy of the License at\n\n *\n\n * http://www.apache.org/licenses/LICENSE-2.0\n\n *\n\n * Unless required by applicable law or agreed to in writing, software\n\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n\n * See the License for the specific language governing permissions and\n\n * limitations under the License.\n\n */\n\n\n\nuse std::convert::TryFrom;\n\n\n\nuse serde::{Deserialize, Serialize};\n\n\n", "file_path": "src/filters/capture_bytes/config.rs", "rank": 9, "score": 27.013931771474194 }, { "content": "/*\n\n * Copyright 2021 Google LLC\n\n *\n\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n\n * you may not use this file except in compliance with the License.\n\n * You may obtain a copy of the License at\n\n *\n\n * http://www.apache.org/licenses/LICENSE-2.0\n\n *\n\n * Unless required by applicable law or agreed to in writing, software\n\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n\n * See the License for the specific language governing permissions and\n\n * limitations under the License.\n\n */\n\n\n\nuse std::net::SocketAddr;\n\n\n\nuse slog::info;\n\nuse tokio::time::{timeout, Duration};\n", "file_path": "tests/compress.rs", "rank": 10, "score": 26.968205777413978 }, { "content": "/*\n\n * Copyright 2021 Google LLC\n\n *\n\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n\n * you may not use this file except in compliance with the License.\n\n * You may obtain a copy of the License at\n\n *\n\n * http://www.apache.org/licenses/LICENSE-2.0\n\n *\n\n * Unless required by applicable law or agreed to in writing, software\n\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n\n * See the License for the specific language governing permissions and\n\n * limitations under the License.\n\n */\n\n\n\nuse std::convert::Infallible;\n\nuse std::net::SocketAddr;\n\nuse std::sync::Arc;\n\n\n", "file_path": "src/proxy/admin.rs", "rank": 11, "score": 26.968205777413978 }, { "content": "/*\n\n * Copyright 2021 Google LLC\n\n *\n\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n\n * you may not use this file except in compliance with the License.\n\n * You may obtain a copy of the License at\n\n *\n\n * http://www.apache.org/licenses/LICENSE-2.0\n\n *\n\n * Unless required by applicable law or agreed to in writing, software\n\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n\n * See the License for the specific language governing permissions and\n\n * limitations under the License.\n\n */\n\n\n\nuse std::io;\n\n\n\nuse snap::read::FrameDecoder;\n\nuse snap::write::FrameEncoder;\n", "file_path": "src/filters/compress/compressor.rs", "rank": 12, "score": 26.968205777413978 }, { "content": "/*\n\n * Copyright 2020 Google LLC\n\n *\n\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n\n * you may not use this file except in compliance with the License.\n\n * You may obtain a copy of the License at\n\n *\n\n * http://www.apache.org/licenses/LICENSE-2.0\n\n *\n\n * Unless required by applicable law or agreed to in writing, software\n\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n\n * See the License for the specific language governing permissions and\n\n * limitations under the License.\n\n */\n\n\n\nuse std::collections::HashMap;\n\n\n\nuse crate::xds::google::rpc::Status as GrpcStatus;\n\nuse backoff::{backoff::Backoff, exponential::ExponentialBackoff, Clock, SystemClock};\n", "file_path": "src/xds/ads_client.rs", "rank": 13, "score": 26.9603201686019 }, { "content": "/*\n\n * Copyright 2021 Google LLC\n\n *\n\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n\n * you may not use this file except in compliance with the License.\n\n * You may obtain a copy of the License at\n\n *\n\n * http://www.apache.org/licenses/LICENSE-2.0\n\n *\n\n * Unless required by applicable law or agreed to in writing, software\n\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n\n * See the License for the specific language governing permissions and\n\n * limitations under the License.\n\n */\n\n\n\nuse crate::config::ValidationError;\n\nuse prometheus::Error as MetricsError;\n\n\n\n#[cfg(doc)]\n", "file_path": "src/filters/error.rs", "rank": 14, "score": 26.890636632286384 }, { "content": "/*\n\n * Copyright 2020 Google LLC\n\n *\n\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n\n * you may not use this file except in compliance with the License.\n\n * You may obtain a copy of the License at\n\n *\n\n * http://www.apache.org/licenses/LICENSE-2.0\n\n *\n\n * Unless required by applicable law or agreed to in writing, software\n\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n\n * See the License for the specific language governing permissions and\n\n * limitations under the License.\n\n */\n\n\n\n//! Quilkin configuration.\n\n\n\nuse std::net::SocketAddr;\n\n\n", "file_path": "src/config.rs", "rank": 15, "score": 26.873395337169445 }, { "content": "/*\n\n * Copyright 2020 Google LLC\n\n *\n\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n\n * you may not use this file except in compliance with the License.\n\n * You may obtain a copy of the License at\n\n *\n\n * http://www.apache.org/licenses/LICENSE-2.0\n\n *\n\n * Unless required by applicable law or agreed to in writing, software\n\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n\n * See the License for the specific language governing permissions and\n\n * limitations under the License.\n\n */\n\n\n\nuse std::convert::TryFrom;\n\n\n\nuse base64_serde::base64_serde_type;\n\nuse serde::{Deserialize, Serialize};\n", "file_path": "src/filters/extensions/concatenate_bytes.rs", "rank": 16, "score": 26.85037548782757 }, { "content": "/*\n\n * Copyright 2021 Google LLC\n\n *\n\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n\n * you may not use this file except in compliance with the License.\n\n * You may obtain a copy of the License at\n\n *\n\n * http://www.apache.org/licenses/LICENSE-2.0\n\n *\n\n * Unless required by applicable law or agreed to in writing, software\n\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n\n * See the License for the specific language governing permissions and\n\n * limitations under the License.\n\n */\n\n\n", "file_path": "examples/quilkin-filter-example/build.rs", "rank": 17, "score": 26.789019746778724 }, { "content": "/*\n\n * Copyright 2021 Google LLC\n\n *\n\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n\n * you may not use this file except in compliance with the License.\n\n * You may obtain a copy of the License at\n\n *\n\n * http://www.apache.org/licenses/LICENSE-2.0\n\n *\n\n * Unless required by applicable law or agreed to in writing, software\n\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n\n * See the License for the specific language governing permissions and\n\n * limitations under the License.\n\n */\n\n\n\nuse std::{any::Any, collections::HashMap, net::SocketAddr};\n\n\n\nuse crate::cluster::Endpoint;\n\n\n", "file_path": "src/filters/write.rs", "rank": 18, "score": 26.76853405246387 }, { "content": "/*\n\n * Copyright 2020 Google LLC\n\n *\n\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n\n * you may not use this file except in compliance with the License.\n\n * You may obtain a copy of the License at\n\n *\n\n * http://www.apache.org/licenses/LICENSE-2.0\n\n *\n\n * Unless required by applicable law or agreed to in writing, software\n\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n\n * See the License for the specific language governing permissions and\n\n * limitations under the License.\n\n */\n\n\n\nuse std::net::{IpAddr, Ipv4Addr, SocketAddr};\n\n\n\nuse slog::info;\n\n\n", "file_path": "tests/metrics.rs", "rank": 19, "score": 26.76853405246387 }, { "content": "/*\n\n * Copyright 2021 Google LLC\n\n *\n\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n\n * you may not use this file except in compliance with the License.\n\n * You may obtain a copy of the License at\n\n *\n\n * http://www.apache.org/licenses/LICENSE-2.0\n\n *\n\n * Unless required by applicable law or agreed to in writing, software\n\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n\n * See the License for the specific language governing permissions and\n\n * limitations under the License.\n\n */\n\n\n\nuse quilkin::filters::prelude::*;\n\n\n\nuse bytes::Bytes;\n\nuse serde::{Deserialize, Serialize};\n\n\n\n#[derive(Serialize, Deserialize, Debug)]\n", "file_path": "examples/quilkin-filter-example/src/main.rs", "rank": 20, "score": 26.733660958935893 }, { "content": "/*\n\n * Copyright 2020 Google LLC\n\n *\n\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n\n * you may not use this file except in compliance with the License.\n\n * You may obtain a copy of the License at\n\n *\n\n * http://www.apache.org/licenses/LICENSE-2.0\n\n *\n\n * Unless required by applicable law or agreed to in writing, software\n\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n\n * See the License for the specific language governing permissions and\n\n * limitations under the License.\n\n */\n\n\n\nuse std::convert::TryFrom;\n\nuse std::sync::atomic::{AtomicUsize, Ordering};\n\n\n\nuse rand::{thread_rng, Rng};\n", "file_path": "src/filters/extensions/load_balancer.rs", "rank": 21, "score": 26.61804550168358 }, { "content": "/*\n\n * Copyright 2020 Google LLC\n\n *\n\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n\n * you may not use this file except in compliance with the License.\n\n * You may obtain a copy of the License at\n\n *\n\n * http://www.apache.org/licenses/LICENSE-2.0\n\n *\n\n * Unless required by applicable law or agreed to in writing, software\n\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n\n * See the License for the specific language governing permissions and\n\n * limitations under the License.\n\n */\n\n\n\nuse hyper::{Body, Response, StatusCode};\n\nuse prometheus::{Encoder, Registry, TextEncoder};\n\nuse slog::{o, warn, Logger};\n\n\n", "file_path": "src/proxy/metrics.rs", "rank": 22, "score": 26.61804550168358 }, { "content": "/*\n\n * Copyright 2021 Google LLC\n\n *\n\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n\n * you may not use this file except in compliance with the License.\n\n * You may obtain a copy of the License at\n\n *\n\n * http://www.apache.org/licenses/LICENSE-2.0\n\n *\n\n * Unless required by applicable law or agreed to in writing, software\n\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n\n * See the License for the specific language governing permissions and\n\n * limitations under the License.\n\n */\n\n\n\nuse std::sync::atomic::AtomicBool;\n\n\n\nuse hyper::{Body, Response, StatusCode};\n\nuse slog::{error, o, Logger};\n", "file_path": "src/proxy/health.rs", "rank": 23, "score": 26.61804550168358 }, { "content": "/*\n\n * Copyright 2020 Google LLC\n\n *\n\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n\n * you may not use this file except in compliance with the License.\n\n * You may obtain a copy of the License at\n\n *\n\n * http://www.apache.org/licenses/LICENSE-2.0\n\n *\n\n * Unless required by applicable law or agreed to in writing, software\n\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n\n * See the License for the specific language governing permissions and\n\n * limitations under the License.\n\n */\n\n\n\nuse std::fmt::{self, Display, Formatter};\n\n\n\n#[derive(Debug)]\n\npub enum Error {\n", "file_path": "src/proxy/sessions/error.rs", "rank": 24, "score": 26.615323822714807 }, { "content": "/*\n\n * Copyright 2020 Google LLC\n\n *\n\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n\n * you may not use this file except in compliance with the License.\n\n * You may obtain a copy of the License at\n\n *\n\n * http://www.apache.org/licenses/LICENSE-2.0\n\n *\n\n * Unless required by applicable law or agreed to in writing, software\n\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n\n * See the License for the specific language governing permissions and\n\n * limitations under the License.\n\n */\n\n\n\n// TODO Move endpoint.rs out of config/ into cluster/\n\nuse crate::cluster::Endpoint;\n\nuse std::sync::Arc;\n\n\n", "file_path": "src/config/endpoints.rs", "rank": 25, "score": 26.527834652397658 }, { "content": "/*\n\n * Copyright 2020 Google LLC\n\n *\n\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n\n * you may not use this file except in compliance with the License.\n\n * You may obtain a copy of the License at\n\n *\n\n * http://www.apache.org/licenses/LICENSE-2.0\n\n *\n\n * Unless required by applicable law or agreed to in writing, software\n\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n\n * See the License for the specific language governing permissions and\n\n * limitations under the License.\n\n */\n\n\n\nuse std::net::{IpAddr, Ipv4Addr, SocketAddr};\n\n\n\nuse tokio::time::{timeout, Duration};\n\n\n", "file_path": "tests/concatenate_bytes.rs", "rank": 26, "score": 26.527834652397658 }, { "content": "/*\n\n * Copyright 2020 Google LLC\n\n *\n\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n\n * you may not use this file except in compliance with the License.\n\n * You may obtain a copy of the License at\n\n *\n\n * http://www.apache.org/licenses/LICENSE-2.0\n\n *\n\n * Unless required by applicable law or agreed to in writing, software\n\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n\n * See the License for the specific language governing permissions and\n\n * limitations under the License.\n\n */\n\n\n\nuse std::net::{IpAddr, Ipv4Addr, SocketAddr};\n\n\n\nuse tokio::time::{timeout, Duration};\n\n\n", "file_path": "tests/token_router.rs", "rank": 27, "score": 26.527834652397658 }, { "content": "/*\n\n * Copyright 2020 Google LLC\n\n *\n\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n\n * you may not use this file except in compliance with the License.\n\n * You may obtain a copy of the License at\n\n *\n\n * http://www.apache.org/licenses/LICENSE-2.0\n\n *\n\n * Unless required by applicable law or agreed to in writing, software\n\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n\n * See the License for the specific language governing permissions and\n\n * limitations under the License.\n\n */\n\n\n\nuse std::net::{IpAddr, Ipv4Addr, SocketAddr};\n\n\n\nuse tokio::time::{timeout, Duration};\n\n\n", "file_path": "tests/local_rate_limit.rs", "rank": 28, "score": 26.527834652397658 }, { "content": "/*\n\n * Copyright 2020 Google LLC\n\n *\n\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n\n * you may not use this file except in compliance with the License.\n\n * You may obtain a copy of the License at\n\n *\n\n * http://www.apache.org/licenses/LICENSE-2.0\n\n *\n\n * Unless required by applicable law or agreed to in writing, software\n\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n\n * See the License for the specific language governing permissions and\n\n * limitations under the License.\n\n */\n\n\n\nuse std::net::{IpAddr, Ipv4Addr, SocketAddr};\n\n\n\nuse tokio::select;\n\nuse tokio::time::{sleep, Duration};\n", "file_path": "tests/no_filter.rs", "rank": 29, "score": 26.50351277040108 }, { "content": "/*\n\n * Copyright 2020 Google LLC\n\n *\n\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n\n * you may not use this file except in compliance with the License.\n\n * You may obtain a copy of the License at\n\n *\n\n * http://www.apache.org/licenses/LICENSE-2.0\n\n *\n\n * Unless required by applicable law or agreed to in writing, software\n\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n\n * See the License for the specific language governing permissions and\n\n * limitations under the License.\n\n */\n\n\n\nuse crate::proxy::sessions::error::Error as SessionError;\n\nuse std::fmt::{self, Display, Formatter};\n\n\n\n#[derive(Debug)]\n", "file_path": "src/proxy/server/error.rs", "rank": 30, "score": 26.40920280377095 }, { "content": "/*\n\n * Copyright 2021 Google LLC\n\n *\n\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n\n * you may not use this file except in compliance with the License.\n\n * You may obtain a copy of the License at\n\n *\n\n * http://www.apache.org/licenses/LICENSE-2.0\n\n *\n\n * Unless required by applicable law or agreed to in writing, software\n\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n\n * See the License for the specific language governing permissions and\n\n * limitations under the License.\n\n */\n\n\n\n///! Complex integration tests that incorporate multiple elements\n\nuse std::net::SocketAddr;\n\nuse std::str::from_utf8;\n\n\n", "file_path": "tests/filter_order.rs", "rank": 31, "score": 26.40920280377095 }, { "content": "/*\n\n * Copyright 2020 Google LLC\n\n *\n\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n\n * you may not use this file except in compliance with the License.\n\n * You may obtain a copy of the License at\n\n *\n\n * http://www.apache.org/licenses/LICENSE-2.0\n\n *\n\n * Unless required by applicable law or agreed to in writing, software\n\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n\n * See the License for the specific language governing permissions and\n\n * limitations under the License.\n\n */\n\n\n\nuse std::convert::{TryFrom, TryInto};\n\nuse std::sync::atomic::{AtomicUsize, Ordering};\n\nuse std::sync::Arc;\n\nuse std::time::Duration;\n", "file_path": "src/filters/local_rate_limit.rs", "rank": 32, "score": 26.390444481251627 }, { "content": "/*\n\n * Copyright 2021 Google LLC\n\n *\n\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n\n * you may not use this file except in compliance with the License.\n\n * You may obtain a copy of the License at\n\n *\n\n * http://www.apache.org/licenses/LICENSE-2.0\n\n *\n\n * Unless required by applicable law or agreed to in writing, software\n\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n\n * See the License for the specific language governing permissions and\n\n * limitations under the License.\n\n */\n\n\n\nuse proc_macro2::{Span, TokenStream};\n\nuse quote::{ToTokens, TokenStreamExt};\n\nuse syn::parse::{Parse, ParseStream};\n\n\n", "file_path": "macros/src/include.rs", "rank": 33, "score": 26.390046753812975 }, { "content": "/*\n\n * Copyright 2020 Google LLC\n\n *\n\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n\n * you may not use this file except in compliance with the License.\n\n * You may obtain a copy of the License at\n\n *\n\n * http://www.apache.org/licenses/LICENSE-2.0\n\n *\n\n * Unless required by applicable law or agreed to in writing, software\n\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n\n * See the License for the specific language governing permissions and\n\n * limitations under the License.\n\n */\n\n\n\n// This build script is used to generate the rust source files that\n\n// we need for XDS GRPC communication.\n", "file_path": "build.rs", "rank": 34, "score": 26.36235846264856 }, { "content": "/*\n\n * Copyright 2020 Google LLC\n\n *\n\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n\n * you may not use this file except in compliance with the License.\n\n * You may obtain a copy of the License at\n\n *\n\n * http://www.apache.org/licenses/LICENSE-2.0\n\n *\n\n * Unless required by applicable law or agreed to in writing, software\n\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n\n * See the License for the specific language governing permissions and\n\n * limitations under the License.\n\n */\n\n\n\nuse std::{\n\n net::{IpAddr, Ipv4Addr, SocketAddr},\n\n sync::Arc,\n\n};\n", "file_path": "tests/filters.rs", "rank": 35, "score": 26.36235846264856 }, { "content": "/*\n\n * Copyright 2021 Google LLC\n\n *\n\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n\n * you may not use this file except in compliance with the License.\n\n * You may obtain a copy of the License at\n\n *\n\n * http://www.apache.org/licenses/LICENSE-2.0\n\n *\n\n * Unless required by applicable law or agreed to in writing, software\n\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n\n * See the License for the specific language governing permissions and\n\n * limitations under the License.\n\n */\n\n\n\nuse crate::filters::{chain::Error as FilterChainError, FilterChain, FilterRegistry};\n\n\n\nuse std::sync::Arc;\n\n\n", "file_path": "src/filters/manager.rs", "rank": 36, "score": 26.291693438097678 }, { "content": "/*\n\n * Copyright 2020 Google LLC\n\n *\n\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n\n * you may not use this file except in compliance with the License.\n\n * You may obtain a copy of the License at\n\n *\n\n * http://www.apache.org/licenses/LICENSE-2.0\n\n *\n\n * Unless required by applicable law or agreed to in writing, software\n\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n\n * See the License for the specific language governing permissions and\n\n * limitations under the License.\n\n */\n\n\n\nuse std::sync::Arc;\n\n\n\nuse crate::filters::{CreateFilterArgs, Error, Filter, FilterMap, FilterSet};\n\n\n", "file_path": "src/filters/registry.rs", "rank": 37, "score": 26.291693438097678 }, { "content": "/*\n\n * Copyright 2021 Google LLC\n\n *\n\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n\n * you may not use this file except in compliance with the License.\n\n * You may obtain a copy of the License at\n\n *\n\n * http://www.apache.org/licenses/LICENSE-2.0\n\n *\n\n * Unless required by applicable law or agreed to in writing, software\n\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n\n * See the License for the specific language governing permissions and\n\n * limitations under the License.\n\n */\n\n\n\nuse quilkin::config::{Admin, Builder, EndPoint};\n\nuse quilkin::test_utils::TestHelper;\n\nuse quilkin::Builder as ProxyBuilder;\n\nuse std::panic;\n", "file_path": "tests/health.rs", "rank": 38, "score": 26.281486958197668 }, { "content": "/*\n\n * Copyright 2020 Google LLC\n\n *\n\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n\n * you may not use this file except in compliance with the License.\n\n * You may obtain a copy of the License at\n\n *\n\n * http://www.apache.org/licenses/LICENSE-2.0\n\n *\n\n * Unless required by applicable law or agreed to in writing, software\n\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n\n * See the License for the specific language governing permissions and\n\n * limitations under the License.\n\n */\n\n\n\nuse std::{collections::HashSet, convert::TryInto, marker::PhantomData, sync::Arc};\n\n\n\nuse prometheus::Registry;\n\nuse slog::{o, Drain, Logger};\n", "file_path": "src/proxy/builder.rs", "rank": 39, "score": 26.277631766331474 }, { "content": "/*\n\n * Copyright 2020 Google LLC\n\n *\n\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n\n * you may not use this file except in compliance with the License.\n\n * You may obtain a copy of the License at\n\n *\n\n * http://www.apache.org/licenses/LICENSE-2.0\n\n *\n\n * Unless required by applicable law or agreed to in writing, software\n\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n\n * See the License for the specific language governing permissions and\n\n * limitations under the License.\n\n */\n\n\n\npub(crate) mod debug;\n", "file_path": "src/utils.rs", "rank": 40, "score": 26.228502752601575 }, { "content": "/*\n\n * Copyright 2020 Google LLC\n\n *\n\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n\n * you may not use this file except in compliance with the License.\n\n * You may obtain a copy of the License at\n\n *\n\n * http://www.apache.org/licenses/LICENSE-2.0\n\n *\n\n * Unless required by applicable law or agreed to in writing, software\n\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n\n * See the License for the specific language governing permissions and\n\n * limitations under the License.\n\n */\n\n\n\nuse std::net::{Ipv4Addr, SocketAddr, SocketAddrV4};\n\nuse std::result::Result as StdResult;\n\nuse std::sync::Arc;\n\n\n", "file_path": "src/proxy/server.rs", "rank": 41, "score": 26.166252439624714 }, { "content": "/*\n\n * Copyright 2020 Google LLC\n\n *\n\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n\n * you may not use this file except in compliance with the License.\n\n * You may obtain a copy of the License at\n\n *\n\n * http://www.apache.org/licenses/LICENSE-2.0\n\n *\n\n * Unless required by applicable law or agreed to in writing, software\n\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n\n * See the License for the specific language governing permissions and\n\n * limitations under the License.\n\n */\n\n\n\nuse std::fmt::{self, Display, Formatter};\n\n\n\n#[derive(Debug, PartialEq)]\n\npub struct ValueInvalidArgs {\n", "file_path": "src/config/error.rs", "rank": 42, "score": 26.11434398765573 }, { "content": "/*\n\n * Copyright 2021 Google LLC\n\n *\n\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n\n * you may not use this file except in compliance with the License.\n\n * You may obtain a copy of the License at\n\n *\n\n * http://www.apache.org/licenses/LICENSE-2.0\n\n *\n\n * Unless required by applicable law or agreed to in writing, software\n\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n\n * See the License for the specific language governing permissions and\n\n * limitations under the License.\n\n */\n\n\n\ncrate::include_proto!(\"quilkin.extensions.filters.load_balancer.v1alpha1\");\n\n\n\nuse std::convert::TryFrom;\n\n\n", "file_path": "src/filters/load_balancer/config.rs", "rank": 43, "score": 26.11434398765573 }, { "content": "/*\n\n * Copyright 2021 Google LLC\n\n *\n\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n\n * you may not use this file except in compliance with the License.\n\n * You may obtain a copy of the License at\n\n *\n\n * http://www.apache.org/licenses/LICENSE-2.0\n\n *\n\n * Unless required by applicable law or agreed to in writing, software\n\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n\n * See the License for the specific language governing permissions and\n\n * limitations under the License.\n\n */\n\n\n\ncrate::include_proto!(\"quilkin.extensions.filters.concatenate_bytes.v1alpha1\");\n\n\n\nuse std::convert::TryFrom;\n\n\n", "file_path": "src/filters/concatenate_bytes/config.rs", "rank": 44, "score": 26.11434398765573 }, { "content": "/*\n\n * Copyright 2021 Google LLC\n\n *\n\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n\n * you may not use this file except in compliance with the License.\n\n * You may obtain a copy of the License at\n\n *\n\n * http://www.apache.org/licenses/LICENSE-2.0\n\n *\n\n * Unless required by applicable law or agreed to in writing, software\n\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n\n * See the License for the specific language governing permissions and\n\n * limitations under the License.\n\n */\n\n\n\nuse crate::metrics::{opts, CollectorExt};\n\nuse prometheus::core::{AtomicI64, GenericGauge};\n\nuse prometheus::Result as MetricsResult;\n\nuse prometheus::{IntGauge, Registry};\n", "file_path": "src/cluster/metrics.rs", "rank": 45, "score": 26.066535354302708 }, { "content": "/*\n\n * Copyright 2020 Google LLC\n\n *\n\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n\n * you may not use this file except in compliance with the License.\n\n * You may obtain a copy of the License at\n\n *\n\n * http://www.apache.org/licenses/LICENSE-2.0\n\n *\n\n * Unless required by applicable law or agreed to in writing, software\n\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n\n * See the License for the specific language governing permissions and\n\n * limitations under the License.\n\n */\n\n\n\npub(crate) use admin::Admin;\n\npub use builder::{logger, Builder, PendingValidation, Validated};\n\npub(crate) use health::Health;\n\npub(crate) use metrics::Metrics;\n", "file_path": "src/proxy.rs", "rank": 46, "score": 26.066535354302708 }, { "content": "/*\n\n * Copyright 2020 Google LLC\n\n *\n\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n\n * you may not use this file except in compliance with the License.\n\n * You may obtain a copy of the License at\n\n *\n\n * http://www.apache.org/licenses/LICENSE-2.0\n\n *\n\n * Unless required by applicable law or agreed to in writing, software\n\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n\n * See the License for the specific language governing permissions and\n\n * limitations under the License.\n\n */\n\n\n\n/// Common utilities for testing\n\nuse std::net::{Ipv4Addr, SocketAddr, SocketAddrV4};\n\nuse std::str::from_utf8;\n\nuse std::sync::Arc;\n", "file_path": "src/test_utils.rs", "rank": 47, "score": 26.055893714449482 }, { "content": "/*\n\n * Copyright 2020 Google LLC\n\n *\n\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n\n * you may not use this file except in compliance with the License.\n\n * You may obtain a copy of the License at\n\n *\n\n * http://www.apache.org/licenses/LICENSE-2.0\n\n *\n\n * Unless required by applicable law or agreed to in writing, software\n\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n\n * See the License for the specific language governing permissions and\n\n * limitations under the License.\n\n */\n\n\n\nuse crate::metrics::{filter_opts, CollectorExt};\n\nuse prometheus::core::{AtomicU64, GenericCounter};\n\nuse prometheus::Result as MetricsResult;\n\nuse prometheus::{IntCounter, Registry};\n", "file_path": "src/filters/local_rate_limit/metrics.rs", "rank": 48, "score": 25.96051288296627 }, { "content": "/*\n\n * Copyright 2020 Google LLC\n\n *\n\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n\n * you may not use this file except in compliance with the License.\n\n * You may obtain a copy of the License at\n\n *\n\n * http://www.apache.org/licenses/LICENSE-2.0\n\n *\n\n * Unless required by applicable law or agreed to in writing, software\n\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n\n * See the License for the specific language governing permissions and\n\n * limitations under the License.\n\n */\n\nuse prometheus::core::{AtomicU64, GenericCounter};\n\nuse prometheus::Result as MetricsResult;\n\nuse prometheus::{IntCounter, Registry};\n\n\n\nuse crate::metrics::{filter_opts, CollectorExt};\n", "file_path": "src/filters/capture_bytes/metrics.rs", "rank": 49, "score": 25.96051288296627 }, { "content": "/*\n\n * Copyright 2020 Google LLC\n\n *\n\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n\n * you may not use this file except in compliance with the License.\n\n * You may obtain a copy of the License at\n\n *\n\n * http://www.apache.org/licenses/LICENSE-2.0\n\n *\n\n * Unless required by applicable law or agreed to in writing, software\n\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n\n * See the License for the specific language governing permissions and\n\n * limitations under the License.\n\n */\n\n\n\nmod compressor;\n\nmod config;\n\nmod metrics;\n\n\n", "file_path": "src/filters/compress.rs", "rank": 50, "score": 25.957241677709625 }, { "content": "/*\n\n * Copyright 2020 Google LLC\n\n *\n\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n\n * you may not use this file except in compliance with the License.\n\n * You may obtain a copy of the License at\n\n *\n\n * http://www.apache.org/licenses/LICENSE-2.0\n\n *\n\n * Unless required by applicable law or agreed to in writing, software\n\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n\n * See the License for the specific language governing permissions and\n\n * limitations under the License.\n\n */\n\n\n\nuse crate::metrics::{opts, CollectorExt};\n\nuse prometheus::core::{AtomicU64, GenericCounter};\n\nuse prometheus::{IntCounterVec, Registry, Result as MetricsResult};\n\n\n", "file_path": "src/proxy/server/metrics.rs", "rank": 51, "score": 25.94654083273881 }, { "content": "/*\n\n * Copyright 2020 Google LLC\n\n *\n\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n\n * you may not use this file except in compliance with the License.\n\n * You may obtain a copy of the License at\n\n *\n\n * http://www.apache.org/licenses/LICENSE-2.0\n\n *\n\n * Unless required by applicable law or agreed to in writing, software\n\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n\n * See the License for the specific language governing permissions and\n\n * limitations under the License.\n\n */\n\n\n\n#[allow(warnings)]\n\nquilkin::include_proto!(\"xds.core.v3\");\n\n#[allow(warnings)]\n\nquilkin::include_proto!(\"google.rpc\");\n", "file_path": "tests/xds.rs", "rank": 52, "score": 25.915027220505824 }, { "content": "/*\n\n * Copyright 2021 Google LLC\n\n *\n\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n\n * you may not use this file except in compliance with the License.\n\n * You may obtain a copy of the License at\n\n *\n\n * http://www.apache.org/licenses/LICENSE-2.0\n\n *\n\n * Unless required by applicable law or agreed to in writing, software\n\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n\n * See the License for the specific language governing permissions and\n\n * limitations under the License.\n\n */\n\n\n\nuse crate::metrics::{opts, CollectorExt};\n\nuse prometheus::core::{AtomicU64, GenericCounter, GenericGauge};\n\nuse prometheus::Result as MetricsResult;\n\nuse prometheus::{IntCounter, Registry};\n", "file_path": "src/xds/metrics.rs", "rank": 53, "score": 25.855440838971905 }, { "content": "/*\n\n * Copyright 2020 Google LLC\n\n *\n\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n\n * you may not use this file except in compliance with the License.\n\n * You may obtain a copy of the License at\n\n *\n\n * http://www.apache.org/licenses/LICENSE-2.0\n\n *\n\n * Unless required by applicable law or agreed to in writing, software\n\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n\n * See the License for the specific language governing permissions and\n\n * limitations under the License.\n\n */\n\n\n\nuse std::net::{IpAddr, Ipv4Addr, SocketAddr};\n\nuse std::sync::{Arc, Mutex};\n\n\n\nuse quilkin::config::{Builder as ConfigBuilder, EndPoint, Filter};\n", "file_path": "tests/load_balancer.rs", "rank": 54, "score": 25.83817932993502 }, { "content": "/*\n\n * Copyright 2020 Google LLC\n\n *\n\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n\n * you may not use this file except in compliance with the License.\n\n * You may obtain a copy of the License at\n\n *\n\n * http://www.apache.org/licenses/LICENSE-2.0\n\n *\n\n * Unless required by applicable law or agreed to in writing, software\n\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n\n * See the License for the specific language governing permissions and\n\n * limitations under the License.\n\n */\n\n\n\nuse prometheus::{Error as PrometheusError, Histogram, HistogramOpts, Registry};\n\n\n\nuse crate::config::{Filter as FilterConfig, ValidationError};\n\nuse crate::filters::{prelude::*, FilterRegistry};\n", "file_path": "src/filters/chain.rs", "rank": 55, "score": 25.83817932993502 }, { "content": "/*\n\n * Copyright 2020 Google LLC\n\n *\n\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n\n * you may not use this file except in compliance with the License.\n\n * You may obtain a copy of the License at\n\n *\n\n * http://www.apache.org/licenses/LICENSE-2.0\n\n *\n\n * Unless required by applicable law or agreed to in writing, software\n\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n\n * See the License for the specific language governing permissions and\n\n * limitations under the License.\n\n */\n\nuse prometheus::core::{AtomicU64, GenericCounter};\n\nuse prometheus::{IntCounterVec, Registry, Result as MetricsResult};\n\n\n\nuse crate::metrics::{filter_opts, CollectorExt};\n\n\n", "file_path": "src/filters/token_router/metrics.rs", "rank": 56, "score": 25.83817932993502 }, { "content": "/*\n\n * Copyright 2020 Google LLC\n\n *\n\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n\n * you may not use this file except in compliance with the License.\n\n * You may obtain a copy of the License at\n\n *\n\n * http://www.apache.org/licenses/LICENSE-2.0\n\n *\n\n * Unless required by applicable law or agreed to in writing, software\n\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n\n * See the License for the specific language governing permissions and\n\n * limitations under the License.\n\n */\n\n\n\nuse std::sync::Arc;\n\n\n\n// We use a parking_lot since it's significantly faster under low contention\n\n// and we will need to acquire a read lock with every packet that is processed\n", "file_path": "src/cluster/cluster_manager.rs", "rank": 57, "score": 25.832553287560856 }, { "content": "/*\n\n * Copyright 2020 Google LLC\n\n *\n\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n\n * you may not use this file except in compliance with the License.\n\n * You may obtain a copy of the License at\n\n *\n\n * http://www.apache.org/licenses/LICENSE-2.0\n\n *\n\n * Unless required by applicable law or agreed to in writing, software\n\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n\n * See the License for the specific language governing permissions and\n\n * limitations under the License.\n\n */\n\n\n\n//! Filters for processing packets.\n\n\n\nmod error;\n\nmod factory;\n", "file_path": "src/filters.rs", "rank": 58, "score": 25.823774486326016 }, { "content": "/*\n\n * Copyright 2020 Google LLC\n\n *\n\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n\n * you may not use this file except in compliance with the License.\n\n * You may obtain a copy of the License at\n\n *\n\n * http://www.apache.org/licenses/LICENSE-2.0\n\n *\n\n * Unless required by applicable law or agreed to in writing, software\n\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n\n * See the License for the specific language governing permissions and\n\n * limitations under the License.\n\n */\n\n\n\n#[derive(Debug)]\n\npub struct Error {\n\n pub message: String,\n\n}\n", "file_path": "src/xds/error.rs", "rank": 59, "score": 25.823774486326016 }, { "content": "/*\n\n * Copyright 2021 Google LLC\n\n *\n\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n\n * you may not use this file except in compliance with the License.\n\n * You may obtain a copy of the License at\n\n *\n\n * http://www.apache.org/licenses/LICENSE-2.0\n\n *\n\n * Unless required by applicable law or agreed to in writing, software\n\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n\n * See the License for the specific language governing permissions and\n\n * limitations under the License.\n\n */\n\n\n\nuse serde_json::map::Map as JsonMap;\n\nuse serde_json::value::Value as JSONValue;\n\nuse serde_json::Number as JSONNumber;\n\nuse serde_yaml::Value as YamlValue;\n", "file_path": "src/config/metadata.rs", "rank": 60, "score": 25.75130571741258 }, { "content": "/*\n\n * Copyright 2020 Google LLC\n\n *\n\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n\n * you may not use this file except in compliance with the License.\n\n * You may obtain a copy of the License at\n\n *\n\n * http://www.apache.org/licenses/LICENSE-2.0\n\n *\n\n * Unless required by applicable law or agreed to in writing, software\n\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n\n * See the License for the specific language governing permissions and\n\n * limitations under the License.\n\n */\n\n\n\nuse crate::config::{parse_endpoint_metadata_from_yaml, EndPoint};\n\nuse serde_json::value::Value;\n\nuse std::collections::{HashMap, HashSet};\n\nuse std::net::SocketAddr;\n", "file_path": "src/cluster.rs", "rank": 61, "score": 25.75130571741258 }, { "content": "/*\n\n * Copyright 2021 Google LLC\n\n *\n\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n\n * you may not use this file except in compliance with the License.\n\n * You may obtain a copy of the License at\n\n *\n\n * http://www.apache.org/licenses/LICENSE-2.0\n\n *\n\n * Unless required by applicable law or agreed to in writing, software\n\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n\n * See the License for the specific language governing permissions and\n\n * limitations under the License.\n\n */\n\n\n\nuse std::sync::atomic::{AtomicUsize, Ordering};\n\n\n\nuse rand::{thread_rng, Rng};\n\n\n\nuse crate::config::UpstreamEndpoints;\n\n\n\n/// EndpointChooser chooses from a set of endpoints that a proxy is connected to.\n", "file_path": "src/filters/load_balancer/endpoint_chooser.rs", "rank": 62, "score": 25.73079502755933 }, { "content": "/*\n\n * Copyright 2020 Google LLC\n\n *\n\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n\n * you may not use this file except in compliance with the License.\n\n * You may obtain a copy of the License at\n\n *\n\n * http://www.apache.org/licenses/LICENSE-2.0\n\n *\n\n * Unless required by applicable law or agreed to in writing, software\n\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n\n * See the License for the specific language governing permissions and\n\n * limitations under the License.\n\n */\n\n\n\nuse crate::cluster::{\n\n Cluster as ProxyCluster, ClusterLocalities, Endpoint, Locality, LocalityEndpoints,\n\n};\n\nuse crate::xds::envoy::config::cluster::v3::{cluster, Cluster};\n", "file_path": "src/xds/cluster.rs", "rank": 63, "score": 25.72041356801529 }, { "content": "/*\n\n * Copyright 2020 Google LLC\n\n *\n\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n\n * you may not use this file except in compliance with the License.\n\n * You may obtain a copy of the License at\n\n *\n\n * http://www.apache.org/licenses/LICENSE-2.0\n\n *\n\n * Unless required by applicable law or agreed to in writing, software\n\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n\n * See the License for the specific language governing permissions and\n\n * limitations under the License.\n\n */\n\n\n\nmod capture;\n\nmod config;\n\nmod metrics;\n\nmod proto;\n", "file_path": "src/filters/capture_bytes.rs", "rank": 64, "score": 25.691718212180106 }, { "content": "/*\n\n * Copyright 2020 Google LLC\n\n *\n\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n\n * you may not use this file except in compliance with the License.\n\n * You may obtain a copy of the License at\n\n *\n\n * http://www.apache.org/licenses/LICENSE-2.0\n\n *\n\n * Unless required by applicable law or agreed to in writing, software\n\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n\n * See the License for the specific language governing permissions and\n\n * limitations under the License.\n\n */\n\nuse prometheus::core::{AtomicU64, GenericCounter};\n\nuse prometheus::{IntCounter, Registry};\n\nuse prometheus::{IntCounterVec, Result as MetricsResult};\n\n\n\nuse crate::metrics::{filter_opts, CollectorExt};\n", "file_path": "src/filters/compress/metrics.rs", "rank": 65, "score": 25.648094277148864 }, { "content": "/*\n\n * Copyright 2020 Google LLC\n\n *\n\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n\n * you may not use this file except in compliance with the License.\n\n * You may obtain a copy of the License at\n\n *\n\n * http://www.apache.org/licenses/LICENSE-2.0\n\n *\n\n * Unless required by applicable law or agreed to in writing, software\n\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n\n * See the License for the specific language governing permissions and\n\n * limitations under the License.\n\n */\n\n\n\nuse prometheus::core::Collector;\n\npub use prometheus::Result;\n\nuse prometheus::{HistogramOpts, Opts, Registry, DEFAULT_BUCKETS};\n\n\n\n/// Create a generic metrics options.\n\n/// Use [filter_opts] instead if the intended target is a filter.\n", "file_path": "src/metrics.rs", "rank": 66, "score": 25.648094277148864 }, { "content": "/*\n\n * Copyright 2020 Google LLC\n\n *\n\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n\n * you may not use this file except in compliance with the License.\n\n * You may obtain a copy of the License at\n\n *\n\n * http://www.apache.org/licenses/LICENSE-2.0\n\n *\n\n * Unless required by applicable law or agreed to in writing, software\n\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n\n * See the License for the specific language governing permissions and\n\n * limitations under the License.\n\n */\n\n\n\nuse std::net::{Ipv4Addr, SocketAddr, SocketAddrV4};\n\nuse std::sync::atomic::{AtomicU64, Ordering};\n\nuse std::sync::Arc;\n\nuse std::time::{SystemTime, UNIX_EPOCH};\n", "file_path": "src/proxy/sessions/session.rs", "rank": 67, "score": 25.54579353426005 }, { "content": "/*\n\n * Copyright 2021 Google LLC\n\n *\n\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n\n * you may not use this file except in compliance with the License.\n\n * You may obtain a copy of the License at\n\n *\n\n * http://www.apache.org/licenses/LICENSE-2.0\n\n *\n\n * Unless required by applicable law or agreed to in writing, software\n\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n\n * See the License for the specific language governing permissions and\n\n * limitations under the License.\n\n */\n\n\n\nuse std::{any::Any, collections::HashMap, net::SocketAddr, sync::Arc};\n\n\n\nuse crate::config::UpstreamEndpoints;\n\n#[cfg(doc)]\n\nuse crate::filters::Filter;\n\n\n\n/// Shared state between [`Filter`]s during processing for a single packet.\n", "file_path": "src/filters/read.rs", "rank": 68, "score": 25.51890269757705 }, { "content": "/*\n\n * Copyright 2020 Google LLC\n\n *\n\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n\n * you may not use this file except in compliance with the License.\n\n * You may obtain a copy of the License at\n\n *\n\n * http://www.apache.org/licenses/LICENSE-2.0\n\n *\n\n * Unless required by applicable law or agreed to in writing, software\n\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n\n * See the License for the specific language governing permissions and\n\n * limitations under the License.\n\n */\n\n\n\n// We don't control the codegen, so disable any code warnings in the\n\n// proto modules.\n\n#[allow(warnings)]\n\nmod xds {\n", "file_path": "src/xds.rs", "rank": 69, "score": 25.431747560798268 }, { "content": "/*\n\n * Copyright 2021 Google LLC\n\n *\n\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n\n * you may not use this file except in compliance with the License.\n\n * You may obtain a copy of the License at\n\n *\n\n * http://www.apache.org/licenses/LICENSE-2.0\n\n *\n\n * Unless required by applicable law or agreed to in writing, software\n\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n\n * See the License for the specific language governing permissions and\n\n * limitations under the License.\n\n */\n\n\n\nuse crate::filters::{\n\n manager::ListenerManagerArgs, CreateFilterArgs, FilterChain as ProxyFilterChain, FilterRegistry,\n\n};\n\nuse crate::xds::envoy::config::listener::v3::{\n", "file_path": "src/xds/listener.rs", "rank": 70, "score": 25.39010155043468 }, { "content": "/*\n\n * Copyright 2020 Google LLC\n\n *\n\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n\n * you may not use this file except in compliance with the License.\n\n * You may obtain a copy of the License at\n\n *\n\n * http://www.apache.org/licenses/LICENSE-2.0\n\n *\n\n * Unless required by applicable law or agreed to in writing, software\n\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n\n * See the License for the specific language governing permissions and\n\n * limitations under the License.\n\n */\n\n\n\nmod metrics;\n\n\n\ncrate::include_proto!(\"quilkin.extensions.filters.token_router.v1alpha1\");\n\n\n", "file_path": "src/filters/token_router.rs", "rank": 71, "score": 25.303788992142042 }, { "content": "/*\n\n * Copyright 2020 Google LLC\n\n *\n\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n\n * you may not use this file except in compliance with the License.\n\n * You may obtain a copy of the License at\n\n *\n\n * http://www.apache.org/licenses/LICENSE-2.0\n\n *\n\n * Unless required by applicable law or agreed to in writing, software\n\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n\n * See the License for the specific language governing permissions and\n\n * limitations under the License.\n\n */\n\n\n\nmod cluster;\n\npub mod config;\n\npub mod filters;\n\npub(crate) mod metrics;\n", "file_path": "src/lib.rs", "rank": 72, "score": 25.177152930748775 }, { "content": "/*\n\n * Copyright 2020 Google LLC\n\n *\n\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n\n * you may not use this file except in compliance with the License.\n\n * You may obtain a copy of the License at\n\n *\n\n * http://www.apache.org/licenses/LICENSE-2.0\n\n *\n\n * Unless required by applicable law or agreed to in writing, software\n\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n\n * See the License for the specific language governing permissions and\n\n * limitations under the License.\n\n */\n\n\n\nuse slog::Logger;\n\n\n\npub(crate) use filter_chain::Error as FilterChainError;\n\n\n\npub(crate) mod filter_manager;\n\nmod filter_registry;\n\npub mod filters;\n\n\n\nmod filter_chain;\n", "file_path": "src/extensions.rs", "rank": 73, "score": 25.174839165767477 }, { "content": "/*\n\n * Copyright 2020 Google LLC\n\n *\n\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n\n * you may not use this file except in compliance with the License.\n\n * You may obtain a copy of the License at\n\n *\n\n * http://www.apache.org/licenses/LICENSE-2.0\n\n *\n\n * Unless required by applicable law or agreed to in writing, software\n\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n\n * See the License for the specific language governing permissions and\n\n * limitations under the License.\n\n */\n\n\n\nuse crate::metrics::{histogram_opts, opts, CollectorExt};\n\nuse prometheus::core::{AtomicI64, AtomicU64, GenericCounter, GenericGauge};\n\nuse prometheus::{Histogram, IntCounter, IntGauge, Registry, Result as MetricsResult};\n\n\n", "file_path": "src/proxy/sessions/metrics.rs", "rank": 74, "score": 25.10625070364899 }, { "content": "/*\n\n * Copyright 2021 Google LLC\n\n *\n\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n\n * you may not use this file except in compliance with the License.\n\n * You may obtain a copy of the License at\n\n *\n\n * http://www.apache.org/licenses/LICENSE-2.0\n\n *\n\n * Unless required by applicable law or agreed to in writing, software\n\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n\n * See the License for the specific language governing permissions and\n\n * limitations under the License.\n\n */\n\n\n\nuse crate::cluster::cluster_manager::{ClusterManager, InitializeError, SharedClusterManager};\n\nuse crate::config::{Endpoints, ManagementServer};\n\nuse crate::filters::{\n\n manager::{FilterManager, ListenerManagerArgs, SharedFilterManager},\n", "file_path": "src/proxy/server/resource_manager.rs", "rank": 75, "score": 25.10625070364899 }, { "content": "/*\n\n * Copyright 2021 Google LLC\n\n *\n\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n\n * you may not use this file except in compliance with the License.\n\n * You may obtain a copy of the License at\n\n *\n\n * http://www.apache.org/licenses/LICENSE-2.0\n\n *\n\n * Unless required by applicable law or agreed to in writing, software\n\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n\n * See the License for the specific language governing permissions and\n\n * limitations under the License.\n\n */\n\n\n\n/// Protobuf config for this filter.\n\npub(super) mod quilkin {\n\n pub mod extensions {\n\n pub mod filters {\n", "file_path": "src/filters/token_router/proto.rs", "rank": 76, "score": 25.05181845662311 }, { "content": "/*\n\n * Copyright 2021 Google LLC\n\n *\n\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n\n * you may not use this file except in compliance with the License.\n\n * You may obtain a copy of the License at\n\n *\n\n * http://www.apache.org/licenses/LICENSE-2.0\n\n *\n\n * Unless required by applicable law or agreed to in writing, software\n\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n\n * See the License for the specific language governing permissions and\n\n * limitations under the License.\n\n */\n\n\n\n/// Protobuf config for this filter.\n\npub(super) mod quilkin {\n\n pub mod extensions {\n\n pub mod filters {\n", "file_path": "src/filters/capture_bytes/proto.rs", "rank": 77, "score": 25.05181845662311 }, { "content": "/*\n\n * Copyright 2021 Google LLC\n\n *\n\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n\n * you may not use this file except in compliance with the License.\n\n * You may obtain a copy of the License at\n\n *\n\n * http://www.apache.org/licenses/LICENSE-2.0\n\n *\n\n * Unless required by applicable law or agreed to in writing, software\n\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n\n * See the License for the specific language governing permissions and\n\n * limitations under the License.\n\n */\n\n\n\n/// Protobuf config for this filter.\n\npub(super) mod quilkin {\n\n pub mod extensions {\n\n pub mod filters {\n", "file_path": "src/filters/load_balancer/proto.rs", "rank": 78, "score": 25.05181845662311 }, { "content": "/*\n\n * Copyright 2021 Google LLC\n\n *\n\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n\n * you may not use this file except in compliance with the License.\n\n * You may obtain a copy of the License at\n\n *\n\n * http://www.apache.org/licenses/LICENSE-2.0\n\n *\n\n * Unless required by applicable law or agreed to in writing, software\n\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n\n * See the License for the specific language governing permissions and\n\n * limitations under the License.\n\n */\n\n\n\n/// Protobuf config for this filter.\n\npub(super) mod quilkin {\n\n pub mod extensions {\n\n pub mod filters {\n", "file_path": "src/filters/local_rate_limit/proto.rs", "rank": 79, "score": 25.05181845662311 }, { "content": "/*\n\n * Copyright 2021 Google LLC\n\n *\n\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n\n * you may not use this file except in compliance with the License.\n\n * You may obtain a copy of the License at\n\n *\n\n * http://www.apache.org/licenses/LICENSE-2.0\n\n *\n\n * Unless required by applicable law or agreed to in writing, software\n\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n\n * See the License for the specific language governing permissions and\n\n * limitations under the License.\n\n */\n\n\n\n/// Protobuf config for this filter.\n\npub(super) mod quilkin {\n\n pub mod extensions {\n\n pub mod filters {\n", "file_path": "src/filters/compress/proto.rs", "rank": 80, "score": 25.05181845662311 }, { "content": "/*\n\n * Copyright 2020 Google LLC\n\n *\n\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n\n * you may not use this file except in compliance with the License.\n\n * You may obtain a copy of the License at\n\n *\n\n * http://www.apache.org/licenses/LICENSE-2.0\n\n *\n\n * Unless required by applicable law or agreed to in writing, software\n\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n\n * See the License for the specific language governing permissions and\n\n * limitations under the License.\n\n */\n\n\n\npub use session::{Packet, Session, SessionKey};\n\npub use session_manager::SESSION_TIMEOUT_SECONDS;\n\n\n\npub(crate) mod error;\n\npub(crate) mod metrics;\n\nmod session;\n\npub(crate) mod session_manager;\n", "file_path": "src/proxy/sessions.rs", "rank": 81, "score": 24.85908911140292 }, { "content": "/*\n\n * Copyright 2020 Google LLC All Rights Reserved.\n\n *\n\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n\n * you may not use this file except in compliance with the License.\n\n * You may obtain a copy of the License at\n\n *\n\n * http://www.apache.org/licenses/LICENSE-2.0\n\n *\n\n * Unless required by applicable law or agreed to in writing, software\n\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n\n * See the License for the specific language governing permissions and\n\n * limitations under the License.\n\n */\n\n\n\nmod config;\n\n\n\nuse crate::filters::prelude::*;\n\n\n\nuse config::ProtoConfig;\n\npub use config::{Config, Strategy};\n\n\n\npub const NAME: &str = \"quilkin.extensions.filters.concatenate_bytes.v1alpha1.ConcatenateBytes\";\n\n\n\n/// Returns a factory for creating concatenation filters.\n", "file_path": "src/filters/concatenate_bytes.rs", "rank": 82, "score": 24.806103580096167 }, { "content": "/*\n\n * Copyright 2021 Google LLC\n\n *\n\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n\n * you may not use this file except in compliance with the License.\n\n * You may obtain a copy of the License at\n\n *\n\n * http://www.apache.org/licenses/LICENSE-2.0\n\n *\n\n * Unless required by applicable law or agreed to in writing, software\n\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n\n * See the License for the specific language governing permissions and\n\n * limitations under the License.\n\n */\n\n\n\nuse prometheus::Registry;\n\n\n\nuse crate::{\n\n config::ConfigType,\n\n filters::{Error, Filter},\n\n};\n\n\n\n/// An owned pointer to a dynamic [`FilterFactory`] instance.\n\npub type DynFilterFactory = Box<dyn FilterFactory>;\n\n\n\n/// Provides the name and creation function for a given [`Filter`].\n\n///\n", "file_path": "src/filters/factory.rs", "rank": 83, "score": 24.65319865996022 }, { "content": "/*\n\n * Copyright 2020 Google LLC\n\n *\n\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n\n * you may not use this file except in compliance with the License.\n\n * You may obtain a copy of the License at\n\n *\n\n * http://www.apache.org/licenses/LICENSE-2.0\n\n *\n\n * Unless required by applicable law or agreed to in writing, software\n\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n\n * See the License for the specific language governing permissions and\n\n * limitations under the License.\n\n */\n\n\n\nuse std::convert::TryFrom;\n\n\n\nuse serde::{Deserialize, Serialize};\n\nuse slog::{info, o, Logger};\n\n\n\nuse crate::filters::prelude::*;\n\n\n\ncrate::include_proto!(\"quilkin.extensions.filters.debug.v1alpha1\");\n\nuse self::quilkin::extensions::filters::debug::v1alpha1::Debug as ProtoDebug;\n\n\n\n/// Debug logs all incoming and outgoing packets\n\n#[derive(Debug)]\n", "file_path": "src/filters/debug.rs", "rank": 84, "score": 24.56640778586551 }, { "content": "/*\n\n * Copyright 2021 Google LLC\n\n *\n\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n\n * you may not use this file except in compliance with the License.\n\n * You may obtain a copy of the License at\n\n *\n\n * http://www.apache.org/licenses/LICENSE-2.0\n\n *\n\n * Unless required by applicable law or agreed to in writing, software\n\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n\n * See the License for the specific language governing permissions and\n\n * limitations under the License.\n\n */\n\n\n\n//! Well known dynamic metadata used by Quilkin.\n\n\n\n/// The default key under which the [`super::capture_bytes`] filter puts the\n\n/// byte slices it extracts from each packet.\n\n/// - **Type** `Vec<u8>`\n\npub const CAPTURED_BYTES: &str = \"quilkin.dev/captured_bytes\";\n", "file_path": "src/filters/metadata.rs", "rank": 85, "score": 24.397961334795042 }, { "content": "/*\n\n * Copyright 2020 Google LLC All Rights Reserved.\n\n *\n\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n\n * you may not use this file except in compliance with the License.\n\n * You may obtain a copy of the License at\n\n *\n\n * http://www.apache.org/licenses/LICENSE-2.0\n\n *\n\n * Unless required by applicable law or agreed to in writing, software\n\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n\n * See the License for the specific language governing permissions and\n\n * limitations under the License.\n\n */\n\n\n\nmod config;\n\nmod endpoint_chooser;\n\n\n\nuse crate::filters::{prelude::*, DynFilterFactory};\n\n\n\nuse config::ProtoConfig;\n\nuse endpoint_chooser::EndpointChooser;\n\n\n\npub use config::{Config, Policy};\n\n\n\npub const NAME: &str = \"quilkin.extensions.filters.load_balancer.v1alpha1.LoadBalancer\";\n\n\n\n/// Returns a factory for creating load balancing filters.\n", "file_path": "src/filters/load_balancer.rs", "rank": 87, "score": 23.93456273734162 }, { "content": "/*\n\n * Copyright 2021 Google LLC\n\n *\n\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n\n * you may not use this file except in compliance with the License.\n\n * You may obtain a copy of the License at\n\n *\n\n * http://www.apache.org/licenses/LICENSE-2.0\n\n *\n\n * Unless required by applicable law or agreed to in writing, software\n\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n\n * See the License for the specific language governing permissions and\n\n * limitations under the License.\n\n */\n\n\n\nuse std::collections::{BTreeMap, HashSet};\n\n\n\nuse crate::config::extract_endpoint_tokens;\n\nuse crate::xds::envoy::config::core::v3::Metadata;\n\nuse prost_types::value::Kind;\n\nuse prost_types::Value as ProstValue;\n\nuse serde_json::map::Map as JsonMap;\n\nuse serde_json::value::Value as JSONValue;\n\nuse serde_json::Number as JSONNumber;\n\n\n\n/// Converts an XDS Metadata object into endpoint specific values and JSON values.\n", "file_path": "src/xds/metadata.rs", "rank": 88, "score": 23.181400430668877 }, { "content": "/*\n\n * Copyright 2020 Google LLC\n\n *\n\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n\n * you may not use this file except in compliance with the License.\n\n * You may obtain a copy of the License at\n\n *\n\n * http://www.apache.org/licenses/LICENSE-2.0\n\n *\n\n * Unless required by applicable law or agreed to in writing, software\n\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n\n * See the License for the specific language governing permissions and\n\n * limitations under the License.\n\n */\n\n//!\n\n//! The `debug` module is for functionality related to realtime debugging of this project.\n\n//!\n\n\n\n/// Attempt to convert a packet into a string, if it is one, otherwise return some human\n\n/// readable details about the packet.\n\npub(crate) fn bytes_to_string(bytes: &[u8]) -> String {\n\n std::str::from_utf8(bytes)\n\n .map(str::to_string)\n\n .unwrap_or_else(|_| format!(\"<raw bytes :: len: {}>\", bytes.len()))\n\n}\n", "file_path": "src/utils/debug.rs", "rank": 89, "score": 22.28838836583376 }, { "content": "## Quilkin Branding Guidelines\n\n\n\nThe Quilkin logo, mascot, and trademark are made available here with the following\n\nguidelines:\n\n\n\n**You may:**\n\n - use them for non-commercial uses such as t-shirts and stickers\n\n - use them to link to the project repository \n\n - use them in a blog post or news article about Quilkin\n\n\n\n**You may not:**\n\n - Use them in a way that would confuse people about the origin of Quilkin,\n\n its maintainers or governance structure\n\n - Use them as your product's logo or trademark\n\n - Create a modified version of the project logo. The mascot image may be modified as detailed below.\n\n - Integrate them into your logo\n\n - Use them in such a manner as to create the impression that your product or\n\n service has been certified, vetted, or otherwise endorsed by the Quilkin\n\n project\n\n\n\nIf the above guidelines do not cover your potential use case, or you're just\n\nnot sure; please file an issue for the project maintainers to review.\n\n\n\n## Quilly, the project mascot\n\n\n\nQuilly is the official mascot of the Quilkin project. They are an adorable hedgehog welcoming all to the project. Quilly is not the project logo; rather they are a fun way to represent the project. You may modify the Quilly image and adapt it for your own use, but do credit back to the Quilkin project. \n\n\n\nQuilly's pronouns are they/them. \n", "file_path": "BRANDING.md", "rank": 90, "score": 12.703965424353271 }, { "content": "# Examples\n\n\n\nSee the [examples](https://github.com/googleforgames/quilkin/tree/main/examples) folder on Github for configuration and \n\nusage examples.\n\n\n\n> Depending on which release version of Quilkin you are using, you may need to choose the appropriate release tag\n\n> from the dropdown, as the API surface for Quilkin is still under development.\n\n\n\nExamples include:\n\n* Quilkin running as a sidecar while hosted on [Agones](https://agones.dev/).\n\n* [iperf3](https://iperf.fr/) throughput.\n\n* [Grafana](https://grafana.com/) dashboards.\n\n\n\n...and more!\n", "file_path": "docs/src/examples.md", "rank": 91, "score": 10.254520666831207 }, { "content": " // when we're shutting down in which case there's nothing we can do here.\n\n .ok();\n\n}\n\n\n\n#[cfg(test)]\n\nmod tests {\n\n use super::AdsClient;\n\n use crate::config::ManagementServer;\n\n use crate::filters::FilterRegistry;\n\n use crate::proxy::logger;\n\n use crate::xds::ads_client::ListenerManagerArgs;\n\n use crate::xds::envoy::service::discovery::v3::DiscoveryRequest;\n\n use crate::xds::google::rpc::Status as GrpcStatus;\n\n use crate::xds::CLUSTER_TYPE;\n\n\n\n use std::time::Duration;\n\n\n\n use prometheus::Registry;\n\n use tokio::sync::{mpsc, watch};\n\n\n", "file_path": "src/xds/ads_client.rs", "rank": 92, "score": 8.922802500111557 }, { "content": " resource_names: Vec<String>,\n\n ) {\n\n send_discovery_req(\n\n self.log.clone(),\n\n type_url,\n\n version_info,\n\n response_nonce,\n\n error_message,\n\n resource_names,\n\n &mut self.discovery_req_tx,\n\n )\n\n .await\n\n }\n\n}\n\n\n\n#[cfg(test)]\n\nmod tests {\n\n use super::ListenerManager;\n\n use crate::filters::{manager::ListenerManagerArgs, prelude::*};\n\n use crate::test_utils::logger;\n", "file_path": "src/xds/listener.rs", "rank": 93, "score": 8.643511632031831 }, { "content": "### Development\n\n\n\n> This documentation is for the development version of Quilkin, currently active on the `main` branch. To view the \n\n> documentation for a specific release, click on the appropriate release documentation link above.\n\n\n\n* [Guide](https://googleforgames.github.io/quilkin/main/book/)\n\n* [Api](https://googleforgames.github.io/quilkin/main/api/quilkin/)\n\n* [Macros](https://googleforgames.github.io/quilkin/main/api/quilkin_macros/)\n\n\n\n## Code of Conduct\n\n\n\nParticipation in this project comes under the [Contributor Covenant Code of Conduct](code-of-conduct.md)\n\n\n\n## Development and Contribution\n\n\n\nPlease read the [contributing](CONTRIBUTING.md) guide for directions on writing code and submitting Pull Requests.\n\n\n\nQuilkin is in active development - we would love your help in shaping its future!\n\n\n\n## Community\n\n\n\nThere are lots of ways to engage with the Quilkin community:\n\n\n\n* Here on [Github](https://github.com/googleforgames/quilkin) via \n\n [issues](https://github.com/googleforgames/quilkin/issues) and \n\n [pull requests](https://github.com/googleforgames/quilkin/pulls).\n\n* Join our [mailing list](https://groups.google.com/forum/#!forum/quilkin-discuss), which also gives you access to\n\n our continuous integration builds.\n\n* Join our [Discord chat server](https://discord.gg/mfBNZjBDnc).\n\n* Follow up on [Twitter](https://twitter.com/quilkindev).\n\n\n\n## Credits\n\n\n\nMany concepts and architectural decisions were inspired by [Envoy Proxy](https://www.envoyproxy.io/). \n\nHuge thanks to that team for the inspiration they provided with all their hard work. \n\n\n\n## Companies using Quilkin\n\n\n\n[<img src=\"./image/embark.png\" alt=\"Embark Studios\" height=\"100\">](https://www.embark-studios.com/)\n\n\n\n## Licence\n\n\n\nApache 2.0\n\n\n\n<img src=\"./docs/logos/mascot.png\" alt=\"Quilly, the Quilkin mascot\" height=\"200\" align=\"right\">\n", "file_path": "README.md", "rank": 94, "score": 7.5097716243041805 }, { "content": "#### Supported APIs\n\n\n\nSince the range of resources configurable by the xDS API extends that of Quilkin's domain (i.e being UDP based, Quilkin does not have a need for HTTP/TCP resources), only a subset of the API is supported. The following lists these relevant parts and any limitation to the provided support as a result:\n\n\n\n- **Cluster Discovery Service [(CDS)][CDS]**: Provides information about known clusters and their membership information.\n\n * The proxy uses these resources to discover clusters and their endpoints.\n\n * While cluster topology information like [locality] can be provided in the configuration, the proxy currently does not use this information (support may be included in the future however).\n\n * Any [load balancing information][lbpolicy] included in this resource is ignored. For load balancing, use [Quilkin filters][filters-doc] instead.\n\n * Only [cluster discovery type] `STATIC` and `EDS` is supported. Configuration including other discovery types e.g `LOGICAL_DNS` is rejected.\n\n\n\n- **Endpoint Discovery Service [(EDS)][EDS]**: Provides information about endpoints.\n\n * The proxy uses these resources to discover information about endpoints like their IP addresses.\n\n * Endpoints may provide [Endpoint Metadata][endpoint-metadata] via the [metadata][xds-endpoint-metadata] field. These metadata will be visible to filters as part of the corresponding endpoints information when processing packets.\n\n * Only [socket addresses] are supported on an endpoint's address configuration - i.e an IP address and port number combination. Configuration including any other type of addressing e.g named pipes will be rejected.\n\n * Any [load balancing information][clapolicy] included in this resource is ignored. For load balancing, use [Quilkin filters][filters-doc] instead.\n\n\n\n- **Listener Discovery Service [(LDS)][LDS]**: Provides information about [Filters and Filter Chains][filters-doc].\n\n * Only the `name` and `filter_chains` fields in the [Listener resource][listener-resource] are used by the proxy. The rest are ignored.\n\n * Since Quilkin only uses one filter chain per proxy, at most one filter chain can be provided in the resource. Otherwise the configuration is rejected.\n\n * Only the list of [filters][xds-filters] specified in the [filter chain][xds-filter-chain] is used by the proxy - i.e other fields like `filter_chain_match` are ignored. This list also specifies the order that the corresponding filter chain will be constructed.\n\n * gRPC proto configuration for Quilkin's built-in filters [can be found here][filter-protos]. They are equivalent to the filter's static configuration.\n\n\n\n\n", "file_path": "docs/src/xds.md", "rank": 95, "score": 7.177238935134948 }, { "content": " log: Logger,\n\n\n\n // Send discovery requests ACKs/NACKs to the server.\n\n discovery_req_tx: mpsc::Sender<DiscoveryRequest>,\n\n\n\n // Sends cluster state updates to the caller.\n\n cluster_updates_tx: mpsc::Sender<HashMap<String, ProxyCluster>>,\n\n\n\n // Tracks each cluster's endpoints and localities.\n\n clusters: HashMap<String, ProxyCluster>,\n\n\n\n // Tracks the (version, nonce) state for EDS request/response.\n\n // This is used to make spontaneous EDS requests to\n\n // subscribe to the latest cluster set anytime the set changes.\n\n last_seen_cluster_load_assignment_version: Option<(String, String)>,\n\n}\n\n\n\nimpl ClusterManager {\n\n /// Creates a new [`ClusterManager`].\n\n /// Cluster updates are sent on the provided channel. DiscoveryRequest\n", "file_path": "src/xds/cluster.rs", "rank": 96, "score": 6.8570176812293315 }, { "content": " use quilkin::filters::{CreateFilterArgs, Error, FilterFactory};\n\n\n\n struct GreetFilterFactory;\n\n impl FilterFactory for GreetFilterFactory {\n\n fn name(&self) -> &'static str {\n\n // We provide the name of filter that we defined earlier.\n\n NAME\n\n }\n\n fn create_filter(&self, _: CreateFilterArgs) -> Result<Box<dyn Filter>, Error> {\n\n Ok(Box::new(Greet))\n\n }\n\n }\n\n ```\n\n\n\n1. **Start the proxy**\n\n\n\n We can run the proxy in the exact manner as the default Quilkin binary using the [run] function, passing in our custom [FilterFactory].\n\n Lets add a main function that does that. Quilkin relies on the [Tokio] async runtime so we need to import that crate and wrap our main function with it.\n\n\n\n Add Tokio as a dependency in `Cargo.toml`.\n\n ```toml\n\n [dependencies]\n\n quilkin = \"0.1.0-dev\"\n\n tokio = { version = \"1\", features = [\"full\"]}\n\n ```\n\n\n\n Add a main function that starts the proxy.\n\n ```no_run\n\n // src/main.rs\n\n # use quilkin::filters::{CreateFilterArgs, Filter, Error, FilterFactory};\n\n\n\n # struct GreetFilterFactory;\n\n # impl FilterFactory for GreetFilterFactory {\n\n # fn name(&self) -> &'static str {\n\n # \"greet.v1\"\n\n # }\n\n # fn create_filter(&self, _: CreateFilterArgs) -> Result<Box<dyn Filter>, Error> {\n\n # unimplemented!()\n\n # }\n\n # }\n\n use quilkin::{filters::DynFilterFactory, run};\n\n\n\n #[tokio::main]\n\n async fn main() {\n\n run(vec![Box::new(GreetFilterFactory) as DynFilterFactory]).await.unwrap();\n\n }\n\n ```\n\n\n\nNow, let's try out the proxy. The following configuration starts our extended version of the proxy at port 7001\n\nand forwards all packets to an upstream server at port 4321.\n\n\n\n```yaml\n", "file_path": "docs/src/filters/writing_custom_filters.md", "rank": 97, "score": 6.697847558052722 }, { "content": " self.send_discovery_req(\n\n LISTENER_TYPE,\n\n response.version_info,\n\n response.nonce,\n\n error_message,\n\n vec![], // LDS uses a wildcard request.\n\n )\n\n .await;\n\n }\n\n\n\n async fn process_listener_response(\n\n &mut self,\n\n mut resources: Vec<prost_types::Any>,\n\n ) -> Result<ProxyFilterChain, Error> {\n\n let resource = match resources.len() {\n\n 0 => return Ok(ProxyFilterChain::new(vec![], &self.metrics_registry)?),\n\n 1 => resources.swap_remove(0),\n\n n => {\n\n return Err(Error::new(format!(\n\n \"at most 1 listener can be specified: got {}\",\n", "file_path": "src/xds/listener.rs", "rank": 98, "score": 6.6526667162541235 }, { "content": "## Enforcement Responsibilities\n\n\n\nCommunity leaders are responsible for clarifying and enforcing our standards of acceptable behavior and will take appropriate and fair corrective action in response to any behavior that they deem inappropriate, threatening, offensive, or harmful.\n\n\n\nCommunity leaders have the right and responsibility to remove, edit, or reject comments, commits, code, wiki edits, issues, and other contributions that are not aligned to this Code of Conduct, and will communicate reasons for moderation decisions when appropriate.\n\n\n\n## Scope\n\n\n\nThis Code of Conduct applies within all community spaces, and also applies when an individual is officially representing the community in public spaces. Examples of representing our community include using an official e-mail address, posting via an official social media account, or acting as an appointed representative at an online or offline event.\n\n\n\n## Enforcement\n\n\n\nInstances of abusive, harassing, or otherwise unacceptable behavior may be reported to the community leaders\n\nresponsible for enforcement at [[email protected]](mailto:[email protected]). All complaints will be\n\nreviewed and investigated promptly and fairly.\n\n\n\nAll community leaders are obligated to respect the privacy and security of the reporter of any incident.\n\n\n\n## Enforcement Guidelines\n\n\n\nCommunity leaders will follow these Community Impact Guidelines in determining the consequences for any action they deem in violation of this Code of Conduct:\n\n\n\n### 1. Correction\n\n\n\n**Community Impact**: Use of inappropriate language or other behavior deemed unprofessional or unwelcome in the community.\n\n\n\n**Consequence**: A private, written warning from community leaders, providing clarity around the nature of the violation and an explanation of why the behavior was inappropriate. A public apology may be requested.\n\n\n", "file_path": "code-of-conduct.md", "rank": 99, "score": 6.273390935858318 } ]
Rust
nanocurrency-peering/src/lib.rs
tundak/railroad
b18298aab4ad72b045227a94162d9cd1a510ef51
use std::iter::IntoIterator; use std::io; use std::net::{SocketAddr, SocketAddrV6, ToSocketAddrs}; use std::cell::RefCell; use std::rc::Rc; use std::time::{Duration, Instant}; use std::collections::{hash_map, HashMap}; use std::marker::PhantomData; use std::fmt::Debug; #[macro_use] extern crate log; #[macro_use] extern crate futures; use futures::{stream, Future, Sink, Stream}; extern crate net2; use net2::UdpBuilder; extern crate bytes; extern crate tokio; use tokio::net::UdpSocket; use tokio::reactor::Handle; extern crate tokio_io; extern crate tokio_timer; use tokio_timer::Timer; extern crate rand; use rand::{thread_rng, Rng}; extern crate nanocurrency_protocol; use nanocurrency_protocol::*; #[macro_use] extern crate nanocurrency_types; use nanocurrency_types::Network; mod udp_framed; const KEEPALIVE_INTERVAL: u64 = 60; const KEEPALIVE_CUTOFF: u64 = KEEPALIVE_INTERVAL * 5; pub fn addr_to_ipv6(addr: SocketAddr) -> SocketAddrV6 { match addr { SocketAddr::V4(addr) => SocketAddrV6::new(addr.ip().to_ipv6_mapped(), addr.port(), 0, 0), SocketAddr::V6(addr) => addr, } } struct IgnoreErrors<S: Stream, E> where S::Error: Debug, { inner: S, err_phantom: PhantomData<E>, } impl<S: Stream, E: Debug> Stream for IgnoreErrors<S, E> where S::Error: Debug, { type Item = S::Item; type Error = E; fn poll(&mut self) -> Result<futures::Async<Option<S::Item>>, E> { loop { match self.inner.poll() { Ok(x) => return Ok(x), Err(err) => debug!("ignoring error: {:?}", err), } } } } fn ignore_errors<S: Stream, E>(stream: S) -> IgnoreErrors<S, E> where S::Error: Debug, { IgnoreErrors { inner: stream, err_phantom: PhantomData, } } pub struct PeerInfo { pub last_heard_from: Instant, pub network_version: u8, _private: (), } #[derive(Default)] pub struct PeeringManagerState { peers: HashMap<SocketAddrV6, PeerInfo>, rand_peers: RefCell<Vec<SocketAddrV6>>, new_peer_backoff: HashMap<SocketAddrV6, Instant>, } impl PeeringManagerState { pub fn get_rand_peers(&self, peers_out: &mut [SocketAddrV6]) { if self.peers.len() < peers_out.len() { for (peer, peer_out) in self.peers.keys().zip(peers_out.iter_mut()) { *peer_out = *peer; } return; } let mut thread_rng = thread_rng(); let mut rand_peers = self.rand_peers.borrow_mut(); for peer_out in peers_out.iter_mut() { if rand_peers.is_empty() { rand_peers.extend(self.peers.keys()); thread_rng.shuffle(&mut rand_peers); } *peer_out = rand_peers.pop().unwrap(); } } pub fn peers(&self) -> &HashMap<SocketAddrV6, PeerInfo> { &self.peers } fn contacted(&mut self, addr: SocketAddr, header: &MessageHeader) { let addr = addr_to_ipv6(addr); match self.peers.entry(addr) { hash_map::Entry::Occupied(mut entry) => { entry.get_mut().last_heard_from = Instant::now(); } hash_map::Entry::Vacant(entry) => { entry.insert(PeerInfo { last_heard_from: Instant::now(), network_version: header.version, _private: (), }); } } } } pub struct PeeringManagerBuilder<F, I, II> where I: Iterator<Item = (Message, SocketAddr)>, II: IntoIterator<Item = (Message, SocketAddr), IntoIter = I>, F: Fn(&PeeringManagerState, MessageHeader, Message, SocketAddr) -> II + 'static, { use_official_peers: bool, custom_peers: Vec<SocketAddr>, listen_addr: SocketAddr, network: Network, message_handler: F, state_base: Rc<RefCell<PeeringManagerState>>, send_messages: Box<Stream<Item = (Message, SocketAddr), Error = ()>>, } impl<F, I, II> PeeringManagerBuilder<F, I, II> where I: Iterator<Item = (Message, SocketAddr)>, II: IntoIterator<Item = (Message, SocketAddr), IntoIter = I>, F: Fn(&PeeringManagerState, MessageHeader, Message, SocketAddr) -> II + 'static, { pub fn new(message_handler: F) -> PeeringManagerBuilder<F, I, II> { PeeringManagerBuilder { use_official_peers: true, custom_peers: Vec::new(), listen_addr: "[::]:7075".parse().unwrap(), network: Network::Live, message_handler, state_base: Default::default(), send_messages: Box::new(stream::empty()), } } pub fn use_official_peers(mut self, value: bool) -> Self { self.use_official_peers = value; self } pub fn custom_peers(mut self, value: Vec<SocketAddr>) -> Self { self.custom_peers = value; self } pub fn listen_addr(mut self, value: SocketAddr) -> Self { self.listen_addr = value; self } pub fn network(mut self, value: Network) -> Self { self.network = value; self } pub fn state_base(mut self, value: Rc<RefCell<PeeringManagerState>>) -> Self { self.state_base = value; self } pub fn send_messages( mut self, value: Box<Stream<Item = (Message, SocketAddr), Error = ()>>, ) -> Self { self.send_messages = value; self } pub fn run(self) -> io::Result<Box<Future<Item = (), Error = ()>>> { let mut configured_peers: Vec<SocketAddrV6> = Vec::new(); if self.use_official_peers { let official_domain = match self.network { Network::Live => Some("rai.raiblocks.net:7075"), Network::Beta => Some("rai-beta.raiblocks.net:7075"), Network::Test => None, }; if let Some(official_domain) = official_domain { configured_peers.extend(official_domain.to_socket_addrs()?.map(addr_to_ipv6)); } } configured_peers.extend(self.custom_peers.into_iter().map(addr_to_ipv6)); let socket; if cfg!(target_os = "windows") { let std_socket = UdpBuilder::new_v6()? .only_v6(false)? .bind(self.listen_addr)?; socket = UdpSocket::from_std(std_socket, &Handle::current())?; } else { socket = UdpSocket::bind(&self.listen_addr)?; } let (sink, stream) = udp_framed::UdpFramed::new(socket, NanoCurrencyCodec).split(); let network = self.network; let message_handler = self.message_handler; let state_rc = self.state_base.clone(); let process_message = move |((header, msg), src)| { let _: &MessageHeader = &header; if header.network != network { warn!("ignoring message from {:?} network", header.network); return stream::iter_ok(Vec::new().into_iter()); } let mut state = state_rc.borrow_mut(); state.contacted(src, &header); trace!("got message from {:?}: {:?}", src, msg); let mut output_messages = Vec::new(); match msg { Message::Keepalive(new_peers) => { let state = &mut state; output_messages.extend(new_peers.to_vec().into_iter().filter_map( move |new_peer| { match state.new_peer_backoff.entry(new_peer) { hash_map::Entry::Occupied(mut entry) => { let entry = entry.get_mut(); if *entry > Instant::now() - Duration::from_secs(KEEPALIVE_CUTOFF) { return None; } *entry = Instant::now(); } hash_map::Entry::Vacant(entry) => { entry.insert(Instant::now()); } } if state.peers.contains_key(&new_peer) { return None; } let ip = new_peer.ip().clone(); if ip.octets().iter().all(|&x| x == 0) { return None; } if new_peer.port() == 0 { return None; } if ip.is_unspecified() || ip.is_loopback() || ip.is_multicast() { return None; } let mut rand_peers = [zero_v6_addr!(); 8]; state.get_rand_peers(&mut rand_peers); Some(( (network, Message::Keepalive(rand_peers)), SocketAddr::V6(new_peer), )) }, )); } _ => {} } output_messages.extend( (message_handler)(&state, header, msg, src) .into_iter() .map(|(m, a)| ((network, m), a)), ); stream::iter_ok::<_, io::Error>(output_messages) }; let process_messages = stream.map(process_message).flatten(); let state_rc = self.state_base.clone(); let timer = Timer::default(); let keepalive = stream::once(Ok(())) .chain(timer.interval(Duration::from_secs(KEEPALIVE_INTERVAL))) .map(move |_| { let mut state = state_rc.borrow_mut(); let last_heard_cutoff = Instant::now() - Duration::from_secs(KEEPALIVE_CUTOFF); state .new_peer_backoff .retain(|_, ts| *ts > last_heard_cutoff); state .peers .retain(|_, info| info.last_heard_from > last_heard_cutoff); debug!("peers: {:?}", state.peers.keys()); let mut keepalives = Vec::with_capacity(state.peers.len()); for addr in state .peers .iter() .map(|(a, _)| a) .chain(configured_peers.iter()) { let mut rand_peers = [zero_v6_addr!(); 8]; state.get_rand_peers(&mut rand_peers); keepalives.push(( (network, Message::Keepalive(rand_peers)), SocketAddr::V6(*addr), )); } stream::iter_ok::<_, io::Error>(keepalives.into_iter()) }) .flatten(); let send_messages = self.send_messages.map(move |(msg, addr)| ((network, msg), addr)); Ok(Box::new( sink.send_all( ignore_errors::<_, io::Error>(process_messages) .select(ignore_errors(keepalive)) .select(ignore_errors(send_messages)), ).map(|_| ()) .map_err(|_| ()), )) } }
use std::iter::IntoIterator; use std::io; use std::net::{SocketAddr, SocketAddrV6, ToSocketAddrs}; use std::cell::RefCell; use std::rc::Rc; use std::time::{Duration, Instant}; use std::collections::{hash_map, HashMap}; use std::marker::PhantomData; use std::fmt::Debug; #[macro_use] extern crate log; #[macro_use] extern crate futures; use futures::{stream, Future, Sink, Stream}; extern crate net2; use net2::UdpBuilder; extern crate bytes; extern crate tokio; use tokio::net::UdpSocket; use tokio::reactor::Handle; extern crate tokio_io; extern crate tokio_timer; use tokio_timer::Timer; extern crate rand; use rand::{thread_rng, Rng}; extern crate nanocurrency_protocol; use nanocurrency_protocol::*; #[macro_use] extern crate nanocurrency_types; use nanocurrency_types::Network; mod udp_frame
hash_map::Entry::Vacant(entry) => { entry.insert(Instant::now()); } } if state.peers.contains_key(&new_peer) { return None; } let ip = new_peer.ip().clone(); if ip.octets().iter().all(|&x| x == 0) { return None; } if new_peer.port() == 0 { return None; } if ip.is_unspecified() || ip.is_loopback() || ip.is_multicast() { return None; } let mut rand_peers = [zero_v6_addr!(); 8]; state.get_rand_peers(&mut rand_peers); Some(( (network, Message::Keepalive(rand_peers)), SocketAddr::V6(new_peer), )) }, )); } _ => {} } output_messages.extend( (message_handler)(&state, header, msg, src) .into_iter() .map(|(m, a)| ((network, m), a)), ); stream::iter_ok::<_, io::Error>(output_messages) }; let process_messages = stream.map(process_message).flatten(); let state_rc = self.state_base.clone(); let timer = Timer::default(); let keepalive = stream::once(Ok(())) .chain(timer.interval(Duration::from_secs(KEEPALIVE_INTERVAL))) .map(move |_| { let mut state = state_rc.borrow_mut(); let last_heard_cutoff = Instant::now() - Duration::from_secs(KEEPALIVE_CUTOFF); state .new_peer_backoff .retain(|_, ts| *ts > last_heard_cutoff); state .peers .retain(|_, info| info.last_heard_from > last_heard_cutoff); debug!("peers: {:?}", state.peers.keys()); let mut keepalives = Vec::with_capacity(state.peers.len()); for addr in state .peers .iter() .map(|(a, _)| a) .chain(configured_peers.iter()) { let mut rand_peers = [zero_v6_addr!(); 8]; state.get_rand_peers(&mut rand_peers); keepalives.push(( (network, Message::Keepalive(rand_peers)), SocketAddr::V6(*addr), )); } stream::iter_ok::<_, io::Error>(keepalives.into_iter()) }) .flatten(); let send_messages = self.send_messages.map(move |(msg, addr)| ((network, msg), addr)); Ok(Box::new( sink.send_all( ignore_errors::<_, io::Error>(process_messages) .select(ignore_errors(keepalive)) .select(ignore_errors(send_messages)), ).map(|_| ()) .map_err(|_| ()), )) } }
d; const KEEPALIVE_INTERVAL: u64 = 60; const KEEPALIVE_CUTOFF: u64 = KEEPALIVE_INTERVAL * 5; pub fn addr_to_ipv6(addr: SocketAddr) -> SocketAddrV6 { match addr { SocketAddr::V4(addr) => SocketAddrV6::new(addr.ip().to_ipv6_mapped(), addr.port(), 0, 0), SocketAddr::V6(addr) => addr, } } struct IgnoreErrors<S: Stream, E> where S::Error: Debug, { inner: S, err_phantom: PhantomData<E>, } impl<S: Stream, E: Debug> Stream for IgnoreErrors<S, E> where S::Error: Debug, { type Item = S::Item; type Error = E; fn poll(&mut self) -> Result<futures::Async<Option<S::Item>>, E> { loop { match self.inner.poll() { Ok(x) => return Ok(x), Err(err) => debug!("ignoring error: {:?}", err), } } } } fn ignore_errors<S: Stream, E>(stream: S) -> IgnoreErrors<S, E> where S::Error: Debug, { IgnoreErrors { inner: stream, err_phantom: PhantomData, } } pub struct PeerInfo { pub last_heard_from: Instant, pub network_version: u8, _private: (), } #[derive(Default)] pub struct PeeringManagerState { peers: HashMap<SocketAddrV6, PeerInfo>, rand_peers: RefCell<Vec<SocketAddrV6>>, new_peer_backoff: HashMap<SocketAddrV6, Instant>, } impl PeeringManagerState { pub fn get_rand_peers(&self, peers_out: &mut [SocketAddrV6]) { if self.peers.len() < peers_out.len() { for (peer, peer_out) in self.peers.keys().zip(peers_out.iter_mut()) { *peer_out = *peer; } return; } let mut thread_rng = thread_rng(); let mut rand_peers = self.rand_peers.borrow_mut(); for peer_out in peers_out.iter_mut() { if rand_peers.is_empty() { rand_peers.extend(self.peers.keys()); thread_rng.shuffle(&mut rand_peers); } *peer_out = rand_peers.pop().unwrap(); } } pub fn peers(&self) -> &HashMap<SocketAddrV6, PeerInfo> { &self.peers } fn contacted(&mut self, addr: SocketAddr, header: &MessageHeader) { let addr = addr_to_ipv6(addr); match self.peers.entry(addr) { hash_map::Entry::Occupied(mut entry) => { entry.get_mut().last_heard_from = Instant::now(); } hash_map::Entry::Vacant(entry) => { entry.insert(PeerInfo { last_heard_from: Instant::now(), network_version: header.version, _private: (), }); } } } } pub struct PeeringManagerBuilder<F, I, II> where I: Iterator<Item = (Message, SocketAddr)>, II: IntoIterator<Item = (Message, SocketAddr), IntoIter = I>, F: Fn(&PeeringManagerState, MessageHeader, Message, SocketAddr) -> II + 'static, { use_official_peers: bool, custom_peers: Vec<SocketAddr>, listen_addr: SocketAddr, network: Network, message_handler: F, state_base: Rc<RefCell<PeeringManagerState>>, send_messages: Box<Stream<Item = (Message, SocketAddr), Error = ()>>, } impl<F, I, II> PeeringManagerBuilder<F, I, II> where I: Iterator<Item = (Message, SocketAddr)>, II: IntoIterator<Item = (Message, SocketAddr), IntoIter = I>, F: Fn(&PeeringManagerState, MessageHeader, Message, SocketAddr) -> II + 'static, { pub fn new(message_handler: F) -> PeeringManagerBuilder<F, I, II> { PeeringManagerBuilder { use_official_peers: true, custom_peers: Vec::new(), listen_addr: "[::]:7075".parse().unwrap(), network: Network::Live, message_handler, state_base: Default::default(), send_messages: Box::new(stream::empty()), } } pub fn use_official_peers(mut self, value: bool) -> Self { self.use_official_peers = value; self } pub fn custom_peers(mut self, value: Vec<SocketAddr>) -> Self { self.custom_peers = value; self } pub fn listen_addr(mut self, value: SocketAddr) -> Self { self.listen_addr = value; self } pub fn network(mut self, value: Network) -> Self { self.network = value; self } pub fn state_base(mut self, value: Rc<RefCell<PeeringManagerState>>) -> Self { self.state_base = value; self } pub fn send_messages( mut self, value: Box<Stream<Item = (Message, SocketAddr), Error = ()>>, ) -> Self { self.send_messages = value; self } pub fn run(self) -> io::Result<Box<Future<Item = (), Error = ()>>> { let mut configured_peers: Vec<SocketAddrV6> = Vec::new(); if self.use_official_peers { let official_domain = match self.network { Network::Live => Some("rai.raiblocks.net:7075"), Network::Beta => Some("rai-beta.raiblocks.net:7075"), Network::Test => None, }; if let Some(official_domain) = official_domain { configured_peers.extend(official_domain.to_socket_addrs()?.map(addr_to_ipv6)); } } configured_peers.extend(self.custom_peers.into_iter().map(addr_to_ipv6)); let socket; if cfg!(target_os = "windows") { let std_socket = UdpBuilder::new_v6()? .only_v6(false)? .bind(self.listen_addr)?; socket = UdpSocket::from_std(std_socket, &Handle::current())?; } else { socket = UdpSocket::bind(&self.listen_addr)?; } let (sink, stream) = udp_framed::UdpFramed::new(socket, NanoCurrencyCodec).split(); let network = self.network; let message_handler = self.message_handler; let state_rc = self.state_base.clone(); let process_message = move |((header, msg), src)| { let _: &MessageHeader = &header; if header.network != network { warn!("ignoring message from {:?} network", header.network); return stream::iter_ok(Vec::new().into_iter()); } let mut state = state_rc.borrow_mut(); state.contacted(src, &header); trace!("got message from {:?}: {:?}", src, msg); let mut output_messages = Vec::new(); match msg { Message::Keepalive(new_peers) => { let state = &mut state; output_messages.extend(new_peers.to_vec().into_iter().filter_map( move |new_peer| { match state.new_peer_backoff.entry(new_peer) { hash_map::Entry::Occupied(mut entry) => { let entry = entry.get_mut(); if *entry > Instant::now() - Duration::from_secs(KEEPALIVE_CUTOFF) { return None; } *entry = Instant::now(); }
random
[ { "content": "mod serde;\n", "file_path": "nanocurrency-types/src/tests/mod.rs", "rank": 2, "score": 26395.1323353986 }, { "content": "mod udp_encode_decode;\n", "file_path": "nanocurrency-protocol/src/tests/mod.rs", "rank": 3, "score": 26394.98531009027 }, { "content": "pub fn run(conf: NodeConfig) -> Box<Future<Item = (), Error = ()>> {\n\n let network = conf.network;\n\n let message_handler =\n\n move |peering: &PeeringManagerState, _header, message, _src| {\n\n let mut output = Vec::new();\n\n match message {\n\n Message::Keepalive(_) => {}\n\n Message::ConfirmReq(_) => {} // probably a rep crawler\n\n Message::Publish(block) => {\n\n if block.work_valid(network) {\n\n debug!(\"got block: {:?}\", block.get_hash());\n\n let mut peers =\n\n vec![zero_v6_addr!(); (peering.peers().len() as f64).sqrt() as usize];\n\n peering.get_rand_peers(&mut peers);\n\n output.extend(peers.into_iter().map(move |peer| {\n\n (Message::Publish(block.clone()), SocketAddr::V6(peer))\n\n }));\n\n }\n\n }\n\n Message::ConfirmAck(Vote { block, .. }) => {\n", "file_path": "src/node.rs", "rank": 4, "score": 21081.13542522305 }, { "content": "fn write_hex(f: &mut fmt::Formatter, bytes: &[u8]) -> fmt::Result {\n\n for b in bytes.iter() {\n\n write!(f, \"{:02X}\", b)?;\n\n }\n\n Ok(())\n\n}\n\n\n", "file_path": "nanocurrency-types/src/lib.rs", "rank": 5, "score": 19747.355328020887 }, { "content": "extern crate net2;\n\nextern crate tokio_io;\n\nextern crate tokio_timer;\n\n\n\nextern crate rand;\n\n\n\nextern crate curve25519_dalek;\n\nextern crate ed25519_dalek;\n\n\n\nextern crate bytes;\n\n\n\nextern crate nanocurrency_types;\n\nuse nanocurrency_types::Network;\n\n\n\nextern crate nanocurrency_protocol;\n\n\n\nextern crate nanocurrency_peering;\n\n\n\n#[macro_use]\n\nmod node;\n\n\n", "file_path": "src/main.rs", "rank": 8, "score": 20.064491132220496 }, { "content": "use std::net::SocketAddr;\n\nuse std::process;\n\nuse std::collections::HashMap;\n\n\n\nextern crate blake2;\n\nextern crate digest;\n\n\n\nextern crate byteorder;\n\n\n\nextern crate clap;\n\nuse clap::Arg;\n\n\n\nextern crate env_logger;\n\n#[macro_use]\n\nextern crate log;\n\n\n\nextern crate futures;\n\nuse futures::future;\n\nextern crate tokio;\n\nuse tokio::runtime::current_thread;\n", "file_path": "src/main.rs", "rank": 10, "score": 18.259980063525038 }, { "content": "use std::io;\n\nuse std::io::prelude::*;\n\nuse std::io::Cursor;\n\nuse std::net;\n\nuse std::net::SocketAddrV6;\n\n\n\nextern crate byteorder;\n\nuse byteorder::{BigEndian, ByteOrder, LittleEndian, ReadBytesExt};\n\n\n\nextern crate ed25519_dalek;\n\nuse ed25519_dalek::PublicKey;\n\n\n\nextern crate tokio_codec;\n\n\n\nextern crate bytes;\n\nuse bytes::{BufMut, BytesMut};\n\n\n\nextern crate nanocurrency_types;\n\nuse nanocurrency_types::*;\n\n\n", "file_path": "nanocurrency-protocol/src/lib.rs", "rank": 11, "score": 14.690560327032266 }, { "content": "use std::io;\n\nuse std::net::{Ipv4Addr, SocketAddr, SocketAddrV4};\n\n\n\nuse futures::{Async, AsyncSink, Poll, Sink, StartSend, Stream};\n\n\n\nuse tokio::net::UdpSocket;\n\n\n\nuse tokio_io::codec::{Decoder, Encoder};\n\nuse bytes::{BufMut, BytesMut};\n\n\n\n/// A unified `Stream` and `Sink` interface to an underlying `UdpSocket`, using\n\n/// the `Encoder` and `Decoder` traits to encode and decode frames.\n\n///\n\n/// Raw UDP sockets work with datagrams, but higher-level code usually wants to\n\n/// batch these into meaningful chunks, called \"frames\". This method layers\n\n/// framing on top of this socket by using the `Encoder` and `Decoder` traits to\n\n/// handle encoding and decoding of messages frames. Note that the incoming and\n\n/// outgoing frame types may be distinct.\n\n///\n\n/// This function returns a *single* object that is both `Stream` and `Sink`;\n", "file_path": "nanocurrency-peering/src/udp_framed.rs", "rank": 12, "score": 12.957657863183188 }, { "content": "\n\nextern crate ed25519_dalek;\n\nuse ed25519_dalek::PublicKey;\n\npub use ed25519_dalek::Signature;\n\n\n\nextern crate hex;\n\n\n\nextern crate serde;\n\nuse serde::de::Error as SerdeError;\n\nuse serde::de::Visitor as serdeVisitor;\n\nuse serde::Deserialize;\n\n\n\n#[macro_use]\n\nextern crate serde_derive;\n\n\n\n#[cfg(test)]\n\nextern crate serde_json;\n\n\n\n#[cfg(test)]\n\nmod tests;\n", "file_path": "nanocurrency-types/src/lib.rs", "rank": 13, "score": 12.004966970883276 }, { "content": "use std::borrow::Cow;\n\nuse std::convert::AsRef;\n\nuse std::fmt;\n\nuse std::hash::{Hash, Hasher};\n\nuse std::iter;\n\nuse std::str;\n\nuse std::str::FromStr;\n\n\n\nextern crate blake2;\n\nuse blake2::{Blake2b, VarBlake2b};\n\nextern crate digest;\n\nuse digest::{Input, VariableOutput};\n\n\n\nextern crate byteorder;\n\nuse byteorder::{BigEndian, ByteOrder, LittleEndian};\n\n\n\nextern crate num_bigint;\n\nuse num_bigint::BigInt;\n\nextern crate num_traits;\n\nuse num_traits::cast::ToPrimitive;\n", "file_path": "nanocurrency-types/src/lib.rs", "rank": 14, "score": 11.368062922212912 }, { "content": "use std::net::Ipv4Addr;\n\nuse std::net::SocketAddrV6;\n\n\n\nuse ed25519_dalek::PublicKey;\n\n\n\nuse tokio_codec::{Decoder, Encoder};\n\n\n\nuse bytes::BytesMut;\n\n\n\nuse nanocurrency_types::*;\n\n\n\nuse Message;\n\nuse NanoCurrencyCodec;\n\n\n\n/// A list of blocks for testing\n", "file_path": "nanocurrency-protocol/src/tests/udp_encode_decode.rs", "rank": 15, "score": 8.384550044188604 }, { "content": "/// grouping this into a single object is often useful for layering things which\n\n/// require both read and write access to the underlying object.\n\n///\n\n/// If you want to work more directly with the streams and sink, consider\n\n/// calling `split` on the `UdpFramed` returned by this method, which will break\n\n/// them into separate objects, allowing them to interact more easily.\n\n#[must_use = \"sinks do nothing unless polled\"]\n\n#[derive(Debug)]\n\npub struct UdpFramed<C> {\n\n socket: UdpSocket,\n\n codec: C,\n\n rd: BytesMut,\n\n wr: BytesMut,\n\n out_addr: SocketAddr,\n\n flushed: bool,\n\n}\n\n\n\nimpl<C: Decoder> Stream for UdpFramed<C> {\n\n type Item = (C::Item, SocketAddr);\n\n type Error = C::Error;\n", "file_path": "nanocurrency-peering/src/udp_framed.rs", "rank": 16, "score": 8.170076594385192 }, { "content": "use std::net::SocketAddr;\n\nuse std::collections::HashMap;\n\n\n\nuse futures::Future;\n\n\n\nuse nanocurrency_types::*;\n\nuse nanocurrency_protocol::*;\n\nuse nanocurrency_peering::{PeeringManagerBuilder, PeeringManagerState};\n\n\n\npub struct NodeConfig {\n\n pub custom_peers: Vec<SocketAddr>,\n\n pub use_official_peers: bool,\n\n pub vote_weights: HashMap<Account, u128>,\n\n pub listen_addr: SocketAddr,\n\n pub network: Network,\n\n}\n\n\n", "file_path": "src/node.rs", "rank": 18, "score": 5.878362325562678 }, { "content": " pub fn get_hash(&self) -> BlockHash {\n\n self.inner.get_hash()\n\n }\n\n\n\n pub fn previous(&self) -> Option<&BlockHash> {\n\n self.inner.previous()\n\n }\n\n\n\n pub fn root_bytes(&self) -> &[u8; 32] {\n\n self.inner.root_bytes()\n\n }\n\n\n\n pub fn into_root(self) -> BlockRoot {\n\n self.inner.into_root()\n\n }\n\n\n\n #[deprecated]\n\n /// Use global work_threshold function instead\n\n pub fn work_threshold(&self, network: Network) -> u64 {\n\n work_threshold(network)\n", "file_path": "nanocurrency-types/src/lib.rs", "rank": 22, "score": 4.156839098435363 }, { "content": "use Account;\n\nuse Block;\n\nuse BlockInner;\n\nuse BlockType;\n\nuse Network;\n\n\n\nuse hex;\n\nuse serde_json;\n\n\n\n#[test]\n", "file_path": "nanocurrency-types/src/tests/serde.rs", "rank": 24, "score": 4.07340723170468 }, { "content": " );\n\n vote_weights.insert(\n\n \"bcb_1anrzcuwe64rwxzcco8dkhpyxpi8kd7zsjc1oeimpc3ppca4mrjtwnqposrs\"\n\n .parse()\n\n .unwrap(),\n\n 1,\n\n );\n\n let node_config = node::NodeConfig {\n\n network,\n\n use_official_peers,\n\n custom_peers,\n\n listen_addr,\n\n vote_weights,\n\n };\n\n current_thread::block_on_all(future::lazy(|| node::run(node_config)))\n\n .expect(\"failed to run node\");\n\n}\n", "file_path": "src/main.rs", "rank": 26, "score": 3.9295535327109987 }, { "content": " match *self {\n\n BlockRoot::Block(BlockHash(ref bytes)) => bytes,\n\n BlockRoot::Account(Account(ref bytes)) => bytes,\n\n }\n\n }\n\n}\n\n\n\nimpl Into<[u8; 32]> for BlockRoot {\n\n fn into(self) -> [u8; 32] {\n\n match self {\n\n BlockRoot::Block(BlockHash(bytes)) => bytes,\n\n BlockRoot::Account(Account(bytes)) => bytes,\n\n }\n\n }\n\n}\n\n\n\n#[derive(PartialEq, Eq, Clone, Copy, Debug)]\n\npub enum BlockType {\n\n Send,\n\n Receive,\n", "file_path": "nanocurrency-types/src/lib.rs", "rank": 28, "score": 3.616710697082153 }, { "content": "\n\n /// Returns a reference to the underlying I/O stream wrapped by `Framed`.\n\n ///\n\n /// # Note\n\n ///\n\n /// Care should be taken to not tamper with the underlying stream of data\n\n /// coming in as it may corrupt the stream of frames otherwise being worked\n\n /// with.\n\n pub fn get_ref(&self) -> &UdpSocket {\n\n &self.socket\n\n }\n\n\n\n /// Returns a mutable reference to the underlying I/O stream wrapped by\n\n /// `Framed`.\n\n ///\n\n /// # Note\n\n ///\n\n /// Care should be taken to not tamper with the underlying stream of data\n\n /// coming in as it may corrupt the stream of frames otherwise being worked\n\n /// with.\n", "file_path": "nanocurrency-peering/src/udp_framed.rs", "rank": 29, "score": 3.5740843937403413 }, { "content": "impl<C: Encoder> Sink for UdpFramed<C> {\n\n type SinkItem = (C::Item, SocketAddr);\n\n type SinkError = C::Error;\n\n\n\n fn start_send(&mut self, item: Self::SinkItem) -> StartSend<Self::SinkItem, Self::SinkError> {\n\n trace!(\"sending frame\");\n\n\n\n if !self.flushed {\n\n match self.poll_complete() {\n\n Ok(Async::Ready(())) => {}\n\n _ => return Ok(AsyncSink::NotReady(item)),\n\n }\n\n }\n\n\n\n let (frame, out_addr) = item;\n\n self.codec.encode(frame, &mut self.wr)?;\n\n self.out_addr = out_addr;\n\n self.flushed = false;\n\n trace!(\"frame encoded; length={}\", self.wr.len());\n\n\n", "file_path": "nanocurrency-peering/src/udp_framed.rs", "rank": 30, "score": 3.544997143601826 }, { "content": " ))\n\n }\n\n _ => {\n\n return Err(io::Error::new(\n\n io::ErrorKind::Other,\n\n \"unrecognized message type\",\n\n ))\n\n }\n\n };\n\n Ok(Some((header, message)))\n\n }\n\n}\n\n\n\nimpl tokio_codec::Encoder for NanoCurrencyCodec {\n\n type Item = (Network, Message);\n\n type Error = io::Error;\n\n\n\n fn encode(&mut self, msg: Self::Item, buf: &mut BytesMut) -> io::Result<()> {\n\n buf.reserve(8); // header (including extensions)\n\n buf.put_slice(&[\n", "file_path": "nanocurrency-protocol/src/lib.rs", "rank": 31, "score": 3.4514137349850382 }, { "content": "\n\n fn visit_str<E: serde::de::Error>(self, v: &str) -> Result<Vec<u8>, E> {\n\n if v.len() > self.byte_len * 2 {\n\n return Err(E::invalid_length(v.len(), &self));\n\n }\n\n let mut hex_string = Cow::Borrowed(v);\n\n if v.len() < self.byte_len * 2 {\n\n let mut new_string = String::with_capacity(self.byte_len * 2);\n\n for _ in 0..(self.byte_len * 2 - v.len()) {\n\n new_string.push('0');\n\n }\n\n new_string.extend(v.chars());\n\n hex_string = Cow::Owned(new_string);\n\n }\n\n let bytes = hex::decode((&hex_string).as_bytes())\n\n .map_err(|_| E::invalid_value(serde::de::Unexpected::Str(&v), &self))?;\n\n assert_eq!(\n\n bytes.len(),\n\n self.byte_len,\n\n \"Hex decoding produced unexpected length\"\n\n );\n\n Ok(bytes)\n\n }\n\n}\n\n\n", "file_path": "nanocurrency-types/src/lib.rs", "rank": 32, "score": 3.39272533600474 }, { "content": " if let Some(response) = response {\n\n buf.put_slice(&response.0.to_bytes());\n\n buf.put_slice(&response.1.to_bytes());\n\n }\n\n }\n\n }\n\n Ok(())\n\n }\n\n}\n", "file_path": "nanocurrency-protocol/src/lib.rs", "rank": 33, "score": 3.263784577864838 }, { "content": " }\n\n let header = MessageHeader {\n\n network,\n\n version_max,\n\n version,\n\n version_min,\n\n extensions,\n\n };\n\n let message = match msg_type {\n\n 2 => {\n\n // keepalive\n\n let mut peers = [zero_v6_addr!(); 8];\n\n let _ = (|| -> io::Result<()> {\n\n for peer in peers.iter_mut() {\n\n let mut ip_bytes: [u8; 16] = [0; 16];\n\n for byte in ip_bytes.iter_mut() {\n\n *byte = cursor.read_u8()?;\n\n }\n\n let port = cursor.read_u16::<LittleEndian>()?;\n\n *peer = SocketAddrV6::new(net::Ipv6Addr::from(ip_bytes), port, 0, 0);\n", "file_path": "nanocurrency-protocol/src/lib.rs", "rank": 34, "score": 3.142267789718826 }, { "content": " fn from_hex<'de, D: serde::de::Deserializer<'de>>(deserializer: D) -> Result<Self, D::Error> {\n\n deserializer\n\n .deserialize_str(InternalHexVisitor::new(8))\n\n .map(|bytes| BigEndian::read_u64(&bytes))\n\n }\n\n}\n\n\n\nimpl InternalFromHex for u128 {\n\n fn from_hex<'de, D: serde::de::Deserializer<'de>>(deserializer: D) -> Result<Self, D::Error> {\n\n deserializer\n\n .deserialize_str(InternalHexVisitor::new(16))\n\n .map(|bytes| BigEndian::read_u128(&bytes))\n\n }\n\n}\n\n\n\nimpl InternalFromHex for BlockHash {\n\n fn from_hex<'de, D: serde::de::Deserializer<'de>>(deserializer: D) -> Result<Self, D::Error> {\n\n deserializer\n\n .deserialize_str(InternalHexVisitor::new(32))\n\n .map(|bytes| {\n\n let mut hash = BlockHash([0u8; 32]);\n\n hash.0.clone_from_slice(&bytes);\n\n hash\n\n })\n\n }\n\n}\n\n\n", "file_path": "nanocurrency-types/src/lib.rs", "rank": 35, "score": 2.874920323762962 }, { "content": "// keepalive 2\n\n// publish 3\n\n// confirm_req 4\n\n// confirm_ack 5\n\n//\n\n// Bootstrap message types:\n\n// bulk_pull 6\n\n// bulk_push 7\n\n// frontier_req 8\n\n\n\nimpl tokio_codec::Decoder for NanoCurrencyCodec {\n\n type Item = (MessageHeader, Message);\n\n type Error = io::Error;\n\n\n\n fn decode(&mut self, buf: &mut BytesMut) -> io::Result<Option<Self::Item>> {\n\n let mut cursor = Cursor::new(buf);\n\n if cursor.read_u8()? != b'R' {\n\n return Err(io::Error::new(io::ErrorKind::Other, \"invalid magic number\"));\n\n }\n\n let network = match cursor.read_u8()? {\n", "file_path": "nanocurrency-protocol/src/lib.rs", "rank": 36, "score": 2.8328035734013204 }, { "content": " ext_pubkey = ext_pubkey + byte;\n\n i += 1;\n\n }\n\n if i != 60 {\n\n return Err(AccountParseError::IncorrectLength);\n\n }\n\n let ext_pubkey = ext_pubkey.to_bytes_le().1;\n\n if ext_pubkey.len() > 37 {\n\n // First character is not a 1 or a 3,\n\n // which causes the pubkey to be too long.\n\n return Err(AccountParseError::IncorrectLength);\n\n }\n\n let ext_pubkey: Vec<u8> = iter::repeat(0)\n\n .take(37 - ext_pubkey.len())\n\n .chain(ext_pubkey.into_iter().rev())\n\n .collect();\n\n let mut pubkey_bytes = [0u8; 32];\n\n pubkey_bytes.clone_from_slice(&ext_pubkey[..32]);\n\n let mut checksum_given = [0u8; 5];\n\n checksum_given.clone_from_slice(&ext_pubkey[32..]);\n", "file_path": "nanocurrency-types/src/lib.rs", "rank": 37, "score": 2.779092743654064 }, { "content": "# Railroad\n\n\n\nThis project aims to be a Rust light node.\n\nCurrently, only the types, protocol, and peering are complete.\n\nThese are very useful in prototyping other projects based on the protocol.\n", "file_path": "README.md", "rank": 39, "score": 2.5591429813655697 }, { "content": " if block.work_valid(network) {\n\n debug!(\"got block: {:?}\", block.get_hash());\n\n // TODO processing\n\n // TODO rebroadcasting\n\n }\n\n }\n\n }\n\n output.into_iter()\n\n };\n\n PeeringManagerBuilder::new(message_handler)\n\n .use_official_peers(conf.use_official_peers)\n\n .custom_peers(conf.custom_peers)\n\n .listen_addr(conf.listen_addr)\n\n .network(conf.network)\n\n .run()\n\n .expect(\"failed to start node\")\n\n}\n", "file_path": "src/node.rs", "rank": 42, "score": 2.4536210453614773 }, { "content": " pub fn get_mut(&mut self) -> &mut UdpSocket {\n\n &mut self.socket\n\n }\n\n\n\n /// Consumes the `Framed`, returning its underlying I/O stream.\n\n pub fn into_inner(self) -> UdpSocket {\n\n self.socket\n\n }\n\n}\n", "file_path": "nanocurrency-peering/src/udp_framed.rs", "rank": 43, "score": 2.43368445166293 }, { "content": " buf.put_slice(&block.header.signature.to_bytes() as &[u8]);\n\n if work_big_endian {\n\n buf.put_u64_be(block.header.work);\n\n } else {\n\n buf.put_u64_le(block.header.work);\n\n }\n\n }\n\n\n\n pub fn network_magic_byte(network: Network) -> u8 {\n\n match network {\n\n Network::Test => b'A',\n\n Network::Beta => b'B',\n\n Network::Live => b'C',\n\n }\n\n }\n\n}\n\n\n\n// Message types:\n\n// invalid 0\n\n// not_a_type 1\n", "file_path": "nanocurrency-protocol/src/lib.rs", "rank": 44, "score": 2.421264317664718 }, { "content": " let mut bytes = [0u8; 16];\n\n BigEndian::write_u128(&mut bytes, *self);\n\n serializer.serialize_str(&hex::encode_upper(&bytes))\n\n }\n\n}\n\n\n\nimpl InternalToHex for BlockHash {\n\n fn to_hex<S: serde::ser::Serializer>(&self, serializer: S) -> Result<S::Ok, S::Error> {\n\n serializer.serialize_str(&hex::encode_upper(&self.0))\n\n }\n\n}\n\n\n\nimpl InternalToHex for [u8; 32] {\n\n fn to_hex<S: serde::ser::Serializer>(&self, serializer: S) -> Result<S::Ok, S::Error> {\n\n serializer.serialize_str(&hex::encode_upper(&self))\n\n }\n\n}\n\n\n\n#[derive(Debug, Clone, PartialEq, Deserialize, Serialize)]\n\npub struct BlockHeader {\n", "file_path": "nanocurrency-types/src/lib.rs", "rank": 45, "score": 2.420757931845615 }, { "content": "}\n\n\n\nimpl Hash for Vote {\n\n fn hash<H: Hasher>(&self, state: &mut H) {\n\n state.write(&self.block.get_hash().0);\n\n let mut seq_bytes = [0u8; 8];\n\n LittleEndian::write_u64(&mut seq_bytes, self.sequence);\n\n state.write(&seq_bytes);\n\n }\n\n}\n\n\n\nimpl Vote {\n\n pub fn get_hash(&self) -> [u8; 32] {\n\n let mut hasher = VarBlake2b::new(32).expect(\"Unsupported hash length\");\n\n self.hash(&mut DigestHasher(&mut hasher));\n\n let mut output = [0u8; 32];\n\n hasher.variable_result(|b| output.copy_from_slice(b));\n\n output\n\n }\n\n\n\n pub fn verify(&self) -> bool {\n\n self.account\n\n .as_pubkey()\n\n .verify::<Blake2b>(&self.get_hash(), &self.signature)\n\n .is_ok()\n\n }\n\n}\n", "file_path": "nanocurrency-types/src/lib.rs", "rank": 46, "score": 2.4073962032124596 }, { "content": " let mut hasher = VarBlake2b::new(5).unwrap();\n\n hasher.input(&pubkey_bytes as &[u8]);\n\n let mut matches = false;\n\n hasher.variable_result(move |checksum_calc| {\n\n matches = checksum_given.iter().rev().eq(checksum_calc.into_iter());\n\n });\n\n if matches {\n\n Err(AccountParseError::InvalidChecksum)\n\n } else {\n\n Ok(Account(pubkey_bytes))\n\n }\n\n }\n\n}\n\n\n\nimpl Hash for Account {\n\n fn hash<H: Hasher>(&self, state: &mut H) {\n\n state.write(&self.0);\n\n }\n\n}\n\n\n", "file_path": "nanocurrency-types/src/lib.rs", "rank": 48, "score": 2.287902145945119 }, { "content": "#[cfg(test)]\n\nmod tests;\n\n\n\nconst NET_VERSION: u8 = 0x10;\n\nconst NET_VERSION_MAX: u8 = 0x10;\n\nconst NET_VERSION_MIN: u8 = 0x01;\n\n\n\nconst NODE_ID_HANDSHAKE_QUERY_FLAG: u16 = 1 << 0;\n\nconst NODE_ID_HANDSHAKE_RESPONSE_FLAG: u16 = 1 << 1;\n\n\n", "file_path": "nanocurrency-protocol/src/lib.rs", "rank": 49, "score": 2.130282197566632 }, { "content": "\n\n fn poll(&mut self) -> Poll<Option<(Self::Item)>, Self::Error> {\n\n self.rd.reserve(INITIAL_RD_CAPACITY);\n\n\n\n let (n, addr) = unsafe {\n\n // Read into the buffer without having to initialize the memory.\n\n let (n, addr) = try_ready!(self.socket.poll_recv_from(self.rd.bytes_mut()));\n\n self.rd.advance_mut(n);\n\n (n, addr)\n\n };\n\n trace!(\"received {} bytes, decoding\", n);\n\n let frame_res = self.codec.decode(&mut self.rd);\n\n self.rd.clear();\n\n let frame = frame_res?;\n\n let result = frame.map(|frame| (frame, addr)); // frame -> (frame, addr)\n\n trace!(\"frame decoded from buffer\");\n\n Ok(Async::Ready(result))\n\n }\n\n}\n\n\n", "file_path": "nanocurrency-peering/src/udp_framed.rs", "rank": 50, "score": 2.075588891602179 }, { "content": "}\n\n\n\nconst INITIAL_RD_CAPACITY: usize = 64 * 1024;\n\nconst INITIAL_WR_CAPACITY: usize = 8 * 1024;\n\n\n\n#[allow(dead_code)]\n\nimpl<C> UdpFramed<C> {\n\n /// Create a new `UdpFramed` backed by the given socket and codec.\n\n ///\n\n /// See struct level documention for more details.\n\n pub fn new(socket: UdpSocket, codec: C) -> UdpFramed<C> {\n\n UdpFramed {\n\n socket: socket,\n\n codec: codec,\n\n out_addr: SocketAddr::V4(SocketAddrV4::new(Ipv4Addr::new(0, 0, 0, 0), 0)),\n\n rd: BytesMut::with_capacity(INITIAL_RD_CAPACITY),\n\n wr: BytesMut::with_capacity(INITIAL_WR_CAPACITY),\n\n flushed: true,\n\n }\n\n }\n", "file_path": "nanocurrency-peering/src/udp_framed.rs", "rank": 51, "score": 1.9768110549418547 }, { "content": " };\n\n let response = if header.extensions & NODE_ID_HANDSHAKE_RESPONSE_FLAG != 0 {\n\n let mut pubkey = [0u8; 32];\n\n cursor.read_exact(&mut pubkey)?;\n\n let pubkey = PublicKey::from_bytes(&pubkey)\n\n .map_err(|_| io::Error::new(io::ErrorKind::Other, \"bad pubkey\"))?;\n\n let mut signature = [0u8; 64];\n\n cursor.read_exact(&mut signature)?;\n\n let signature = Signature::from_bytes(&signature)\n\n .map_err(|_| io::Error::new(io::ErrorKind::Other, \"bad signature\"))?;\n\n Some((pubkey, signature))\n\n } else {\n\n None\n\n };\n\n Message::NodeIdHandshake(query, response)\n\n }\n\n 6 | 7 | 8 => {\n\n return Err(io::Error::new(\n\n io::ErrorKind::Other,\n\n \"bootstrap message sent over UDP\",\n", "file_path": "nanocurrency-protocol/src/lib.rs", "rank": 52, "score": 1.9502924985333339 }, { "content": " }\n\n\n\n pub fn work_value(&self) -> u64 {\n\n work_value(self.root_bytes() as _, self.header.work)\n\n }\n\n\n\n pub fn work_valid(&self, network: Network) -> bool {\n\n self.work_value() > work_threshold(network)\n\n }\n\n\n\n pub fn ty(&self) -> BlockType {\n\n self.inner.ty()\n\n }\n\n\n\n pub fn size(&self) -> usize {\n\n // inner + sig + work\n\n self.inner.size() + 64 + 8\n\n }\n\n}\n\n\n", "file_path": "nanocurrency-types/src/lib.rs", "rank": 53, "score": 1.8637290496995376 }, { "content": " }\n\n}\n\n\n\nimpl Hash for BlockHash {\n\n fn hash<H: Hasher>(&self, state: &mut H) {\n\n state.write(&self.0);\n\n }\n\n}\n\n\n\npub const ACCOUNT_LOOKUP: &[u8] = b\"13456789abcdefghijkmnopqrstuwxyz\";\n\n\n\n#[derive(Default, PartialEq, Eq, Clone)]\n\npub struct Account(pub [u8; 32]);\n\n\n\nimpl Account {\n\n pub fn as_pubkey(&self) -> PublicKey {\n\n PublicKey::from_bytes(&self.0).unwrap()\n\n }\n\n}\n\n\n", "file_path": "nanocurrency-types/src/lib.rs", "rank": 54, "score": 1.8171397621649326 }, { "content": " Ok(AsyncSink::Ready)\n\n }\n\n\n\n fn poll_complete(&mut self) -> Poll<(), C::Error> {\n\n if self.flushed {\n\n return Ok(Async::Ready(()));\n\n }\n\n\n\n trace!(\"flushing frame; length={}\", self.wr.len());\n\n let n = match self.socket.poll_send_to(&self.wr, &self.out_addr) {\n\n Ok(Async::Ready(n)) => n,\n\n Ok(Async::NotReady) => return Ok(Async::NotReady),\n\n Err(e) => {\n\n if e.kind() == ::std::io::ErrorKind::WouldBlock {\n\n return Ok(Async::NotReady);\n\n }\n\n debug!(\"error sending frame: {:?}\", e);\n\n return Ok(Async::Ready(()));\n\n }\n\n };\n", "file_path": "nanocurrency-peering/src/udp_framed.rs", "rank": 55, "score": 1.6337782917250836 }, { "content": " if s.starts_with(\"bcb_\") {\n\n (&mut s_chars).take(4).count();\n\n } else if s.starts_with(\"nano_\") {\n\n (&mut s_chars).take(5).count();\n\n } else {\n\n return Err(AccountParseError::MissingPrefix);\n\n }\n\n let mut i = 0;\n\n for ch in s_chars {\n\n if i >= 60 {\n\n return Err(AccountParseError::IncorrectLength);\n\n }\n\n let lookup = ACCOUNT_LOOKUP.iter().position(|&c| (c as char) == ch);\n\n let byte = match lookup {\n\n Some(p) => p as u8,\n\n None => {\n\n return Err(AccountParseError::InvalidCharacter(ch));\n\n }\n\n };\n\n ext_pubkey = ext_pubkey << 5;\n", "file_path": "nanocurrency-types/src/lib.rs", "rank": 56, "score": 1.5631494492696136 }, { "content": " let mut buf = [0u8; 16];\n\n BigEndian::write_u128(&mut buf, n);\n\n self.put_slice(&buf)\n\n }\n\n}\n\n\n\nimpl BufMutExt for BytesMut {}\n\n\n\n// Note: this does not include the message type.\n\n// That's wrapped into the Message enum.\n\n#[allow(dead_code)]\n\n#[derive(PartialEq, Eq, Clone, Debug)]\n\npub struct MessageHeader {\n\n pub network: Network,\n\n pub version_max: u8,\n\n pub version: u8,\n\n pub version_min: u8,\n\n pub extensions: u16,\n\n}\n\n\n", "file_path": "nanocurrency-protocol/src/lib.rs", "rank": 57, "score": 1.5143044701519774 }, { "content": "\n\n pub fn block_type_num(block: &Block) -> u8 {\n\n match block.inner {\n\n BlockInner::Send { .. } => 2,\n\n BlockInner::Receive { .. } => 3,\n\n BlockInner::Open { .. } => 4,\n\n BlockInner::Change { .. } => 5,\n\n BlockInner::State { .. } => 6,\n\n }\n\n }\n\n\n\n /// Does NOT include block type\n\n pub fn write_block(buf: &mut BytesMut, block: Block) {\n\n buf.reserve(block.size());\n\n let mut work_big_endian = false;\n\n match block.inner {\n\n BlockInner::Send {\n\n previous,\n\n destination,\n\n balance,\n", "file_path": "nanocurrency-protocol/src/lib.rs", "rank": 58, "score": 1.498694172283337 }, { "content": " BlockInner::Send { ref previous, .. } => Some(previous),\n\n BlockInner::Receive { ref previous, .. } => Some(previous),\n\n BlockInner::Change { ref previous, .. } => Some(previous),\n\n BlockInner::Open { .. } => None,\n\n BlockInner::State { ref previous, .. } => {\n\n let is_zero = previous.0.iter().all(|&x| x == 0);\n\n if is_zero {\n\n None\n\n } else {\n\n Some(previous)\n\n }\n\n }\n\n }\n\n }\n\n\n\n pub fn root_bytes(&self) -> &[u8; 32] {\n\n match *self {\n\n BlockInner::Send { ref previous, .. } => &previous.0,\n\n BlockInner::Receive { ref previous, .. } => &previous.0,\n\n BlockInner::Change { ref previous, .. } => &previous.0,\n", "file_path": "nanocurrency-types/src/lib.rs", "rank": 59, "score": 1.4684195905768558 }, { "content": " let mut signature = [0u8; 64];\n\n cursor.read_exact(&mut signature)?;\n\n let signature = Signature::from_bytes(&signature).unwrap();\n\n let sequence = cursor.read_u64::<LittleEndian>()?;\n\n let block = Self::read_block(&mut cursor, ty as u8)?;\n\n Message::ConfirmAck(Vote {\n\n account,\n\n signature,\n\n sequence,\n\n block,\n\n })\n\n }\n\n 10 => {\n\n // node_id_handshake\n\n let query = if header.extensions & NODE_ID_HANDSHAKE_QUERY_FLAG != 0 {\n\n let mut query = [0u8; 32];\n\n cursor.read_exact(&mut query)?;\n\n Some(query)\n\n } else {\n\n None\n", "file_path": "nanocurrency-protocol/src/lib.rs", "rank": 60, "score": 1.4684195905768558 }, { "content": " };\n\n let use_official_peers = !matches.is_present(\"disable_official_peers\");\n\n if let Some(peers) = matches.values_of(\"peer\") {\n\n for node in peers {\n\n match node.parse() {\n\n Ok(node) => custom_peers.push(node),\n\n Err(err) => {\n\n eprintln!(\"Failed to parse custom peer {:?}: {}\", node, err);\n\n process::exit(1);\n\n }\n\n }\n\n }\n\n }\n\n let mut listen_addr = \"[::]:7075\".parse().unwrap();\n\n if let Some(addr) = matches.value_of(\"listen_address\") {\n\n match addr.parse() {\n\n Ok(addr) => listen_addr = addr,\n\n Err(err) => {\n\n eprintln!(\"Failed to parse listen address: {}\", err);\n\n process::exit(1);\n", "file_path": "src/main.rs", "rank": 61, "score": 1.4380668386481483 }, { "content": " return Err(io::Error::new(\n\n io::ErrorKind::Other,\n\n \"unrecognized block type\",\n\n ))\n\n }\n\n };\n\n let mut signature = [0u8; 64];\n\n cursor.read_exact(&mut signature)?;\n\n let signature = Signature::from_bytes(&signature)\n\n .map_err(|_| io::Error::new(io::ErrorKind::Other, \"bad signature\"))?;\n\n let work;\n\n if block_ty >= 6 {\n\n // New block types have work in big endian\n\n work = cursor.read_u64::<BigEndian>()?;\n\n } else {\n\n work = cursor.read_u64::<LittleEndian>()?;\n\n }\n\n let header = BlockHeader { signature, work };\n\n Ok(Block { header, inner })\n\n }\n", "file_path": "nanocurrency-protocol/src/lib.rs", "rank": 62, "score": 1.4113973313097175 }, { "content": " b'R',\n\n Self::network_magic_byte(msg.0),\n\n NET_VERSION_MAX,\n\n NET_VERSION,\n\n NET_VERSION_MIN,\n\n ]);\n\n match msg.1 {\n\n Message::Keepalive(peers) => {\n\n buf.put_slice(&[2]);\n\n buf.put_slice(&[0, 0]); // extensions\n\n buf.reserve(peers.len() * (16 + 2));\n\n for peer in peers.iter() {\n\n buf.put_slice(&peer.ip().octets());\n\n buf.put_u16_le(peer.port());\n\n }\n\n }\n\n Message::Publish(block) => {\n\n buf.put_slice(&[3]);\n\n let type_num = Self::block_type_num(&block) as u16;\n\n buf.put_u16_le((type_num & 0x0f) << 8);\n", "file_path": "nanocurrency-protocol/src/lib.rs", "rank": 63, "score": 1.358638149068112 }, { "content": " Self::write_block(buf, block);\n\n }\n\n Message::ConfirmReq(block) => {\n\n buf.put_slice(&[4]);\n\n let type_num = Self::block_type_num(&block) as u16;\n\n buf.put_u16_le((type_num & 0x0f) << 8);\n\n Self::write_block(buf, block);\n\n }\n\n Message::ConfirmAck(Vote {\n\n account,\n\n signature,\n\n sequence,\n\n block,\n\n }) => {\n\n buf.put_slice(&[5]);\n\n let type_num = Self::block_type_num(&block) as u16;\n\n buf.put_u16_le((type_num & 0x0f) << 8);\n\n buf.reserve(32 + 64 + 8);\n\n buf.put_slice(&account.0);\n\n buf.put_slice(&signature.to_bytes());\n", "file_path": "nanocurrency-protocol/src/lib.rs", "rank": 64, "score": 1.3460589539534253 }, { "content": " \"signature\": \"E7A791BC1AB92C91E3C0FAF37265B3832EE5E3A86070D5AADC734DFFB2788582FE6B2697B7C871BF2ECEC45198C444EA1FF95FCF3922C93B25710B85D0424B0B\",\n\n \"work\": \"fc1a2229b17264ba\"\n\n }\n\n \"#;\n\n let block: Block = serde_json::from_str(json).expect(\"Failed to deserialize block\");\n\n assert_eq!(\n\n serde_json::from_str::<Block>(json2).expect(\"Failed to deserialize block2\"),\n\n block\n\n );\n\n assert_eq!(block.ty(), BlockType::State);\n\n assert_eq!(block.header.work, 0xfc1a2229b17264ba);\n\n assert!(block.work_valid(Network::Live));\n\n assert_eq!(hex::encode_upper(&block.header.signature.to_bytes() as &[u8]), \"E7A791BC1AB92C91E3C0FAF37265B3832EE5E3A86070D5AADC734DFFB2788582FE6B2697B7C871BF2ECEC45198C444EA1FF95FCF3922C93B25710B85D0424B0B\");\n\n if let BlockInner::State {\n\n ref account,\n\n ref previous,\n\n ref representative,\n\n ref balance,\n\n ref link,\n\n } = block.inner\n", "file_path": "nanocurrency-types/src/tests/serde.rs", "rank": 65, "score": 1.2319926990640968 }, { "content": "impl fmt::Debug for Account {\n\n fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {\n\n fmt::Display::fmt(&self, f)\n\n }\n\n}\n\n\n\nimpl fmt::Display for Account {\n\n fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {\n\n write!(f, \"bcb_\")?;\n\n let mut reverse_chars = Vec::<u8>::new();\n\n let mut check_hash = VarBlake2b::new(5).unwrap();\n\n check_hash.input(&self.0 as &[u8]);\n\n let mut ext_addr = self.0.to_vec();\n\n check_hash.variable_result(|b| ext_addr.extend(b.iter().rev()));\n\n let mut ext_addr = BigInt::from_bytes_be(num_bigint::Sign::Plus, &ext_addr);\n\n for _ in 0..60 {\n\n let n: BigInt = (&ext_addr) % 32; // lower 5 bits\n\n reverse_chars.push(ACCOUNT_LOOKUP[n.to_usize().unwrap()]);\n\n ext_addr = ext_addr >> 5;\n\n }\n", "file_path": "nanocurrency-types/src/lib.rs", "rank": 66, "score": 1.144690779034108 } ]
Rust
fltk-derive/src/group.rs
andrrff/fltk-rs
1db0fd4c2341b005cd949ac6a3a7b8ab949ada6c
use crate::utils::get_fl_name; use proc_macro::TokenStream; use quote::*; use syn::*; pub fn impl_group_trait(ast: &DeriveInput) -> TokenStream { let name = &ast.ident; let name_str = get_fl_name(name.to_string()); let begin = Ident::new(format!("{}_{}", name_str, "begin").as_str(), name.span()); let end = Ident::new(format!("{}_{}", name_str, "end").as_str(), name.span()); let clear = Ident::new(format!("{}_{}", name_str, "clear").as_str(), name.span()); let children = Ident::new(format!("{}_{}", name_str, "children").as_str(), name.span()); let child = Ident::new(format!("{}_{}", name_str, "child").as_str(), name.span()); let find = Ident::new(format!("{}_{}", name_str, "find").as_str(), name.span()); let add = Ident::new(format!("{}_{}", name_str, "add").as_str(), name.span()); let insert = Ident::new(format!("{}_{}", name_str, "insert").as_str(), name.span()); let remove = Ident::new(format!("{}_{}", name_str, "remove").as_str(), name.span()); let remove_by_index = Ident::new( format!("{}_{}", name_str, "remove_by_index").as_str(), name.span(), ); let resizable = Ident::new( format!("{}_{}", name_str, "resizable").as_str(), name.span(), ); let clip_children = Ident::new( format!("{}_{}", name_str, "clip_children").as_str(), name.span(), ); let set_clip_children = Ident::new( format!("{}_{}", name_str, "set_clip_children").as_str(), name.span(), ); let init_sizes = Ident::new( format!("{}_{}", name_str, "init_sizes").as_str(), name.span(), ); let gen = quote! { impl IntoIterator for #name { type Item = Widget; type IntoIter = std::vec::IntoIter<Self::Item>; fn into_iter(self) -> Self::IntoIter { let mut v: Vec<Widget> = vec![]; for i in 0..self.children() { v.push(self.child(i).unwrap()); } v.into_iter() } } unsafe impl GroupExt for #name { fn begin(&self) { assert!(!self.was_deleted()); unsafe { #begin(self.inner) } } fn end(&self) { assert!(!self.was_deleted()); unsafe { #end(self.inner) } } fn clear(&mut self) { assert!(!self.was_deleted()); unsafe { #clear(self.inner); } } unsafe fn unsafe_clear(&mut self) { assert!(!self.was_deleted()); unsafe { #clear(self.inner); } } fn children(&self) -> i32 { unsafe { assert!(!self.was_deleted()); #children(self.inner) as i32 } } fn child(&self, idx: i32) -> Option<Widget> { unsafe { assert!(!self.was_deleted()); if idx >= self.children() || idx < 0 { return None; } let child_widget = #child(self.inner, idx as i32); if child_widget.is_null() { None } else { Some(Widget::from_widget_ptr(child_widget as *mut fltk_sys::widget::Fl_Widget)) } } } fn find<W: WidgetExt>(&self, widget: &W) -> i32 { unsafe { assert!(!self.was_deleted()); assert!(!widget.was_deleted()); #find(self.inner, widget.as_widget_ptr() as *mut _) as i32 } } fn add<W: WidgetExt>(&mut self, widget: &W) { unsafe { assert!(!self.was_deleted()); assert!(!widget.was_deleted()); #add(self.inner, widget.as_widget_ptr() as *mut _) } } fn insert<W: WidgetExt>(&mut self, widget: &W, index: i32) { unsafe { assert!(!self.was_deleted()); assert!(!widget.was_deleted()); #insert(self.inner, widget.as_widget_ptr() as *mut _, index as i32) } } fn remove<W: WidgetExt>(&mut self, widget: &W) { unsafe { assert!(!self.was_deleted()); assert!(!widget.was_deleted()); #remove(self.inner, widget.as_widget_ptr() as *mut _) } } fn remove_by_index(&mut self, idx: i32) { unsafe { assert!(!self.was_deleted()); assert!(idx < self.children()); #remove_by_index(self.inner, idx as i32); } } fn resizable<W: WidgetExt>(&self, widget: &W) { unsafe { assert!(!self.was_deleted()); assert!(!widget.was_deleted()); #resizable(self.inner, widget.as_widget_ptr() as *mut _) } } fn make_resizable(&mut self, val: bool) { assert!(!self.was_deleted()); let ptr = if val { self.inner } else { std::ptr::null_mut() }; unsafe { #resizable(self.inner, ptr as *mut _) } } fn add_resizable<W: WidgetExt>(&mut self, widget: &W) { self.resizable(widget); self.add(widget); } fn set_clip_children(&mut self, flag: bool) { assert!(!self.was_deleted()); unsafe { #set_clip_children(self.inner, flag as i32) } } fn clip_children(&mut self) -> bool { assert!(!self.was_deleted()); unsafe { #clip_children(self.inner) != 0 } } fn draw_child<W: WidgetExt>(&self, w: &mut W) { assert!(!self.was_deleted()); assert!(!w.was_deleted()); unsafe { crate::app::open_display(); Fl_Group_draw_child(self.inner as _, w.as_widget_ptr() as _) } } fn update_child<W: WidgetExt>(&self, w: &mut W) { assert!(!self.was_deleted()); assert!(!w.was_deleted()); unsafe { crate::app::open_display(); Fl_Group_update_child(self.inner as _, w.as_widget_ptr() as _) } } fn draw_outside_label<W: WidgetExt>(&self, w: &mut W) { assert!(!self.was_deleted()); assert!(!w.was_deleted()); unsafe { crate::app::open_display(); Fl_Group_draw_outside_label(self.inner as _, w.as_widget_ptr() as _) } } fn draw_children(&mut self) { assert!(!self.was_deleted()); unsafe { crate::app::open_display(); Fl_Group_draw_children(self.inner as _) } } fn init_sizes(&mut self) { unsafe { assert!(!self.was_deleted()); #init_sizes(self.inner) } } fn bounds(&self) -> Vec<(i32, i32, i32, i32)> { let children = self.children(); let mut vec = vec![]; for i in 0..children { let child = self.child(i).unwrap(); let x = child.x(); let y = child.y(); let r = child.w() + x; let b = child.h() + y; vec.push((x, y, r, b)); } vec } unsafe fn into_group(&self) -> crate::group::Group { crate::group::Group::from_widget_ptr(self.inner as _) } } }; gen.into() }
use crate::utils::get_fl_name; use proc_macro::TokenStream; use quote::*; use syn::*; pub fn impl_group_trait(ast: &DeriveInput) -> TokenStream { let name = &ast.ident; let name_str = get_fl_name(name.to_string()); let begin = Ident::new(format!("{}_{}", name_str, "begin").as_str(), name.span()); let end = Ident::new(format!("{}_{}", name_str, "end").as_str(), name.span()); let clear = Ident::new(format!("{}_{}", name_str, "clear").as_str(), name.span()); let children = Ident::new(format!("{}_{}", name_str, "children").as_str(), name.span()); let child = Ident::new(format!("{}_{}", name_str, "child").as_str(), name.span()); let find = Ident::new(format!("{}_{}", name_str, "find").as_str(), name.span()); let add = Ident::new(format!("{}_{}", name_str, "add").as_str(), name.span()); let insert = Ident::new(format!("{}_{}", name_str, "insert").as_str(), name.span()); let remove = Ident::new(format!("{}_{}", name_str, "remove").as_str(), name.span()); let remove_by_index = Ident::new( format!("{}_{}", name_str, "remove_by_index").as_str(), name.span(), ); let resizable = Ident::new( format!("{}_{}", name_str, "resizable").as_str(), name.span(), ); let clip_children = Ident::new( format!("{}_{}", name_str, "clip_children").as_str(), name.span(), ); let set_clip_children = Ident::new( format!("{}_{}", name_str, "set_clip_children").as_str(), name.span(), ); let init_sizes = Ident::new( format!("{}_{}", name_str, "init_sizes").as_str(), name.span(), ); let gen = quote! { impl IntoIterator for #name { type Item = Widget; type IntoIter = std::vec::IntoIter<Self::Item>; fn into_iter(self) -> Self::IntoIter { let mut v: Vec<Widget> = vec![]; for i in 0..self.children() { v.push(self.child(i).unwrap()); } v.into_iter() } } unsafe impl GroupExt for #name { fn begin(&self) { assert!(!self.was_deleted()); unsafe { #begin(self.inner) } } fn end(&self) { assert!(!self.was_deleted()); unsafe { #end(self.inner) } } fn clear(&mut self) { assert!(!self.was_deleted()); unsafe { #clear(self.inner); } } unsafe fn unsafe_clear(&mut self) { assert!(!self.was_deleted()); unsafe { #clear(self.inner); } } fn children(&self) -> i32 { unsafe { assert!(!self.was_deleted()); #children(self.inner) as i32 } } fn child(&self, idx: i32) -> Option<Widget> { unsafe { assert!(!self.was_deleted()); if idx >= self.children() || idx < 0 { return None; } let child_widget = #child(self.inner, idx as i32); if child_widget.is_null() { None } else { Some(Widget::from_widget_ptr(child_widget as *mut fltk_sys::widget::Fl_Widget)) } } } fn find<W: WidgetExt>(&self, widget: &W) -> i32 { unsafe { assert!(!self.was_deleted()); assert!(!widget.was_deleted()); #find(self.inner, widget.as_widget_ptr() as *mut _) as i32 } } fn add<W: WidgetExt>(&mut self, widget: &W) { unsafe { assert!(!self.was_deleted()); assert!(!widget.was_deleted()); #add(self.inner, widget.as_widget_ptr() as *mut _) } } fn insert<W: WidgetExt>(&mut self, widget: &W, index: i32) { unsafe { assert!(!self.was_deleted()); assert!(!widget.was_deleted()); #insert(self.inner, widget.as_widget_ptr() as *mut _, index as i32) } } fn remove<W: WidgetExt>(&mut self, widget: &W) { unsafe { assert!(!self.was_deleted()); assert!(!widget.was_deleted()); #remove(self.inner, widget.as_widget_ptr() as *mut _) } } fn remove_by_index(&mut self, idx: i32) { unsafe { assert!(!self.was_deleted()); assert!(idx < self.children()); #remove_by_index(self.inner, idx as i32); } } fn resizable<W: WidgetExt>(&self, widget: &W) { unsafe { assert!(!self.was_deleted()); assert!(!widget.was_deleted()); #resizable(self.inner, widget.as_widget_ptr() as *mut _) } } fn make_resizable(&mut self, val: bool) { assert!(!self.was_deleted()); let ptr = if val { self.inner } else { std::ptr::null_mut() }; unsafe { #resizable(self.inner, ptr as *mut _) } } fn add_resizable<W: WidgetExt>(&mut self, widget: &W) { self.resizable(widget); self.add(widget); } fn set_clip_children(&mut self, flag: bool) { assert!(!self.was_deleted()); unsafe { #set_clip_children(self.inner, flag as i32) } } fn clip_children(&mut self) -> bool { assert!(!self.was_deleted()); unsafe { #clip_children(self.inner) != 0 } } fn draw_child<W: WidgetExt>(&self, w: &mut W) { assert!(!self.was_deleted()); assert!(!w.was_deleted()); unsafe { crate::app::open_display(); Fl_Group_draw_child(self.inner as _, w.as_widget_ptr() as _) } } fn update_child<W: WidgetExt>(&self, w: &mut W) { assert!(!self.was_deleted()); assert!(!w.was_deleted()); unsafe { crate::app::open_display(); Fl_Group_update_child(self.inner as _, w.as_widget_ptr() as _) } } fn draw_outside_label<W: WidgetExt>(&self, w: &mut W) { assert!(!self.was_deleted()); assert!(!w.was_deleted());
unsafe { crate::app::open_display(); Fl_Group_draw_outside_label(self.inner as _, w.as_widget_ptr() as _) } } fn draw_children(&mut self) { assert!(!self.was_deleted()); unsafe { crate::app::open_display(); Fl_Group_draw_children(self.inner as _) } } fn init_sizes(&mut self) { unsafe { assert!(!self.was_deleted()); #init_sizes(self.inner) } } fn bounds(&self) -> Vec<(i32, i32, i32, i32)> { let children = self.children(); let mut vec = vec![]; for i in 0..children { let child = self.child(i).unwrap(); let x = child.x(); let y = child.y(); let r = child.w() + x; let b = child.h() + y; vec.push((x, y, r, b)); } vec } unsafe fn into_group(&self) -> crate::group::Group { crate::group::Group::from_widget_ptr(self.inner as _) } } }; gen.into() }
function_block-function_prefix_line
[ { "content": "/// Sets the callback of a widget\n\npub fn set_callback<F, W>(widget: &mut W, cb: F)\n\nwhere\n\n F: FnMut(&mut dyn WidgetExt),\n\n W: WidgetExt,\n\n{\n\n assert!(!widget.was_deleted());\n\n unsafe {\n\n unsafe extern \"C\" fn shim(wid: *mut fltk_sys::widget::Fl_Widget, data: *mut raw::c_void) {\n\n let a: *mut Box<dyn FnMut(&mut dyn WidgetExt)> =\n\n data as *mut Box<dyn FnMut(&mut dyn WidgetExt)>;\n\n let f: &mut (dyn FnMut(&mut dyn WidgetExt)) = &mut **a;\n\n let mut wid = crate::widget::Widget::from_widget_ptr(wid);\n\n let _ = panic::catch_unwind(panic::AssertUnwindSafe(|| f(&mut wid)));\n\n }\n\n let _old_data = widget.user_data();\n\n let a: *mut Box<dyn FnMut(&mut dyn WidgetExt)> = Box::into_raw(Box::new(Box::new(cb)));\n\n let data: *mut raw::c_void = a as *mut raw::c_void;\n\n let callback: fltk_sys::widget::Fl_Callback = Some(shim);\n\n fltk_sys::widget::Fl_Widget_set_callback(widget.as_widget_ptr(), callback, data);\n\n }\n", "file_path": "fltk/src/app/widget.rs", "rank": 0, "score": 337630.3664012919 }, { "content": "/// Sets the damage to true or false, illiciting a redraw by the application\n\npub fn set_damage(flag: bool) {\n\n unsafe { fl::Fl_set_damage(flag as i32) }\n\n}\n\n\n", "file_path": "fltk/src/app/widget.rs", "rank": 1, "score": 322236.0161023327 }, { "content": "/// Returns whether the rectangle intersect with the current clip region\n\npub fn not_clipped(x: i32, y: i32, w: i32, h: i32) -> bool {\n\n unsafe { Fl_not_clipped(x, y, w, h) != 0 }\n\n}\n\n\n", "file_path": "fltk/src/draw.rs", "rank": 2, "score": 310510.9787696409 }, { "content": "pub fn impl_widget_type(ast: &DeriveInput) -> TokenStream {\n\n let name = &ast.ident;\n\n\n\n let gen = quote! {\n\n impl WidgetType for #name {\n\n fn to_i32(self) -> i32 {\n\n self as i32\n\n }\n\n\n\n fn from_i32(val: i32) -> #name {\n\n unsafe { mem::transmute(val) }\n\n }\n\n }\n\n };\n\n gen.into()\n\n}\n", "file_path": "fltk-derive/src/widget.rs", "rank": 3, "score": 308934.7696995484 }, { "content": "/// Returns whether an event occured within a region\n\npub fn event_inside(x: i32, y: i32, w: i32, h: i32) -> bool {\n\n unsafe { fl::Fl_event_inside(x, y, w, h) != 0 }\n\n}\n\n\n\n/**\n\n Gets the widget that is below the mouse cursor.\n\n This returns an Option<impl WidgetExt> which can be specified in the function call\n\n ```rust,no_run\n\n use fltk::app;\n\n use fltk::widget;\n\n let w = app::belowmouse::<widget::Widget>(); // or by specifying a more concrete type\n\n ```\n\n*/\n", "file_path": "fltk/src/app/event.rs", "rank": 4, "score": 302682.7131276089 }, { "content": "/// Returns the apps windows.\n\npub fn windows() -> Option<Vec<impl WindowExt>> {\n\n let mut v: Vec<Window> = vec![];\n\n if let Some(first) = first_window() {\n\n let first: Window = unsafe { first.into_widget() };\n\n v.push(first.clone());\n\n let mut win = first;\n\n while let Some(wind) = next_window(&win) {\n\n let w = unsafe { wind.into_widget::<Window>() };\n\n v.push(w.clone());\n\n win = w;\n\n }\n\n Some(v)\n\n } else {\n\n None\n\n }\n\n}\n", "file_path": "fltk/src/app/widget.rs", "rank": 5, "score": 301223.07516041945 }, { "content": "/// Returns the next window in order\n\npub fn next_window<W: WindowExt>(w: &W) -> Option<impl WindowExt> {\n\n unsafe {\n\n let x = fl::Fl_next_window(w.as_widget_ptr() as *const raw::c_void);\n\n if x.is_null() {\n\n None\n\n } else {\n\n let x = Window::from_widget_ptr(x as *mut fltk_sys::widget::Fl_Widget);\n\n Some(x)\n\n }\n\n }\n\n}\n\n\n", "file_path": "fltk/src/app/widget.rs", "rank": 6, "score": 298340.0977804871 }, { "content": "fn inc_frame(frame: &mut Frame, val: &mut i32, step: i32) {\n\n *val += step;\n\n frame.set_label(&val.to_string());\n\n}\n\n\n", "file_path": "fltk/examples/messages.rs", "rank": 7, "score": 293297.5609675969 }, { "content": "/// Determines whether a program should quit\n\npub fn program_should_quit(flag: bool) {\n\n unsafe { fl::Fl_program_should_quit(flag as i32) }\n\n}\n\n\n", "file_path": "fltk/src/app/rt.rs", "rank": 8, "score": 279053.1800466601 }, { "content": "/// Show focus around widgets\n\npub fn set_visible_focus(flag: bool) {\n\n unsafe { fl::Fl_set_visible_focus(flag as i32) }\n\n}\n\n\n", "file_path": "fltk/src/app/visual.rs", "rank": 9, "score": 274382.2021016275 }, { "content": "/// Set the menu linespacing\n\npub fn set_menu_linespacing(val: i32) {\n\n unsafe { fl::Fl_set_menu_linespacing(val) }\n\n}\n\n\n", "file_path": "fltk/src/app/visual.rs", "rank": 10, "score": 273256.05987681693 }, { "content": "/// Draws a box given the box type, size, position and color\n\npub fn draw_box(box_type: FrameType, x: i32, y: i32, w: i32, h: i32, color: Color) {\n\n unsafe { Fl_draw_box(box_type as i32, x, y, w, h, color.bits() as u32) }\n\n}\n\n\n", "file_path": "fltk/src/draw.rs", "rank": 11, "score": 271479.2695337534 }, { "content": "pub fn impl_widget_trait(ast: &DeriveInput) -> TokenStream {\n\n let name = &ast.ident;\n\n\n\n let name_str = get_fl_name(name.to_string());\n\n let ptr_name = Ident::new(name_str.as_str(), name.span());\n\n let x = Ident::new(format!(\"{}_{}\", name_str, \"x\").as_str(), name.span());\n\n let y = Ident::new(format!(\"{}_{}\", name_str, \"y\").as_str(), name.span());\n\n let width = Ident::new(format!(\"{}_{}\", name_str, \"width\").as_str(), name.span());\n\n let height = Ident::new(format!(\"{}_{}\", name_str, \"height\").as_str(), name.span());\n\n let label = Ident::new(format!(\"{}_{}\", name_str, \"label\").as_str(), name.span());\n\n let measure_label = Ident::new(\n\n format!(\"{}_{}\", name_str, \"measure_label\").as_str(),\n\n name.span(),\n\n );\n\n let set_label = Ident::new(\n\n format!(\"{}_{}\", name_str, \"set_label\").as_str(),\n\n name.span(),\n\n );\n\n let redraw = Ident::new(format!(\"{}_{}\", name_str, \"redraw\").as_str(), name.span());\n\n let show = Ident::new(format!(\"{}_{}\", name_str, \"show\").as_str(), name.span());\n", "file_path": "fltk-derive/src/widget.rs", "rank": 12, "score": 269928.6640227063 }, { "content": "/// Measure the width and height of a text\n\npub fn measure(txt: &str, draw_symbols: bool) -> (i32, i32) {\n\n let txt = CString::safe_new(txt);\n\n let mut x = 0;\n\n let mut y = 0;\n\n unsafe {\n\n Fl_measure(txt.as_ptr(), &mut x, &mut y, draw_symbols as i32);\n\n }\n\n (x, y)\n\n}\n\n\n", "file_path": "fltk/src/draw.rs", "rank": 13, "score": 269006.99520303344 }, { "content": "pub fn impl_widget_base_trait(ast: &DeriveInput) -> TokenStream {\n\n let name = &ast.ident;\n\n\n\n let name_str = get_fl_name(name.to_string());\n\n let ptr_name = Ident::new(name_str.as_str(), name.span());\n\n let new = Ident::new(format!(\"{}_{}\", name_str, \"new\").as_str(), name.span());\n\n let handle = Ident::new(format!(\"{}_{}\", name_str, \"handle\").as_str(), name.span());\n\n let draw = Ident::new(format!(\"{}_{}\", name_str, \"draw\").as_str(), name.span());\n\n let handle_data = Ident::new(\n\n format!(\"{}_{}\", name_str, \"handle_data\").as_str(),\n\n name.span(),\n\n );\n\n let draw_data = Ident::new(\n\n format!(\"{}_{}\", name_str, \"draw_data\").as_str(),\n\n name.span(),\n\n );\n\n let set_handle_data = Ident::new(\n\n format!(\"{}_{}\", name_str, \"set_handle_data\").as_str(),\n\n name.span(),\n\n );\n", "file_path": "fltk-derive/src/widget.rs", "rank": 14, "score": 266211.9424247788 }, { "content": "/// Sets the widget which has focus at the start of the application\n\npub fn set_focus<W: WidgetExt>(wid: &W) {\n\n unsafe { fl::Fl_set_focus(wid.as_widget_ptr() as *mut raw::c_void) }\n\n}\n\n\n", "file_path": "fltk/src/app/widget.rs", "rank": 15, "score": 262478.3838776103 }, { "content": "/// Returns whether any of the widgets were damaged\n\npub fn damage() -> bool {\n\n unsafe { fl::Fl_damage() != 0 }\n\n}\n\n\n", "file_path": "fltk/src/app/widget.rs", "rank": 16, "score": 259971.5024650399 }, { "content": "/// Gets the widget which was pushed\n\npub fn pushed() -> Option<impl WidgetExt> {\n\n unsafe {\n\n let ptr = fl::Fl_pushed();\n\n if ptr.is_null() {\n\n None\n\n } else {\n\n Some(crate::widget::Widget::from_widget_ptr(ptr as *mut _))\n\n }\n\n }\n\n}\n\n\n", "file_path": "fltk/src/app/widget.rs", "rank": 17, "score": 251199.25963183888 }, { "content": "/// Gets the widget which has focus\n\npub fn focus() -> Option<impl WidgetExt> {\n\n unsafe {\n\n let ptr = fl::Fl_focus();\n\n if ptr.is_null() {\n\n None\n\n } else {\n\n Some(crate::widget::Widget::from_widget_ptr(\n\n ptr as *mut fltk_sys::widget::Fl_Widget,\n\n ))\n\n }\n\n }\n\n}\n\n\n", "file_path": "fltk/src/app/widget.rs", "rank": 18, "score": 251199.25963183888 }, { "content": "/// Adds a custom handler for unhandled events\n\npub fn add_handler(cb: fn(Event) -> bool) {\n\n unsafe {\n\n let callback: Option<unsafe extern \"C\" fn(ev: raw::c_int) -> raw::c_int> =\n\n Some(mem::transmute(move |ev| {\n\n let _ = panic::catch_unwind(panic::AssertUnwindSafe(|| cb(ev) as i32));\n\n }));\n\n fl::Fl_add_handler(callback);\n\n }\n\n}\n\n\n\n/**\n\n Send a signal to a window.\n\n Integral values from 0 to 30 are reserved.\n\n Returns Ok(true) if the event was handled.\n\n Returns Ok(false) if the event was not handled.\n\n Returns Err on error or in use of one of the reserved values.\n\n ```rust,no_run\n\n use fltk::{prelude::*, *};\n\n const CHANGE_FRAME: i32 = 100;\n\n let mut wind = window::Window::default();\n", "file_path": "fltk/src/app/event.rs", "rank": 19, "score": 248177.40394396227 }, { "content": "/// Draws a filled rectangle\n\npub fn draw_rectf(x: i32, y: i32, w: i32, h: i32) {\n\n unsafe { Fl_rectf(x, y, w, h) }\n\n}\n\n\n", "file_path": "fltk/src/draw.rs", "rank": 20, "score": 247318.5137495658 }, { "content": "/// Draws a selection rectangle, erasing a previous one by XOR'ing it first.\n\npub fn overlay_rect(x: i32, y: i32, w: i32, h: i32) {\n\n unsafe { Fl_overlay_rect(x, y, w, h) }\n\n}\n\n\n", "file_path": "fltk/src/draw.rs", "rank": 21, "score": 247318.5137495658 }, { "content": "/// Sets the status\n\npub fn set_status(x: i32, y: i32, w: i32, h: i32) {\n\n unsafe { Fl_set_status(x, y, w, h) }\n\n}\n\n\n", "file_path": "fltk/src/draw.rs", "rank": 22, "score": 247318.5137495658 }, { "content": "/// Draws a rectangle\n\npub fn draw_rect(x: i32, y: i32, w: i32, h: i32) {\n\n unsafe { Fl_rect(x, y, w, h) }\n\n}\n\n\n", "file_path": "fltk/src/draw.rs", "rank": 23, "score": 247318.5137495658 }, { "content": "/// Limits drawing to a region\n\npub fn push_clip(x: i32, y: i32, w: i32, h: i32) {\n\n unsafe {\n\n Fl_push_clip(x, y, w, h);\n\n }\n\n}\n\n\n", "file_path": "fltk/src/draw.rs", "rank": 24, "score": 247318.5137495658 }, { "content": "/// Draws a focus rectangle\n\npub fn draw_focus_rect(x: i32, y: i32, w: i32, h: i32) {\n\n unsafe { Fl_focus_rect(x, y, w, h) }\n\n}\n\n\n", "file_path": "fltk/src/draw.rs", "rank": 25, "score": 244424.63126625097 }, { "content": "/// Set the current grab\n\npub fn set_grab<W: WindowExt>(win: Option<W>) {\n\n unsafe {\n\n win.map_or_else(\n\n || fl::Fl_set_grab(ptr::null_mut()),\n\n |w| fl::Fl_set_grab(w.as_widget_ptr() as *mut _),\n\n )\n\n }\n\n}\n\n\n", "file_path": "fltk/src/app/widget.rs", "rank": 26, "score": 242166.07185622724 }, { "content": "/// Returns a list of available fonts to the application\n\npub fn get_font_names() -> Vec<String> {\n\n let mut vec: Vec<String> = vec![];\n\n let cnt = set_fonts(\"*\") as usize;\n\n for i in 0..cnt {\n\n let temp = unsafe {\n\n CStr::from_ptr(fl::Fl_get_font(i as i32))\n\n .to_string_lossy()\n\n .to_string()\n\n };\n\n vec.push(temp);\n\n }\n\n vec\n\n}\n\n\n", "file_path": "fltk/src/app/font.rs", "rank": 27, "score": 241815.26363110944 }, { "content": "/// Get the grabbed window\n\npub fn grab() -> Option<impl WindowExt> {\n\n unsafe {\n\n let ptr = fl::Fl_grab();\n\n if ptr.is_null() {\n\n None\n\n } else {\n\n Some(crate::window::Window::from_widget_ptr(ptr as *mut _))\n\n }\n\n }\n\n}\n\n\n", "file_path": "fltk/src/app/widget.rs", "rank": 28, "score": 237886.04350988794 }, { "content": "// The selected flag sets the color of the cell to a grayish color, otherwise white\n\nfn draw_data(txt: &str, x: i32, y: i32, w: i32, h: i32, selected: bool) {\n\n draw::push_clip(x, y, w, h);\n\n if selected {\n\n draw::set_draw_color(enums::Color::from_u32(0x00D3_D3D3));\n\n } else {\n\n draw::set_draw_color(enums::Color::White);\n\n }\n\n draw::draw_rectf(x, y, w, h);\n\n draw::set_draw_color(enums::Color::Gray0);\n\n draw::draw_text2(txt, x, y, w, h, enums::Align::Center);\n\n draw::draw_rect(x, y, w, h);\n\n draw::pop_clip();\n\n}\n", "file_path": "fltk/examples/table.rs", "rank": 29, "score": 237308.94778405342 }, { "content": "#[proc_macro_derive(WidgetType)]\n\npub fn widget_type_macro(input: TokenStream) -> TokenStream {\n\n let ast = syn::parse(input).unwrap();\n\n impl_widget_type(&ast)\n\n}\n\n\n", "file_path": "fltk-derive/src/lib.rs", "rank": 30, "score": 234251.19352797072 }, { "content": "/// Draws a filled rectangle\n\npub fn draw_rect_fill(x: i32, y: i32, w: i32, h: i32, color: Color) {\n\n unsafe { Fl_rectf_with_color(x, y, w, h, color.bits() as u32) }\n\n}\n\n\n", "file_path": "fltk/src/draw.rs", "rank": 31, "score": 233485.4020650853 }, { "content": "/// Draws a rectangle with border color\n\npub fn draw_rect_with_color(x: i32, y: i32, w: i32, h: i32, color: Color) {\n\n unsafe { Fl_rect_with_color(x, y, w, h, color.bits() as u32) }\n\n}\n\n\n", "file_path": "fltk/src/draw.rs", "rank": 32, "score": 233485.4020650853 }, { "content": "/// Returns the first window of the application\n\npub fn first_window() -> Option<impl WindowExt> {\n\n unsafe {\n\n let x = fl::Fl_first_window();\n\n if x.is_null() {\n\n None\n\n } else {\n\n let x = Window::from_widget_ptr(x as *mut fltk_sys::widget::Fl_Widget);\n\n Some(x)\n\n }\n\n }\n\n}\n\n\n", "file_path": "fltk/src/app/widget.rs", "rank": 33, "score": 233466.30845686945 }, { "content": "pub fn belowmouse<Wid: WidgetExt>() -> Option<impl WidgetExt> {\n\n unsafe {\n\n let x = fl::Fl_belowmouse() as *mut fltk_sys::fl::Fl_Widget;\n\n if x.is_null() {\n\n None\n\n } else {\n\n Some(crate::widget::Widget::from_widget_ptr(\n\n x as *mut fltk_sys::widget::Fl_Widget,\n\n ))\n\n }\n\n }\n\n}\n\n\n", "file_path": "fltk/src/app/event.rs", "rank": 34, "score": 232602.4330660082 }, { "content": "pub fn center() -> (i32, i32) {\n\n (\n\n (app::screen_size().0 / 2.0) as i32,\n\n (app::screen_size().1 / 2.0) as i32,\n\n )\n\n}\n\n\n\npub struct MyEditor {\n\n editor: text::TextEditor,\n\n}\n\n\n\nimpl MyEditor {\n\n pub fn new(buf: text::TextBuffer) -> Self {\n\n let mut editor = text::TextEditor::new(5, 35, 790, 560, \"\");\n\n editor.set_buffer(Some(buf));\n\n\n\n #[cfg(target_os = \"macos\")]\n\n editor.resize(5, 5, 790, 590);\n\n\n\n editor.set_scrollbar_size(15);\n", "file_path": "fltk/examples/editor.rs", "rank": 35, "score": 230542.08883849508 }, { "content": "/// Gets the name of a font through its index\n\npub fn font_name(idx: usize) -> Option<String> {\n\n let f = FONTS.lock().unwrap();\n\n Some(f[idx].clone())\n\n}\n\n\n", "file_path": "fltk/src/app/font.rs", "rank": 36, "score": 230448.71456689783 }, { "content": "/// Finds the index of a font through its name\n\npub fn font_index(name: &str) -> Option<usize> {\n\n let f = FONTS.lock().unwrap();\n\n f.iter().position(|i| i == name)\n\n}\n\n\n", "file_path": "fltk/src/app/font.rs", "rank": 37, "score": 230405.44501905533 }, { "content": "/// Checks whether an idle function is installed\n\npub fn has_idle<F: FnMut() + 'static>(cb: F) -> bool {\n\n unsafe {\n\n unsafe extern \"C\" fn shim(data: *mut raw::c_void) {\n\n let a: *mut Box<dyn FnMut()> = data as *mut Box<dyn FnMut()>;\n\n let f: &mut (dyn FnMut()) = &mut **a;\n\n let _ = panic::catch_unwind(panic::AssertUnwindSafe(|| f()));\n\n }\n\n let a: *mut Box<dyn FnMut()> = Box::into_raw(Box::new(Box::new(cb)));\n\n let data: *mut raw::c_void = a as *mut raw::c_void;\n\n let callback: Option<unsafe extern \"C\" fn(arg1: *mut raw::c_void)> = Some(shim);\n\n fl::Fl_has_idle(callback, data) != 0\n\n }\n\n}\n\n\n", "file_path": "fltk/src/app/rt.rs", "rank": 38, "score": 229499.06463446593 }, { "content": "/// Check whether a timeout is installed\n\npub fn has_timeout<F: FnMut() + 'static>(cb: F) -> bool {\n\n unsafe {\n\n unsafe extern \"C\" fn shim(data: *mut raw::c_void) {\n\n let a: *mut Box<dyn FnMut()> = data as *mut Box<dyn FnMut()>;\n\n let f: &mut (dyn FnMut()) = &mut **a;\n\n let _ = panic::catch_unwind(panic::AssertUnwindSafe(|| f()));\n\n }\n\n let a: *mut Box<dyn FnMut()> = Box::into_raw(Box::new(Box::new(cb)));\n\n let data: *mut raw::c_void = a as *mut raw::c_void;\n\n let callback: Option<unsafe extern \"C\" fn(arg1: *mut raw::c_void)> = Some(shim);\n\n fltk_sys::fl::Fl_has_timeout(callback, data) != 0\n\n }\n\n}\n\n\n\n/**\n\n Adds a one-shot timeout callback. The timeout duration `tm` is indicated in seconds\n\n Example:\n\n ```rust,no_run\n\n use fltk::{prelude::*, *};\n\n fn callback() {\n", "file_path": "fltk/src/app/rt.rs", "rank": 39, "score": 229499.06463446593 }, { "content": "/// Returns whether an event occured within a widget\n\npub fn event_inside_widget<Wid: WidgetExt>(wid: &Wid) -> bool {\n\n assert!(!wid.was_deleted());\n\n let x = wid.x();\n\n let y = wid.y();\n\n let w = wid.width();\n\n let h = wid.height();\n\n unsafe { fl::Fl_event_inside(x, y, w, h) != 0 }\n\n}\n\n\n", "file_path": "fltk/src/app/event.rs", "rank": 40, "score": 228495.54317908848 }, { "content": "pub fn handle<I: Into<i32> + Copy + PartialEq + PartialOrd, W: WindowExt>(\n\n msg: I,\n\n w: &W,\n\n) -> Result<bool, FltkError> {\n\n let val = msg.into();\n\n if (0..=30).contains(&val) {\n\n Err(FltkError::Internal(FltkErrorKind::FailedOperation))\n\n } else {\n\n let ret = unsafe { fl::Fl_handle(val, w.as_widget_ptr() as _) != 0 };\n\n Ok(ret)\n\n }\n\n}\n\n\n\n/**\n\n Send a signal to the main window.\n\n Integral values from 0 to 30 are reserved.\n\n Returns Ok(true) if the event was handled.\n\n Returns Ok(false) if the event was not handled.\n\n ```rust,no_run\n\n use fltk::{prelude::*, *};\n", "file_path": "fltk/src/app/event.rs", "rank": 41, "score": 227936.39883883554 }, { "content": "/// Returns the x and y coordinates of the captured event\n\npub fn event_coords() -> (i32, i32) {\n\n unsafe { (fl::Fl_event_x(), fl::Fl_event_y()) }\n\n}\n\n\n", "file_path": "fltk/src/app/event.rs", "rank": 42, "score": 223356.14058701548 }, { "content": "/// Returns a pair of the x & y coords of the screen\n\npub fn screen_coords() -> (i32, i32) {\n\n unsafe { (fl::Fl_screen_x(), fl::Fl_screen_y()) }\n\n}\n\n\n", "file_path": "fltk/src/app/screen.rs", "rank": 43, "score": 223356.14058701548 }, { "content": "/// Gets the mouse coordinates relative to the screen\n\npub fn get_mouse() -> (i32, i32) {\n\n unsafe {\n\n let mut x: i32 = 0;\n\n let mut y: i32 = 0;\n\n fl::Fl_get_mouse(&mut x, &mut y);\n\n (x, y)\n\n }\n\n}\n\n\n\n/// Types of Clipboard contents\n\n#[derive(Debug, Clone, Copy)]\n\npub enum ClipboardContent {\n\n /// Textual content\n\n Text,\n\n /// Image content\n\n Image,\n\n}\n\n\n", "file_path": "fltk/src/app/event.rs", "rank": 44, "score": 223350.27269423293 }, { "content": "/// Get the screen number based on its coordinates\n\npub fn screen_num(x: i32, y: i32) -> i32 {\n\n unsafe { fl::Fl_screen_num(x, y) }\n\n}\n\n\n", "file_path": "fltk/src/app/screen.rs", "rank": 45, "score": 222075.78947273767 }, { "content": "/// Get a screen's xywh\n\npub fn screen_xywh(screen_num: i32) -> (i32, i32, i32, i32) {\n\n let mut x = 0;\n\n let mut y = 0;\n\n let mut w = 0;\n\n let mut h = 0;\n\n unsafe {\n\n fl::Fl_screen_xywh(&mut x, &mut y, &mut w, &mut h, screen_num);\n\n }\n\n (x, y, w, h)\n\n}\n\n\n", "file_path": "fltk/src/app/screen.rs", "rank": 46, "score": 220542.5798413746 }, { "content": "/// Draws a point\n\npub fn draw_point(x: i32, y: i32) {\n\n unsafe { Fl_point(x, y) }\n\n}\n\n\n", "file_path": "fltk/src/draw.rs", "rank": 47, "score": 220490.4885182981 }, { "content": "/// Draws a vertical line from (x,y) to (x,y1)\n\npub fn draw_yxline(x: i32, y: i32, y1: i32) {\n\n unsafe { Fl_yxline(x, y, y1) }\n\n}\n\n\n", "file_path": "fltk/src/draw.rs", "rank": 48, "score": 219634.79075977113 }, { "content": "/// Draws a horizontal line from (x,y) to (x1,y)\n\npub fn draw_xyline(x: i32, y: i32, x1: i32) {\n\n unsafe { Fl_xyline(x, y, x1) }\n\n}\n\n\n", "file_path": "fltk/src/draw.rs", "rank": 49, "score": 219634.79075977113 }, { "content": "/// Get a screen's working area\n\npub fn screen_work_area(screen_num: i32) -> (i32, i32, i32, i32) {\n\n let mut x = 0;\n\n let mut y = 0;\n\n let mut w = 0;\n\n let mut h = 0;\n\n unsafe {\n\n fl::Fl_screen_work_area(&mut x, &mut y, &mut w, &mut h, screen_num);\n\n }\n\n (x, y, w, h)\n\n}\n", "file_path": "fltk/src/app/screen.rs", "rank": 50, "score": 218187.06910378626 }, { "content": "pub fn impl_input_trait(ast: &DeriveInput) -> TokenStream {\n\n let name = &ast.ident;\n\n let name_str = get_fl_name(name.to_string());\n\n let value = Ident::new(format!(\"{}_{}\", name_str, \"value\").as_str(), name.span());\n\n let set_value = Ident::new(\n\n format!(\"{}_{}\", name_str, \"set_value\").as_str(),\n\n name.span(),\n\n );\n\n let maximum_size = Ident::new(\n\n format!(\"{}_{}\", name_str, \"maximum_size\").as_str(),\n\n name.span(),\n\n );\n\n let set_maximum_size = Ident::new(\n\n format!(\"{}_{}\", name_str, \"set_maximum_size\").as_str(),\n\n name.span(),\n\n );\n\n let position = Ident::new(format!(\"{}_{}\", name_str, \"position\").as_str(), name.span());\n\n let set_position = Ident::new(\n\n format!(\"{}_{}\", name_str, \"set_position\").as_str(),\n\n name.span(),\n", "file_path": "fltk-derive/src/input.rs", "rank": 51, "score": 217422.19609732792 }, { "content": "pub fn impl_menu_trait(ast: &DeriveInput) -> TokenStream {\n\n let name = &ast.ident;\n\n let name_str = get_fl_name(name.to_string());\n\n let ptr_name = Ident::new(name_str.as_str(), name.span());\n\n let add = Ident::new(format!(\"{}_{}\", name_str, \"add\").as_str(), name.span());\n\n let insert = Ident::new(format!(\"{}_{}\", name_str, \"insert\").as_str(), name.span());\n\n let remove = Ident::new(format!(\"{}_{}\", name_str, \"remove\").as_str(), name.span());\n\n let get_item = Ident::new(format!(\"{}_{}\", name_str, \"get_item\").as_str(), name.span());\n\n let set_item = Ident::new(format!(\"{}_{}\", name_str, \"set_item\").as_str(), name.span());\n\n let find_index = Ident::new(\n\n format!(\"{}_{}\", name_str, \"find_index\").as_str(),\n\n name.span(),\n\n );\n\n let text_font = Ident::new(\n\n format!(\"{}_{}\", name_str, \"text_font\").as_str(),\n\n name.span(),\n\n );\n\n let set_text_font = Ident::new(\n\n format!(\"{}_{}\", name_str, \"set_text_font\").as_str(),\n\n name.span(),\n", "file_path": "fltk-derive/src/menu.rs", "rank": 52, "score": 217422.19609732792 }, { "content": "pub fn impl_image_trait(ast: &DeriveInput) -> TokenStream {\n\n let name = &ast.ident;\n\n let name_str = get_fl_name(name.to_string());\n\n let ptr_name = Ident::new(name_str.as_str(), name.span());\n\n\n\n let new = Ident::new(format!(\"{}_{}\", name_str, \"new\").as_str(), name.span());\n\n let draw = Ident::new(format!(\"{}_{}\", name_str, \"draw\").as_str(), name.span());\n\n let width = Ident::new(format!(\"{}_{}\", name_str, \"width\").as_str(), name.span());\n\n let height = Ident::new(format!(\"{}_{}\", name_str, \"height\").as_str(), name.span());\n\n let delete = Ident::new(format!(\"{}_{}\", name_str, \"delete\").as_str(), name.span());\n\n let count = Ident::new(format!(\"{}_{}\", name_str, \"count\").as_str(), name.span());\n\n let data = Ident::new(format!(\"{}_{}\", name_str, \"data\").as_str(), name.span());\n\n let copy = Ident::new(format!(\"{}_{}\", name_str, \"copy\").as_str(), name.span());\n\n let scale = Ident::new(format!(\"{}_{}\", name_str, \"scale\").as_str(), name.span());\n\n let data_w = Ident::new(format!(\"{}_{}\", name_str, \"data_w\").as_str(), name.span());\n\n let data_h = Ident::new(format!(\"{}_{}\", name_str, \"data_h\").as_str(), name.span());\n\n let d = Ident::new(format!(\"{}_{}\", name_str, \"d\").as_str(), name.span());\n\n let ld = Ident::new(format!(\"{}_{}\", name_str, \"ld\").as_str(), name.span());\n\n let inactive = Ident::new(format!(\"{}_{}\", name_str, \"inactive\").as_str(), name.span());\n\n\n", "file_path": "fltk-derive/src/image.rs", "rank": 53, "score": 217422.19609732795 }, { "content": "pub fn impl_display_trait(ast: &DeriveInput) -> TokenStream {\n\n let name = &ast.ident;\n\n let name_str = get_fl_name(name.to_string());\n\n\n\n let get_buffer = Ident::new(\n\n format!(\"{}_{}\", name_str, \"get_buffer\").as_str(),\n\n name.span(),\n\n );\n\n let set_buffer = Ident::new(\n\n format!(\"{}_{}\", name_str, \"set_buffer\").as_str(),\n\n name.span(),\n\n );\n\n let get_style_buffer = Ident::new(\n\n format!(\"{}_{}\", name_str, \"get_style_buffer\").as_str(),\n\n name.span(),\n\n );\n\n let text_font = Ident::new(\n\n format!(\"{}_{}\", name_str, \"text_font\").as_str(),\n\n name.span(),\n\n );\n", "file_path": "fltk-derive/src/display.rs", "rank": 54, "score": 217422.19609732792 }, { "content": "pub fn impl_valuator_trait(ast: &DeriveInput) -> TokenStream {\n\n let name = &ast.ident;\n\n let name_str = get_fl_name(name.to_string());\n\n\n\n let set_bounds = Ident::new(\n\n format!(\"{}_{}\", name_str, \"set_bounds\").as_str(),\n\n name.span(),\n\n );\n\n let minimum = Ident::new(format!(\"{}_{}\", name_str, \"minimum\").as_str(), name.span());\n\n let set_minimum = Ident::new(\n\n format!(\"{}_{}\", name_str, \"set_minimum\").as_str(),\n\n name.span(),\n\n );\n\n let maximum = Ident::new(format!(\"{}_{}\", name_str, \"maximum\").as_str(), name.span());\n\n let set_maximum = Ident::new(\n\n format!(\"{}_{}\", name_str, \"set_maximum\").as_str(),\n\n name.span(),\n\n );\n\n let set_range = Ident::new(\n\n format!(\"{}_{}\", name_str, \"set_range\").as_str(),\n", "file_path": "fltk-derive/src/valuator.rs", "rank": 55, "score": 217422.19609732792 }, { "content": "pub fn impl_table_trait(ast: &DeriveInput) -> TokenStream {\n\n let name = &ast.ident;\n\n let name_str = get_fl_name(name.to_string());\n\n\n\n let new = Ident::new(format!(\"{}_{}\", name_str, \"new\").as_str(), name.span());\n\n let clear = Ident::new(format!(\"{}_{}\", name_str, \"clear\").as_str(), name.span());\n\n let set_table_box = Ident::new(\n\n format!(\"{}_{}\", name_str, \"set_table_box\").as_str(),\n\n name.span(),\n\n );\n\n let table_box = Ident::new(\n\n format!(\"{}_{}\", name_str, \"table_box\").as_str(),\n\n name.span(),\n\n );\n\n let set_rows = Ident::new(format!(\"{}_{}\", name_str, \"set_rows\").as_str(), name.span());\n\n let rows = Ident::new(format!(\"{}_{}\", name_str, \"rows\").as_str(), name.span());\n\n let set_cols = Ident::new(format!(\"{}_{}\", name_str, \"set_cols\").as_str(), name.span());\n\n let cols = Ident::new(format!(\"{}_{}\", name_str, \"cols\").as_str(), name.span());\n\n let visible_cells = Ident::new(\n\n format!(\"{}_{}\", name_str, \"visible_cells\").as_str(),\n", "file_path": "fltk-derive/src/table.rs", "rank": 56, "score": 217422.19609732792 }, { "content": "pub fn impl_browser_trait(ast: &DeriveInput) -> TokenStream {\n\n let name = &ast.ident;\n\n let name_str = get_fl_name(name.to_string());\n\n\n\n let remove = Ident::new(format!(\"{}_{}\", name_str, \"remove\").as_str(), name.span());\n\n let add = Ident::new(format!(\"{}_{}\", name_str, \"add\").as_str(), name.span());\n\n let insert = Ident::new(format!(\"{}_{}\", name_str, \"insert\").as_str(), name.span());\n\n let move_item = Ident::new(format!(\"{}_{}\", name_str, \"move\").as_str(), name.span());\n\n let swap = Ident::new(format!(\"{}_{}\", name_str, \"swap\").as_str(), name.span());\n\n let clear = Ident::new(format!(\"{}_{}\", name_str, \"clear\").as_str(), name.span());\n\n let size = Ident::new(format!(\"{}_{}\", name_str, \"size\").as_str(), name.span());\n\n let set_size = Ident::new(format!(\"{}_{}\", name_str, \"set_size\").as_str(), name.span());\n\n let select = Ident::new(format!(\"{}_{}\", name_str, \"select\").as_str(), name.span());\n\n let selected = Ident::new(format!(\"{}_{}\", name_str, \"selected\").as_str(), name.span());\n\n let text = Ident::new(format!(\"{}_{}\", name_str, \"text\").as_str(), name.span());\n\n let set_text = Ident::new(format!(\"{}_{}\", name_str, \"set_text\").as_str(), name.span());\n\n let load_file = Ident::new(\n\n format!(\"{}_{}\", name_str, \"load_file\").as_str(),\n\n name.span(),\n\n );\n", "file_path": "fltk-derive/src/browser.rs", "rank": 57, "score": 217422.19609732792 }, { "content": "pub fn impl_window_trait(ast: &DeriveInput) -> TokenStream {\n\n let name = &ast.ident;\n\n let name_str = get_fl_name(name.to_string());\n\n\n\n let make_modal = Ident::new(\n\n format!(\"{}_{}\", name_str, \"make_modal\").as_str(),\n\n name.span(),\n\n );\n\n let fullscreen = Ident::new(\n\n format!(\"{}_{}\", name_str, \"fullscreen\").as_str(),\n\n name.span(),\n\n );\n\n let make_current = Ident::new(\n\n format!(\"{}_{}\", name_str, \"make_current\").as_str(),\n\n name.span(),\n\n );\n\n let icon = Ident::new(format!(\"{}_{}\", name_str, \"icon\").as_str(), name.span());\n\n let set_icon = Ident::new(format!(\"{}_{}\", name_str, \"set_icon\").as_str(), name.span());\n\n let set_border = Ident::new(\n\n format!(\"{}_{}\", name_str, \"set_border\").as_str(),\n", "file_path": "fltk-derive/src/window.rs", "rank": 58, "score": 217422.19609732792 }, { "content": "pub fn impl_button_trait(ast: &DeriveInput) -> TokenStream {\n\n let name = &ast.ident;\n\n\n\n let name_str = get_fl_name(name.to_string());\n\n\n\n let shortcut = Ident::new(format!(\"{}_{}\", name_str, \"shortcut\").as_str(), name.span());\n\n let set_shortcut = Ident::new(\n\n format!(\"{}_{}\", name_str, \"set_shortcut\").as_str(),\n\n name.span(),\n\n );\n\n let clear = Ident::new(format!(\"{}_{}\", name_str, \"clear\").as_str(), name.span());\n\n let value = Ident::new(format!(\"{}_{}\", name_str, \"value\").as_str(), name.span());\n\n let set_value = Ident::new(\n\n format!(\"{}_{}\", name_str, \"set_value\").as_str(),\n\n name.span(),\n\n );\n\n let down_box = Ident::new(format!(\"{}_{}\", name_str, \"down_box\").as_str(), name.span());\n\n let set_down_box = Ident::new(\n\n format!(\"{}_{}\", name_str, \"set_down_box\").as_str(),\n\n name.span(),\n", "file_path": "fltk-derive/src/button.rs", "rank": 60, "score": 217422.19609732795 }, { "content": "/// Returns the recommended minimum line spacing for the current font\n\npub fn height() -> i32 {\n\n unsafe { Fl_height() as i32 }\n\n}\n\n\n", "file_path": "fltk/src/draw.rs", "rank": 61, "score": 217265.87168151868 }, { "content": "/// Gets the current font size, which is used in various drawing routines\n\npub fn size() -> i32 {\n\n unsafe { Fl_size() as i32 }\n\n}\n\n\n", "file_path": "fltk/src/draw.rs", "rank": 62, "score": 217265.8002339647 }, { "content": "/// Returns the recommended distance above the bottom of a height() tall box to\n\n/// draw the text at so it looks centered vertically in that box\n\npub fn descent() -> i32 {\n\n unsafe { Fl_descent() }\n\n}\n\n\n", "file_path": "fltk/src/draw.rs", "rank": 63, "score": 217265.48036970024 }, { "content": "/// Check whether a timeout is installed\n\npub fn has_timeout2(cb: fn()) -> bool {\n\n unsafe {\n\n let data: *mut raw::c_void = std::ptr::null_mut();\n\n let callback: Option<unsafe extern \"C\" fn(arg1: *mut raw::c_void)> = Some(mem::transmute(cb));\n\n fltk_sys::fl::Fl_has_timeout(callback, data) != 0\n\n }\n\n}\n", "file_path": "fltk/src/app/rt.rs", "rank": 64, "score": 216799.6240560077 }, { "content": "/// Checks whether an idle function is installed\n\npub fn has_idle2(cb: fn()) -> bool {\n\n unsafe {\n\n let data: *mut raw::c_void = std::ptr::null_mut();\n\n let callback: Option<unsafe extern \"C\" fn(arg1: *mut raw::c_void)> = Some(mem::transmute(cb));\n\n fl::Fl_has_idle(callback, data) != 0\n\n }\n\n}\n\n\n\n/**\n\n Adds a one-shot timeout callback. The timeout duration `tm` is indicated in seconds\n\n Example:\n\n ```rust,no_run\n\n use fltk::{prelude::*, *};\n\n fn callback() {\n\n println!(\"TICK\");\n\n app::repeat_timeout(1.0, callback);\n\n }\n\n fn main() {\n\n let app = app::App::default();\n\n let mut wind = window::Window::new(100, 100, 400, 300, \"\");\n\n wind.show();\n\n app::add_timeout(1.0, callback);\n\n app.run().unwrap();\n\n }\n\n ```\n\n*/\n", "file_path": "fltk/src/app/rt.rs", "rank": 65, "score": 216799.6240560077 }, { "content": "/// Draws a vertical line from (x,y) to (x,y1), then a horizontal from (x,y1) to (x2,y1)\n\npub fn draw_yxline2(x: i32, y: i32, y1: i32, x2: i32) {\n\n unsafe { Fl_yxline2(x, y, y1, x2) }\n\n}\n\n\n", "file_path": "fltk/src/draw.rs", "rank": 66, "score": 216633.71754939546 }, { "content": "/// Draws a horizontal line from (x,y) to (x1,y), then vertical from (x1,y) to (x1,y2)\n\npub fn draw_xyline2(x: i32, y: i32, x1: i32, y2: i32) {\n\n unsafe { Fl_xyline2(x, y, x1, y2) }\n\n}\n\n\n", "file_path": "fltk/src/draw.rs", "rank": 67, "score": 216633.71754939546 }, { "content": "/// This is similar to app::check() except this does not call app::flush() or any callbacks,\n\n/// which is useful if your program is in a state where such callbacks are illegal.\n\npub fn ready() -> bool {\n\n unsafe {\n\n if !IS_INIT.load(Ordering::Relaxed) {\n\n init_all();\n\n }\n\n fl::Fl_ready() != 0\n\n }\n\n}\n\n\n", "file_path": "fltk/src/app/rt.rs", "rank": 68, "score": 214232.55380652274 }, { "content": "/// Calling this during a big calculation will keep the screen up to date and the interface responsive.\n\npub fn check() -> bool {\n\n unsafe {\n\n if !IS_INIT.load(Ordering::Relaxed) {\n\n init_all();\n\n }\n\n fl::Fl_check() != 0\n\n }\n\n}\n\n\n", "file_path": "fltk/src/app/rt.rs", "rank": 69, "score": 214227.2976712177 }, { "content": "/// Starts waiting for events.\n\n/// Calls to redraw within wait require an explicit sleep\n\npub fn wait() -> bool {\n\n unsafe {\n\n if !IS_INIT.load(Ordering::Relaxed) {\n\n init_all();\n\n }\n\n fl::Fl_wait() != 0\n\n }\n\n}\n\n\n", "file_path": "fltk/src/app/rt.rs", "rank": 70, "score": 214227.2976712177 }, { "content": "/// Gets the y coordinate of the mouse in the window\n\npub fn event_y() -> i32 {\n\n unsafe { fl::Fl_event_y() }\n\n}\n\n\n", "file_path": "fltk/src/app/event.rs", "rank": 71, "score": 213104.2333342586 }, { "content": "/// Gets the x coordinate of the mouse in the window\n\npub fn event_x() -> i32 {\n\n unsafe { fl::Fl_event_x() }\n\n}\n\n\n", "file_path": "fltk/src/app/event.rs", "rank": 72, "score": 213104.2333342586 }, { "content": "/// Draws a horizontal line from (x,y) to (x1,y), then a vertical from (x1,y) to (x1,y2)\n\n/// and then another horizontal from (x1,y2) to (x3,y2)\n\npub fn draw_xyline3(x: i32, y: i32, x1: i32, y2: i32, x3: i32) {\n\n unsafe { Fl_xyline3(x, y, x1, y2, x3) }\n\n}\n\n\n", "file_path": "fltk/src/draw.rs", "rank": 73, "score": 213009.230571252 }, { "content": "/// Draws a vertical line from (x,y) to (x,y1) then a horizontal from (x,y1)\n\n/// to (x2,y1), then another vertical from (x2,y1) to (x2,y3)\n\npub fn draw_yxline3(x: i32, y: i32, y1: i32, x2: i32, y3: i32) {\n\n unsafe { Fl_yxline3(x, y, y1, x2, y3) }\n\n}\n\n\n", "file_path": "fltk/src/draw.rs", "rank": 74, "score": 213009.230571252 }, { "content": "/// Sets spot within the window\n\npub fn set_spot<Win: WindowExt>(font: Font, size: i32, x: i32, y: i32, w: i32, h: i32, win: &Win) {\n\n unsafe {\n\n assert!(!win.was_deleted());\n\n Fl_set_spot(\n\n font.bits() as i32,\n\n size as i32,\n\n x,\n\n y,\n\n w,\n\n h,\n\n win.as_widget_ptr() as *mut raw::c_void,\n\n )\n\n }\n\n}\n\n\n", "file_path": "fltk/src/draw.rs", "rank": 75, "score": 212548.84185790614 }, { "content": "/// Displays a message box\n\npub fn message(x: i32, y: i32, txt: &str) {\n\n unsafe {\n\n let txt = CString::safe_new(txt);\n\n Fl_message(x, y, txt.as_ptr())\n\n }\n\n}\n\n\n", "file_path": "fltk/src/dialog.rs", "rank": 76, "score": 211581.77546773184 }, { "content": "/// Displays an alert box\n\npub fn alert(x: i32, y: i32, txt: &str) {\n\n unsafe {\n\n let txt = CString::safe_new(txt);\n\n Fl_alert(x, y, txt.as_ptr())\n\n }\n\n}\n\n\n", "file_path": "fltk/src/dialog.rs", "rank": 77, "score": 211581.77546773184 }, { "content": "/// Draws a line\n\npub fn draw_line(x1: i32, y1: i32, x2: i32, y2: i32) {\n\n unsafe {\n\n Fl_line(x1, y1, x2, y2);\n\n }\n\n}\n\n\n", "file_path": "fltk/src/draw.rs", "rank": 78, "score": 211449.42284892016 }, { "content": "/// Returns false for a single click and true for more\n\npub fn event_clicks() -> bool {\n\n unsafe { fl::Fl_event_clicks() != 0 }\n\n}\n\n\n", "file_path": "fltk/src/app/event.rs", "rank": 79, "score": 210313.08225626004 }, { "content": "/// Returns whether the event is a shift press\n\npub fn is_event_shift() -> bool {\n\n unsafe { fl::Fl_event_shift() != 0 }\n\n}\n\n\n", "file_path": "fltk/src/app/event.rs", "rank": 80, "score": 210313.08225626004 }, { "content": "/// Return whether visible focus is shown\n\npub fn visible_focus() -> bool {\n\n unsafe { fl::Fl_visible_focus() != 0 }\n\n}\n\n\n", "file_path": "fltk/src/app/visual.rs", "rank": 81, "score": 210313.08225626004 }, { "content": "/// Returns whether a quit signal was sent\n\npub fn should_program_quit() -> bool {\n\n unsafe { fl::Fl_should_program_quit() != 0 }\n\n}\n\n\n", "file_path": "fltk/src/app/rt.rs", "rank": 82, "score": 210313.08225626004 }, { "content": "/// Returns whether the event is a command key press\n\npub fn is_event_command() -> bool {\n\n unsafe { fl::Fl_event_command() != 0 }\n\n}\n\n\n", "file_path": "fltk/src/app/event.rs", "rank": 83, "score": 210313.0094992749 }, { "content": "/// Returns whether the event is a alt key press\n\npub fn is_event_alt() -> bool {\n\n unsafe { fl::Fl_event_alt() != 0 }\n\n}\n\n\n", "file_path": "fltk/src/app/event.rs", "rank": 84, "score": 210313.0094992749 }, { "content": "/// Returns whether the event is a control key press\n\npub fn is_event_ctrl() -> bool {\n\n unsafe { fl::Fl_event_ctrl() != 0 }\n\n}\n\n\n", "file_path": "fltk/src/app/event.rs", "rank": 85, "score": 210313.0094992749 }, { "content": "/// Determines whether an event was a click\n\npub fn event_is_click() -> bool {\n\n unsafe { fl::Fl_event_is_click() != 0 }\n\n}\n\n\n", "file_path": "fltk/src/app/event.rs", "rank": 86, "score": 210307.28899504326 }, { "content": "/// Checks whether platform supports true alpha blending for RGBA images\n\npub fn can_do_alpha_blending() -> bool {\n\n unsafe { Fl_can_do_alpha_blending() != 0 }\n\n}\n\n\n", "file_path": "fltk/src/draw.rs", "rank": 87, "score": 210307.28899504326 }, { "content": "/// Fills a 3-sided polygon. The polygon must be convex\n\npub fn draw_polygon(x: i32, y: i32, x1: i32, y1: i32, x2: i32, y2: i32) {\n\n unsafe { Fl_polygon(x, y, x1, y1, x2, y2) }\n\n}\n\n\n", "file_path": "fltk/src/draw.rs", "rank": 88, "score": 209282.2480790817 }, { "content": "/// Returns the duration of an event\n\npub fn event_length() -> i32 {\n\n unsafe { fl::Fl_event_length() as i32 }\n\n}\n\n\n", "file_path": "fltk/src/app/event.rs", "rank": 89, "score": 209192.54411482537 }, { "content": "/// Returns the captured button event.\n\n/// 1 for left key, 2 for middle, 3 for right\n\npub fn event_button() -> i32 {\n\n unsafe { fl::Fl_event_button() }\n\n}\n\n\n\n/// Defines Mouse buttons\n\n#[repr(i32)]\n\n#[derive(Debug, Copy, Clone, PartialEq)]\n\n#[non_exhaustive]\n\npub enum MouseButton {\n\n /// Left mouse button\n\n Left = 1,\n\n /// Middle mouse button\n\n Middle = 2,\n\n /// Right mouse button\n\n Right = 3,\n\n}\n\n\n", "file_path": "fltk/src/app/event.rs", "rank": 90, "score": 209192.1799809166 }, { "content": "/// Get the app's scrollbar size\n\npub fn scrollbar_size() -> i32 {\n\n unsafe { fl::Fl_scrollbar_size() as i32 }\n\n}\n\n\n", "file_path": "fltk/src/app/visual.rs", "rank": 91, "score": 209186.59964250313 }, { "content": "/// Gets FLTK API version\n\npub fn api_version() -> i32 {\n\n unsafe { fl::Fl_api_version() }\n\n}\n\n\n", "file_path": "fltk/src/app/version.rs", "rank": 92, "score": 209186.59964250313 }, { "content": "/// Get the screen count\n\npub fn screen_count() -> i32 {\n\n unsafe { fl::Fl_screen_count() as i32 }\n\n}\n\n\n", "file_path": "fltk/src/app/screen.rs", "rank": 93, "score": 209186.59964250313 }, { "content": "/// Gets the y coordinate of the mouse in the screen\n\npub fn event_y_root() -> i32 {\n\n unsafe { fl::Fl_event_y_root() }\n\n}\n\n\n\n/// Event direction with Mousewheel event\n\n#[derive(Debug, Copy, Clone, PartialEq)]\n\npub enum MouseWheel {\n\n /// No movement\n\n None,\n\n /// Right movement\n\n Right,\n\n /// Left movement\n\n Left,\n\n /// Up movement\n\n Up,\n\n /// Down movement\n\n Down,\n\n}\n\n\n", "file_path": "fltk/src/app/event.rs", "rank": 94, "score": 209186.59964250313 }, { "content": "/// Get the default menu linespacing\n\npub fn menu_linespacing() -> i32 {\n\n unsafe { fl::Fl_menu_linespacing() }\n\n}\n\n\n", "file_path": "fltk/src/app/visual.rs", "rank": 95, "score": 209186.59964250313 }, { "content": "/// Gets the x coordinate of the mouse in the screen\n\npub fn event_x_root() -> i32 {\n\n unsafe { fl::Fl_event_x_root() }\n\n}\n\n\n", "file_path": "fltk/src/app/event.rs", "rank": 96, "score": 209186.59964250313 }, { "content": "/// Gets FLTK ABI version\n\npub fn abi_version() -> i32 {\n\n unsafe { fl::Fl_abi_version() }\n\n}\n\n\n", "file_path": "fltk/src/app/version.rs", "rank": 97, "score": 209186.59964250313 }, { "content": "/// Draws a string starting at the given x, y location\n\npub fn draw_text(txt: &str, x: i32, y: i32) {\n\n let txt = CString::safe_new(txt);\n\n unsafe { Fl_draw(txt.as_ptr(), x, y) }\n\n}\n\n\n", "file_path": "fltk/src/draw.rs", "rank": 98, "score": 208248.86290325964 }, { "content": "/// Draws a UTF-8 string right to left starting at the given x, y location\n\npub fn rtl_draw(txt: &str, x: i32, y: i32) {\n\n let len = txt.len() as i32;\n\n let txt = CString::safe_new(txt);\n\n unsafe { Fl_rtl_draw(txt.as_ptr(), len, x, y) }\n\n}\n\n\n", "file_path": "fltk/src/draw.rs", "rank": 99, "score": 208248.86290325964 } ]
Rust
render_pi/src/gl_context.rs
j-selby/leaffront
13b15fda0ffa309433e08dc17d4bb0e3f20e9335
use egl; use egl::{EGLConfig, EGLContext, EGLDisplay, EGLNativeDisplayType, EGLSurface}; use videocore::bcm_host; use videocore::dispmanx; use videocore::dispmanx::{ DisplayHandle, ElementHandle, FlagsAlpha, Transform, UpdateHandle, VCAlpha, Window, }; use videocore::image::Rect; use videocore::bcm_host::GraphicsDisplaySize; use std::ptr; pub struct Context { pub config: EGLConfig, pub context: EGLContext, pub display: EGLDisplay, pub surface: EGLSurface, #[allow(dead_code)] window: Box<Window>, pub dispman_display: DisplayHandle, pub update: UpdateHandle, pub element: ElementHandle, pub bg_element: ElementHandle, } impl Context { pub fn get_resolution() -> GraphicsDisplaySize { bcm_host::graphics_get_display_size(0).unwrap() } pub fn swap_buffers(&self) -> bool { egl::swap_buffers(self.display, self.surface) } pub fn build() -> Result<Self, String> { bcm_host::init(); let display = dispmanx::display_open(0); let update = dispmanx::update_start(0); let dimensions: Result<GraphicsDisplaySize, String> = match bcm_host::graphics_get_display_size(0) { Some(x) => Ok(x), None => Err("bcm_host::init() did not succeed".into()), }; let dimensions = dimensions?; println!("Display size: {}x{}", dimensions.width, dimensions.height); let mut dest_rect = Rect { x: 0, y: 0, width: dimensions.width as i32, height: dimensions.height as i32, }; let mut src_rect = Rect { x: 0, y: 0, width: (dimensions.width as i32) << 16, height: (dimensions.height as i32) << 16, }; let mut alpha = VCAlpha { flags: FlagsAlpha::FIXED_ALL_PIXELS, opacity: 255, mask: 0, }; let bg_element = dispmanx::element_add( update, display, 2, &mut dest_rect, 0, &mut src_rect, dispmanx::DISPMANX_PROTECTION_NONE, &mut alpha, ptr::null_mut(), Transform::NO_ROTATE, ); let mut alpha = VCAlpha { flags: FlagsAlpha::FROM_SOURCE, opacity: 255, mask: 0, }; let mut src_rect = Rect { x: 0, y: 0, width: 0, height: 0, }; let element = dispmanx::element_add( update, display, 3, &mut dest_rect, 0, &mut src_rect, dispmanx::DISPMANX_PROTECTION_NONE, &mut alpha, ptr::null_mut(), Transform::NO_ROTATE, ); dispmanx::update_submit_sync(update); let mut window = Box::new(Window { element, width: dimensions.width as i32, height: dimensions.height as i32, }); let context_attr = [egl::EGL_CONTEXT_CLIENT_VERSION, 2, egl::EGL_NONE]; let config_attr = [ egl::EGL_RED_SIZE, 8, egl::EGL_GREEN_SIZE, 8, egl::EGL_BLUE_SIZE, 8, egl::EGL_ALPHA_SIZE, 8, egl::EGL_SURFACE_TYPE, egl::EGL_WINDOW_BIT, egl::EGL_NONE, ]; let egl_display: Result<EGLDisplay, String> = match egl::get_display(egl::EGL_DEFAULT_DISPLAY) { Some(x) => Ok(x), None => Err("Failed to get EGL display".into()), }; let egl_display: EGLDisplay = egl_display?; if !egl::initialize(egl_display, &mut 0i32, &mut 0i32) { return Err("Failed to initialize EGL".into()); } let egl_config: Result<EGLConfig, String> = match egl::choose_config(egl_display, &config_attr, 1) { Some(x) => Ok(x), None => Err("Failed to get EGL configuration".into()), }; let egl_config: EGLConfig = egl_config?; if !egl::bind_api(egl::EGL_OPENGL_ES_API) { return Err("Failed to bind EGL OpenGL ES API".into()); } let egl_context: Result<EGLContext, String> = match egl::create_context( egl_display, egl_config, egl::EGL_NO_CONTEXT, &context_attr, ) { Some(x) => Ok(x), None => Err("Failed to create EGL context".into()), }; let egl_context: EGLContext = egl_context?; let egl_surface: Result<EGLSurface, String> = match egl::create_window_surface( egl_display, egl_config, window.as_mut() as *mut _ as EGLNativeDisplayType, &[], ) { Some(x) => Ok(x), None => Err("Failed to create EGL surface".into()), }; let egl_surface: EGLSurface = egl_surface?; if !egl::make_current(egl_display, egl_surface, egl_surface, egl_context) { return Err("Failed to make EGL current context".into()); } if !egl::swap_interval(egl_display, 1) { return Err("Failed to setup swapping".into()); } Ok(Self { config: egl_config, context: egl_context, display: egl_display, surface: egl_surface, window, dispman_display: display, update, element, bg_element, }) } } impl Drop for Context { fn drop(&mut self) { println!("Context shutdown!"); egl::destroy_surface(self.display, self.surface); egl::destroy_context(self.display, self.context); egl::terminate(self.display); dispmanx::element_remove(self.update, self.element); dispmanx::element_remove(self.update, self.bg_element); dispmanx::update_submit_sync(self.update); if !dispmanx::display_close(self.dispman_display) { println!("Display shutdown successful."); } else { println!("Display shutdown failed."); } bcm_host::deinit(); } }
use egl; use egl::{EGLConfig, EGLContext, EGLDisplay, EGLNativeDisplayType, EGLSurface}; use videocore::bcm_host; use videocore::dispmanx; use videocore::dispmanx::{ DisplayHandle, ElementHandle, FlagsAlpha, Transform, UpdateHandle, VCAlpha, Window, }; use videocore::image::Rect; use videocore::bcm_host::GraphicsDisplaySize; use std::ptr; pub struct Context { pub config: EGLConfig, pub context: EGLContext, pub display: EGLDisplay, pub surface: EGLSurface, #[allow(dead_code)] window: Box<Window>, pub dispman_display: DisplayHandle, pub update: UpdateHandle, pub element: ElementHandle, pub bg_element: ElementHandle, } impl Context { pub fn get_resolution() -> GraphicsDisplaySize { bcm_host::graphics_get_display_size(0).unwrap() } pub fn swap_buffers(&self) -> bool { egl::swap_buffers(self.display, self.surface) } pub fn build() -> Result<Self, String> { bcm_host::init(); let display = dispmanx::display_open(0); let update = dispmanx::update_start(0); let dimensions: Result<GraphicsDisplaySize, String> = match bcm_host::graphics_get_display_size(0) { Some(x) => Ok(x), None => Err("bcm_host::init() did not succeed".into()), }; let dimensions = dimensions?; println!("Display size: {}x{}", dimensions.width, dimensions.height); let mut dest_rect = Rect { x: 0, y: 0, width: dimensions.width as i32, height: dimensions.height as i32, }; let mut src_rect = Rect { x: 0, y: 0, width: (dimensions.width as i32) << 16, height: (dimensions.height as i32) << 16, }; let mut alpha = VCAlpha { flags: FlagsAlpha::FIXED_ALL_PIXELS, opacity: 255, mask: 0, }; let bg_element = dispmanx::element_add( update, display, 2, &mut dest_rect, 0, &mut src_rect, dispmanx::DISPMANX_PROTECTION_NONE, &mut alpha, ptr::null_mut(), Transform::NO_ROTATE, ); let mut alpha = VCAlpha { flags: FlagsAlpha::FROM_SOURCE, opacity: 255, mask: 0, }; let mut src_rect = Rect { x: 0, y: 0, width: 0, height: 0, }; let element = dispmanx::element_add( update, display, 3, &mut dest_rect, 0, &mut src_rect, dispmanx::DISPMANX_PROTECTION_NONE, &mut alpha, ptr::null_mut(), Transform::NO_ROTATE,
("Display shutdown successful."); } else { println!("Display shutdown failed."); } bcm_host::deinit(); } }
); dispmanx::update_submit_sync(update); let mut window = Box::new(Window { element, width: dimensions.width as i32, height: dimensions.height as i32, }); let context_attr = [egl::EGL_CONTEXT_CLIENT_VERSION, 2, egl::EGL_NONE]; let config_attr = [ egl::EGL_RED_SIZE, 8, egl::EGL_GREEN_SIZE, 8, egl::EGL_BLUE_SIZE, 8, egl::EGL_ALPHA_SIZE, 8, egl::EGL_SURFACE_TYPE, egl::EGL_WINDOW_BIT, egl::EGL_NONE, ]; let egl_display: Result<EGLDisplay, String> = match egl::get_display(egl::EGL_DEFAULT_DISPLAY) { Some(x) => Ok(x), None => Err("Failed to get EGL display".into()), }; let egl_display: EGLDisplay = egl_display?; if !egl::initialize(egl_display, &mut 0i32, &mut 0i32) { return Err("Failed to initialize EGL".into()); } let egl_config: Result<EGLConfig, String> = match egl::choose_config(egl_display, &config_attr, 1) { Some(x) => Ok(x), None => Err("Failed to get EGL configuration".into()), }; let egl_config: EGLConfig = egl_config?; if !egl::bind_api(egl::EGL_OPENGL_ES_API) { return Err("Failed to bind EGL OpenGL ES API".into()); } let egl_context: Result<EGLContext, String> = match egl::create_context( egl_display, egl_config, egl::EGL_NO_CONTEXT, &context_attr, ) { Some(x) => Ok(x), None => Err("Failed to create EGL context".into()), }; let egl_context: EGLContext = egl_context?; let egl_surface: Result<EGLSurface, String> = match egl::create_window_surface( egl_display, egl_config, window.as_mut() as *mut _ as EGLNativeDisplayType, &[], ) { Some(x) => Ok(x), None => Err("Failed to create EGL surface".into()), }; let egl_surface: EGLSurface = egl_surface?; if !egl::make_current(egl_display, egl_surface, egl_surface, egl_context) { return Err("Failed to make EGL current context".into()); } if !egl::swap_interval(egl_display, 1) { return Err("Failed to setup swapping".into()); } Ok(Self { config: egl_config, context: egl_context, display: egl_display, surface: egl_surface, window, dispman_display: display, update, element, bg_element, }) } } impl Drop for Context { fn drop(&mut self) { println!("Context shutdown!"); egl::destroy_surface(self.display, self.surface); egl::destroy_context(self.display, self.context); egl::terminate(self.display); dispmanx::element_remove(self.update, self.element); dispmanx::element_remove(self.update, self.bg_element); dispmanx::update_submit_sync(self.update); if !dispmanx::display_close(self.dispman_display) { println!
random
[ { "content": "/// Loads a configuration file.\n\npub fn load_config(dir: String) -> LeaffrontConfig {\n\n let mut f = File::open(dir).expect(\"Config file not found\");\n\n\n\n let mut config_string = String::new();\n\n f.read_to_string(&mut config_string).unwrap();\n\n\n\n toml::from_str(&config_string).unwrap()\n\n}\n", "file_path": "src/config.rs", "rank": 0, "score": 154970.53532904215 }, { "content": "pub fn main_loop(config: LeaffrontConfig) {\n\n let start_night = config.sleep.sleep_hour;\n\n let end_night = config.sleep.wakeup_hour;\n\n\n\n // Connect to the backend\n\n let mut backend = BackendImpl::new().unwrap();\n\n\n\n let mut notifications = Vec::new();\n\n\n\n // Create our mechanism for rendering\n\n let mut drawer = DrawerImpl::new();\n\n\n\n // Startup input handling\n\n let input = InputImpl::new();\n\n\n\n // Check the startup time\n\n let mut state = if check_night(start_night, end_night) {\n\n ScreenState::Night\n\n } else {\n\n ScreenState::Day(Message::Date)\n", "file_path": "src/main_loop.rs", "rank": 1, "score": 127571.91873289112 }, { "content": "pub fn check_night(start_night: u32, end_night: u32) -> bool {\n\n let time = Local::now();\n\n let start_time = NaiveTime::from_hms(start_night, 0, 0);\n\n let end_time = NaiveTime::from_hms(end_night, 0, 0);\n\n let cur_date = time.naive_local();\n\n let cur_time = cur_date.time();\n\n\n\n let start_date = if (cur_time < end_time) && !(start_time < end_time) {\n\n // Early morning\n\n let start_date = time.date().naive_local();\n\n let start_date = start_date - cDuration::days(1);\n\n start_date.and_time(start_time)\n\n } else {\n\n time.date().naive_local().and_time(start_time)\n\n };\n\n\n\n let end_date = if start_time > end_time && !(cur_time < end_time) {\n\n // End night is on the next day\n\n let end_date = time.date().naive_local();\n\n let end_date = end_date + cDuration::days(1);\n\n end_date.and_time(end_time)\n\n } else {\n\n time.date().naive_local().and_time(end_time)\n\n };\n\n\n\n cur_date > start_date && cur_date < end_date\n\n}\n", "file_path": "src/clock.rs", "rank": 2, "score": 101487.42504018865 }, { "content": "fn main() {\n\n println!(\"cargo:rustc-link-search=/opt/vc/lib\");\n\n}\n", "file_path": "build.rs", "rank": 3, "score": 89030.31714068295 }, { "content": "#[derive(Deserialize, Debug)]\n\nstruct BOMConfig {\n\n /// Some location - will be looked up against BOM's API.\n\n /// e.g. \"Sydney\"\n\n location: String,\n\n}\n\n\n\n/// Metadata tag on JSON responses\n", "file_path": "weather/src/bom.rs", "rank": 4, "score": 79782.36576108931 }, { "content": "struct InputUpdate {\n\n mouse_x: usize,\n\n mouse_y: usize,\n\n mouse_down: bool,\n\n}\n\n\n\nimpl PiInputThreaded {\n\n fn detect_devices(&mut self) {\n\n self.devices.clear();\n\n\n\n let devices = evdev::enumerate();\n\n\n\n for device in devices {\n\n if device.supported_events().contains(EventType::ABSOLUTE) {\n\n info!(\"Found input device: {:?}\", device.name());\n\n self.devices.push(device);\n\n }\n\n }\n\n }\n\n\n", "file_path": "input_pi/src/lib.rs", "rank": 5, "score": 77728.42210682188 }, { "content": "#[derive(Deserialize, Debug)]\n\nstruct OpenWeatherMapConfig {\n\n api_key: String,\n\n // e.g. \"Sydney,AU\"\n\n location: String,\n\n temp_units: WeatherUnits,\n\n}\n\n\n\n/// Actual location for request\n", "file_path": "weather/src/openweathermap.rs", "rank": 6, "score": 75567.5380810787 }, { "content": "pub fn set_brightness(brightness: u8) -> Result<(), io::Error> {\n\n // Attempt to search for a brightness controller\n\n let path = Path::new(\"/sys/class/backlight/\");\n\n\n\n if path.exists() {\n\n let path_contents = fs::read_dir(path)?;\n\n for child in path_contents {\n\n let child = child?;\n\n let child_metadata = child.metadata()?;\n\n\n\n if child_metadata.is_dir() || child_metadata.is_symlink() {\n\n // This is a possibility!\n\n let mut child_path = child.path();\n\n debug!(\"Found screen controller classed object: {:?}\", child_path);\n\n child_path.push(\"brightness\");\n\n\n\n // Get the absolute path\n\n let brightness_path = fs::canonicalize(child_path)?;\n\n debug!(\"Choosing brightness object: {:?}\", brightness_path);\n\n\n", "file_path": "core/src/brightness.rs", "rank": 7, "score": 68803.78262690152 }, { "content": "fn main() {\n\n let env = Env::default().default_filter_or(\"info\");\n\n env_logger::init_from_env(env);\n\n\n\n let matches = Command::new(\"Leaffront\")\n\n .version(VERSION)\n\n .author(\"Selby (https://github.com/j-selby)\")\n\n .about(\"A simple photoframe for the Raspberry Pi\")\n\n .long_about(\n\n \"Leaffront uses DispmanX + OpenGL to provide a simple slideshow, \\\n\n along with basic clock, date and weather information. \\\n\n Most values can be configured, and is lightweight enough that other \\\n\n applications can be run alongside to enhance the experience.\",\n\n )\n\n .arg(\n\n Arg::new(\"config\")\n\n .short('c')\n\n .long(\"config\")\n\n .help(\"Provide a custom configuration file\")\n\n .default_value(\"config.toml\")\n", "file_path": "src/main.rs", "rank": 8, "score": 52852.89447167798 }, { "content": "fn main() {\n\n let server = NotificationServer::create();\n\n\n\n let client = redis::Client::open(\"redis://127.0.0.1/\").unwrap();\n\n let sub = client.get_connection().unwrap();\n\n\n\n NotificationServer::start(&server, move |notify| {\n\n let notification = Notification {\n\n name: notify.appname.to_owned(),\n\n contents: notify.body.to_owned(),\n\n };\n\n\n\n let v: String =\n\n serde_json::to_string(&notification).expect(\"Failed to convert notification to JSON\");\n\n let k: &str = \"leaffront.notify\";\n\n\n\n redis::cmd(\"PUBLISH\").arg(k).arg(&v).execute(&sub);\n\n });\n\n}\n", "file_path": "dbus/src/main.rs", "rank": 9, "score": 51578.91527575582 }, { "content": "/// A texture bundle contains both a raw, CPU-managed texture, as well\n\n/// as a GPU texture. This allows for updates to the CPU-managed texture\n\n/// easily.\n\nstruct TextureBundle {\n\n sample: Texture,\n\n native: <DrawerImpl as Drawer>::NativeTexture,\n\n}\n\n\n", "file_path": "src/main_loop.rs", "rank": 10, "score": 48981.60902904952 }, { "content": "#[derive(Deserialize, Debug)]\n\nstruct ResponseLocations {\n\n metadata: ResponseMetadata,\n\n data: Vec<ResponseLocation>,\n\n}\n\n\n\n/// Live data as part of the first payload of forecasts\n", "file_path": "weather/src/bom.rs", "rank": 11, "score": 48978.353091754085 }, { "content": "#[derive(Deserialize, Debug)]\n\nstruct ResponseObservations {\n\n metadata: ResponseMetadata,\n\n data: ResponseObservationsPayload,\n\n}\n\n\n\nstatic MIN_GEOCODE_LENGTH: usize = 4;\n\n\n\npub struct BOM;\n\n\n\nimpl BOM {}\n\n\n", "file_path": "weather/src/bom.rs", "rank": 12, "score": 48978.353091754085 }, { "content": "#[derive(Deserialize, Debug)]\n\nstruct ResponseMetadata {\n\n #[serde(default)]\n\n response_timestamp: Option<String>,\n\n #[serde(default)]\n\n issue_time: Option<String>,\n\n #[serde(default)]\n\n forecast_region: Option<String>,\n\n #[serde(default)]\n\n forecast_type: Option<String>,\n\n}\n\n\n\n/// Information on a single location\n", "file_path": "weather/src/bom.rs", "rank": 13, "score": 48978.353091754085 }, { "content": "#[derive(Deserialize, Debug)]\n\nstruct ResponseCoords {\n\n #[serde(default)]\n\n lon: f64,\n\n #[serde(default)]\n\n lat: f64,\n\n}\n\n\n\n/// Contains a particular state of weather (e.g. \"cloudy\")\n", "file_path": "weather/src/openweathermap.rs", "rank": 14, "score": 48978.353091754085 }, { "content": "#[derive(Deserialize, Debug)]\n\nstruct ResponseForecast {\n\n metadata: ResponseMetadata,\n\n data: Vec<ResponseWeather>,\n\n}\n\n\n\n/// The inner observations payload\n", "file_path": "weather/src/bom.rs", "rank": 15, "score": 48978.353091754085 }, { "content": "#[derive(Deserialize, Debug)]\n\nstruct ResponseLocation {\n\n geohash: String,\n\n #[serde(default)]\n\n id: Option<String>,\n\n name: String,\n\n #[serde(default)]\n\n postcode: Option<String>,\n\n #[serde(default)]\n\n state: Option<String>,\n\n}\n\n\n\n/// Response from the V1 locations API\n", "file_path": "weather/src/bom.rs", "rank": 16, "score": 48978.353091754085 }, { "content": "struct WeatherWorker {\n\n channel_sender: Sender<()>,\n\n channel_receiver: Receiver<Result<Weather, String>>,\n\n}\n\n\n\nimpl WeatherWorker {\n\n pub fn send_request(&self) {\n\n self.channel_sender\n\n .send(())\n\n .expect(\"Failed to send message!\")\n\n }\n\n\n\n pub fn wait_for_request(\n\n &self,\n\n timeout: Duration,\n\n ) -> Result<Result<Weather, String>, RecvTimeoutError> {\n\n self.channel_receiver.recv_timeout(timeout)\n\n }\n\n\n\n pub fn new(kind: WeatherProviderKind, config: Option<toml::Value>) -> Self {\n", "file_path": "weather/src/manager.rs", "rank": 17, "score": 48978.353091754085 }, { "content": "#[derive(Deserialize, Debug)]\n\nstruct ResponseWeather {\n\n // \"rain\", \"uv\", \"astronomical\" ignored\n\n date: String,\n\n #[serde(default)]\n\n temp_max: Option<f64>,\n\n #[serde(default)]\n\n temp_min: Option<f64>,\n\n #[serde(default)]\n\n extended_text: Option<String>,\n\n #[serde(default)]\n\n icon_descriptor: Option<String>,\n\n #[serde(default)]\n\n short_text: Option<String>,\n\n #[serde(default)]\n\n fire_danger: Option<String>,\n\n #[serde(default)]\n\n now: Option<ResponseWeatherNow>,\n\n}\n\n\n\n/// The entire forecasts query\n", "file_path": "weather/src/bom.rs", "rank": 18, "score": 48978.353091754085 }, { "content": "#[derive(Deserialize, Debug)]\n\nstruct ResponseWeatherClouds {\n\n #[serde(default)]\n\n all: f64,\n\n}\n\n\n\n/// Information about the location of the data collector\n", "file_path": "weather/src/openweathermap.rs", "rank": 19, "score": 47894.20785593633 }, { "content": "#[derive(Deserialize, Debug)]\n\nstruct ResponseObservationsPayload {\n\n temp: f64,\n\n temp_feels_like: f64,\n\n // wind\n\n // rain_since_9am\n\n // humidity\n\n // staiton\n\n}\n\n\n\n/// Current observations for a location\n", "file_path": "weather/src/bom.rs", "rank": 20, "score": 47894.20785593633 }, { "content": "#[derive(Deserialize, Debug)]\n\nstruct ResponseWeatherEntry {\n\n #[serde(default)]\n\n id: u64,\n\n #[serde(default)]\n\n main: String,\n\n description: String,\n\n #[serde(default)]\n\n icon: String,\n\n}\n\n\n\n/// Contains the main set of measurements (temp, humidity, etc)\n", "file_path": "weather/src/openweathermap.rs", "rank": 21, "score": 47894.20785593633 }, { "content": "#[derive(Deserialize, Debug)]\n\nstruct ResponseWeatherWind {\n\n speed: f64,\n\n deg: f64,\n\n}\n\n\n\n/// Information about cloud levels\n", "file_path": "weather/src/openweathermap.rs", "rank": 22, "score": 47894.20785593633 }, { "content": "#[derive(Deserialize, Debug)]\n\nstruct ResponseWeatherNow {\n\n #[serde(default)]\n\n is_night: bool,\n\n now_label: String,\n\n #[serde(default)]\n\n later_label: Option<String>,\n\n temp_now: f64,\n\n #[serde(default)]\n\n temp_later: Option<f64>,\n\n}\n\n\n\n/// A single weather response from the API\n", "file_path": "weather/src/bom.rs", "rank": 23, "score": 47894.20785593633 }, { "content": "#[derive(Deserialize, Debug)]\n\nstruct ResponseWeatherSystem {\n\n #[serde(rename = \"type\")]\n\n #[serde(default)]\n\n sys_type: u64,\n\n #[serde(default)]\n\n id: u64,\n\n #[serde(default)]\n\n country: String,\n\n #[serde(default)]\n\n sunrise: u64,\n\n #[serde(default)]\n\n sunset: u64,\n\n}\n\n\n\n/// JSON output from OpenWeatherMap\n", "file_path": "weather/src/openweathermap.rs", "rank": 24, "score": 47894.20785593633 }, { "content": "pub trait Backend {\n\n fn get_notification(&mut self) -> Option<Notification>;\n\n}\n", "file_path": "core/src/backend.rs", "rank": 25, "score": 47211.404302368246 }, { "content": "#[derive(Deserialize, Debug)]\n\nstruct ResponseWeatherMainMeasurements {\n\n temp: f64,\n\n #[serde(default)]\n\n pressure: f64,\n\n #[serde(default)]\n\n humidity: f64,\n\n #[serde(default)]\n\n temp_min: f64,\n\n #[serde(default)]\n\n temp_max: f64,\n\n}\n\n\n\n/// Direction/speed of wind\n", "file_path": "weather/src/openweathermap.rs", "rank": 26, "score": 46884.717850978755 }, { "content": "/// Implements a basic input mechanism for the Pi through evdev.\n\nstruct PiInputThreaded {\n\n devices: Vec<evdev::Device>,\n\n mouse_x: usize,\n\n mouse_y: usize,\n\n mouse_down: bool,\n\n outgoing_channel: Sender<InputUpdate>,\n\n}\n\n\n", "file_path": "input_pi/src/lib.rs", "rank": 27, "score": 46884.717850978755 }, { "content": "#[derive(Deserialize)]\n\nstruct OpenWeatherMapResponse {\n\n #[serde(default)]\n\n coord: Option<ResponseCoords>,\n\n weather: Vec<ResponseWeatherEntry>,\n\n /// Unknown use - reports \"stations\"?\n\n #[serde(default)]\n\n base: Option<String>,\n\n main: ResponseWeatherMainMeasurements,\n\n #[serde(default)]\n\n visibility: Option<u64>,\n\n #[serde(default)]\n\n wind: Option<ResponseWeatherWind>,\n\n #[serde(default)]\n\n clouds: Option<ResponseWeatherClouds>,\n\n // Day/time\n\n #[serde(default)]\n\n dt: Option<u64>,\n\n #[serde(default)]\n\n sys: Option<ResponseWeatherSystem>,\n\n #[serde(default)]\n", "file_path": "weather/src/openweathermap.rs", "rank": 28, "score": 46884.717850978755 }, { "content": "/// The dimensions of a object\n\npub trait Dimensions {\n\n /// Returns the width of this object.\n\n fn get_width(&self) -> usize;\n\n\n\n /// Returns the height of this object.\n\n fn get_height(&self) -> usize;\n\n}\n\n\n", "file_path": "core/src/render/mod.rs", "rank": 29, "score": 46116.7115747095 }, { "content": "pub trait VersionInfo {\n\n /// Returns version information about this implementation\n\n fn version() -> String;\n\n}\n", "file_path": "core/src/version.rs", "rank": 30, "score": 46116.7115747095 }, { "content": "pub trait WeatherProvider {\n\n fn get_weather(config: Option<toml::Value>) -> Result<Weather, String>;\n\n}\n\n\n\n/// What weather providers are available:\n\n#[derive(Copy, Clone, Deserialize, Debug)]\n\npub enum WeatherProviderKind {\n\n OpenWeatherMap,\n\n BOM,\n\n}\n", "file_path": "weather/src/lib.rs", "rank": 31, "score": 46116.7115747095 }, { "content": "/// Handles basic input\n\npub trait Input {\n\n type Window: Drawer;\n\n\n\n /// Infinitely runs the loop until told otherwise\n\n fn run<T: FnMut(&Self, &mut Self::Window) -> (bool, Instant) + 'static>(\n\n self,\n\n drawer: Self::Window,\n\n function: T,\n\n ) -> !;\n\n\n\n /// Checks to see if the mouse/pointer is down\n\n fn is_mouse_down(&self) -> bool;\n\n\n\n /// Returns the current mouse position in a (x, y) tuple.\n\n fn get_mouse_pos(&self) -> (usize, usize);\n\n\n\n /// Checks to see if execution should be continued\n\n fn do_continue(&self) -> bool;\n\n}\n", "file_path": "core/src/input/mod.rs", "rank": 32, "score": 46116.7115747095 }, { "content": "/// Structures for rendering stuff to the screen\n\npub trait Drawer {\n\n type NativeTexture: Sized + Dimensions;\n\n\n\n /// Starts a particular rendering frame\n\n fn start(&mut self);\n\n\n\n /// Ends a frame, requesting for framebuffers to be finalised/etc\n\n fn end(&mut self);\n\n\n\n /// Clears the frame.\n\n /// transparent: If the frame should be cleared to alpha 0.\n\n fn clear(&mut self, transparent: bool);\n\n\n\n /// Enables blending of a texture/etc with the background, if this is\n\n /// explicitly required.\n\n fn enable_blending(&mut self);\n\n\n\n /// Converts a texture to a native reference.\n\n fn convert_native_texture(&mut self, texture: Texture) -> Self::NativeTexture;\n\n\n", "file_path": "core/src/render/mod.rs", "rank": 33, "score": 46116.7115747095 }, { "content": "fn try_with_different_length_geocodes<T, F>(\n\n client: &reqwest::blocking::Client,\n\n endpoint: F,\n\n geohash: &str,\n\n) -> Result<T, String>\n\nwhere\n\n F: Fn(&str) -> String,\n\n for<'de> T: serde::Deserialize<'de>,\n\n{\n\n match client\n\n .get(&endpoint(geohash))\n\n .send()\n\n .map_err(|x| format!(\"Error sending request: {:?}\", x))?\n\n .json()\n\n .map_err(|x| format!(\"Error parsing request: {:?}\", x))\n\n {\n\n Ok(v) => Ok(v),\n\n Err(e) => {\n\n if geohash.len() <= MIN_GEOCODE_LENGTH {\n\n return Err(e);\n", "file_path": "weather/src/bom.rs", "rank": 34, "score": 41096.45570904754 }, { "content": "use std::fs::File;\n\nuse std::io::Read;\n\n\n\nuse toml;\n\n\n\nuse leaffront_weather::WeatherProviderKind;\n\n\n\n#[derive(Deserialize, Debug)]\n\npub struct LeaffrontConfig {\n\n pub art_dir: String,\n\n pub refresh_rate: u64,\n\n pub sleep: Sleep,\n\n pub day: Day,\n\n pub night: Night,\n\n pub weather: Weather,\n\n pub fullscreen: bool,\n\n}\n\n\n\n#[derive(Deserialize, Debug)]\n\npub struct Sleep {\n", "file_path": "src/config.rs", "rank": 35, "score": 34662.66509517153 }, { "content": " pub sleep_hour: u32,\n\n pub wakeup_hour: u32,\n\n}\n\n\n\n#[derive(Deserialize, Debug)]\n\npub struct Night {\n\n pub move_secs: u64,\n\n pub night_tap_cooldown: u64,\n\n pub brightness: u8,\n\n}\n\n\n\n#[derive(Deserialize, Debug)]\n\npub struct Day {\n\n pub background_secs: u64,\n\n pub subtitle_secs: u64,\n\n pub brightness: u8,\n\n}\n\n\n\n#[derive(Deserialize, Debug)]\n\npub struct Weather {\n\n pub update_freq: u64,\n\n pub kind: WeatherProviderKind,\n\n pub config: Option<toml::Value>,\n\n}\n\n\n\n/// Loads a configuration file.\n", "file_path": "src/config.rs", "rank": 36, "score": 34656.19948240878 }, { "content": "fn unwrap_redis<T>(result: RedisResult<T>) -> Result<T, BackendError> {\n\n match result {\n\n Ok(val) => Ok(val),\n\n Err(_) => Err(BackendError::RedisFail),\n\n }\n\n}\n\n\n\nimpl RedisBackend {\n\n pub fn new() -> Result<Self, BackendError> {\n\n // TODO: Don't hardcode this URL\n\n let client = unwrap_redis(redis::Client::open(\"redis://127.0.0.1/\"))?;\n\n let mut sub = unwrap_redis(client.get_pubsub())?;\n\n\n\n unwrap_redis(sub.subscribe(\"leaffront.notify\"))?;\n\n\n\n // Start up listening thread\n\n let (notify_tx, notify_rx): (Sender<Notification>, Receiver<Notification>) =\n\n mpsc::channel();\n\n\n\n // TODO: Handle shutdowns\n", "file_path": "backend_redis/src/lib.rs", "rank": 37, "score": 30965.771677949237 }, { "content": "```\n\n\n\nFinally, you are going to need access to the Raspberry Pi's OpenGLES/DispmanX/etc\n\n stack. This can be found on a Raspberry Pi at `/opt/vc/lib`, which is \n\n the location which will be assumed from here on. These artifacts can also\n\n be found here (as of writing): <https://github.com/raspberrypi/firmware/tree/master/opt/vc/lib>\n\n\n\nThe supplied `station/build.sh` script will automatically invoke Cargo, strip\n\n the build artifact, and package it into a .deb file targeting\n\n `armv7-unknown-linux-gnueabihf`.\n\n\n\nAs Leaffront directly uses the the hardware video scaler and OpenGLES,\n\n a X server cannot run at the same time.\n\n\n", "file_path": "README.md", "rank": 51, "score": 24246.848285752465 }, { "content": "Leaffront\n\n=========\n\n\n\n[![Build Status](https://ci.jselby.net/job/leaffront/job/master/badge/icon)](https://ci.jselby.net/job/leaffront/job/master/)\n\n\n\nA weather station and notification synchronisation platform, designed to run\n\n pretty much anywhere. Targeted at the Raspberry Pi.\n\n \n\n![Splash](example.jpg)\n\n\n\nBuilding\n\n--------\n\n\n\nBuilding the application should be fairly simple as long as you are compiling\n\n on the target platform.\n\n\n\n```bash\n\ncd station\n\ncargo build --features glutin\n\n```\n\n\n\nReplace `glutin` with your preferred frontend.\n\n\n\nRunning\n\n-------\n\n\n\nTwo things (other then the application binary) are required to run Leaffront\n\n in the working directory:\n\n\n\n- An `art` directory, containing `.jpg`s or `.png`s. This can be empty, but\n\n Leaffront will only display a blank screen.\n\n- A `config.toml` file. An example can be found [here](example_config.toml).\n\n\n\nIf you want to use Redis for notifications, you also going to need this installed\n\n and running. This can be found in the Debian package `redis-server`.\n\n\n\nCross-compilation (for the Raspberry Pi)\n\n----------------------------------------\n\n\n\nCross-compiling *is* possible with the frontends provided (and is pretty much\n\n essential when targeting a platform such as the Pi), but requires a bit of\n\n hacking around.\n\n\n\nFirstly, ensure that you have Rustup installed on your building machine, then\n\n you are going to want to install the required cross-compiling utilities\n\n (For Debian):\n\n\n\n```bash\n\nsudo apt-get install gcc-4.7-arm-linux-gnueabihf\n\nrustup target add armv7-unknown-linux-gnueabihf\n\n```\n\n\n\nSeveral dependencies require a generic path to `gcc`, so a few ugly symlink\n\n *may* be required:\n\n\n\n```bash\n\nln -s /usr/bin/arm-linux-gnueabihf-gcc-4.7 /usr/bin/arm-linux-gnueabihf-gcc\n\ncp -r /usr/include/GL /usr/arm-linux-gnueabihf/include/GL\n\n```\n\n\n\nYou are going to want to configure Cargo to find this linker in `~/.cargo/config`:\n\n\n\n```toml\n\n[target.armv7-unknown-linux-gnueabihf]\n\nlinker = \"arm-linux-gnueabihf-gcc-4.7\"\n", "file_path": "README.md", "rank": 52, "score": 24246.0213408738 }, { "content": "Using systemd\n\n-------------\n\n\n\nThere is a systemd .service file provided for the Raspberry Pi, which can\n\n be found [here](res/leaffront.service). This runs as a system service, not\n\n a user one, and is only really useful in automated systems where there\n\n is no requirement for a X server.\n\n\n\nThe best way to use Leaffront on a traditional desktop platform would by\n\n via launching the executable from your DE.\n\n\n\nD-Bus Notification support\n\n--------------------------\n\n\n\nThe D-Bus bridge allows for messages sent via Gnome's Notification system,\n\n which is used by a whole array of GUI applications.\n\n\n\nSee [here](dbus/README.md) for more information.\n\n\n\nNetworked notifications\n\n-----------------------\n\n\n\n(TODO)\n\n\n\nLicense\n\n-------\n\n\n", "file_path": "README.md", "rank": 53, "score": 24244.6459110654 }, { "content": "D-Bus Bridge\n\n============\n\n\n\nA bridge which converts D-Bus notifications, as defined\n\n [here](https://developer.gnome.org/notification-spec/), into Redis events\n\n which are then distributed through the normal mechanisms.\n\n\n\nBuilding\n\n--------\n\n\n\nThis is really the easiest to build on your target platform, so cross-compilation\n\n instructions are not provided.\n\n\n\n```bash\n\ncargo build\n\n```\n\n\n\nAlternatively, if you want a Debian package with a user systemd service (for the\n\n Raspberry Pi):\n\n\n\n```bash\n\ncargo deb\n\n```\n\n\n\nTesting\n\n-------\n\n\n\nWhile the bridge, Leaffront, and redis is running:\n\n\n\n```bash\n\nnotify-send \"Title\" \"Body\"\n\n```\n\n\n\nshould display a message to the screen. If this fails, make sure that\n\n you have access to the correct D-Bus session.\n", "file_path": "dbus/README.md", "rank": 54, "score": 23552.926764506912 }, { "content": "}\n\n\n\nimpl Drawer for GlutinDrawer {\n\n type NativeTexture = GlTexture;\n\n\n\n fn start(&mut self) {\n\n self.calls = 0;\n\n self.transition_count = 0;\n\n\n\n self.state = DrawState::None;\n\n\n\n let (width, height): (u32, u32) = self.gl_window.window().inner_size().into();\n\n\n\n unsafe {\n\n gl::Viewport(0, 0, width as i32, height as i32);\n\n }\n\n }\n\n\n\n /// Ends this frame.\n\n fn end(&mut self) {\n", "file_path": "render_glutin/src/drawer.rs", "rank": 55, "score": 24.905577849783604 }, { "content": "/// Represents a X/Y position.\n\n#[derive(Copy, Clone)]\n\npub struct Position {\n\n pub x: i32,\n\n pub y: i32,\n\n}\n\n\n\nimpl Position {\n\n pub fn new(x: i32, y: i32) -> Self {\n\n Position { x, y }\n\n }\n\n}\n\n\n\n/// Represents a screen-space X/Y position, width and height.\n\npub struct Rect {\n\n pub x: i32,\n\n pub y: i32,\n\n pub width: i32,\n\n pub height: i32,\n\n}\n", "file_path": "core/src/pos.rs", "rank": 56, "score": 24.218544604271518 }, { "content": "\n\nimpl Rect {\n\n pub fn new_from_pos(pos: &Position, width: i32, height: i32) -> Self {\n\n Rect {\n\n x: pos.x,\n\n y: pos.y,\n\n width,\n\n height,\n\n }\n\n }\n\n\n\n pub fn new(x: i32, y: i32, width: i32, height: i32) -> Self {\n\n Rect {\n\n x,\n\n y,\n\n width,\n\n height,\n\n }\n\n }\n\n\n", "file_path": "core/src/pos.rs", "rank": 57, "score": 23.47064841522203 }, { "content": " bg_img.to_vec()\n\n };\n\n\n\n let bg_ptr = img_buffer.as_mut_ptr() as *mut _ as *mut c_void;\n\n let mut ptr = 0; // Unused\n\n\n\n let dest_rect = VCRect {\n\n x: 0,\n\n y: 0,\n\n width: target_width as i32,\n\n height: target_height as i32,\n\n };\n\n\n\n let element = self.context.bg_element;\n\n\n\n let bg_resource = dispmanx::resource_create(\n\n ImageType::RGB888,\n\n target_width as u32,\n\n target_height as u32,\n\n &mut ptr,\n", "file_path": "render_pi/src/drawer.rs", "rank": 58, "score": 23.470602397123297 }, { "content": " self.configure_state(DrawState::None);\n\n\n\n self.gl_window.swap_buffers().unwrap();\n\n }\n\n\n\n /// Clears the framebuffer.\n\n fn clear(&mut self, transparent: bool) {\n\n unsafe {\n\n gl::ClearColor(0.0, 0.0, 0.0, 1.0);\n\n gl::Clear(gl::COLOR_BUFFER_BIT);\n\n }\n\n\n\n // Draw our background here, if required\n\n if transparent {\n\n if self.background.is_some() {\n\n let size = Rect::new(0, 0, self.get_width() as i32, self.get_height() as i32);\n\n let tex = self.background.take();\n\n let tex = tex.unwrap();\n\n self.draw_texture_sized(&tex, &size, &Color::new_3byte(255, 255, 255));\n\n self.background = Some(tex);\n", "file_path": "render_glutin/src/drawer.rs", "rank": 59, "score": 21.749664363695807 }, { "content": " );\n\n\n\n if dispmanx::resource_write_data(\n\n bg_resource,\n\n ImageType::RGB888,\n\n (3 * (target_width + padding)) as i32,\n\n bg_ptr,\n\n &dest_rect,\n\n ) {\n\n warn!(\"Failed to write data\")\n\n }\n\n\n\n let update = dispmanx::update_start(10);\n\n\n\n // Resize the element's src attr\n\n let src_rect = VCRect {\n\n x: 0,\n\n y: 0,\n\n width: (target_width as i32) << 16,\n\n height: (target_height as i32) << 16,\n", "file_path": "render_pi/src/drawer.rs", "rank": 60, "score": 20.673129416145514 }, { "content": " running: bool,\n\n}\n\n\n\nimpl GlutinInput {\n\n pub fn new() -> Self {\n\n GlutinInput {\n\n mouse_down: false,\n\n mouse_x: 0,\n\n mouse_y: 0,\n\n running: true,\n\n }\n\n }\n\n}\n\n\n\nimpl Input for GlutinInput {\n\n type Window = GlutinDrawer;\n\n\n\n fn run<T: FnMut(&Self, &mut Self::Window) -> (bool, Instant) + 'static>(\n\n mut self,\n\n mut drawer: Self::Window,\n", "file_path": "input_glutin/src/lib.rs", "rank": 61, "score": 19.63962931513437 }, { "content": " let height = texture.get_height();\n\n\n\n self.draw_texture_sized(\n\n texture,\n\n &Rect::new_from_pos(pos, width as i32, height as i32),\n\n color,\n\n )\n\n }\n\n\n\n /// Draws a texture to the screen, with the specified x/y coordinates (relative to screen size),\n\n /// and the texture dimensions as width/height.\n\n fn draw_texture(&mut self, texture: &Self::NativeTexture, pos: &Position) {\n\n // TODO: Potentially dedicated shader for non colored?\n\n self.draw_texture_colored(texture, pos, &Color::new_4byte(255, 255, 255, 255))\n\n }\n\n\n\n /// Draws a colored rectangle to the screen, with a single color.\n\n fn draw_colored_rect(&mut self, rect: &Rect, color: &Color) {\n\n let vertices: [f32; 12] = self.rect_to_vertices(&rect);\n\n let mut colors: [f32; 24] = [0.0; 24];\n", "file_path": "core/src/render/mod.rs", "rank": 62, "score": 19.08870366947535 }, { "content": " pub fn get(&mut self) -> Result<Weather, String> {\n\n for result in self.input.try_iter() {\n\n self.current = Some(result);\n\n }\n\n\n\n let data = self.current.clone();\n\n\n\n match data {\n\n Some(weather) => weather,\n\n None => Err(\"unavailable\".into()),\n\n }\n\n }\n\n\n\n /// Creates a new manager with a dedicated thread.\n\n /// update_frequency: milliseconds between updates\n\n pub fn new(\n\n update_frequency: u64,\n\n provider: WeatherProviderKind,\n\n config: Option<toml::Value>,\n\n ) -> Self {\n", "file_path": "weather/src/manager.rs", "rank": 63, "score": 18.917696633408767 }, { "content": " leaffront_core::brightness::set_brightness(val)\n\n }\n\n\n\n fn set_fullscreen(&mut self, fullscreen: bool) {\n\n self.gl_window.window().set_fullscreen(if fullscreen {\n\n Some(Fullscreen::Borderless(None))\n\n } else {\n\n None\n\n });\n\n self.gl_window.window().set_cursor_visible(!fullscreen)\n\n }\n\n\n\n fn get_transition_count(&self) -> usize {\n\n self.transition_count\n\n }\n\n\n\n fn start_clip(&self, rect: &Rect) {\n\n let min_x = rect.x;\n\n let min_y = rect.y;\n\n let max_x = rect.x + rect.width;\n", "file_path": "render_glutin/src/drawer.rs", "rank": 64, "score": 18.616902980279885 }, { "content": " pub fn new() -> Self {\n\n let events_loop = glutin::event_loop::EventLoop::new();\n\n let window = glutin::window::WindowBuilder::new()\n\n .with_title(\"Leaffront\")\n\n .with_inner_size(LogicalSize::new(1270.0, 720.0));\n\n let context = glutin::ContextBuilder::new()\n\n .with_gl(glutin::GlRequest::Latest)\n\n .with_gl_profile(glutin::GlProfile::Core)\n\n .with_vsync(true);\n\n let gl_window = context\n\n .build_windowed(window, &events_loop)\n\n .expect(\"Failed to create GL window\");\n\n\n\n let gl_window = unsafe {\n\n gl_window\n\n .make_current()\n\n .expect(\"Failed to set GL window as current\")\n\n };\n\n\n\n let (width, height): (u32, u32) = gl_window.window().inner_size().into();\n", "file_path": "render_glutin/src/drawer.rs", "rank": 65, "score": 18.556860190654795 }, { "content": " let min_y = rect.y;\n\n let max_x = rect.x + rect.width;\n\n let max_y = rect.y + rect.height;\n\n\n\n gl::scissor(\n\n min_x as _,\n\n self.get_height() as i32 - max_y as i32,\n\n (max_x - min_x) as _,\n\n (max_y - min_y) as _,\n\n );\n\n }\n\n\n\n fn end_clip(&self) {\n\n gl::disable(gl::GL_SCISSOR_TEST);\n\n }\n\n}\n\n\n\nimpl VersionInfo for PiDrawer {\n\n fn version() -> String {\n\n format!(\"opengles + dispmanx ({})\", env!(\"CARGO_PKG_VERSION\"))\n", "file_path": "render_pi/src/drawer.rs", "rank": 66, "score": 18.12024600388365 }, { "content": " let (width, _): (u32, u32) = self.gl_window.window().inner_size().into();\n\n\n\n width as usize\n\n }\n\n\n\n /// Returns the height of the screen.\n\n fn get_height(&self) -> usize {\n\n let (_, height): (u32, u32) = self.gl_window.window().inner_size().into();\n\n\n\n height as usize\n\n }\n\n\n\n /// Draws a texture to the screen, with a specified set of vertices to draw to, a UV\n\n /// to decode the image with, and a color to use as a base.\n\n fn draw_textured_vertices_colored_uv(\n\n &mut self,\n\n texture: &Self::NativeTexture,\n\n vertices: &[f32],\n\n colors: &[f32],\n\n uv: &[f32],\n", "file_path": "render_glutin/src/drawer.rs", "rank": 67, "score": 18.069515965543754 }, { "content": "extern crate leaffront_core;\n\n\n\nuse leaffront_core::backend::Backend;\n\nuse leaffront_core::backend::Notification;\n\nuse leaffront_core::version::VersionInfo;\n\n\n\npub struct NullBackend {}\n\n\n\nimpl NullBackend {\n\n pub fn new() -> Result<Self, ()> {\n\n Ok(Self {})\n\n }\n\n}\n\n\n\nimpl VersionInfo for NullBackend {\n\n fn version() -> String {\n\n format!(\"null ({})\", env!(\"CARGO_PKG_VERSION\"))\n\n }\n\n}\n\n\n\nimpl Backend for NullBackend {\n\n fn get_notification(&mut self) -> Option<Notification> {\n\n None\n\n }\n\n}\n", "file_path": "backend_null/src/lib.rs", "rank": 68, "score": 16.472003311214017 }, { "content": " }\n\n\n\n egui_ctx.begin_frame(raw_input);\n\n\n\n let screen_width = drawer.get_width();\n\n let screen_height = drawer.get_height();\n\n\n\n match &state {\n\n &ScreenState::Day(ref subtitle) => {\n\n let datetime = Local::now();\n\n\n\n egui::Window::new(\"Day Display\")\n\n .enabled(true)\n\n .resizable(false)\n\n .anchor(Align2::LEFT_BOTTOM, (10.0, -10.0))\n\n .auto_sized()\n\n .min_width(100.0)\n\n .min_height(70.0)\n\n .collapsible(false)\n\n .title_bar(false)\n", "file_path": "src/main_loop.rs", "rank": 69, "score": 16.372327107889124 }, { "content": "use leaffront_core::render::texture::Texture;\n\nuse leaffront_core::render::Dimensions;\n\n\n\nuse gl;\n\n\n\nuse image::RgbaImage;\n\nuse std::mem::MaybeUninit;\n\n\n\npub struct GlTexture {\n\n width: usize,\n\n height: usize,\n\n ptr: gl::types::GLuint,\n\n}\n\n\n\nimpl GlTexture {\n\n /// Converts a RGBA byte array to a OpenGL reference.\n\n fn from_bytes(bytes: &[u8], width: usize, height: usize) -> Self {\n\n let mut texture_ref = MaybeUninit::uninit();\n\n let texture;\n\n unsafe {\n", "file_path": "render_glutin/src/texture.rs", "rank": 70, "score": 16.050981317325892 }, { "content": " _ => {}\n\n }\n\n\n\n let bg_img = image.to_rgb8();\n\n\n\n // Resize the background to the correct size\n\n //let size = Context::get_resolution();\n\n\n\n // Pad out the image, if required\n\n let target_width;\n\n let target_height;\n\n let padding;\n\n\n\n let mut img_buffer = if bg_img.width() % 16 != 0 {\n\n // Find the next multiple that *is* even\n\n padding = 16 - (bg_img.width() % 16);\n\n target_width = bg_img.width();\n\n target_height = bg_img.height();\n\n\n\n let old_width = bg_img.width();\n", "file_path": "render_pi/src/drawer.rs", "rank": 71, "score": 15.702034613859528 }, { "content": " pub fn bind_texture(&self, target: gl::types::GLenum) {\n\n unsafe { gl::BindTexture(target, self.ptr) }\n\n }\n\n}\n\n\n\nimpl Dimensions for GlTexture {\n\n /// Returns the width of this texture.\n\n fn get_width(&self) -> usize {\n\n self.width\n\n }\n\n\n\n /// Returns the height of this texture.\n\n fn get_height(&self) -> usize {\n\n self.height\n\n }\n\n}\n\n\n\nimpl Drop for GlTexture {\n\n fn drop(&mut self) {\n\n unsafe {\n\n gl::DeleteTextures(1, [self.ptr].as_ptr());\n\n }\n\n }\n\n}\n", "file_path": "render_glutin/src/texture.rs", "rank": 72, "score": 15.409989792080246 }, { "content": " attr_textured_uv,\n\n bg: None,\n\n transitions: 0,\n\n }\n\n }\n\n}\n\n\n\nimpl Drawer for PiDrawer {\n\n type NativeTexture = GlTexture;\n\n\n\n fn start(&mut self) {\n\n self.transitions = 0;\n\n self.size = Context::get_resolution();\n\n self.state = DrawState::None;\n\n }\n\n\n\n /// Ends this frame.\n\n fn end(&mut self) {\n\n self.configure_state(DrawState::None);\n\n\n", "file_path": "render_pi/src/drawer.rs", "rank": 73, "score": 15.347998867665453 }, { "content": " /// Returns the width of the framebuffer.\n\n fn get_width(&self) -> usize;\n\n\n\n /// Returns the height of the framebuffer.\n\n fn get_height(&self) -> usize;\n\n\n\n /// Uses the specified image as a background. This is provided as several platforms\n\n /// have ways to accelerate this beyond OpenGL calls.\n\n fn set_background(&mut self, image: DynamicImage);\n\n\n\n /// Sets the screen brightness, if possible. Ignore call if not.\n\n fn set_brightness(&mut self, brightness: u8) -> ::std::io::Result<()>;\n\n\n\n /// Configures the full screen state of the window if possible.\n\n fn set_fullscreen(&mut self, fullscreen: bool);\n\n\n\n /// Draws a texture to the screen, with a specified set of vertices to draw to, a UV\n\n /// to decode the image with, and a color to use as a base.\n\n fn draw_textured_vertices_colored_uv(\n\n &mut self,\n", "file_path": "core/src/render/mod.rs", "rank": 74, "score": 15.345958914660326 }, { "content": "\n\nimpl Input for PiInput {\n\n type Window = PiDrawer;\n\n\n\n fn run<T: FnMut(&Self, &mut Self::Window) -> (bool, Instant) + 'static>(\n\n mut self,\n\n mut drawer: Self::Window,\n\n mut function: T,\n\n ) -> ! {\n\n loop {\n\n let (do_continue, wait_for) = function(&mut self, &mut drawer);\n\n if !do_continue {\n\n break;\n\n }\n\n\n\n self.mouse_down = false;\n\n\n\n loop {\n\n let now = Instant::now();\n\n let duration = if now >= wait_for {\n", "file_path": "input_pi/src/lib.rs", "rank": 75, "score": 15.3000322090402 }, { "content": " };\n\n\n\n dispmanx::element_change_attributes(\n\n update,\n\n element,\n\n (1 << 3) | (1 << 2),\n\n 0, // Ignored\n\n 255, // Ignored\n\n &src_rect, //&dest_rect,\n\n &dest_rect, //&src_rect,\n\n 0, // Ignored\n\n Transform::NO_ROTATE, // Ignored\n\n );\n\n\n\n if dispmanx::element_change_source(update, element, bg_resource) {\n\n warn!(\"Resource change failed!\");\n\n }\n\n\n\n if dispmanx::update_submit_sync(update) {\n\n warn!(\"Failed to update\");\n", "file_path": "render_pi/src/drawer.rs", "rank": 76, "score": 15.17720805045948 }, { "content": "/// Manages an interface for drawing different kinds of images.\n\nuse opengles::glesv2 as gl;\n\n\n\nuse image::DynamicImage;\n\n\n\nuse videocore::dispmanx;\n\nuse videocore::dispmanx::ResourceHandle;\n\nuse videocore::dispmanx::Transform;\n\nuse videocore::image::ImageType;\n\nuse videocore::image::Rect as VCRect;\n\n\n\nuse libc::c_void;\n\n\n\nuse videocore::bcm_host::GraphicsDisplaySize;\n\n\n\nuse gl_context::Context;\n\n\n\nuse brightness::set_brightness;\n\n\n\nuse shader::GLSLShader;\n\nuse texture::GlTexture;\n\nuse vbo::GLVBO;\n\n\n\nuse leaffront_core::pos::Rect;\n\nuse leaffront_core::render::texture::Texture;\n\nuse leaffront_core::render::Drawer;\n\nuse leaffront_core::version::VersionInfo;\n\n\n\n#[derive(Ord, PartialOrd, Eq, PartialEq)]\n", "file_path": "render_pi/src/drawer.rs", "rank": 77, "score": 15.145897072588026 }, { "content": "/// Handles OpenGLES textures, and provides mechanisms for interacting/drawing on them\n\n/// safely.\n\nuse render::color::Color;\n\n\n\npub struct Texture {\n\n pub tex_data: Vec<u8>,\n\n width: usize,\n\n height: usize,\n\n}\n\n\n\nimpl Texture {\n\n pub fn draw_pixel(&mut self, color: &Color, x: usize, y: usize) {\n\n let starting_pos = (y * self.width + x) * 4;\n\n\n\n self.tex_data[starting_pos] = color.r;\n\n self.tex_data[starting_pos + 1] = color.g;\n\n self.tex_data[starting_pos + 2] = color.b;\n\n self.tex_data[starting_pos + 3] = color.a;\n\n }\n\n\n", "file_path": "core/src/render/texture.rs", "rank": 78, "score": 14.861412374221889 }, { "content": "/// Represents different states that the display can be in\n\nuse leaffront_core::backend::Notification;\n\n\n\nuse std::time::Instant;\n\n\n\npub enum ScreenState {\n\n Day(Message),\n\n Night,\n\n}\n\n\n\npub enum Message {\n\n Date,\n\n Weather,\n\n}\n\n\n\nimpl Message {\n\n pub fn next(&self) -> Self {\n\n match self {\n\n &Message::Date => Message::Weather,\n\n &Message::Weather => Message::Date,\n", "file_path": "src/state.rs", "rank": 79, "score": 14.74109667961474 }, { "content": " .resizable(false)\n\n .anchor(Align2::CENTER_CENTER, (night_x, night_y))\n\n .auto_sized()\n\n .min_width(100.0)\n\n .min_height(70.0)\n\n .collapsible(false)\n\n .title_bar(false)\n\n .frame(Frame::none())\n\n .show(&egui_ctx, |ui| {\n\n // Render out both the top and bottom strings, and center them.\n\n let datetime = Local::now();\n\n let top_msg = datetime.format(\"%-I:%M:%S %P\").to_string();\n\n\n\n let suffix = match datetime.day() {\n\n 1 | 21 | 31 => \"st\",\n\n 2 | 22 => \"nd\",\n\n 3 | 23 => \"rd\",\n\n _ => \"th\",\n\n };\n\n\n", "file_path": "src/main_loop.rs", "rank": 80, "score": 14.527221877801585 }, { "content": " for ClippedPrimitive {\n\n clip_rect,\n\n primitive,\n\n } in shapes\n\n {\n\n // Translate the vertexes into points we can use\n\n let mut positions = Vec::with_capacity(16);\n\n let mut colors = Vec::with_capacity(24);\n\n let mut uv = Vec::with_capacity(16);\n\n\n\n let mesh = match primitive {\n\n Primitive::Mesh(mesh) => mesh,\n\n _ => continue,\n\n };\n\n\n\n for index in mesh.indices {\n\n let vertex = &mesh.vertices[index as usize];\n\n positions.push(vertex.pos.x / drawer.get_width() as f32 * 2.0 - 1.0);\n\n positions.push((vertex.pos.y / drawer.get_height() as f32 * 2.0 - 1.0) * -1.0);\n\n\n", "file_path": "src/main_loop.rs", "rank": 81, "score": 14.199457091703106 }, { "content": " self.draw_textured_vertices_colored_uv(\n\n texture,\n\n vertices,\n\n colors,\n\n &[0.0, 0.0, 0.0, 1.0, 1.0, 1.0, 0.0, 0.0, 1.0, 0.0, 1.0, 1.0],\n\n )\n\n }\n\n\n\n /// Draws a texture to the screen, with a specified set of vertices to draw to, and a\n\n /// default UV.\n\n fn draw_textured_vertices(&mut self, texture: &Self::NativeTexture, vertices: &[f32]) {\n\n self.draw_textured_vertices_colored(texture, vertices, &[1.0; 24])\n\n }\n\n\n\n /// Draws a texture to the screen, with the specified x/y coordinates (relative to screen size),\n\n /// and a specified width/height.\n\n fn draw_texture_sized(&mut self, texture: &Self::NativeTexture, rect: &Rect, color: &Color) {\n\n let vertices = self.rect_to_vertices(rect);\n\n\n\n let mut colors: [f32; 24] = [0.0; 24];\n", "file_path": "core/src/render/mod.rs", "rank": 82, "score": 14.052767781415412 }, { "content": " /// Returns the width of this texture.\n\n fn get_width(&self) -> usize {\n\n self.width\n\n }\n\n\n\n /// Returns the height of this texture.\n\n fn get_height(&self) -> usize {\n\n self.height\n\n }\n\n}\n\n\n\nimpl Drop for GlTexture {\n\n fn drop(&mut self) {\n\n gl::delete_textures(&[self.ptr]);\n\n }\n\n}\n", "file_path": "render_pi/src/texture.rs", "rank": 83, "score": 13.885036648109919 }, { "content": " gl::enable(gl::GL_SCISSOR_TEST);\n\n gl::enable(gl::GL_BLEND);\n\n gl::blend_func(gl::GL_ONE, gl::GL_ONE_MINUS_SRC_ALPHA);\n\n }\n\n\n\n fn convert_native_texture(&mut self, texture: Texture) -> Self::NativeTexture {\n\n GlTexture::from_texture(&texture)\n\n }\n\n\n\n /// Returns the width of the screen.\n\n fn get_width(&self) -> usize {\n\n return self.size.width as usize;\n\n }\n\n\n\n /// Returns the height of the screen.\n\n fn get_height(&self) -> usize {\n\n return self.size.height as usize;\n\n }\n\n\n\n /// Draws a texture to the screen, with a specified set of vertices to draw to, a UV\n", "file_path": "render_pi/src/drawer.rs", "rank": 84, "score": 13.877589890697225 }, { "content": " let max_y = rect.y + rect.height;\n\n\n\n unsafe {\n\n gl::Scissor(\n\n min_x as _,\n\n self.get_height() as i32 - max_y as i32,\n\n (max_x - min_x) as _,\n\n (max_y - min_y) as _,\n\n )\n\n }\n\n }\n\n\n\n fn end_clip(&self) {\n\n unsafe {\n\n gl::Disable(gl::SCISSOR_TEST);\n\n }\n\n }\n\n}\n\n\n\nimpl VersionInfo for GlutinDrawer {\n", "file_path": "render_glutin/src/drawer.rs", "rank": 85, "score": 13.682110183522965 }, { "content": " pub fn new_from_logical_space(\n\n x: f32,\n\n y: f32,\n\n width: f32,\n\n height: f32,\n\n screen_dims: &(usize, usize),\n\n ) -> Self {\n\n Rect {\n\n x: (x * (screen_dims.0 as f32)) as _,\n\n y: (y * (screen_dims.1 as f32)) as _,\n\n width: (width * (screen_dims.0 as f32)) as _,\n\n height: (height * (screen_dims.1 as f32)) as _,\n\n }\n\n }\n\n}\n", "file_path": "core/src/pos.rs", "rank": 86, "score": 13.232957766999556 }, { "content": "/// A holder for a OpenGL texture\n\nuse opengles::glesv2 as gl;\n\n\n\nuse leaffront_core::render::texture::Texture;\n\nuse leaffront_core::render::Dimensions;\n\n\n\nuse image::RgbaImage;\n\n\n\npub struct GlTexture {\n\n width: usize,\n\n height: usize,\n\n ptr: gl::GLuint,\n\n}\n\n\n\nimpl GlTexture {\n\n /// Converts a RGBA byte array to a OpenGL reference.\n\n fn from_bytes(bytes: &[u8], width: usize, height: usize) -> Self {\n\n let texture_ref: gl::GLuint = gl::gen_textures(1)[0];\n\n gl::bind_texture(gl::GL_TEXTURE_2D, texture_ref);\n\n gl::tex_image_2d(\n", "file_path": "render_pi/src/texture.rs", "rank": 87, "score": 12.865584976929586 }, { "content": " self.attr_textured_color as gl::GLuint,\n\n 4,\n\n gl::GL_FLOAT,\n\n false,\n\n 0,\n\n 0,\n\n );\n\n }\n\n }\n\n\n\n self.state = target;\n\n }\n\n }\n\n\n\n /// Creates a new drawer.\n\n pub fn new() -> Self {\n\n let context = Context::build().unwrap();\n\n\n\n let size = Context::get_resolution();\n\n\n", "file_path": "render_pi/src/drawer.rs", "rank": 88, "score": 12.816924987710584 }, { "content": " pub fn get_width(&self) -> usize {\n\n self.width\n\n }\n\n\n\n pub fn get_height(&self) -> usize {\n\n self.height\n\n }\n\n\n\n /// Creates a new Texture for drawing. This is only uploaded on demand.\n\n pub fn new(width: usize, height: usize) -> Self {\n\n Texture {\n\n tex_data: vec![0; width * height * 4],\n\n width,\n\n height,\n\n }\n\n }\n\n}\n", "file_path": "core/src/render/texture.rs", "rank": 89, "score": 12.653214980908647 }, { "content": " /// Updates input\n\n fn update(&mut self) -> bool {\n\n let mut input = Vec::new();\n\n\n\n // Rust's retain doesn't allow for mutable access, so do this manually\n\n let mut i = 0;\n\n while i < self.devices.len() {\n\n let device = &mut self.devices[i];\n\n\n\n // Grab the devices name, then read events from it\n\n match device.name().map(|x| x.to_owned()) {\n\n Some(device_name) => match device.fetch_events() {\n\n Ok(events) => {\n\n for evt in events {\n\n input.push(evt);\n\n }\n\n i += 1;\n\n continue;\n\n }\n\n Err(e) => {\n", "file_path": "input_pi/src/lib.rs", "rank": 90, "score": 12.633381826736201 }, { "content": " timezone: Option<u64>,\n\n #[serde(default)]\n\n id: Option<u64>,\n\n #[serde(default)]\n\n name: Option<String>,\n\n #[serde(default)]\n\n cod: Option<u64>,\n\n}\n\n\n\npub struct OpenWeatherMap;\n\n\n\nimpl OpenWeatherMap {}\n\n\n\nimpl WeatherProvider for OpenWeatherMap {\n\n fn get_weather(config: Option<toml::Value>) -> Result<Weather, String> {\n\n // We require a config for OpenWeatherMap:\n\n let config = config.ok_or_else(|| \"OpenWeatherMap configuration needed\".to_string())?;\n\n\n\n // Parse into a configuration type\n\n let config: OpenWeatherMapConfig = config\n", "file_path": "weather/src/openweathermap.rs", "rank": 91, "score": 12.587846729426058 }, { "content": "\n\n unsafe {\n\n gl::load_with(|symbol| gl_window.get_proc_address(symbol) as *const _);\n\n\n\n gl::DebugMessageCallback(Some(gl_debug_message), ptr::null_mut());\n\n\n\n gl::ClearColor(0.0, 1.0, 0.0, 1.0);\n\n gl::Viewport(0, 0, width as i32, height as i32);\n\n }\n\n\n\n let vertex_vbo = GLVBO::new();\n\n let color_vbo = GLVBO::new();\n\n let uv_vbo = GLVBO::new();\n\n\n\n unsafe {\n\n let mut ptr = MaybeUninit::uninit();\n\n gl::GenVertexArrays(1, ptr.as_mut_ptr());\n\n gl::BindVertexArray(ptr.assume_init());\n\n }\n\n\n", "file_path": "render_glutin/src/drawer.rs", "rank": 92, "score": 12.522938676417407 }, { "content": " };\n\n\n\n let brightness = match state {\n\n ScreenState::Day(_) => config.day.brightness,\n\n ScreenState::Night => config.night.brightness,\n\n };\n\n match drawer.set_brightness(brightness) {\n\n Err(v) => warn!(\"Failed to set brightness: {:?}\", v),\n\n _ => {}\n\n }\n\n\n\n let mut state_countdown = Instant::now();\n\n\n\n //let font_data = include_bytes!(\"../res/Lato-Regular.ttf\");\n\n\n\n let mut weather_manager = WeatherManager::new(\n\n config.weather.update_freq * 60 * 1000,\n\n config.weather.kind,\n\n config.weather.config.clone(),\n\n );\n", "file_path": "src/main_loop.rs", "rank": 93, "score": 12.4354437847466 }, { "content": " }\n\n WindowEvent::CursorMoved { position, .. } => {\n\n let (x, y): (i32, i32) = position.into();\n\n self.mouse_x = x as usize;\n\n self.mouse_y = y as usize;\n\n }\n\n WindowEvent::Resized(physical_size) => drawer.gl_window.resize(physical_size),\n\n _ => (),\n\n },\n\n Event::RedrawRequested(_) => {\n\n let (result, wait_till) = function(&self, &mut drawer);\n\n next_time = wait_till;\n\n if !result {\n\n *control_flow = ControlFlow::Exit;\n\n } else {\n\n *control_flow = ControlFlow::WaitUntil(next_time.clone());\n\n }\n\n }\n\n _ => (),\n\n }\n", "file_path": "input_glutin/src/lib.rs", "rank": 94, "score": 12.246660940847676 }, { "content": " }\n\n }\n\n}\n\n\n\npub struct DisplayNotification {\n\n pub source: Notification,\n\n pub displayed: Instant,\n\n}\n\n\n\nimpl DisplayNotification {\n\n pub fn new(notify: Notification) -> Self {\n\n DisplayNotification {\n\n source: notify,\n\n displayed: Instant::now(),\n\n }\n\n }\n\n}\n", "file_path": "src/state.rs", "rank": 95, "score": 11.758665083283105 }, { "content": "#[cfg(feature = \"raspberry_pi\")]\n\npub use leaffront_input_pi::PiInput as InputImpl;\n\n#[cfg(feature = \"raspberry_pi\")]\n\npub use leaffront_render_pi::drawer::PiDrawer as DrawerImpl;\n\n\n\n#[cfg(feature = \"glutin\")]\n\npub use leaffront_input_glutin::GlutinInput as InputImpl;\n\n#[cfg(feature = \"glutin\")]\n\npub use leaffront_render_glutin::drawer::GlutinDrawer as DrawerImpl;\n\n\n\n#[cfg(feature = \"null_backend\")]\n\npub use leaffront_backend_null::NullBackend as BackendImpl;\n\n#[cfg(feature = \"redis_backend\")]\n\npub use leaffront_backend_redis::RedisBackend as BackendImpl;\n", "file_path": "src/platform.rs", "rank": 96, "score": 11.755303088000517 }, { "content": "/// Holds and parses GLSL shaders.\n\nuse gl;\n\nuse gl::types::GLint;\n\n\n\nuse std::ptr;\n\n\n\nuse std::ffi::CString;\n\n\n\npub struct GLSLShader {\n\n program: gl::types::GLuint,\n\n vertex: gl::types::GLuint,\n\n fragment: gl::types::GLuint,\n\n}\n\n\n\nimpl GLSLShader {\n\n /// Enables this program to be used.\n\n /// Shader MUST remain in scope for duration of usage.\n\n pub fn use_program(&self) {\n\n unsafe { gl::UseProgram(self.program) }\n\n }\n", "file_path": "render_glutin/src/shader.rs", "rank": 97, "score": 11.741330948055372 }, { "content": " // For gap:\n\n let min_y = 200.0;\n\n let max_y = screen_height as f32 - 200.0;\n\n\n\n night_x = rng.gen_range(min_x..max_x) - screen_width as f32 / 2.0;\n\n night_y = rng.gen_range(min_y..max_y) - screen_height as f32 / 2.0;\n\n }\n\n }\n\n }\n\n\n\n // Draw notifications\n\n for (i, notification) in notifications.iter().enumerate() {\n\n egui::Window::new(format!(\"Night Display {}\", i))\n\n .enabled(true)\n\n .resizable(false)\n\n .anchor(Align2::RIGHT_TOP, (-10.0, 50.0 + (i as f32 * 120.0)))\n\n .auto_sized()\n\n .collapsible(false)\n\n .title_bar(false)\n\n .show(&egui_ctx, |ui| {\n", "file_path": "src/main_loop.rs", "rank": 98, "score": 11.717679706430138 }, { "content": "\n\n if Instant::now() >= next_time {\n\n drawer.gl_window.window().request_redraw();\n\n }\n\n })\n\n }\n\n\n\n /// Checks to see if the mouse/pointer is down\n\n fn is_mouse_down(&self) -> bool {\n\n self.mouse_down\n\n }\n\n\n\n fn get_mouse_pos(&self) -> (usize, usize) {\n\n (self.mouse_x, self.mouse_y)\n\n }\n\n\n\n fn do_continue(&self) -> bool {\n\n self.running\n\n }\n\n}\n\n\n\nimpl VersionInfo for GlutinInput {\n\n fn version() -> String {\n\n format!(\"glutin ({})\", env!(\"CARGO_PKG_VERSION\"))\n\n }\n\n}\n", "file_path": "input_glutin/src/lib.rs", "rank": 99, "score": 11.692652528927873 } ]
Rust
src/modules/import_export.rs
lilith645/Maat-Editor3D
bbde60db0555e05bfed2be313d886fa0a3386b35
use csv; use crate::modules::WorldObject; use crate::modules::scenes::GameOptions; use crate::modules::Logs; use crate::cgmath::Vector3; use std::fs::File; use std::fs; pub fn get_models(logs: &mut Logs) -> Vec<(String, String, bool)> { if let Err(e) = fs::create_dir_all("./Models") { logs.add_error(e.to_string()); } let paths = fs::read_dir("./Models/").unwrap(); let mut models = Vec::new(); for path in paths { models.push(path.unwrap().path().display().to_string()); } let mut known_models = Vec::new(); for i in 0..models.len() { let mut location = models[i].to_string(); let mut name = "".to_string(); let b = location.pop(); let l = location.pop(); let g = location.pop(); let full_stop = location.pop(); if full_stop.unwrap() == '.' && g.unwrap() == 'g' && l.unwrap() == 'l' && b.unwrap() == 'b' { loop { let letter = location.pop(); if let Some(letter) = letter { name.push_str(&letter.to_string()); if letter == '/' { name.pop(); name = name.chars().rev().collect::<String>(); break; } } else { break; } } known_models.push((name, models[i].to_string(), false)); } } known_models } pub fn export(scene_name: String, world_objects: &Vec<WorldObject>, camera_details: &GameOptions, logs: &mut Logs) { if let Err(e) = fs::create_dir_all("./Scenes/".to_owned() + &scene_name) { logs.add_error(e.to_string()); } match csv::Writer::from_path("./Scenes/".to_owned() + &scene_name + "/" + &scene_name + ".csv") { Ok(mut file) => { file.write_record(&["id", "name", "model", "location", "instanced", "x", "y", "z", "rot_x", "rot_y", "rot_z", "size_x", "size_y", "size_z"]).unwrap(); for object in world_objects { let id = object.id().to_string(); let name = object.name().to_string(); let model = object.model(); let location = object.location(); let instanced = object.instanced_rendered().to_string(); let x = object.position().x.to_string(); let y = object.position().y.to_string(); let z = object.position().z.to_string(); let rot_x = object.rotation().x.to_string(); let rot_y = object.rotation().y.to_string(); let rot_z = object.rotation().z.to_string(); let size_x = object.size().x.to_string(); let size_y = object.size().y.to_string(); let size_z = object.size().z.to_string(); if let Err(e) = file.write_record(&[id, name, model, location, instanced, x, y, z, rot_x, rot_y, rot_z, size_x, size_y, size_z]) { logs.add_error(e.to_string()); } } file.flush().unwrap(); }, Err(e) => { logs.add_error(e.to_string()); } } match csv::Writer::from_path("./Scenes/".to_owned() + &scene_name + "/camera.csv") { Ok(mut file) => { file.write_record(&["type", "target_id", "distance", "x", "y", "z"]).unwrap(); let camera_type = camera_details.camera_type.to_string(); let target_id = camera_details.camera_target.to_string(); let distance = camera_details.camera_distance.to_string(); let x = camera_details.camera_location.x.to_string(); let y = camera_details.camera_location.y.to_string(); let z = camera_details.camera_location.z.to_string(); file.write_record(&[camera_type, target_id, distance, x, y, z]).unwrap(); file.flush().unwrap(); }, Err(e) => { logs.add_error(e.to_string()); } } } pub fn import(scene_name: String, logs: &mut Logs) -> (Vec<(String, String)>, Vec<WorldObject>, GameOptions) { let mut world_objects = Vec::new(); let mut used_models: Vec<(String, String)> = Vec::new(); let mut game_options = GameOptions::new(); match File::open("./Scenes/".to_owned() + &scene_name + "/" + &scene_name + ".csv") { Ok(file) => { let mut reader = csv::Reader::from_reader(file); for whole_object in reader.records() { match whole_object { Ok(object) => { let id: u32 = object[0].parse().unwrap(); let name: String = object[1].parse().unwrap(); let model: String = object[2].parse().unwrap(); let location: String = object[3].parse().unwrap(); let instanced: bool = object[4].parse().unwrap(); let x: f32 = object[5].parse().unwrap(); let y: f32 = object[6].parse().unwrap(); let z: f32 = object[7].parse().unwrap(); let rot_x: f32 = object[8].parse().unwrap(); let rot_y: f32 = object[9].parse().unwrap(); let rot_z: f32 = object[10].parse().unwrap(); let size_x: f32 = object[11].parse().unwrap(); let size_y: f32 = object[12].parse().unwrap(); let size_z: f32 = object[13].parse().unwrap(); let mut unique = true; for i in 0..used_models.len() { if used_models[i].0 == model { unique = false; break; } } if unique { used_models.push((model.to_string(), location.to_string())); } world_objects.push(WorldObject::new_with_data(id, name, scene_name.to_string(), model, location, Vector3::new(x, y, z), Vector3::new(rot_x, rot_y, rot_z), Vector3::new(size_x, size_y, size_z), instanced)); }, Err(e) => { logs.add_error("Scene details data:".to_owned() + &e.to_string()); } } } }, Err(e) => { logs.add_error("Scene details: ".to_owned() + &e.to_string()); }, } match File::open("./Scenes/".to_owned() + &scene_name + "/camera.csv") { Ok(file) => { let mut reader = csv::Reader::from_reader(file); for whole_object in reader.records() { match whole_object { Ok(object) => { let camera_type: i32 = object[0].parse().unwrap(); let target_id: i32 = object[1].parse().unwrap(); let distance: f32 = object[2].parse().unwrap(); let x: f32 = object[3].parse().unwrap(); let y: f32 = object[4].parse().unwrap(); let z: f32 = object[5].parse().unwrap(); game_options.camera_type = camera_type; game_options.camera_target = target_id; game_options.camera_distance = distance; game_options.camera_location = Vector3::new(x,y,z); }, Err(e) => { logs.add_error(e.to_string()); } } } }, Err(e) => { logs.add_error("Camera: ".to_owned() + &e.to_string()); } } (used_models, world_objects, game_options) }
use csv; use crate::modules::WorldObject; use crate::modules::scenes::GameOptions; use crate::modules::Logs; use crate::cgmath::Vector3; use std::fs::File; use std::fs; pub fn get_models(logs: &mut Logs) -> Vec<(String, String, bool)> { if let Err(e) = fs::create_dir_all("./Models") { logs.add_error(e.to_string()); } let paths = fs::read_dir("./Models/").unwrap(); let mut models = Vec::new(); for path in paths { models.push(path.unwrap().path().display().to_string()); } let mut known_models = Vec::new(); for i in 0..models.len() { let mut location = models[i].to_string(); let mut name = "".to_string(); let b = location.pop(); let l = location.pop(); let g = location.pop(); let full_stop = location.pop(); if full_stop.unwrap() == '.' && g.unwrap() == 'g' && l.unwrap() == 'l' && b.unwrap() == 'b' { loop { let letter = location.pop(); if let Some(letter) = letter { name.push_str(&letter.to_string()); if letter == '/' { name.pop(); name = name.char
rot_x", "rot_y", "rot_z", "size_x", "size_y", "size_z"]).unwrap(); for object in world_objects { let id = object.id().to_string(); let name = object.name().to_string(); let model = object.model(); let location = object.location(); let instanced = object.instanced_rendered().to_string(); let x = object.position().x.to_string(); let y = object.position().y.to_string(); let z = object.position().z.to_string(); let rot_x = object.rotation().x.to_string(); let rot_y = object.rotation().y.to_string(); let rot_z = object.rotation().z.to_string(); let size_x = object.size().x.to_string(); let size_y = object.size().y.to_string(); let size_z = object.size().z.to_string(); if let Err(e) = file.write_record(&[id, name, model, location, instanced, x, y, z, rot_x, rot_y, rot_z, size_x, size_y, size_z]) { logs.add_error(e.to_string()); } } file.flush().unwrap(); }, Err(e) => { logs.add_error(e.to_string()); } } match csv::Writer::from_path("./Scenes/".to_owned() + &scene_name + "/camera.csv") { Ok(mut file) => { file.write_record(&["type", "target_id", "distance", "x", "y", "z"]).unwrap(); let camera_type = camera_details.camera_type.to_string(); let target_id = camera_details.camera_target.to_string(); let distance = camera_details.camera_distance.to_string(); let x = camera_details.camera_location.x.to_string(); let y = camera_details.camera_location.y.to_string(); let z = camera_details.camera_location.z.to_string(); file.write_record(&[camera_type, target_id, distance, x, y, z]).unwrap(); file.flush().unwrap(); }, Err(e) => { logs.add_error(e.to_string()); } } } pub fn import(scene_name: String, logs: &mut Logs) -> (Vec<(String, String)>, Vec<WorldObject>, GameOptions) { let mut world_objects = Vec::new(); let mut used_models: Vec<(String, String)> = Vec::new(); let mut game_options = GameOptions::new(); match File::open("./Scenes/".to_owned() + &scene_name + "/" + &scene_name + ".csv") { Ok(file) => { let mut reader = csv::Reader::from_reader(file); for whole_object in reader.records() { match whole_object { Ok(object) => { let id: u32 = object[0].parse().unwrap(); let name: String = object[1].parse().unwrap(); let model: String = object[2].parse().unwrap(); let location: String = object[3].parse().unwrap(); let instanced: bool = object[4].parse().unwrap(); let x: f32 = object[5].parse().unwrap(); let y: f32 = object[6].parse().unwrap(); let z: f32 = object[7].parse().unwrap(); let rot_x: f32 = object[8].parse().unwrap(); let rot_y: f32 = object[9].parse().unwrap(); let rot_z: f32 = object[10].parse().unwrap(); let size_x: f32 = object[11].parse().unwrap(); let size_y: f32 = object[12].parse().unwrap(); let size_z: f32 = object[13].parse().unwrap(); let mut unique = true; for i in 0..used_models.len() { if used_models[i].0 == model { unique = false; break; } } if unique { used_models.push((model.to_string(), location.to_string())); } world_objects.push(WorldObject::new_with_data(id, name, scene_name.to_string(), model, location, Vector3::new(x, y, z), Vector3::new(rot_x, rot_y, rot_z), Vector3::new(size_x, size_y, size_z), instanced)); }, Err(e) => { logs.add_error("Scene details data:".to_owned() + &e.to_string()); } } } }, Err(e) => { logs.add_error("Scene details: ".to_owned() + &e.to_string()); }, } match File::open("./Scenes/".to_owned() + &scene_name + "/camera.csv") { Ok(file) => { let mut reader = csv::Reader::from_reader(file); for whole_object in reader.records() { match whole_object { Ok(object) => { let camera_type: i32 = object[0].parse().unwrap(); let target_id: i32 = object[1].parse().unwrap(); let distance: f32 = object[2].parse().unwrap(); let x: f32 = object[3].parse().unwrap(); let y: f32 = object[4].parse().unwrap(); let z: f32 = object[5].parse().unwrap(); game_options.camera_type = camera_type; game_options.camera_target = target_id; game_options.camera_distance = distance; game_options.camera_location = Vector3::new(x,y,z); }, Err(e) => { logs.add_error(e.to_string()); } } } }, Err(e) => { logs.add_error("Camera: ".to_owned() + &e.to_string()); } } (used_models, world_objects, game_options) }
s().rev().collect::<String>(); break; } } else { break; } } known_models.push((name, models[i].to_string(), false)); } } known_models } pub fn export(scene_name: String, world_objects: &Vec<WorldObject>, camera_details: &GameOptions, logs: &mut Logs) { if let Err(e) = fs::create_dir_all("./Scenes/".to_owned() + &scene_name) { logs.add_error(e.to_string()); } match csv::Writer::from_path("./Scenes/".to_owned() + &scene_name + "/" + &scene_name + ".csv") { Ok(mut file) => { file.write_record(&["id", "name", "model", "location", "instanced", "x", "y", "z", "
random
[ { "content": "fn benchmark(draw_calls: &mut Vec<DrawCall>, dimensions: Vector2<f32>) {\n\n draw_calls.push(DrawCall::draw_text_basic(Vector2::new(dimensions.x - 80.0, 15.0), \n\n Vector2::new(64.0, 64.0), \n\n Vector4::new(1.0, 1.0, 1.0, 1.0), \n\n \"v\".to_string() + &MAJOR.to_string() + \".\" + &MINOR.to_string() + \".\" + &PATCH.to_string(), \n\n \"Arial\".to_string()));\n\n}\n\n\n", "file_path": "src/main.rs", "rank": 3, "score": 47051.15304556144 }, { "content": "fn fps_overlay(draw_calls: &mut Vec<DrawCall>, dimensions: Vector2<f32>, fps: f64) {\n\n let mut fps = fps.to_string();\n\n fps.truncate(6);\n\n \n\n draw_calls.push(DrawCall::draw_text_basic(Vector2::new(32.0, dimensions.y-48.0), \n\n Vector2::new(64.0, 64.0), \n\n Vector4::new(0.0, 0.0, 0.0, 1.0), \n\n \"fps: \".to_string() + &fps, \n\n \"Arial\".to_string()));\n\n}\n\n\n", "file_path": "src/main.rs", "rank": 4, "score": 42337.201004463306 }, { "content": "fn main() {\n\n let mut lua = Lua::new();\n\n \n\n let mut imgui = ImGui::init();\n\n let mut graphics = CoreMaat::new(\"Maat Editor\".to_string(), (MAJOR) << 22 | (MINOR) << 12 | (PATCH), 1280.0, 1080.0, true).use_imgui(&mut imgui);\n\n \n\n graphics.preload_font(String::from(\"Arial\"),\n\n String::from(\"./resources/Fonts/TimesNewRoman.png\"),\n\n include_bytes!(\"../resources/Fonts/TimesNewRoman.fnt\"));\n\n graphics.preload_texture(String::from(\"Logo\"), \n\n String::from(\"./resources/Textures/Logo.png\"));\n\n \n\n graphics.add_model(String::from(\"Axis\"), String::from(\"./Models/Axis.glb\"));\n\n \n\n graphics.load_shaders();\n\n \n\n graphics.set_clear_colour(0.2, 0.2, 0.2, 1.0);\n\n \n\n let mut game: Box<Scene> = Box::new(LoadScreen::new());\n\n \n", "file_path": "src/main.rs", "rank": 5, "score": 35329.8398327582 }, { "content": "pub trait Scene {\n\n fn data(&self) -> &SceneData;\n\n fn mut_data(&mut self) -> &mut SceneData;\n\n fn future_scene(&mut self, window_size: Vector2<f32>) -> Box<Scene>;\n\n \n\n fn update(&mut self, ui: Option<&Ui>, lua: Option<&mut Lua>, delta_time: f32);\n\n fn draw(&self, draw_calls: &mut Vec<DrawCall>);\n\n \n\n fn scene_finished(&self) -> bool {\n\n self.data().next_scene\n\n }\n\n \n\n fn reset_scroll_value(&mut self) {\n\n self.mut_data().scroll_delta = 0.0;\n\n }\n\n \n\n fn get_models_to_load(&mut self) -> Vec<(String, String)> {\n\n let models = self.data().models_to_load.clone();\n\n self.mut_data().models_to_load = Vec::new();\n\n \n", "file_path": "src/modules/scenes/mod.rs", "rank": 6, "score": 33256.11559079597 }, { "content": " position: window_size*0.5,\n\n size: Vector2::new(400.0, 200.0),\n\n show: false,\n\n last_error: \"No Errors\".to_string(),\n\n error_log: f,\n\n }\n\n }\n\n \n\n pub fn is_shown(&self) -> bool {\n\n self.show\n\n }\n\n \n\n pub fn add_error(&mut self, err: String) {\n\n self.last_error = err.to_string();\n\n if let Err(_) = self.error_log.write(&(err.to_owned() + \"\\n\").as_bytes()) {\n\n println!(\"Writting logs failed\");\n\n }\n\n self.show = true;\n\n }\n\n \n", "file_path": "src/modules/logs.rs", "rank": 7, "score": 26230.046706406363 }, { "content": "use maat_graphics::imgui::*;\n\nuse std::fs::File;\n\nuse std::io::{BufWriter, Write};\n\n\n\nuse crate::cgmath::Vector2;\n\n\n\npub struct Logs {\n\n position: Vector2<f32>,\n\n size: Vector2<f32>,\n\n show: bool,\n\n last_error: String,\n\n error_log: BufWriter<File>,\n\n}\n\n\n\nimpl Logs {\n\n pub fn new(window_size: Vector2<f32>) -> Logs {\n\n let f = File::create(\"./log.ini\").expect(\"Error: Failed to create settings file\");\n\n let f = BufWriter::new(f);\n\n \n\n Logs {\n", "file_path": "src/modules/logs.rs", "rank": 8, "score": 26226.56732163569 }, { "content": " pub fn draw(&mut self, ui: Option<&Ui>) {\n\n if let Some(ui) = ui {\n\n ui.window(im_str!(\"Error\"))\n\n .size([self.size.x, self.size.y], Condition::Appearing)\n\n .position([self.position.x, self.position.y], Condition::Appearing)\n\n .build(|| {\n\n ui.text_wrapped(&ImString::new(\"Error: \".to_owned() + &self.last_error));\n\n if ui.button(im_str!(\"Ok\"), [0.0, 0.0]) {\n\n self.show = false;\n\n }\n\n });\n\n }\n\n }\n\n}\n\n\n", "file_path": "src/modules/logs.rs", "rank": 9, "score": 26219.825449269814 }, { "content": " \n\n object\n\n }\n\n \n\n pub fn _new(reference_num: u32, model: String, location: String, directory: String, position: Vector3<f32>, rotation: Vector3<f32>, size: Vector3<f32>) -> WorldObject {\n\n let object_name = model.to_owned() + &reference_num.to_string();\n\n \n\n WorldObject::new_with_name(reference_num, object_name.to_string(), directory, model, location, position, rotation, size)\n\n }\n\n \n\n pub fn create_script(&mut self, logs: &mut Logs) {\n\n if self.has_script {\n\n return;\n\n }\n\n \n\n let file_name = self.name.to_owned() + \".lua\";\n\n \n\n // Create lua file\n\n if let Err(e) = fs::create_dir_all(LOCATION.to_owned() + &self.directory.to_string() + &OBJECTS.to_string()) {\n\n logs.add_error(e.to_string());\n", "file_path": "src/modules/world_object.rs", "rank": 10, "score": 18.921886173161898 }, { "content": " \n\n let file_name = self.name.to_owned() + \".lua\";\n\n if let Err(e) = fs::remove_file(LOCATION.to_owned() + &self.directory.to_string() + &OBJECTS.to_string() + &file_name.to_string()) {\n\n logs.add_error(e.to_string());\n\n }\n\n self.has_script = false;\n\n self.update_function = None;\n\n }\n\n \n\n pub fn save_script(&mut self, directory: String, logs: &mut Logs) {\n\n if !self.has_script {\n\n return;\n\n }\n\n \n\n let file_name = self.name.to_owned() + \".lua\";\n\n \n\n // Create lua folder\n\n if let Err(e) = fs::create_dir_all(LOCATION.to_owned() + &directory.to_string() + &OBJECTS.to_string()) {\n\n logs.add_error(e.to_string());\n\n }\n", "file_path": "src/modules/world_object.rs", "rank": 12, "score": 17.555383283021136 }, { "content": " let location = self.known_models[i].1.clone();\n\n self.object_being_placed = Some(WorldObject::new_empty(id, model_name.to_string(), location, self.scene_name.to_string()));\n\n self.object_selected = 1;\n\n }\n\n }\n\n }\n\n }\n\n \n\n pub fn draw_imgui(&mut self, ui: Option<&Ui>) {\n\n if let Some(ui) = &ui {\n\n self.mut_data().imgui_info.wants_mouse = ui.want_capture_mouse();\n\n self.mut_data().imgui_info.wants_keyboard = ui.want_capture_keyboard();\n\n \n\n if self.windows.load_window {\n\n if let Err(e) = fs::create_dir_all(\"./Scenes\") {\n\n self.logs.add_error(e.to_string());\n\n }\n\n \n\n let paths = fs::read_dir(\"./Scenes/\").unwrap();\n\n \n", "file_path": "src/modules/scenes/editor_screen.rs", "rank": 13, "score": 16.914959303547768 }, { "content": " \n\n let file_from = LOCATION.to_owned() + &self.directory.to_string() + &OBJECTS.to_string() + &file_name.to_string();\n\n let file_to = LOCATION.to_owned() + &directory.to_string() + &OBJECTS.to_string() + &file_name.to_string();\n\n \n\n if file_from.eq(&file_to) {\n\n return;\n\n }\n\n \n\n if let Err(e) = copy(file_from, file_to) {\n\n logs.add_error(e.to_string());\n\n }\n\n }\n\n \n\n pub fn load_script(&mut self) {\n\n self.update_function = None;\n\n \n\n let file_name = self.name.to_owned() + \".lua\";\n\n if let Ok(f) = File::open(&Path::new(&(LOCATION.to_owned() + &self.directory.to_string() + &OBJECTS.to_string() + &file_name))) {\n\n self.update_function = Some(f);\n\n }\n", "file_path": "src/modules/world_object.rs", "rank": 14, "score": 16.887492444381476 }, { "content": " pub fn name(&self) -> String {\n\n self.name.to_string()\n\n }\n\n \n\n pub fn model(&self) -> String {\n\n self.model.to_string()\n\n }\n\n \n\n pub fn location(&self) -> String {\n\n self.location.to_string()\n\n }\n\n \n\n pub fn position(&self) -> Vector3<f32> {\n\n self.position\n\n }\n\n \n\n pub fn size(&self) -> Vector3<f32> {\n\n self.size\n\n }\n\n \n", "file_path": "src/modules/world_object.rs", "rank": 15, "score": 16.03075917785022 }, { "content": "\n\nimpl Clone for WorldObject {\n\n fn clone(&self) -> Self {\n\n let mut obj = WorldObject::new_with_name(self.reference_num, self.name.to_string(), self.directory.to_string(), self.model.to_string(), self.location.to_string(), self.position, self.rotation, self.size);\n\n if let Some(function) = &self.update_function {\n\n obj.update_function = Some(function.try_clone().unwrap());\n\n }\n\n \n\n obj\n\n }\n\n}\n\n\n\nimpl WorldObject {\n\n pub fn new_empty(reference_num: u32, model: String, location: String, scene_name: String) -> WorldObject {\n\n WorldObject {\n\n reference_num,\n\n model: model.to_string(),\n\n location,\n\n directory: scene_name.to_string(),\n\n name: model.to_owned() + &reference_num.to_string(),\n", "file_path": "src/modules/world_object.rs", "rank": 17, "score": 14.379741250112717 }, { "content": " \n\n position_edit: false,\n\n size_edit: false,\n\n rotation_edit: false,\n\n has_script,\n\n update_function: function,\n\n default_options: DefaultOptions::new(position, size, rotation),\n\n \n\n instanced_buffer: false,\n\n };\n\n \n\n object\n\n }\n\n \n\n pub fn new_with_data(reference_num: u32, object_name: String, directory: String, model: String, location: String, position: Vector3<f32>, rotation: Vector3<f32>, size: Vector3<f32>, instanced: bool) -> WorldObject {\n\n let mut object = WorldObject::new_with_name(reference_num, object_name, directory.to_string(), model, location,\n\n position,\n\n rotation,\n\n size);\n\n object.instanced_buffer = instanced;\n", "file_path": "src/modules/world_object.rs", "rank": 19, "score": 13.525725068425736 }, { "content": " let function = None;\n\n \n\n let file_name = object_name.to_owned() + \".lua\";\n\n let mut has_script = false;\n\n if let Ok(_) = File::open(&Path::new(&(LOCATION.to_owned() + &directory.to_string() + &OBJECTS.to_string() + &file_name))) {\n\n has_script = true;\n\n }\n\n \n\n let object = WorldObject {\n\n reference_num,\n\n model,\n\n name: object_name,\n\n location,\n\n directory,\n\n \n\n position,\n\n rotation,\n\n size,\n\n velocity: Vector3::new(0.0, 0.0, 0.0),\n\n acceleration: Vector3::new(0.0, 0.0, 0.0),\n", "file_path": "src/modules/world_object.rs", "rank": 20, "score": 13.45674965947251 }, { "content": " if self.load_scene_option as usize+1 > scenes.len() {\n\n self.windows.load_window = false;\n\n return;\n\n }\n\n \n\n let mut path = scenes[self.load_scene_option as usize].to_str().to_string();\n\n path.remove(0);\n\n path.remove(0);\n\n path.remove(0);\n\n path.remove(0);\n\n path.remove(0);\n\n path.remove(0);\n\n path.remove(0);\n\n path.remove(0);\n\n path.remove(0);\n\n let (load_models, objects, game_options) = import(path.to_string(), &mut self.logs);\n\n for object in &objects {\n\n if object.instanced_rendered() {\n\n if !self.instanced_buffers_added.contains(&object.model().to_string()) {\n\n self.instanced_buffers_added.push(object.model().to_string());\n", "file_path": "src/modules/scenes/editor_screen.rs", "rank": 22, "score": 12.70377301688605 }, { "content": " }\n\n \n\n pub fn instanced_buffer_removed(&mut self, reference: String) {\n\n if self.model.to_string() == reference {\n\n self.instanced_buffer = false;\n\n }\n\n }\n\n \n\n pub fn instanced_rendered(&self) -> bool {\n\n self.instanced_buffer\n\n }\n\n \n\n pub fn _get_id(&mut self) -> i64 {\n\n self.reference_num as i64\n\n }\n\n \n\n pub fn id(&self) -> u32 {\n\n self.reference_num\n\n }\n\n \n", "file_path": "src/modules/world_object.rs", "rank": 23, "score": 12.373106068891287 }, { "content": " vel_x = vel_x + acc_x*delta_time*delta_time;\n\n vel_y = vel_y + acc_y*delta_time*delta_time;\n\n vel_z = vel_z + acc_z*delta_time*delta_time;\n\nend\";\n\n \n\n if let Err(e) = f.write_all(data.as_bytes()) {\n\n logs.add_error(e.to_string());\n\n }\n\n self.has_script = true;\n\n },\n\n Err(e) => {\n\n logs.add_error(e.to_string());\n\n }\n\n }\n\n }\n\n \n\n pub fn delete_script(&mut self, logs: &mut Logs) {\n\n if !self.has_script {\n\n return;\n\n }\n", "file_path": "src/modules/world_object.rs", "rank": 24, "score": 12.057719765038385 }, { "content": "use maat_graphics::DrawCall;\n\nuse maat_graphics::imgui::*;\n\n\n\nuse crate::modules::Logs;\n\n\n\nuse crate::cgmath::{Vector2, Vector3};\n\n\n\n#[derive(Clone)]\n\npub struct LightObject {\n\n reference_num: u32,\n\n name: String,\n\n \n\n position: Vector3<f32>,\n\n colour: Vector3<f32>,\n\n intensity: f32,\n\n}\n\n\n\nimpl LightObject {\n\n pub fn new_on(reference_num: u32, name: String) -> LightObject {\n\n LightObject {\n", "file_path": "src/modules/light_object.rs", "rank": 25, "score": 12.012505854060542 }, { "content": " self.world_objects.clear();\n\n self.placing_height = 0.0;\n\n self.object_being_placed = None;\n\n self.mouse_state = MouseState::World;\n\n self.selected_model = 0;\n\n self.object_selected = 0;\n\n self.run_game = false;\n\n self.f6_released_last_frame = true;\n\n let mut new_scene = ImString::with_capacity(32);\n\n new_scene.push_str(\"empty_scene\");\n\n imstr_scene_name = new_scene;\n\n self.load_scene_option = 0;\n\n \n\n if let Err(e) = fs::remove_dir_all(\"./Scenes/\".to_owned() + &self.scene_name) {\n\n self.logs.add_error(e.to_string());\n\n }\n\n }\n\n });\n\n \n\n self.scene_name = imstr_scene_name.to_str().to_string();\n", "file_path": "src/modules/scenes/editor_screen.rs", "rank": 26, "score": 11.035610575663625 }, { "content": " /*\n\n if self.known_models[i].2 {\n\n ui.same_line(0.0);\n\n if ui.button(im_str!(\"Unload\"), (0.0, 0.0)) { \n\n self.data.models_to_unload.push(self.known_models[i].0.to_string());\n\n self.known_models[i].2 = false;\n\n }\n\n }*/\n\n }\n\n });\n\n });\n\n \n\n if should_load_all {\n\n for i in 0..self.known_models.len() {\n\n let reference = self.known_models[i].0.to_string();\n\n let location = self.known_models[i].1.to_string();\n\n self.mut_data().models_to_load.push((reference, location));\n\n }\n\n }\n\n }\n", "file_path": "src/modules/scenes/editor_screen.rs", "rank": 27, "score": 10.770865297480544 }, { "content": " }\n\n }\n\n }\n\n self.world_objects = objects;\n\n self.data.models_to_load = load_models;\n\n self.game_options = game_options;\n\n self.windows.load_window = false;\n\n self.scene_name = path.to_string();\n\n }\n\n \n\n return;\n\n }\n\n \n\n let mut should_new = false;\n\n let mut should_save = false;\n\n let mut should_load = false;\n\n let mut should_exit = false;\n\n \n\n ui.main_menu_bar(|| {\n\n ui.menu(im_str!(\"File\")).build(|| {\n", "file_path": "src/modules/scenes/editor_screen.rs", "rank": 28, "score": 10.660130770500862 }, { "content": " });\n\n });\n\n \n\n if should_new {\n\n self.reset();\n\n }\n\n \n\n if should_save {\n\n for object in &mut self.world_objects {\n\n object.save_script(self.scene_name.to_string(), &mut self.logs);\n\n }\n\n export(self.scene_name.to_string(), &self.world_objects, &self.game_options, &mut self.logs);\n\n self.windows.saved = true;\n\n }\n\n if should_load {\n\n self.windows.load_window = true;\n\n }\n\n if should_exit {\n\n self.data.should_close = true;\n\n }\n", "file_path": "src/modules/scenes/editor_screen.rs", "rank": 29, "score": 10.637360261151729 }, { "content": " rng: rand::prelude::ThreadRng,\n\n camera: PerspectiveCamera,\n\n last_mouse_pos: Vector2<f32>,\n\n placing_height: f32,\n\n object_being_placed: Option<WorldObject>,\n\n world_objects: Vec<WorldObject>,\n\n light_objects: Vec<LightObject>,\n\n mouse_state: MouseState,\n\n selected_model: i32,\n\n object_selected: i32,\n\n known_models: Vec<(String, String, bool)>,\n\n run_game: bool,\n\n f6_released_last_frame: bool,\n\n right_clicked_last_frame: bool,\n\n update_mouse_cursor: bool,\n\n scene_name: String,\n\n load_scene_option: i32,\n\n logs: Logs,\n\n windows: EditorWindows,\n\n options: EditorOptions,\n", "file_path": "src/modules/scenes/editor_screen.rs", "rank": 30, "score": 10.606095653317801 }, { "content": " ui.input_float(im_str!(\"##Sizez\"), &mut self.size.z).build();\n\n }\n\n //.display_format(im_str!(\"%.0f\"))\n\n \n\n });\n\n \n\n self.name = imstr_name.to_str().to_string();\n\n \n\n self.default_options.position = self.position;\n\n self.default_options.size = self.size;\n\n self.default_options.rotation = self.rotation;\n\n }\n\n }\n\n \n\n pub fn draw_hologram(&self, draw_calls: &mut Vec<DrawCall>) {\n\n if self.instanced_buffer {\n\n draw_calls.push(DrawCall::add_instanced_hologram_model(self.model.to_string(), self.position, self.size, self.rotation));\n\n } else {\n\n draw_calls.push(DrawCall::draw_hologram_model(self.position, self.size, self.rotation, self.model.to_string()));\n\n }\n", "file_path": "src/modules/world_object.rs", "rank": 31, "score": 10.385213092884873 }, { "content": " snap_to_grid: bool,\n\n show_axis: bool,\n\n place_with_mouse: bool,\n\n instanced_option: i32,\n\n}\n\n\n\n#[derive(Clone)]\n\npub struct GameOptions {\n\n first_game_loop: bool,\n\n pub camera_type: i32,\n\n pub camera_target: i32,\n\n pub camera_distance: f32,\n\n pub camera_location: Vector3<f32>,\n\n pub camera_horizontal_rotation: bool,\n\n pub camera_vertical_rotation: bool,\n\n}\n\n\n\nimpl EditorWindows {\n\n pub fn new() -> EditorWindows {\n\n EditorWindows {\n", "file_path": "src/modules/scenes/editor_screen.rs", "rank": 32, "score": 10.33457666265985 }, { "content": "pub use self::world_object::WorldObject;\n\npub use self::light_object::LightObject;\n\npub use self::logs::Logs;\n\n\n\npub mod scenes;\n\npub mod import_export;\n\n\n\nmod logs;\n\nmod world_object;\n\nmod light_object;\n", "file_path": "src/modules/mod.rs", "rank": 34, "score": 10.17813257479143 }, { "content": " if let Err(e) = open::that(file) {\n\n logs.add_error(e.to_string());\n\n }\n\n }\n\n if ui.button(im_str!(\"Delete Script\"), [0.0, 0.0]) {\n\n self.delete_script(logs);\n\n }\n\n } else {\n\n if ui.button(im_str!(\"Create Script\"), [0.0, 0.0]) {\n\n self.create_script(logs);\n\n }\n\n }\n\n ui.text(\"Name:\");\n\n ui.same_line(0.0);\n\n ui.input_text(im_str!(\"\"), &mut imstr_name).build();\n\n if show_instanced_option {\n\n ui.checkbox(im_str!(\" Instance render\"), &mut self.instanced_buffer);\n\n }\n\n \n\n ui.text(im_str!(\n", "file_path": "src/modules/world_object.rs", "rank": 35, "score": 10.132358848948027 }, { "content": "use maat_graphics::DrawCall;\n\nuse maat_graphics::imgui::*;\n\n\n\nuse crate::modules::Logs;\n\n\n\nuse std::io::{Write, BufWriter};\n\nuse std::fs::File;\n\nuse std::fs;\n\nuse std::fs::copy;\n\nuse std::path::Path;\n\n\n\nuse hlua;\n\nuse hlua::Lua;\n\n\n\nuse open;\n\n\n\nuse crate::cgmath::{Vector2, Vector3};\n\n\n\nconst LOCATION: &str = \"./Scenes/\";\n\nconst OBJECTS: &str = \"/Objects/\";\n", "file_path": "src/modules/world_object.rs", "rank": 36, "score": 9.96505668419935 }, { "content": " name: String,\n\n location: String,\n\n directory: String,\n\n \n\n position: Vector3<f32>,\n\n rotation: Vector3<f32>,\n\n size: Vector3<f32>,\n\n velocity: Vector3<f32>,\n\n acceleration: Vector3<f32>,\n\n \n\n position_edit: bool,\n\n size_edit: bool,\n\n rotation_edit: bool,\n\n \n\n has_script: bool,\n\n update_function: Option<File>,\n\n default_options: DefaultOptions,\n\n \n\n instanced_buffer: bool,\n\n}\n", "file_path": "src/modules/world_object.rs", "rank": 37, "score": 9.913523999353378 }, { "content": " object_selected: 0,\n\n known_models: import_export::get_models(&mut logs),\n\n run_game,\n\n f6_released_last_frame: true,\n\n right_clicked_last_frame: false,\n\n update_mouse_cursor: false,\n\n scene_name,\n\n load_scene_option: 0,\n\n logs,\n\n windows,\n\n options,\n\n game_options,\n\n instanced_buffers,\n\n instanced_buffers_added: Vec::new(),\n\n }\n\n }\n\n \n\n pub fn update_input(&mut self, delta_time: f32) {\n\n self.data.controller.update();\n\n \n", "file_path": "src/modules/scenes/editor_screen.rs", "rank": 38, "score": 9.89553320794566 }, { "content": " pub currently_pressed: Vec<u32>,\n\n pub released_this_render: Vec<u32>,\n\n pub keys: MappedKeys,\n\n pub window_resized: bool,\n\n pub controller: Controller,\n\n pub model_sizes: Vec<(String, Vector3<f32>)>,\n\n imgui_info: ImGuiInfo,\n\n models_to_load: Vec<(String, String)>,\n\n models_to_unload: Vec<String>,\n\n}\n\n\n\nimpl SceneData {\n\n pub fn new(window_size: Vector2<f32>, model_sizes: Vec<(String, Vector3<f32>)>) -> SceneData {\n\n SceneData {\n\n should_close: false,\n\n next_scene: false,\n\n mouse_pos: Vector2::new(0.0, 0.0),\n\n scroll_delta: 0.0, // Scroll Delta is either -1, 0 or 1\n\n left_mouse: false,\n\n right_mouse: false,\n", "file_path": "src/modules/scenes/mod.rs", "rank": 39, "score": 9.830499339838926 }, { "content": " instanced_buffers: Vec::new(),\n\n instanced_buffers_added: Vec::new(),\n\n }\n\n }\n\n \n\n pub fn new_with_data(window_size: Vector2<f32>, rng: rand::prelude::ThreadRng, camera: PerspectiveCamera, object_being_placed: Option<WorldObject>, scene_name: String, placing_height: f32, world_objects: Vec<WorldObject>, light_objects: Vec<LightObject>, windows: EditorWindows, options: EditorOptions, game_options: GameOptions, run_game: bool, model_sizes: Vec<(String, Vector3<f32>)>, instanced_buffers: Vec<String>) -> EditorScreen {\n\n \n\n let mut logs = Logs::new(window_size);\n\n \n\n EditorScreen {\n\n data: SceneData::new(window_size, model_sizes),\n\n rng,\n\n camera,\n\n last_mouse_pos: Vector2::new(-1.0, -1.0),\n\n placing_height,\n\n object_being_placed,\n\n world_objects,\n\n light_objects,\n\n mouse_state: MouseState::World,\n\n selected_model: 0,\n", "file_path": "src/modules/scenes/editor_screen.rs", "rank": 41, "score": 9.752105189972887 }, { "content": "use maat_graphics::DrawCall;\n\nuse maat_graphics::imgui::*;\n\n\n\nuse crate::modules::scenes::Scene;\n\nuse crate::modules::scenes::SceneData;\n\nuse crate::modules::scenes::EditorScreen;\n\n\n\nuse hlua::Lua;\n\n\n\nuse crate::cgmath::{Vector2, Vector4};\n\n\n\nconst LOGO_TIMER: f32 = 1.5;\n\n\n\npub struct LoadScreen {\n\n data: SceneData,\n\n alpha: f32,\n\n logo_timer: f32,\n\n first_loop: bool,\n\n loop_num: u32,\n\n}\n", "file_path": "src/modules/scenes/load_screen.rs", "rank": 42, "score": 9.614746492762107 }, { "content": " reference_num,\n\n name,\n\n \n\n position: Vector3::new(0.0, 0.0, 0.0),\n\n colour: Vector3::new(1.0, 1.0, 1.0),\n\n intensity: 100.0,\n\n }\n\n }\n\n \n\n pub fn id(&self) -> u32 {\n\n self.reference_num\n\n }\n\n \n\n pub fn name(&self) -> String {\n\n self.name.to_string()\n\n }\n\n \n\n pub fn position(&self) -> Vector3<f32> {\n\n self.position\n\n }\n", "file_path": "src/modules/light_object.rs", "rank": 43, "score": 9.339512656955353 }, { "content": " }\n\n \n\n pub fn draw(&self, draw_calls: &mut Vec<DrawCall>) {\n\n if self.instanced_buffer {\n\n draw_calls.push(DrawCall::add_instanced_model(self.model.to_string(), \n\n self.position,\n\n self.size,\n\n self.rotation));\n\n } else {\n\n draw_calls.push(DrawCall::draw_model(self.position,\n\n self.size,\n\n self.rotation,\n\n self.model.to_string()));\n\n }\n\n }\n\n}\n", "file_path": "src/modules/world_object.rs", "rank": 44, "score": 9.305490968481815 }, { "content": " if ui.button(im_str!(\"Load All\"), [0.0, 0.0]) {\n\n should_load_all = true;\n\n }\n\n let [size_x, size_y] = ui.get_content_region_avail();//get_window_size();\n\n ui.child_frame(im_str!(\"child frame\"), [size_x, size_y])\n\n .show_borders(true)\n\n .build(|| {\n\n for i in 0..self.known_models.len() {\n\n let _model_loaded = self.known_models[i].2;\n\n ui.text(im_str!(\"{}\", self.known_models[i].0));\n\n \n\n //ui.checkbox(im_str!(\"##{}\", i), &mut model_loaded);\n\n if !self.known_models[i].2 {\n\n ui.same_line(0.0);\n\n if ui.button(&im_str!(\"Load##{}\", i), [0.0, 0.0]) {\n\n let reference = self.known_models[i].0.to_string();\n\n let location = self.known_models[i].1.to_string();\n\n self.mut_data().models_to_load.push((reference, location));\n\n }\n\n }\n", "file_path": "src/modules/scenes/editor_screen.rs", "rank": 45, "score": 9.070529256667523 }, { "content": " \n\n position: Vector3::new(0.0, 0.0, 0.0),\n\n rotation: Vector3::new(0.0, 0.0, 0.0),\n\n size: Vector3::new(1.0, 1.0, 1.0),\n\n position_edit: false,\n\n velocity: Vector3::new(0.0, 0.0, 0.0),\n\n acceleration: Vector3::new(0.0, 0.0, 0.0),\n\n \n\n size_edit: false,\n\n rotation_edit: false,\n\n \n\n has_script: false,\n\n update_function: None,\n\n default_options: DefaultOptions::new(Vector3::new(0.0, 0.0, 0.0), Vector3::new(1.0, 1.0, 1.0),Vector3::new(0.0, 0.0, 0.0)),\n\n \n\n instanced_buffer: false,\n\n }\n\n }\n\n \n\n pub fn new_with_name(reference_num: u32, object_name: String, directory: String, model: String, location: String, position: Vector3<f32>, rotation: Vector3<f32>, size: Vector3<f32>) -> WorldObject {\n", "file_path": "src/modules/world_object.rs", "rank": 46, "score": 8.871231637314853 }, { "content": " self.camera = PerspectiveCamera::default_vk();\n\n self.camera.set_position(Vector3::new(CAMERA_DEFAULT_X, CAMERA_DEFAULT_Y, CAMERA_DEFAULT_Z));\n\n self.camera.set_pitch(CAMERA_DEFAULT_PITCH);\n\n self.camera.set_yaw(CAMERA_DEFAULT_YAW);\n\n self.camera.set_move_speed(CAMERA_DEFAULT_SPEED);\n\n }\n\n \n\n pub fn change_selected_object(&mut self) {\n\n let id = {\n\n if self.world_objects.len() > 0 {\n\n self.world_objects[self.world_objects.len()-1].id()+1\n\n } else {\n\n 0\n\n }\n\n };\n\n \n\n if self.data().model_sizes.len() > self.selected_model as usize {\n\n let (model_name, _) = self.data().model_sizes[self.selected_model as usize].clone();\n\n for i in 0..self.known_models.len() {\n\n if model_name.to_string() == self.known_models[i].0 {\n", "file_path": "src/modules/scenes/editor_screen.rs", "rank": 47, "score": 8.821669717865833 }, { "content": " let ui_window_size = [450.0, 200.0];\n\n \n\n let mut imstr_name = ImString::with_capacity(32);\n\n imstr_name.push_str(&self.name);\n\n \n\n ui.window(im_str!(\"Object Being Placed\"))\n\n .size(ui_window_size, Condition::Appearing)\n\n .position([window_dim.x-ui_window_size[0]-20.0, 432.0], Condition::Appearing)\n\n //.always_auto_resize(true)\n\n .build(|| {\n\n if self.has_script {\n\n let txt = \"Script: \".to_owned() + &self.name.to_string() + \".lua\";\n\n let mut imstr_script = ImString::with_capacity(32);\n\n imstr_script.push_str(&txt);\n\n ui.text(imstr_script);\n\n ui.same_line(0.0);\n\n if ui.button(im_str!(\"Open\"), [0.0, 0.0]) {\n\n let file_name = self.name.to_owned() + \".lua\";\n\n \n\n let file = LOCATION.to_owned() + &self.directory.to_string() + &OBJECTS.to_string() + &file_name;\n", "file_path": "src/modules/world_object.rs", "rank": 48, "score": 8.819147020266675 }, { "content": " logs.add_error(e.to_string());\n\n }\n\n \n\n let function_name = self.name.to_owned() + \"update\";\n\n \n\n if let Some(update) = lua.get(function_name.to_string()) {\n\n let mut update: hlua::LuaFunction<_> = update;\n\n let result = update.call::<()>();\n\n if let Some(e) = hlua_error!(result) {\n\n logs.add_error(e.to_string());\n\n }\n\n }\n\n }\n\n \n\n self.position.x = lua.get(\"x\").unwrap();\n\n self.position.y = lua.get(\"y\").unwrap();\n\n self.position.z = lua.get(\"z\").unwrap();\n\n self.size.x = lua.get(\"size_x\").unwrap();\n\n self.size.y = lua.get(\"size_y\").unwrap();\n\n self.size.z = lua.get(\"size_z\").unwrap();\n", "file_path": "src/modules/world_object.rs", "rank": 49, "score": 8.74783722093962 }, { "content": " pub fn rotation(&self) -> Vector3<f32> {\n\n self.rotation\n\n }\n\n \n\n pub fn set_position(&mut self, pos: Vector3<f32>) {\n\n self.default_options.position = pos;\n\n }\n\n \n\n pub fn reset(&mut self) {\n\n self.position = self.default_options.position;\n\n self.size = self.default_options.size;\n\n self.rotation = self.default_options.rotation;\n\n }\n\n \n\n pub fn update_game(&mut self, lua: &mut Option<&mut Lua>, logs: &mut Logs) {\n\n if self.update_function.is_none() {\n\n return;\n\n }\n\n \n\n if let Some(lua) = lua {\n", "file_path": "src/modules/world_object.rs", "rank": 51, "score": 8.536889489259256 }, { "content": " game_options: GameOptions,\n\n instanced_buffers: Vec<String>,\n\n instanced_buffers_added: Vec<String>,\n\n}\n\n\n\nimpl EditorScreen {\n\n pub fn new(window_size: Vector2<f32>, model_sizes: Vec<(String, Vector3<f32>)>) -> EditorScreen {\n\n let rng = thread_rng();\n\n \n\n let mut camera = PerspectiveCamera::default_vk();\n\n camera.set_position(Vector3::new(CAMERA_DEFAULT_X, CAMERA_DEFAULT_Y, CAMERA_DEFAULT_Z));\n\n camera.set_pitch(CAMERA_DEFAULT_PITCH);\n\n camera.set_yaw(CAMERA_DEFAULT_YAW);\n\n camera.set_move_speed(CAMERA_DEFAULT_SPEED);\n\n \n\n let mut logs = Logs::new(window_size);\n\n \n\n EditorScreen {\n\n data: SceneData::new(window_size, model_sizes),\n\n rng,\n", "file_path": "src/modules/scenes/editor_screen.rs", "rank": 52, "score": 8.491214923650853 }, { "content": " \n\n if self.windows.loaded_models {\n\n ui.window(im_str!(\"Loaded Models\"))\n\n .position([0.0, 540.0], Condition::Appearing)\n\n .size([200.0, 400.0], Condition::Appearing)\n\n //.always_auto_resize(true)\n\n .build(|| {\n\n let old_selection = self.selected_model;\n\n for i in 0..self.data().model_sizes.len() {\n\n let (reference, _) = self.data().model_sizes[i].clone();\n\n let name = (reference.to_string()).to_owned();\n\n ui.radio_button(&im_str!(\"{}##{}\",name,i), &mut self.selected_model, i as i32);\n\n }\n\n if old_selection != self.selected_model {\n\n if self.object_being_placed.is_some() {\n\n self.change_selected_object();\n\n }\n\n }\n\n });\n\n }\n", "file_path": "src/modules/scenes/editor_screen.rs", "rank": 53, "score": 8.473112948529062 }, { "content": " models\n\n }\n\n \n\n fn set_window_dimensions(&mut self, new_dim: Vector2<f32>) {\n\n self.mut_data().update_window_dim(new_dim);\n\n }\n\n \n\n fn set_mouse_position(&mut self, mouse_position: Vector2<f32>) {\n\n self.mut_data().update_mouse_pos(mouse_position);\n\n }\n\n \n\n fn add_model_size(&mut self, reference: String, size: Vector3<f32>) {\n\n self.mut_data().model_sizes.push((reference, size));\n\n }\n\n \n\n fn handle_input(&mut self, event: &winit::WindowEvent) -> bool {\n\n self.mut_data().released_this_render.clear();\n\n\n\n\n\n if self.data().left_mouse {\n", "file_path": "src/modules/scenes/mod.rs", "rank": 54, "score": 8.390252216658636 }, { "content": " last_fps = frame_counter as f64 * (1.0/fps_timer);\n\n fps_timer = 0.0;\n\n frame_counter = 0;\n\n }\n\n \n\n dimensions = graphics.get_virtual_dimensions();\n\n \n\n let models = game.get_models_to_unload();\n\n for reference in &models {\n\n draw_calls.push(DrawCall::unload_model(reference.to_string()));\n\n }\n\n \n\n let models = game.get_models_to_load();\n\n for (reference, location) in &models {\n\n graphics.add_model(reference.to_string(), location.to_string());\n\n draw_calls.push(DrawCall::load_model(reference.to_string()));\n\n }\n\n \n\n if game.scene_finished() {\n\n game = game.future_scene(dimensions);\n", "file_path": "src/main.rs", "rank": 55, "score": 8.385641356738448 }, { "content": " }\n\n \n\n match File::create(LOCATION.to_owned() + &self.directory.to_string() + &OBJECTS.to_string() + &file_name.to_string()) {\n\n Ok(f) => {\n\n let mut f = BufWriter::new(f);\n\n \n\n let data = \"-- ref_num\n\n-- delta_time\n\n-- mouse_x\n\n-- mouse_y\n\n-- left_mouse\n\n-- right_mouse\n\n-- window_dim_x\n\n-- window_dim_y\n\n-- w_key\n\n-- a_key\n\n-- s_key\n\n-- d_key\n\n\n\n-- x\n", "file_path": "src/modules/world_object.rs", "rank": 56, "score": 8.358564002085414 }, { "content": " offset += 1;\n\n for objects in &mut self.world_objects {\n\n objects.instanced_buffer_removed(buffer.to_string());\n\n }\n\n }\n\n }\n\n \n\n ui.push_item_width(190.0);\n\n if self.data.model_sizes.len() != self.instanced_buffers.len() {\n\n let mut items = self.data.model_sizes.clone().into_iter().map(|model| {\n\n ImString::new(model.0)\n\n }).collect::<Vec<ImString>>();\n\n \n\n let mut offset = 0;\n\n for i in 0..items.len() {\n\n if i < offset {\n\n break;\n\n }\n\n \n\n if self.instanced_buffers.contains(&items[i-offset].to_str().to_string()) {\n", "file_path": "src/modules/scenes/editor_screen.rs", "rank": 57, "score": 8.256301246960241 }, { "content": " camera,\n\n last_mouse_pos: Vector2::new(-1.0, -1.0),\n\n placing_height: 0.0,\n\n object_being_placed: None,\n\n world_objects: Vec::new(),\n\n light_objects: Vec::new(),\n\n mouse_state: MouseState::World,\n\n selected_model: 0,\n\n object_selected: 0,\n\n known_models: import_export::get_models(&mut logs),\n\n run_game: false,\n\n f6_released_last_frame: true,\n\n right_clicked_last_frame: false,\n\n update_mouse_cursor: false,\n\n scene_name: \"empty_scene\".to_string(),\n\n load_scene_option: 0,\n\n logs,\n\n windows: EditorWindows::new(),\n\n options: EditorOptions::new(),\n\n game_options: GameOptions::new(),\n", "file_path": "src/modules/scenes/editor_screen.rs", "rank": 58, "score": 8.144369704348065 }, { "content": " let mut scenes = Vec::new();\n\n \n\n for path in paths {\n\n scenes.push(ImString::new(path.unwrap().path().display().to_string()));\n\n }\n\n \n\n let mut should_load = false;\n\n let mut should_cancel = false;\n\n let mut new = false;\n\n ui.window(im_str!(\"Load Scene\"))\n\n .size([500.0, 100.0], Condition::Appearing)\n\n .always_auto_resize(true)\n\n .collapsible(false)\n\n .build( || {\n\n let items: Vec<_> = scenes.iter().map(|p| \n\n p//.as_ref()\n\n ).collect();\n\n \n\n ui.text(\"Scene: \");\n\n ui.same_line(0.0);\n", "file_path": "src/modules/scenes/editor_screen.rs", "rank": 59, "score": 8.011346791317793 }, { "content": " models\n\n }\n\n \n\n fn get_models_to_unload(&mut self) -> Vec<String> {\n\n let mut idxs = Vec::new();\n\n for i in 0..self.data().models_to_unload.len() {\n\n for j in 0..self.data().model_sizes.len() {\n\n if self.data().model_sizes[j].0 == self.data().models_to_unload[i] {\n\n idxs.push(j);\n\n }\n\n }\n\n }\n\n \n\n for i in 0..idxs.len() {\n\n self.mut_data().model_sizes.remove(idxs[i]-i);\n\n }\n\n \n\n let models = self.data().models_to_unload.clone();\n\n self.mut_data().models_to_unload = Vec::new();\n\n \n", "file_path": "src/modules/scenes/mod.rs", "rank": 60, "score": 7.9670936859483685 }, { "content": " self.change_selected_object()\n\n }\n\n \n\n self.right_clicked_last_frame = right_clicked;\n\n self.last_mouse_pos = mouse;\n\n }\n\n \n\n pub fn reset(&mut self) {\n\n self.world_objects.clear();\n\n self.placing_height = 0.0;\n\n self.object_being_placed = None;\n\n self.mouse_state = MouseState::World;\n\n self.selected_model = 0;\n\n self.object_selected = 0;\n\n self.run_game = false;\n\n self.f6_released_last_frame = true;\n\n self.scene_name = \"new_scene\".to_string();\n\n self.load_scene_option = 0;\n\n self.windows.load_window = false;\n\n \n", "file_path": "src/modules/scenes/editor_screen.rs", "rank": 61, "score": 7.682555007938236 }, { "content": " ui.input_float(im_str!(\"##x\"), &mut self.game_options.camera_location.x).build();\n\n ui.next_column();\n\n ui.text(im_str!(\"y:\"));\n\n ui.same_line(0.0);\n\n ui.input_float(im_str!(\"##y\"), &mut self.game_options.camera_location.y).build();\n\n ui.next_column();\n\n ui.text(im_str!(\"z:\"));\n\n ui.same_line(0.0);\n\n ui.input_float(im_str!(\"##z\"), &mut self.game_options.camera_location.z).build();\n\n },\n\n 1 => {\n\n ui.text(\"Target:\");\n\n ui.same_line(0.0);\n\n \n\n let mut objects = Vec::new();\n\n \n\n for i in 0..self.world_objects.len() {\n\n objects.push(ImString::new(self.world_objects[i].name()));\n\n }\n\n \n", "file_path": "src/modules/scenes/editor_screen.rs", "rank": 62, "score": 7.668936884665118 }, { "content": " self.rotation.x = lua.get(\"rot_x\").unwrap();\n\n self.rotation.y = lua.get(\"rot_y\").unwrap();\n\n self.rotation.z = lua.get(\"rot_z\").unwrap();\n\n self.velocity.x = lua.get(\"vel_x\").unwrap();\n\n self.velocity.y = lua.get(\"vel_y\").unwrap();\n\n self.velocity.z = lua.get(\"vel_z\").unwrap();\n\n self.acceleration.x = lua.get(\"acc_x\").unwrap();\n\n self.acceleration.y = lua.get(\"acc_y\").unwrap();\n\n self.acceleration.z = lua.get(\"acc_z\").unwrap();\n\n }\n\n }\n\n \n\n pub fn update(&mut self, ui: Option<&Ui>, instanced_buffers: &Vec<String>, window_dim: Vector2<f32>, _delta_time: f32, logs: &mut Logs) {\n\n self.position = self.default_options.position;\n\n self.size = self.default_options.size;\n\n self.rotation = self.default_options.rotation;\n\n \n\n let show_instanced_option = instanced_buffers.contains(&self.model.to_string());\n\n \n\n if let Some(ui) = &ui {\n", "file_path": "src/modules/world_object.rs", "rank": 63, "score": 7.518480436611121 }, { "content": "mod load_screen;\n\nmod editor_screen;\n\n\n\npub struct ImGuiInfo {\n\n wants_mouse: bool,\n\n wants_keyboard: bool,\n\n}\n\n\n\npub struct SceneData {\n\n pub should_close: bool,\n\n pub next_scene: bool,\n\n mouse_pos: Vector2<f32>,\n\n pub scroll_delta: f32,\n\n left_mouse: bool,\n\n right_mouse: bool,\n\n middle_mouse: bool,\n\n pub left_mouse_dragged: bool,\n\n pub right_mouse_dragged: bool,\n\n pub middle_mouse_dragged: bool,\n\n pub window_dim: Vector2<f32>,\n", "file_path": "src/modules/scenes/mod.rs", "rank": 64, "score": 7.48009326850082 }, { "content": "\n\nimpl LoadScreen {\n\n pub fn new() -> LoadScreen {\n\n LoadScreen {\n\n data: SceneData::new_default(),\n\n alpha: 0.0,\n\n logo_timer: LOGO_TIMER,\n\n first_loop: true,\n\n loop_num: 0,\n\n }\n\n }\n\n}\n\n\n\nimpl Scene for LoadScreen {\n\n fn data(&self) -> &SceneData {\n\n &self.data\n\n }\n\n \n\n fn mut_data(&mut self) -> &mut SceneData {\n\n &mut self.data\n", "file_path": "src/modules/scenes/load_screen.rs", "rank": 65, "score": 7.338046209612194 }, { "content": "extern crate maat_graphics;\n\nextern crate maat_input_handler;\n\nextern crate rand;\n\nextern crate csv;\n\nextern crate hlua;\n\nextern crate open;\n\n\n\nuse hlua::Lua;\n\nuse maat_graphics::imgui::*;\n\npub use maat_graphics::winit;\n\npub use maat_graphics::cgmath;\n\n\n\nmod modules;\n\n\n\nuse crate::modules::scenes::Scene;\n\nuse crate::modules::scenes::LoadScreen;\n\n\n\nuse maat_graphics::graphics::CoreRender;\n\nuse maat_graphics::CoreMaat;\n\nuse maat_graphics::DrawCall;\n\n\n\nuse cgmath::{Vector2, Vector4};\n\n\n\nuse std::time;\n\n\n\nconst MAJOR: u32 = 0;\n\nconst MINOR: u32 = 2;\n\nconst PATCH: u32 = 1;\n\n\n", "file_path": "src/main.rs", "rank": 66, "score": 7.19130203566573 }, { "content": " }\n\n \n\n fn future_scene(&mut self, window_size: Vector2<f32>) -> Box<Scene> {\n\n Box::new(EditorScreen::new(window_size, self.data.model_sizes.clone()))\n\n }\n\n \n\n fn update(&mut self, _ui: Option<&Ui>, _lua: Option<&mut Lua>, delta_time: f32) {\n\n self.logo_timer -= delta_time as f32;\n\n self.alpha = 1.0 - (self.logo_timer / (LOGO_TIMER*0.7));\n\n \n\n if self.logo_timer <= 0.0 {\n\n self.mut_data().next_scene = true;\n\n }\n\n \n\n if self.loop_num == 1 {\n\n self.first_loop = false;\n\n }\n\n self.loop_num += 1;\n\n }\n\n \n", "file_path": "src/modules/scenes/load_screen.rs", "rank": 67, "score": 6.953397128369338 }, { "content": " }\n\n \n\n fn mut_data(&mut self) -> &mut SceneData {\n\n &mut self.data\n\n }\n\n \n\n fn future_scene(&mut self, window_size: Vector2<f32>) -> Box<Scene> {\n\n if self.data().window_resized {\n\n Box::new(EditorScreen::new_with_data(window_size, self.rng.clone(), self.camera.clone(), \n\n self.object_being_placed.clone(), self.scene_name.to_string(), \n\n self.placing_height, self.world_objects.clone(), self.light_objects.clone(), \n\n self.windows.clone(), self.options.clone(), self.game_options.clone(),\n\n self.run_game, self.data.model_sizes.clone(), self.instanced_buffers.clone()))\n\n } else {\n\n Box::new(EditorScreen::new(window_size, self.data.model_sizes.clone()))\n\n }\n\n }\n\n \n\n fn update(&mut self, ui: Option<&Ui>, mut lua: Option<&mut Lua>, delta_time: f32) {\n\n if self.data.window_resized {\n", "file_path": "src/modules/scenes/editor_screen.rs", "rank": 68, "score": 6.856728992321636 }, { "content": " }\n\n }\n\n}\n\n\n\nimpl GameOptions {\n\n pub fn new() -> GameOptions {\n\n GameOptions {\n\n first_game_loop: true,\n\n camera_type: 0,\n\n camera_target: 0,\n\n camera_distance: 90.0,\n\n camera_location: Vector3::new(0.0,0.0,0.0),\n\n camera_horizontal_rotation: false,\n\n camera_vertical_rotation: false,\n\n }\n\n }\n\n}\n\n\n\npub struct EditorScreen {\n\n data: SceneData,\n", "file_path": "src/modules/scenes/editor_screen.rs", "rank": 69, "score": 6.610421517169593 }, { "content": "use maat_graphics::DrawCall;\n\nuse maat_graphics::imgui::*;\n\n\n\nuse maat_input_handler::MappedKeys;\n\nuse maat_input_handler::Controller;\n\n\n\nuse hlua::Lua;\n\n\n\nuse std::vec::Vec;\n\n\n\nuse maat_graphics::winit;\n\nuse maat_graphics::winit::MouseScrollDelta::LineDelta;\n\nuse maat_graphics::winit::MouseScrollDelta::PixelDelta;\n\n\n\nuse crate::cgmath::{Vector2, Vector3};\n\n\n\npub use self::load_screen::LoadScreen;\n\npub use self::editor_screen::EditorScreen;\n\npub use self::editor_screen::GameOptions;\n\n\n", "file_path": "src/modules/scenes/mod.rs", "rank": 70, "score": 6.467565520220246 }, { "content": "\n\npub struct DefaultOptions {\n\n position: Vector3<f32>,\n\n size: Vector3<f32>,\n\n rotation: Vector3<f32>,\n\n}\n\n\n\nimpl DefaultOptions {\n\n pub fn new(position: Vector3<f32>, size: Vector3<f32>, rotation: Vector3<f32>) -> DefaultOptions {\n\n DefaultOptions {\n\n position,\n\n size,\n\n rotation,\n\n }\n\n }\n\n}\n\n\n\npub struct WorldObject {\n\n reference_num: u32,\n\n model: String,\n", "file_path": "src/modules/world_object.rs", "rank": 71, "score": 6.37953156158753 }, { "content": " \n\n pub fn set_position(&mut self, pos: Vector3<f32>) {\n\n self.position = pos;\n\n }\n\n \n\n pub fn update(&mut self, ui: Option<&Ui>,window_dim: Vector2<f32>, _delta_time: f32, _logs: &mut Logs) {\n\n if let Some(ui) = &ui {\n\n ui.window(im_str!(\"Light Options\"))\n\n .always_auto_resize(true)\n\n .size([200.0, 200.0], Condition::Appearing)\n\n .position([window_dim.x - 500.0, 200.0], Condition::Appearing)\n\n .build(|| {\n\n ui.new_line();\n\n ui.text(im_str!(\"Position\"));\n\n \n\n ui.columns(3, im_str!(\"x | y | z\"), true);\n\n ui.text(im_str!(\"x:\"));\n\n ui.same_line(0.0);\n\n ui.input_float(im_str!(\"##x\"), &mut self.position.x).build();\n\n ui.next_column();\n", "file_path": "src/modules/light_object.rs", "rank": 72, "score": 6.35553745481217 }, { "content": " should_delete_object = ui.button(im_str!(\"Delete\"), [0.0,0.0]);\n\n }\n\n }\n\n \n\n if should_delete_object {\n\n self.world_objects[self.object_selected as usize-2].delete_script(&mut self.logs);\n\n self.world_objects.remove(self.object_selected as usize-2);\n\n self.object_selected = 0;\n\n }\n\n });\n\n }\n\n \n\n if self.windows.model_list {\n\n let mut should_load_all = false;\n\n \n\n let window_width = 200.0;\n\n ui.window(im_str!(\"Model List ./Models/*\"))\n\n .position([self.data.window_dim.x-window_width*1.1, 32.0], Condition::Appearing)\n\n .size([window_width, 400.0], Condition::Appearing)\n\n .build(|| {\n", "file_path": "src/modules/scenes/editor_screen.rs", "rank": 73, "score": 6.3438796330508005 }, { "content": " \n\n }\n\n self.f6_released_last_frame = !self.data.keys.f6_pressed();\n\n \n\n \n\n if self.logs.is_shown() {\n\n self.logs.draw(ui);\n\n }\n\n }\n\n \n\n fn draw(&self, draw_calls: &mut Vec<DrawCall>) {\n\n /* if self.update_mouse_cursor {\n\n draw_calls.push(DrawCall::set_cursor_position(self.last_mouse_pos.x, self.last_mouse_pos.y));\n\n }*/\n\n for buffer in &self.instanced_buffers_added {\n\n draw_calls.push(DrawCall::add_instanced_model_buffer(buffer.to_string()));\n\n }\n\n \n\n draw_calls.push(DrawCall::set_camera(self.camera.clone()));\n\n \n", "file_path": "src/modules/scenes/editor_screen.rs", "rank": 74, "score": 6.26186036091217 }, { "content": " \n\n if self.run_game {\n\n return;\n\n }\n\n \n\n if self.windows.scene_details {\n\n let mut imstr_scene_name = ImString::with_capacity(32);\n\n imstr_scene_name.push_str(&self.scene_name);\n\n \n\n ui.window(im_str!(\"Scene Details\"))\n\n .size([250.0, 60.0], Condition::Appearing)\n\n .position([0.0, 55.0], Condition::Appearing)\n\n .always_auto_resize(true)\n\n .build( || {\n\n ui.text(\"Scene name:\");\n\n ui.same_line(0.0);\n\n ui.push_item_width(150.0);\n\n ui.input_text(im_str!(\"\"), &mut imstr_scene_name).build();\n\n ui.push_item_width(0.0);\n\n if ui.button(im_str!(\"Delete Scene\"), [0.0, 0.0]) {\n", "file_path": "src/modules/scenes/editor_screen.rs", "rank": 75, "score": 6.211238037359989 }, { "content": " if !self.game_options.first_game_loop {\n\n self.options.show_axis = true;\n\n self.game_options.first_game_loop = true;\n\n }\n\n \n\n for i in 0..self.data.model_sizes.len() {\n\n for j in 0..self.known_models.len() {\n\n if self.data.model_sizes[i].0 == self.known_models[j].0 {\n\n self.known_models[j].2 = true;\n\n }\n\n }\n\n }\n\n \n\n let mouse = self.data.mouse_pos;\n\n \n\n match self.mouse_state {\n\n MouseState::Ui => {\n\n \n\n },\n\n MouseState::World => {\n", "file_path": "src/modules/scenes/editor_screen.rs", "rank": 76, "score": 5.985103866441474 }, { "content": "use maat_graphics::DrawCall;\n\nuse maat_graphics::camera::PerspectiveCamera;\n\nuse maat_graphics::imgui::*;\n\n\n\nuse hlua::Lua;\n\n\n\nuse crate::modules::scenes::Scene;\n\nuse crate::modules::scenes::SceneData;\n\nuse crate::modules::WorldObject;\n\nuse crate::modules::LightObject;\n\nuse crate::modules::import_export;\n\nuse crate::modules::import_export::{import, export};\n\nuse crate::modules::Logs;\n\n\n\nuse rand;\n\nuse rand::{thread_rng};\n\n\n\nuse crate::cgmath::{Vector2, Vector3};\n\n\n\nuse std::fs;\n", "file_path": "src/modules/scenes/editor_screen.rs", "rank": 77, "score": 5.628673256652409 }, { "content": " fn draw(&self, draw_calls: &mut Vec<DrawCall>) {\n\n let dim = self.data().window_dim;\n\n let (width, height) = (dim.x as f32, dim.y as f32);\n\n \n\n if self.first_loop {\n\n draw_calls.push(DrawCall::load_model(\"Axis\".to_string()));\n\n }\n\n \n\n draw_calls.push(DrawCall::set_texture_scale(1.0));\n\n \n\n draw_calls.push(\n\n DrawCall::draw_coloured(Vector2::new(width*0.5, height*0.5),\n\n Vector2::new(width*5.0, height*5.0),\n\n Vector4::new(1.0, 1.0, 1.0, 1.0),\n\n 90.0)\n\n );\n\n \n\n draw_calls.push(\n\n DrawCall::draw_textured(Vector2::new(width*0.45, height*0.6), \n\n Vector2::new(500.0, 500.0),\n", "file_path": "src/modules/scenes/load_screen.rs", "rank": 78, "score": 5.333402424915385 }, { "content": " },\n\n }\n\n },\n\n winit::WindowEvent::ReceivedCharacter(character) => {\n\n if character.is_ascii() || character.is_ascii_control() || character.is_ascii_whitespace() {\n\n let mut string_char = character.to_string();\n\n \n\n if *character == '\\n' || *character == '\\r' {\n\n string_char = \"Enter\".to_string();\n\n } else if *character == '\\x08' {\n\n string_char = \"Backspace\".to_string();\n\n } else if character.is_ascii_control() {\n\n string_char = \"\".to_string();\n\n }\n\n \n\n self.mut_data().keys.pressed_this_frame.push(string_char);\n\n }\n\n },\n\n winit::WindowEvent::KeyboardInput{device_id: _, input} => {\n\n let key = input.scancode;\n", "file_path": "src/modules/scenes/mod.rs", "rank": 79, "score": 5.291690676996355 }, { "content": " let axis_position = Vector3::new(0.0, 0.0, 0.0);\n\n let axis_size = Vector3::new(50.0, 10.0, 10.0);\n\n let rot_x_size = Vector3::new(0.0, 0.0, 0.0);\n\n let rot_y_size = Vector3::new(0.0, 0.0, 90.0);\n\n let rot_z_size = Vector3::new(0.0, 90.0, 0.0);\n\n let axis = String::from(\"Axis\");\n\n draw_calls.push(DrawCall::draw_model(axis_position,\n\n axis_size,\n\n rot_x_size,\n\n axis.to_string()));\n\n draw_calls.push(DrawCall::draw_model(axis_position,\n\n axis_size,\n\n rot_y_size,\n\n axis.to_string()));\n\n draw_calls.push(DrawCall::draw_model(axis_position,\n\n axis_size,\n\n rot_z_size,\n\n axis.to_string()));\n\n }\n\n \n\n for buffer in &self.instanced_buffers {\n\n draw_calls.push(DrawCall::draw_instanced_model(buffer.to_string()));\n\n }\n\n }\n\n}\n", "file_path": "src/modules/scenes/editor_screen.rs", "rank": 80, "score": 5.290674761500984 }, { "content": " }\n\n \n\n pub fn update_mouse_pos(&mut self, mouse_position: Vector2<f32>) {\n\n self.mouse_pos = mouse_position;\n\n }\n\n \n\n pub fn update_window_dim(&mut self, dim: Vector2<f32>) {\n\n if self.window_dim != dim {\n\n self.window_resized = true;\n\n self.window_dim = dim;\n\n }\n\n }\n\n}\n\n\n\n\n", "file_path": "src/modules/scenes/mod.rs", "rank": 81, "score": 5.201150548719609 }, { "content": " ui.menu_item(im_str!(\"New\")).selected(&mut should_new).build();\n\n ui.menu_item(im_str!(\"Save\")).selected(&mut should_save).build();\n\n ui.menu_item(im_str!(\"Load\")).selected(&mut should_load).build();\n\n ui.menu_item(im_str!(\"Exit\")).selected(&mut should_exit).build();\n\n });\n\n ui.menu(im_str!(\"Edit Options\")).build(|| {\n\n ui.menu_item(im_str!(\"Mouse Placement\")).shortcut(im_str!(\"Ctrl+M\")).selected(&mut self.options.place_with_mouse).build();\n\n ui.menu_item(im_str!(\"Show Axis\")).shortcut(im_str!(\"Ctrl+A\")).selected(&mut self.options.show_axis).build();\n\n ui.menu_item(im_str!(\"Snap to grid\")).shortcut(im_str!(\"Ctrl+G\")).selected(&mut self.options.snap_to_grid).build();\n\n });\n\n ui.menu(im_str!(\"Run Options\")).build(|| {\n\n ui.menu_item(im_str!(\"Run\")).shortcut(im_str!(\"F6\")).selected(&mut self.run_game).build();\n\n });\n\n ui.menu(im_str!(\"Windows\")).build(|| {\n\n ui.menu_item(im_str!(\"Scene Details\")).selected(&mut self.windows.scene_details).build();\n\n ui.menu_item(im_str!(\"Model List\")).selected(&mut self.windows.model_list).build();\n\n ui.menu_item(im_str!(\"Loaded Models\")).selected(&mut self.windows.loaded_models).build();\n\n ui.menu_item(im_str!(\"World Objects\")).selected(&mut self.windows.world_objects).build();\n\n ui.menu_item(im_str!(\"Camera Options\")).selected(&mut self.windows.camera_options).build();\n\n ui.menu_item(im_str!(\"Light Options\")).selected(&mut self.windows.lights).build();\n", "file_path": "src/modules/scenes/editor_screen.rs", "rank": 82, "score": 5.021597221443621 }, { "content": " game.reset_scroll_value();\n\n for (reference, size) in &model_details {\n\n game.add_model_size(reference.to_string(), *size);\n\n }\n\n \n\n let events = graphics.get_events(Some(&mut imgui));\n\n let mouse_pos = graphics.get_mouse_position();\n\n \n\n game.set_mouse_position(mouse_pos);\n\n \n\n for ev in events {\n\n match &ev {\n\n winit::Event::WindowEvent{ event, .. } => {\n\n match event {\n\n winit::WindowEvent::CloseRequested => {\n\n done = true;\n\n },\n\n _ => {\n\n if game.handle_input(event) {\n\n done = true;\n", "file_path": "src/main.rs", "rank": 83, "score": 4.901850000904716 }, { "content": " object.set_position(cam_pos.xyz());\n\n }\n\n }\n\n }\n\n }\n\n \n\n if let Some(object) = &mut self.object_being_placed {\n\n object.update(ui, &self.instanced_buffers, self.data.window_dim, delta_time, &mut self.logs);\n\n }\n\n \n\n if self.object_selected > 1 {\n\n self.world_objects[self.object_selected as usize-2].update(ui, &self.instanced_buffers, self.data.window_dim, delta_time, &mut self.logs);\n\n }\n\n }\n\n }\n\n \n\n if self.data().imgui_info.wants_mouse {\n\n self.mouse_state = MouseState::Ui;\n\n } else {\n\n self.mouse_state = MouseState::World;\n", "file_path": "src/modules/scenes/editor_screen.rs", "rank": 84, "score": 4.858340994665367 }, { "content": " let mut draw_calls: Vec<DrawCall> = Vec::with_capacity(100);\n\n \n\n let mut delta_time;\n\n let mut last_time = time::Instant::now();\n\n let mut imgui_time = time::Instant::now();\n\n \n\n let mut done = false;\n\n let mut dimensions;\n\n \n\n let mut frame_counter = 0;\n\n let mut fps_timer = 0.0;\n\n let mut last_fps = 0.0;\n\n \n\n loop {\n\n delta_time = last_time.elapsed().subsec_nanos() as f64 / 1000000000.0 as f64;\n\n last_time = time::Instant::now();\n\n \n\n frame_counter += 1;\n\n fps_timer += delta_time;\n\n if fps_timer > 1.0 {\n", "file_path": "src/main.rs", "rank": 85, "score": 4.655963799320197 }, { "content": "\n\n#[macro_export]\n\nmacro_rules! hlua_error {\n\n ($result:expr) => (\n\n match $result {\n\n Err(hlua_e) => {\n\n match hlua_e {\n\n hlua::LuaError::SyntaxError(e) | hlua::LuaError:: ExecutionError(e) => {\n\n Some(e.to_string())\n\n },\n\n hlua::LuaError::ReadError(io_e) => {\n\n Some(io_e.to_string())\n\n },\n\n _ => {None}\n\n }\n\n },\n\n Ok(_) => {None},\n\n }\n\n )\n\n}\n", "file_path": "src/modules/world_object.rs", "rank": 86, "score": 4.475482486682184 }, { "content": " for object in &mut self.world_objects {\n\n object.load_script();\n\n }\n\n // Reset positions if went from game run to edit\n\n } else if !self.run_game && should_run {\n\n for object in &mut self.world_objects {\n\n object.reset();\n\n }\n\n }\n\n }\n\n \n\n if self.object_selected == 1 {\n\n if self.data.model_sizes.len() == 0 {\n\n self.object_selected = 0;\n\n } else if self.object_being_placed.is_none() {\n\n self.change_selected_object();\n\n }\n\n } else {\n\n self.object_being_placed = None;\n\n }\n", "file_path": "src/modules/scenes/editor_screen.rs", "rank": 87, "score": 4.3583275177971394 }, { "content": " \n\n lua.set(\"w_key\", self.data.keys.w_pressed());\n\n lua.set(\"a_key\", self.data.keys.a_pressed());\n\n lua.set(\"s_key\", self.data.keys.s_pressed());\n\n lua.set(\"d_key\", self.data.keys.d_pressed());\n\n }\n\n \n\n let mut i = 0;\n\n for world_object in &mut self.world_objects {\n\n world_object.update_game(&mut lua, &mut self.logs);\n\n \n\n if i == self.game_options.camera_target {\n\n self.camera.set_target(world_object.position());\n\n }\n\n \n\n i += 1;\n\n }\n\n \n\n },\n\n false => {\n", "file_path": "src/modules/scenes/editor_screen.rs", "rank": 88, "score": 4.330854463995267 }, { "content": "-- y\n\n-- z\n\n-- rot_x\n\n-- rot_y\n\n-- rot_z\n\n-- size_x\n\n-- size_y\n\n-- size_z\n\n-- vel_x\n\n-- vel_y\n\n-- vel_z\n\n-- acc_x\n\n-- acc_y\n\n-- acc_z\n\n\n\nfunction \".to_owned() + &self.name.to_string() + \"update()\n\n x = x + vel_x*delta_time;\n\n y = y + vel_y*delta_time;\n\n z = z + vel_z*delta_time;\n\n \n", "file_path": "src/modules/world_object.rs", "rank": 89, "score": 4.188524651960912 }, { "content": " world_objects: true,\n\n model_list: true,\n\n loaded_models: true,\n\n scene_details: true,\n\n camera_options: true,\n\n lights: true,\n\n load_window: true,\n\n saved: false,\n\n error_window: false,\n\n }\n\n }\n\n}\n\n\n\nimpl EditorOptions {\n\n pub fn new() -> EditorOptions {\n\n EditorOptions {\n\n snap_to_grid: false,\n\n show_axis: true,\n\n place_with_mouse: true,\n\n instanced_option: 0,\n", "file_path": "src/modules/scenes/editor_screen.rs", "rank": 90, "score": 4.137647971815094 }, { "content": " }\n\n \n\n game.set_window_dimensions(dimensions);\n\n \n\n graphics.prepare_imgui_ui(Some(&mut imgui));\n\n imgui_time = imgui.io_mut().update_delta_time(imgui_time);\n\n let ui = imgui.frame();\n\n \n\n game.draw(&mut draw_calls);\n\n game.update(Some(&ui), Some(&mut lua), delta_time as f32);\n\n \n\n benchmark(&mut draw_calls, dimensions);\n\n fps_overlay(&mut draw_calls, dimensions, last_fps);\n\n \n\n let model_details = graphics.pre_draw();\n\n graphics.draw(&draw_calls, Some(ui), delta_time as f32);\n\n graphics.post_draw();\n\n \n\n draw_calls.clear();\n\n \n", "file_path": "src/main.rs", "rank": 91, "score": 4.071665300766781 }, { "content": " self.mut_data().left_mouse_dragged = true;\n\n }\n\n \n\n if self.data().right_mouse {\n\n self.mut_data().right_mouse_dragged = true;\n\n }\n\n \n\n if self.data().middle_mouse {\n\n self.mut_data().middle_mouse_dragged = true;\n\n }\n\n \n\n match event {\n\n winit::WindowEvent::MouseWheel {device_id: _, delta, phase: _, modifiers: _} => {\n\n match delta {\n\n PixelDelta(scroll_delta) => {\n\n println!(\"Not used. Please contact [email protected]: {}\", scroll_delta.y);\n\n },\n\n LineDelta(_x, y) => {\n\n // Scroll Delta is either -1, 0 or 1\n\n self.mut_data().scroll_delta = *y;\n", "file_path": "src/modules/scenes/mod.rs", "rank": 92, "score": 4.062200361770161 }, { "content": " self.mut_data().left_mouse_dragged = false;\n\n }\n\n if *button == winit::MouseButton::Right {\n\n self.mut_data().right_mouse = false;\n\n self.mut_data().right_mouse_dragged = false;\n\n }\n\n if *button == winit::MouseButton::Middle {\n\n self.mut_data().middle_mouse = false;\n\n self.mut_data().middle_mouse_dragged = false;\n\n }\n\n }\n\n },\n\n _ => {},\n\n }\n\n let cp = self.data().currently_pressed.clone();\n\n let rr = self.data().released_this_render.clone();\n\n self.mut_data().keys.update_keys(cp, rr);\n\n \n\n self.data().should_close\n\n }\n\n \n\n fn get_keys_pressed_this_frame(&self) -> Vec<String> {\n\n self.data().keys.get_pressed_this_frame()\n\n }\n\n}\n", "file_path": "src/modules/scenes/mod.rs", "rank": 93, "score": 4.011249942084374 }, { "content": " middle_mouse: false,\n\n left_mouse_dragged: false,\n\n right_mouse_dragged: false,\n\n middle_mouse_dragged: false,\n\n window_dim: window_size,\n\n currently_pressed: Vec::new(),\n\n released_this_render: Vec::new(),\n\n keys: MappedKeys::new(),\n\n window_resized: false,\n\n controller: Controller::new(),\n\n model_sizes,\n\n imgui_info: ImGuiInfo { wants_mouse: false, wants_keyboard: false },\n\n models_to_load: Vec::new(),\n\n models_to_unload: Vec::new(),\n\n }\n\n }\n\n \n\n pub fn new_default() -> SceneData {\n\n SceneData {\n\n should_close: false,\n", "file_path": "src/modules/scenes/mod.rs", "rank": 94, "score": 3.8803617488515423 }, { "content": " \n\n match self.run_game {\n\n true => {\n\n if self.game_options.first_game_loop {\n\n for object in &mut self.world_objects {\n\n object.load_script();\n\n }\n\n self.camera.set_zoom(self.game_options.camera_distance);\n\n self.options.show_axis = false;\n\n self.game_options.first_game_loop = false;\n\n }\n\n \n\n if let Some(lua) = &mut lua {\n\n lua.set(\"delta_time\", delta_time);\n\n lua.set(\"mouse_x\", self.data.mouse_pos.x);\n\n lua.set(\"mouse_y\", self.data.mouse_pos.y);\n\n lua.set(\"left_mouse\", self.data.left_mouse);\n\n lua.set(\"right_mouse\", self.data.right_mouse);\n\n lua.set(\"window_dim_x\", self.data.window_dim.x);\n\n lua.set(\"window_dim_y\", self.data.window_dim.y);\n", "file_path": "src/modules/scenes/editor_screen.rs", "rank": 95, "score": 3.721777817751423 }, { "content": " }\n\n \n\n if self.windows.world_objects {\n\n ui.window(im_str!(\"World Objects\"))\n\n .size([200.0, 400.0], Condition::Appearing)\n\n .position([0.0, 140.0], Condition::Appearing)\n\n .build(|| {\n\n ui.text(\"None\");\n\n ui.same_line(0.0);\n\n ui.radio_button(&im_str!(\"##0\"), &mut self.object_selected, 0);\n\n ui.text(\"Placing New\");\n\n ui.same_line(0.0);\n\n ui.radio_button(im_str!(\"Key 1##1\"), &mut self.object_selected, 1);\n\n let mut should_delete_object = false;\n\n for i in 0..self.world_objects.len() {\n\n ui.text(im_str!(\"{}: {}\", self.world_objects[i].id(), self.world_objects[i].name()));\n\n ui.same_line(0.0);\n\n ui.radio_button(&im_str!(\"##{}\", i+2), &mut self.object_selected, i as i32+2);\n\n if self.object_selected == i as i32 +2 {\n\n ui.same_line(0.0);\n", "file_path": "src/modules/scenes/editor_screen.rs", "rank": 96, "score": 3.701941966184869 }, { "content": " items.remove(i-offset);\n\n offset+=1;\n\n }\n\n }\n\n \n\n let items: Vec<&ImString> = items.iter().map(|p| \n\n p//.as_ref()\n\n ).collect::<Vec<&ImString>>();\n\n \n\n ui.combo(im_str!(\"##\"), &mut self.options.instanced_option, &items[..], -1);\n\n ui.same_line(0.0);\n\n if self.options.instanced_option > items.len() as i32-1 {\n\n self.options.instanced_option = items.len() as i32-1;\n\n }\n\n \n\n if ui.button(im_str!(\"Add Buffer\"), [0.0, 0.0]) {\n\n // Actually add buffer\n\n let buffer = items[self.options.instanced_option as usize].to_str();\n\n self.instanced_buffers_added.push(buffer.to_string());\n\n }\n", "file_path": "src/modules/scenes/editor_screen.rs", "rank": 97, "score": 3.6707897696764524 }, { "content": " if self.rotation_edit {\n\n loop {\n\n if ui.get_column_index() == 0 {\n\n break;\n\n }\n\n ui.next_column();\n\n }\n\n ui.text(im_str!(\"Rotation\"));\n\n ui.next_column();\n\n ui.text(im_str!(\"X:\"));\n\n ui.same_line(0.0);\n\n ui.input_float(im_str!(\"##rotx\"), &mut self.rotation.x).build();\n\n ui.next_column();\n\n ui.text(im_str!(\"Y:\"));\n\n ui.same_line(0.0);\n\n ui.input_float(im_str!(\"##roty\"), &mut self.rotation.y).build();\n\n ui.next_column();\n\n ui.text(im_str!(\"Z:\"));\n\n ui.same_line(0.0);\n\n ui.input_float(im_str!(\"##rotz\"), &mut self.rotation.z).build();\n", "file_path": "src/modules/world_object.rs", "rank": 98, "score": 3.5127149349097033 }, { "content": " ui.text(im_str!(\"y:\"));\n\n ui.same_line(0.0);\n\n ui.input_float(im_str!(\"##y\"), &mut self.position.y).build();\n\n ui.next_column();\n\n ui.text(im_str!(\"z:\"));\n\n ui.same_line(0.0);\n\n ui.input_float(im_str!(\"##z\"), &mut self.position.z).build();\n\n ui.columns(1, im_str!(\"\"), false);\n\n ui.new_line();\n\n ui.text(im_str!(\"Intensity:\"));\n\n ui.same_line(0.0);\n\n ui.slider_float(im_str!(\"\"), &mut self.intensity, 0.1, 1000.0).build();\n\n ui.new_line();\n\n ui.tree_node(im_str!(\"Light Colour\")).build(|| {\n\n let mut colour = [self.colour.x, self.colour.y, self.colour.z];\n\n ui.color_picker(im_str!(\"Colour\"), &mut colour).build();\n\n self.colour = Vector3::new(colour[0], colour[1], colour[2]);\n\n });\n\n });\n\n }\n\n }\n\n \n\n pub fn draw(&self, draw_calls: &mut Vec<DrawCall>) {\n\n draw_calls.push(DrawCall::set_light(self.position, self.colour, self.intensity));\n\n }\n\n}\n", "file_path": "src/modules/light_object.rs", "rank": 99, "score": 3.508941506166453 } ]
Rust
src/nodes/item.rs
olefasting/rust_rpg_toolkit
3f82a0fd4175f0b65518ceda1319416d5bf0ae1b
use crate::prelude::*; #[derive(Debug, Clone, PartialEq, Serialize, Deserialize)] #[serde(rename_all = "snake_case")] pub enum ItemKind { OneHandedWeapon, TwoHandedWeapon, Misc, } #[derive(Debug, Clone, Serialize, Deserialize)] pub struct ItemParams { pub id: String, pub name: String, pub description: String, #[serde( default, with = "json::opt_vec2", skip_serializing_if = "Option::is_none" )] pub position: Option<Vec2>, pub kind: ItemKind, pub weight: f32, #[serde(default, rename = "ability", skip_serializing_if = "Option::is_none")] pub ability_id: Option<String>, pub sprite: Sprite, #[serde(default)] pub is_quest_item: bool, } impl Default for ItemParams { fn default() -> Self { ItemParams { id: "".to_string(), name: "Unnamed Item".to_string(), description: "".to_string(), position: Default::default(), kind: ItemKind::Misc, weight: 0.1, ability_id: None, sprite: Default::default(), is_quest_item: false, } } } #[derive(Clone)] pub struct Item { pub id: String, pub name: String, pub description: String, pub position: Vec2, pub kind: ItemKind, pub weight: f32, pub is_quest_item: bool, ability: Option<AbilityParams>, sprite: Sprite, } impl Item { pub fn new(params: ItemParams) -> Self { let resources = storage::get::<Resources>(); let ability = if let Some(ability_id) = params.ability_id { Some(resources.abilities.get(&ability_id).cloned().unwrap()) } else { None }; Item { id: params.id, position: params.position.unwrap_or_default(), kind: params.kind, name: params.name, description: params.description, weight: params.weight, is_quest_item: params.is_quest_item, ability, sprite: params.sprite, } } pub fn add_node(params: ItemParams) -> Handle<Self> { scene::add_node(Self::new(params)) } pub fn to_params(&self) -> ItemParams { let ability_id = self.ability.as_ref().map(|ability| ability.id.clone()); ItemParams { id: self.id.clone(), name: self.name.clone(), description: self.description.clone(), position: Some(self.position), kind: self.kind.clone(), weight: self.weight, ability_id, sprite: self.sprite.clone(), is_quest_item: self.is_quest_item, } } } impl BufferedDraw for Item { fn buffered_draw(&mut self) { self.sprite.draw(self.position, 0.0); } fn get_z_index(&self) -> f32 { self.position.y } fn get_bounds(&self) -> Bounds { Bounds::Point(self.position) } } impl Node for Item { fn draw(node: RefMut<Self>) { let mut draw_buffer = scene::find_node_by_type::<DrawBuffer<Self>>().unwrap(); draw_buffer.buffered.push(node.handle()); } } #[derive(Debug, Clone)] pub struct Credits { pub position: Vec2, pub amount: u32, pub sprite: Sprite, } impl Credits { pub fn new(position: Vec2, amount: u32) -> Self { Credits { position, amount, sprite: Sprite { texture_id: "credits".to_string(), tile_size: uvec2(8, 8), ..Default::default() }, } } pub fn add_node(position: Vec2, amount: u32) -> Handle<Self> { scene::add_node(Self::new(position, amount)) } } impl BufferedDraw for Credits { fn buffered_draw(&mut self) { self.sprite.draw(self.position, 0.0); } fn get_z_index(&self) -> f32 { self.position.y } fn get_bounds(&self) -> Bounds { Bounds::Point(self.position) } } impl Node for Credits { fn ready(node: RefMut<Self>) { let mut draw_buffer = scene::find_node_by_type::<DrawBuffer<Credits>>().unwrap(); draw_buffer.buffered.push(node.handle()); } }
use crate::prelude::*; #[derive(Debug, Clone, PartialEq, Serialize, Deserialize)] #[serde(rename_all = "snake_case")] pub enum ItemKind { OneHandedWeapon, TwoHandedWeapon, Misc, } #[derive(Debug, Clone, Serialize, Deserialize)] pub struct ItemParams { pub id: String, pub name: String, pub description: String, #[serde( default, with = "json::opt_vec2", skip_serializing_if = "Option::is_none" )] pub position: Option<Vec2>, pub kind: ItemKind, pub weight: f32, #[serde(default, rename = "ability", skip_serializing_if = "Option::is_none")] pub ability_id: Option<String>, pub sprite: Sprite, #[serde(default)] pub is_quest_item: bool, } impl Default for ItemParams { fn default() -> Self { ItemParams { id: "".to_string(), name: "Unnamed Item".to_string(), description: "".to_string(), position: Default::default(), kind: ItemKind::Misc, weight: 0.1, ability_id: None, sprite: Default::default(), is_quest_item: false, } } } #[derive(Clone)] pub struct Item { pub id: String, pub name: String, pub description: String, pub position: Vec2, pub kind: ItemKind, pub weight: f32, pub is_quest_item: bool, ability: Option<AbilityParams>, sprite: Sprite, } impl Item { pub fn new(params: ItemParams) -> Self { let resources = storage::get::<Resources>(); let ability = if let Some(ability_id) = params.ability_id { Some(resources.abilities.get(&ability_id).cloned().unwrap()) } else { None }; Item { id: params.id, position: params.position.unwrap_or_default(), kind: params.kind, name: params.name, description: params.description, weight: params.weight, is_quest_item: params.is_quest_item, ability, sprite: params.sprite, } } pub fn add_node(params: ItemParams) -> Handle<Self> { scene::add_node(Self::new(params)) } pub fn to_params(&self) -> ItemParams { let ability_id = self.ability.as_ref().map(|ability| ability.id.clone()); ItemParams { id: self.id.clone(), name: self.name.clone(), description: self.description.clone(), position: Some(self.position), kind: self.kind.clone(), weight: self.weight, ability_id, sprite: self.sprite.clone(), is_quest_item: self.is_quest_item, } } } impl BufferedDraw for Item { fn buffered_draw(&mut self) { self.sprite.draw(self.position, 0.0); } fn get_z_index(&self) -> f32 { self.position.y } fn get_bounds(&self) -> Bounds { Bounds::Point(self.position) } } impl Node for Item { fn draw(node: RefMut<Self>) { let mut draw_buffer = scene::find_node_by_type::<DrawBuffer<Self>>().unwrap(); draw_buffer.buffered.push(node.handle()); } } #[derive(Debug, Clone)] pub struct Credits { pub position: Vec2, pub amount: u32, pub sprite: Sprite, } impl Credits { pub fn new(position: Vec2, amount: u32) -> Self { Credits { position, amount, sprite: Sprite {
pub fn add_node(position: Vec2, amount: u32) -> Handle<Self> { scene::add_node(Self::new(position, amount)) } } impl BufferedDraw for Credits { fn buffered_draw(&mut self) { self.sprite.draw(self.position, 0.0); } fn get_z_index(&self) -> f32 { self.position.y } fn get_bounds(&self) -> Bounds { Bounds::Point(self.position) } } impl Node for Credits { fn ready(node: RefMut<Self>) { let mut draw_buffer = scene::find_node_by_type::<DrawBuffer<Credits>>().unwrap(); draw_buffer.buffered.push(node.handle()); } }
texture_id: "credits".to_string(), tile_size: uvec2(8, 8), ..Default::default() }, } }
function_block-function_prefix_line
[ { "content": "pub fn default_behavior_set() -> String {\n\n DEFAULT_BEHAVIOR_SET_ID.to_string()\n\n}\n\n\n\n#[derive(Debug, Clone, Serialize, Deserialize)]\n\npub struct ActorBehaviorParams {\n\n pub aggression: ActorAggression,\n\n #[serde(\n\n default,\n\n with = \"json::opt_vec2\",\n\n skip_serializing_if = \"Option::is_none\"\n\n )]\n\n pub home: Option<Vec2>,\n\n #[serde(default = \"default_behavior_set\", rename = \"behavior_set\")]\n\n pub behavior_set_id: String,\n\n #[serde(default)]\n\n pub is_stationary: bool,\n\n #[serde(default)]\n\n pub is_on_guard: bool,\n\n #[serde(default)]\n", "file_path": "src/nodes/actor/behavior.rs", "rank": 0, "score": 218335.24829095535 }, { "content": "pub fn generate_id() -> String {\n\n let mut chars = Vec::with_capacity(UID_LENGTH);\n\n\n\n for _ in 0..UID_LENGTH {\n\n let i: usize = rand::gen_range(0, UID_CHARS_LEN);\n\n chars.push(UID_CHARS[i]);\n\n }\n\n\n\n chars.iter().collect::<String>()\n\n}\n\n\n\n\n", "file_path": "src/helpers.rs", "rank": 1, "score": 202600.84541501888 }, { "content": "pub fn apply_input(_player_id: &str, node: &mut RefMut<Actor>) {\n\n let mut game_state = scene::find_node_by_type::<GameState>().unwrap();\n\n\n\n let mouse_position = get_mouse_in_world_space();\n\n\n\n node.controller.should_use_weapon = is_mouse_button_down(MouseButton::Left);\n\n node.controller.should_use_selected_ability = is_mouse_button_down(MouseButton::Right);\n\n\n\n node.controller.move_direction = Vec2::ZERO;\n\n if is_key_down(KeyCode::Up) || is_key_down(KeyCode::W) {\n\n node.controller.move_direction.y -= 1.0;\n\n }\n\n if is_key_down(KeyCode::Down) || is_key_down(KeyCode::S) {\n\n node.controller.move_direction.y += 1.0;\n\n }\n\n if is_key_down(KeyCode::Left) || is_key_down(KeyCode::A) {\n\n node.controller.move_direction.x -= 1.0;\n\n }\n\n if is_key_down(KeyCode::Right) || is_key_down(KeyCode::D) {\n\n node.controller.move_direction.x += 1.0;\n", "file_path": "src/input.rs", "rank": 2, "score": 201999.10808788348 }, { "content": "pub fn get_mouse_position() -> Vec2 {\n\n let (x, y) = mouse_position();\n\n vec2(x, y)\n\n}\n\n\n", "file_path": "src/input.rs", "rank": 3, "score": 197436.73783466066 }, { "content": "pub fn rotate_vector(vec: Vec2, rad: f32) -> Vec2 {\n\n let sa = rad.sin();\n\n let ca = rad.cos();\n\n vec2(ca * vec.x - sa * vec.y, sa * vec.x + ca * vec.y)\n\n}\n\n\n", "file_path": "src/math/vector.rs", "rank": 4, "score": 195022.83298941937 }, { "content": "pub fn get_beam_end(origin: Vec2, end: Vec2, width: f32, tolerance: f32) -> Vec2 {\n\n let map = storage::get::<Map>();\n\n let tile_size = map.tile_size;\n\n let collider = {\n\n let ((x, w), (y, h)) = (\n\n if origin.x > end.x {\n\n (end.x, origin.x)\n\n } else {\n\n (origin.x, end.x)\n\n },\n\n if origin.y > end.y {\n\n (end.y, origin.y)\n\n } else {\n\n (origin.y, end.y)\n\n },\n\n );\n\n Collider::rect(x, y, w, h)\n\n };\n\n\n\n let mut collisions: Vec<Vec2> = map\n", "file_path": "src/physics/beam.rs", "rank": 5, "score": 193932.28356466678 }, { "content": "pub fn get_centered(size: Vec2, bounds: Vec2) -> Vec2 {\n\n (bounds - size) / 2.0\n\n}\n\n\n", "file_path": "src/gui/mod.rs", "rank": 6, "score": 191129.59944550725 }, { "content": "pub fn sort_by_distance(position: Vec2, a: &Vec2, b: &Vec2) -> Ordering {\n\n a.distance(position)\n\n .partial_cmp(&b.distance(position))\n\n .unwrap()\n\n}\n\n\n", "file_path": "src/helpers.rs", "rank": 7, "score": 188440.73727098 }, { "content": "pub fn draw_confirmation_modal(ui: &mut Ui, body: Vec<String>) -> Option<bool> {\n\n let mut res = None;\n\n\n\n let mut size = vec2(\n\n 0.0,\n\n GuiSkins::BUTTON_HEIGHT + GuiSkins::ELEMENT_MARGIN + GuiSkins::WINDOW_MARGIN_Y * 2.0,\n\n );\n\n\n\n for line in &body {\n\n let line_size = ui.calc_size(line);\n\n\n\n if line_size.x + 50.0 > size.x {\n\n size.x = line_size.x + 50.0;\n\n }\n\n\n\n size.y += line_size.y;\n\n }\n\n\n\n let position = get_centered_on_screen(size);\n\n\n", "file_path": "src/gui/confirmation_modal.rs", "rank": 8, "score": 185282.2464887252 }, { "content": "pub fn use_default_material() {\n\n gl_use_default_material()\n\n}\n\n\n", "file_path": "src/render/material.rs", "rank": 9, "score": 180509.70039653493 }, { "content": "// Used in serde attributes to skip serialization of bools that are false\n\npub fn is_false(value: &bool) -> bool {\n\n *value\n\n}\n\n\n", "file_path": "src/helpers.rs", "rank": 10, "score": 171869.87411211687 }, { "content": "pub fn get_timestamp() -> String {\n\n chrono::Utc::now().to_string()\n\n}\n\n\n\nconst UID_CHARS_LEN: usize = 36;\n\nconst UID_LENGTH: usize = 16;\n\nconst UID_CHARS: [char; 36] = [\n\n 'a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n', 'o', 'p', 'q', 'r', 's',\n\n 't', 'u', 'v', 'w', 'x', 'y', 'z', '0', '1', '2', '3', '4', '5', '6', '7', '8', '9',\n\n];\n\n\n", "file_path": "src/helpers.rs", "rank": 11, "score": 167641.59840487703 }, { "content": "pub fn deg_to_rad(deg: f32) -> f32 {\n\n deg * std::f32::consts::PI / 180.0\n\n}\n\n\n", "file_path": "src/math/vector.rs", "rank": 12, "score": 165073.88470439514 }, { "content": "pub fn rad_to_deg(rad: f32) -> f32 {\n\n (rad * 180.0) / std::f32::consts::PI\n\n}\n", "file_path": "src/math/vector.rs", "rank": 13, "score": 165073.88470439514 }, { "content": "pub fn get_toolkit_version() -> String {\n\n format!(\n\n \"{}.{}.{}\",\n\n env!(\"CARGO_PKG_VERSION_MAJOR\"),\n\n env!(\"CARGO_PKG_VERSION_MINOR\"),\n\n env!(\"CARGO_PKG_VERSION_PATCH\"),\n\n )\n\n}\n\n\n", "file_path": "src/versions.rs", "rank": 14, "score": 163723.92209882164 }, { "content": "pub fn get_centered_on_screen(size: Vec2) -> Vec2 {\n\n let bounds = vec2(get_screen_width(), get_screen_height());\n\n get_centered(size, bounds)\n\n}\n", "file_path": "src/gui/mod.rs", "rank": 15, "score": 161924.7333318182 }, { "content": "pub fn get_mouse_in_world_space() -> Vec2 {\n\n let viewport = storage::get::<Viewport>();\n\n viewport.to_world_space(get_mouse_position())\n\n}\n", "file_path": "src/input.rs", "rank": 16, "score": 160103.61311673315 }, { "content": "pub fn character_name_to_path(name: &str) -> PathBuf {\n\n let game_params = storage::get::<GameParams>();\n\n Path::new(&game_params.characters_path).join(&format!(\"{}.json\", name))\n\n}\n\n\n", "file_path": "src/character.rs", "rank": 17, "score": 153194.2828929858 }, { "content": "pub fn to_int_version(version: &str) -> u32 {\n\n let regex = Regex::new(r\"(?P<major>[0-9]+).(?P<minor>[0-9]+)(.(?P<patch>[0-9]+))?\").unwrap();\n\n let captures = regex\n\n .captures(version)\n\n .expect(&format!(\"Invalid version string '{}'!\", version));\n\n\n\n let major = captures[\"major\"].parse::<u32>().unwrap();\n\n let minor = captures[\"minor\"].parse::<u32>().unwrap();\n\n let patch = if let Some(res) = captures.name(\"patch\") {\n\n res.as_str().parse::<u32>().unwrap()\n\n } else {\n\n 0\n\n };\n\n\n\n (major << 24) + (minor << 16) + patch\n\n}\n", "file_path": "src/versions.rs", "rank": 18, "score": 148499.27118732847 }, { "content": "#[cfg(target_family = \"wasm\")]\n\npub fn delete_character(name: &str) -> Result<()> {\n\n let game_params = storage::get::<GameParams>();\n\n let storage = &mut quad_storage::STORAGE.lock().unwrap();\n\n let save_name = format!(\"{}_character\", game_params.game_name);\n\n storage.remove(save_name);\n\n\n\n Ok(())\n\n}\n", "file_path": "src/character.rs", "rank": 19, "score": 148447.38271404605 }, { "content": "// Returns a modules index in the active_modules vector, calculated from either the entry\n\n// id, or the id of the drop-zone before the entry, as well as a bool that will be true\n\n// if the id was for the modules entry in the module list\n\nfn id_to_module_index(id: u64) -> (usize, bool) {\n\n if id % 2 == 0 {\n\n ((id as usize / 2) - 1, true)\n\n } else {\n\n (((id as usize - 1) / 2) - 1, false)\n\n }\n\n}\n\n\n", "file_path": "src/gui/main_menu/module_management.rs", "rank": 20, "score": 146160.86840896675 }, { "content": "pub fn get_volume(category: VolumeCategory) -> f32 {\n\n let config = storage::get::<Config>();\n\n let master_volume = config.master_volume as f32 / 100.0;\n\n match category {\n\n VolumeCategory::SoundEffect => (config.sound_effects_volume as f32 / 100.0) * master_volume,\n\n VolumeCategory::Music => (config.music_volume as f32 / 100.0) * master_volume,\n\n }\n\n}\n\n\n\npub async fn load_sound_from_bytes(category: VolumeCategory, bytes: &[u8]) -> Result<Sound> {\n\n let sound = audio::load_sound_from_bytes(bytes).await?;\n\n\n\n let res = Sound { sound, category };\n\n\n\n Ok(res)\n\n}\n\n\n\npub async fn load_sound<P: AsRef<Path>>(category: VolumeCategory, path: P) -> Result<Sound> {\n\n let path = path.as_ref();\n\n let bytes = load_file(path).await?;\n\n\n\n load_sound_from_bytes(category, &bytes).await\n\n}\n\n\n", "file_path": "src/audio.rs", "rank": 21, "score": 145018.22373452748 }, { "content": "pub fn play_sound(sound: Sound, should_loop: bool) {\n\n sound.play(should_loop);\n\n}\n", "file_path": "src/audio.rs", "rank": 22, "score": 140631.09643992904 }, { "content": "pub trait BufferedDraw: Node {\n\n fn buffered_draw(&mut self);\n\n\n\n fn get_z_index(&self) -> f32;\n\n\n\n fn get_bounds(&self) -> Bounds;\n\n\n\n fn is_in_frustum(&self, frustum: &Rect) -> bool {\n\n match self.get_bounds() {\n\n Bounds::Point(vec) => frustum.contains(vec),\n\n Bounds::Rectangle(rect) => frustum.overlaps(&rect),\n\n Bounds::Circle(circle) => circle.overlaps_rect(frustum),\n\n Bounds::Collider(collider) => collider.overlaps_rect(frustum),\n\n }\n\n }\n\n}\n\n\n\npub struct DrawBuffer<T: 'static + BufferedDraw> {\n\n pub buffered: Vec<Handle<T>>,\n\n}\n", "file_path": "src/nodes/draw_buffer.rs", "rank": 23, "score": 139836.22631608378 }, { "content": "pub fn get_button_builder(id: &str) -> ButtonBuilder {\n\n try_get_button_builder(id).unwrap()\n\n}\n\n\n\n#[derive(Default, Clone)]\n\npub struct ButtonBuilder {\n\n position: Option<Vec2>,\n\n label: Option<String>,\n\n style: ButtonStyle,\n\n is_highlighted: bool,\n\n is_inactive: bool,\n\n}\n\n\n\nimpl ButtonBuilder {\n\n pub fn new() -> Self {\n\n ButtonBuilder {\n\n position: None,\n\n label: None,\n\n style: Default::default(),\n\n is_highlighted: false,\n", "file_path": "src/gui/button_builder.rs", "rank": 24, "score": 136098.04089029584 }, { "content": "pub fn check_version(req: &str, version: &str) -> bool {\n\n if req.starts_with(\"^\") {\n\n return to_int_version(&req[1..req.len()]) <= to_int_version(version);\n\n }\n\n to_int_version(&req) == to_int_version(version)\n\n}\n\n\n", "file_path": "src/versions.rs", "rank": 25, "score": 133777.37047569783 }, { "content": "pub fn get_behavior_set(id: &str) -> ActorBehaviorConstructor {\n\n try_get_behavior_set(id).unwrap()\n\n}\n\n\n", "file_path": "src/behavior_sets/mod.rs", "rank": 26, "score": 133509.4813181327 }, { "content": "pub fn register_button_builder(id: &str, builder: ButtonBuilder) {\n\n unsafe {\n\n get_directory().insert(id.to_string(), builder);\n\n }\n\n}\n\n\n", "file_path": "src/gui/button_builder.rs", "rank": 27, "score": 129125.36136334532 }, { "content": "fn get_directory() -> &'static mut HashMap<String, ActorBehaviorConstructor> {\n\n unsafe {\n\n if DIRECTORY.is_none() {\n\n DIRECTORY = Some(HashMap::new());\n\n DIRECTORY\n\n .as_mut()\n\n .unwrap()\n\n .insert(DEFAULT_BEHAVIOR_SET_ID.to_string(), || {\n\n Box::new(IdleMode::new())\n\n });\n\n }\n\n\n\n DIRECTORY.as_mut().unwrap()\n\n }\n\n}\n\n\n", "file_path": "src/behavior_sets/mod.rs", "rank": 28, "score": 127914.85817114596 }, { "content": "pub fn use_material(material: &Material) -> Result<()> {\n\n material.use_material()\n\n}\n", "file_path": "src/render/material.rs", "rank": 29, "score": 126970.50389723113 }, { "content": "pub fn register_behavior_set(id: &str, constructor: ActorBehaviorConstructor) {\n\n let dir = get_directory();\n\n dir.insert(id.to_string(), constructor);\n\n}\n", "file_path": "src/behavior_sets/mod.rs", "rank": 30, "score": 126690.99876672355 }, { "content": "pub fn try_get_button_builder(id: &str) -> Option<ButtonBuilder> {\n\n unsafe { get_directory().get(id).cloned() }\n\n}\n\n\n", "file_path": "src/gui/button_builder.rs", "rank": 31, "score": 126690.99876672355 }, { "content": "pub fn get_default_behavior_set() -> ActorBehaviorConstructor {\n\n get_behavior_set(DEFAULT_BEHAVIOR_SET_ID)\n\n}\n\n\n", "file_path": "src/behavior_sets/mod.rs", "rank": 32, "score": 125657.13861126709 }, { "content": "pub fn try_get_behavior_set(id: &str) -> Option<ActorBehaviorConstructor> {\n\n let dir = get_directory();\n\n dir.get(id).cloned()\n\n}\n\n\n", "file_path": "src/behavior_sets/mod.rs", "rank": 33, "score": 124397.45368732655 }, { "content": "pub fn get_player_actor() -> Option<RefMut<Actor>> {\n\n let player = storage::get::<LocalPlayer>();\n\n Actor::find_by_player_id(&player.id)\n\n}\n", "file_path": "src/player.rs", "rank": 34, "score": 123799.3820147218 }, { "content": "pub fn color_from_hex_string(str: &str) -> Color {\n\n let str = if str.starts_with('#') {\n\n str[1..str.len()].to_string()\n\n } else {\n\n str.to_string()\n\n };\n\n\n\n let r = u8::from_str_radix(&str[0..2], 16).unwrap();\n\n let g = u8::from_str_radix(&str[2..4], 16).unwrap();\n\n let b = u8::from_str_radix(&str[4..6], 16).unwrap();\n\n let a = if str.len() > 6 {\n\n u8::from_str_radix(&str[6..8], 16).unwrap()\n\n } else {\n\n 255\n\n };\n\n\n\n Color::new(\n\n r as f32 / 255.0,\n\n g as f32 / 255.0,\n\n b as f32 / 255.0,\n", "file_path": "src/render/helpers.rs", "rank": 35, "score": 123774.70581391129 }, { "content": "fn default_filter_mode() -> FilterMode {\n\n FilterMode::Nearest\n\n}\n\n\n\n#[derive(Debug, Clone, Serialize, Deserialize)]\n\npub struct TextureAssetParams {\n\n pub id: String,\n\n pub path: String,\n\n #[serde(default, skip_serializing_if = \"Option::is_none\")]\n\n pub height_map_path: Option<String>,\n\n #[serde(default, skip_serializing_if = \"Option::is_none\")]\n\n pub normal_map_path: Option<String>,\n\n #[serde(default = \"default_filter_mode\", with = \"json::FilterModeDef\")]\n\n pub filter_mode: FilterMode,\n\n}\n\n\n\n#[derive(Debug, Clone, Serialize, Deserialize)]\n\npub struct ImageAssetParams {\n\n pub id: String,\n\n pub path: String,\n", "file_path": "src/resources.rs", "rank": 36, "score": 123469.44803201323 }, { "content": "pub fn raycast(\n\n origin: Vec2,\n\n end: Vec2,\n\n ignore_barriers: bool,\n\n ignore_actors: bool,\n\n) -> Option<Vec2> {\n\n if origin.distance(end) > COLLISION_RESOLUTION {\n\n let map = storage::get::<Map>();\n\n let direction = end.sub(origin).normalize_or_zero();\n\n let collider = Collider::circle(0.0, 0.0, 1.0);\n\n let change = direction * COLLISION_RESOLUTION;\n\n let mut current = origin;\n\n while current.distance(end) > COLLISION_RESOLUTION {\n\n let collider = collider.with_offset(current);\n\n for (_, kind) in map.get_collisions(collider) {\n\n if !ignore_barriers || kind == CollisionKind::Solid {\n\n return Some(current);\n\n }\n\n }\n\n if !ignore_actors {\n", "file_path": "src/physics/raycast.rs", "rank": 37, "score": 118665.19405229861 }, { "content": "pub fn begin_frame() {\n\n clear_background(color::BLACK);\n\n draw_gui();\n\n}\n\n\n\npub async fn end_frame() {\n\n next_frame().await;\n\n}\n", "file_path": "src/game.rs", "rank": 38, "score": 118665.19405229861 }, { "content": "pub fn draw_text(\n\n text: &str,\n\n position: Vec2,\n\n ha: HorizontalAlignment,\n\n va: VerticalAlignment,\n\n params: TextParams,\n\n) {\n\n let measure = get_text_measure(text, Some(params.font), params.font_size, params.font_scale);\n\n\n\n let x = match ha {\n\n HorizontalAlignment::Left => position.x,\n\n _ => {\n\n if ha == HorizontalAlignment::Center {\n\n position.x - (measure.width / 2.0)\n\n } else {\n\n position.x - measure.width\n\n }\n\n }\n\n };\n\n let y = match va {\n\n VerticalAlignment::Top => position.y + measure.height,\n\n VerticalAlignment::Center => position.y + measure.height / 2.0,\n\n _ => position.y,\n\n };\n\n\n\n draw_text_ex(text, x, y, params);\n\n}\n\n\n", "file_path": "src/render/helpers.rs", "rank": 39, "score": 115851.53961263897 }, { "content": "pub fn draw_texture(\n\n texture: &Texture,\n\n position: Vec2,\n\n color: Option<Color>,\n\n params: DrawTextureParams,\n\n) {\n\n texture.draw(position, color, params)\n\n}\n", "file_path": "src/render/texture.rs", "rank": 40, "score": 115851.53961263897 }, { "content": "pub fn beam_collision_check(\n\n point: Vec2,\n\n origin: Vec2,\n\n end: Vec2,\n\n width: f32,\n\n tolerance: f32,\n\n) -> bool {\n\n let va = origin - end;\n\n let vb = point - end;\n\n let area = va.x * vb.y - va.y * vb.x;\n\n area.abs() < width * tolerance\n\n}\n\n\n", "file_path": "src/physics/beam.rs", "rank": 41, "score": 113249.63944309216 }, { "content": "pub fn draw_progress_bar(\n\n current_value: f32,\n\n max_value: f32,\n\n position: Vec2,\n\n length: f32,\n\n height: f32,\n\n color: Color,\n\n bg_color: Color,\n\n border: f32,\n\n alignment: HorizontalAlignment,\n\n text: Option<&str>,\n\n text_params: Option<TextParams>,\n\n) {\n\n assert!(\n\n border * 2.0 < height && border * 2.0 < length,\n\n \"Progress bar length and height must be greater than border * 2\"\n\n );\n\n {\n\n let coords = match alignment {\n\n HorizontalAlignment::Left => (position.x, position.y, position.x + length, position.y),\n", "file_path": "src/render/helpers.rs", "rank": 42, "score": 113249.63944309216 }, { "content": "pub fn draw_inventory_window() {\n\n if let Some(game_state) = scene::find_node_by_type::<GameState>() {\n\n if game_state.gui_state.should_draw_inventory_window {\n\n if let Some(mut player) = get_player_actor() {\n\n let gui_skins = storage::get::<GuiSkins>();\n\n\n\n let size = vec2(300.0, 400.0);\n\n let position = vec2(50.0, 475.0);\n\n\n\n root_ui().push_skin(&gui_skins.default);\n\n\n\n WindowBuilder::new(hash!(), size)\n\n .with_pos(position, false)\n\n .build(&mut *root_ui(), |ui| {\n\n ui.label(\n\n None,\n\n &format!(\n\n \"credits: {}, weight: {}/{}\",\n\n player.inventory.credits,\n\n player.inventory.get_total_weight(),\n", "file_path": "src/gui/inventory.rs", "rank": 43, "score": 113249.63944309216 }, { "content": "pub fn draw_character_window() {\n\n if let Some(game_state) = scene::find_node_by_type::<GameState>() {\n\n if game_state.gui_state.should_draw_character_window {\n\n if let Some(player) = get_player_actor() {\n\n let gui_skins = storage::get::<GuiSkins>();\n\n\n\n let size = vec2(300.0, 300.0);\n\n let position = vec2(50.0, 150.0);\n\n\n\n root_ui().push_skin(&gui_skins.default);\n\n\n\n WindowBuilder::new(hash!(), size)\n\n .with_pos(position, false)\n\n .build(&mut *root_ui(), |ui| {\n\n ui.label(None, &format!(\"STR: {}\", player.stats.strength));\n\n ui.label(None, &format!(\"DEX: {}\", player.stats.dexterity));\n\n ui.label(None, &format!(\"CON: {}\", player.stats.constitution));\n\n ui.label(None, &format!(\"INT: {}\", player.stats.intelligence));\n\n ui.label(None, &format!(\"WIL: {}\", player.stats.willpower));\n\n ui.label(None, &format!(\"PER: {}\", player.stats.perception));\n", "file_path": "src/gui/character.rs", "rank": 44, "score": 113249.63944309216 }, { "content": "pub fn draw_dialogue_window() {\n\n if let Some(mut player) = get_player_actor() {\n\n if let Some(dialogue) = player.current_dialogue.clone() {\n\n let gui_skins = storage::get::<GuiSkins>();\n\n\n\n let size = vec2(400.0, 350.0);\n\n\n\n root_ui().push_skin(&gui_skins.default);\n\n\n\n WindowBuilder::new(hash!(), size)\n\n .with_centered_pos(true)\n\n .build(&mut *root_ui(), |ui| {\n\n if !dialogue.body.is_empty() {\n\n ui.label(None, &format!(\"{}:\", player.name));\n\n }\n\n\n\n for line in dialogue.body.clone() {\n\n ui.label(None, &format!(\" {}\", line));\n\n }\n\n\n", "file_path": "src/gui/dialogue.rs", "rank": 45, "score": 113249.63944309216 }, { "content": "pub fn draw_game_menu() {\n\n if let Some(mut game_state) = scene::find_node_by_type::<GameState>() {\n\n if game_state.gui_state.should_draw_game_menu {\n\n let gui_skins = storage::get::<GuiSkins>();\n\n let params = gui_skins\n\n .theme\n\n .menu_params\n\n .get(\"game_menu\")\n\n .cloned()\n\n .unwrap();\n\n let builder = MenuBuilder::new(hash!(), params);\n\n\n\n root_ui().push_skin(&gui_skins.default);\n\n\n\n if let MenuResult::Index(i) = builder.build(&mut *root_ui()) {\n\n match i {\n\n GAME_MENU_OPT_RESUME => {\n\n game_state.gui_state.should_draw_game_menu = false;\n\n }\n\n GAME_MENU_OPT_SAVE => {\n", "file_path": "src/gui/game_menu.rs", "rank": 46, "score": 110836.45566766836 }, { "content": "pub fn dispatch_event(event: Event) {\n\n let queue = unsafe { get_event_queue() };\n\n queue.insert(0, event);\n\n}\n\n\n\n// This will perform all the internal handling of an event and return it afterwards.\n\n// Note that `Event::Quit` will clear the scene, but it will probably also need to be\n\n// handled manually to break the game loop and exit.\n\n// If you have no need handle events manually, `handle_queued_events` can be used in stead.\n\npub async fn handle_event(event: Event) -> Result<Event> {\n\n // println!(\"Event: {}\", event.to_str());\n\n match event.clone() {\n\n Event::OpenMainMenu => {\n\n scene::clear();\n\n gui::show_main_menu().await?;\n\n }\n\n Event::StartGame { character } => {\n\n load_scene(*character)?;\n\n }\n\n Event::ChangeMap {\n", "file_path": "src/events.rs", "rank": 47, "score": 103727.35804056522 }, { "content": "pub fn get_next_event() -> Option<Event> {\n\n let queue = unsafe { get_event_queue() };\n\n queue.pop()\n\n}\n\n\n", "file_path": "src/events.rs", "rank": 48, "score": 101314.17426514142 }, { "content": "pub fn window_conf() -> WindowConf {\n\n let config = Config::load(CONFIG_PATH);\n\n\n\n WindowConf {\n\n window_title: GAME_NAME.to_owned(),\n\n high_dpi: false,\n\n window_width: config.resolution.x as i32,\n\n window_height: config.resolution.y as i32,\n\n fullscreen: config.fullscreen,\n\n ..Default::default()\n\n }\n\n}\n\n\n\n#[macroquad::main(window_conf)]\n\nasync fn main() -> Result<()> {\n\n let params = GameParams {\n\n name: GAME_NAME.to_string(),\n\n version: GAME_VERSION.to_string(),\n\n data_path: DATA_PATH.to_string(),\n\n modules_path: MODULES_PATH.to_string(),\n", "file_path": "examples/building_scenes/src/main.rs", "rank": 49, "score": 101198.09993875808 }, { "content": "pub fn window_conf() -> WindowConf {\n\n let config = Config::load(CONFIG_PATH);\n\n\n\n WindowConf {\n\n window_title: GAME_NAME.to_owned(),\n\n high_dpi: false,\n\n window_width: config.resolution.x as i32,\n\n window_height: config.resolution.y as i32,\n\n fullscreen: config.fullscreen,\n\n ..Default::default()\n\n }\n\n}\n\n\n\n#[macroquad::main(window_conf)]\n\nasync fn main() -> Result<()> {\n\n let params = GameParams {\n\n name: GAME_NAME.to_string(),\n\n version: GAME_VERSION.to_string(),\n\n data_path: DATA_PATH.to_string(),\n\n modules_path: MODULES_PATH.to_string(),\n", "file_path": "examples/example_project/src/main.rs", "rank": 50, "score": 101198.09993875808 }, { "content": "fn draw_entry(ui: &mut Ui, player: &mut RefMut<Actor>, entry: &InventoryEntry) {\n\n let gui_skins = storage::get::<GuiSkins>();\n\n\n\n widgets::Group::new(hash!(), vec2(250.0, 30.0)).ui(ui, |ui| {\n\n ui.label(vec2(0.0, 0.0), &entry.params.name);\n\n if entry.equipped_to == EquipmentSlot::None {\n\n ui.push_skin(&gui_skins.condensed_button);\n\n if ui.button(vec2(160.0, 0.0), \"Equip\") {\n\n player.equip_item(&entry.params.id);\n\n }\n\n ui.pop_skin();\n\n } else {\n\n ui.push_skin(&gui_skins.condensed_button);\n\n if ui.button(vec2(150.0, 0.0), \"Unequip\") {\n\n player.unequip_item(&entry.params.id);\n\n }\n\n ui.pop_skin();\n\n }\n\n\n\n if !entry.params.is_quest_item {\n", "file_path": "src/gui/inventory.rs", "rank": 51, "score": 99145.33714117753 }, { "content": "/// This is used to implement `ToString` for non-crate types.\n\n/// It is mainly used for types like `Path`, to eliminate the extra steps introduced by the\n\n/// `to_string_lossy` method, as we are not that concerned with correctness in these settings.\n\npub trait ToStringHelper {\n\n fn to_string_helper(&self) -> String;\n\n}\n\n\n\nimpl ToString for dyn ToStringHelper {\n\n fn to_string(&self) -> String {\n\n self.to_string_helper()\n\n }\n\n}\n\n\n\nimpl ToStringHelper for Path {\n\n fn to_string_helper(&self) -> String {\n\n self.to_string_lossy().into_owned()\n\n }\n\n}\n\n\n\nimpl ToStringHelper for PathBuf {\n\n fn to_string_helper(&self) -> String {\n\n self.to_string_lossy().into_owned()\n\n }\n", "file_path": "src/helpers.rs", "rank": 52, "score": 96047.25640597944 }, { "content": "pub fn remove_filename(path: PathBuf) -> PathBuf {\n\n path.ancestors()\n\n .collect::<Vec<&Path>>()\n\n .get(1)\n\n .cloned()\n\n .unwrap()\n\n .to_path_buf()\n\n}\n\n\n", "file_path": "src/helpers.rs", "rank": 53, "score": 93537.55877669723 }, { "content": "fn process_path(\n\n position: Vec2,\n\n controller: &mut ActorController,\n\n mut path: NavigationPath,\n\n) -> Option<NavigationPath> {\n\n if let Some(mut node) = path.nodes.first().cloned() {\n\n if position.distance(node) <= 2.0 {\n\n path.nodes.remove(0);\n\n if let Some(next) = path.nodes.first().cloned() {\n\n node = next;\n\n } else {\n\n return None;\n\n }\n\n }\n\n controller.move_direction = node.sub(position).normalize_or_zero();\n\n return Some(path);\n\n }\n\n None\n\n}\n", "file_path": "src/behavior_sets/default_humanoid.rs", "rank": 54, "score": 93265.4306707946 }, { "content": "fn pair_from_tiled_prop(tiled_prop: TiledProperty) -> (String, MapProperty) {\n\n match tiled_prop {\n\n TiledProperty::Bool { name, value } => (name, MapProperty::Bool { value }),\n\n TiledProperty::Float { name, value } => (name, MapProperty::Float { value }),\n\n TiledProperty::Int { name, value } => (name, MapProperty::Int { value }),\n\n TiledProperty::String { name, value } => (name, MapProperty::String { value }),\n\n TiledProperty::Color { name, value } => (\n\n name,\n\n MapProperty::Color {\n\n value: color_from_hex_string(&value),\n\n },\n\n ),\n\n TiledProperty::Object { name, value } => (name, MapProperty::Int { value }),\n\n TiledProperty::File { name, value } => (name, MapProperty::String { value }),\n\n }\n\n}\n", "file_path": "src/json/map/tiled.rs", "rank": 55, "score": 87644.38963213674 }, { "content": "fn spawn_item(map_object: &MapObject) {\n\n if let Some(prop) = map_object.properties.get(\"prototype_id\").cloned() {\n\n if let MapProperty::String {\n\n value: prototype_id,\n\n } = prop\n\n {\n\n if prototype_id == \"credits\" {\n\n if let Some(prop) = map_object.properties.get(\"amount\") {\n\n if let MapProperty::Int { value } = prop {\n\n Credits::add_node(map_object.position, *value as u32);\n\n }\n\n }\n\n } else {\n\n let resources = storage::get::<Resources>();\n\n let params = resources.items.get(&prototype_id).cloned().unwrap();\n\n let mut instance_id = None;\n\n if let Some(prop) = map_object.properties.get(\"instance_id\").cloned() {\n\n if let MapProperty::String { value } = prop {\n\n instance_id = Some(value)\n\n }\n", "file_path": "src/scene.rs", "rank": 56, "score": 84910.32127261347 }, { "content": "#[cfg(target_family = \"wasm\")]\n\npub fn get_available_characters(_: &str) -> io::Result<Vec<Character>> {\n\n let game_params = storage::get::<GameParams>();\n\n let storage = &mut quad_storage::STORAGE.lock().unwrap();\n\n let save_name = format!(\"{}_character\", game_params.game_name);\n\n if let Some(json) = storage.get(&save_name) {\n\n let character: Character = serde_json::from_str(&json)?;\n\n return Ok(vec![character]);\n\n }\n\n\n\n Ok(Vec::new())\n\n}\n\n\n", "file_path": "src/character.rs", "rank": 57, "score": 84251.4382704111 }, { "content": "#[cfg(not(any(target_family = \"wasm\", target_os = \"android\")))]\n\npub fn load_character<P: AsRef<Path>>(path: P) -> Result<Character> {\n\n let json = fs::read(path)?;\n\n let character: Character = serde_json::from_slice(&json)?;\n\n Ok(character)\n\n}\n\n\n", "file_path": "src/character.rs", "rank": 58, "score": 80636.14211872047 }, { "content": "#[cfg(not(any(target_family = \"wasm\", target_os = \"android\")))]\n\npub fn get_available_characters<P: AsRef<Path>>(path: P) -> Result<Vec<Character>> {\n\n let regex = Regex::new(r\".json$\")?;\n\n let mut res = Vec::new();\n\n for entry in (fs::read_dir(path)?).flatten() {\n\n if regex.is_match(&entry.path().to_string_lossy().to_string()) {\n\n let character = load_character(entry.path())?;\n\n res.push(character);\n\n }\n\n }\n\n\n\n Ok(res)\n\n}\n\n\n", "file_path": "src/character.rs", "rank": 67, "score": 75742.05516931316 }, { "content": "// Returns two ids, the first for the group holding the module entry in the list and the\n\n// second for the drop-zone before the entry, letting you drop a module before another in\n\n// the load order\n\nfn module_index_to_id(i: usize) -> (u64, u64) {\n\n let id = (i as u64 + 1) * 2;\n\n (id, id + 1)\n\n}\n\n\n", "file_path": "src/gui/main_menu/module_management.rs", "rank": 68, "score": 72966.63573117177 }, { "content": "#[allow(clippy::too_many_arguments)]\n\npub trait ActorBehavior: Mode<Family = ActorBehaviorFamily> {\n\n fn update(\n\n self: Box<Self>,\n\n params: ActorBehaviorParams,\n\n factions: &[String],\n\n stats: ActorStats,\n\n position: Vec2,\n\n controller: &mut ActorController,\n\n weapon_range: Option<f32>,\n\n selected_ability_range: Option<f32>,\n\n inventory: Inventory,\n\n equipped_items: EquippedItems,\n\n ) -> Box<dyn ActorBehavior>;\n\n}\n\n\n\npub struct ActorBehaviorFamily;\n\n\n\nimpl Family for ActorBehaviorFamily {\n\n type Base = dyn ActorBehavior;\n\n\n\n type Mode = Box<dyn ActorBehavior>;\n\n}\n", "file_path": "src/nodes/actor/behavior.rs", "rank": 69, "score": 72629.56663656326 }, { "content": "fn check_map_collision(collider: Collider) -> Vec<(Collider, CollisionKind)> {\n\n let map = storage::get::<Map>();\n\n let tile_size = map.tile_size;\n\n let collisions = map.get_collisions(collider);\n\n\n\n collisions\n\n .into_iter()\n\n .map(|(position, kind)| {\n\n let collider = Collider::rect(position.x, position.y, tile_size.x, tile_size.y);\n\n (collider, kind)\n\n })\n\n .collect()\n\n}\n\n\n", "file_path": "src/physics/physics_body.rs", "rank": 70, "score": 69870.2405174022 }, { "content": "#[derive(Debug)]\n\nstruct Custom {\n\n kind: ErrorKind,\n\n error: Box<dyn std::error::Error + Send + Sync>,\n\n}\n\n\n\n#[derive(Debug, Copy, Clone, PartialEq, Eq)]\n\npub enum ErrorKind {\n\n File,\n\n Parse,\n\n Material,\n\n}\n\n\n\nimpl ErrorKind {\n\n pub(crate) fn as_str(&self) -> &'static str {\n\n match *self {\n\n ErrorKind::File => \"file error\",\n\n ErrorKind::Parse => \"parse error\",\n\n ErrorKind::Material => \"material error\",\n\n }\n\n }\n", "file_path": "src/error.rs", "rank": 71, "score": 68435.19478038128 }, { "content": "enum Repr {\n\n Simple(ErrorKind),\n\n SimpleMessage(ErrorKind, &'static &'static str),\n\n Custom(Box<Custom>),\n\n}\n\n\n", "file_path": "src/error.rs", "rank": 72, "score": 68397.87332896874 }, { "content": "#[derive(StructOpt, Debug)]\n\n#[structopt(name = \"mapconv\")]\n\nstruct Cli {\n\n #[structopt(name = \"FILE\", parse(from_os_str))]\n\n file: PathBuf,\n\n #[structopt(name = \"OUT\", parse(from_os_str))]\n\n output: PathBuf,\n\n}\n\n\n", "file_path": "cli/mapconv/src/main.rs", "rank": 73, "score": 65215.43937197598 }, { "content": "enum MainMenuResult {\n\n StartGame,\n\n Settings,\n\n Modules,\n\n Quit,\n\n}\n\n\n\npub async fn show_main_menu() -> Result<()> {\n\n let gui_skins = storage::get::<GuiSkins>();\n\n root_ui().push_skin(&gui_skins.default);\n\n\n\n 'menu: loop {\n\n match draw_main_menu().await {\n\n MainMenuResult::StartGame => match draw_character_selection().await {\n\n CharacterSelectionResult::SelectCharacter(character) => {\n\n dispatch_event(Event::StartGame { character });\n\n break 'menu;\n\n }\n\n CharacterSelectionResult::CreateCharacter => {\n\n if let Some(class_id) = draw_class_selection().await {\n", "file_path": "src/gui/main_menu/mod.rs", "rank": 74, "score": 61206.17305308601 }, { "content": "#[derive(Debug, Copy, Clone)]\n\nenum LoadOrderChange {\n\n LoadBefore { i: usize, target_i: usize },\n\n LoadAfter { i: usize, target_i: usize },\n\n}\n\n\n", "file_path": "src/gui/main_menu/module_management.rs", "rank": 75, "score": 60074.19380809369 }, { "content": "#[cfg(feature = \"collision_between_actors\")]\n\nfn check_actor_collisions(\n\n collider: Collider,\n\n actors: &Vec<RefMut<Actor>>,\n\n) -> Vec<(Collider, CollisionKind)> {\n\n let mut collisions = Vec::new();\n\n for actor in actors {\n\n if let Some(other_collider) = actor.body.get_offset_collider() {\n\n if collider.overlaps(other_collider) {\n\n collisions.push((other_collider, CollisionKind::Actor));\n\n }\n\n }\n\n }\n\n collisions\n\n}\n", "file_path": "src/physics/physics_body.rs", "rank": 76, "score": 59704.47068980725 }, { "content": "fn draw_module_entry(\n\n ui: &mut Ui,\n\n i: usize,\n\n name: &str,\n\n params: &ModuleParams,\n\n value: &mut bool,\n\n is_dragging: bool,\n\n) -> Drag {\n\n let gui_skins = storage::get::<GuiSkins>();\n\n\n\n let module_list_entry_skin = gui_skins.custom.get(\"module_list_entry\").unwrap();\n\n\n\n ui.push_skin(module_list_entry_skin);\n\n\n\n let size = vec2(450.0, 24.0);\n\n let position = vec2(0.0, i as f32 * 28.0);\n\n\n\n let (entry_id, drop_before_id) = module_index_to_id(i);\n\n\n\n widgets::Group::new(drop_before_id, vec2(size.x, 4.0))\n", "file_path": "src/gui/main_menu/module_management.rs", "rank": 77, "score": 57379.5954947073 }, { "content": "fn draw_character_list(\n\n selected_i: &mut Option<usize>,\n\n characters: &[Character],\n\n) -> Option<CharacterSelectionResult> {\n\n const WINDOW_WIDTH: f32 = 300.0;\n\n const WINDOW_HEIGHT: f32 = 250.0;\n\n\n\n let size = vec2(WINDOW_WIDTH, WINDOW_HEIGHT);\n\n\n\n let btn_size = vec2(\n\n (WINDOW_WIDTH - GuiSkins::WINDOW_MARGIN_X * 2.0) / 2.0 - GuiSkins::ELEMENT_MARGIN,\n\n GuiSkins::BUTTON_HEIGHT,\n\n );\n\n let btn_position_y = WINDOW_HEIGHT - GuiSkins::WINDOW_MARGIN_Y * 2.0 - GuiSkins::BUTTON_HEIGHT;\n\n\n\n let mut result = None;\n\n\n\n WindowBuilder::new(hash!(), size)\n\n .with_centered_pos(true)\n\n .build(&mut *root_ui(), |ui| {\n", "file_path": "src/gui/main_menu/character_selection.rs", "rank": 78, "score": 57379.5954947073 }, { "content": "fn draw_character_attribute(\n\n ui: &mut Ui,\n\n i: usize,\n\n name: &str,\n\n value: &mut u32,\n\n build_points: &mut u32,\n\n) {\n\n let gui_skins = storage::get::<GuiSkins>();\n\n\n\n let y_offset = i as f32 * 22.0;\n\n\n\n ui.label(vec2(2.0, y_offset - 2.0), &format!(\"{}: {}\", name, value));\n\n\n\n if *value > 6 {\n\n ui.push_skin(&gui_skins.condensed_button);\n\n if ui.button(vec2(58.0, y_offset), \"-\") {\n\n *value -= 1;\n\n *build_points += 1;\n\n }\n\n ui.pop_skin();\n", "file_path": "src/gui/main_menu/character_creation.rs", "rank": 79, "score": 57379.5954947073 }, { "content": "fn draw_character_details(\n\n selected_i: &mut Option<usize>,\n\n delete_i: &mut Option<usize>,\n\n character: &Character,\n\n) -> Option<CharacterSelectionResult> {\n\n const WINDOW_WIDTH: f32 = 400.0;\n\n const WINDOW_HEIGHT: f32 = 500.0;\n\n\n\n let size = vec2(WINDOW_WIDTH, WINDOW_HEIGHT);\n\n let position = get_centered_on_screen(size);\n\n\n\n let btn_size = vec2(\n\n (WINDOW_WIDTH - GuiSkins::WINDOW_MARGIN_X * 2.0) / 2.0 - GuiSkins::ELEMENT_MARGIN,\n\n GuiSkins::BUTTON_HEIGHT,\n\n );\n\n let btn_position_y = WINDOW_HEIGHT - GuiSkins::WINDOW_MARGIN_Y * 2.0 - GuiSkins::BUTTON_HEIGHT;\n\n\n\n let mut result = None;\n\n\n\n widgets::Window::new(hash!(), position, size)\n", "file_path": "src/gui/main_menu/character_selection.rs", "rank": 80, "score": 57379.5954947073 }, { "content": "fn main() -> CliResult {\n\n let args = Cli::from_args();\n\n\n\n let json = read_file(args.file)?;\n\n let tiled_map = serde_json::from_str(&json)?;\n\n let map = Map::from_tiled(tiled_map);\n\n map.save(args.output).unwrap();\n\n\n\n println!(\"Success!\");\n\n\n\n Ok(())\n\n}\n", "file_path": "cli/mapconv/src/main.rs", "rank": 81, "score": 56312.90214004935 }, { "content": "fn spawn_light_source(map_object: &MapObject) {\n\n let size = map_object.size.unwrap_or(LightSource::DEFAULT_SIZE);\n\n\n\n let mut color = LightSource::DEFAULT_COLOR;\n\n if let Some(prop) = map_object.properties.get(\"color\").cloned() {\n\n if let MapProperty::Color { value } = prop {\n\n color = value;\n\n }\n\n }\n\n\n\n let mut intensity = LightSource::DEFAULT_INTENSITY;\n\n if let Some(prop) = map_object.properties.get(\"intensity\").cloned() {\n\n if let MapProperty::Float { value } = prop {\n\n intensity = value;\n\n }\n\n }\n\n\n\n LightSource::add_node(map_object.position, size, color, intensity, None);\n\n}\n", "file_path": "src/scene.rs", "rank": 82, "score": 51366.394501833485 }, { "content": "fn sub_offsets(a: RectOffset, b: RectOffset) -> RectOffset {\n\n RectOffset::new(\n\n a.left - b.left,\n\n a.right - b.right,\n\n a.top - b.top,\n\n a.bottom - b.bottom,\n\n )\n\n}\n\n\n\n#[derive(Debug, Clone, Serialize, Deserialize)]\n\npub struct GuiImage {\n\n pub image_id: String,\n\n #[serde(with = \"json::RectOffsetDef\")]\n\n pub margins: RectOffset,\n\n}\n\n\n\n#[derive(Debug, Clone, Serialize, Deserialize)]\n\npub struct GuiTheme {\n\n pub font_size: u16,\n\n pub header_font_size: u16,\n", "file_path": "src/gui/theme.rs", "rank": 83, "score": 44144.588007546845 }, { "content": "fn spawn_actor(game_state: Handle<GameState>, map_object: &MapObject) {\n\n if let Some(prop) = map_object.properties.get(\"prototype_id\") {\n\n if let MapProperty::String {\n\n value: prototype_id,\n\n } = prop\n\n {\n\n let mut instance_id = None;\n\n if let Some(prop) = map_object.properties.get(\"instance_id\").cloned() {\n\n if let MapProperty::String { value } = prop {\n\n instance_id = Some(value);\n\n }\n\n }\n\n\n\n let resources = storage::get::<Resources>();\n\n let params = resources.actors.get(prototype_id).cloned().unwrap();\n\n let mut actor = Actor::new(\n\n game_state,\n\n ActorControllerKind::Computer,\n\n ActorParams {\n\n id: instance_id.unwrap_or(generate_id()),\n", "file_path": "src/scene.rs", "rank": 84, "score": 42372.00282183698 }, { "content": "}\n\n\n\n#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]\n\n#[serde(tag = \"type\", rename_all = \"snake_case\")]\n\npub enum AbilityDelivery {\n\n Projectile {\n\n projectile_kind: ProjectileKind,\n\n spread: f32,\n\n speed: f32,\n\n },\n\n Melee,\n\n ContinuousBeam,\n\n}\n\n\n\n#[derive(Clone, Serialize, Deserialize)]\n\npub struct AbilityParams {\n\n pub id: String,\n\n #[serde(\n\n default,\n\n rename = \"sound_effect\",\n", "file_path": "src/ability.rs", "rank": 85, "score": 41448.5087662503 }, { "content": " pub range: f32,\n\n pub effects: Vec<Effect>,\n\n #[serde(\n\n default,\n\n with = \"json::opt_color\",\n\n skip_serializing_if = \"Option::is_none\"\n\n )]\n\n pub color_override: Option<Color>,\n\n #[serde(default, skip_serializing_if = \"Option::is_none\")]\n\n pub size_override: Option<f32>,\n\n}\n\n\n\nimpl Default for AbilityParams {\n\n fn default() -> Self {\n\n AbilityParams {\n\n id: \"\".to_string(),\n\n sound_effect_id: None,\n\n on_hit_sound_effect_id: None,\n\n noise_level: NoiseLevel::Moderate,\n\n delivery: AbilityDelivery::Projectile {\n", "file_path": "src/ability.rs", "rank": 86, "score": 41444.25247347388 }, { "content": "use crate::nodes::projectiles::ProjectileParams;\n\nuse crate::prelude::*;\n\n\n\n#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]\n\n#[serde(rename_all = \"snake_case\")]\n\npub enum DamageType {\n\n Piercing,\n\n Slashing,\n\n Blunt,\n\n Energy,\n\n Heat,\n\n}\n\n\n\n#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]\n\n#[serde(tag = \"type\", rename_all = \"snake_case\")]\n\npub enum Effect {\n\n Damage {\n\n damage_type: DamageType,\n\n amount: f32,\n\n },\n", "file_path": "src/ability.rs", "rank": 87, "score": 41441.355199428515 }, { "content": " skip_serializing_if = \"Option::is_none\"\n\n )]\n\n pub sound_effect_id: Option<String>,\n\n #[serde(\n\n default,\n\n rename = \"on_hit_sound_effect\",\n\n skip_serializing_if = \"Option::is_none\"\n\n )]\n\n pub on_hit_sound_effect_id: Option<String>,\n\n #[serde(default)]\n\n pub noise_level: NoiseLevel,\n\n pub delivery: AbilityDelivery,\n\n #[serde(default)]\n\n pub cooldown: f32,\n\n #[serde(default)]\n\n pub health_cost: f32,\n\n #[serde(default)]\n\n pub stamina_cost: f32,\n\n #[serde(default)]\n\n pub energy_cost: f32,\n", "file_path": "src/ability.rs", "rank": 88, "score": 41440.14397650594 }, { "content": " pub sound_effect: Option<Sound>,\n\n pub on_hit_sound_effect: Option<Sound>,\n\n pub cooldown: f32,\n\n pub cooldown_timer: f32,\n\n pub health_cost: f32,\n\n pub stamina_cost: f32,\n\n pub energy_cost: f32,\n\n pub range: f32,\n\n pub effects: Vec<Effect>,\n\n pub color_override: Option<Color>,\n\n pub size_override: Option<f32>,\n\n}\n\n\n\nimpl Ability {\n\n pub fn new(params: AbilityParams) -> Self {\n\n let resources = storage::get::<Resources>();\n\n\n\n let mut sound_effect = None;\n\n if let Some(sound_effect_id) = params.sound_effect_id {\n\n let res = resources\n", "file_path": "src/ability.rs", "rank": 89, "score": 41436.4207291422 }, { "content": " projectile_kind: ProjectileKind::Bullet,\n\n speed: 8.0,\n\n spread: 5.0,\n\n },\n\n cooldown: 0.0,\n\n health_cost: 0.0,\n\n stamina_cost: 0.0,\n\n energy_cost: 0.0,\n\n range: 5.0,\n\n effects: Vec::new(),\n\n color_override: None,\n\n size_override: None,\n\n }\n\n }\n\n}\n\n\n\n#[derive(Clone)]\n\npub struct Ability {\n\n pub noise_level: NoiseLevel,\n\n pub delivery: AbilityDelivery,\n", "file_path": "src/ability.rs", "rank": 90, "score": 41426.451133544135 }, { "content": " &node.factions,\n\n &self.effects,\n\n self.color_override,\n\n self.size_override,\n\n origin,\n\n end,\n\n );\n\n }\n\n AbilityDelivery::Projectile {\n\n projectile_kind,\n\n spread,\n\n speed,\n\n } => {\n\n let params = ProjectileParams {\n\n kind: projectile_kind,\n\n effects: self.effects.clone(),\n\n color: self\n\n .color_override\n\n .unwrap_or(Projectiles::DEFAULT_PROJECTILE_COLOR),\n\n size: self\n", "file_path": "src/ability.rs", "rank": 91, "score": 41424.3057224244 }, { "content": "\n\n for mut other_actor in scene::find_nodes_by_type::<Actor>() {\n\n hit_success =\n\n if let Some(other_collider) = other_actor.body.get_offset_collider() {\n\n collider.overlaps(other_collider)\n\n } else {\n\n collider.contains(other_actor.body.position)\n\n };\n\n\n\n if hit_success {\n\n for effect in self.effects.clone() {\n\n other_actor.apply_effect(\n\n &node.id,\n\n node.handle(),\n\n &node.factions,\n\n effect,\n\n );\n\n }\n\n }\n\n }\n", "file_path": "src/ability.rs", "rank": 92, "score": 41423.55884451008 }, { "content": " .sound_effects\n\n .get(&sound_effect_id)\n\n .cloned()\n\n .unwrap_or_else(|| {\n\n panic!(\"Unable to find sound effect with id '{}'\", &sound_effect_id)\n\n });\n\n sound_effect = Some(res);\n\n }\n\n\n\n let mut on_hit_sound_effect = None;\n\n if let Some(sound_effect_id) = params.on_hit_sound_effect_id {\n\n let res = resources\n\n .sound_effects\n\n .get(&sound_effect_id)\n\n .cloned()\n\n .unwrap_or_else(|| {\n\n panic!(\"Unable to find sound effect with id '{}'\", &sound_effect_id)\n\n });\n\n on_hit_sound_effect = Some(res);\n\n }\n", "file_path": "src/ability.rs", "rank": 93, "score": 41422.89842053598 }, { "content": " && (self.health_cost == 0.0 || node.stats.current_health >= self.health_cost)\n\n && (self.stamina_cost == 0.0 || node.stats.current_stamina >= self.stamina_cost)\n\n && (self.energy_cost == 0.0 || node.stats.current_energy >= self.energy_cost)\n\n {\n\n self.cooldown_timer = 0.0;\n\n\n\n node.set_noise_level(self.noise_level);\n\n node.stats.current_health -= self.health_cost;\n\n node.stats.current_stamina -= self.stamina_cost;\n\n node.stats.current_energy -= self.energy_cost;\n\n\n\n match self.delivery.clone() {\n\n AbilityDelivery::ContinuousBeam => {\n\n let end = node.body.position + direction * self.range;\n\n\n\n let mut continuous_beams =\n\n scene::find_node_by_type::<ContinuousBeams>().unwrap();\n\n continuous_beams.spawn(\n\n &node.id,\n\n node.handle(),\n", "file_path": "src/ability.rs", "rank": 94, "score": 41422.78993579252 }, { "content": " .size_override\n\n .unwrap_or(Projectiles::DEFAULT_PROJECTILE_SIZE),\n\n origin,\n\n direction,\n\n speed,\n\n range: self.range,\n\n on_hit_sound_effect: self.on_hit_sound_effect,\n\n };\n\n\n\n let mut projectiles = scene::find_node_by_type::<Projectiles>().unwrap();\n\n projectiles.spawn(&node.id, node.handle(), &node.factions, spread, params);\n\n\n\n if let Some(sound_effect) = self.sound_effect {\n\n play_sound(sound_effect, false);\n\n }\n\n }\n\n AbilityDelivery::Melee => {\n\n let collider = Collider::circle(origin.x, origin.y, self.range);\n\n\n\n let mut hit_success = false;\n", "file_path": "src/ability.rs", "rank": 95, "score": 41422.502870639495 }, { "content": "\n\n Ability {\n\n sound_effect,\n\n on_hit_sound_effect,\n\n noise_level: params.noise_level,\n\n delivery: params.delivery,\n\n health_cost: params.health_cost,\n\n stamina_cost: params.stamina_cost,\n\n energy_cost: params.energy_cost,\n\n cooldown: params.cooldown,\n\n cooldown_timer: params.cooldown,\n\n range: params.range,\n\n effects: params.effects,\n\n color_override: params.color_override,\n\n size_override: params.size_override,\n\n }\n\n }\n\n\n\n pub fn activate(&mut self, node: &mut RefMut<Actor>, origin: Vec2, direction: Vec2) {\n\n if self.cooldown_timer >= self.cooldown\n", "file_path": "src/ability.rs", "rank": 96, "score": 41421.09902035154 }, { "content": "use crate::file_io::deserialize_file;\n\nuse crate::prelude::*;\n\n\n\nuse crate::macroquad::texture::{load_texture, Texture2D};\n\nuse crate::helpers::ToStringHelper;\n\n\n\n#[derive(Debug, Clone, Serialize, Deserialize)]\n\npub struct CharacterClass {\n\n pub id: String,\n\n pub prototype_id: String,\n\n pub name: String,\n\n pub description: String,\n\n}\n\n\n", "file_path": "src/resources.rs", "rank": 97, "score": 41415.11916652131 }, { "content": "\n\n if hit_success {\n\n if let Some(sound_effect) = self.on_hit_sound_effect {\n\n play_sound(sound_effect, false);\n\n } else if let Some(sound_effect) = self.sound_effect {\n\n play_sound(sound_effect, false);\n\n }\n\n } else if let Some(sound_effect) = self.sound_effect {\n\n play_sound(sound_effect, false);\n\n }\n\n }\n\n }\n\n }\n\n }\n\n\n\n pub fn update(&mut self) {\n\n self.cooldown_timer += get_frame_time();\n\n }\n\n}\n", "file_path": "src/ability.rs", "rank": 98, "score": 41412.65815997124 }, { "content": "use crate::prelude::*;\n\n\n\n#[derive(Debug, Clone, Serialize, Deserialize)]\n\npub struct SpriteAnimationParams {\n\n #[serde(with = \"json::def_vec2\")]\n\n pub offset: Vec2,\n\n pub texture_id: String,\n\n #[serde(default, skip_serializing_if = \"Option::is_none\")]\n\n pub normal_map_id: Option<String>,\n\n #[serde(with = \"json::def_vec2\")]\n\n pub tile_size: Vec2,\n\n #[serde(with = \"json::vec_animation\")]\n\n pub animations: Vec<Animation>,\n\n #[serde(skip)]\n\n pub should_play: bool,\n\n}\n\n\n\nimpl Default for SpriteAnimationParams {\n\n fn default() -> Self {\n\n SpriteAnimationParams {\n", "file_path": "src/render/animation.rs", "rank": 99, "score": 47.2100220114885 } ]
Rust
capi/src/session.rs
jws121295/dansible
4c32335b048560352135480ab0216ff5be6bd8fa
use libc::{c_int, c_char}; use std::ffi::CStr; use std::slice::from_raw_parts; use std::sync::mpsc; use std::boxed::FnBox; use std::sync::Mutex; use librespot::session::{Session, Config, Bitrate}; use eventual::{Async, AsyncResult, Future}; use cstring_cache::CStringCache; use types::sp_error; use types::sp_error::*; use types::sp_session_config; use types::sp_session_callbacks; static mut global_session: Option<(*const sp_session, *const Mutex<mpsc::Sender<SpSessionEvent>>)> = None; pub type SpSessionEvent = Box<FnBox(&mut SpSession) -> ()>; pub struct SpSession { pub session: Session, cache: CStringCache, rx: mpsc::Receiver<SpSessionEvent>, pub callbacks: &'static sp_session_callbacks, } impl SpSession { pub unsafe fn global() -> &'static SpSession { &*global_session.unwrap().0 } pub fn run<F: FnOnce(&mut SpSession) -> () + 'static>(event: F) { let tx = unsafe { &*global_session.unwrap().1 }; tx.lock().unwrap().send(Box::new(event)).unwrap(); } pub fn receive<T, E, F>(future: Future<T, E>, handler: F) where T : Send, E: Send, F : FnOnce(&mut SpSession, AsyncResult<T, E>) -> () + Send + 'static { future.receive(move |result| { SpSession::run(move |session| { handler(session, result); }) }) } } #[allow(non_camel_case_types)] pub type sp_session = SpSession; #[no_mangle] pub unsafe extern "C" fn sp_session_create(c_config: *const sp_session_config, c_session: *mut *mut sp_session) -> sp_error { assert!(global_session.is_none()); let c_config = &*c_config; let application_key = from_raw_parts::<u8>(c_config.application_key as *const u8, c_config.application_key_size); let user_agent = CStr::from_ptr(c_config.user_agent).to_string_lossy().into_owned(); let device_name = CStr::from_ptr(c_config.device_id).to_string_lossy().into_owned(); let cache_location = CStr::from_ptr(c_config.cache_location).to_string_lossy().into_owned(); let config = Config { application_key: application_key.to_owned(), user_agent: user_agent, device_name: device_name, cache_location: cache_location.into(), bitrate: Bitrate::Bitrate160, }; let (tx, rx) = mpsc::channel(); let session = SpSession { session: Session::new(config), cache: CStringCache::new(), rx: rx, callbacks: &*c_config.callbacks, }; let session = Box::into_raw(Box::new(session)); let tx = Box::into_raw(Box::new(Mutex::new(tx))); global_session = Some((session, tx)); *c_session = session; SP_ERROR_OK } #[no_mangle] pub unsafe extern "C" fn sp_session_release(c_session: *mut sp_session) -> sp_error { global_session = None; drop(Box::from_raw(c_session)); SP_ERROR_OK } #[no_mangle] pub unsafe extern "C" fn sp_session_login(c_session: *mut sp_session, c_username: *const c_char, c_password: *const c_char, _remember_me: bool, _blob: *const c_char) -> sp_error { let session = &*c_session; let username = CStr::from_ptr(c_username).to_string_lossy().into_owned(); let password = CStr::from_ptr(c_password).to_string_lossy().into_owned(); { let session = session.session.clone(); SpSession::receive(Future::spawn(move || { session.login_password(username, password) }), |session, result| { result.unwrap(); { let session = session.session.clone(); ::std::thread::spawn(move || { loop { session.poll(); } }); } }); } SP_ERROR_OK } #[no_mangle] pub unsafe extern "C" fn sp_session_user_name(c_session: *mut sp_session) -> *const c_char { let session = &mut *c_session; let username = session.session.username(); session.cache.intern(&username).as_ptr() } #[no_mangle] pub unsafe extern "C" fn sp_session_user_country(c_session: *mut sp_session) -> c_int { let session = &*c_session; let country = session.session.country(); country.chars().fold(0, |acc, x| { acc << 8 | (x as u32) }) as c_int } #[no_mangle] pub unsafe extern "C" fn sp_session_process_events(c_session: *mut sp_session, next_timeout: *mut c_int) -> sp_error { let session = &mut *c_session; if !next_timeout.is_null() { *next_timeout = 10; } let event = session.rx.recv().unwrap(); event.call_box((session,)); SP_ERROR_OK }
use libc::{c_int, c_char}; use std::ffi::CStr; use std::slice::from_raw_parts; use std::sync::mpsc; use std::boxed::FnBox; use std::sync::Mutex; use librespot::session::{Session, Config, Bitrate}; use eventual::{Async, AsyncResult, Future}; use cstring_cache::CStringCache; use types::sp_error; use types::sp_error::*; use types::sp_session_config; use types::sp_session_callbacks; static mut global_session: Option<(*const sp_session, *const Mutex<mpsc::Sender<SpSessionEvent>>)> = None; pub type SpSessionEvent = Box<FnBox(&mut SpSession) -> ()>; pub struct SpSession { pub session: Session, cache: CStringCache, rx: mpsc::Receiver<SpSessionEvent>, pub callbacks: &'static sp_session_callbacks, } impl SpSession { pub unsafe fn global() -> &'static SpSession { &*global_session.unwrap().0 } pub fn run<F: FnOnce(&mut SpSession) -> () + 'static>(event: F) { let tx = unsafe { &*global
pub unsafe extern "C" fn sp_session_release(c_session: *mut sp_session) -> sp_error { global_session = None; drop(Box::from_raw(c_session)); SP_ERROR_OK } #[no_mangle] pub unsafe extern "C" fn sp_session_login(c_session: *mut sp_session, c_username: *const c_char, c_password: *const c_char, _remember_me: bool, _blob: *const c_char) -> sp_error { let session = &*c_session; let username = CStr::from_ptr(c_username).to_string_lossy().into_owned(); let password = CStr::from_ptr(c_password).to_string_lossy().into_owned(); { let session = session.session.clone(); SpSession::receive(Future::spawn(move || { session.login_password(username, password) }), |session, result| { result.unwrap(); { let session = session.session.clone(); ::std::thread::spawn(move || { loop { session.poll(); } }); } }); } SP_ERROR_OK } #[no_mangle] pub unsafe extern "C" fn sp_session_user_name(c_session: *mut sp_session) -> *const c_char { let session = &mut *c_session; let username = session.session.username(); session.cache.intern(&username).as_ptr() } #[no_mangle] pub unsafe extern "C" fn sp_session_user_country(c_session: *mut sp_session) -> c_int { let session = &*c_session; let country = session.session.country(); country.chars().fold(0, |acc, x| { acc << 8 | (x as u32) }) as c_int } #[no_mangle] pub unsafe extern "C" fn sp_session_process_events(c_session: *mut sp_session, next_timeout: *mut c_int) -> sp_error { let session = &mut *c_session; if !next_timeout.is_null() { *next_timeout = 10; } let event = session.rx.recv().unwrap(); event.call_box((session,)); SP_ERROR_OK }
_session.unwrap().1 }; tx.lock().unwrap().send(Box::new(event)).unwrap(); } pub fn receive<T, E, F>(future: Future<T, E>, handler: F) where T : Send, E: Send, F : FnOnce(&mut SpSession, AsyncResult<T, E>) -> () + Send + 'static { future.receive(move |result| { SpSession::run(move |session| { handler(session, result); }) }) } } #[allow(non_camel_case_types)] pub type sp_session = SpSession; #[no_mangle] pub unsafe extern "C" fn sp_session_create(c_config: *const sp_session_config, c_session: *mut *mut sp_session) -> sp_error { assert!(global_session.is_none()); let c_config = &*c_config; let application_key = from_raw_parts::<u8>(c_config.application_key as *const u8, c_config.application_key_size); let user_agent = CStr::from_ptr(c_config.user_agent).to_string_lossy().into_owned(); let device_name = CStr::from_ptr(c_config.device_id).to_string_lossy().into_owned(); let cache_location = CStr::from_ptr(c_config.cache_location).to_string_lossy().into_owned(); let config = Config { application_key: application_key.to_owned(), user_agent: user_agent, device_name: device_name, cache_location: cache_location.into(), bitrate: Bitrate::Bitrate160, }; let (tx, rx) = mpsc::channel(); let session = SpSession { session: Session::new(config), cache: CStringCache::new(), rx: rx, callbacks: &*c_config.callbacks, }; let session = Box::into_raw(Box::new(session)); let tx = Box::into_raw(Box::new(Mutex::new(tx))); global_session = Some((session, tx)); *c_session = session; SP_ERROR_OK } #[no_mangle]
random
[ { "content": "pub fn add_session_arguments(opts: &mut getopts::Options) {\n\n opts.optopt(\"c\", \"cache\", \"Path to a directory where files will be cached.\", \"CACHE\")\n\n .reqopt(\"n\", \"name\", \"Device name\", \"NAME\")\n\n .optopt(\"b\", \"bitrate\", \"Bitrate (96, 160 or 320). Defaults to 160\", \"BITRATE\");\n\n\n\n if APPKEY.is_none() {\n\n opts.reqopt(\"a\", \"appkey\", \"Path to a spotify appkey\", \"APPKEY\");\n\n } else {\n\n opts.optopt(\"a\", \"appkey\", \"Path to a spotify appkey\", \"APPKEY\");\n\n };\n\n}\n\n\n", "file_path": "src/main_helper.rs", "rank": 0, "score": 142247.5659734952 }, { "content": "pub fn create_session(matches: &getopts::Matches) -> Session {\n\n info!(\"librespot {} ({}). Built on {}.\",\n\n version::short_sha(),\n\n version::commit_date(),\n\n version::short_now());\n\n\n\n let appkey = load_appkey(matches.opt_str(\"a\"));\n\n let name = matches.opt_str(\"n\").unwrap();\n\n let bitrate = match matches.opt_str(\"b\").as_ref().map(String::as_ref) {\n\n None => Bitrate::Bitrate160, // default value\n\n\n\n Some(\"96\") => Bitrate::Bitrate96,\n\n Some(\"160\") => Bitrate::Bitrate160,\n\n Some(\"320\") => Bitrate::Bitrate320,\n\n Some(b) => {\n\n error!(\"Invalid bitrate {}\", b);\n\n exit(1)\n\n }\n\n };\n\n\n", "file_path": "src/main_helper.rs", "rank": 1, "score": 130991.74423768924 }, { "content": "pub fn get_credentials(session: &Session, matches: &getopts::Matches) -> Credentials {\n\n let credentials = session.cache().get_credentials();\n\n\n\n match (matches.opt_str(\"username\"),\n\n matches.opt_str(\"password\"),\n\n credentials) {\n\n\n\n (Some(username), Some(password), _)\n\n => Credentials::with_password(username, password),\n\n\n\n (Some(ref username), _, Some(ref credentials)) if *username == credentials.username\n\n => credentials.clone(),\n\n\n\n (Some(username), None, _) => {\n\n print!(\"Password for {}: \", username);\n\n stdout().flush().unwrap();\n\n let password = rpassword::read_password().unwrap();\n\n Credentials::with_password(username.clone(), password)\n\n }\n\n\n", "file_path": "src/main_helper.rs", "rank": 2, "score": 127996.79235998917 }, { "content": "pub fn create_player(session: &Session, matches: &getopts::Matches) -> Player {\n\n let make_backend = find_backend(matches.opt_str(\"backend\").as_ref().map(AsRef::as_ref));\n\n\n\n Player::new(session.clone(), move || make_backend())\n\n}\n", "file_path": "src/main_helper.rs", "rank": 3, "score": 127996.79235998917 }, { "content": "pub fn add_player_arguments(opts: &mut getopts::Options) {\n\n opts.optopt(\"\", \"backend\", \"Audio backend to use. Use '?' to list options\", \"BACKEND\");\n\n}\n\n\n", "file_path": "src/main_helper.rs", "rank": 4, "score": 119227.75878422987 }, { "content": "pub fn add_authentication_arguments(opts: &mut getopts::Options) {\n\n opts.optopt(\"u\", \"username\", \"Username to sign in with\", \"USERNAME\")\n\n .optopt(\"p\", \"password\", \"Password\", \"PASSWORD\");\n\n\n\n if cfg!(feature = \"facebook\") {\n\n opts.optflag(\"\", \"facebook\", \"Login with a Facebook account\");\n\n }\n\n}\n\n\n", "file_path": "src/main_helper.rs", "rank": 5, "score": 119227.75878422987 }, { "content": "pub fn find_backend(name: Option<&str>) -> &'static (Fn() -> Box<Sink> + Send + Sync) {\n\n match name {\n\n Some(\"?\") => {\n\n println!(\"Available Backends : \");\n\n for (&(name, _), idx) in BACKENDS.iter().zip(0..) {\n\n if idx == 0 {\n\n println!(\"- {} (default)\", name);\n\n } else {\n\n println!(\"- {}\", name);\n\n }\n\n }\n\n\n\n exit(0);\n\n },\n\n Some(name) => {\n\n BACKENDS.iter().find(|backend| name == backend.0).expect(\"Unknown backend\").1\n\n },\n\n None => {\n\n BACKENDS.first().expect(\"No backends were enabled at build time\").1\n\n }\n\n }\n\n}\n\n\n", "file_path": "src/main_helper.rs", "rank": 6, "score": 114842.1930202324 }, { "content": "pub trait MetadataTrait : Send + 'static {\n\n type Message: protobuf::MessageStatic;\n\n\n\n fn base_url() -> &'static str;\n\n fn parse(msg: &Self::Message, session: &Session) -> Self;\n\n}\n\n\n\n#[derive(Debug, Clone)]\n\npub struct Track {\n\n pub id: SpotifyId,\n\n pub name: String,\n\n pub album: SpotifyId,\n\n pub artists: Vec<SpotifyId>,\n\n pub files: LinearMap<FileFormat, FileId>,\n\n pub alternatives: Vec<SpotifyId>,\n\n pub available: bool,\n\n}\n\n\n\n#[derive(Debug, Clone)]\n\npub struct Album {\n", "file_path": "src/metadata.rs", "rank": 7, "score": 93743.53016048903 }, { "content": "pub fn rand_vec<G: Rng, R: Rand>(rng: &mut G, size: usize) -> Vec<R> {\n\n rng.gen_iter().take(size).collect()\n\n}\n\n\n", "file_path": "src/util/mod.rs", "rank": 8, "score": 93075.99983791294 }, { "content": "pub fn now_ms() -> i64 {\n\n let ts = time::now_utc().to_timespec();\n\n ts.sec * 1000 + ts.nsec as i64 / 1000000\n\n}\n\n\n", "file_path": "src/util/mod.rs", "rank": 9, "score": 91196.23469281066 }, { "content": "pub trait Handler : Sized + Send + 'static {\n\n fn on_header(self, header_id: u8, header_data: &[u8], session: &Session) -> Response<Self>;\n\n fn on_data(self, offset: usize, data: &[u8], session: &Session) -> Response<Self>;\n\n fn on_eof(self, session: &Session) -> Response<Self>;\n\n fn on_error(self, session: &Session);\n\n}\n\n\n\npub struct AudioFile<H: Handler> {\n\n handler: H,\n\n file_id: FileId,\n\n offset: usize,\n\n}\n\n\n\nimpl <H: Handler> AudioFile<H> {\n\n pub fn new(file_id: FileId, offset: usize, handler: H, session: &Session) {\n\n let handler = AudioFile {\n\n handler: handler,\n\n file_id: file_id,\n\n offset: offset,\n\n };\n", "file_path": "src/audio_file2.rs", "rank": 10, "score": 89256.59331151526 }, { "content": "pub trait Cache {\n\n fn get_audio_key(&self, _track: SpotifyId, _file: FileId) -> Option<AudioKey> {\n\n None\n\n }\n\n fn put_audio_key(&self, _track: SpotifyId, _file: FileId, _audio_key: AudioKey) { }\n\n\n\n fn get_credentials(&self) -> Option<Credentials> {\n\n None\n\n }\n\n fn put_credentials(&self, _cred: &Credentials) { }\n\n\n\n fn get_file(&self, _file: FileId) -> Option<Box<ReadSeek>> {\n\n None\n\n }\n\n fn put_file(&self, _file: FileId, _contents: &mut Read) { }\n\n}\n\n\n\npub struct NoCache;\n\nimpl Cache for NoCache { }\n\n\n\nmod default_cache;\n\npub use self::default_cache::DefaultCache;\n", "file_path": "src/cache/mod.rs", "rank": 11, "score": 88870.21441867073 }, { "content": "fn find_available_alternative<'a>(session: &Session, track: &'a Track) -> Option<Cow<'a, Track>> {\n\n if track.available {\n\n Some(Cow::Borrowed(track))\n\n } else {\n\n let alternatives = track.alternatives\n\n .iter()\n\n .map(|alt_id| {\n\n session.metadata::<Track>(*alt_id)\n\n })\n\n .collect::<Vec<TrackRef>>();\n\n\n\n eventual::sequence(alternatives.into_iter()).iter().find(|alt| alt.available).map(Cow::Owned)\n\n }\n\n}\n\n\n", "file_path": "src/player.rs", "rank": 12, "score": 86975.60906853528 }, { "content": "pub fn facebook_login() -> Result<Credentials, ()> {\n\n let (tx, rx) = mpsc::channel();\n\n\n\n let csrf = rand::thread_rng().gen_ascii_chars().take(32).collect::<String>();\n\n let handler = ServerHandler {\n\n token_tx: Mutex::new(tx),\n\n csrf: csrf.clone()\n\n };\n\n\n\n let ssl = ssl_context().unwrap();\n\n\n\n let mut listener = hyper::net::HttpsListener::new(\"127.0.0.1:0\", ssl).unwrap();\n\n let port = listener.local_addr().unwrap().port();\n\n\n\n let mut server = hyper::Server::new(listener).handle(handler).unwrap();\n\n\n\n println!(\"Logging in using Facebook, please visit https://login.spotify.com/login-facebook-sso/?csrf={}&port={} in your browser.\",\n\n csrf, port);\n\n\n\n let token = rx.recv().unwrap();\n", "file_path": "src/authentication/facebook.rs", "rank": 13, "score": 86705.79630266677 }, { "content": "#[cfg(not(feature = \"facebook\"))]\n\npub fn facebook_login() -> Result<Credentials, ()> {\n\n Err(())\n\n}\n", "file_path": "src/authentication/mod.rs", "rank": 14, "score": 86705.79630266677 }, { "content": "pub fn apresolve() -> Result<Vec<String>, ()> {\n\n let client = hyper::client::Client::new();\n\n \n\n let mut response = client.get(APRESOLVE_ENDPOINT).send().unwrap();\n\n let mut data = String::new();\n\n response.read_to_string(&mut data).unwrap();\n\n\n\n let data : APResolveData = json::decode(&data).unwrap();\n\n\n\n Ok(data.ap_list)\n\n}\n", "file_path": "src/apresolve.rs", "rank": 15, "score": 86694.46513748386 }, { "content": "pub fn ssl_context() -> Result<Openssl, SslError> {\n\n let cert = try!(X509::from_pem(&mut Cursor::new(SPOTILOCAL_CERT)));\n\n let key = try!(PKey::private_key_from_pem(&mut Cursor::new(SPOTILOCAL_KEY)));\n\n\n\n let mut ctx = try!(SslContext::new(SslMethod::Sslv23));\n\n try!(ctx.set_cipher_list(\"DEFAULT\"));\n\n try!(ctx.set_private_key(&key));\n\n try!(ctx.set_certificate(&cert));\n\n ctx.set_verify(SSL_VERIFY_NONE, None);\n\n Ok(Openssl { context: Arc::new(ctx) })\n\n}\n", "file_path": "src/spotilocal.rs", "rank": 16, "score": 82659.72445484348 }, { "content": "pub trait PacketHandler {\n\n fn handle(&mut self, cmd: u8, data: Vec<u8>, session: &Session);\n\n}\n", "file_path": "src/session.rs", "rank": 17, "score": 79408.68534227065 }, { "content": "pub fn mkdir_existing(path: &Path) -> io::Result<()> {\n\n fs::create_dir(path).or_else(|err| {\n\n if err.kind() == io::ErrorKind::AlreadyExists {\n\n Ok(())\n\n } else {\n\n Err(err)\n\n }\n\n })\n\n}\n\n\n", "file_path": "src/util/mod.rs", "rank": 18, "score": 78992.30977158007 }, { "content": "fn load_track(session: &Session, track_id: SpotifyId) -> Option<vorbis::Decoder<Subfile<AudioDecrypt<Box<ReadSeek>>>>> {\n\n let track = session.metadata::<Track>(track_id).await().unwrap();\n\n\n\n let track = match find_available_alternative(session, &track) {\n\n Some(track) => track,\n\n None => {\n\n warn!(\"Track \\\"{}\\\" is not available\", track.name);\n\n return None;\n\n }\n\n };\n\n\n\n let format = match session.config().bitrate {\n\n Bitrate::Bitrate96 => FileFormat::OGG_VORBIS_96,\n\n Bitrate::Bitrate160 => FileFormat::OGG_VORBIS_160,\n\n Bitrate::Bitrate320 => FileFormat::OGG_VORBIS_320,\n\n };\n\n\n\n\n\n\n\n let file_id = match track.files.get(&format) {\n", "file_path": "src/player.rs", "rank": 19, "score": 76995.58937995763 }, { "content": "#[allow(dead_code)]\n\nfn mk_sink<S: Sink + Open + 'static>() -> Box<Sink> {\n\n Box::new(S::open())\n\n}\n\n\n\n#[cfg(feature = \"portaudio-backend\")]\n\nmod portaudio;\n\n#[cfg(feature = \"portaudio-backend\")]\n\nuse self::portaudio::PortAudioSink;\n\n\n\n#[cfg(feature = \"pulseaudio-backend\")]\n\nmod pulseaudio;\n\n#[cfg(feature = \"pulseaudio-backend\")]\n\nuse self::pulseaudio::PulseAudioSink;\n\n\n\n\n\ndeclare_backends! {\n\n pub const BACKENDS : &'static [(&'static str, &'static (Fn() -> Box<Sink> + Sync + Send + 'static))] = &[\n\n #[cfg(feature = \"portaudio-backend\")]\n\n (\"portaudio\", &mk_sink::<PortAudioSink>),\n\n #[cfg(feature = \"pulseaudio-backend\")]\n\n (\"pulseaudio\", &mk_sink::<PulseAudioSink>),\n\n\n\n ];\n\n}\n", "file_path": "src/audio_backend/mod.rs", "rank": 20, "score": 76880.35044341566 }, { "content": "pub fn discovery_login(device_name: &str, device_id: &str) -> Result<Credentials, ()> {\n\n let (tx, rx) = mpsc::channel();\n\n\n\n let key_data = util::rand_vec(&mut rand::thread_rng(), 95);\n\n let private_key = BigUint::from_bytes_be(&key_data);\n\n let public_key = util::powm(&DH_GENERATOR, &private_key, &DH_PRIME);\n\n\n\n let handler = ServerHandler {\n\n device_name: device_name.to_owned(),\n\n device_id: device_id.to_owned(),\n\n private_key: private_key,\n\n public_key: public_key,\n\n credentials_tx: Mutex::new(tx),\n\n };\n\n\n\n let mut listener = hyper::net::HttpListener::new(\"0.0.0.0:0\").unwrap();\n\n let port = listener.local_addr().unwrap().port();\n\n\n\n let mut server = hyper::Server::new(listener).handle(handler).unwrap();\n\n\n", "file_path": "src/authentication/discovery.rs", "rank": 21, "score": 69770.36742704059 }, { "content": "#[cfg(not(feature = \"discovery\"))]\n\npub fn discovery_login(_device_name: &str, _device_id: &str) -> Result<Credentials, ()> {\n\n Err(())\n\n}\n\n\n\n#[cfg(feature = \"facebook\")]\n\nmod facebook;\n\n#[cfg(feature = \"facebook\")]\n\npub use self::facebook::facebook_login;\n", "file_path": "src/authentication/mod.rs", "rank": 22, "score": 69770.36742704059 }, { "content": "pub fn load_appkey<P: AsRef<Path>>(path: Option<P>) -> Vec<u8> {\n\n path.map(|path| {\n\n let mut file = File::open(path).expect(\"Could not open app key.\");\n\n\n\n let mut data = Vec::new();\n\n file.read_to_end(&mut data).unwrap();\n\n\n\n data\n\n }).or_else(|| APPKEY.map(ToOwned::to_owned)).unwrap()\n\n}\n\n\n", "file_path": "src/main_helper.rs", "rank": 23, "score": 67184.1451115371 }, { "content": "pub fn powm(base: &BigUint, exp: &BigUint, modulus: &BigUint) -> BigUint {\n\n let mut base = base.clone();\n\n let mut exp = exp.clone();\n\n let mut result: BigUint = One::one();\n\n\n\n while !exp.is_zero() {\n\n if exp.is_odd() {\n\n result = result.mul(&base).rem(modulus);\n\n }\n\n exp = exp.shr(1);\n\n base = (&base).mul(&base).rem(modulus);\n\n }\n\n\n\n result\n\n}\n\n\n\npub struct StrChunks<'s>(&'s str, usize);\n\n\n", "file_path": "src/util/mod.rs", "rank": 24, "score": 65929.98697230978 }, { "content": "#[cfg(feature = \"with-tremor\")]\n\nfn vorbis_time_tell_ms<R>(decoder: &mut vorbis::Decoder<R>) -> Result<i64, vorbis::VorbisError> where R: Read + Seek {\n\n decoder.time_tell()\n\n}\n\n\n\npub type PlayerObserver = Box<Fn(&PlayerState) + Send>;\n\n\n\n#[derive(Clone)]\n\npub struct Player {\n\n state: Arc<Mutex<PlayerState>>,\n\n observers: Arc<Mutex<Vec<PlayerObserver>>>,\n\n\n\n commands: mpsc::Sender<PlayerCommand>,\n\n}\n\n\n\n#[derive(Clone)]\n\npub struct PlayerState {\n\n pub status: PlayStatus,\n\n pub position_ms: u32,\n\n pub position_measured_at: i64,\n\n pub update_time: i64,\n\n pub volume: u16,\n\n pub track: Option<SpotifyId>,\n\n\n\n pub end_of_track: bool,\n\n}\n\n\n", "file_path": "src/player.rs", "rank": 25, "score": 57463.23937772603 }, { "content": "struct PlayerInternal {\n\n state: Arc<Mutex<PlayerState>>,\n\n observers: Arc<Mutex<Vec<PlayerObserver>>>,\n\n\n\n session: Session,\n\n commands: mpsc::Receiver<PlayerCommand>,\n\n}\n\n\n", "file_path": "src/player.rs", "rank": 26, "score": 56489.91915530838 }, { "content": "struct SpircInternal {\n\n player: Player,\n\n session: Session,\n\n\n\n seq_nr: u32,\n\n\n\n name: String,\n\n ident: String,\n\n device_type: u8,\n\n can_play: bool,\n\n\n\n repeat: bool,\n\n shuffle: bool,\n\n\n\n is_active: bool,\n\n became_active_at: i64,\n\n\n\n last_command_ident: String,\n\n last_command_msgid: u32,\n\n\n", "file_path": "src/spirc.rs", "rank": 27, "score": 56489.91915530838 }, { "content": "#[cfg(feature = \"with-tremor\")]\n\nfn vorbis_time_seek_ms<R>(decoder: &mut vorbis::Decoder<R>, ms: i64) -> Result<(), vorbis::VorbisError> where R: Read + Seek {\n\n decoder.time_seek(ms)\n\n}\n\n\n", "file_path": "src/player.rs", "rank": 28, "score": 55747.79038615256 }, { "content": "struct ServerHandler {\n\n credentials_tx: Mutex<mpsc::Sender<Credentials>>,\n\n private_key: BigUint,\n\n public_key: BigUint,\n\n device_id: String,\n\n device_name: String,\n\n}\n\n\n\nimpl ServerHandler {\n\n fn handle_get_info(&self, _params: &BTreeMap<String, String>,\n\n mut response: hyper::server::Response<hyper::net::Fresh>) {\n\n\n\n let public_key = self.public_key.to_bytes_be()\n\n .to_base64(base64::STANDARD);\n\n\n\n let result = json!({\n\n \"status\": 101,\n\n \"statusString\": \"ERROR-OK\",\n\n \"spotifyError\": 0,\n\n \"version\": \"2.1.0\",\n", "file_path": "src/authentication/discovery.rs", "rank": 29, "score": 55115.808386263954 }, { "content": "#[derive(Debug, Clone)]\n\n#[derive(RustcDecodable, RustcEncodable)]\n\nstruct StoredCredentials {\n\n pub username: String,\n\n pub auth_type: i32,\n\n pub auth_data: String,\n\n}\n\n\n\nimpl Credentials {\n\n pub fn with_password(username: String, password: String) -> Credentials {\n\n Credentials {\n\n username: username,\n\n auth_type: AuthenticationType::AUTHENTICATION_USER_PASS,\n\n auth_data: password.into_bytes(),\n\n }\n\n }\n\n\n\n pub fn with_blob(username: String, encrypted_blob: &str, device_id: &str) -> Credentials {\n\n fn read_u8<R: Read>(stream: &mut R) -> io::Result<u8> {\n\n let mut data = [0u8];\n\n try!(stream.read_exact(&mut data));\n\n Ok(data[0])\n", "file_path": "src/authentication/mod.rs", "rank": 30, "score": 55115.808386263954 }, { "content": "struct ServerHandler {\n\n token_tx: Mutex<mpsc::Sender<String>>,\n\n csrf: String,\n\n}\n\n\n\nimpl ServerHandler {\n\n fn handle_login(&self, params: &BTreeMap<String, String>) -> hyper::status::StatusCode {\n\n let token = params.get(\"access_token\").unwrap();\n\n let csrf = params.get(\"csrf\").unwrap();\n\n\n\n if *csrf == self.csrf {\n\n self.token_tx.lock().unwrap().send(token.to_owned()).unwrap();\n\n hyper::status::StatusCode::Ok\n\n } else {\n\n hyper::status::StatusCode::Forbidden\n\n }\n\n }\n\n}\n\n\n\nimpl hyper::server::Handler for ServerHandler {\n", "file_path": "src/authentication/facebook.rs", "rank": 31, "score": 55115.808386263954 }, { "content": "struct CommandSender<'a> {\n\n spirc_internal: &'a mut SpircInternal,\n\n cmd: MessageType,\n\n recipient: Option<&'a str>,\n\n player_state: Option<&'a PlayerState>,\n\n state: Option<protocol::spirc::State>,\n\n}\n\n\n\nimpl<'a> CommandSender<'a> {\n\n fn new(spirc_internal: &'a mut SpircInternal, cmd: MessageType) -> CommandSender {\n\n CommandSender {\n\n spirc_internal: spirc_internal,\n\n cmd: cmd,\n\n recipient: None,\n\n player_state: None,\n\n state: None,\n\n }\n\n }\n\n\n\n fn recipient(mut self, r: &'a str) -> CommandSender {\n", "file_path": "src/spirc.rs", "rank": 32, "score": 54630.8930457892 }, { "content": "#[cfg(not(feature = \"with-syntex\"))]\n\nfn codegen() { }\n\n\n", "file_path": "build.rs", "rank": 33, "score": 54405.60185586079 }, { "content": "#[cfg(feature = \"with-syntex\")]\n\nfn codegen() {\n\n use std::env;\n\n use std::path::PathBuf;\n\n use std::path::Path;\n\n\n\n let mut registry = syntex::Registry::new();\n\n let out = PathBuf::from(env::var(\"OUT_DIR\").unwrap());\n\n\n\n json_macros::plugin_registrar(&mut registry);\n\n protobuf_macros::plugin_registrar(&mut registry);\n\n registry.expand(\"librespot\", Path::new(\"src/lib.in.rs\"), &out.join(\"lib.rs\")).unwrap();\n\n}\n\n\n", "file_path": "build.rs", "rank": 34, "score": 54405.60185586079 }, { "content": "fn main() {\n\n vergen::vergen(vergen::OutputFns::all()).unwrap();\n\n codegen();\n\n}\n\n\n", "file_path": "build.rs", "rank": 35, "score": 54405.60185586079 }, { "content": "struct AudioFileShared {\n\n cond: Condvar,\n\n bitmap: Mutex<BitSet>,\n\n}\n\n\n\nimpl AudioFile {\n\n pub fn new(session: &Session, file_id: FileId)\n\n -> (eventual::Future<AudioFile, ()>, eventual::Future<NamedTempFile, ()>) {\n\n\n\n let shared = Arc::new(AudioFileShared {\n\n cond: Condvar::new(),\n\n bitmap: Mutex::new(BitSet::new()),\n\n });\n\n\n\n let (seek_tx, seek_rx) = mpsc::channel();\n\n let (partial_tx, partial_rx) = eventual::Future::pair();\n\n let (complete_tx, complete_rx) = eventual::Future::pair();\n\n\n\n let internal = AudioFileInternal {\n\n shared: shared.clone(),\n", "file_path": "src/audio_file.rs", "rank": 36, "score": 53858.355393550766 }, { "content": "struct AudioFileInternal {\n\n partial_tx: Option<eventual::Complete<fs::File, ()>>,\n\n complete_tx: eventual::Complete<NamedTempFile, ()>,\n\n write_file: NamedTempFile,\n\n seek_rx: mpsc::Receiver<u64>,\n\n shared: Arc<AudioFileShared>,\n\n chunk_count: usize,\n\n}\n\n\n", "file_path": "src/audio_file.rs", "rank": 37, "score": 53858.355393550766 }, { "content": "fn main() {\n\n let root = PathBuf::from(env::var(\"CARGO_MANIFEST_DIR\").unwrap());\n\n let out = PathBuf::from(env::var(\"OUT_DIR\").unwrap());\n\n let proto = root.join(\"proto\");\n\n\n\n let mut compiler = protobuf_build::Compiler::new(&proto, &out);\n\n\n\n let files = [\"keyexchange\",\n\n \"authentication\",\n\n \"mercury\",\n\n \"metadata\",\n\n \"pubsub\",\n\n \"spirc\"];\n\n\n\n for file in &files {\n\n compiler.compile(&((*file).to_owned() + \".proto\")).unwrap();\n\n\n\n // Hack for rust-lang/rust#18810\n\n // Wrap the generated rust files with \"pub mod { ... }\", so they\n\n // can be included.\n", "file_path": "protocol/build.rs", "rank": 38, "score": 52774.27443501112 }, { "content": "fn main() {\n\n if env::var(\"RUST_LOG\").is_err() {\n\n env::set_var(\"RUST_LOG\", \"info,librespot=trace\")\n\n }\n\n env_logger::init().unwrap();\n\n\n\n let mut opts = getopts::Options::new();\n\n main_helper::add_session_arguments(&mut opts);\n\n main_helper::add_authentication_arguments(&mut opts);\n\n main_helper::add_player_arguments(&mut opts);\n\n\n\n let args: Vec<String> = std::env::args().collect();\n\n\n\n let matches = match opts.parse(&args[1..]) {\n\n Ok(m) => m,\n\n Err(f) => {\n\n error!(\"Error: {}\\n{}\", f.to_string(), usage(&args[0], &opts));\n\n exit(1)\n\n }\n\n };\n", "file_path": "src/main.rs", "rank": 39, "score": 52774.27443501112 }, { "content": "pub trait Sink {\n\n fn start(&self) -> io::Result<()>;\n\n fn stop(&self) -> io::Result<()>;\n\n fn write(&self, data: &[i16]) -> io::Result<()>;\n\n}\n\n\n\n/*\n\n * Allow #[cfg] rules around elements of a list.\n\n * Workaround until stmt_expr_attributes is stable.\n\n *\n\n * This generates 2^n declarations of the list, with every combination possible\n\n */\n\nmacro_rules! declare_backends {\n\n (pub const $name:ident : $ty:ty = & [ $($tt:tt)* ];) => (\n\n _declare_backends!($name ; $ty ; []; []; []; $($tt)*);\n\n );\n\n}\n\n\n\nmacro_rules! _declare_backends {\n\n ($name:ident ; $ty:ty ; [ $($yes:meta,)* ] ; [ $($no:meta,)* ] ; [ $($exprs:expr,)* ] ; #[cfg($m:meta)] $e:expr, $($rest:tt)* ) => (\n", "file_path": "src/audio_backend/mod.rs", "rank": 40, "score": 49024.391439811276 }, { "content": "pub trait IgnoreExt {\n\n fn ignore(self);\n\n}\n\n\n\nimpl<T, E> IgnoreExt for Result<T, E> {\n\n fn ignore(self) {\n\n match self {\n\n Ok(_) => (),\n\n Err(_) => (),\n\n }\n\n }\n\n}\n\n\n", "file_path": "src/util/mod.rs", "rank": 41, "score": 49024.391439811276 }, { "content": "pub trait Open {\n\n fn open() -> Self;\n\n}\n\n\n", "file_path": "src/audio_backend/mod.rs", "rank": 42, "score": 49024.391439811276 }, { "content": "pub trait Handler: Send {\n\n fn on_create(self, channel_id: ChannelId, session: &Session) -> Response<Self> where Self: Sized;\n\n fn on_header(self, header_id: u8, header_data: &[u8], session: &Session) -> Response<Self> where Self: Sized;\n\n fn on_data(self, data: &[u8], session: &Session) -> Response<Self> where Self: Sized;\n\n fn on_error(self, session: &Session) -> Response<Self> where Self: Sized;\n\n fn on_close(self, session: &Session) -> Response<Self> where Self: Sized;\n\n\n\n fn box_on_create(self: Box<Self>, channel_id: ChannelId, session: &Session) -> Response<Box<Handler>>;\n\n fn box_on_header(self: Box<Self>, header_id: u8, header_data: &[u8], session: &Session) -> Response<Box<Handler>>;\n\n fn box_on_data(self: Box<Self>, data: &[u8], session: &Session) -> Response<Box<Handler>>;\n\n fn box_on_error(self: Box<Self>, session: &Session) -> Response<Box<Handler>>;\n\n fn box_on_close(self: Box<Self>, session: &Session) -> Response<Box<Handler>>;\n\n}\n\n\n\npub type ChannelId = u16;\n\n\n", "file_path": "src/stream.rs", "rank": 43, "score": 48837.68858319914 }, { "content": "pub trait StrChunksExt {\n\n fn chunks(&self, size: usize) -> StrChunks;\n\n}\n\n\n\nimpl StrChunksExt for str {\n\n fn chunks(&self, size: usize) -> StrChunks {\n\n StrChunks(self, size)\n\n }\n\n}\n\n\n\nimpl<'s> Iterator for StrChunks<'s> {\n\n type Item = &'s str;\n\n fn next(&mut self) -> Option<&'s str> {\n\n let &mut StrChunks(data, size) = self;\n\n if data.is_empty() {\n\n None\n\n } else {\n\n let ret = Some(&data[..size]);\n\n self.0 = &data[size..];\n\n ret\n\n }\n\n }\n\n}\n\n\n", "file_path": "src/util/mod.rs", "rank": 44, "score": 47883.86198284701 }, { "content": "struct Channel(ChannelMode, Box<Handler>);\n\n\n\nimpl Channel {\n\n fn handle_packet(self, cmd: u8, data: Vec<u8>, session: &Session) -> Response<Self, Box<Handler>> {\n\n let Channel(mode, mut handler) = self;\n\n\n\n let mut packet = Cursor::new(&data as &[u8]);\n\n packet.read_u16::<BigEndian>().unwrap(); // Skip channel id\n\n\n\n if cmd == 0xa {\n\n println!(\"error: {} {}\", data.len(), packet.read_u16::<BigEndian>().unwrap());\n\n return match handler.box_on_error(session) {\n\n Response::Continue(_) => Response::Close,\n\n Response::Spawn(f) => Response::Spawn(f),\n\n Response::Close => Response::Close,\n\n };\n\n }\n\n\n\n match mode {\n\n ChannelMode::Header => {\n", "file_path": "src/stream.rs", "rank": 45, "score": 47836.100670445885 }, { "content": "#[derive(Debug,Hash,PartialEq,Eq,Copy,Clone)]\n\nstruct AudioKeyId(SpotifyId, FileId);\n\n\n\npub struct AudioKeyManager {\n\n next_seq: u32,\n\n pending: HashMap<u32, AudioKeyId>,\n\n cache: HashMap<AudioKeyId, Vec<eventual::Complete<AudioKey, AudioKeyError>>>,\n\n}\n\n\n\nimpl AudioKeyManager {\n\n pub fn new() -> AudioKeyManager {\n\n AudioKeyManager {\n\n next_seq: 1,\n\n pending: HashMap::new(),\n\n cache: HashMap::new(),\n\n }\n\n }\n\n\n\n fn send_key_request(&mut self, session: &Session, track: SpotifyId, file: FileId) -> u32 {\n\n let seq = self.next_seq;\n\n self.next_seq += 1;\n", "file_path": "src/audio_key.rs", "rank": 46, "score": 46275.78428980043 }, { "content": "use lmdb_rs as lmdb;\n\nuse lmdb_rs::core::MdbResult;\n\nuse std::path::PathBuf;\n\nuse std::io::Read;\n\nuse std::fs::File;\n\n\n\nuse util::{SpotifyId, FileId, ReadSeek, mkdir_existing};\n\nuse authentication::Credentials;\n\nuse audio_key::AudioKey;\n\n\n\nuse super::Cache;\n\n\n\npub struct DefaultCache {\n\n environment: lmdb::Environment,\n\n root: PathBuf,\n\n}\n\n\n\nimpl DefaultCache {\n\n pub fn new(location: PathBuf) -> Result<DefaultCache, ()> {\n\n let env = lmdb::EnvBuilder::new().max_dbs(5).open(&location.join(\"db\"), 0o755).unwrap();\n", "file_path": "src/cache/default_cache.rs", "rank": 47, "score": 39768.03252268439 }, { "content": " self.root.join(\"credentials.json\")\n\n }\n\n}\n\n\n\nimpl Cache for DefaultCache {\n\n fn get_audio_key(&self, track: SpotifyId, file: FileId) -> Option<AudioKey> {\n\n let reader = self.environment.get_reader().unwrap();\n\n let handle = self.audio_keys().unwrap();\n\n let db = reader.bind(&handle);\n\n\n\n let mut key = Vec::new();\n\n key.extend_from_slice(&track.to_raw());\n\n key.extend_from_slice(&file.0);\n\n\n\n let value : Option<Vec<_>> = db.get(&key).ok();\n\n value.and_then(|value| if value.len() == 16 {\n\n let mut result = [0u8; 16];\n\n result.clone_from_slice(&value);\n\n Some(result)\n\n } else {\n", "file_path": "src/cache/default_cache.rs", "rank": 48, "score": 39763.304036014364 }, { "content": "\n\n fn get_credentials(&self) -> Option<Credentials> {\n\n let path = self.credentials_path();\n\n Credentials::from_file(path)\n\n }\n\n fn put_credentials(&self, cred: &Credentials) {\n\n let path = self.credentials_path();\n\n cred.save_to_file(&path);\n\n }\n\n\n\n fn get_file(&self, file: FileId) -> Option<Box<ReadSeek>> {\n\n File::open(self.file_path(file)).ok().map(|f| Box::new(f) as Box<ReadSeek>)\n\n }\n\n\n\n fn put_file(&self, file: FileId, contents: &mut Read) {\n\n let path = self.file_path(file);\n\n\n\n mkdir_existing(path.parent().unwrap()).unwrap();\n\n\n\n let mut cache_file = File::create(path).unwrap();\n\n ::std::io::copy(contents, &mut cache_file).unwrap();\n\n }\n\n}\n", "file_path": "src/cache/default_cache.rs", "rank": 49, "score": 39761.46337181506 }, { "content": " None\n\n })\n\n }\n\n\n\n fn put_audio_key(&self, track: SpotifyId, file: FileId, audio_key: AudioKey) {\n\n let xact = self.environment.new_transaction().unwrap();\n\n let handle = self.audio_keys().unwrap();\n\n\n\n {\n\n let db = xact.bind(&handle);\n\n\n\n let mut key = Vec::new();\n\n key.extend_from_slice(&track.to_raw());\n\n key.extend_from_slice(&file.0);\n\n\n\n db.set(&key, &audio_key.as_ref()).unwrap();\n\n }\n\n\n\n xact.commit().unwrap();\n\n }\n", "file_path": "src/cache/default_cache.rs", "rank": 50, "score": 39760.08215926997 }, { "content": "\n\n mkdir_existing(&location).unwrap();\n\n mkdir_existing(&location.join(\"files\")).unwrap();\n\n\n\n Ok(DefaultCache {\n\n environment: env,\n\n root: location\n\n })\n\n }\n\n\n\n fn audio_keys(&self) -> MdbResult<lmdb::DbHandle> {\n\n self.environment.create_db(\"audio-keys\", lmdb::DbFlags::empty())\n\n }\n\n\n\n fn file_path(&self, file: FileId) -> PathBuf {\n\n let name = file.to_base16();\n\n self.root.join(\"files\").join(&name[0..2]).join(&name[2..])\n\n }\n\n\n\n fn credentials_path(&self) -> PathBuf {\n", "file_path": "src/cache/default_cache.rs", "rank": 51, "score": 39757.89971319128 }, { "content": "fn countrylist_contains(list: &str, country: &str) -> bool {\n\n list.chunks(2).any(|cc| cc == country)\n\n}\n\n\n", "file_path": "src/metadata.rs", "rank": 52, "score": 39675.33688289046 }, { "content": "fn facebook_get_me_id(token: &str) -> Result<String, ()> {\n\n let url = format!(\"https://graph.facebook.com/me?fields=id&access_token={}\", token);\n\n\n\n let client = hyper::Client::new();\n\n let mut response = client.get(&url).send().unwrap();\n\n let mut body = String::new();\n\n response.read_to_string(&mut body).unwrap();\n\n\n\n let mut result : BTreeMap<String, String> = json::decode(&body).unwrap();\n\n Ok(result.remove(\"id\").unwrap())\n\n}\n\n\n", "file_path": "src/authentication/facebook.rs", "rank": 53, "score": 39675.32978654698 }, { "content": "fn usage(program: &str, opts: &getopts::Options) -> String {\n\n let brief = format!(\"Usage: {} [options]\", program);\n\n format!(\"{}\", opts.usage(&brief))\n\n}\n\n\n", "file_path": "src/main.rs", "rank": 54, "score": 38874.930386970525 }, { "content": "fn apply_volume(volume: u16, data: &[i16]) -> Cow<[i16]> {\n\n // Fast path when volume is 100%\n\n if volume == 0xFFFF {\n\n Cow::Borrowed(data)\n\n } else {\n\n Cow::Owned(data.iter()\n\n .map(|&x| {\n\n (x as i32\n\n * volume as i32\n\n / 0xFFFF) as i16\n\n })\n\n .collect())\n\n }\n\n}\n\n\n", "file_path": "src/player.rs", "rank": 55, "score": 37978.73407829785 }, { "content": "pub trait ReadSeek : ::std::io::Read + ::std::io::Seek { }\n\nimpl <T: ::std::io::Read + ::std::io::Seek> ReadSeek for T { }\n\n\n", "file_path": "src/util/mod.rs", "rank": 56, "score": 36942.41239432573 }, { "content": "fn parse_restrictions<'s, I>(restrictions: I, country: &str, catalogue: &str) -> bool\n\n where I: IntoIterator<Item = &'s protocol::metadata::Restriction>\n\n{\n\n restrictions.into_iter()\n\n .filter(|r| r.get_catalogue_str().contains(&catalogue.to_owned()))\n\n .all(|r| {\n\n !countrylist_contains(r.get_countries_forbidden(), country) &&\n\n (!r.has_countries_allowed() ||\n\n countrylist_contains(r.get_countries_allowed(), country))\n\n })\n\n}\n\n\n", "file_path": "src/metadata.rs", "rank": 57, "score": 36019.87144286735 }, { "content": " tx_connection: Mutex<Option<CipherConnection>>,\n\n}\n\n\n\n#[derive(Clone)]\n\npub struct Session(pub Arc<SessionInternal>);\n\n\n\nimpl Session {\n\n pub fn new(config: Config, cache: Box<Cache + Send + Sync>) -> Session {\n\n let device_id = {\n\n let mut h = Sha1::new();\n\n h.input_str(&config.device_name);\n\n h.result_str()\n\n };\n\n\n\n Session(Arc::new(SessionInternal {\n\n config: config,\n\n device_id: device_id,\n\n data: RwLock::new(SessionData {\n\n country: String::new(),\n\n canonical_username: String::new(),\n", "file_path": "src/session.rs", "rank": 58, "score": 33633.472064811984 }, { "content": " pub device_name: String,\n\n pub bitrate: Bitrate,\n\n}\n\n\n\npub struct SessionData {\n\n country: String,\n\n canonical_username: String,\n\n}\n\n\n\npub struct SessionInternal {\n\n config: Config,\n\n device_id: String,\n\n data: RwLock<SessionData>,\n\n\n\n cache: Box<Cache + Send + Sync>,\n\n mercury: Mutex<MercuryManager>,\n\n metadata: Mutex<MetadataManager>,\n\n stream: Mutex<StreamManager>,\n\n audio_key: Mutex<AudioKeyManager>,\n\n rx_connection: Mutex<Option<CipherConnection>>,\n", "file_path": "src/session.rs", "rank": 59, "score": 33631.518327069316 }, { "content": " }\n\n }\n\n\n\n pub fn recv(&self) -> (u8, Vec<u8>) {\n\n self.0.rx_connection.lock().unwrap().as_mut().unwrap().recv_packet().unwrap()\n\n }\n\n\n\n pub fn send_packet(&self, cmd: u8, data: &[u8]) -> connection::Result<()> {\n\n self.0.tx_connection.lock().unwrap().as_mut().unwrap().send_packet(cmd, data)\n\n }\n\n\n\n pub fn audio_key(&self, track: SpotifyId, file_id: FileId) -> Future<AudioKey, AudioKeyError> {\n\n self.0.cache\n\n .get_audio_key(track, file_id)\n\n .map(Future::of)\n\n .unwrap_or_else(|| {\n\n let self_ = self.clone();\n\n self.0.audio_key.lock().unwrap()\n\n .request(self, track, file_id)\n\n .map(move |key| {\n", "file_path": "src/session.rs", "rank": 60, "score": 33627.32515419328 }, { "content": " self.0.stream.lock().unwrap().create(handler, self)\n\n }\n\n\n\n pub fn metadata<T: MetadataTrait>(&self, id: SpotifyId) -> MetadataRef<T> {\n\n self.0.metadata.lock().unwrap().get(self, id)\n\n }\n\n\n\n pub fn mercury(&self, req: MercuryRequest) -> Future<MercuryResponse, ()> {\n\n self.0.mercury.lock().unwrap().request(self, req)\n\n }\n\n\n\n pub fn mercury_sub(&self, uri: String) -> mpsc::Receiver<MercuryResponse> {\n\n self.0.mercury.lock().unwrap().subscribe(self, uri)\n\n }\n\n\n\n pub fn cache(&self) -> &Cache {\n\n self.0.cache.as_ref()\n\n }\n\n\n\n pub fn config(&self) -> &Config {\n", "file_path": "src/session.rs", "rank": 61, "score": 33625.6712241573 }, { "content": "\n\n pub fn album_cover(&self, file_id: FileId) -> eventual::Future<Vec<u8>, ()> {\n\n self.0.cache\n\n .get_file(file_id)\n\n .map(|mut f| {\n\n let mut data = Vec::new();\n\n f.read_to_end(&mut data).unwrap();\n\n Future::of(data)\n\n })\n\n .unwrap_or_else(|| {\n\n let self_ = self.clone();\n\n AlbumCover::get(file_id, self)\n\n .map(move |data| {\n\n self_.0.cache.put_file(file_id, &mut Cursor::new(&data));\n\n data\n\n })\n\n })\n\n }\n\n\n\n pub fn stream(&self, handler: Box<stream::Handler>) {\n", "file_path": "src/session.rs", "rank": 62, "score": 33625.52600005964 }, { "content": "use connection::{self, PlainConnection, CipherConnection};\n\nuse diffie_hellman::DHLocalKeys;\n\nuse mercury::{MercuryManager, MercuryRequest, MercuryResponse};\n\nuse metadata::{MetadataManager, MetadataRef, MetadataTrait};\n\nuse protocol;\n\nuse stream::StreamManager;\n\nuse util::{self, SpotifyId, FileId, ReadSeek};\n\nuse version;\n\n\n\nuse stream;\n\n\n\npub enum Bitrate {\n\n Bitrate96,\n\n Bitrate160,\n\n Bitrate320,\n\n}\n\n\n\npub struct Config {\n\n pub application_key: Vec<u8>,\n\n pub user_agent: String,\n", "file_path": "src/session.rs", "rank": 63, "score": 33625.115623875354 }, { "content": " }),\n\n\n\n rx_connection: Mutex::new(None),\n\n tx_connection: Mutex::new(None),\n\n\n\n cache: cache,\n\n mercury: Mutex::new(MercuryManager::new()),\n\n metadata: Mutex::new(MetadataManager::new()),\n\n stream: Mutex::new(StreamManager::new()),\n\n audio_key: Mutex::new(AudioKeyManager::new()),\n\n }))\n\n }\n\n\n\n fn connect(&self) -> CipherConnection {\n\n let local_keys = DHLocalKeys::random(&mut thread_rng());\n\n\n\n let aps = apresolve().unwrap();\n\n let ap = thread_rng().choose(&aps).expect(\"No APs found\");\n\n\n\n info!(\"Connecting to AP {}\", ap);\n", "file_path": "src/session.rs", "rank": 64, "score": 33624.78866197742 }, { "content": " self_.0.cache.put_audio_key(track, file_id, key);\n\n key\n\n })\n\n })\n\n }\n\n\n\n pub fn audio_file(&self, file_id: FileId) -> Box<ReadSeek> {\n\n self.0.cache\n\n .get_file(file_id)\n\n .unwrap_or_else(|| {\n\n let (audio_file, complete_rx) = AudioFile::new(self, file_id);\n\n\n\n let self_ = self.clone();\n\n complete_rx.map(move |mut complete_file| {\n\n self_.0.cache.put_file(file_id, &mut complete_file)\n\n }).fire();\n\n\n\n Box::new(audio_file.await().unwrap())\n\n })\n\n }\n", "file_path": "src/session.rs", "rank": 65, "score": 33624.31757587351 }, { "content": " devkey: self.config().application_key[0x1..0x81].to_vec(),\n\n signature: self.config().application_key[0x81..0x141].to_vec(),\n\n useragent: self.config().user_agent.clone(),\n\n callback_hash: vec![0; 20],\n\n }\n\n });\n\n\n\n let mut connection = self.connect();\n\n connection.send_packet(0xab, &packet.write_to_bytes().unwrap()).unwrap();\n\n let (cmd, data) = connection.recv_packet().unwrap();\n\n\n\n match cmd {\n\n 0xac => {\n\n let welcome_data: protocol::authentication::APWelcome =\n\n protobuf::parse_from_bytes(&data).unwrap();\n\n\n\n let username = welcome_data.get_canonical_username().to_owned();\n\n self.0.data.write().unwrap().canonical_username = username.clone();\n\n *self.0.rx_connection.lock().unwrap() = Some(connection.clone());\n\n *self.0.tx_connection.lock().unwrap() = Some(connection);\n", "file_path": "src/session.rs", "rank": 66, "score": 33623.49052255568 }, { "content": "use crypto::digest::Digest;\n\nuse crypto::sha1::Sha1;\n\nuse crypto::hmac::Hmac;\n\nuse crypto::mac::Mac;\n\nuse eventual;\n\nuse eventual::Future;\n\nuse eventual::Async;\n\nuse protobuf::{self, Message};\n\nuse rand::thread_rng;\n\nuse rand::Rng;\n\nuse std::io::{Read, Write, Cursor};\n\nuse std::result::Result;\n\nuse std::sync::{Mutex, RwLock, Arc, mpsc};\n\n\n\nuse album_cover::AlbumCover;\n\nuse apresolve::apresolve;\n\nuse audio_key::{AudioKeyManager, AudioKey, AudioKeyError};\n\nuse audio_file::AudioFile;\n\nuse authentication::Credentials;\n\nuse cache::Cache;\n", "file_path": "src/session.rs", "rank": 67, "score": 33622.09984796714 }, { "content": " &self.0.config\n\n }\n\n\n\n pub fn username(&self) -> String {\n\n self.0.data.read().unwrap().canonical_username.clone()\n\n }\n\n\n\n pub fn country(&self) -> String {\n\n self.0.data.read().unwrap().country.clone()\n\n }\n\n\n\n pub fn device_id(&self) -> &str {\n\n &self.0.device_id\n\n }\n\n}\n\n\n", "file_path": "src/session.rs", "rank": 68, "score": 33619.764891940205 }, { "content": " &send_key,\n\n &recv_key)\n\n }\n\n\n\n pub fn login(&self, credentials: Credentials) -> Result<Credentials, ()> {\n\n let packet = protobuf_init!(protocol::authentication::ClientResponseEncrypted::new(), {\n\n login_credentials => {\n\n username: credentials.username,\n\n typ: credentials.auth_type,\n\n auth_data: credentials.auth_data,\n\n },\n\n system_info => {\n\n cpu_family: protocol::authentication::CpuFamily::CPU_UNKNOWN,\n\n os: protocol::authentication::Os::OS_UNKNOWN,\n\n system_information_string: \"librespot\".to_owned(),\n\n device_id: self.device_id().to_owned(),\n\n },\n\n version_string: version::version_string(),\n\n appkey => {\n\n version: self.config().application_key[0] as u32,\n", "file_path": "src/session.rs", "rank": 69, "score": 33618.66263521767 }, { "content": "\n\n info!(\"Authenticated !\");\n\n\n\n let reusable_credentials = Credentials {\n\n username: username,\n\n auth_type: welcome_data.get_reusable_auth_credentials_type(),\n\n auth_data: welcome_data.get_reusable_auth_credentials().to_owned(),\n\n };\n\n\n\n self.0.cache.put_credentials(&reusable_credentials);\n\n\n\n Ok(reusable_credentials)\n\n }\n\n\n\n 0xad => {\n\n let msg: protocol::keyexchange::APLoginFailed =\n\n protobuf::parse_from_bytes(&data).unwrap();\n\n error!(\"Authentication failed, {:?}\", msg);\n\n Err(())\n\n }\n", "file_path": "src/session.rs", "rank": 70, "score": 33618.37364835439 }, { "content": "\n\n let remote_key = response.get_challenge()\n\n .get_login_crypto_challenge()\n\n .get_diffie_hellman()\n\n .get_gs();\n\n\n\n let shared_secret = local_keys.shared_secret(remote_key);\n\n let (challenge, send_key, recv_key) = {\n\n let mut data = Vec::with_capacity(0x64);\n\n let mut mac = Hmac::new(Sha1::new(), &shared_secret);\n\n\n\n for i in 1..6 {\n\n mac.input(&init_client_packet);\n\n mac.input(&init_server_packet);\n\n mac.input(&[i]);\n\n data.write(&mac.result().code()).unwrap();\n\n mac.reset();\n\n }\n\n\n\n mac = Hmac::new(Sha1::new(), &data[..0x14]);\n", "file_path": "src/session.rs", "rank": 71, "score": 33615.479254896396 }, { "content": " _ => {\n\n error!(\"Unexpected message {:x}\", cmd);\n\n Err(())\n\n }\n\n }\n\n }\n\n\n\n pub fn poll(&self) {\n\n let (cmd, data) = self.recv();\n\n\n\n match cmd {\n\n 0x4 => self.send_packet(0x49, &data).unwrap(),\n\n 0x4a => (),\n\n 0x9 | 0xa => self.0.stream.lock().unwrap().handle(cmd, data, self),\n\n 0xd | 0xe => self.0.audio_key.lock().unwrap().handle(cmd, data, self),\n\n 0x1b => {\n\n self.0.data.write().unwrap().country = String::from_utf8(data).unwrap();\n\n }\n\n 0xb2...0xb6 => self.0.mercury.lock().unwrap().handle(cmd, data, self),\n\n _ => (),\n", "file_path": "src/session.rs", "rank": 72, "score": 33614.93404326388 }, { "content": " ],\n\n */\n\n login_crypto_hello.diffie_hellman => {\n\n gc: local_keys.public_key(),\n\n server_keys_known: 1,\n\n },\n\n client_nonce: util::rand_vec(&mut thread_rng(), 0x10),\n\n padding: vec![0x1e],\n\n feature_set => {\n\n autoupdate2: true,\n\n }\n\n });\n\n\n\n let init_client_packet = connection.send_packet_prefix(&[0, 4],\n\n &request.write_to_bytes().unwrap())\n\n .unwrap();\n\n let init_server_packet = connection.recv_packet().unwrap();\n\n\n\n let response: protocol::keyexchange::APResponseMessage =\n\n protobuf::parse_from_bytes(&init_server_packet[4..]).unwrap();\n", "file_path": "src/session.rs", "rank": 73, "score": 33614.76631369512 }, { "content": " let mut connection = PlainConnection::connect(ap).unwrap();\n\n\n\n let request = protobuf_init!(protocol::keyexchange::ClientHello::new(), {\n\n build_info => {\n\n product: protocol::keyexchange::Product::PRODUCT_LIBSPOTIFY_EMBEDDED,\n\n platform: protocol::keyexchange::Platform::PLATFORM_LINUX_X86,\n\n version: 0x10800000000,\n\n },\n\n /*\n\n fingerprints_supported => [\n\n protocol::keyexchange::Fingerprint::FINGERPRINT_GRAIN\n\n ],\n\n */\n\n cryptosuites_supported => [\n\n protocol::keyexchange::Cryptosuite::CRYPTO_SUITE_SHANNON,\n\n //protocol::keyexchange::Cryptosuite::CRYPTO_SUITE_RC4_SHA1_HMAC\n\n ],\n\n /*\n\n powschemes_supported => [\n\n protocol::keyexchange::Powscheme::POW_HASH_CASH\n", "file_path": "src/session.rs", "rank": 74, "score": 33614.70729551914 }, { "content": " mac.input(&init_client_packet);\n\n mac.input(&init_server_packet);\n\n\n\n (mac.result().code().to_vec(),\n\n data[0x14..0x34].to_vec(),\n\n data[0x34..0x54].to_vec())\n\n };\n\n\n\n let packet = protobuf_init!(protocol::keyexchange::ClientResponsePlaintext::new(), {\n\n login_crypto_response.diffie_hellman => {\n\n hmac: challenge\n\n },\n\n pow_response => {},\n\n crypto_response => {},\n\n });\n\n\n\n\n\n connection.send_packet(&packet.write_to_bytes().unwrap()).unwrap();\n\n\n\n CipherConnection::new(connection.into_stream(),\n", "file_path": "src/session.rs", "rank": 75, "score": 33612.83708516431 }, { "content": "fn track_ids_to_state<I: Iterator<Item = SpotifyId>>(track_ids: I) -> protocol::spirc::State {\n\n let tracks: Vec<protocol::spirc::TrackRef> =\n\n track_ids.map(|i| {\n\n protobuf_init!(protocol::spirc::TrackRef::new(), { gid: i.to_raw().to_vec()})\n\n })\n\n .collect();\n\n protobuf_init!(protocol::spirc::State::new(), {\n\n track: RepeatedField::from_vec(tracks)\n\n })\n\n}\n", "file_path": "src/spirc.rs", "rank": 76, "score": 33003.05431919625 }, { "content": " pub device_id: *const c_char,\n\n pub proxy: *const c_char,\n\n pub proxy_username: *const c_char,\n\n pub proxy_password: *const c_char,\n\n pub tracefile: *const c_char,\n\n}\n\n\n\n#[repr(C)]\n\n#[derive(Clone, Copy)]\n\npub struct sp_session_callbacks {\n\n pub logged_in: Option<unsafe extern \"C\" fn(session: *mut sp_session,\n\n error: sp_error)>,\n\n\n\n pub logged_out: Option<unsafe extern \"C\" fn(session: *mut sp_session)>,\n\n\n\n pub metadata_updated: Option<unsafe extern \"C\" fn(session: *mut sp_session)>,\n\n\n\n pub connection_error: Option<unsafe extern \"C\" fn(session: *mut sp_session,\n\n error: sp_error)>,\n\n\n", "file_path": "capi/src/types.rs", "rank": 77, "score": 32587.987706190794 }, { "content": "\n\n pub userinfo_updated: Option<unsafe extern \"C\" fn(session: *mut sp_session)>,\n\n\n\n pub start_playback: Option<unsafe extern \"C\" fn(session: *mut sp_session)>,\n\n\n\n pub stop_playback: Option<unsafe extern \"C\" fn(session: *mut sp_session)>,\n\n\n\n pub get_audio_buffer_stats: Option<unsafe extern \"C\" fn(session: *mut sp_session,\n\n stats: *mut sp_audio_buffer_stats)>,\n\n\n\n pub offline_status_updated: Option<unsafe extern \"C\" fn(session: *mut sp_session)>,\n\n\n\n pub offline_error: Option<unsafe extern \"C\" fn(session: *mut sp_session,\n\n error: sp_error)>,\n\n\n\n pub credentials_blob_updated: Option<unsafe extern \"C\" fn(session: *mut sp_session,\n\n blob: *const c_char)>,\n\n\n\n pub connectionstate_updated: Option<unsafe extern \"C\" fn(session: *mut sp_session)>,\n\n\n", "file_path": "capi/src/types.rs", "rank": 78, "score": 32586.79338664557 }, { "content": " pub message_to_user: Option<unsafe extern \"C\" fn(session: *mut sp_session,\n\n message: *const c_char)>,\n\n\n\n pub notify_main_thread: Option<unsafe extern \"C\" fn(session: *mut sp_session)>,\n\n\n\n pub music_delivery: Option<unsafe extern \"C\" fn(session: *mut sp_session,\n\n format: *const sp_audioformat,\n\n frames: *const c_void,\n\n num_frames: c_int)\n\n -> c_int>,\n\n\n\n pub play_token_lost: Option<unsafe extern \"C\" fn(session: *mut sp_session)>,\n\n\n\n pub log_message: Option<unsafe extern \"C\" fn(session: *mut sp_session,\n\n data: *const c_char)>,\n\n\n\n pub end_of_track: Option<unsafe extern \"C\" fn(session: *mut sp_session)>,\n\n\n\n pub streaming_error: Option<unsafe extern \"C\" fn(session: *mut sp_session,\n\n error: sp_error)>,\n", "file_path": "capi/src/types.rs", "rank": 79, "score": 32586.524230603172 }, { "content": " SP_ERROR_OFFLINE_LICENSE_ERROR = 36,\n\n SP_ERROR_LASTFM_AUTH_ERROR = 39,\n\n SP_ERROR_INVALID_ARGUMENT = 40,\n\n SP_ERROR_SYSTEM_FAILURE = 41,\n\n}\n\n\n\n#[repr(C)]\n\n#[derive(Copy,Clone)]\n\npub struct sp_session_config {\n\n pub api_version: c_int,\n\n pub cache_location: *const c_char,\n\n pub settings_location: *const c_char,\n\n pub application_key: *const c_void,\n\n pub application_key_size: size_t,\n\n pub user_agent: *const c_char,\n\n pub callbacks: *const sp_session_callbacks,\n\n pub userdata: *mut c_void,\n\n pub compress_playlists: bool,\n\n pub dont_save_metadata_for_playlists: bool,\n\n pub initially_unload_playlists: bool,\n", "file_path": "capi/src/types.rs", "rank": 80, "score": 32585.95670858822 }, { "content": " pub scrobble_error: Option<unsafe extern \"C\" fn(session: *mut sp_session,\n\n error: sp_error)>,\n\n\n\n pub private_session_mode_changed: Option<unsafe extern \"C\" fn(session: *mut sp_session,\n\n is_private: bool)>,\n\n}\n\n\n\n#[repr(C)]\n\n#[derive(Clone, Copy)]\n\npub struct sp_audioformat {\n\n pub sample_type: sp_sampletype,\n\n pub sample_rate: c_int,\n\n pub channels: c_int,\n\n}\n\n\n\n#[derive(Clone, Copy)]\n\n#[repr(u32)]\n\npub enum sp_sampletype {\n\n SP_SAMPLETYPE_INT16_NATIVE_ENDIAN = 0,\n\n _Dummy // rust #10292\n\n}\n\n\n\n#[repr(C)]\n\n#[derive(Clone, Copy)]\n\npub struct sp_audio_buffer_stats {\n\n pub samples: c_int,\n\n pub stutter: c_int,\n\n}\n", "file_path": "capi/src/types.rs", "rank": 81, "score": 32585.5878626697 }, { "content": "#![allow(non_camel_case_types, dead_code)]\n\n\n\nuse libc::{size_t, c_int, c_char, c_void};\n\nuse session::sp_session;\n\n\n\n#[derive(Clone, Copy)]\n\n#[repr(u32)]\n\npub enum sp_error {\n\n SP_ERROR_OK = 0,\n\n SP_ERROR_BAD_API_VERSION = 1,\n\n SP_ERROR_API_INITIALIZATION_FAILED = 2,\n\n SP_ERROR_TRACK_NOT_PLAYABLE = 3,\n\n SP_ERROR_BAD_APPLICATION_KEY = 5,\n\n SP_ERROR_BAD_USERNAME_OR_PASSWORD = 6,\n\n SP_ERROR_USER_BANNED = 7,\n\n SP_ERROR_UNABLE_TO_CONTACT_SERVER = 8,\n\n SP_ERROR_CLIENT_TOO_OLD = 9,\n\n SP_ERROR_OTHER_PERMANENT = 10,\n\n SP_ERROR_BAD_USER_AGENT = 11,\n\n SP_ERROR_MISSING_CALLBACK = 12,\n", "file_path": "capi/src/types.rs", "rank": 82, "score": 32581.57321263122 }, { "content": " SP_ERROR_INVALID_INDATA = 13,\n\n SP_ERROR_INDEX_OUT_OF_RANGE = 14,\n\n SP_ERROR_USER_NEEDS_PREMIUM = 15,\n\n SP_ERROR_OTHER_TRANSIENT = 16,\n\n SP_ERROR_IS_LOADING = 17,\n\n SP_ERROR_NO_STREAM_AVAILABLE = 18,\n\n SP_ERROR_PERMISSION_DENIED = 19,\n\n SP_ERROR_INBOX_IS_FULL = 20,\n\n SP_ERROR_NO_CACHE = 21,\n\n SP_ERROR_NO_SUCH_USER = 22,\n\n SP_ERROR_NO_CREDENTIALS = 23,\n\n SP_ERROR_NETWORK_DISABLED = 24,\n\n SP_ERROR_INVALID_DEVICE_ID = 25,\n\n SP_ERROR_CANT_OPEN_TRACE_FILE = 26,\n\n SP_ERROR_APPLICATION_BANNED = 27,\n\n SP_ERROR_OFFLINE_TOO_MANY_TRACKS = 31,\n\n SP_ERROR_OFFLINE_DISK_CACHE = 32,\n\n SP_ERROR_OFFLINE_EXPIRED = 33,\n\n SP_ERROR_OFFLINE_NOT_ALLOWED = 34,\n\n SP_ERROR_OFFLINE_LICENSE_LOST = 35,\n", "file_path": "capi/src/types.rs", "rank": 83, "score": 32573.352373668018 }, { "content": "use util::{SpotifyId, FileId, ReadSeek};\n\nuse audio_key::AudioKey;\n\nuse authentication::Credentials;\n\nuse std::io::Read;\n\n\n", "file_path": "src/cache/mod.rs", "rank": 84, "score": 32420.889350221816 }, { "content": "enum MercuryCallback {\n\n Future(eventual::Complete<MercuryResponse, ()>),\n\n Subscription(mpsc::Sender<MercuryResponse>),\n\n Channel,\n\n}\n\n\n\npub struct MercuryPending {\n\n parts: Vec<Vec<u8>>,\n\n partial: Option<Vec<u8>>,\n\n callback: MercuryCallback,\n\n}\n\n\n\npub struct MercuryManager {\n\n next_seq: u32,\n\n pending: HashMap<Vec<u8>, MercuryPending>,\n\n subscriptions: HashMap<String, mpsc::Sender<MercuryResponse>>,\n\n}\n\n\n\nimpl ToString for MercuryMethod {\n\n fn to_string(&self) -> String {\n", "file_path": "src/mercury.rs", "rank": 93, "score": 31187.615488668933 }, { "content": "use std::collections::HashMap;\n\nuse std::ffi::{CString, CStr};\n\n\n\npub struct CStringCache {\n\n cache: HashMap<String, CString>\n\n}\n\n\n\nimpl CStringCache {\n\n pub fn new() -> CStringCache {\n\n CStringCache {\n\n cache: HashMap::new()\n\n }\n\n }\n\n\n\n pub fn intern(&mut self, string: &str) -> &CStr {\n\n self.cache.entry(string.to_owned()).or_insert_with(|| {\n\n CString::new(string).unwrap()\n\n })\n\n }\n\n}\n\n\n", "file_path": "capi/src/cstring_cache.rs", "rank": 94, "score": 30927.818808379354 }, { "content": "## Facebook Accounts\n\n*librespot* can be built with Facebook authentication support. OpenSSL is required for this.\n\n\n\n```shell\n\ncargo build --release --features facebook\n\ntarget/release/librespot --appkey APPKEY --cache CACHEDIR --name DEVICENAME --facebook\n\n```\n\n\n\nThis will print a link to the console, which must be visited on the same computer *librespot* is running on.\n\n\n\n## Audio Backends\n\n*librespot* supports various audio backends. Multiple backends can be enabled at compile time by enabling the\n\ncorresponding cargo feature. By default, only PortAudio is enabled.\n\n\n\nA specific backend can selected at runtime using the `--backend` switch.\n\n\n\n```shell\n\ncargo build --features portaudio-backend\n\ntarget/release/librespot [...] --backend portaudio\n\n```\n\n\n\nThe following backends are currently available :\n\n- PortAudio \n\n- PulseAudio\n\n\n\n## Development\n\nWhen developing *librespot*, it is preferable to use Rust nightly, and build it using the following :\n\n```shell\n\ncargo build --no-default-features --features portaudio-backend\n\n```\n\n\n\nThis produces better compilation error messages than with the default configuration.\n\n\n\n## Disclaimer\n\nUsing this code to connect to Spotify's API is probably forbidden by them, and\n\nmight result in you application key getting banned. Use at you own risk\n\n\n\n## Contact\n\nCome and hang out on gitter if you need help or want to offer some.\n\nhttps://gitter.im/sashahilton00/spotify-connect-resources\n\n\n\n## License\n\nEverything in this repository is licensed under the MIT license.\n\n\n", "file_path": "README.md", "rank": 95, "score": 22550.5539523259 }, { "content": "# librespot\n\n*librespot* is an open source client library for Spotify. It enables\n\napplications to use Spotify's service, without using the official but\n\nclosed-source libspotify. Additionally, it will provide extra features\n\nwhich are not available in the official library.\n\n\n\n## Status\n\n*librespot* is currently under development and is not fully functional yet. You\n\nare however welcome to experiment with it.\n\n\n\n## Building\n\nRust 1.7.0 or later is required to build librespot.\n\n\n\nIt also requires a C and C++ toolchain, with libprotoc and portaudio.\n\n\n\nOn debian / ubuntu, the following command will install these dependencies :\n\n```shell\n\nsudo apt-get install build-essential portaudio19-dev libprotoc-dev\n\n```\n\n\n\nOn Fedora systems, the following command will install these dependencies :\n\n```shell\n\nsudo dnf install portaudio-devel protobuf-devel make gcc gcc-c++\n\n```\n\n\n\nOn OS X, using homebrew :\n\n```shell\n\nbrew install portaudio protobuf\n\n```\n\n\n\nOnce you've cloned this repository you can build *librespot* using `cargo`.\n\n```shell\n\ncargo build --release\n\n```\n\n\n\n## Usage\n\nA sample program implementing a headless Spotify Connect receiver is provided.\n\nOnce you've built *librespot*, run it using :\n\n```shell\n\ntarget/release/librespot --appkey APPKEY --username USERNAME --cache CACHEDIR --name DEVICENAME\n\n```\n\n\n\n## Discovery mode\n\n*librespot* can be run in discovery mode, in which case no password is required at startup.\n\ndns-sd or avahi's compatibility layer is required for this. On debian/ubuntu this is the\n\n`libavahi-compat-libdnssd-dev` package. On Fedora, this is the\n\n`avahi-compat-libdns_sd-devel` package. It come preinstalled on OS X.\n\n\n\nIt must be enabled at build time :\n\n```shell\n\ncargo build --release --features discovery\n\n```\n\n\n\nWhen running *librespot* simply omit the `--username` argument.\n\n\n", "file_path": "README.md", "rank": 96, "score": 22550.106864705976 }, { "content": "# Authentication\n\nOnce the connection is setup, the client can authenticate with the AP. For this, it sends an\n\n`ClientResponseEncrypted` message, using packet type `0xab`.\n\n\n\nA few different authentication methods are available. They are described below.\n\n\n\nThe AP will then reply with either a `APWelcome` message using packet type `0xac` if authentication\n\nis successful, or an `APLoginFailed` with packet type `0xad` otherwise.\n\n\n\n## Password based Authentication\n\nPassword authentication is trivial.\n\nThe `ClientResponseEncrypted` message's `LoginCredentials` is simply filled with the username\n\nand setting the password as the `auth_data`, and type `AUTHENTICATION_USER_PASS`.\n\n\n\n## Zeroconf based Authentication\n\nRather than relying on the user entering a username and password, devices can use zeroconf based\n\nauthentication. This is especially useful for headless Spotify Connect devices.\n\n\n\nIn this case, an already authenticated device, a phone or computer for example, discovers Spotify\n\nConnect receivers on the local network using Zeroconf. The receiver exposes an HTTP server with\n\nservice type `_spotify-connect._tcp`,\n\n\n\nTwo actions on the HTTP server are exposed, `getInfo` and `addUser`.\n\nThe former returns information about the receiver, including its DH public key, in JSON format.\n\nThe latter is used to send the username, the controller's DH public key, as well as the encrypted\n\nblob used to authenticate with Spotify's servers.\n\n\n\nThe blob is decrypted using the following algorithm.\n\n\n\n```\n\n# encrypted_blob is the blob sent by the controller, decoded using base64\n", "file_path": "docs/authentication.md", "rank": 97, "score": 21815.21961993491 }, { "content": " callback: cb,\n\n });\n\n }\n\n\n\n pub fn request(&mut self,\n\n session: &Session,\n\n req: MercuryRequest)\n\n -> eventual::Future<MercuryResponse, ()> {\n\n let (tx, rx) = eventual::Future::pair();\n\n self.request_with_callback(session, req, MercuryCallback::Future(tx));\n\n rx\n\n }\n\n\n\n pub fn subscribe(&mut self, session: &Session, uri: String) -> mpsc::Receiver<MercuryResponse> {\n\n let (tx, rx) = mpsc::channel();\n\n\n\n self.request_with_callback(session,\n\n MercuryRequest {\n\n method: MercuryMethod::SUB,\n\n uri: uri,\n", "file_path": "src/mercury.rs", "rank": 98, "score": 24.946711195573222 }, { "content": " .get_mut(&id)\n\n .map(|ref mut requests| {\n\n let (tx, rx) = eventual::Future::pair();\n\n requests.push(tx);\n\n rx\n\n })\n\n .unwrap_or_else(|| {\n\n let seq = self.send_key_request(session, track, file);\n\n self.pending.insert(seq, id.clone());\n\n\n\n let (tx, rx) = eventual::Future::pair();\n\n self.cache.insert(id, vec![tx]);\n\n rx\n\n })\n\n }\n\n}\n\n\n\nimpl PacketHandler for AudioKeyManager {\n\n fn handle(&mut self, cmd: u8, data: Vec<u8>, _session: &Session) {\n\n let mut data = Cursor::new(data);\n", "file_path": "src/audio_key.rs", "rank": 99, "score": 21.902798819250407 } ]
Rust
src/main.rs
svenstaro/cargo2junit
8f6555bccd025b794e041b2f6ce46321ec12cb91
extern crate junit_report; extern crate serde; use junit_report::*; use serde::{Deserialize, Serialize}; use std; use std::collections::BTreeSet; use std::io::*; #[derive(Serialize, Deserialize, Debug, PartialEq, Eq)] struct SuiteResults { passed: usize, failed: usize, } #[derive(Serialize, Deserialize, Debug, PartialEq, Eq)] #[serde(tag = "event")] enum SuiteEvent { #[serde(rename = "started")] Started { test_count: usize }, #[serde(rename = "ok")] Ok { #[serde(flatten)] results: SuiteResults, }, #[serde(rename = "failed")] Failed { #[serde(flatten)] results: SuiteResults, }, } #[derive(Serialize, Deserialize, Debug, PartialEq, Eq)] #[serde(tag = "event")] enum TestEvent { #[serde(rename = "started")] Started { name: String }, #[serde(rename = "ok")] Ok { name: String }, #[serde(rename = "failed")] Failed { name: String, stdout: String }, #[serde(rename = "ignored")] Ignored { name: String }, #[serde(rename = "timeout")] Timeout { name: String }, } #[derive(Serialize, Deserialize, Debug, PartialEq)] #[serde(untagged)] enum Event { #[serde(rename = "suite")] Suite { #[serde(flatten)] event: SuiteEvent, }, #[serde(rename = "test")] TestStringTime { #[serde(flatten)] event: TestEvent, duration: Option<f64>, exec_time: Option<String>, }, #[serde(rename = "test")] TestFloatTime { #[serde(flatten)] event: TestEvent, duration: Option<f64>, exec_time: Option<f64>, }, } impl Event { fn get_duration(&self) -> Duration { match &self { Event::Suite { event: _ } => panic!(), Event::TestStringTime { event: _, duration, exec_time, } => { let duration_ns = match (duration, exec_time) { (_, Some(s)) => { assert_eq!(s.chars().last(), Some('s')); let seconds_chars = &(s[0..(s.len() - 1)]); let seconds = seconds_chars.parse::<f64>().unwrap(); (seconds * 1_000_000_000.0) as i64 } (Some(ms), None) => (ms * 1_000_000.0) as i64, (None, None) => 0, }; Duration::nanoseconds(duration_ns) }, Event::TestFloatTime { event: _, duration, exec_time, } => { let duration_ns = match (duration, exec_time) { (_, Some(seconds)) => { (seconds * 1_000_000_000.0) as i64 } (Some(ms), None) => (ms * 1_000_000.0) as i64, (None, None) => 0, }; Duration::nanoseconds(duration_ns) } } } } fn split_name(full_name: &str) -> (&str, String) { let mut parts: Vec<&str> = full_name.split("::").collect(); let name = parts.pop().unwrap_or(""); let module_path = parts.join("::"); return (name, module_path); } fn parse<T: BufRead>( input: T, suite_name_prefix: &str, timestamp: DateTime<Utc>, ) -> Result<Report> { let mut r = Report::new(); let mut suite_index = 0; let mut current_suite: Option<TestSuite> = None; let mut tests: BTreeSet<String> = BTreeSet::new(); for line in input.lines() { let line = line?; if line.chars().filter(|c| !c.is_whitespace()).next() != Some('{') { continue; } let e: Event = match serde_json::from_str(&line) { Ok(event) => Ok(event), Err(orig_err) => { let line = line.replace("\\", "\\\\"); match serde_json::from_str(&line) { Ok(event) => Ok(event), Err(_) => Err(Error::new( ErrorKind::Other, format!("Error parsing '{}': {}", &line, orig_err), )), } } }?; match &e { Event::Suite { event } => match event { SuiteEvent::Started { test_count: _ } => { assert!(current_suite.is_none()); assert!(tests.is_empty()); let ts = TestSuite::new(&format!("{} #{}", suite_name_prefix, suite_index)) .set_timestamp(timestamp); current_suite = Some(ts); suite_index += 1; } SuiteEvent::Ok { results: _ } | SuiteEvent::Failed { results: _ } => { assert_eq!(None, tests.iter().next()); r = r.add_testsuite( current_suite.expect("Suite complete event found outside of suite!"), ); current_suite = None; } }, Event::TestStringTime { event, duration: _, exec_time: _, } | Event::TestFloatTime { event, duration: _, exec_time: _, } => { let current_suite = current_suite .as_mut() .expect("Test event found outside of suite!"); let duration = e.get_duration(); match event { TestEvent::Started { name } => { assert!(tests.insert(name.clone())); } TestEvent::Ok { name } => { assert!(tests.remove(name)); let (name, module_path) = split_name(&name); *current_suite = current_suite.clone().add_testcase( TestCase::success(&name, duration).set_classname(module_path.as_str()), ); } TestEvent::Failed { name, stdout } => { assert!(tests.remove(name)); let (name, module_path) = split_name(&name); *current_suite = current_suite.clone().add_testcase( TestCase::failure(&name, duration, "cargo test", &stdout) .set_classname(module_path.as_str()), ); } TestEvent::Ignored { name } => { assert!(tests.remove(name)); } TestEvent::Timeout { name: _ } => { } } } } } Ok(r) } fn main() -> Result<()> { let timestamp = Utc::now(); let stdin = std::io::stdin(); let stdin = stdin.lock(); let report = parse(stdin, "cargo test", timestamp)?; let stdout = std::io::stdout(); let stdout = stdout.lock(); report .write_xml(stdout) .map_err(|e| Error::new(ErrorKind::Other, format!("{}", e)))?; Ok(()) } #[cfg(test)] mod tests { use crate::parse; use junit_report::*; use regex::Regex; use std::io::*; fn parse_bytes(bytes: &[u8]) -> Result<Report> { parse(BufReader::new(bytes), "cargo test", Utc::now()) } fn parse_string(input: &str) -> Result<Report> { parse_bytes(input.as_bytes()) } fn normalize(input: &str) -> String { let date_regex = Regex::new(r"(\d{4})-(\d{2})-(\d{2})T(\d{2}):(\d{2}):(\d{2})\.(\d+)\+00:00").unwrap(); date_regex .replace_all(input, "TIMESTAMP") .replace("\r\n", "\n") } fn assert_output(report: &Report, expected: &[u8]) { let mut output = Vec::new(); report.write_xml(&mut output).unwrap(); let output = normalize(std::str::from_utf8(&output).unwrap()); let expected = normalize(std::str::from_utf8(expected).unwrap()); assert_eq!(output, expected); } #[test] fn error_on_garbage() { assert!(parse_string("{garbage}").is_err()); } #[test] fn success_self() { let report = parse_bytes(include_bytes!("test_inputs/self.json")) .expect("Could not parse test input"); let suite = &report.testsuites()[0]; let test_cases = suite.testcases(); assert_eq!(test_cases[0].name(), "error_on_garbage"); assert_eq!(*test_cases[0].classname(), Some("tests".to_string())); assert_eq!(test_cases[0].time(), &Duration::nanoseconds(213_100)); assert_output(&report, include_bytes!("expected_outputs/self.json.out")); } #[test] fn success_self_exec_time() { let report = parse_bytes(include_bytes!("test_inputs/self_exec_time.json")) .expect("Could not parse test input"); let suite = &report.testsuites()[0]; let test_cases = suite.testcases(); assert_eq!(test_cases[4].name(), "az_func_regression"); assert_eq!(*test_cases[0].classname(), Some("tests".to_string())); assert_eq!(test_cases[4].time(), &Duration::milliseconds(72)); assert_output( &report, include_bytes!("expected_outputs/self_exec_time.json.out"), ); } #[test] fn success_single_suite() { let report = parse_bytes(include_bytes!("test_inputs/success.json")) .expect("Could not parse test input"); assert_output(&report, include_bytes!("expected_outputs/success.json.out")); } #[test] fn success_timeout() { let report = parse_bytes(include_bytes!("test_inputs/timeout.json")) .expect("Could not parse test input"); let suite = &report.testsuites()[0]; let test_cases = suite.testcases(); assert_eq!(test_cases[0].name(), "long_execution_time"); assert_eq!(*test_cases[0].classname(), Some("tests".to_string())); assert!(test_cases[0].is_success()); assert_output(&report, include_bytes!("expected_outputs/timeout.json.out")); } #[test] fn failded_single_suite() { let report = parse_bytes(include_bytes!("test_inputs/failed.json")) .expect("Could not parse test input"); assert_output(&report, include_bytes!("expected_outputs/failed.json.out")); } #[test] fn multi_suite_success() { let report = parse_bytes(include_bytes!("test_inputs/multi_suite_success.json")) .expect("Could not parse test input"); assert_output( &report, include_bytes!("expected_outputs/multi_suite_success.json.out"), ); } #[test] fn cargo_project_failure() { let report = parse_bytes(include_bytes!("test_inputs/cargo_failure.json")) .expect("Could not parse test input"); assert_output( &report, include_bytes!("expected_outputs/cargo_failure.json.out"), ); } #[test] fn az_func_regression() { let report = parse_bytes(include_bytes!("test_inputs/azfunc.json")) .expect("Could not parse test input"); assert_output(&report, include_bytes!("expected_outputs/azfunc.json.out")); } #[test] fn float_time() { parse_bytes(include_bytes!("test_inputs/float_time.json")) .expect("Could not parse test input"); } }
extern crate junit_report; extern crate serde; use junit_report::*; use serde::{Deserialize, Serialize}; use std; use std::collections::BTreeSet; use std::io::*; #[derive(Serialize, Deserialize, Debug, PartialEq, Eq)] struct SuiteResults { passed: usize, failed: usize, } #[derive(Serialize, Deserialize, Debug, PartialEq, Eq)] #[serde(tag = "event")] enum SuiteEvent { #[serde(rename = "started")] Started { test_count: usize }, #[serde(rename = "ok")] Ok { #[serde(flatten)] results: SuiteResults, }, #[serde(rename = "failed")] Failed { #[serde(flatten)] results: SuiteResults, }, } #[derive(Serialize, Deserialize, Debug, PartialEq, Eq)] #[serde(tag = "event")] enum TestEvent { #[serde(rename = "started")] Started { name: String }, #[serde(rename = "ok")] Ok { name: String }, #[serde(rename = "failed")] Failed { name: String, stdout: String }, #[serde(rename = "ignored")] Ignored { name: String }, #[serde(rename = "timeout")] Timeout { name: String }, } #[derive(Serialize, Deserialize, Debug, PartialEq)] #[serde(untagged)] enum Event { #[serde(rename = "suite")] Suite { #[serde(flatten)] event: SuiteEvent, }, #[serde(rename = "test")] TestStringTime { #[serde(flatten)] event: TestEvent, duration: Option<f64>, exec_time: Option<String>, }, #[serde(rename = "test")] TestFloatTime { #[serde(flatten)] event: TestEvent, duration: Option<f64>, exec_time: Option<f64>, }, } impl Event { fn get_duration(&self) -> Duration { match &self { Event::Suite { event: _ } => panic!(), Event::TestStringTime { event: _, duration, exec_time, } => { let duration_ns = match (duration, exec_time) { (_, Some(s)) => { assert_eq!(s.chars().last(), Some('s')); let seconds_chars = &(s[0..(s.len() - 1)]); let seconds = seconds_chars.parse::<f64>().unwrap(); (seconds * 1_000_000_000.0) as i64 } (Some(ms), None) => (ms * 1_000_000.0) as i64, (None, None) => 0, }; Duration::nanoseconds(duration_ns) }, Event::TestFloatTime { event: _, duration, exec_time, } => { let duration_ns = match (duration, exec_time) { (_, Some(seconds)) => { (seconds * 1_000_000_000.0) as i64 } (Some(ms), None) => (ms * 1_000_000.0) as i64, (None, None) => 0, }; Duration::nanoseconds(duration_ns) } } } } fn split_name(full_name: &str) -> (&str, String) { let mut parts: Vec<&str> = full_name.split("::").collect(); let name = parts.pop().unwrap_or(""); let module_path = parts.join("::"); return (name, module_path); } fn parse<T: BufRead>( input: T, suite_name_prefix: &str, timestamp: DateTime<Utc>, ) -> Result<Report> { let mut r = Report::new(); let mut suite_index = 0; let mut current_suite: Option<TestSuite> = None; let mut tests: BTreeSet<String> = BTreeSet::new(); for line in input.lines() { let line = line?; if line.chars().filter(|c| !c.is_whitespace()).next() != Some('{') { continue; } let e: Event = match serde_json::from_str(&line) { Ok(event) => Ok(event), Err(orig_err) => { let line = line.replace("\\", "\\\\"); match serde_json::from_str(&line) { Ok(event) => Ok(event), Err(_) => Err(Error::new( ErrorKind::Other, format!("Error parsing '{}': {}", &line, orig_err), )), } } }?; match &e { Event::Suite { event } => match event { SuiteEvent::Started { test_count: _ } => { assert!(current_suite.is_none()); assert!(tests.is_empty()); let ts = TestSuite::new(&format!("{} #{}", suite_name_prefix, suite_index)) .set_timestamp(timestamp); current_suite = Some(ts); suite_index += 1; } SuiteEvent::Ok { results: _ } | SuiteEvent::Failed { results: _ } => { assert_eq!(None, tests.iter().next()); r = r.add_testsuite( current_suite.expect("Suite complete event found outside of suite!"), ); current_suite = None; } }, Event::TestStringTime { event, duration: _, exec_time: _, } | Event::TestFloatTime { event, duration: _, exec_time: _, } => { let current_suite = current_suite .as_mut() .expect("Test event found outside of suite!"); let duration = e.get_duration(); match event { TestEvent::Started { name } => { assert!(tests.insert(name.clone())); } TestEvent::Ok { name } => { assert!(tests.remove(name)); let (name, module_path) = split_name(&name); *current_suite = current_suite.clone().add_testcase( TestCase::success(&name, duration).set_classname(module_path.as_str()), ); } TestEvent::Failed { name, stdout } => { assert!(tests.remove(name)); let (name, module_path) = split_name(&name); *current_suite = current_suite.clone().add_testcase( TestCase::failure(&name, duration, "cargo test", &stdout) .set_classname(module_path.as_str()), ); } TestEvent::Ignored { name } => { assert!(tests.remove(name)); } TestEvent::Timeout { name: _ } => { } } } } } Ok(r) } fn main() -> Result<()> { let timestamp = Utc::now(); let stdin = std::io::stdin(); let stdin = stdin.lock(); let report = parse(stdin, "cargo test", timestamp)?; let stdout = std::io::stdout(); let stdout = stdout.lock(); report .write_xml(stdout) .map_err(|e| Error::new(ErrorKind::Other, format!("{}", e)))?; Ok(()) } #[cfg(test)] mod tests { use crate::parse; use junit_report::*; use regex::Regex; use std::io::*; fn parse_bytes(bytes: &[u8]) -> Result<Report> { parse(BufReader::new(bytes), "cargo test", Utc::now()) } fn parse_string(input: &str) -> Result<Report> { parse_bytes(input.as_bytes()) } fn normalize(input: &str) -> String { let date_regex = Regex::new(r"(\d{4})-(\d{2})-(\d{2})T(\d{2}):(\d{2}):(\d{2})\.(\d+)\+00:00").unwrap(); date_regex .replace_all(input, "TIMESTAMP") .replace("\r\n", "\n") } fn assert_output(report: &Report, expected: &[u8]) { let mut output = Vec::new(); report.write_xml(&mut output).unwrap(); let output = normalize(std::str::from_utf8(&output).unwrap()); let expected = normalize(std::str::from_utf8(expected).unwrap()); assert_eq!(output, expected); } #[test] fn error_on_garbage() { assert!(parse_string("{garbage}").is_err()); } #[test] fn success_self() { let report = parse_bytes(include_bytes!("test_inputs/self.json")) .expect("Could not parse test input"); let suite = &report.testsuites()[0]; let test_cases = suite.testcases(); assert_eq!(test_cases[0].name(), "error_on_garbage"); assert_eq!(*test_cases[0].classname(), Some("tests".to_string())); assert_eq!(test_cases[0].time(), &Duration::nanoseconds(213_100)); assert_output(&report, include_bytes!("expected_outputs/self.json.out")); } #[test] fn success_self_exec_time() { let report = parse_bytes(include_bytes!("test_inputs/self_exec_time.json")) .expect("Could not parse test input"); let suite = &report.testsuites()[0]; let test_cases = suite.testcases(); assert_eq!(test_cases[4].name(), "az_func_regression"); assert_eq!(*test_cases[0].classname(), Some("tests".to_string())); assert_eq!(test_cases[4].time(), &Duration::milliseconds(72)); assert_output( &report, include_bytes!("expected_outputs/self_exec_time.json.out"), ); } #[test] fn success_single_suite() { let report = parse_bytes(include_bytes!("test_inputs/success.json")) .expect("Could not parse test input"); assert_output(&report, include_bytes!("expected_outputs/success.json.out")); } #[test] fn success_timeout() { let report = parse_bytes(include_bytes!("test_inputs/timeout.json")) .expect("Could not parse test input"); let suite = &report.testsuites()[0]; let test_cases = suite.testcases(); assert_eq!(test_cases[0].name(), "long_execution_time"); assert_eq!(*test_cases[0].classname(), Some("tests".to_string())); assert!(test_cases[0].is_success()); assert_output(&report, include_bytes!("expected_outputs/timeout.json.out")); } #[test] fn failded_single_suite() { let report = parse_bytes(include_bytes!("test_inputs/failed.json")) .expect("Could not parse test input"); assert_output(&report, include_bytes!("expected_outputs/failed.json.out")); } #[test] fn multi_suite_success() { let report = parse_bytes(include_bytes!("test_inputs/multi_suite_success.json")) .expect("Could not parse test input"); assert_output( &report, include_bytes!("expected_outputs/multi_suite_success.json.out"), ); } #[test]
#[test] fn az_func_regression() { let report = parse_bytes(include_bytes!("test_inputs/azfunc.json")) .expect("Could not parse test input"); assert_output(&report, include_bytes!("expected_outputs/azfunc.json.out")); } #[test] fn float_time() { parse_bytes(include_bytes!("test_inputs/float_time.json")) .expect("Could not parse test input"); } }
fn cargo_project_failure() { let report = parse_bytes(include_bytes!("test_inputs/cargo_failure.json")) .expect("Could not parse test input"); assert_output( &report, include_bytes!("expected_outputs/cargo_failure.json.out"), ); }
function_block-full_function
[ { "content": "[![Build Status](https://dev.azure.com/cargo2junit/cargo2junit/_apis/build/status/johnterickson.cargo2junit?branchName=master)](https://dev.azure.com/cargo2junit/cargo2junit/_build/latest?definitionId=1&branchName=master)\n\n\n\n# cargo2junit\n\nConverts cargo's json output (from stdin) to JUnit XML (to stdout).\n\n\n\nTo use, first install:\n\n```\n\ncargo install cargo2junit\n\n```\n\n\n\nThen, run cargo test and convert:\n\n```\n\ncargo test -- -Z unstable-options --format json --report-time | cargo2junit > results.xml\n\n```\n\n\n\nOr, use tee for streaming output to console as the tests run:\n\n```\n\ncargo test -- -Z unstable-options --format json --report-time | tee results.json\n\ncat results.json | cargo2junit > results.xml\n\n```\n\n\n\nOnce you have your XML, publish it (e.g. for Azure Pipelines):\n\n```\n\n - task: PublishTestResults@2\n\n inputs: \n\n testResultsFormat: 'JUnit'\n\n testResultsFiles: 'test_results.xml'\n\n condition: succeededOrFailed()\n\n```\n", "file_path": "README.md", "rank": 20, "score": 10.715027030998948 } ]
Rust
src/stock.rs
teohhanhui/stocker
ac666f50762620b4e4e0bed39aad150f42aa056c
use crate::{ app::{Indicator, TimeFrame}, reactive::StreamExt, }; use async_compat::Compat; use chrono::{DateTime, Duration, TimeZone, Utc}; use futures::executor; use gcollections::ops::{Bounded, Difference, Union}; use im::{hashmap, ordset, HashMap, OrdSet}; use interval::interval_set::{IntervalSet, ToIntervalSet}; use reactive_rs::Stream; use std::{cell::RefCell, ops::Range, rc::Rc}; use yahoo_finance::{history, Bar, Profile, Quote, Timestamped}; #[derive(Clone, Debug, Default)] pub struct Stock { pub bars: OrdSet<Bar>, pub profile: Option<Profile>, pub quote: Option<Quote>, pub symbol: String, } impl Stock { pub fn name(&self) -> Option<&str> { match &self.profile { Some(Profile::Company(company)) => Some(company.name.as_str()), Some(Profile::Fund(fund)) => Some(fund.name.as_str()), None => None, } } } pub fn to_stock_profiles<'a, S>(stock_symbols: S) -> ToStockProfiles<S> where S: Stream<'a, Item = String>, { ToStockProfiles { stock_profile_map: Rc::new(RefCell::new(hashmap! {})), stock_symbols, } } pub struct ToStockProfiles<S> { stock_profile_map: Rc<RefCell<HashMap<String, Profile>>>, stock_symbols: S, } impl<'a, S> Stream<'a> for ToStockProfiles<S> where S: Stream<'a, Item = String>, { type Context = S::Context; type Item = Profile; fn subscribe_ctx<O>(self, mut observer: O) where O: 'a + FnMut(&Self::Context, &Self::Item), { let stock_profile_map = self.stock_profile_map.clone(); self.stock_symbols .distinct_until_changed() .subscribe_ctx(move |ctx, stock_symbol| { let profile = { let stock_profile_map = stock_profile_map.borrow(); stock_profile_map.get(stock_symbol).cloned() }; let profile = profile.unwrap_or_else(|| { let profile = executor::block_on(Compat::new(async { Profile::load(stock_symbol.as_str()).await })) .expect("profile load failed"); let mut stock_profile_map = stock_profile_map.borrow_mut(); stock_profile_map.insert(stock_symbol.clone(), profile.clone()); profile }); observer(ctx, &profile); }); } } pub fn to_stock_bar_sets<'a, S, U, R, V>( stock_symbols: S, time_frames: U, date_ranges: R, indicators: V, ) -> ToStockBarSets<S, U, R, V> where S: Stream<'a, Item = String>, U: Stream<'a, Item = TimeFrame>, R: Stream<'a, Item = Option<Range<DateTime<Utc>>>>, V: Stream<'a, Item = Option<Indicator>>, { ToStockBarSets { date_ranges, indicators, stock_bars_map: Rc::new(RefCell::new(hashmap! {})), stock_symbols, time_frames, } } type DateRangeIntervalSet = IntervalSet<i64>; type BarCoverageHashMap = HashMap<String, (OrdSet<Bar>, DateRangeIntervalSet)>; pub struct ToStockBarSets<S, U, R, V> { date_ranges: R, indicators: V, stock_bars_map: Rc<RefCell<BarCoverageHashMap>>, stock_symbols: S, time_frames: U, } impl<'a, S, U, R, V, C> Stream<'a> for ToStockBarSets<S, U, R, V> where S: Stream<'a, Item = String, Context = C>, U: Stream<'a, Item = TimeFrame>, R: Stream<'a, Item = Option<Range<DateTime<Utc>>>>, V: Stream<'a, Item = Option<Indicator>>, C: 'a + Clone + Sized, { type Context = C; type Item = OrdSet<Bar>; fn subscribe_ctx<O>(self, mut observer: O) where O: 'a + FnMut(&Self::Context, &Self::Item), { let stock_bars_map = self.stock_bars_map.clone(); self.stock_symbols .distinct_until_changed() .combine_latest( self.time_frames.distinct_until_changed(), |(stock_symbol, time_frame)| (stock_symbol.clone(), *time_frame), ) .combine_latest( self.date_ranges.distinct_until_changed(), |((stock_symbol, time_frame), date_range)| { (stock_symbol.clone(), *time_frame, date_range.clone()) }, ) .combine_latest( self.indicators.distinct_until_changed(), |((stock_symbol, time_frame, date_range), indicator)| { ( stock_symbol.clone(), *time_frame, date_range.clone(), *indicator, ) }, ) .subscribe_ctx( move |ctx, (stock_symbol, time_frame, date_range, indicator)| { let (stock_bar_set, covered_date_ranges) = { let stock_bars_map = stock_bars_map.borrow(); stock_bars_map .get(stock_symbol) .cloned() .unwrap_or((ordset![], vec![].to_interval_set())) }; let (stock_bar_set, covered_date_ranges) = if let Some(date_range) = date_range { let uncovered_date_ranges = ( date_range.start.timestamp(), (date_range.end - Duration::seconds(1)).timestamp(), ) .to_interval_set(); let uncovered_date_ranges = match indicator { Some(Indicator::BollingerBands(n, _)) => uncovered_date_ranges.union( &( (date_range.start - Duration::days(**n as i64 - 1)).timestamp(), (date_range.start - Duration::seconds(1)).timestamp(), ) .to_interval_set(), ), Some(Indicator::ExponentialMovingAverage(n)) => uncovered_date_ranges .union( &( (date_range.start - Duration::days(**n as i64 - 1)) .timestamp(), (date_range.start - Duration::seconds(1)).timestamp(), ) .to_interval_set(), ), Some(Indicator::SimpleMovingAverage(n)) => uncovered_date_ranges.union( &( (date_range.start - Duration::days(**n as i64 - 1)).timestamp(), (date_range.start - Duration::seconds(1)).timestamp(), ) .to_interval_set(), ), None => uncovered_date_ranges, }; let uncovered_date_ranges = uncovered_date_ranges.difference(&covered_date_ranges); let mut covered_date_ranges = covered_date_ranges; let mut stock_bar_set = stock_bar_set; for uncovered_date_range in uncovered_date_ranges { let bars = executor::block_on(Compat::new(async { history::retrieve_range( stock_symbol.as_str(), Utc.timestamp(uncovered_date_range.lower(), 0), Some(Utc.timestamp(uncovered_date_range.upper(), 0)), ) .await })) .expect("historical prices retrieval failed"); covered_date_ranges = covered_date_ranges.union( &(uncovered_date_range.lower(), uncovered_date_range.upper()) .to_interval_set(), ); stock_bar_set = stock_bar_set + OrdSet::from(bars); } (stock_bar_set, covered_date_ranges) } else { let bars = executor::block_on(Compat::new(async { history::retrieve_interval(stock_symbol.as_str(), time_frame.interval()) .await })) .expect("historical prices retrieval failed"); let covered_date_ranges = if let (Some(first_bar), Some(last_bar)) = (bars.first(), bars.last()) { covered_date_ranges.union( &vec![( first_bar.timestamp_seconds() as i64, last_bar.timestamp_seconds() as i64, )] .to_interval_set(), ) } else { covered_date_ranges }; let stock_bar_set = stock_bar_set + OrdSet::from(bars); (stock_bar_set, covered_date_ranges) }; observer(ctx, &stock_bar_set); let mut stock_bars_map = stock_bars_map.borrow_mut(); stock_bars_map .insert(stock_symbol.clone(), (stock_bar_set, covered_date_ranges)); }, ); } }
use crate::{ app::{Indicator, TimeFrame}, reactive::StreamExt, }; use async_compat::Compat; use chrono::{DateTime, Duration, TimeZone, Utc}; use futures::executor; use gcollections::ops::{Bounded, Difference, Union}; use im::{hashmap, ordset, HashMap, OrdSet}; use interval::interval_set::{IntervalSet, ToIntervalSet}; use reactive_rs::Stream; use std::{cell::RefCell, ops::Range, rc::Rc}; use yahoo_finance::{history, Bar, Profile, Quote, Timestamped}; #[derive(Clone, Debug, Default)] pub struct Stock { pub bars: OrdSet<Bar>, pub profile: Option<Profile>, pub quote: Option<Quote>, pub symbol: String, } impl Stock { pub fn name(&self) -> Option<&str> { match &self.profile { Some(Profile::Company(company)) => Some(company.name.as_str()), Some(Profile::Fund(fund)) => Some(fund.name.as_str()), None => None, } } } pub fn to_stock_profiles<'a, S>(stock_symbols: S) -> ToStockProfiles<S> where S: Stream<'a, Item = String>, { ToStockProfiles { stock_profile_map: Rc::new(RefCell::new(hashmap! {})), stock_symbols, } } pub struct ToStockProfiles<S> { stock_profile_map: Rc<RefCell<HashMap<String, Profile>>>, stock_symbols: S, } impl<'a, S> Stream<'a> for ToStockProfiles<S> where S: Stream<'a, Item = String>, { type Context = S::Context; type Item = Profile; fn subscribe_ctx<O>(self, mut observer: O) where O: 'a + FnMut(&Self::Context, &Self::Item), { let stock_profile_map = self.stock_profile_map.clone(); self.stock_symbols .distinct_until_changed() .subscribe_ctx(move |ctx, stock_symbol| { let profile = { let stock_profile_map = stock_profile_map.borrow(); stock_profile_map.get(stock_symbol).cloned() }; let profile = profile.unwrap_or_else(|| { let profile = executor::block_on(Compat::new(async { Profile::load(stock_symbol.as_str()).await })) .expect("profile load failed"); let mut stock_profile_map = stock_profile_map.borrow_mut(); stock_profile_map.insert(stock_symbol.clone(), profile.clone()); profile }); observer(ctx, &profile); }); } } pub fn to_stock_bar_sets<'a, S, U, R, V>( stock_symbols: S, time_frames: U, date_ranges: R, indicators: V, ) -> ToStockBarSets<S, U, R, V> where S: Stream<'a, Item = String>, U: Stream<'a, Item = TimeFrame>, R: Stream<'a, Item = Option<Range<DateTime<Utc>>>>, V: Stream<'a, Item = Option<Indicator>>, { ToStockBarSets { date_ranges, indicators, stock_bars_map: Rc::new(RefCell::new(hashmap! {})), stock_symbols, time_frames, } } type DateRangeIntervalSet = IntervalSet<i64>; type BarCoverageHashMap = HashMap<String, (OrdSet<Bar>, DateRangeIntervalSet)>; pub struct ToStockBarSets<S, U, R, V> { date_ranges: R, indicators: V, stock_bars_map: Rc<RefCell<BarCoverageHashMap>>, stock_symbols: S, time_frames: U, } impl<'a, S, U, R, V, C> Stream<'a> for ToStockBarSets<S, U, R, V> where S: Stream<'a, Item = String, Context = C>, U: Stream<'a, Item = TimeFrame>, R: Stream<'a, Item = Option<Range<DateTime<Utc>>>>, V: Stream<'a, Item = Option<Indicator>>, C: 'a + Clone + Sized, { type Context = C; type Item = OrdSet<Bar>; fn subscribe_ctx<O>(self, mut observer: O) where O: 'a + FnMut(&Self::Context, &Self::Item), { let stock_bars_map = self.stock_bars_map.clone(); self.stock_symbols .distinct_until_changed() .combine_latest( self.time_frames.distinct_until_changed(), |(stock_symbol, time_frame)| (stock_symbol.clone(), *time_frame), ) .combine_latest( self.date_ranges.distinct_until_changed(), |((stock_symbol, time_frame), date_range)| { (stock_symbol.clone(), *time_frame, date_range.clone()) }, ) .combine_latest( self.indicators.distinct_until_changed(), |((stock_symbol, time_frame, date_range), indicator)| { ( stock_symbol.clone(), *time_frame, date_range.clone(), *indicator, ) }, ) .subscribe_ctx( move |ctx, (stock_symbol, time_frame, date_range, indicator)| { let (stock_bar_set, covered_date_ranges) = { let stock_bars_map = stock_bars_map.borrow(); stock_bars_map .get(stock_symbol) .cloned() .unwrap_or((ordset![], vec![].to_interval_set())) }; let (stock_bar_set, covered_date_ranges) = if let Some(date_range) = date_range { let uncovered_date_ranges = ( date_range.start.timestamp(), (date_range.end - Duration::seconds(1)).timestamp(), ) .to_interval_set(); let uncovered_date_ranges = match indicator { Some(Indicator::BollingerBands(n, _)) => uncovered_date_ranges.union( &( (date_range.start - Duration::days(**n as i64 - 1)).timestamp(), (date_range.start - Duration::seconds(1)).timestamp(), ) .to_interval_set(), ), Some(Indicator::ExponentialMovingAverage(n)) => uncovered_date_ranges .union( &( (date_range.start - Duration::days(**n as i64 - 1)) .timestamp(), (date_range.start - Duration::seconds(1)).timestamp(), ) .to_interval_set(), ), Some(Indicator::SimpleMovingAverage(n)) => uncovered_date_ranges.union( &( (date_range.start - Duration::days(**n as i64 - 1)).timestamp(), (date_range.start - Duration::seconds(1)).timestamp(), ) .to_interval_set(), ), None => uncovered_date_ranges, }; let uncovered_date_ranges = uncovered_date_ranges.difference(&covered_date_ranges); let mut covered_date_ranges = covered_date_ranges; let mut stock_bar_set = stock_bar_set; for uncovered_date_range in uncovered_date_ranges { let bars = executor::block_on(Compat::new(async { history::retrieve_range( stock_symbol.as_str(), Utc.timestamp(uncovered_date_range.lower(), 0), Some(Utc.timestamp(uncovered_date_range.upper(), 0)), ) .await })) .expect("historical prices retrieval failed"); covered_date_ranges = covered_date_ranges.union( &(uncovered_date_range.lower(), uncovered_date_range.upper()) .to_interval_set(), ); stock_bar_set = stock_bar_set + OrdSet::from(bars); } (stock_bar_set, covered_date_ranges) } else { let bars = executor::block_on(Compat::new(async {
covered_date_ranges.union( &vec![( first_bar.timestamp_seconds() as i64, last_bar.timestamp_seconds() as i64, )] .to_interval_set(), ) } else { covered_date_ranges }; let stock_bar_set = stock_bar_set + OrdSet::from(bars); (stock_bar_set, covered_date_ranges) }; observer(ctx, &stock_bar_set); let mut stock_bars_map = stock_bars_map.borrow_mut(); stock_bars_map .insert(stock_symbol.clone(), (stock_bar_set, covered_date_ranges)); }, ); } }
history::retrieve_interval(stock_symbol.as_str(), time_frame.interval()) .await })) .expect("historical prices retrieval failed"); let covered_date_ranges = if let (Some(first_bar), Some(last_bar)) = (bars.first(), bars.last()) {
random
[ { "content": "pub fn to_date_ranges<'a, S, U, R, C>(\n\n chart_events: S,\n\n stock_symbols: U,\n\n init_stock_symbol: String,\n\n time_frames: R,\n\n init_time_frame: TimeFrame,\n\n) -> impl Stream<'a, Item = Option<DateRange>, Context = C>\n\nwhere\n\n S: Stream<'a, Item = ChartEvent, Context = C>,\n\n U: Stream<'a, Item = String>,\n\n R: Stream<'a, Item = TimeFrame>,\n\n C: 'a + Clone,\n\n{\n\n chart_events\n\n .combine_latest(\n\n stock_symbols.distinct_until_changed(),\n\n |(ev, stock_symbol)| (*ev, stock_symbol.clone()),\n\n )\n\n .combine_latest(\n\n time_frames.distinct_until_changed(),\n", "file_path": "src/app.rs", "rank": 2, "score": 155570.68965357466 }, { "content": "pub fn to_chart_events<'a, S, C>(input_events: S) -> impl Stream<'a, Item = ChartEvent, Context = C>\n\nwhere\n\n S: Stream<'a, Item = InputEvent, Context = C>,\n\n C: 'a + Clone,\n\n{\n\n input_events.filter_map(|ev| match ev {\n\n InputEvent::Key(KeyEvent { code, .. }) => match code {\n\n KeyCode::Left => Some(ChartEvent::PanBackward),\n\n KeyCode::Right => Some(ChartEvent::PanForward),\n\n KeyCode::End => Some(ChartEvent::Reset),\n\n KeyCode::PageUp => Some(ChartEvent::PanBackward),\n\n KeyCode::PageDown => Some(ChartEvent::PanForward),\n\n _ => None,\n\n },\n\n _ => None,\n\n })\n\n}\n\n\n", "file_path": "src/event.rs", "rank": 3, "score": 150318.4744912661 }, { "content": "pub fn to_grouped_user_input_events<'a, S, U, R, C>(\n\n user_input_events: S,\n\n ui_target_areas: U,\n\n active_overlays: R,\n\n hotkey_overlay_map: BiMap<KeyCode, UiTarget>,\n\n associated_overlay_map: HashMap<UiTarget, UiTarget>,\n\n) -> impl Stream<'a, Item = Grouped<'a, Option<UiTarget>, InputEvent, C>, Context = C>\n\nwhere\n\n S: Stream<'a, Item = InputEvent, Context = C>,\n\n U: Stream<'a, Item = (UiTarget, Option<Rect>)>,\n\n R: Stream<'a, Item = Option<UiTarget>>,\n\n C: 'a,\n\n{\n\n user_input_events\n\n .with_latest_from(\n\n ui_target_areas\n\n .filter({\n\n let associated_overlay_map = associated_overlay_map.clone();\n\n move |(ui_target, _)| associated_overlay_map.contains_key(ui_target)\n\n })\n", "file_path": "src/event.rs", "rank": 4, "score": 147245.4069500853 }, { "content": "pub fn to_select_menu_events<'a, S, V, O, U, C>(\n\n input_events: S,\n\n init_select_menu_state: SelectMenuState<V>,\n\n overlay_states: O,\n\n activation_hotkey: KeyCode,\n\n ui_target_areas: U,\n\n self_ui_target: UiTarget,\n\n select_menu_event_map: HashMap<Option<UiTarget>, SelectMenuEvent>,\n\n) -> impl Stream<'a, Item = (SelectMenuEvent, SelectMenuState<V>), Context = C>\n\nwhere\n\n S: Stream<'a, Item = InputEvent, Context = C>,\n\n V: 'a + Clone + PartialEq + ToString,\n\n O: Stream<'a, Item = OverlayState>,\n\n U: Stream<'a, Item = (UiTarget, Option<Rect>)>,\n\n C: 'a + Clone,\n\n{\n\n let select_menu_event_map = select_menu_event_map.without(&Some(self_ui_target));\n\n\n\n let ui_target_area_bufs = ui_target_areas\n\n .filter({\n", "file_path": "src/event.rs", "rank": 5, "score": 144317.5246419714 }, { "content": "pub trait ContextFn<C: ?Sized, T: ?Sized> {\n\n type Output;\n\n\n\n fn call_mut(&mut self, ctx: &C, item: &T) -> Self::Output;\n\n}\n\n\n\nimpl<C: ?Sized, T: ?Sized, V, F> ContextFn<C, T> for F\n\nwhere\n\n F: FnMut(&C, &T) -> V,\n\n{\n\n type Output = V;\n\n\n\n #[inline(always)]\n\n fn call_mut(&mut self, ctx: &C, item: &T) -> Self::Output {\n\n self(ctx, item)\n\n }\n\n}\n\n\n\npub struct NoContext<F>(F);\n\n\n", "file_path": "src/reactive/stream_ext.rs", "rank": 7, "score": 122655.43244257715 }, { "content": "pub fn to_text_field_events<'a, S, O, U, F, C>(\n\n input_events: S,\n\n init_text_field_state: TextFieldState,\n\n overlay_states: O,\n\n activation_hotkey: KeyCode,\n\n ui_target_areas: U,\n\n self_ui_target: UiTarget,\n\n text_field_event_map: HashMap<Option<UiTarget>, TextFieldEvent>,\n\n map_value_func: F,\n\n) -> impl Stream<'a, Item = (TextFieldEvent, TextFieldState), Context = C>\n\nwhere\n\n S: Stream<'a, Item = InputEvent, Context = C>,\n\n O: Stream<'a, Item = OverlayState>,\n\n U: Stream<'a, Item = (UiTarget, Option<Rect>)>,\n\n F: 'a + Clone + FnOnce(String) -> String,\n\n C: 'a + Clone,\n\n{\n\n let text_field_event_map = text_field_event_map.without(&Some(self_ui_target));\n\n\n\n let ui_target_area_bufs = ui_target_areas\n", "file_path": "src/event.rs", "rank": 8, "score": 113707.35142574279 }, { "content": "pub fn to_active_overlays<'a, S, C>(\n\n overlay_states: S,\n\n) -> impl Stream<'a, Item = Option<UiTarget>, Context = C>\n\nwhere\n\n S: Stream<'a, Item = (UiTarget, OverlayState), Context = C>,\n\n{\n\n overlay_states\n\n .fold(\n\n None,\n\n |acc_active_overlay, (ui_target, overlay_state)| match overlay_state {\n\n OverlayState::Active => Some(*ui_target),\n\n OverlayState::Inactive => {\n\n if acc_active_overlay.as_ref() == Some(ui_target) {\n\n None\n\n } else {\n\n *acc_active_overlay\n\n }\n\n }\n\n },\n\n )\n\n .distinct_until_changed()\n\n .inspect(|active_overlay| {\n\n debug!(\"active overlay: {:?}\", active_overlay);\n\n })\n\n}\n", "file_path": "src/event.rs", "rank": 10, "score": 100535.03331858348 }, { "content": "pub fn draw<B: Backend>(f: &mut Frame<B>, app: &App) -> anyhow::Result<()> {\n\n let chunks = Layout::default()\n\n .direction(Direction::Vertical)\n\n .constraints(vec![\n\n Constraint::Length(2),\n\n Constraint::Min(5),\n\n Constraint::Length(2),\n\n ])\n\n .split(f.size());\n\n let header_area = chunks[0];\n\n let body_area = chunks[1];\n\n let footer_area = chunks[2];\n\n\n\n draw_header(f, app, header_area)?;\n\n draw_body(f, app, body_area)?;\n\n draw_footer(f, app, footer_area)?;\n\n draw_overlay(f, app)?;\n\n if app.ui_state.debug_draw {\n\n draw_debug(f, app)?;\n\n }\n\n\n\n Ok(())\n\n}\n\n\n", "file_path": "src/ui.rs", "rank": 11, "score": 74985.37794701528 }, { "content": "type DateRange = Range<DateTime<Utc>>;\n\n\n\n#[derive(Clone, Derivative)]\n\n#[derivative(Debug)]\n\npub struct UiState<'r> {\n\n pub date_range: Option<DateRange>,\n\n pub debug_draw: bool,\n\n pub frame_rate_counter: Rc<RefCell<FrameRateCounter>>,\n\n pub indicator: Option<Indicator>,\n\n pub indicator_menu_state: Rc<RefCell<SelectMenuState<Indicator>>>,\n\n pub stock_symbol_field_state: Rc<RefCell<TextFieldState>>,\n\n pub time_frame: TimeFrame,\n\n pub time_frame_menu_state: Rc<RefCell<SelectMenuState<TimeFrame>>>,\n\n #[derivative(Debug = \"ignore\")]\n\n pub ui_target_areas: Broadcast<'r, (), (UiTarget, Option<Rect>)>,\n\n}\n\n\n\nimpl<'r> Default for UiState<'r> {\n\n fn default() -> Self {\n\n Self {\n", "file_path": "src/app.rs", "rank": 12, "score": 73426.34222303351 }, { "content": "/// Queues the overlay states to send on next tick.\n\n///\n\n/// This is necessary to prevent a cycle.\n\npub fn queue_overlay_states_for_next_tick<'a, S>(\n\n overlay_events: S,\n\n overlay_state_queue: Rc<RefCell<VecDeque<(UiTarget, OverlayState)>>>,\n\n) where\n\n S: Stream<'a, Item = (UiTarget, OverlayEvent)>,\n\n{\n\n overlay_events\n\n .fold(\n\n (hashmap! {}, hashmap! {}),\n\n |(_, acc_overlay_state_map), (ui_target, ev)| {\n\n let acc_overlay_state = acc_overlay_state_map\n\n .get(ui_target)\n\n .copied()\n\n .unwrap_or(OverlayState::Inactive);\n\n\n\n let overlay_state = match ev {\n\n OverlayEvent::TextField(ev) => match ev {\n\n TextFieldEvent::Activate => OverlayState::Active,\n\n TextFieldEvent::Accept(_) | TextFieldEvent::Deactivate => {\n\n OverlayState::Inactive\n", "file_path": "src/event.rs", "rank": 13, "score": 62573.133816042755 }, { "content": "#[allow(clippy::unnecessary_wraps)]\n\nfn draw_debug<B: Backend>(\n\n f: &mut Frame<B>,\n\n App {\n\n ui_state: UiState {\n\n frame_rate_counter, ..\n\n },\n\n ..\n\n }: &App,\n\n) -> anyhow::Result<()> {\n\n let frame_time = {\n\n let mut frame_rate_counter = frame_rate_counter.borrow_mut();\n\n if let Some(frame_time) = frame_rate_counter.incr() {\n\n Some(frame_time)\n\n } else {\n\n frame_rate_counter.frame_time()\n\n }\n\n };\n\n let frame_time_text = if let Some(frame_time) = frame_time {\n\n format!(\"{} ms\", frame_time.num_milliseconds())\n\n } else {\n", "file_path": "src/ui.rs", "rank": 14, "score": 56509.167617467356 }, { "content": "#[derive(Debug, FromArgs)]\n\nstruct Args {\n\n /// debug draw\n\n #[argh(switch)]\n\n debug_draw: bool,\n\n /// indicator for technical analysis\n\n #[argh(option, short = 'i')]\n\n indicator: Option<Indicator>,\n\n /// path to log file\n\n #[argh(option)]\n\n log_file: Option<String>,\n\n /// stock symbol\n\n #[argh(option, short = 's', default = \"DEFAULT_SYMBOL.to_owned()\")]\n\n symbol: String,\n\n /// time frame for historical prices\n\n #[argh(option, short = 't', default = \"TimeFrame::default()\")]\n\n time_frame: TimeFrame,\n\n}\n\n\n", "file_path": "src/main.rs", "rank": 15, "score": 47878.55925955325 }, { "content": "#[allow(clippy::unnecessary_wraps)]\n\nfn draw_overlay<B: Backend>(f: &mut Frame<B>, App { ui_state, .. }: &App) -> anyhow::Result<()> {\n\n let active_base_style = Style::default().fg(Color::White).bg(Color::DarkGray);\n\n let highlight_base_style = Style::default().fg(Color::Black).bg(Color::White);\n\n\n\n let stock_symbol_field_state = ui_state.stock_symbol_field_state.borrow();\n\n\n\n if stock_symbol_field_state.active {\n\n let chunks = Layout::default()\n\n .direction(Direction::Horizontal)\n\n .constraints(vec![Constraint::Length(30), Constraint::Min(0)])\n\n .split(f.size());\n\n let stock_symbol_field_area = chunks[0];\n\n let chunks = Layout::default()\n\n .direction(Direction::Vertical)\n\n .constraints(vec![\n\n Constraint::Length(1),\n\n Constraint::Length(3),\n\n Constraint::Min(0),\n\n ])\n\n .split(stock_symbol_field_area);\n", "file_path": "src/ui.rs", "rank": 16, "score": 47599.614142273465 }, { "content": "// Adapted from https://github.com/cjbassi/ytop/blob/89a210f0e5e2de6aa0e8d7a153a21f959d77607e/src/main.rs#L51-L66\n\nfn cleanup_terminal() {\n\n let mut stdout = io::stdout();\n\n\n\n // Needed for when run in a TTY since TTYs don't actually have an alternate screen.\n\n //\n\n // Must be executed before attempting to leave the alternate screen so that it only modifies the\n\n // primary screen if we are running in a TTY.\n\n //\n\n // If not running in a TTY, then we just end up modifying the alternate screen which should have\n\n // no effect.\n\n execute!(\n\n stdout,\n\n cursor::MoveTo(0, 0),\n\n terminal::Clear(terminal::ClearType::All)\n\n )\n\n .unwrap();\n\n\n\n execute!(\n\n stdout,\n\n terminal::LeaveAlternateScreen,\n\n cursor::Show,\n\n cursor::EnableBlinking,\n\n crossterm::event::DisableMouseCapture\n\n )\n\n .unwrap();\n\n\n\n terminal::disable_raw_mode().unwrap();\n\n}\n\n\n", "file_path": "src/main.rs", "rank": 17, "score": 38388.42731095624 }, { "content": "fn setup_terminal() {\n\n let mut stdout = io::stdout();\n\n\n\n execute!(\n\n stdout,\n\n terminal::EnterAlternateScreen,\n\n cursor::Hide,\n\n cursor::DisableBlinking,\n\n crossterm::event::EnableMouseCapture\n\n )\n\n .unwrap();\n\n\n\n // Needed for when run in a TTY since TTYs don't actually have an alternate screen.\n\n //\n\n // Must be executed after attempting to enter the alternate screen so that it only clears the\n\n // primary screen if we are running in a TTY.\n\n //\n\n // If not running in a TTY, then we just end up clearing the alternate screen which should have\n\n // no effect.\n\n execute!(stdout, terminal::Clear(terminal::ClearType::All)).unwrap();\n\n\n\n terminal::enable_raw_mode().unwrap();\n\n}\n\n\n", "file_path": "src/main.rs", "rank": 18, "score": 38388.42731095624 }, { "content": "// Adapted from https://github.com/cjbassi/ytop/blob/89a210f0e5e2de6aa0e8d7a153a21f959d77607e/src/main.rs#L113-L120\n\n//\n\n// We need to catch panics since we need to close the UI and cleanup the terminal before logging any\n\n// error messages to the screen.\n\nfn setup_panic_hook() {\n\n panic::set_hook(Box::new(|panic_info| {\n\n cleanup_terminal();\n\n better_panic::Settings::auto().create_panic_handler()(panic_info);\n\n }));\n\n}\n\n\n\n#[smol_potat::main]\n\nasync fn main() -> anyhow::Result<()> {\n\n better_panic::install();\n\n\n\n let args: Args = argh::from_env();\n\n\n\n if let Some(log_file) = args.log_file {\n\n WriteLogger::init(\n\n LevelFilter::Debug,\n\n LoggerConfig::default(),\n\n File::create(log_file)?,\n\n )?;\n\n }\n", "file_path": "src/main.rs", "rank": 19, "score": 36939.78319470608 }, { "content": "#[allow(clippy::unnecessary_wraps)]\n\nfn draw_footer<B: Backend>(\n\n f: &mut Frame<B>,\n\n App { ui_state, .. }: &App,\n\n area: Rect,\n\n) -> anyhow::Result<()> {\n\n let (indicator_box_area, time_frame_box_area) = {\n\n let chunks = Layout::default()\n\n .direction(Direction::Horizontal)\n\n .constraints(vec![\n\n Constraint::Min(0),\n\n Constraint::Length(30),\n\n Constraint::Length(20),\n\n ])\n\n .split(area);\n\n (chunks[1], chunks[2])\n\n };\n\n\n\n let menu_active_base_style = Style::default().fg(Color::White).bg(Color::DarkGray);\n\n\n\n let indicator_menu_state = ui_state.indicator_menu_state.borrow();\n", "file_path": "src/ui.rs", "rank": 20, "score": 33710.81331072563 }, { "content": "#[allow(clippy::unnecessary_wraps)]\n\nfn draw_header<B: Backend>(\n\n f: &mut Frame<B>,\n\n App {\n\n stock, ui_state, ..\n\n }: &App,\n\n area: Rect,\n\n) -> anyhow::Result<()> {\n\n let stock_name = stock.name().unwrap_or(\"\");\n\n\n\n let chunks = Layout::default()\n\n .direction(Direction::Horizontal)\n\n .horizontal_margin(1)\n\n .constraints(vec![\n\n Constraint::Length(10),\n\n Constraint::Length(cmp::max(stock_name.chars().count() as u16, 20)),\n\n Constraint::Min(0),\n\n ])\n\n .split(area);\n\n let stock_symbol_area = chunks[0];\n\n let stock_name_area = chunks[1];\n", "file_path": "src/ui.rs", "rank": 21, "score": 33710.81331072563 }, { "content": "#[allow(clippy::unnecessary_wraps)]\n\nfn draw_body<B: Backend>(\n\n f: &mut Frame<B>,\n\n App { stock, ui_state }: &App,\n\n area: Rect,\n\n) -> anyhow::Result<()> {\n\n const X_AXIS_LABEL_PADDING: u8 = 4;\n\n const X_AXIS_LABEL_WIDTH: u8 = 10;\n\n const Y_AXIS_LABEL_HEIGHT: u8 = 1;\n\n const Y_AXIS_LABEL_PADDING: u8 = 2;\n\n\n\n let mut historical_prices_data: HashMap<String, Vec<_>> = hashmap! {};\n\n let stock_data = stock\n\n .bars\n\n .iter()\n\n .filter(|&bar| {\n\n ui_state\n\n .date_range\n\n .as_ref()\n\n .map_or(true, |date_range| date_range.contains(&bar.datetime()))\n\n })\n", "file_path": "src/ui.rs", "rank": 22, "score": 33710.81331072563 }, { "content": "pub trait StreamExt<'a>: Stream<'a> {\n\n fn buffer(self, count: usize) -> Buffer<Self, Self::Item>\n\n where\n\n Self::Item: 'a + Clone + Sized,\n\n {\n\n Buffer {\n\n buf: Rc::new(RefCell::new(Vec::with_capacity(count))),\n\n count,\n\n stream: self,\n\n }\n\n }\n\n\n\n fn combine_latest<U, F, T>(\n\n self,\n\n other: U,\n\n func: F,\n\n ) -> CombineLatest<Self, U, NoContext<F>, Self::Item, U::Item, Self::Context>\n\n where\n\n U: Stream<'a>,\n\n F: 'a + FnMut(&(Self::Item, U::Item)) -> T,\n", "file_path": "src/reactive/stream_ext.rs", "rank": 23, "score": 32878.104825011425 }, { "content": "# Stocker\n\n\n\nStocks dashboard\n\n\n\n## License\n\n\n\nLicensed under either of\n\n\n\n * Apache License, Version 2.0, ([LICENSE-APACHE](LICENSE-APACHE) or http://www.apache.org/licenses/LICENSE-2.0)\n\n * MIT license ([LICENSE-MIT](LICENSE-MIT) or http://opensource.org/licenses/MIT)\n\n\n\nat your option.\n\n\n\n### Contribution\n\n\n\nUnless you explicitly state otherwise, any contribution intentionally submitted\n\nfor inclusion in the work by you, as defined in the Apache-2.0 license, shall be dual licensed as above, without any\n\nadditional terms or conditions.\n", "file_path": "README.md", "rank": 33, "score": 17140.26462096707 }, { "content": "#[derivative(Clone(bound = \"K: Clone\"))]\n\npub struct Grouped<'a, K: Sized, V: 'a + Sized, C: 'a> {\n\n pub key: K,\n\n sink: Broadcast<'a, C, V>,\n\n}\n\n\n\nimpl<'a, K, V, C> Stream<'a> for Grouped<'a, K, V, C>\n\nwhere\n\n V: 'a,\n\n C: 'a,\n\n{\n\n type Context = C;\n\n type Item = V;\n\n\n\n fn subscribe_ctx<O>(self, observer: O)\n\n where\n\n O: 'a + FnMut(&Self::Context, &Self::Item),\n\n {\n\n self.sink.subscribe_ctx(observer);\n\n }\n", "file_path": "src/reactive/stream_ext.rs", "rank": 34, "score": 31.773355558230183 }, { "content": " buf_ctx: Rc<RefCell<Option<C>>>,\n\n func: F,\n\n stream_a: S,\n\n stream_b: U,\n\n}\n\n\n\nimpl<'a, S, U, F, A, B, C> Stream<'a> for CombineLatest<S, U, F, A, B, C>\n\nwhere\n\n S: Stream<'a, Item = A, Context = C>,\n\n U: Stream<'a, Item = B>,\n\n F: 'a + ContextFn<C, (A, B)>,\n\n A: 'a + Clone + Sized,\n\n B: 'a + Clone + Sized,\n\n C: 'a + Clone + Sized,\n\n{\n\n type Context = C;\n\n type Item = F::Output;\n\n\n\n fn subscribe_ctx<O>(self, mut observer: O)\n\n where\n", "file_path": "src/reactive/stream_ext.rs", "rank": 35, "score": 28.19557831294781 }, { "content": "impl<F, C: ?Sized, T: ?Sized, V> ContextFn<C, T> for NoContext<F>\n\nwhere\n\n F: FnMut(&T) -> V,\n\n{\n\n type Output = V;\n\n\n\n #[inline(always)]\n\n fn call_mut(&mut self, _ctx: &C, item: &T) -> Self::Output {\n\n (self.0)(item)\n\n }\n\n}\n", "file_path": "src/reactive/stream_ext.rs", "rank": 36, "score": 27.733072497882084 }, { "content": "\n\nimpl<'a, S, X, T, C> Stream<'a> for Switch<S>\n\nwhere\n\n S: Stream<'a, Item = X>,\n\n X: Clone + Stream<'a, Item = T, Context = C>,\n\n T: 'a,\n\n C: 'a,\n\n{\n\n type Context = C;\n\n type Item = T;\n\n\n\n fn subscribe_ctx<O>(self, mut observer: O)\n\n where\n\n O: 'a + FnMut(&Self::Context, &Self::Item),\n\n {\n\n let sink = Broadcast::new();\n\n sink.clone().subscribe_ctx(move |ctx, x| {\n\n observer(ctx, x);\n\n });\n\n self.stream.subscribe(move |inner_stream| {\n", "file_path": "src/reactive/stream_ext.rs", "rank": 37, "score": 26.888111625055622 }, { "content": " U: Stream<'a, Item = B>,\n\n F: 'a + ContextFn<S::Context, (A, B)>,\n\n A: 'a + Clone + Sized,\n\n B: 'a + Clone + Sized,\n\n{\n\n type Context = S::Context;\n\n type Item = F::Output;\n\n\n\n fn subscribe_ctx<O>(self, mut observer: O)\n\n where\n\n O: 'a + FnMut(&Self::Context, &Self::Item),\n\n {\n\n self.stream_a.subscribe_ctx({\n\n let buf_b = self.buf_b.clone();\n\n let mut func = self.func;\n\n move |ctx, a| {\n\n let buf_b = buf_b.borrow();\n\n if let Some(b) = buf_b.as_ref() {\n\n let b = b.clone();\n\n drop(buf_b);\n", "file_path": "src/reactive/stream_ext.rs", "rank": 38, "score": 26.862027056318368 }, { "content": "}\n\n\n\npub struct Merge<S, U> {\n\n stream_a: S,\n\n stream_b: U,\n\n}\n\n\n\nimpl<'a, S, U, T, C> Stream<'a> for Merge<S, U>\n\nwhere\n\n S: Stream<'a, Item = T, Context = C>,\n\n U: Stream<'a, Item = T, Context = C>,\n\n T: 'a,\n\n C: 'a,\n\n{\n\n type Context = C;\n\n type Item = T;\n\n\n\n fn subscribe_ctx<O>(self, mut observer: O)\n\n where\n\n O: 'a + FnMut(&Self::Context, &Self::Item),\n", "file_path": "src/reactive/stream_ext.rs", "rank": 39, "score": 26.655574517517586 }, { "content": " O: 'a + FnMut(&Self::Context, &Self::Item),\n\n {\n\n self.stream.subscribe_ctx({\n\n let buf = self.buf;\n\n move |ctx, x| {\n\n if !matches!(&*buf.borrow(), Some(y) if x == y) {\n\n buf.borrow_mut().replace(x.clone());\n\n observer(ctx, x);\n\n }\n\n }\n\n });\n\n }\n\n}\n\n\n\npub struct GroupBy<'a, S, F, G, K: Sized, V: Sized, C> {\n\n key_func: F,\n\n #[allow(clippy::type_complexity)]\n\n key_grouped_map: Rc<RefCell<HashMap<K, Grouped<'a, K, V, C>>>>,\n\n stream: S,\n\n value_func: G,\n", "file_path": "src/reactive/stream_ext.rs", "rank": 40, "score": 26.3914558838708 }, { "content": "}\n\n\n\nimpl<'a, S, F, G, K, V, T, C> Stream<'a> for GroupBy<'a, S, F, G, K, V, C>\n\nwhere\n\n S: Stream<'a, Item = T, Context = C>,\n\n F: 'a + ContextFn<C, T, Output = K>,\n\n G: 'a + ContextFn<C, T, Output = V>,\n\n K: 'a + Clone + Eq + Hash,\n\n V: 'a,\n\n C: 'a,\n\n{\n\n type Context = C;\n\n type Item = Grouped<'a, K, V, C>;\n\n\n\n fn subscribe_ctx<O>(self, mut observer: O)\n\n where\n\n O: 'a + FnMut(&Self::Context, &Self::Item),\n\n {\n\n self.stream.subscribe_ctx({\n\n let mut key_func = self.key_func;\n", "file_path": "src/reactive/stream_ext.rs", "rank": 41, "score": 25.957609133827546 }, { "content": "impl<'a, T> StreamExt<'a> for T where T: Stream<'a> {}\n\n\n\npub struct Buffer<S, T: Sized> {\n\n buf: Rc<RefCell<Vec<T>>>,\n\n count: usize,\n\n stream: S,\n\n}\n\n\n\nimpl<'a, S, T> Stream<'a> for Buffer<S, T>\n\nwhere\n\n S: Stream<'a, Item = T>,\n\n T: 'a + Clone + Sized,\n\n{\n\n type Context = S::Context;\n\n type Item = [T];\n\n\n\n fn subscribe_ctx<O>(self, mut observer: O)\n\n where\n\n O: 'a + FnMut(&Self::Context, &Self::Item),\n\n {\n", "file_path": "src/reactive/stream_ext.rs", "rank": 42, "score": 22.422139401609993 }, { "content": " } else {\n\n data_item\n\n };\n\n let data_item = data_item.build().unwrap();\n\n (bar.timestamp_seconds() as f64, data_item)\n\n });\n\n\n\n match indicator {\n\n Indicator::BollingerBands(n, k) => {\n\n let indicator_prices_data = indicator_prices_data.filter(|(timestamp, _)| {\n\n ui_state.date_range.as_ref().map_or(true, |date_range| {\n\n let date_range =\n\n (date_range.start - Duration::days(*n as i64 - 1))..date_range.end;\n\n date_range.contains(&Utc.timestamp(*timestamp as i64, 0))\n\n })\n\n });\n\n let mut bb = indicators::BollingerBands::new(*n as usize, *k as f64).unwrap();\n\n let (bb_upper_data, bb_middle_data, bb_lower_data) = indicator_prices_data.fold(\n\n (vec![], vec![], vec![]),\n\n |mut acc_data, (timestamp, data_item)| {\n", "file_path": "src/ui.rs", "rank": 43, "score": 22.16903243035342 }, { "content": " fn with_latest_from<U, F, T>(\n\n self,\n\n other: U,\n\n func: F,\n\n ) -> WithLatestFrom<Self, U, NoContext<F>, U::Item>\n\n where\n\n U: Stream<'a>,\n\n F: 'a + FnMut(&(Self::Item, U::Item)) -> T,\n\n Self::Item: 'a + Clone + Sized,\n\n U::Item: 'a + Clone + Sized,\n\n {\n\n WithLatestFrom {\n\n buf_b: Rc::new(RefCell::new(None)),\n\n func: NoContext(func),\n\n stream_a: self,\n\n stream_b: other,\n\n }\n\n }\n\n}\n\n\n", "file_path": "src/reactive/stream_ext.rs", "rank": 44, "score": 22.147080639894043 }, { "content": " .map(|bar| {\n\n (\n\n bar.timestamp_seconds() as f64,\n\n round::half_to_even(bar.close, 2),\n\n )\n\n })\n\n .collect();\n\n historical_prices_data.insert(stock.symbol.clone(), stock_data);\n\n\n\n let mut historical_prices_datasets = vec![];\n\n\n\n if let Some(indicator) = ui_state.indicator {\n\n let indicator_prices_data = stock.bars.iter().map(|bar| {\n\n let data_item = DataItem::builder()\n\n .open(bar.open)\n\n .high(bar.high)\n\n .low(bar.low)\n\n .close(bar.close);\n\n let data_item = if let Some(volume) = bar.volume {\n\n data_item.volume(volume as f64)\n", "file_path": "src/ui.rs", "rank": 45, "score": 22.067055298331375 }, { "content": " O: 'a + FnMut(&Self::Context, &Self::Item),\n\n {\n\n let sink: Broadcast<C, (A, B)> = Broadcast::new();\n\n sink.clone().subscribe_ctx({\n\n let mut func = self.func;\n\n move |ctx, x| {\n\n observer(ctx, &func.call_mut(ctx, x));\n\n }\n\n });\n\n self.stream_a.subscribe_ctx({\n\n let buf_a = self.buf_a.clone();\n\n let buf_b = self.buf_b.clone();\n\n let buf_ctx = self.buf_ctx.clone();\n\n let sink = sink.clone();\n\n move |ctx, a| {\n\n buf_a.borrow_mut().replace(a.clone());\n\n buf_ctx.borrow_mut().replace(ctx.clone());\n\n let buf_b = buf_b.borrow();\n\n if let Some(b) = buf_b.as_ref() {\n\n let b = b.clone();\n", "file_path": "src/reactive/stream_ext.rs", "rank": 46, "score": 21.55477428648428 }, { "content": " let stock_profiles = stock::to_stock_profiles(stock_symbols.clone())\n\n .map(|stock_profile| Some(stock_profile.clone()))\n\n .broadcast();\n\n\n\n let stock_bar_sets = stock::to_stock_bar_sets(\n\n stock_symbols.clone(),\n\n time_frames.clone(),\n\n date_ranges.clone(),\n\n indicators.clone(),\n\n )\n\n .broadcast();\n\n\n\n let stocks = stock_symbols\n\n .clone()\n\n .combine_latest(stock_profiles.clone(), |(stock_symbol, stock_profile)| {\n\n (stock_symbol.clone(), stock_profile.clone())\n\n })\n\n .combine_latest(\n\n stock_bar_sets.clone(),\n\n |((stock_symbol, stock_profile), stock_bar_set)| Stock {\n", "file_path": "src/main.rs", "rank": 47, "score": 20.473288803764692 }, { "content": " }\n\n });\n\n }\n\n}\n\n\n\npub struct DistinctUntilChanged<S, T: Sized> {\n\n buf: Rc<RefCell<Option<T>>>,\n\n stream: S,\n\n}\n\n\n\nimpl<'a, S, T> Stream<'a> for DistinctUntilChanged<S, T>\n\nwhere\n\n S: Stream<'a, Item = T>,\n\n T: 'a + Clone + PartialEq + Sized,\n\n{\n\n type Context = S::Context;\n\n type Item = T;\n\n\n\n fn subscribe_ctx<O>(self, mut observer: O)\n\n where\n", "file_path": "src/reactive/stream_ext.rs", "rank": 48, "score": 20.177270152655105 }, { "content": " let indicator_prices_data = indicator_prices_data.filter(|(timestamp, _)| {\n\n ui_state.date_range.as_ref().map_or(true, |date_range| {\n\n let date_range =\n\n (date_range.start - Duration::days(*n as i64 - 1))..date_range.end;\n\n date_range.contains(&Utc.timestamp(*timestamp as i64, 0))\n\n })\n\n });\n\n let mut ema = indicators::ExponentialMovingAverage::new(*n as usize).unwrap();\n\n let ema_data = indicator_prices_data\n\n .map(|(timestamp, data_item)| (timestamp, ema.next(&data_item)))\n\n .collect();\n\n historical_prices_data.insert(\"EMA\".to_owned(), ema_data);\n\n let ema_data = historical_prices_data.get(\"EMA\").unwrap();\n\n\n\n historical_prices_datasets.push(\n\n Dataset::default()\n\n .marker(Marker::Braille)\n\n .style(Style::default().fg(Color::Cyan))\n\n .graph_type(GraphType::Line)\n\n .data(&ema_data),\n", "file_path": "src/ui.rs", "rank": 49, "score": 20.08287545469934 }, { "content": " stream: self,\n\n }\n\n }\n\n\n\n fn group_by<F, G, K, V>(\n\n self,\n\n key_func: F,\n\n value_func: G,\n\n ) -> GroupBy<'a, Self, NoContext<F>, NoContext<G>, K, V, Self::Context>\n\n where\n\n F: 'a + FnMut(&Self::Item) -> K,\n\n G: 'a + FnMut(&Self::Item) -> V,\n\n Self::Item: 'a + Clone + Sized,\n\n Self::Context: 'a + Sized,\n\n {\n\n GroupBy {\n\n key_func: NoContext(key_func),\n\n key_grouped_map: Rc::new(RefCell::new(hashmap! {})),\n\n stream: self,\n\n value_func: NoContext(value_func),\n", "file_path": "src/reactive/stream_ext.rs", "rank": 50, "score": 20.050980239348412 }, { "content": " );\n\n }\n\n Indicator::SimpleMovingAverage(n) => {\n\n let indicator_prices_data = indicator_prices_data.filter(|(timestamp, _)| {\n\n ui_state.date_range.as_ref().map_or(true, |date_range| {\n\n let date_range =\n\n (date_range.start - Duration::days(*n as i64 - 1))..date_range.end;\n\n date_range.contains(&Utc.timestamp(*timestamp as i64, 0))\n\n })\n\n });\n\n let mut sma = indicators::SimpleMovingAverage::new(*n as usize).unwrap();\n\n let sma_data = indicator_prices_data\n\n .map(|(timestamp, data_item)| (timestamp, sma.next(&data_item)))\n\n .collect();\n\n historical_prices_data.insert(\"SMA\".to_owned(), sma_data);\n\n let sma_data = historical_prices_data.get(\"SMA\").unwrap();\n\n\n\n historical_prices_datasets.push(\n\n Dataset::default()\n\n .marker(Marker::Braille)\n", "file_path": "src/ui.rs", "rank": 51, "score": 20.03806548086951 }, { "content": " self.stream.subscribe_ctx({\n\n let buf = self.buf;\n\n let count = self.count;\n\n move |ctx, x| {\n\n let full = {\n\n buf.borrow_mut().push(x.clone());\n\n buf.borrow().len() == count\n\n };\n\n if full {\n\n observer(ctx, &buf.borrow()[..]);\n\n buf.borrow_mut().clear();\n\n }\n\n }\n\n });\n\n }\n\n}\n\n\n\npub struct CombineLatest<S, U, F, A: Sized, B: Sized, C: Sized> {\n\n buf_a: Rc<RefCell<Option<A>>>,\n\n buf_b: Rc<RefCell<Option<B>>>,\n", "file_path": "src/reactive/stream_ext.rs", "rank": 52, "score": 19.69925958787081 }, { "content": " None\n\n }\n\n\n\n pub fn frame_time(&self) -> Option<Duration> {\n\n match self.frame_time {\n\n 0 => None,\n\n frame_time => Some(Duration::milliseconds(frame_time as i64)),\n\n }\n\n }\n\n}\n\n\n\n#[derive(Clone, Copy, Debug, EnumIter, Eq, PartialEq)]\n\npub enum Indicator {\n\n BollingerBands(Period<U20>, StdDevMultiplier<U2>),\n\n ExponentialMovingAverage(Period<U50>),\n\n // MovingAverageConvergenceDivergence,\n\n // RelativeStrengthIndex,\n\n SimpleMovingAverage(Period<U50>),\n\n}\n\n\n", "file_path": "src/app.rs", "rank": 53, "score": 19.4778808902175 }, { "content": " inner_stream.clone().subscribe_ctx({\n\n let sink = sink.clone();\n\n move |ctx, x| {\n\n sink.send_ctx(ctx, x);\n\n }\n\n });\n\n });\n\n }\n\n}\n\n\n\npub struct WithLatestFrom<S, U, F, B: Sized> {\n\n buf_b: Rc<RefCell<Option<B>>>,\n\n func: F,\n\n stream_a: S,\n\n stream_b: U,\n\n}\n\n\n\nimpl<'a, S, U, F, A, B> Stream<'a> for WithLatestFrom<S, U, F, B>\n\nwhere\n\n S: Stream<'a, Item = A>,\n", "file_path": "src/reactive/stream_ext.rs", "rank": 54, "score": 19.093820674232045 }, { "content": " Self::Item: 'a + Clone + Sized,\n\n Self::Context: 'a + Clone + Sized,\n\n U::Item: 'a + Clone + Sized,\n\n {\n\n CombineLatest {\n\n buf_a: Rc::new(RefCell::new(None)),\n\n buf_b: Rc::new(RefCell::new(None)),\n\n buf_ctx: Rc::new(RefCell::new(None)),\n\n func: NoContext(func),\n\n stream_a: self,\n\n stream_b: other,\n\n }\n\n }\n\n\n\n fn distinct_until_changed(self) -> DistinctUntilChanged<Self, Self::Item>\n\n where\n\n Self::Item: 'a + Clone + PartialEq + Sized,\n\n {\n\n DistinctUntilChanged {\n\n buf: Rc::new(RefCell::new(None)),\n", "file_path": "src/reactive/stream_ext.rs", "rank": 55, "score": 18.5609411393508 }, { "content": " bars: stock_bar_set.clone(),\n\n profile: stock_profile.clone(),\n\n symbol: stock_symbol.clone(),\n\n ..Stock::default()\n\n },\n\n )\n\n .broadcast();\n\n\n\n let stock_symbol_field_states = stock_symbol_text_field_events\n\n .clone()\n\n .map(|(_, text_field_state)| text_field_state.clone())\n\n .broadcast();\n\n\n\n let time_frame_menu_states = time_frame_select_menu_events\n\n .clone()\n\n .map(|(_, select_menu_state)| select_menu_state.clone())\n\n .broadcast();\n\n\n\n let indicator_menu_states = indicator_select_menu_events\n\n .clone()\n", "file_path": "src/main.rs", "rank": 56, "score": 17.728818150602287 }, { "content": "use crate::{\n\n app::{App, Indicator, TimeFrame, UiState, UiTarget},\n\n widgets::{SelectMenuBox, SelectMenuList, TextField},\n\n};\n\nuse chrono::{Duration, TimeZone, Utc};\n\nuse im::{hashmap, HashMap};\n\nuse itertools::Itertools;\n\nuse itertools::MinMaxResult::{MinMax, NoElements, OneElement};\n\nuse math::round;\n\nuse std::{cmp, iter, ops::Range};\n\nuse strum::IntoEnumIterator;\n\nuse ta::indicators;\n\nuse ta::{DataItem, Next};\n\nuse tui::{\n\n backend::Backend,\n\n layout::{Alignment, Constraint, Direction, Layout, Rect},\n\n style::{Color, Modifier, Style},\n\n symbols::Marker,\n\n text::{Span, Spans},\n\n widgets::{Axis, Block, Borders, Chart, Clear, Dataset, GraphType, ListItem, Paragraph},\n\n Frame,\n\n};\n\nuse yahoo_finance::Timestamped;\n\n\n", "file_path": "src/ui.rs", "rank": 57, "score": 16.24698408086697 }, { "content": " stock_symbol_field_state,\n\n time_frame_menu_state,\n\n indicator_menu_state,\n\n ),\n\n debug_draw,\n\n )| {\n\n (\n\n *time_frame,\n\n date_range.clone(),\n\n *indicator,\n\n stock_symbol_field_state.clone(),\n\n time_frame_menu_state.clone(),\n\n indicator_menu_state.clone(),\n\n *debug_draw,\n\n )\n\n },\n\n )\n\n .fold(init_ui_state.clone(), {\n\n let ui_target_areas = ui_target_areas.clone();\n\n move |acc_ui_state,\n", "file_path": "src/main.rs", "rank": 58, "score": 16.067328535780593 }, { "content": " observer(ctx, &func.call_mut(ctx, &(a.clone(), b)));\n\n }\n\n }\n\n });\n\n self.stream_b.subscribe({\n\n let buf_b = self.buf_b;\n\n move |b| {\n\n buf_b.borrow_mut().replace(b.clone());\n\n }\n\n });\n\n }\n\n}\n\n\n", "file_path": "src/reactive/stream_ext.rs", "rank": 59, "score": 15.91880447085346 }, { "content": "}\n\n\n\n#[derive(Debug, Error)]\n\npub enum ParseIndicatorError {\n\n #[error(\"cannot parse indicator from empty string\")]\n\n Empty,\n\n #[error(\"invalid indicator literal\")]\n\n Invalid,\n\n #[error(\"invalid indicator parameter {}: {}\", .name, .value)]\n\n ParseInt {\n\n name: String,\n\n source: ParseIntError,\n\n value: String,\n\n },\n\n}\n\n\n\nimpl fmt::Display for Indicator {\n\n fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {\n\n match self {\n\n Self::BollingerBands(n, k) => write!(f, \"BB({}, {})\", n, k),\n", "file_path": "src/app.rs", "rank": 60, "score": 15.836829322634877 }, { "content": " });\n\n (date_range, stock_symbol.clone(), *time_frame)\n\n }\n\n ChartEvent::Reset => reset(),\n\n _ => noop(),\n\n }\n\n },\n\n )\n\n .map(|(date_range, ..)| date_range.clone())\n\n .distinct_until_changed()\n\n}\n\n\n\n#[derive(Clone, Copy, Debug, Eq, Hash, PartialEq)]\n\npub enum UiTarget {\n\n IndicatorBox,\n\n IndicatorMenu,\n\n StockNameButton,\n\n StockSymbolButton,\n\n StockSymbolField,\n\n TimeFrameBox,\n", "file_path": "src/app.rs", "rank": 61, "score": 15.836234595818055 }, { "content": "impl<'a> widgets::StatefulWidget for TextField<'a> {\n\n type State = TextFieldState;\n\n\n\n fn render(self, area: Rect, buf: &mut Buffer, _state: &mut Self::State) {\n\n widgets::Widget::render(Clear, area, buf);\n\n widgets::Widget::render(self.paragraph, area, buf);\n\n }\n\n}\n\n\n\n#[derive(Clone, Debug, Default)]\n\npub struct TextFieldState {\n\n pub active: bool,\n\n pub cursor_offset: usize,\n\n pub value: String,\n\n}\n\n\n\nimpl TextFieldState {\n\n pub fn cursor_point(&self, text_field_area: Rect) -> Option<(u16, u16)> {\n\n if !self.active {\n\n return None;\n", "file_path": "src/widgets/text_field.rs", "rank": 62, "score": 15.668756130663883 }, { "content": "use thiserror::Error;\n\nuse tui::layout::Rect;\n\nuse typenum::{Unsigned, U2, U20, U50};\n\nuse yahoo_finance::Interval;\n\n\n\n#[derive(Clone, Debug)]\n\npub struct App<'r> {\n\n pub stock: Stock,\n\n pub ui_state: UiState<'r>,\n\n}\n\n\n", "file_path": "src/app.rs", "rank": 63, "score": 14.863961406374962 }, { "content": " {\n\n let sink = Broadcast::new();\n\n sink.clone().subscribe_ctx(move |ctx, x| {\n\n observer(ctx, x);\n\n });\n\n self.stream_a.subscribe_ctx({\n\n let sink = sink.clone();\n\n move |ctx, x| {\n\n sink.send_ctx(ctx, x);\n\n }\n\n });\n\n self.stream_b.subscribe_ctx(move |ctx, x| {\n\n sink.send_ctx(ctx, x);\n\n });\n\n }\n\n}\n\n\n\npub struct Switch<S> {\n\n stream: S,\n\n}\n", "file_path": "src/reactive/stream_ext.rs", "rank": 64, "score": 14.67803415161708 }, { "content": " .style(Style::default().fg(Color::Cyan))\n\n .graph_type(GraphType::Line)\n\n .data(&sma_data),\n\n );\n\n }\n\n }\n\n }\n\n\n\n let stock_data = historical_prices_data.get(&stock.symbol).unwrap();\n\n let (stock_timestamps, stock_prices): (Vec<_>, Vec<_>) = stock_data.clone().into_iter().unzip();\n\n\n\n let historical_prices_dataset = Dataset::default()\n\n .marker(Marker::Braille)\n\n .style(Style::default().fg({\n\n let first_price = stock_prices.first().unwrap_or(&0f64);\n\n let last_price = stock_prices.last().unwrap_or(&0f64);\n\n if last_price >= first_price {\n\n Color::Green\n\n } else {\n\n Color::Red\n", "file_path": "src/ui.rs", "rank": 65, "score": 14.590831767795624 }, { "content": " }\n\n}\n\n\n\nimpl<'a, S> widgets::StatefulWidget for SelectMenuList<'a, S>\n\nwhere\n\n S: Clone + PartialEq + ToString,\n\n{\n\n type State = SelectMenuState<S>;\n\n\n\n fn render(self, area: Rect, buf: &mut Buffer, state: &mut Self::State) {\n\n widgets::Widget::render(Clear, area, buf);\n\n widgets::StatefulWidget::render(self.list, area, buf, &mut state.list_state);\n\n }\n\n}\n\n\n\n#[derive(Clone, Debug, Default)]\n\npub struct SelectMenuState<T>\n\nwhere\n\n T: Clone + PartialEq + ToString,\n\n{\n", "file_path": "src/widgets/select_menu.rs", "rank": 66, "score": 14.505814360271593 }, { "content": " }\n\n }))\n\n .graph_type(GraphType::Line)\n\n .data(&stock_data);\n\n historical_prices_datasets.push(historical_prices_dataset);\n\n\n\n let timestamp_steps: Vec<_> = match stock_timestamps.clone().into_iter().minmax() {\n\n MinMax(min, max) => {\n\n let n = cmp::min(\n\n round::floor(\n\n (area.width - 2) as f64 / (X_AXIS_LABEL_WIDTH + X_AXIS_LABEL_PADDING) as f64,\n\n 0,\n\n ) as usize,\n\n stock_timestamps.len(),\n\n );\n\n\n\n itertools_num::linspace(min, max, n).collect()\n\n }\n\n OneElement(t) => vec![t, t],\n\n NoElements => {\n", "file_path": "src/ui.rs", "rank": 67, "score": 14.3045502311662 }, { "content": "\n\n#[derive(Clone, Copy, Debug)]\n\npub enum ChartEvent {\n\n PanBackward,\n\n PanForward,\n\n Reset,\n\n}\n\n\n\n#[derive(Clone, Debug)]\n\npub enum TextFieldEvent {\n\n Accept(String),\n\n Activate,\n\n BackspacePastStart,\n\n Deactivate,\n\n DeletePastEnd,\n\n Input(String),\n\n MoveCursor(usize),\n\n MoveCursorPastEnd,\n\n MoveCursorPastStart,\n\n Toggle,\n", "file_path": "src/event.rs", "rank": 68, "score": 14.1524509564934 }, { "content": " (\n\n time_frame,\n\n date_range,\n\n indicator,\n\n stock_symbol_field_state,\n\n time_frame_menu_state,\n\n indicator_menu_state,\n\n debug_draw,\n\n )| UiState {\n\n date_range: date_range.clone(),\n\n debug_draw: *debug_draw,\n\n indicator: *indicator,\n\n indicator_menu_state: Rc::new(RefCell::new(indicator_menu_state.clone())),\n\n stock_symbol_field_state: Rc::new(RefCell::new(stock_symbol_field_state.clone())),\n\n time_frame: *time_frame,\n\n time_frame_menu_state: Rc::new(RefCell::new(time_frame_menu_state.clone())),\n\n ui_target_areas: ui_target_areas.clone(),\n\n ..acc_ui_state.clone()\n\n }\n\n })\n", "file_path": "src/main.rs", "rank": 69, "score": 13.98868343709275 }, { "content": " ),\n\n indicator_menu_state,\n\n )| {\n\n (\n\n *time_frame,\n\n date_range.clone(),\n\n *indicator,\n\n stock_symbol_field_state.clone(),\n\n time_frame_menu_state.clone(),\n\n indicator_menu_state.clone(),\n\n )\n\n },\n\n )\n\n .combine_latest(\n\n debug_draws.clone(),\n\n |(\n\n (\n\n time_frame,\n\n date_range,\n\n indicator,\n", "file_path": "src/main.rs", "rank": 70, "score": 13.76866788298543 }, { "content": "}\n\n\n\n#[derive(Clone, Debug)]\n\npub enum SelectMenuEvent {\n\n Accept(Option<String>),\n\n Activate,\n\n Deactivate,\n\n SelectIndex(usize),\n\n Toggle,\n\n}\n\n\n\n#[derive(Clone, Debug)]\n\npub enum OverlayEvent {\n\n SelectMenu(SelectMenuEvent),\n\n TextField(TextFieldEvent),\n\n}\n\n\n\n#[derive(Clone, Copy, Debug, Derivative, Eq, PartialEq)]\n\n#[derivative(Default)]\n\npub enum OverlayState {\n\n Active,\n\n #[derivative(Default)]\n\n Inactive,\n\n}\n\n\n", "file_path": "src/event.rs", "rank": 71, "score": 13.64549102840295 }, { "content": " })\n\n .combine_latest(\n\n indicators.clone(),\n\n |((time_frame, date_range), indicator)| (*time_frame, date_range.clone(), *indicator),\n\n )\n\n .combine_latest(\n\n stock_symbol_field_states.clone(),\n\n |((time_frame, date_range, indicator), stock_symbol_field_state)| {\n\n (\n\n *time_frame,\n\n date_range.clone(),\n\n *indicator,\n\n stock_symbol_field_state.clone(),\n\n )\n\n },\n\n )\n\n .combine_latest(\n\n time_frame_menu_states.clone(),\n\n |(\n\n (time_frame, date_range, indicator, stock_symbol_field_state),\n", "file_path": "src/main.rs", "rank": 72, "score": 13.54264671373302 }, { "content": " // send the initial values\n\n chart_events.send(ChartEvent::Reset);\n\n time_frames.send(args.time_frame);\n\n indicators.send(args.indicator);\n\n stock_symbols.send(args.symbol);\n\n stock_symbol_field_states.send(init_stock_symbol_field_state);\n\n time_frame_menu_states.send(init_time_frame_menu_state);\n\n indicator_menu_states.send(init_indicator_menu_state);\n\n debug_draws.send(args.debug_draw);\n\n active_overlays.send(None);\n\n overlay_states.feed(\n\n vec![\n\n (UiTarget::StockSymbolField, OverlayState::default()),\n\n (UiTarget::TimeFrameMenu, OverlayState::default()),\n\n (UiTarget::IndicatorMenu, OverlayState::default()),\n\n ]\n\n .iter(),\n\n );\n\n\n\n while !should_quit.load(atomic::Ordering::Relaxed) {\n", "file_path": "src/main.rs", "rank": 73, "score": 13.398028320489956 }, { "content": "pub struct SelectMenuList<'a, S: 'a>\n\nwhere\n\n S: Clone + PartialEq + ToString,\n\n{\n\n list: List<'a>,\n\n phantom_s: PhantomData<&'a S>,\n\n}\n\n\n\nimpl<'a, S> SelectMenuList<'a, S>\n\nwhere\n\n S: Clone + PartialEq + ToString,\n\n{\n\n pub fn new<L>(items: L) -> Self\n\n where\n\n L: Into<Vec<ListItem<'a>>>,\n\n {\n\n Self {\n\n list: List::new(items)\n\n .block(\n\n Block::default()\n", "file_path": "src/widgets/select_menu.rs", "rank": 74, "score": 13.092181930360999 }, { "content": " (\n\n UiTarget::IndicatorMenu,\n\n OverlayEvent::SelectMenu(ev.clone()),\n\n )\n\n }))\n\n .inspect(|(ui_target, ev)| {\n\n debug!(\"overlay event: {:?}\", (ui_target, ev));\n\n })\n\n .broadcast();\n\n\n\n event::queue_overlay_states_for_next_tick(overlay_events.clone(), overlay_state_queue.clone());\n\n\n\n let stock_symbols = stock_symbol_text_field_events\n\n .clone()\n\n .fold(args.symbol.clone(), |acc_symbol, (ev, ..)| {\n\n if let TextFieldEvent::Accept(symbol) = ev {\n\n symbol.clone()\n\n } else {\n\n acc_symbol.clone()\n\n }\n", "file_path": "src/main.rs", "rank": 75, "score": 12.866066056107861 }, { "content": " let key_grouped_map = self.key_grouped_map;\n\n let mut value_func = self.value_func;\n\n move |ctx, x| {\n\n let key = key_func.call_mut(ctx, x);\n\n let mut key_grouped_map = key_grouped_map.borrow_mut();\n\n let grouped = key_grouped_map.entry(key.clone()).or_insert_with(|| {\n\n let grouped = Grouped {\n\n key: key.clone(),\n\n sink: Broadcast::new(),\n\n };\n\n observer(ctx, &grouped);\n\n grouped\n\n });\n\n grouped.sink.send_ctx(ctx, value_func.call_mut(ctx, x));\n\n }\n\n });\n\n }\n\n}\n\n\n\n#[derive(Derivative)]\n", "file_path": "src/reactive/stream_ext.rs", "rank": 76, "score": 12.592953289771405 }, { "content": " TimeFrameMenu,\n\n}\n\n\n\n#[derive(Debug)]\n\npub struct FrameRateCounter {\n\n frame_time: u16,\n\n frames: u16,\n\n last_interval: DateTime<Utc>,\n\n update_interval: Duration,\n\n}\n\n\n\nimpl FrameRateCounter {\n\n pub fn new(update_interval: Duration) -> Self {\n\n Self {\n\n frame_time: 0,\n\n frames: 0,\n\n last_interval: Utc::now(),\n\n update_interval,\n\n }\n\n }\n", "file_path": "src/app.rs", "rank": 77, "score": 12.55606262219985 }, { "content": "use crate::{\n\n app::UiTarget,\n\n reactive::{Grouped, StreamExt},\n\n widgets::{SelectMenuState, TextFieldState},\n\n};\n\nuse bimap::BiMap;\n\nuse crossterm::event::{KeyCode, KeyEvent, MouseButton, MouseEvent, MouseEventKind};\n\nuse derivative::Derivative;\n\nuse im::{hashmap, hashmap::HashMap};\n\nuse log::debug;\n\nuse reactive_rs::Stream;\n\nuse std::{cell::RefCell, collections::VecDeque, iter, rc::Rc};\n\nuse tui::layout::Rect;\n\n\n\n#[derive(Clone, Copy, Debug)]\n\npub enum InputEvent {\n\n Key(KeyEvent),\n\n Mouse(MouseEvent),\n\n Tick,\n\n}\n", "file_path": "src/event.rs", "rank": 78, "score": 12.369765875126337 }, { "content": " time_frame_menu_state,\n\n )| {\n\n (\n\n *time_frame,\n\n date_range.clone(),\n\n *indicator,\n\n stock_symbol_field_state.clone(),\n\n time_frame_menu_state.clone(),\n\n )\n\n },\n\n )\n\n .combine_latest(\n\n indicator_menu_states.clone(),\n\n |(\n\n (\n\n time_frame,\n\n date_range,\n\n indicator,\n\n stock_symbol_field_state,\n\n time_frame_menu_state,\n", "file_path": "src/main.rs", "rank": 79, "score": 12.263423478494902 }, { "content": " pub active: bool,\n\n pub allow_empty_selection: bool,\n\n pub items: Vec<T>,\n\n list_state: ListState,\n\n}\n\n\n\nimpl<T> SelectMenuState<T>\n\nwhere\n\n T: Clone + PartialEq + ToString,\n\n{\n\n pub fn new<I>(items: I) -> SelectMenuState<T>\n\n where\n\n I: IntoIterator<Item = T>,\n\n {\n\n Self {\n\n active: false,\n\n allow_empty_selection: false,\n\n items: items.into_iter().collect(),\n\n list_state: ListState::default(),\n\n }\n", "file_path": "src/widgets/select_menu.rs", "rank": 80, "score": 12.074466117880068 }, { "content": " self.list_state.selected()\n\n }\n\n\n\n pub fn select(&mut self, item: Option<T>) -> anyhow::Result<()> {\n\n let n = item.map_or_else(\n\n || {\n\n ensure!(self.allow_empty_selection, \"empty selection not allowed\");\n\n Ok(0)\n\n },\n\n |item| {\n\n self.items\n\n .iter()\n\n .cloned()\n\n .position(|t| t == item)\n\n .map(|n| if self.allow_empty_selection { n + 1 } else { n })\n\n .with_context(|| \"item not found\")\n\n },\n\n )?;\n\n\n\n self.select_index(n)?;\n", "file_path": "src/widgets/select_menu.rs", "rank": 81, "score": 12.062513873690529 }, { "content": " chart_events.clone(),\n\n stock_symbols.clone(),\n\n args.symbol.clone(),\n\n time_frames.clone(),\n\n args.time_frame,\n\n )\n\n .broadcast();\n\n\n\n let indicators = indicator_select_menu_events\n\n .clone()\n\n .fold(args.indicator, |acc_indicator, (ev, ..)| {\n\n if let SelectMenuEvent::Accept(indicator) = ev {\n\n indicator.as_ref().map(|s| s.parse().unwrap())\n\n } else {\n\n *acc_indicator\n\n }\n\n })\n\n .distinct_until_changed()\n\n .broadcast();\n\n\n", "file_path": "src/main.rs", "rank": 82, "score": 11.978954959181348 }, { "content": " TenYears,\n\n Max,\n\n}\n\n\n\nimpl TimeFrame {\n\n pub fn duration(self) -> Option<Duration> {\n\n match self {\n\n Self::FiveDays => Some(Duration::days(5)),\n\n Self::OneMonth => Some(Duration::days(30)),\n\n Self::ThreeMonths => Some(Duration::days(30 * 3)),\n\n Self::SixMonths => Some(Duration::days(30 * 6)),\n\n Self::OneYear => Some(Duration::days(30 * 12)),\n\n Self::TwoYears => Some(Duration::days(30 * 12 * 2)),\n\n Self::FiveYears => Some(Duration::days(30 * 12 * 5)),\n\n Self::TenYears => Some(Duration::days(30 * 12 * 10)),\n\n _ => None,\n\n }\n\n }\n\n\n\n pub fn interval(self) -> Interval {\n", "file_path": "src/app.rs", "rank": 83, "score": 11.975113832811601 }, { "content": " Constraint::Min(0),\n\n Constraint::Length(cmp::min(\n\n Indicator::iter().count() as u16 + 1 + 2,\n\n indicator_list_area.height - 2,\n\n )),\n\n Constraint::Length(2),\n\n ])\n\n .split(indicator_list_area);\n\n chunks[1]\n\n };\n\n\n\n let indicator_menu_items: Vec<_> = iter::once(\"None\".to_owned())\n\n .chain(Indicator::iter().map(|t| t.to_string()))\n\n .map(ListItem::new)\n\n .collect();\n\n let indicator_list = SelectMenuList::new(indicator_menu_items)\n\n .border_style(Style::default().fg(Color::Gray))\n\n .highlight_style(highlight_base_style);\n\n drop(indicator_menu_state);\n\n let mut indicator_menu_state = ui_state.indicator_menu_state.borrow_mut();\n", "file_path": "src/ui.rs", "rank": 84, "score": 11.74926245732562 }, { "content": " ];\n\n let x_axis_labels: Vec<_> = timestamp_steps\n\n .iter()\n\n .map(|&t| Span::from(Utc.timestamp(t as i64, 0).format(\"%Y-%m-%d\").to_string()))\n\n .collect();\n\n\n\n let (_, prices): (Vec<_>, Vec<_>) = historical_prices_data.values().flatten().copied().unzip();\n\n let price_steps: Vec<_> = match prices.into_iter().minmax() {\n\n MinMax(min, max) => {\n\n let n = round::floor(\n\n (area.height - 2) as f64 / (Y_AXIS_LABEL_HEIGHT + Y_AXIS_LABEL_PADDING) as f64,\n\n 0,\n\n ) as usize;\n\n\n\n itertools_num::linspace(min, max, n).collect()\n\n }\n\n OneElement(p) => vec![p, p],\n\n NoElements => vec![0_f64, f64::INFINITY],\n\n };\n\n let y_axis_bounds = [*price_steps.first().unwrap(), *price_steps.last().unwrap()];\n", "file_path": "src/ui.rs", "rank": 85, "score": 11.746882244799648 }, { "content": " let stock_symbol_field_area = chunks[1];\n\n\n\n let stock_symbol_field = TextField::new(Span::styled(\n\n stock_symbol_field_state.value.clone(),\n\n active_base_style,\n\n ))\n\n .border_style(Style::default().fg(Color::Gray));\n\n drop(stock_symbol_field_state);\n\n let mut stock_symbol_field_state = ui_state.stock_symbol_field_state.borrow_mut();\n\n f.render_stateful_widget(\n\n stock_symbol_field,\n\n stock_symbol_field_area,\n\n &mut stock_symbol_field_state,\n\n );\n\n\n\n ui_state\n\n .ui_target_areas\n\n .send((UiTarget::StockSymbolField, Some(stock_symbol_field_area)));\n\n } else {\n\n ui_state\n", "file_path": "src/ui.rs", "rank": 86, "score": 11.74082476690558 }, { "content": " None => SelectMenuEvent::Deactivate,\n\n },\n\n )\n\n .broadcast();\n\n\n\n let overlay_events = stock_symbol_text_field_events\n\n .clone()\n\n .map(|(ev, ..)| {\n\n (\n\n UiTarget::StockSymbolField,\n\n OverlayEvent::TextField(ev.clone()),\n\n )\n\n })\n\n .merge(time_frame_select_menu_events.clone().map(|(ev, ..)| {\n\n (\n\n UiTarget::TimeFrameMenu,\n\n OverlayEvent::SelectMenu(ev.clone()),\n\n )\n\n }))\n\n .merge(indicator_select_menu_events.clone().map(|(ev, ..)| {\n", "file_path": "src/main.rs", "rank": 87, "score": 11.616218827051107 }, { "content": " .map(|(_, select_menu_state)| select_menu_state.clone())\n\n .broadcast();\n\n\n\n let debug_draws: Broadcast<(), bool> = Broadcast::new();\n\n\n\n let init_ui_state = UiState {\n\n date_range: args.time_frame.now_date_range(),\n\n debug_draw: args.debug_draw,\n\n indicator: args.indicator,\n\n indicator_menu_state: Rc::new(RefCell::new(init_indicator_menu_state.clone())),\n\n stock_symbol_field_state: Rc::new(RefCell::new(init_stock_symbol_field_state.clone())),\n\n time_frame: args.time_frame,\n\n time_frame_menu_state: Rc::new(RefCell::new(init_time_frame_menu_state.clone())),\n\n ..UiState::default()\n\n };\n\n\n\n let ui_states = time_frames\n\n .clone()\n\n .combine_latest(date_ranges.clone(), |(time_frame, date_range)| {\n\n (*time_frame, date_range.clone())\n", "file_path": "src/main.rs", "rank": 88, "score": 11.596325601382913 }, { "content": "use anyhow::{ensure, Context};\n\nuse std::marker::PhantomData;\n\nuse tui::{\n\n buffer::Buffer,\n\n layout::{Alignment, Margin, Rect},\n\n style::{Color, Style},\n\n text::Text,\n\n widgets::{self, Block, Borders, Clear, List, ListItem, ListState, Paragraph},\n\n};\n\n\n\npub struct SelectMenuBox<'a, S: 'a>\n\nwhere\n\n S: Clone + PartialEq + ToString,\n\n{\n\n active_border_style: Style,\n\n active_style: Style,\n\n paragraph: Paragraph<'a>,\n\n phantom_s: PhantomData<&'a S>,\n\n}\n\n\n", "file_path": "src/widgets/select_menu.rs", "rank": 89, "score": 11.538802204970983 }, { "content": " .broadcast();\n\n\n\n let cursor_points = stock_symbol_field_states\n\n .clone()\n\n .combine_latest(\n\n ui_target_areas\n\n .clone()\n\n .filter(|(ui_target, ..)| matches!(ui_target, UiTarget::StockSymbolField)),\n\n |(text_field_state, (_, area))| (text_field_state.clone(), *area),\n\n )\n\n .map(|(text_field_state, area)| {\n\n if let Some(area) = *area {\n\n text_field_state.cursor_point(area)\n\n } else {\n\n None\n\n }\n\n })\n\n .broadcast();\n\n\n\n tick_input_events\n", "file_path": "src/main.rs", "rank": 90, "score": 11.434642095552087 }, { "content": " .filter(|grouped| !grouped.key)\n\n .switch()\n\n .broadcast();\n\n\n\n let hotkey_overlay_map = {\n\n let mut bimap = BiMap::new();\n\n bimap.insert(KeyCode::Char('i'), UiTarget::IndicatorMenu);\n\n bimap.insert(KeyCode::Char('s'), UiTarget::StockSymbolField);\n\n bimap.insert(KeyCode::Char('t'), UiTarget::TimeFrameMenu);\n\n bimap\n\n };\n\n\n\n let associated_overlay_map = hashmap! {\n\n UiTarget::IndicatorBox => UiTarget::IndicatorMenu,\n\n UiTarget::IndicatorMenu => UiTarget::IndicatorMenu,\n\n UiTarget::StockNameButton => UiTarget::StockSymbolField,\n\n UiTarget::StockSymbolButton => UiTarget::StockSymbolField,\n\n UiTarget::StockSymbolField => UiTarget::StockSymbolField,\n\n UiTarget::TimeFrameBox => UiTarget::TimeFrameMenu,\n\n UiTarget::TimeFrameMenu => UiTarget::TimeFrameMenu,\n", "file_path": "src/main.rs", "rank": 91, "score": 11.348929757049515 }, { "content": "use crate::{\n\n app::{App, Indicator, TimeFrame, UiState, UiTarget},\n\n event::{ChartEvent, InputEvent, OverlayEvent, OverlayState, SelectMenuEvent, TextFieldEvent},\n\n reactive::StreamExt as ReactiveStreamExt,\n\n stock::Stock,\n\n widgets::{SelectMenuState, TextFieldState},\n\n};\n\nuse argh::FromArgs;\n\nuse async_std::stream::{self, StreamExt};\n\nuse bimap::BiMap;\n\nuse crossterm::{\n\n cursor,\n\n event::{Event, EventStream, KeyCode, KeyEvent},\n\n execute, terminal,\n\n};\n\nuse im::hashmap;\n\nuse log::debug;\n\nuse reactive_rs::{Broadcast, Stream};\n\nuse simplelog::{Config as LoggerConfig, LevelFilter, WriteLogger};\n\nuse std::{\n", "file_path": "src/main.rs", "rank": 92, "score": 11.180301446445934 }, { "content": "\n\n let stock_symbol_text_field_events = event::to_text_field_events(\n\n grouped_user_input_events\n\n .clone()\n\n .filter(|grouped| grouped.key == Some(UiTarget::StockSymbolField))\n\n .switch(),\n\n init_stock_symbol_field_state.clone(),\n\n grouped_overlay_states\n\n .clone()\n\n .filter(|grouped| grouped.key == UiTarget::StockSymbolField)\n\n .switch(),\n\n hotkey_overlay_map\n\n .get_by_right(&UiTarget::StockSymbolField)\n\n .copied()\n\n .unwrap(),\n\n ui_target_areas.clone(),\n\n UiTarget::StockSymbolField,\n\n hashmap! {\n\n Some(UiTarget::StockSymbolButton) => TextFieldEvent::Toggle,\n\n Some(UiTarget::StockNameButton) => TextFieldEvent::Toggle,\n", "file_path": "src/main.rs", "rank": 93, "score": 11.152871623665042 }, { "content": " *time_frame,\n\n )\n\n };\n\n\n\n let stock_symbol_changed = acc_stock_symbol != stock_symbol;\n\n let time_frame_changed = acc_time_frame != time_frame;\n\n if stock_symbol_changed || time_frame_changed {\n\n return reset();\n\n }\n\n\n\n match ev {\n\n ChartEvent::PanBackward if time_frame != &TimeFrame::YearToDate => {\n\n let date_range = time_frame.duration().map(|duration| {\n\n acc_date_range\n\n .as_ref()\n\n .map(|acc_date_range| {\n\n let end_date = acc_date_range.start;\n\n (end_date - duration)..end_date\n\n })\n\n .unwrap()\n", "file_path": "src/app.rs", "rank": 94, "score": 11.140815554969233 }, { "content": " }\n\n }\n\n\n\n fn merge<U>(self, other: U) -> Merge<Self, U>\n\n where\n\n U: Stream<'a, Item = Self::Item, Context = Self::Context>,\n\n {\n\n Merge {\n\n stream_a: self,\n\n stream_b: other,\n\n }\n\n }\n\n\n\n fn switch(self) -> Switch<Self>\n\n where\n\n Self::Item: Stream<'a>,\n\n {\n\n Switch { stream: self }\n\n }\n\n\n", "file_path": "src/reactive/stream_ext.rs", "rank": 95, "score": 11.136733133207962 }, { "content": " drop(buf_b);\n\n sink.send_ctx(ctx, &(a.clone(), b));\n\n }\n\n }\n\n });\n\n self.stream_b.subscribe({\n\n let buf_a = self.buf_a;\n\n let buf_b = self.buf_b;\n\n let buf_ctx = self.buf_ctx;\n\n move |b| {\n\n buf_b.borrow_mut().replace(b.clone());\n\n let buf_a = buf_a.borrow();\n\n if let Some(a) = buf_a.as_ref() {\n\n let a = a.clone();\n\n let buf_ctx = buf_ctx.borrow();\n\n let ctx = buf_ctx.as_ref().cloned().unwrap();\n\n drop(buf_a);\n\n drop(buf_ctx);\n\n sink.send_ctx(&ctx, &(a, b.clone()));\n\n }\n", "file_path": "src/reactive/stream_ext.rs", "rank": 96, "score": 11.090344771013132 }, { "content": "\n\n pub fn active_style(mut self, active_style: Style) -> Self {\n\n self.active_style = active_style;\n\n self\n\n }\n\n\n\n pub fn alignment(mut self, alignment: Alignment) -> Self {\n\n self.paragraph = self.paragraph.alignment(alignment);\n\n self\n\n }\n\n}\n\n\n\nimpl<'a, S> widgets::StatefulWidget for SelectMenuBox<'a, S>\n\nwhere\n\n S: Clone + PartialEq + ToString,\n\n{\n\n type State = SelectMenuState<S>;\n\n\n\n fn render(self, area: Rect, buf: &mut Buffer, state: &mut Self::State) {\n\n let paragraph = self\n", "file_path": "src/widgets/select_menu.rs", "rank": 97, "score": 10.990281551066943 }, { "content": " }\n\n\n\n pub fn selected(&self) -> Option<T> {\n\n self.list_state\n\n .selected()\n\n .map(|n| {\n\n if self.allow_empty_selection {\n\n if n == 0 {\n\n None\n\n } else {\n\n Some(n - 1)\n\n }\n\n } else {\n\n Some(n)\n\n }\n\n })?\n\n .map(|n| self.items[n].clone())\n\n }\n\n\n\n pub fn selected_index(&self) -> Option<usize> {\n", "file_path": "src/widgets/select_menu.rs", "rank": 98, "score": 10.9887814890306 }, { "content": " let input_event_stream = EventStream::new()\n\n .filter(|ev| matches!(ev, Ok(Event::Key(_)) | Ok(Event::Mouse(_))))\n\n .map(|ev| match ev {\n\n Ok(Event::Key(key_event)) => InputEvent::Key(key_event),\n\n Ok(Event::Mouse(mouse_event)) => InputEvent::Mouse(mouse_event),\n\n _ => unreachable!(),\n\n });\n\n let tick_stream = stream::interval(time::Duration::from_millis(TICK_RATE));\n\n let input_tick_stream = tick_stream.map(|()| InputEvent::Tick);\n\n let mut input_event_stream = input_event_stream.merge(input_tick_stream);\n\n\n\n // draw once before hitting the network, as it is blocking\n\n stocks.send(Stock {\n\n symbol: args.symbol.clone(),\n\n ..Stock::default()\n\n });\n\n ui_states.send(init_ui_state);\n\n cursor_points.send(None);\n\n input_events.send(InputEvent::Tick);\n\n\n", "file_path": "src/main.rs", "rank": 99, "score": 10.83264609353551 } ]
Rust
qlib/kernel/fs/fsutil/inode/simple_file_inode.rs
abel-von/Quark
7bbba67ee1105e3b7df751a278cbad9b2af666a1
use alloc::string::String; use crate::qlib::mutex::*; use core::ops::Deref; use alloc::vec::Vec; use core::any::Any; use super::super::super::super::socket::unix::transport::unix::*; use super::super::super::mount::*; use super::super::super::attr::*; use super::super::super::inode::*; use super::super::super::flags::*; use super::super::super::file::*; use super::super::super::dirent::*; use super::super::super::super::super::linux_def::*; use super::super::super::super::task::*; use super::super::super::super::super::common::*; use super::super::super::super::super::auth::*; use super::super::super::super::kernel::time::*; use super::super::super::host::hostinodeop::*; pub trait SimpleFileTrait : Send + Sync { fn GetFile(&self, _task: &Task, _dir: &Inode, _dirent: &Dirent, _flags: FileFlags) -> Result<File> { return Err(Error::SysError(SysErr::ENXIO)) }} pub struct SimpleFileNode {} impl SimpleFileTrait for SimpleFileNode {} pub struct SimpleFileInodeInternal <T: 'static + SimpleFileTrait> { pub fsType: u64, pub unstable: UnstableAttr, pub wouldBlock: bool, pub data: T, } pub struct SimpleFileInode<T: 'static + SimpleFileTrait> (QRwLock<SimpleFileInodeInternal<T>>); impl <T: 'static + SimpleFileTrait> Deref for SimpleFileInode <T> { type Target = QRwLock<SimpleFileInodeInternal<T>>; fn deref(&self) -> &QRwLock<SimpleFileInodeInternal<T>> { &self.0 } } impl <T: 'static + SimpleFileTrait> SimpleFileInode <T> { pub fn New(task: &Task, owner: &FileOwner, perms: &FilePermissions, typ: u64, wouldBlock: bool, data: T) -> Self { let unstable = WithCurrentTime(task, &UnstableAttr { Owner: *owner, Perms: *perms, ..Default::default() }); return Self::NewWithUnstable(&unstable, typ, wouldBlock, data) } pub fn NewWithUnstable(u: &UnstableAttr, typ: u64, wouldBlock: bool, data: T) -> Self { let internal = SimpleFileInodeInternal { fsType: typ, unstable: *u, wouldBlock: wouldBlock, data: data, }; return Self(QRwLock::new(internal)) } } impl <T: 'static + SimpleFileTrait> InodeOperations for SimpleFileInode <T> { fn as_any(&self) -> &Any { self } fn IopsType(&self) -> IopsType { return IopsType::SimpleFileInode; } fn InodeType(&self) -> InodeType { return InodeType::SpecialFile; } fn InodeFileType(&self) -> InodeFileType { return InodeFileType::SimpleFileInode; } fn WouldBlock(&self) -> bool { return self.read().wouldBlock; } fn Check(&self, task: &Task, inode: &Inode, reqPerms: &PermMask) -> Result<bool> { return ContextCanAccessFile(task, inode, reqPerms) } fn Getxattr(&self, _dir: &Inode, _name: &str) -> Result<String> { return Err(Error::SysError(SysErr::EOPNOTSUPP)) } fn Setxattr(&self, _dir: &mut Inode, _name: &str, _value: &str) -> Result<()> { return Err(Error::SysError(SysErr::EOPNOTSUPP)) } fn Listxattr(&self, _dir: &Inode) -> Result<Vec<String>> { return Err(Error::SysError(SysErr::EOPNOTSUPP)) } fn Allocate(&self, _task: &Task, _dir: &mut Inode, _offset: i64, _length: i64) -> Result<()> { return Err(Error::SysError(SysErr::EOPNOTSUPP)) } fn Lookup(&self, _task: &Task, _dir: &Inode, _name: &str) -> Result<Dirent> { return Err(Error::SysError(SysErr::ENOTDIR)) } fn Create(&self, _task: &Task, _dir: &mut Inode, _name: &str, _flags: &FileFlags, _perm: &FilePermissions) -> Result<File> { return Err(Error::SysError(SysErr::ENOTDIR)) } fn CreateDirectory(&self, _task: &Task, _dir: &mut Inode, _name: &str, _perm: &FilePermissions) -> Result<()> { return Err(Error::SysError(SysErr::ENOTDIR)) } fn CreateLink(&self, _task: &Task, _dir: &mut Inode, _oldname: &str, _newname: &str) -> Result<()> { return Err(Error::SysError(SysErr::ENOTDIR)) } fn CreateHardLink(&self, _task: &Task, _dir: &mut Inode, _target: &Inode, _name: &str) -> Result<()> { return Err(Error::SysError(SysErr::ENOTDIR)) } fn CreateFifo(&self, _task: &Task, _dir: &mut Inode, _name: &str, _perm: &FilePermissions) -> Result<()> { return Err(Error::SysError(SysErr::ENOTDIR)) } fn Remove(&self, _task: &Task, _dir: &mut Inode, _name: &str) -> Result<()> { return Err(Error::SysError(SysErr::ENOTDIR)) } fn RemoveDirectory(&self, _task: &Task, _dir: &mut Inode, _name: &str) -> Result<()> { return Err(Error::SysError(SysErr::ENOTDIR)) } fn Rename(&self, _task: &Task, _dir: &mut Inode, _oldParent: &Inode, _oldname: &str, _newParent: &Inode, _newname: &str, _replacement: bool) -> Result<()> { return Err(Error::SysError(SysErr::EINVAL)) } fn Bind(&self, _task: &Task, _dir: &Inode, _name: &str, _data: &BoundEndpoint, _perms: &FilePermissions) -> Result<Dirent> { return Err(Error::SysError(SysErr::ENOTDIR)) } fn BoundEndpoint(&self, _task: &Task, _inode: &Inode, _path: &str) -> Option<BoundEndpoint> { return None } fn GetFile(&self, task: &Task, dir: &Inode, dirent: &Dirent, flags: FileFlags) -> Result<File> { return self.read().data.GetFile(task, dir, dirent, flags) } fn ReadLink(&self, _task: &Task,_dir: &Inode) -> Result<String> { return Err(Error::SysError(SysErr::ENOLINK)) } fn GetLink(&self, _task: &Task, _dir: &Inode) -> Result<Dirent> { return Err(Error::SysError(SysErr::ENOLINK)) } fn Truncate(&self, _task: &Task, _dir: &mut Inode, _size: i64) -> Result<()> { return Err(Error::SysError(SysErr::EINVAL)) } fn IsVirtual(&self) -> bool { return false } fn UnstableAttr(&self, _task: &Task, _dir: &Inode) -> Result<UnstableAttr> { let u = self.read().unstable; return Ok(u) } fn SetPermissions(&self, task: &Task, _dir: &mut Inode, p: FilePermissions) -> bool { self.write().unstable.SetPermissions(task, &p); return true; } fn SetOwner(&self, task: &Task, _dir: &mut Inode, owner: &FileOwner) -> Result<()> { self.write().unstable.SetOwner(task, owner); return Ok(()) } fn SetTimestamps(&self, task: &Task, _dir: &mut Inode, ts: &InterTimeSpec) -> Result<()> { self.write().unstable.SetTimestamps(task, ts); return Ok(()) } fn AddLink(&self, _task: &Task) { self.write().unstable.Links += 1; } fn DropLink(&self, _task: &Task) { self.write().unstable.Links -= 1; } fn Sync(&self) -> Result<()> { return Err(Error::SysError(SysErr::ENOSYS)); } fn StatFS(&self, _task: &Task) -> Result<FsInfo> { if self.read().fsType == 0 { return Err(Error::SysError(SysErr::ENOSYS)) } return Ok(FsInfo { Type: self.read().fsType, ..Default::default() }) } fn Mappable(&self) -> Result<HostInodeOp> { return Err(Error::SysError(SysErr::ENODEV)) } } #[derive(Clone, Default, Debug)] pub struct InodeSimpleAttributesInternal { pub fsType: u64, pub unstable: UnstableAttr, } impl InodeSimpleAttributesInternal { pub fn New(task: &Task, owner: &FileOwner, perms: &FilePermissions, typ: u64) -> Self { let unstable = WithCurrentTime(task, &UnstableAttr { Owner: *owner, Perms: *perms, ..Default::default() }); let internal = InodeSimpleAttributesInternal { fsType: typ, unstable: unstable, }; return internal } } pub struct InodeSimpleAttributes(pub QRwLock<InodeSimpleAttributesInternal>); impl Default for InodeSimpleAttributes { fn default() -> Self { return Self(QRwLock::new(Default::default())) } } impl Deref for InodeSimpleAttributes { type Target = QRwLock<InodeSimpleAttributesInternal>; fn deref(&self) -> &QRwLock<InodeSimpleAttributesInternal> { &self.0 } } impl InodeSimpleAttributes { pub fn New(task: &Task, owner: &FileOwner, perms: &FilePermissions, typ: u64) -> Self { let unstable = WithCurrentTime(task, &UnstableAttr { Owner: *owner, Perms: *perms, ..Default::default() }); return Self::NewWithUnstable(&unstable, typ) } fn NewWithUnstable(u: &UnstableAttr, typ: u64) -> Self { let internal = InodeSimpleAttributesInternal { fsType: typ, unstable: *u, }; return Self(QRwLock::new(internal)) } fn UnstableAttr(&self, _task: &Task, _dir: &Inode) -> Result<UnstableAttr> { let u = self.read().unstable; return Ok(u) } fn SetPermissions(&self, task: &Task, _dir: &mut Inode, p: FilePermissions) -> bool { self.write().unstable.SetPermissions(task, &p); return true; } fn SetOwner(&self, task: &Task, _dir: &mut Inode, owner: &FileOwner) -> Result<()> { self.write().unstable.SetOwner(task, owner); return Ok(()) } fn SetTimestamps(&self, task: &Task, _dir: &mut Inode, ts: &InterTimeSpec) -> Result<()> { self.write().unstable.SetTimestamps(task, ts); return Ok(()) } fn AddLink(&self, _task: &Task) { self.write().unstable.Links += 1; } fn DropLink(&self, _task: &Task) { self.write().unstable.Links -= 1; } }
use alloc::string::String; use crate::qlib::mutex::*; use core::ops::Deref; use alloc::vec::Vec; use core::any::Any; use super::super::super::super::socket::unix::transport::unix::*; use super::super::super::mount::*; use super::super::super::attr::*; use super::super::super::inode::*; use super::super::super::flags::*; use super::super::super::file::*; use super::super::super::dirent::*; use super::super::super::super::super::linux_def::*; use super::super::super::super::task::*; use super::super::super::super::super::common::*; use super::super::super::super::super::auth::*; use super::super::super::super::kernel::time::*; use super::super::super::host::hostinodeop::*; pub trait SimpleFileTrait : Send + Sync { fn GetFile(&self, _task: &Task, _dir: &Inode, _dirent: &Dirent, _flags: FileFlags) -> Result<File> { return Err(Error::SysError(SysErr::ENXIO)) }} pub struct SimpleFileNode {} impl SimpleFileTrait for SimpleFileNode {} pub struct SimpleFileInodeInternal <T: 'static + SimpleFileTrait> { pub fsType: u64, pub unstable: UnstableAttr, pub wouldBlock: bool, pub data: T, } pub struct SimpleFileInode<T: 'static + SimpleFileTrait> (QRwLock<SimpleFileInodeInternal<T>>); impl <T: 'static + SimpleFileTrait> Deref for SimpleFileInode <T> { type Target = QRwLock<SimpleFileInodeInternal<T>>; fn deref(&self) -> &QRwLock<SimpleFileInodeInternal<T>> { &self.0 } } impl <T: 'static + SimpleFileTrait> SimpleFileInode <T> { pub fn New(task: &Task, owner: &FileOwner, perms: &FilePermissions, typ: u64, wouldBlock: bool, data: T) -> Self { let unstable = WithCurrentTime(task, &UnstableAttr { Owner: *owner, Perms: *perms, ..Default::default() }); return Self::NewWithUnstable(&unstable, typ, wouldBlock, data) } pub fn NewWithUnstable(u: &UnstableAttr, typ: u64, wouldBlock: bool, data: T) -> Self { let internal = SimpleFileInodeInternal { fsType: typ, unstable: *u, wouldBlock: wouldBlock, data: data, }; return Self(QRwLock::new(internal)) } } impl <T: 'static + SimpleFileTrait> InodeOperations for SimpleFileInode <T> { fn as_any(&self) -> &Any { self } fn IopsType(&self) -> IopsType { return IopsType::SimpleFileInode; } fn InodeType(&self) -> InodeType { return InodeType::SpecialFile; } fn InodeFileType(&self) -> InodeFileType { return InodeFileType::SimpleFileInode; } fn WouldBlock(&self) -> bool { return self.read().wouldBlock; } fn Check(&self, task: &Task, inode: &Inode, reqPerms: &PermMask) -> Result<bool> { return ContextCanAccessFile(task, inode, reqPerms) } fn Getxattr(&self, _dir: &Inode, _name: &str) -> Result<String> { return Err(Error::SysError(SysErr::EOPNOTSUPP)) } fn Setxattr(&self, _dir: &mut Inode, _name: &str, _value: &str) -> Result<()> { return Err(Error::SysError(SysErr::EOPNOTSUPP)) } fn Listxattr(&self, _dir: &Inode) -> Result<Vec<String>> { return Err(Error::SysError(SysErr::EOPNOTSUPP)) } fn Allocate(&self, _task: &Task, _dir: &mut Inode, _offset: i64, _length: i64) -> Result<()> { return Err(Error::SysError(SysErr::EOPNOTSUPP)) } fn Lookup(&self, _task: &Task, _dir: &Inode, _name: &str) -> Result<Dirent> { return Err(Error::SysError(SysErr::ENOTDIR)) } fn Create(&self, _task: &Task, _dir: &mut Inode, _name: &str, _flags: &FileFlags, _perm: &FilePermissions) -> Result<File> { return Err(Error::SysError(SysErr::ENOTDIR)) } fn CreateDirectory(&self, _task: &Task, _dir: &mut Inode, _name: &str, _perm: &FilePermissions) -> Result<()> { return Err(Error::SysError(SysErr::ENOTDIR)) } fn CreateLink(&self, _task: &Task, _dir: &mut Inode, _oldname: &str, _newname: &str) -> Result<()> { return Err(Error::SysError(SysErr::ENOTDIR)) } fn CreateHardLink(&self, _task: &Task, _dir: &mut Inode, _target: &Inode, _name: &str) -> Result<()> { return Err(Error::SysError(SysErr::ENOTDIR)) } fn CreateFifo(&self, _task: &Task, _dir: &mut Inode, _name: &str, _perm: &FilePermissions) -> Result<()> { return Err(Error::SysError(SysErr::ENOTDIR)) } fn Remove(&self, _task: &Task, _dir: &mut Inode, _name: &str) -> Result<()> { return Err(Error::SysError(SysErr::ENOTDIR)) } fn RemoveDirectory(&self, _task: &Task, _dir: &mut Inode, _name: &str) -> Result<()> { return Err(Error::SysError(SysErr::ENOTDIR)) } fn Rename(&self, _task: &Task, _dir: &mut Inode, _oldParent: &Inode, _oldname: &str, _newParent: &Inode, _newname: &str, _replacement: bool) -> Result<()> { return Err(Error::SysError(SysErr::EINVAL)) } fn Bind(&self, _task: &Task, _dir: &Inode, _name: &str, _data: &BoundEndpoint, _perms: &FilePermissions) -> Result<Dirent> { return Err(Error::SysError(SysErr::ENOTDIR)) } fn BoundEndpoint(&self, _task: &Task, _inode: &Inode, _path: &str) -> Option<BoundEndpoint> { return None } fn GetFile(&self, task: &Task, dir: &Inode, dirent: &Dirent, flags: FileFlags) -> Result<File> { return self.read().data.GetFile(task, dir, dirent, flags) }
r::ENOSYS)) } return Ok(FsInfo { Type: self.read().fsType, ..Default::default() }) } fn Mappable(&self) -> Result<HostInodeOp> { return Err(Error::SysError(SysErr::ENODEV)) } } #[derive(Clone, Default, Debug)] pub struct InodeSimpleAttributesInternal { pub fsType: u64, pub unstable: UnstableAttr, } impl InodeSimpleAttributesInternal { pub fn New(task: &Task, owner: &FileOwner, perms: &FilePermissions, typ: u64) -> Self { let unstable = WithCurrentTime(task, &UnstableAttr { Owner: *owner, Perms: *perms, ..Default::default() }); let internal = InodeSimpleAttributesInternal { fsType: typ, unstable: unstable, }; return internal } } pub struct InodeSimpleAttributes(pub QRwLock<InodeSimpleAttributesInternal>); impl Default for InodeSimpleAttributes { fn default() -> Self { return Self(QRwLock::new(Default::default())) } } impl Deref for InodeSimpleAttributes { type Target = QRwLock<InodeSimpleAttributesInternal>; fn deref(&self) -> &QRwLock<InodeSimpleAttributesInternal> { &self.0 } } impl InodeSimpleAttributes { pub fn New(task: &Task, owner: &FileOwner, perms: &FilePermissions, typ: u64) -> Self { let unstable = WithCurrentTime(task, &UnstableAttr { Owner: *owner, Perms: *perms, ..Default::default() }); return Self::NewWithUnstable(&unstable, typ) } fn NewWithUnstable(u: &UnstableAttr, typ: u64) -> Self { let internal = InodeSimpleAttributesInternal { fsType: typ, unstable: *u, }; return Self(QRwLock::new(internal)) } fn UnstableAttr(&self, _task: &Task, _dir: &Inode) -> Result<UnstableAttr> { let u = self.read().unstable; return Ok(u) } fn SetPermissions(&self, task: &Task, _dir: &mut Inode, p: FilePermissions) -> bool { self.write().unstable.SetPermissions(task, &p); return true; } fn SetOwner(&self, task: &Task, _dir: &mut Inode, owner: &FileOwner) -> Result<()> { self.write().unstable.SetOwner(task, owner); return Ok(()) } fn SetTimestamps(&self, task: &Task, _dir: &mut Inode, ts: &InterTimeSpec) -> Result<()> { self.write().unstable.SetTimestamps(task, ts); return Ok(()) } fn AddLink(&self, _task: &Task) { self.write().unstable.Links += 1; } fn DropLink(&self, _task: &Task) { self.write().unstable.Links -= 1; } }
fn ReadLink(&self, _task: &Task,_dir: &Inode) -> Result<String> { return Err(Error::SysError(SysErr::ENOLINK)) } fn GetLink(&self, _task: &Task, _dir: &Inode) -> Result<Dirent> { return Err(Error::SysError(SysErr::ENOLINK)) } fn Truncate(&self, _task: &Task, _dir: &mut Inode, _size: i64) -> Result<()> { return Err(Error::SysError(SysErr::EINVAL)) } fn IsVirtual(&self) -> bool { return false } fn UnstableAttr(&self, _task: &Task, _dir: &Inode) -> Result<UnstableAttr> { let u = self.read().unstable; return Ok(u) } fn SetPermissions(&self, task: &Task, _dir: &mut Inode, p: FilePermissions) -> bool { self.write().unstable.SetPermissions(task, &p); return true; } fn SetOwner(&self, task: &Task, _dir: &mut Inode, owner: &FileOwner) -> Result<()> { self.write().unstable.SetOwner(task, owner); return Ok(()) } fn SetTimestamps(&self, task: &Task, _dir: &mut Inode, ts: &InterTimeSpec) -> Result<()> { self.write().unstable.SetTimestamps(task, ts); return Ok(()) } fn AddLink(&self, _task: &Task) { self.write().unstable.Links += 1; } fn DropLink(&self, _task: &Task) { self.write().unstable.Links -= 1; } fn Sync(&self) -> Result<()> { return Err(Error::SysError(SysErr::ENOSYS)); } fn StatFS(&self, _task: &Task) -> Result<FsInfo> { if self.read().fsType == 0 { return Err(Error::SysError(SysEr
random
[ { "content": "fn InodeIsDirAllocate_Allocate(_data: &InodeOpsData, _task: &Task, _dir: &mut Inode, _offset: i64, _length: i64) -> Result<()> {\n\n return Err(Error::SysError(SysErr::EISDIR))\n\n}\n\n\n", "file_path": "qlib/kernel/fs/fsutil/inode/iopsutil.rs", "rank": 0, "score": 637044.610642917 }, { "content": "fn InodeNotAllocatable_Allocate(_data: &InodeOpsData, _task: &Task, _dir: &mut Inode, _offset: i64, _length: i64) -> Result<()> {\n\n return Err(Error::SysError(SysErr::EOPNOTSUPP))\n\n}\n\n\n", "file_path": "qlib/kernel/fs/fsutil/inode/iopsutil.rs", "rank": 1, "score": 627421.208965692 }, { "content": "fn InodeNotDirectory_CreateHardLink(_data: &InodeOpsData, _task: &Task, _dir: &mut Inode, _target: &Inode, _name: &str) -> Result<()> {\n\n return Err(Error::SysError(SysErr::ENOTDIR))\n\n}\n\n\n", "file_path": "qlib/kernel/fs/fsutil/inode/iopsutil.rs", "rank": 2, "score": 626320.7664422577 }, { "content": "fn InodeNotDirectory_Create(_data: &InodeOpsData, _task: &Task, _dir: &mut Inode, _name: &str, _flags: &FileFlags, _perm: &FilePermissions) -> Result<File> {\n\n return Err(Error::SysError(SysErr::ENOTDIR))\n\n}\n\n\n", "file_path": "qlib/kernel/fs/fsutil/inode/iopsutil.rs", "rank": 3, "score": 624376.2773667173 }, { "content": "fn InodeNotDirectory_CreateFifo(_data: &InodeOpsData, _task: &Task, _dir: &mut Inode, _name: &str, _perm: &FilePermissions) -> Result<()> {\n\n return Err(Error::SysError(SysErr::ENOTDIR))\n\n}\n\n\n", "file_path": "qlib/kernel/fs/fsutil/inode/iopsutil.rs", "rank": 4, "score": 622295.3712152189 }, { "content": "fn InodeNotDirectory_CreateDirectory(_data: &InodeOpsData, _task: &Task, _dir: &mut Inode, _name: &str, _perm: &FilePermissions) -> Result<()> {\n\n return Err(Error::SysError(SysErr::ENOTDIR))\n\n}\n\n\n", "file_path": "qlib/kernel/fs/fsutil/inode/iopsutil.rs", "rank": 5, "score": 622295.3712152189 }, { "content": "fn InodeNoopAllocate_Allocate(_data: &InodeOpsData, _task: &Task, _dir: &mut Inode, _offset: i64, _length: i64) -> Result<()> {\n\n return Ok(())\n\n}\n\n\n", "file_path": "qlib/kernel/fs/fsutil/inode/iopsutil.rs", "rank": 6, "score": 622070.4701813268 }, { "content": "fn InodeNotDirectory_Lookup(_data: &InodeOpsData, _task: &Task, _dir: &Inode, _name: &str) -> Result<Dirent> {\n\n return Err(Error::SysError(SysErr::ENOTDIR))\n\n}\n\n\n", "file_path": "qlib/kernel/fs/fsutil/inode/iopsutil.rs", "rank": 7, "score": 602872.8286086537 }, { "content": "fn InodeNotDirectory_Remove(_data: &InodeOpsData, _task: &Task, _dir: &mut Inode, _name: &str) -> Result<()> {\n\n return Err(Error::SysError(SysErr::ENOTDIR))\n\n}\n\n\n", "file_path": "qlib/kernel/fs/fsutil/inode/iopsutil.rs", "rank": 8, "score": 601806.1832690191 }, { "content": "fn InodeNotDirectory_RemoveDirectory(_data: &InodeOpsData, _task: &Task, _dir: &mut Inode, _name: &str) -> Result<()> {\n\n return Err(Error::SysError(SysErr::ENOTDIR))\n\n}\n\n\n", "file_path": "qlib/kernel/fs/fsutil/inode/iopsutil.rs", "rank": 9, "score": 596098.6470654787 }, { "content": "fn InodeIsDirTruncate_Truncate(_data: &InodeOpsData, _task: &Task, _dir: &mut Inode, _size: i64) -> Result<()> {\n\n return Err(Error::SysError(SysErr::EISDIR))\n\n}\n\n\n", "file_path": "qlib/kernel/fs/fsutil/inode/iopsutil.rs", "rank": 10, "score": 578975.4183328843 }, { "content": "pub fn FileNotDir_IterateDir(_task: &Task, _data: &FileOptionsData, _d: &Dirent, _dirCtx: &mut DirCtx, _offset: i32) -> (i32, Result<i64>) {\n\n return (0, Err(Error::SysError(SysErr::ENOTDIR)))\n\n}\n\n\n", "file_path": "qlib/kernel/fs/fsutil/file/fileopsutil.rs", "rank": 11, "score": 574959.2578465673 }, { "content": "fn InodeNotTruncatable_Truncate(_data: &InodeOpsData, _task: &Task, _dir: &mut Inode, _size: i64) -> Result<()> {\n\n return Err(Error::SysError(SysErr::EINVAL))\n\n}\n\n\n", "file_path": "qlib/kernel/fs/fsutil/inode/iopsutil.rs", "rank": 12, "score": 569622.1594119639 }, { "content": "pub fn seccomp(_task: &mut Task, _mode: u64, _flags: u64, _addr: u64) -> Result<i64> {\n\n return Err(Error::SysError(SysErr::ENOSYS))\n\n}", "file_path": "qkernel/src/syscalls/sys_seccomp.rs", "rank": 13, "score": 565803.441886009 }, { "content": "fn InodeNotDirectory_CreateLink(_data: &InodeOpsData, _task: &Task, _dir: &mut Inode, _oldname: &str, _newname: &str) -> Result<()> {\n\n return Err(Error::SysError(SysErr::ENOTDIR))\n\n}\n\n\n", "file_path": "qlib/kernel/fs/fsutil/inode/iopsutil.rs", "rank": 14, "score": 564846.3131722956 }, { "content": "fn InodeNoopTruncate_Truncate(_data: &InodeOpsData, _task: &Task, _dir: &mut Inode, _size: i64) -> Result<()> {\n\n return Ok(())\n\n}\n\n\n", "file_path": "qlib/kernel/fs/fsutil/inode/iopsutil.rs", "rank": 15, "score": 563917.2903747056 }, { "content": "fn InodeNotOpenable_GetFile(_data: &InodeOpsData, _task: &Task, _dir: &Inode, _dirent: &Dirent, _flags: FileFlags) -> Result<File> {\n\n return Err(Error::SysError(SysErr::EIO))\n\n}\n\n\n", "file_path": "qlib/kernel/fs/fsutil/inode/iopsutil.rs", "rank": 16, "score": 563637.525652478 }, { "content": "fn InodeNotDirectory_Rename(_data: &InodeOpsData, _task: &Task, _dir: &mut Inode, _oldParent: &Inode, _oldname: &str, _newParent: &Inode, _newname: &str, _replacement: bool) -> Result<()> {\n\n return Err(Error::SysError(SysErr::EINVAL))\n\n}\n\n\n", "file_path": "qlib/kernel/fs/fsutil/inode/iopsutil.rs", "rank": 17, "score": 553006.9801853667 }, { "content": "fn InodeNotRenameable_Rename(_data: &InodeOpsData, _task: &Task, _dir: &mut Inode, _oldParent: &Inode, _oldname: &str, _newParent: &Inode, _newname: &str, _replacement: bool) -> Result<()> {\n\n return Err(Error::SysError(SysErr::EINVAL))\n\n}\n\n\n", "file_path": "qlib/kernel/fs/fsutil/inode/iopsutil.rs", "rank": 18, "score": 553006.9801853667 }, { "content": "fn InodeDefault_SetOwner(_data: &InodeOpsData, _task: &Task, _dir: &mut Inode, _owner: &FileOwner) -> Result<()> {\n\n return Err(Error::SysError(SysErr::ENOSYS))\n\n}\n\n\n", "file_path": "qlib/kernel/fs/fsutil/inode/iopsutil.rs", "rank": 19, "score": 552072.6981630637 }, { "content": "fn ReadDescriptors(task: &Task, c: &mut DirCtx, offset: i64, typ: InodeType) -> Result<i64> {\n\n let fds = task.fdTbl.lock().GetFDs();\n\n\n\n let mut fdInts = &fds[..];\n\n let idx = match fds.binary_search(&(offset as i32)) {\n\n Err(idx) => idx,\n\n Ok(idx) => idx,\n\n };\n\n\n\n if idx == fdInts.len() {\n\n return Ok(offset)\n\n }\n\n\n\n fdInts = &fdInts[idx..];\n\n\n\n let mut ret = offset as i32;\n\n for i in 0..fdInts.len() {\n\n let fd = fdInts[i];\n\n let name = format!(\"{}\", fd);\n\n match c.DirEmit(task, &name, &DentAttr::GenericDentAttr(typ, &PROC_DEVICE)) {\n", "file_path": "qlib/kernel/fs/procfs/task/fds.rs", "rank": 20, "score": 545528.1088313868 }, { "content": "pub fn DirentReadDir(task: &Task, d: &Dirent, it: &FileOperations, root: &Dirent, dirCtx: &mut DirCtx, offset: i64) -> Result<i64> {\n\n let (offset, err) = direntReadDir(task, d, it, root, dirCtx, offset);\n\n\n\n if dirCtx.Serializer.Written() > 0 {\n\n return Ok(offset)\n\n }\n\n\n\n return err\n\n}\n\n\n", "file_path": "qlib/kernel/fs/dirent.rs", "rank": 21, "score": 539969.9112662951 }, { "content": "pub fn FileNoSplice_ReadAt(_data: &FileOptionsData, _task: &Task, _f: &File, _dsts: &mut [IoVec], _offset: i64, _blocking: bool) -> Result<i64> {\n\n return Err(Error::SysError(SysErr::ENOSYS))\n\n}\n\n\n", "file_path": "qlib/kernel/fs/fsutil/file/fileopsutil.rs", "rank": 22, "score": 539378.5078791708 }, { "content": "fn InodeDefault_UnstableAttr(_data: &InodeOpsData, _task: &Task, _dir: &Inode) -> Result<UnstableAttr> {\n\n return Err(Error::SysError(SysErr::ENOSYS))\n\n}\n\n\n", "file_path": "qlib/kernel/fs/fsutil/inode/iopsutil.rs", "rank": 23, "score": 538347.7389550275 }, { "content": "pub fn FileNotDir_Readdir(_data: &FileOptionsData, _task: &Task, _f: &File, _offset: i64, _serializer: &mut DentrySerializer) -> Result<i64> {\n\n return Err(Error::SysError(SysErr::ENOTDIR))\n\n}\n\n\n", "file_path": "qlib/kernel/fs/fsutil/file/fileopsutil.rs", "rank": 24, "score": 537969.6307578778 }, { "content": "fn InodeNotMappable_Mmap(_data: &InodeOpsData, _task: &Task, _len: u64, _hugePage: bool, _offset: u64, _share: bool, _prot: u64) -> Result<u64> {\n\n return Err(Error::SysError(SysErr::EACCES))\n\n}\n\n\n", "file_path": "qlib/kernel/fs/fsutil/inode/iopsutil.rs", "rank": 25, "score": 536365.3396192943 }, { "content": "pub fn FileNoopRead_ReadAt(_data: &FileOptionsData, _task: &Task, _f: &File, _dsts: &mut [IoVec], _offset: i64, _blocking: bool) -> Result<i64> {\n\n return Ok(0)\n\n}\n\n\n", "file_path": "qlib/kernel/fs/fsutil/file/fileopsutil.rs", "rank": 26, "score": 534681.3968153493 }, { "content": "pub fn overlayBind(task: &Task, o: &Arc<RwLock<OverlayEntry>>, name: &str, data: &BoundEndpoint, perm: &FilePermissions) -> Result<Dirent> {\n\n let overlay = o.write();\n\n\n\n // We do not support doing anything exciting with sockets unless there\n\n // is already a directory in the upper filesystem.\n\n if overlay.upper.is_none() {\n\n return Err(Error::SysError(SysErr::EOPNOTSUPP))\n\n }\n\n\n\n let upperInode = overlay.upper.as_ref().unwrap().clone();\n\n let iops = upperInode.lock().InodeOp.clone();\n\n let d = iops.Bind(task, &upperInode, name, data, perm)?;\n\n\n\n let inode = d.Inode();\n\n\n\n let msrc = inode.lock().MountSource.clone();\n\n // Create a new overlay entry and dirent for the socket.\n\n let entry = OverlayEntry::New(task, Some(inode), None, false)?;\n\n\n\n let oInode = NewOverlayInode(task, entry, &msrc);\n\n return Ok(Dirent::New(&oInode, name))\n\n}\n\n\n", "file_path": "qlib/kernel/fs/inode_overlay.rs", "rank": 27, "score": 534111.7866544452 }, { "content": "pub fn Pipe2(task: &mut Task, addr: u64, flags: i32) -> Result<i64> {\n\n if flags & !(Flags::O_NONBLOCK | Flags::O_CLOEXEC) != 0 {\n\n return Err(Error::SysError(SysErr::EINVAL))\n\n }\n\n\n\n let (r, w) = NewConnectedPipe(task, DEFAULT_PIPE_SIZE, MemoryDef::PAGE_SIZE as usize);\n\n\n\n r.SetFlags(task, FileFlags::FromFlags(flags as u32).SettableFileFlags());\n\n r.flags.lock().0.NonSeekable = true;\n\n w.SetFlags(task, FileFlags::FromFlags(flags as u32).SettableFileFlags());\n\n w.flags.lock().0.NonSeekable = true;\n\n\n\n //let fds : &mut [i32; 2] = task.GetTypeMut(addr)?;\n\n\n\n let mut fds : [i32; 2] = [0, 0];\n\n let rfd = task.NewFDFrom(0, &r, &FDFlags {\n\n CloseOnExec: flags & Flags::O_CLOEXEC != 0,\n\n })?;\n\n\n\n let wfd = task.NewFDFrom(0, &w, &FDFlags {\n", "file_path": "qkernel/src/syscalls/sys_pipe.rs", "rank": 28, "score": 533986.61682325 }, { "content": "fn InodeNotSymlink_GetLink(_data: &InodeOpsData, _task: &Task, _dir: &Inode) -> Result<Dirent> {\n\n return Err(Error::SysError(SysErr::ENOLINK))\n\n}\n\n\n", "file_path": "qlib/kernel/fs/fsutil/inode/iopsutil.rs", "rank": 29, "score": 528243.3958684047 }, { "content": "fn DirFileOperations_ReadAt(_data: &FileOptionsData, _task: &Task, _f: &File, _dsts: &mut [IoVec], _offset: i64, _blocking: bool) -> Result<i64> {\n\n return Err(Error::SysError(SysErr::ENOSYS))\n\n}\n\n\n", "file_path": "qlib/kernel/fs/fsutil/file/fileopsutil.rs", "rank": 30, "score": 524717.8967898125 }, { "content": "fn NewSymlinkFn(task: &Task, dir: &Inode, target: &str) -> Result<Inode> {\n\n let msrc = dir.lock().MountSource.clone();\n\n return Ok(NewTmpfsSymlink(task, target, &task.FileOwner(), &msrc))\n\n}\n\n\n", "file_path": "qlib/kernel/fs/tmpfs/tmpfs_dir.rs", "rank": 31, "score": 524599.0279575072 }, { "content": "// Sync implements linux system call sync(2).\n\npub fn SysSync(_task: &mut Task, _args: &SyscallArguments) -> Result<i64> {\n\n HostSpace::SysSync();\n\n return Ok(0)\n\n}\n\n\n", "file_path": "qkernel/src/syscalls/sys_sync.rs", "rank": 32, "score": 515552.19554238825 }, { "content": "fn InodeNoExtendedAttributes_Setxattr(_data: &InodeOpsData, _dir: &mut Inode, _name: &str, _value: &str) -> Result<()> {\n\n return Err(Error::SysError(SysErr::EOPNOTSUPP))\n\n}\n\n\n", "file_path": "qlib/kernel/fs/fsutil/inode/iopsutil.rs", "rank": 33, "score": 515130.0773395198 }, { "content": "pub fn FileNoFsync_Fsync(_data: &FileOptionsData, _task: &Task, _f: &File, _start: i64, _end: i64, _syncType: SyncType) -> Result<()> {\n\n return Err(Error::SysError(SysErr::EINVAL))\n\n}\n\n\n", "file_path": "qlib/kernel/fs/fsutil/file/fileopsutil.rs", "rank": 34, "score": 509286.1855501897 }, { "content": "pub fn FileNoopFsync_Fsync(_data: &FileOptionsData, _task: &Task, _f: &File, _start: i64, _end: i64, _syncType: SyncType) -> Result<()> {\n\n return Ok(())\n\n}\n\n\n", "file_path": "qlib/kernel/fs/fsutil/file/fileopsutil.rs", "rank": 35, "score": 504301.1773314986 }, { "content": "fn InodeNoop_SetPermissions(_data: &InodeOpsData, _task: &Task, _dir: &mut Inode, _f: FilePermissions) -> bool {\n\n return true\n\n}\n\n\n", "file_path": "qlib/kernel/fs/fsutil/inode/iopsutil.rs", "rank": 36, "score": 502460.26836426 }, { "content": "fn direntReadDir(task: &Task, d: &Dirent, it: &FileOperations, root: &Dirent, dirCtx: &mut DirCtx, offset: i64) -> (i64, Result<i64>) {\n\n let mut offset = offset;\n\n\n\n let inode = d.Inode();\n\n if !inode.StableAttr().IsDir() {\n\n return (0, Err(Error::SysError(SysErr::ENOTDIR)))\n\n }\n\n\n\n if offset == FILE_MAX_OFFSET {\n\n return (offset, Ok(0))\n\n }\n\n\n\n if (d.0).0.lock().frozen {\n\n return d.readdirFrozen(task, root, offset, dirCtx);\n\n }\n\n\n\n let (dot, dotdot) = d.GetDotAttrs(root);\n\n\n\n if offset == 0 {\n\n match dirCtx.DirEmit(task, &\".\".to_string(), &dot) {\n", "file_path": "qlib/kernel/fs/dirent.rs", "rank": 37, "score": 501861.0081265791 }, { "content": "fn FileNoRead_ReadAt(_data: &FileOptionsData, _task: &Task, _f: &File, _dsts: &mut [IoVec], _offset: i64, _blocking: bool) -> Result<i64> {\n\n return Err(Error::SysError(SysErr::EINVAL))\n\n}\n\n\n", "file_path": "qlib/kernel/fs/fsutil/file/fileopsutil.rs", "rank": 38, "score": 498672.5494930502 }, { "content": "fn NoSock_Accept(_data: &FileOptionsData, _task: &Task, _addr: &mut [u8], _addrlen: &mut u32, _flags: i32, _blocking: bool) -> Result<i64> {\n\n return Err(Error::SysError(SysErr::ENOTSOCK))\n\n}\n\n\n", "file_path": "qlib/kernel/fs/fsutil/file/fileopsutil.rs", "rank": 39, "score": 497109.6699164527 }, { "content": "pub fn NansleepFor(task: &mut Task, timer: Timer, dur: i64, rem: u64) -> Result<i64> {\n\n let (remaining, res) = task.blocker.BlockWithTimeout(timer, false, Some(dur));\n\n\n\n if rem != 0 && remaining != 0 {\n\n let timeleft = Timespec::FromNs(remaining);\n\n //*task.GetTypeMut(rem)? = timeleft;\n\n task.CopyOutObj(&timeleft, rem)?;\n\n }\n\n\n\n match res {\n\n Err(Error::ErrInterrupted) => {\n\n let b = Box::new(NanosleepRestartBlock {\n\n dur: remaining,\n\n rem: rem,\n\n });\n\n task.SetSyscallRestartBlock(b);\n\n return Err(Error::SysError(SysErr::ERESTART_RESTARTBLOCK));\n\n }\n\n Err(Error::SysError(SysErr::ETIMEDOUT)) => {\n\n return Ok(0)\n", "file_path": "qkernel/src/syscalls/sys_time.rs", "rank": 40, "score": 496529.3593644461 }, { "content": "pub fn FileNoSplice_WriteAt(_data: &FileOptionsData, _task: &Task, _f: &File, _srcs: &[IoVec], _offset: i64, _blocking: bool) -> Result<i64> {\n\n return Err(Error::SysError(SysErr::ENOSYS))\n\n}\n\n\n", "file_path": "qlib/kernel/fs/fsutil/file/fileopsutil.rs", "rank": 41, "score": 495478.5742334106 }, { "content": "pub fn FileNoWrite_WriteAt(_data: &FileOptionsData, _task: &Task, _f: &File, _srcs: &[IoVec], _offset: i64, _blocking: bool) -> Result<i64> {\n\n //return Ok(srcs.NumBytes() as i64)\n\n panic!(\"FileNoWrite_WriteAt: need implement\");\n\n}\n\n\n", "file_path": "qlib/kernel/fs/fsutil/file/fileopsutil.rs", "rank": 42, "score": 495478.57423341053 }, { "content": "pub fn ContextCanAccessFile(task: &Task, inode: &Inode, reqPerms: &PermMask) -> Result<bool> {\n\n let creds = task.creds.clone();\n\n let uattr = inode.UnstableAttr(task)?;\n\n\n\n //info!(\"ContextCanAccessFile 1, perms is {:?}\", &uattr.Perms);\n\n let mut p = &uattr.Perms.Other;\n\n {\n\n let creds = creds.lock();\n\n if uattr.Owner.UID == creds.EffectiveKUID {\n\n p = &uattr.Perms.User\n\n } else if creds.InGroup(uattr.Owner.GID) {\n\n p = &uattr.Perms.Group\n\n }\n\n }\n\n\n\n //info!(\"ContextCanAccessFile 2\");\n\n if inode.StableAttr().IsFile() && reqPerms.execute && inode.lock().MountSource.lock().Flags.NoExec {\n\n return Ok(false);\n\n }\n\n\n", "file_path": "qlib/kernel/fs/inode.rs", "rank": 43, "score": 494195.6565602481 }, { "content": "fn InodeGenericChecker_Check(_data: &InodeOpsData, task: &Task, inode: &Inode, reqPerms: &PermMask) -> Result<bool> {\n\n return ContextCanAccessFile(task, inode, reqPerms)\n\n}\n\n\n", "file_path": "qlib/kernel/fs/fsutil/inode/iopsutil.rs", "rank": 44, "score": 491487.6409179339 }, { "content": "fn DirFileOperations_Fsync(_data: &FileOptionsData, _task: &Task, _f: &File, _start: i64, _end: i64, _syncType: SyncType) -> Result<()> {\n\n return Ok(())\n\n}\n\n\n", "file_path": "qlib/kernel/fs/fsutil/file/fileopsutil.rs", "rank": 45, "score": 491426.6125287741 }, { "content": "pub fn ReadAll(task: &mut Task, file: &File, data: &mut [u8], offset: u64) -> Result<usize> {\n\n let mut data = data;\n\n let mut offset = offset;\n\n let mut cnt = 0;\n\n\n\n while data.len() > 0 {\n\n let mut iovecs : [IoVec; 1] = [IoVec {\n\n start: &data[0] as * const _ as u64,\n\n len: data.len(),\n\n }];\n\n\n\n let l = file.Preadv(task, &mut iovecs, offset as i64)? as usize;\n\n cnt += l;\n\n\n\n if l == data.len() || l == 0 {\n\n return Ok(cnt);\n\n }\n\n\n\n data = &mut data[l..];\n\n offset += l as u64;\n\n }\n\n\n\n return Ok(cnt)\n\n}\n\n\n", "file_path": "qlib/kernel/loader/elf.rs", "rank": 46, "score": 491366.316664133 }, { "content": "pub fn FileNoopWrite_WriteAt(_data: &FileOptionsData, _task: &Task, _f: &File, _srcs: &[IoVec], _offset: i64, _blocking: bool) -> Result<i64> {\n\n //return Ok(srcs.NumBytes() as i64)\n\n panic!(\"FileNoopWrite_WriteAt: need implement\");\n\n}\n\n\n", "file_path": "qlib/kernel/fs/fsutil/file/fileopsutil.rs", "rank": 47, "score": 491205.7818003734 }, { "content": "fn InodeDefault_SetTimestamps(_data: &InodeOpsData, _task: &Task, _dir: &mut Inode, _ts: &InterTimeSpec) -> Result<()> {\n\n return Err(Error::SysError(SysErr::ENOSYS))\n\n}\n\n\n", "file_path": "qlib/kernel/fs/fsutil/inode/iopsutil.rs", "rank": 48, "score": 490814.2785479835 }, { "content": "pub fn overlayLookup(task: &Task, parent: &Arc<RwLock<OverlayEntry>>, inode: &Inode, name: &str) -> Result<(Dirent, bool)> {\n\n let parent = parent.read();\n\n\n\n if parent.upper.is_none() && parent.lower.is_none() {\n\n panic!(\"invalid overlayEntry, needs at least one Inode\")\n\n }\n\n\n\n let mut upperInode: Option<Inode> = None;\n\n let mut lowerInode: Option<Inode> = None;\n\n\n\n if parent.upper.is_some() {\n\n let upper = parent.upper.as_ref().unwrap().clone();\n\n match upper.Lookup(task, name) {\n\n Ok(child) => {\n\n upperInode = Some(child.Inode());\n\n }\n\n Err(Error::SysError(SysErr::ENOENT)) => {\n\n upperInode = None;\n\n }\n\n Err(e) => return Err(e)\n", "file_path": "qlib/kernel/fs/inode_overlay.rs", "rank": 49, "score": 489047.20399143826 }, { "content": "pub fn overlayCreateHardLink(task: &Task, o: &Arc<RwLock<OverlayEntry>>, parent: &Dirent, target: &Dirent, name: &str) -> Result<()> {\n\n CopyUpLockedForRename(task, parent)?;\n\n CopyUpLockedForRename(task, target)?;\n\n\n\n let mut inode = o.read().upper.as_ref().unwrap().clone();\n\n let iops = inode.lock().InodeOp.clone();\n\n\n\n let tmpInode = target.Inode();\n\n let targetInode = tmpInode.lock().Overlay.as_ref().unwrap().read().upper.as_ref().unwrap().clone();\n\n let res = iops.CreateHardLink(task, &mut inode, &targetInode, name);\n\n return res;\n\n}\n\n\n", "file_path": "qlib/kernel/fs/inode_overlay.rs", "rank": 50, "score": 487886.9485048884 }, { "content": "// Syncfs implements linux system call syncfs(2).\n\npub fn SysSyncFs(task: &mut Task, args: &SyscallArguments) -> Result<i64> {\n\n let fd = args.arg0 as i32;\n\n\n\n let file = task.GetFile(fd)?;\n\n let inode = file.Dirent.Inode();\n\n let iops = inode.lock().InodeOp.clone();\n\n match iops.as_any().downcast_ref::<HostInodeOp>() {\n\n None => {\n\n return Ok(0)\n\n },\n\n Some(h) => {\n\n h.SyncFs()?;\n\n return Ok(0)\n\n }\n\n }\n\n}\n\n\n", "file_path": "qkernel/src/syscalls/sys_sync.rs", "rank": 51, "score": 487405.1911135049 }, { "content": "fn InodeDenyWriteChecker_Check(_data: &InodeOpsData, task: &Task, inode: &Inode, reqPerms: &PermMask) -> Result<bool> {\n\n if reqPerms.write {\n\n return Ok(false)\n\n }\n\n\n\n return ContextCanAccessFile(task, inode, reqPerms)\n\n}\n\n\n", "file_path": "qlib/kernel/fs/fsutil/inode/iopsutil.rs", "rank": 52, "score": 486999.9862704993 }, { "content": "// SyncFileRange implements linux syscall sync_file_rage(2)\n\npub fn SysSyncFileRange(task: &mut Task, args: &SyscallArguments) -> Result<i64> {\n\n let fd = args.arg0 as i32;\n\n let offset = args.arg1 as i64;\n\n let nbytes = args.arg2 as i64;\n\n let uflags = args.arg3 as u32;\n\n\n\n let file = task.GetFile(fd)?;\n\n let inode = file.Dirent.Inode();\n\n let iops = inode.lock().InodeOp.clone();\n\n match iops.as_any().downcast_ref::<HostInodeOp>() {\n\n None => {\n\n return Ok(0)\n\n },\n\n Some(h) => {\n\n h.SyncFileRange(offset, nbytes, uflags)?;\n\n return Ok(0)\n\n }\n\n }\n\n}\n\n\n", "file_path": "qkernel/src/syscalls/sys_sync.rs", "rank": 53, "score": 481438.789600571 }, { "content": "pub fn LoadVDSO(task: &mut Task) -> Result<u64> {\n\n let vAddr = task.mm.FindAvailableSeg(task, 0, 3 * MemoryDef::PAGE_SIZE)?;\n\n\n\n let vdsoParamPageAddr = GetVDSOParamPageAddr();\n\n let paramVAddr = MapVDSOParamPage(task, vAddr, vdsoParamPageAddr)?;\n\n assert!(paramVAddr == vAddr, \"LoadVDSO paramVAddr doesn't match\");\n\n let vdsoVAddr = MapVDSOPage(task, paramVAddr + MemoryDef::PAGE_SIZE, vdsoParamPageAddr + MemoryDef::PAGE_SIZE)?;\n\n\n\n\n\n //info!(\"vdsoParamPageAddr is {:x}, phyaddr is {:x}\", vdsoParamPageAddr, task.VirtualToPhy(paramVAddr)?);\n\n //info!(\"paramVAddr is {:x}, phyaddr is {:x}\", paramVAddr, task.VirtualToPhy(paramVAddr)?);\n\n //info!(\"vdsoVAddr is {:x}, phyaddr is {:x}\", vdsoVAddr, task.VirtualToPhy(vdsoVAddr)?);\n\n //info!(\"paramVAddr is {:x}, vdsoVAddr is {:x}\", paramVAddr, vdsoVAddr);\n\n\n\n return Ok(vdsoVAddr)\n\n}\n\n\n", "file_path": "qlib/kernel/loader/loader.rs", "rank": 54, "score": 480844.0503432038 }, { "content": "fn DirFileOperations_WriteAt(_data: &FileOptionsData, _task: &Task, _f: &File, _srcs: &[IoVec], _offset: i64, _blocking: bool) -> Result<i64> {\n\n return Err(Error::SysError(SysErr::ENOSYS))\n\n}\n\n\n", "file_path": "qlib/kernel/fs/fsutil/file/fileopsutil.rs", "rank": 55, "score": 479744.93390100205 }, { "content": "// Fdatasync implements linux syscall fdatasync(2).\n\n//\n\n// At the moment, it just calls Fsync, which is a big hammer, but correct.\n\npub fn SysDatasync(task: &mut Task, args: &SyscallArguments) -> Result<i64> {\n\n let fd = args.arg0 as i32;\n\n\n\n let file = task.GetFile(fd)?;\n\n\n\n file.Fsync(task, 0, FILE_MAX_OFFSET, SyncType::SyncData)?;\n\n return Ok(0)\n\n}", "file_path": "qkernel/src/syscalls/sys_sync.rs", "rank": 56, "score": 478500.67117144313 }, { "content": "// Fsync implements linux syscall fsync(2).\n\npub fn SysFsync(task: &mut Task, args: &SyscallArguments) -> Result<i64> {\n\n let fd = args.arg0 as i32;\n\n\n\n let file = task.GetFile(fd)?;\n\n\n\n file.Fsync(task, 0, FILE_MAX_OFFSET, SyncType::SyncAll)?;\n\n return Ok(0)\n\n}\n\n\n", "file_path": "qkernel/src/syscalls/sys_sync.rs", "rank": 57, "score": 478500.67117144313 }, { "content": "pub fn SysSendTo(task: &mut Task, args: &SyscallArguments) -> Result<i64> {\n\n let fd = args.arg0 as i32;\n\n let bufPtr = args.arg1 as u64;\n\n let buflen = args.arg2 as i64;\n\n let mut flags = args.arg3 as i32;\n\n let namePtr = args.arg4 as u64;\n\n let nameLen = args.arg5 as u32;\n\n\n\n let file = task.GetFile(fd)?;\n\n\n\n let sock = file.FileOp.clone();\n\n\n\n if buflen < 0 {\n\n return Err(Error::SysError(-SysErr::EINVAL))\n\n }\n\n\n\n task.CheckPermission(bufPtr, buflen as u64, false, false)?;\n\n let iov = IoVec::NewFromAddr(bufPtr, buflen as usize);\n\n let iovs: [IoVec; 1] = [iov];\n\n\n", "file_path": "qkernel/src/syscalls/sys_socket.rs", "rank": 58, "score": 478499.4111749493 }, { "content": "fn stat(task: &Task, d: &Dirent, dirPath: bool, statAddr: u64) -> Result<()> {\n\n let inode = d.Inode();\n\n\n\n if dirPath && !inode.StableAttr().IsDir() {\n\n return Err(Error::SysError(SysErr::ENOTDIR))\n\n }\n\n\n\n let uattr = inode.UnstableAttr(task)?;\n\n let sattr = inode.StableAttr();\n\n\n\n copyOutStat(task, statAddr, &sattr, &uattr)?;\n\n return Ok(())\n\n}\n\n\n", "file_path": "qkernel/src/syscalls/sys_stat.rs", "rank": 59, "score": 477999.5838301313 }, { "content": "pub fn OpenPath(task: &mut Task, filename: &str, maxTraversals: u32) -> Result<(File, Dirent)> {\n\n let fscontex = task.fsContext.clone();\n\n let cwd = fscontex.lock().cwd.clone();\n\n let root = fscontex.lock().root.clone();\n\n let mut remainingTraversals = maxTraversals;\n\n\n\n let d = task.mountNS.FindDirent(task, &root, Some(cwd), filename, &mut remainingTraversals, true)?;\n\n\n\n let perms = PermMask {\n\n read: true,\n\n execute: true,\n\n ..Default::default()\n\n };\n\n\n\n let inode = d.Inode();\n\n inode.CheckPermission(task, &perms)?;\n\n\n\n let len = filename.len();\n\n // If they claim it's a directory, then make sure.\n\n //\n", "file_path": "qlib/kernel/loader/loader.rs", "rank": 60, "score": 477393.330118066 }, { "content": "pub fn TmpfsRename(task: &Task, oldParent: &Inode, oldname: &str, newParent: &Inode, newname: &str, _replacement: bool) -> Result<()> {\n\n let oldInode = oldParent.lock().InodeOp.clone();\n\n let op = match oldInode.as_any().downcast_ref::<TmpfsDir>() {\n\n None => return Err(Error::SysError(SysErr::EXDEV)),\n\n Some(op) => op.clone(),\n\n };\n\n\n\n let newInode = newParent.lock().InodeOp.clone();\n\n let np = match newInode.as_any().downcast_ref::<TmpfsDir>() {\n\n None => return Err(Error::SysError(SysErr::EXDEV)),\n\n Some(op) => op.clone(),\n\n };\n\n\n\n Rename(task, Arc::new(op.0.clone()), oldname, Arc::new(np.0.clone()), newname, _replacement)\n\n}\n\n\n", "file_path": "qlib/kernel/fs/tmpfs/tmpfs_dir.rs", "rank": 61, "score": 475150.97384023655 }, { "content": "pub fn OverlayCreate(task: &Task, o: &Arc<RwLock<OverlayEntry>>, parent: &Dirent, name: &str, flags: &FileFlags, perm: &FilePermissions) -> Result<File> {\n\n CopyUpLockedForRename(task, parent)?;\n\n\n\n let mut upper = o.read().upper.as_ref().unwrap().clone();\n\n let upperInodeOp = upper.lock().InodeOp.clone();\n\n let upperFile = upperInodeOp.Create(task, &mut upper, name, flags, perm)?;\n\n\n\n let upperFileInode = upperFile.Dirent.Inode();\n\n let entry = match OverlayEntry::New(task, Some(upperFileInode.clone()), None, false) {\n\n Ok(e) => e,\n\n Err(e) => {\n\n cleanupUpper(task, &mut upper, name);\n\n return Err(e);\n\n }\n\n };\n\n\n\n //let mut upperDirent = Dirent::NewTransient(&upperFileInode);\n\n (*(upperFile.Dirent.0).0.lock()).Inode = upperFileInode;\n\n (*(upperFile.Dirent.0).0.lock()).Parent = None;\n\n\n", "file_path": "qlib/kernel/fs/inode_overlay.rs", "rank": 62, "score": 474915.5045322571 }, { "content": "pub fn SysSendMsg(task: &mut Task, args: &SyscallArguments) -> Result<i64> {\n\n let fd = args.arg0 as i32;\n\n let msgPtr = args.arg1 as u64;\n\n let mut flags = args.arg2 as i32;\n\n\n\n let file = task.GetFile(fd)?;\n\n\n\n let sock = file.FileOp.clone();\n\n\n\n if flags & !(MsgType::MSG_DONTWAIT | MsgType::MSG_EOR | MsgType::MSG_MORE | MsgType::MSG_NOSIGNAL) != 0 {\n\n return Err(Error::SysError(SysErr::EINVAL))\n\n }\n\n\n\n if !file.Blocking() {\n\n flags |= MsgType::MSG_DONTWAIT;\n\n }\n\n\n\n let mut deadline = None;\n\n let dl = sock.SendTimeout();\n\n if dl > 0 {\n\n let now = MonotonicNow();\n\n deadline = Some(Time(now + dl));\n\n } else if dl < 0 {\n\n flags |= MsgType::MSG_DONTWAIT\n\n }\n\n\n\n let res = sendSingleMsg(task, &sock, msgPtr, flags, deadline)?;\n\n return Ok(res)\n\n}\n\n\n", "file_path": "qkernel/src/syscalls/sys_socket.rs", "rank": 63, "score": 472242.6798053325 }, { "content": "// Load loads file with filename into memory.\n\n//return (entry: u64, usersp: u64, kernelsp: u64)\n\npub fn Load(task: &mut Task, filename: &str, argv: &mut Vec<String>, envv: &[String], extraAuxv: &[AuxEntry]) -> Result<(u64, u64, u64)> {\n\n let vdsoAddr = LoadVDSO(task)?;\n\n\n\n let (loaded, executable, tmpArgv) = LoadExecutable(task, filename, argv)?;\n\n let argv = tmpArgv;\n\n\n\n let e = Addr(loaded.end).RoundUp()?.0;\n\n\n\n task.mm.BrkSetup(e);\n\n task.mm.SetExecutable(&executable);\n\n\n\n let mut name = Base(&filename);\n\n if name.len() > TASK_COMM_LEN - 1 {\n\n name = &name[0..TASK_COMM_LEN-1];\n\n }\n\n\n\n task.thread.as_ref().unwrap().lock().name = name.to_string();\n\n\n\n let stackRange = CreateStack(task)?;\n\n\n\n let mut stack = Stack::New(stackRange.End());\n\n\n\n let usersp = SetupUserStack(task, &mut stack, &loaded, filename, &argv, envv, extraAuxv, vdsoAddr)?;\n\n let kernelsp = Task::TaskId().Addr() + MemoryDef::DEFAULT_STACK_SIZE - 0x10;\n\n let entry = loaded.entry;\n\n\n\n return Ok((entry, usersp, kernelsp));\n\n}\n\n\n", "file_path": "qlib/kernel/loader/loader.rs", "rank": 64, "score": 471331.4545088936 }, { "content": "fn getDents(task: &Task, fd: i32, addr: u64, size: i32, f: fn(&Task, &Dirent, &mut IOWriter) -> Result<i32>) -> Result<i64> {\n\n let dir = task.GetFile(fd)?;\n\n\n\n task.CheckPermission(addr, size as u64, true, false)?;\n\n\n\n let mut writer : MemBuf = MemBuf::New(size as usize);\n\n\n\n let len = size; // writer.Len() as i32;\n\n let mut ds = HostDirentSerializer::New(f, &mut writer, WIDTH, len);\n\n let err = dir.ReadDir(task, &mut ds);\n\n match err {\n\n Ok(()) => {\n\n let buf = &writer.data;\n\n task.CopyOutSlice(buf, addr, size as usize)?;\n\n return Ok(buf.len() as i64)\n\n },\n\n Err(Error::EOF) => return Ok(0),\n\n Err(e) => return Err(e)\n\n }\n\n}\n\n\n", "file_path": "qkernel/src/syscalls/sys_getdents.rs", "rank": 65, "score": 471184.99939511117 }, { "content": "pub fn SysNoSys(_task: &mut Task, _args: &SyscallArguments) -> Result<i64> {\n\n return Err(Error::SysError(SysErr::ENOSYS));\n\n}", "file_path": "qkernel/src/syscalls/syscalls.rs", "rank": 66, "score": 467539.8112492937 }, { "content": "pub fn SysObsolete(_task: &mut Task, _args: &SyscallArguments) -> Result<i64> {\n\n return Err(Error::SysError(SysErr::ENOSYS));\n\n //return Err(Error::SysError(SysErr::ENOTSUP));\n\n}\n\n\n", "file_path": "qkernel/src/syscalls/syscalls.rs", "rank": 67, "score": 467539.81124929374 }, { "content": "pub fn NotImplementSyscall(_task: &mut Task, _args: &SyscallArguments) -> Result<i64> {\n\n return Err(Error::SysCallNotImplement)\n\n}\n\n\n", "file_path": "qkernel/src/syscalls/syscalls.rs", "rank": 68, "score": 467539.81124929374 }, { "content": "pub fn SysNoSupport(_task: &mut Task, _args: &SyscallArguments) -> Result<i64> {\n\n return Err(Error::SysError(SysErr::ENODATA));\n\n //return Err(Error::SysError(SysErr::ENOTSUP));\n\n}\n\n\n", "file_path": "qkernel/src/syscalls/syscalls.rs", "rank": 69, "score": 467539.8112492937 }, { "content": "pub fn SysSendMMsg(task: &mut Task, args: &SyscallArguments) -> Result<i64> {\n\n let fd = args.arg0 as i32;\n\n let msgPtr = args.arg1 as u64;\n\n let vlen = args.arg2 as u32;\n\n let mut flags = args.arg3 as i32;\n\n\n\n let file = task.GetFile(fd)?;\n\n\n\n let sock = file.FileOp.clone();\n\n\n\n if flags & !(MsgType::MSG_DONTWAIT | MsgType::MSG_EOR | MsgType::MSG_MORE | MsgType::MSG_NOSIGNAL) != 0 {\n\n return Err(Error::SysError(SysErr::EINVAL))\n\n }\n\n\n\n if !file.Blocking() {\n\n flags |= MsgType::MSG_DONTWAIT;\n\n }\n\n\n\n let mut deadline = None;\n\n let dl = sock.SendTimeout();\n", "file_path": "qkernel/src/syscalls/sys_socket.rs", "rank": 70, "score": 466262.2611711232 }, { "content": "pub fn write_file(dir: &str, file: &str, data: &str) -> Result<()> {\n\n let path = format!{\"{}/{}\", dir, file};\n\n debug!{\"writing {} to {}\", data, &path};\n\n let mut f = File::create(&path).map_err(|e| Error::SystemErr(e.raw_os_error().unwrap()))?;\n\n f.write_all(data.as_bytes()).map_err(|e| Error::SystemErr(e.raw_os_error().unwrap()))?;\n\n Ok(())\n\n}\n\n\n", "file_path": "qvisor/src/runc/container/cgroups.rs", "rank": 71, "score": 465582.5233240669 }, { "content": "fn FileNoMMap_Mmap(_data: &FileOptionsData, _task: &Task, _f: &File, _len: u64, _hugePage: bool, _offset: u64, _share: bool, _prot: u64) -> Result<u64> {\n\n return Err(Error::SysError(SysErr::ENODEV))\n\n}\n\n\n", "file_path": "qlib/kernel/fs/fsutil/file/fileopsutil.rs", "rank": 72, "score": 464982.0023525172 }, { "content": "pub fn Poll(task: &mut Task, pfdAddr: u64, nfds: u32, timeout: Duration) -> Result<i64> {\n\n if nfds > 4096 {\n\n // linux support poll max 4096 fds\n\n return Err(Error::SysError(SysErr::EINVAL))\n\n }\n\n\n\n let (remain, res) = DoPoll(task, pfdAddr, nfds, timeout);\n\n match res {\n\n Err(Error::SysError(SysErr::EINTR)) => {\n\n let b = Box::new(PollRestartBlock {\n\n pfdAddr: pfdAddr,\n\n nfds: nfds,\n\n timeout: remain,\n\n });\n\n task.SetSyscallRestartBlock(b);\n\n return Err(Error::SysError(SysErr::ERESTART_RESTARTBLOCK));\n\n }\n\n Err(e) => {\n\n return Err(e)\n\n }\n\n Ok(n) => return Ok(n as i64)\n\n }\n\n}\n\n\n", "file_path": "qkernel/src/syscalls/sys_poll.rs", "rank": 73, "score": 463587.36171257973 }, { "content": "fn WalkDescriptors(task: &Task, p: &str, toInode: &mut FnMut(&File, &FDFlags) -> Inode) -> Result<Inode> {\n\n let n : i32 = match p.parse() {\n\n Err(_) => return Err(Error::SysError(SysErr::ENOENT)),\n\n Ok(n) => n,\n\n };\n\n\n\n let (file, fdFlags) = match task.GetDescriptor(n) {\n\n Err(_) => return Err(Error::SysError(SysErr::ENOENT)),\n\n Ok(f) => f,\n\n };\n\n\n\n return Ok(toInode(&file, &fdFlags))\n\n}\n\n\n", "file_path": "qlib/kernel/fs/procfs/task/fds.rs", "rank": 74, "score": 462153.62093868933 }, { "content": "// Membarrier implements syscall membarrier(2).\n\npub fn SysMembarrier(_task: &mut Task, args: &SyscallArguments) -> Result<i64> {\n\n let cmd = args.arg0 as i32;\n\n let flags = args.arg1 as u32;\n\n\n\n match cmd {\n\n MEMBARRIER_CMD_QUERY => {\n\n if flags != 0 {\n\n return Err(Error::SysError(SysErr::EINVAL))\n\n }\n\n\n\n let supportedCommands = 0;\n\n return Ok(supportedCommands)\n\n }\n\n // todo: enable membarrier\n\n _ => {\n\n return Err(Error::SysError(SysErr::EINVAL))\n\n }\n\n }\n\n}", "file_path": "qkernel/src/syscalls/sys_membarrier.rs", "rank": 75, "score": 461938.0927738993 }, { "content": "pub fn Lstat(task: &Task, addr: u64, statAddr: u64) -> Result<i64> {\n\n let (path, dirPath) = copyInPath(task, addr, false)?;\n\n\n\n info!(\"Lstat path is {}\", &path);\n\n let resolve = dirPath;\n\n\n\n fileOpOn(task, ATType::AT_FDCWD, &path, resolve, &mut |_root: &Dirent, d: &Dirent, _remainingTraversals: u32| -> Result<()> {\n\n return stat(task, d, dirPath, statAddr)\n\n })?;\n\n\n\n return Ok(0)\n\n}\n\n\n", "file_path": "qkernel/src/syscalls/sys_stat.rs", "rank": 76, "score": 460971.64311416645 }, { "content": "pub fn Stat(task: &Task, addr: u64, statAddr: u64) -> Result<i64> {\n\n let (path, dirPath) = copyInPath(task, addr, false)?;\n\n info!(\"Stat path is {}\", &path);\n\n\n\n fileOpOn(task, ATType::AT_FDCWD, &path, true, &mut |_root: &Dirent, d: &Dirent, _remainingTraversals: u32| -> Result<()> {\n\n return stat(task, d, dirPath, statAddr)\n\n\n\n })?;\n\n\n\n return Ok(0);\n\n}\n\n\n", "file_path": "qkernel/src/syscalls/sys_stat.rs", "rank": 77, "score": 460971.64311416645 }, { "content": "pub fn overlayCreateDirectory(task: &Task, o: &Arc<RwLock<OverlayEntry>>, parent: &Dirent, name: &str, perm: &FilePermissions) -> Result<()> {\n\n CopyUpLockedForRename(task, parent)?;\n\n\n\n let mut inode = o.read().upper.as_ref().unwrap().clone();\n\n let iops = inode.lock().InodeOp.clone();\n\n let res = iops.CreateDirectory(task, &mut inode, name, perm);\n\n return res;\n\n}\n\n\n", "file_path": "qlib/kernel/fs/inode_overlay.rs", "rank": 78, "score": 460431.42008093966 }, { "content": "pub fn overlayCreateFifo(task: &Task, o: &Arc<RwLock<OverlayEntry>>, parent: &Dirent, name: &str, perm: &FilePermissions) -> Result<()> {\n\n CopyUpLockedForRename(task, parent)?;\n\n\n\n let mut inode = o.read().upper.as_ref().unwrap().clone();\n\n let iops = inode.lock().InodeOp.clone();\n\n let res = iops.CreateFifo(task, &mut inode, name, perm);\n\n return res;\n\n}\n\n\n", "file_path": "qlib/kernel/fs/inode_overlay.rs", "rank": 79, "score": 460431.42008093966 }, { "content": "fn InodeNotSymlink_ReadLink(_data: &InodeOpsData, _task: &Task,_dir: &Inode) -> Result<String> {\n\n return Err(Error::SysError(SysErr::ENOLINK))\n\n}\n\n\n", "file_path": "qlib/kernel/fs/fsutil/inode/iopsutil.rs", "rank": 80, "score": 459437.18701624486 }, { "content": "pub fn Eventfd2(task: &mut Task, initVal: i32, flags: i32) -> Result<i64> {\n\n let allOps = EFD_SEMAPHORE | EFD_NONBLOCK | EFD_CLOEXEC;\n\n\n\n if flags & !allOps != 0 {\n\n return Err(Error::SysError(SysErr::EINVAL))\n\n }\n\n\n\n let event = NewEventfd(task, initVal as u64, flags & EFD_SEMAPHORE != 0);\n\n event.SetFlags(task, SettableFileFlags{\n\n NonBlocking: flags & EFD_NONBLOCK != 0,\n\n ..Default::default()\n\n });\n\n event.flags.lock().0.NonSeekable = true;\n\n\n\n let fd = task.NewFDFrom(0, &event, &FDFlags{\n\n CloseOnExec: flags & EFD_CLOEXEC != 0,\n\n })?;\n\n\n\n return Ok(fd as i64)\n\n}\n\n\n", "file_path": "qkernel/src/syscalls/sys_eventfd.rs", "rank": 81, "score": 458566.34989787836 }, { "content": "// loadPath resolves filename to a binary and loads it.\n\npub fn LoadExecutable(task: &mut Task, filename: &str, argv: &mut Vec<String>) -> Result<(LoadedElf, Dirent, Vec<String>)> {\n\n let mut filename = filename.to_string();\n\n\n\n let mut tmp = Vec::new();\n\n tmp.append(argv);\n\n let mut argv = tmp;\n\n\n\n for _i in 0..MAX_LOADER_ATTEMPTS {\n\n let (file, executable) = OpenPath(task, &filename, 40)?;\n\n let mut hdr : [u8; 4] = [0; 4];\n\n\n\n match ReadAll(task, &file, &mut hdr, 0) {\n\n Err(e) => {\n\n print!(\"Error loading ELF {:?}\", e);\n\n return Err(Error::SysError(SysErr::ENOEXEC));\n\n }\n\n Ok(n) => {\n\n if n < 4 {\n\n print!(\"Error loading ELF, there is less than 4 bytes data, cnt is {}\", n);\n\n return Err(Error::SysError(SysErr::ENOEXEC));\n", "file_path": "qlib/kernel/loader/loader.rs", "rank": 82, "score": 458208.08721307456 }, { "content": "pub fn FileNoSeek_Seek(_data: &FileOptionsData, _task: &Task, _f: &File, _whence: i32, _current: i64, _offset: i64) -> Result<i64> {\n\n return Err(Error::SysError(SysErr::EINVAL))\n\n}\n\n\n", "file_path": "qlib/kernel/fs/fsutil/file/fileopsutil.rs", "rank": 83, "score": 457774.97961699485 }, { "content": "pub fn Accept4(task: &Task, fd: i32, addr: u64, addrlen: u64, flags: i32) -> Result<i64> {\n\n if flags & !(SocketFlags::SOCK_CLOEXEC | SocketFlags::SOCK_NONBLOCK) != 0 {\n\n return Err(Error::SysError(SysErr::EINVAL))\n\n }\n\n\n\n let file = task.GetFile(fd)?;\n\n\n\n let sock = file.FileOp.clone();\n\n\n\n let blocking = !file.Flags().NonBlocking;\n\n\n\n let len = if addrlen == 0 {\n\n 0\n\n } else {\n\n let len = task.CopyInObj::<i32>(addrlen)?;\n\n\n\n if len < 0 {\n\n return Err(Error::SysError(SysErr::EINVAL))\n\n }\n\n len as u32\n", "file_path": "qkernel/src/syscalls/sys_socket.rs", "rank": 84, "score": 457594.28313586744 }, { "content": "pub fn ReadLinkAt(task: &Task, dirFd: i32, addr: u64, bufAddr: u64, size: u64) -> Result<i64> {\n\n let size = size as u32;\n\n\n\n return readlinkAt(task, dirFd, addr, bufAddr, size)\n\n}\n\n\n", "file_path": "qkernel/src/syscalls/sys_file.rs", "rank": 85, "score": 457202.2209297387 }, { "content": "// SchedYield implements linux syscall sched_yield(2).\n\npub fn SysScheduleYield(_task: &mut Task, _args: &SyscallArguments) -> Result<i64> {\n\n Yield();\n\n\n\n return Ok(0)\n\n}\n\n\n", "file_path": "qkernel/src/syscalls/sys_thread.rs", "rank": 86, "score": 456587.7115509922 }, { "content": "pub fn SysClockSettime(_task: &mut Task, _args: &SyscallArguments) -> Result<i64> {\n\n return Err(Error::SysError(SysErr::EPERM))\n\n}\n\n\n", "file_path": "qkernel/src/syscalls/sys_time.rs", "rank": 87, "score": 456587.71155099233 }, { "content": "// IoCancel implements linux syscall io_cancel(2).\n\n//\n\n// It is not presently supported (ENOSYS indicates no support on this\n\n// architecture).\n\npub fn SysIOCancel(_task: &mut Task, _args: &SyscallArguments) -> Result<i64> {\n\n return Err(Error::SysError(SysErr::ENOSYS))\n\n}", "file_path": "qkernel/src/syscalls/sys_aio.rs", "rank": 88, "score": 456587.7115509922 }, { "content": "// CreateEpoll implements the epoll_create(2) linux syscall.\n\npub fn CreateEpoll(task: &Task, closeOnExec: bool) -> Result<i64> {\n\n let file = NewEventPoll(task);\n\n\n\n let flags = FDFlags {\n\n CloseOnExec: closeOnExec,\n\n };\n\n\n\n let fd = task.NewFDFrom(0, &file, &flags)?;\n\n\n\n return Ok(fd as i64);\n\n}\n\n\n", "file_path": "qkernel/src/syscalls/sys_epoll.rs", "rank": 89, "score": 454265.6145164922 }, { "content": "pub fn MapVDSOPage(task: &mut Task, virtualAddr: u64, vdsoAddr: u64) -> Result<u64> {\n\n let mut moptions = MMapOpts::NewAnonOptions(\"[vdso]\".to_string())?;\n\n moptions.Length = 2 * MemoryDef::PAGE_SIZE;\n\n moptions.Addr = virtualAddr;\n\n moptions.Fixed = true;\n\n moptions.Perms = AccessType::Executable();\n\n moptions.MaxPerms = AccessType::Executable();\n\n moptions.Private = false;\n\n moptions.VDSO = true;\n\n moptions.Kernel = false;\n\n moptions.Offset = vdsoAddr; //use offset to store the phyaddress\n\n\n\n let addr = task.mm.MMap(task, &mut moptions)?;\n\n return Ok(addr);\n\n}\n\n\n", "file_path": "qlib/kernel/loader/loader.rs", "rank": 90, "score": 454192.92437523534 }, { "content": "pub fn FileZeroSeek_Seek(_data: &FileOptionsData, _task: &Task, _f: &File, _whence: i32, _current: i64, _offset: i64) -> Result<i64> {\n\n return Ok(0)\n\n}\n\n\n", "file_path": "qlib/kernel/fs/fsutil/file/fileopsutil.rs", "rank": 91, "score": 454004.83449868986 }, { "content": "pub fn FilePipeSeek_Seek(_data: &FileOptionsData, _task: &Task, _f: &File, _whence: i32, _current: i64, _offset: i64) -> Result<i64> {\n\n return Err(Error::SysError(SysErr::ESPIPE))\n\n}\n\n\n", "file_path": "qlib/kernel/fs/fsutil/file/fileopsutil.rs", "rank": 92, "score": 454004.8344986898 }, { "content": "fn FileUseInodeUnstableAttr_UnstableAttr(_data: &FileOptionsData, task: &Task, f: &File) -> Result<UnstableAttr> {\n\n let inode = f.Dirent.Inode();\n\n return inode.UnstableAttr(task);\n\n}\n\n\n", "file_path": "qlib/kernel/fs/fsutil/file/fileopsutil.rs", "rank": 93, "score": 452333.5899875498 }, { "content": "pub fn Fstatat(task: &Task, fd: i32, addr: u64, statAddr: u64, flags: i32) -> Result<i64> {\n\n let (path, dirPath) = copyInPath(task, addr, flags & ATType::AT_EMPTY_PATH != 0)?;\n\n\n\n info!(\"Fstatat path is {} dirPath {}, flags & ATType::AT_SYMLINK_NOFOLLOW {:x}\",\n\n &path, dirPath, flags & ATType::AT_SYMLINK_NOFOLLOW);\n\n if path.len() == 0 {\n\n let file = task.GetFile(fd)?;\n\n\n\n fstat(task, &file, statAddr)?;\n\n return Ok(0)\n\n }\n\n\n\n let resolve = dirPath || flags & ATType::AT_SYMLINK_NOFOLLOW == 0;\n\n\n\n let ret = fileOpOn(task, fd, &path, resolve, &mut |_root: &Dirent, d: &Dirent, _remainingTraversals: u32| -> Result<()> {\n\n return stat(task, d, dirPath, statAddr)\n\n });\n\n\n\n match ret {\n\n Err(e) => {\n\n //error!(\"Fstatat fail path is {}, error is {:?}\", &path, &e);\n\n return Err(e)\n\n }\n\n _ => ()\n\n }\n\n\n\n return Ok(0)\n\n}\n\n\n", "file_path": "qkernel/src/syscalls/sys_stat.rs", "rank": 94, "score": 452097.4578138628 }, { "content": "pub fn overlaySetOwner(task: &Task, o: &Arc<RwLock<OverlayEntry>>, d: &Dirent, owner: &FileOwner) -> Result<()> {\n\n copyUp(task, d)?;\n\n\n\n let overlay = o.read();\n\n let mut upperInode = overlay.upper.as_ref().unwrap().clone();\n\n let upperInodeOps = upperInode.lock().InodeOp.clone();\n\n return upperInodeOps.SetOwner(task, &mut upperInode, owner)\n\n}\n\n\n", "file_path": "qlib/kernel/fs/inode_overlay.rs", "rank": 95, "score": 450028.5226727885 }, { "content": "fn NoSock_GetPeerName(_data: &FileOptionsData, _task: &Task, _socketaddr: &mut [u8]) -> Result<i64> {\n\n return Err(Error::SysError(SysErr::ENOTSOCK))\n\n}\n\n\n", "file_path": "qlib/kernel/fs/fsutil/file/fileopsutil.rs", "rank": 96, "score": 448896.9066567662 }, { "content": "fn NoSock_GetSockName(_data: &FileOptionsData, _task: &Task, _socketaddr: &mut [u8]) -> Result<i64> {\n\n return Err(Error::SysError(SysErr::ENOTSOCK))\n\n}\n\n\n", "file_path": "qlib/kernel/fs/fsutil/file/fileopsutil.rs", "rank": 97, "score": 448896.9066567662 }, { "content": "fn InodeNoExtendedAttributes_Getxattr(_data: &InodeOpsData, _dir: &Inode, _name: &str) -> Result<String> {\n\n return Err(Error::SysError(SysErr::EOPNOTSUPP))\n\n}\n\n\n", "file_path": "qlib/kernel/fs/fsutil/inode/iopsutil.rs", "rank": 98, "score": 446903.12856356055 }, { "content": "pub fn ParseBool(str: &str) -> Result<bool> {\n\n match str {\n\n \"1\" | \"t\" | \"T\" | \"true\" | \"TRUE\" | \"True\" => Ok(true),\n\n \"0\" | \"f\" | \"F\" | \"false\" | \"FALSE\" | \"False\" => Ok(false),\n\n _ => Err(Error::Common(\"parse error\".to_string()))\n\n }\n\n}", "file_path": "qlib/path.rs", "rank": 99, "score": 446333.2588430339 } ]
Rust
lib/src/command/process.rs
abitrolly/watchexec
5bdd87dbf6a67360c78555924e777bd5507d5ec6
use std::process::ExitStatus; use command_group::AsyncGroupChild; use tokio::process::Child; use tracing::{debug, trace}; use crate::error::RuntimeError; #[derive(Debug)] pub enum Process { None, Grouped(AsyncGroupChild), Ungrouped(Child), Done(ExitStatus), } impl Default for Process { fn default() -> Self { Process::None } } impl Process { #[cfg(unix)] pub fn signal(&mut self, sig: command_group::Signal) -> Result<(), RuntimeError> { use command_group::UnixChildExt; match self { Self::None | Self::Done(_) => Ok(()), Self::Grouped(c) => { debug!(signal=%sig, pgid=?c.id(), "sending signal to process group"); c.signal(sig) } Self::Ungrouped(c) => { debug!(signal=%sig, pid=?c.id(), "sending signal to process"); c.signal(sig) } } .map_err(RuntimeError::Process) } pub async fn kill(&mut self) -> Result<(), RuntimeError> { match self { Self::None | Self::Done(_) => Ok(()), Self::Grouped(c) => { debug!(pgid=?c.id(), "killing process group"); c.kill() } Self::Ungrouped(c) => { debug!(pid=?c.id(), "killing process"); c.kill().await } } .map_err(RuntimeError::Process) } pub fn is_running(&mut self) -> Result<bool, RuntimeError> { match self { Self::None | Self::Done(_) => Ok(false), Self::Grouped(c) => c.try_wait().map(|status| { trace!("try-waiting on process group"); if let Some(status) = status { trace!(?status, "converting to ::Done"); *self = Self::Done(status); true } else { false } }), Self::Ungrouped(c) => c.try_wait().map(|status| { trace!("try-waiting on process"); if let Some(status) = status { trace!(?status, "converting to ::Done"); *self = Self::Done(status); true } else { false } }), } .map_err(RuntimeError::Process) } pub async fn wait(&mut self) -> Result<Option<ExitStatus>, RuntimeError> { match self { Self::None => Ok(None), Self::Done(status) => Ok(Some(*status)), Self::Grouped(c) => { trace!("waiting on process group"); let status = c.wait().await.map_err(|err| RuntimeError::IoError { about: "waiting on process group", err, })?; trace!(?status, "converting to ::Done"); *self = Self::Done(status); Ok(Some(status)) } Self::Ungrouped(c) => { trace!("waiting on process"); let status = c.wait().await.map_err(|err| RuntimeError::IoError { about: "waiting on process (ungrouped)", err, })?; trace!(?status, "converting to ::Done"); *self = Self::Done(status); Ok(Some(status)) } } .map_err(RuntimeError::Process) } }
use std::process::ExitStatus; use command_group::AsyncGroupChild; use tokio::process::Child; use tracing::{debug, trace}; use crate::error::RuntimeError; #[derive(Debug)] pub enum Process { None, Grouped(AsyncGroupChild), Ungrouped(Child), Done(ExitStatus), } impl Default for Process { fn default() -> Self { Process::None } } impl Process { #[cfg(unix)] pub fn signal(&mut self, sig: command_group::Signal) -> Result<(), RuntimeError> { use command_group::UnixChildExt;
.map_err(RuntimeError::Process) } pub async fn kill(&mut self) -> Result<(), RuntimeError> { match self { Self::None | Self::Done(_) => Ok(()), Self::Grouped(c) => { debug!(pgid=?c.id(), "killing process group"); c.kill() } Self::Ungrouped(c) => { debug!(pid=?c.id(), "killing process"); c.kill().await } } .map_err(RuntimeError::Process) } pub fn is_running(&mut self) -> Result<bool, RuntimeError> { match self { Self::None | Self::Done(_) => Ok(false), Self::Grouped(c) => c.try_wait().map(|status| { trace!("try-waiting on process group"); if let Some(status) = status { trace!(?status, "converting to ::Done"); *self = Self::Done(status); true } else { false } }), Self::Ungrouped(c) => c.try_wait().map(|status| { trace!("try-waiting on process"); if let Some(status) = status { trace!(?status, "converting to ::Done"); *self = Self::Done(status); true } else { false } }), } .map_err(RuntimeError::Process) } pub async fn wait(&mut self) -> Result<Option<ExitStatus>, RuntimeError> { match self { Self::None => Ok(None), Self::Done(status) => Ok(Some(*status)), Self::Grouped(c) => { trace!("waiting on process group"); let status = c.wait().await.map_err(|err| RuntimeError::IoError { about: "waiting on process group", err, })?; trace!(?status, "converting to ::Done"); *self = Self::Done(status); Ok(Some(status)) } Self::Ungrouped(c) => { trace!("waiting on process"); let status = c.wait().await.map_err(|err| RuntimeError::IoError { about: "waiting on process (ungrouped)", err, })?; trace!(?status, "converting to ::Done"); *self = Self::Done(status); Ok(Some(status)) } } .map_err(RuntimeError::Process) } }
match self { Self::None | Self::Done(_) => Ok(()), Self::Grouped(c) => { debug!(signal=%sig, pgid=?c.id(), "sending signal to process group"); c.signal(sig) } Self::Ungrouped(c) => { debug!(signal=%sig, pid=?c.id(), "sending signal to process"); c.signal(sig) } }
if_condition
[ { "content": "/// Convenience function to check a glob pattern from a string.\n\n///\n\n/// This parses the glob and wraps any error with nice [miette] diagnostics.\n\npub fn check_glob(glob: &str) -> Result<(), GlobParseError> {\n\n\tlet mut builder = GitignoreBuilder::new(\"/\");\n\n\tif let Err(err) = builder.add_line(None, glob) {\n\n\t\tif let ignore::Error::Glob { err, .. } = err {\n\n\t\t\t// TODO: use globset and return a nicer error\n\n\t\t\tErr(GlobParseError::new(glob, &err))\n\n\t\t} else {\n\n\t\t\tErr(GlobParseError::new(glob, \"unknown error\"))\n\n\t\t}\n\n\t} else {\n\n\t\tOk(())\n\n\t}\n\n}\n", "file_path": "lib/src/filter.rs", "rank": 0, "score": 125326.5633029367 }, { "content": "pub fn init(_args: &ArgMatches<'static>) -> Result<InitConfig> {\n\n\tlet mut config = InitConfig::default();\n\n\tconfig.on_error(SyncFnHandler::from(\n\n\t\t|data| -> std::result::Result<(), Infallible> {\n\n\t\t\t// if let RuntimeError::IoError { .. } = data {\n\n\t\t\t// \t// these are often spurious, so condemn them to -v only\n\n\t\t\t// \terror!(\"{}\", data);\n\n\t\t\t// \treturn Ok(());\n\n\t\t\t// }\n\n\n\n\t\t\tif cfg!(debug_assertions) {\n\n\t\t\t\teprintln!(\"[[{:?}]]\", data);\n\n\t\t\t} else {\n\n\t\t\t\teprintln!(\"[[{}]]\", data);\n\n\t\t\t}\n\n\n\n\t\t\tOk(())\n\n\t\t},\n\n\t));\n\n\n\n\tOk(config)\n\n}\n", "file_path": "cli/src/config/init.rs", "rank": 1, "score": 119963.30906930019 }, { "content": "pub fn get_args(tagged_filterer: bool) -> Result<ArgMatches<'static>> {\n\n\tlet app = App::new(\"watchexec\")\n\n\t\t.version(crate_version!())\n\n\t\t.about(\"Execute commands when watched files change\")\n\n\t\t.after_help(\"Use @argfile as first argument to load arguments from the file `argfile` (one argument per line) which will be inserted in place of the @argfile (further arguments on the CLI will override or add onto those in the file).\")\n\n\t\t.arg(Arg::with_name(\"command\")\n\n\t\t\t.help_heading(Some(OPTSET_COMMAND))\n\n\t\t\t.help(\"Command to execute\")\n\n\t\t\t.multiple(true)\n\n\t\t\t.required(true))\n\n\t\t.arg(Arg::with_name(\"paths\")\n\n\t\t\t.help_heading(Some(OPTSET_FILTERING))\n\n\t\t\t.help(\"Watch a specific file or directory\")\n\n\t\t\t.short(\"w\")\n\n\t\t\t.long(\"watch\")\n\n\t\t\t.value_name(\"path\")\n\n\t\t\t.number_of_values(1)\n\n\t\t\t.multiple(true)\n\n\t\t\t.takes_value(true))\n\n\t\t.arg(Arg::with_name(\"clear\")\n", "file_path": "cli/src/args.rs", "rank": 2, "score": 119963.30906930019 }, { "content": "pub fn runtime(args: &ArgMatches<'static>) -> Result<RuntimeConfig> {\n\n\tlet mut config = RuntimeConfig::default();\n\n\n\n\tconfig.command(\n\n\t\targs.values_of_lossy(\"command\")\n\n\t\t\t.expect(\"(clap) Bug: command is not present\")\n\n\t\t\t.iter(),\n\n\t);\n\n\n\n\tconfig.pathset(match args.values_of_os(\"paths\") {\n\n\t\tSome(paths) => paths.map(|os| Path::new(os).to_owned()).collect(),\n\n\t\tNone => vec![current_dir().into_diagnostic()?],\n\n\t});\n\n\n\n\tconfig.action_throttle(Duration::from_millis(\n\n\t\targs.value_of(\"debounce\")\n\n\t\t\t.unwrap_or(\"100\")\n\n\t\t\t.parse()\n\n\t\t\t.into_diagnostic()?,\n\n\t));\n", "file_path": "cli/src/config/runtime.rs", "rank": 3, "score": 119963.30906930019 }, { "content": "#[inline]\n\nfn flatten(join_res: Result<Result<(), CriticalError>, JoinError>) -> Result<(), CriticalError> {\n\n\tjoin_res\n\n\t\t.map_err(CriticalError::MainTaskJoin)\n\n\t\t.and_then(|x| x)\n\n}\n\n\n\nasync fn error_hook(\n\n\tmut errors: mpsc::Receiver<RuntimeError>,\n\n\tmut handler: Box<dyn Handler<RuntimeError> + Send>,\n\n) -> Result<(), CriticalError> {\n\n\twhile let Some(err) = errors.recv().await {\n\n\t\tif matches!(err, RuntimeError::Exit) {\n\n\t\t\ttrace!(\"got graceful exit request via runtime error, upgrading to crit\");\n\n\t\t\treturn Err(CriticalError::Exit);\n\n\t\t}\n\n\n\n\t\terror!(%err, \"runtime error\");\n\n\t\tif let Err(err) = handler.handle(err) {\n\n\t\t\terror!(%err, \"error while handling error\");\n\n\t\t\thandler\n\n\t\t\t\t.handle(rte(\"error hook\", err))\n\n\t\t\t\t.unwrap_or_else(|err| {\n\n\t\t\t\t\terror!(%err, \"error while handling error of handling error\");\n\n\t\t\t\t});\n\n\t\t}\n\n\t}\n\n\n\n\tOk(())\n\n}\n", "file_path": "lib/src/watchexec.rs", "rank": 4, "score": 102312.73556597637 }, { "content": "/// Summarise [`Event`]s as a set of environment variables by category.\n\n///\n\n/// - `CREATED` -> `Create(_)`\n\n/// - `META_CHANGED` -> `Modify(Metadata(_))`\n\n/// - `REMOVED` -> `Remove(_)`\n\n/// - `RENAMED` -> `Modify(Name(_))`\n\n/// - `WRITTEN` -> `Modify(Data(_))`, `Access(Close(Write))`\n\n/// - `OTHERWISE_CHANGED` -> anything else\n\n/// - plus `COMMON` with the common prefix of all paths (even if there's only one path).\n\n///\n\n/// It ignores non-path events and pathed events without event kind. Multiple events are sorted in\n\n/// byte order and joined with the platform-specific path separator (`:` for unix, `;` for Windows).\n\npub fn summarise_events_to_env<'events>(\n\n\tevents: impl IntoIterator<Item = &'events Event>,\n\n) -> HashMap<&'static str, OsString> {\n\n\tlet mut all_trunks = Vec::new();\n\n\tlet mut kind_buckets = HashMap::new();\n\n\tfor event in events {\n\n\t\tlet (paths, trunks): (Vec<_>, Vec<_>) = event\n\n\t\t\t.paths()\n\n\t\t\t.map(|(p, ft)| {\n\n\t\t\t\t(\n\n\t\t\t\t\tp.to_owned(),\n\n\t\t\t\t\tmatch ft {\n\n\t\t\t\t\t\tSome(FileType::Dir) => None,\n\n\t\t\t\t\t\t_ => p.parent(),\n\n\t\t\t\t\t}\n\n\t\t\t\t\t.unwrap_or(p)\n\n\t\t\t\t\t.to_owned(),\n\n\t\t\t\t)\n\n\t\t\t})\n\n\t\t\t.unzip();\n", "file_path": "lib/src/paths.rs", "rank": 5, "score": 96351.86541896735 }, { "content": "pub fn filter(expr: &str) -> Filter {\n\n\tFilter::from_str(expr).expect(\"parse filter\")\n\n}\n\n\n", "file_path": "lib/tests/helpers.rs", "rank": 6, "score": 90941.32793595617 }, { "content": "pub fn glob_filter(pat: &str) -> Filter {\n\n\tFilter {\n\n\t\tin_path: None,\n\n\t\ton: Matcher::Path,\n\n\t\top: Op::Glob,\n\n\t\tpat: Pattern::Glob(pat.into()),\n\n\t\tnegate: false,\n\n\t}\n\n}\n\n\n", "file_path": "lib/tests/helpers.rs", "rank": 7, "score": 88852.70729654326 }, { "content": "pub fn notglob_filter(pat: &str) -> Filter {\n\n\tFilter {\n\n\t\tin_path: None,\n\n\t\ton: Matcher::Path,\n\n\t\top: Op::NotGlob,\n\n\t\tpat: Pattern::Glob(pat.into()),\n\n\t\tnegate: false,\n\n\t}\n\n}\n\n\n", "file_path": "lib/tests/helpers.rs", "rank": 8, "score": 88852.70729654326 }, { "content": "fn tracing_init() {\n\n\tuse tracing_subscriber::{\n\n\t\tfmt::{format::FmtSpan, Subscriber},\n\n\t\tutil::SubscriberInitExt,\n\n\t\tEnvFilter,\n\n\t};\n\n\tSubscriber::builder()\n\n\t\t.pretty()\n\n\t\t.with_span_events(FmtSpan::NEW | FmtSpan::CLOSE)\n\n\t\t.with_env_filter(EnvFilter::from_default_env())\n\n\t\t.finish()\n\n\t\t.try_init()\n\n\t\t.ok();\n\n}\n\n\n\npub async fn globset_filt(\n\n\tfilters: &[&str],\n\n\tignores: &[&str],\n\n\textensions: &[&str],\n\n) -> GlobsetFilterer {\n", "file_path": "lib/tests/helpers.rs", "rank": 9, "score": 87071.9696009561 }, { "content": "pub fn ff_file(name: &str) -> FilterFile {\n\n\tFilterFile(ig_file(name))\n\n}\n\n\n", "file_path": "lib/tests/helpers.rs", "rank": 10, "score": 86897.80785087877 }, { "content": "pub fn ig_file(name: &str) -> IgnoreFile {\n\n\tlet path = dunce::canonicalize(\".\")\n\n\t\t.unwrap()\n\n\t\t.join(\"tests\")\n\n\t\t.join(\"ignores\")\n\n\t\t.join(name);\n\n\tIgnoreFile {\n\n\t\tpath,\n\n\t\tapplies_in: None,\n\n\t\tapplies_to: None,\n\n\t}\n\n}\n\n\n", "file_path": "lib/tests/helpers.rs", "rank": 11, "score": 86897.80785087877 }, { "content": "fn process_event(\n\n\tnev: Result<notify::Event, notify::Error>,\n\n\tkind: Watcher,\n\n\tn_events: mpsc::Sender<Event>,\n\n) -> Result<(), RuntimeError> {\n\n\tlet nev = nev.map_err(|err| RuntimeError::FsWatcherEvent { kind, err })?;\n\n\n\n\tlet mut tags = Vec::with_capacity(4);\n\n\ttags.push(Tag::Source(Source::Filesystem));\n\n\ttags.push(Tag::FileEventKind(nev.kind));\n\n\n\n\tfor path in nev.paths {\n\n\t\t// possibly pull file_type from whatever notify (or the native driver) returns?\n\n\t\ttags.push(Tag::Path {\n\n\t\t\tfile_type: metadata(&path).ok().map(|m| m.file_type().into()),\n\n\t\t\tpath: dunce::canonicalize(&path).unwrap_or_else(|err| {\n\n\t\t\t\twarn!(?err, ?path, \"failed to canonicalise event path\");\n\n\t\t\t\tpath\n\n\t\t\t}),\n\n\t\t});\n", "file_path": "lib/src/fs.rs", "rank": 12, "score": 86882.89753562039 }, { "content": "#[cfg(test)]\n\n#[test]\n\nfn os_split_none() {\n\n\tlet os = OsString::from(\"\");\n\n\tassert_eq!(\n\n\t\tos.split(b',').collect::<Vec<OsString>>(),\n\n\t\tVec::<OsString>::new()\n\n\t);\n\n\n\n\tlet mut split = os.split(b',');\n\n\tassert_eq!(split.next(), None);\n\n}\n\n\n", "file_path": "cli/src/filterer/globset.rs", "rank": 13, "score": 82064.82692515833 }, { "content": "#[cfg(test)]\n\n#[test]\n\nfn os_strip_none() {\n\n\tlet os = OsString::from(\"abc\");\n\n\tassert_eq!(os_strip_prefix(os, b'.'), OsString::from(\"abc\"));\n\n}\n\n\n", "file_path": "cli/src/filterer/globset.rs", "rank": 14, "score": 82064.82692515833 }, { "content": "#[cfg(not(windows))]\n\nfn default_shell() -> Shell {\n\n\tShell::default()\n\n}\n\n\n\n// because Shell::Cmd is only on windows\n", "file_path": "cli/src/config/runtime.rs", "rank": 15, "score": 80282.17985563709 }, { "content": "/// Returns the longest common prefix of all given paths.\n\n///\n\n/// This is a utility function which is useful for finding the common root of a set of origins.\n\n///\n\n/// Returns `None` if zero paths are given or paths share no common prefix.\n\npub fn common_prefix<I, P>(paths: I) -> Option<PathBuf>\n\nwhere\n\n\tI: IntoIterator<Item = P>,\n\n\tP: AsRef<Path>,\n\n{\n\n\tlet mut paths = paths.into_iter();\n\n\tlet first_path = paths.next().map(|p| p.as_ref().to_owned());\n\n\tlet mut longest_path = if let Some(ref p) = first_path {\n\n\t\tp.components().collect::<Vec<_>>()\n\n\t} else {\n\n\t\treturn None;\n\n\t};\n\n\n\n\tfor path in paths {\n\n\t\tlet mut greatest_distance = 0;\n\n\t\tfor component_pair in path.as_ref().components().zip(longest_path.iter()) {\n\n\t\t\tif component_pair.0 != *component_pair.1 {\n\n\t\t\t\tbreak;\n\n\t\t\t}\n\n\n", "file_path": "lib/src/paths.rs", "rank": 16, "score": 79612.70231055039 }, { "content": "#[derive(Debug)]\n\nenum Visit {\n\n\tFind(PathBuf),\n\n\tSkip,\n\n\tDone,\n\n}\n\n\n\nimpl DirTourist {\n\n\tpub async fn new(base: &Path, files: &[IgnoreFile]) -> Result<Self, Error> {\n\n\t\tlet base = dunce::canonicalize(base)?;\n\n\t\ttrace!(\"create IgnoreFilterer for visiting directories\");\n\n\t\tlet mut filter = IgnoreFilterer::new(&base, files)\n\n\t\t\t.await\n\n\t\t\t.map_err(|err| Error::new(ErrorKind::Other, err))?;\n\n\n\n\t\tfilter\n\n\t\t\t.add_globs(\n\n\t\t\t\t&[\n\n\t\t\t\t\t\"/.git\",\n\n\t\t\t\t\t\"/.hg\",\n\n\t\t\t\t\t\"/.bzr\",\n", "file_path": "lib/src/ignore/files.rs", "rank": 17, "score": 61486.66250193455 }, { "content": "#[derive(Clone, Copy, Debug)]\n\nenum Intervention {\n\n\tKill,\n\n\tSignal(SubSignal),\n\n}\n\n\n\n/// A task which supervises a process.\n\n///\n\n/// This spawns a process from a [`Command`] and waits for it to complete while handling\n\n/// interventions to it: orders to terminate it, or to send a signal to it. It also immediately\n\n/// issues a [`Tag::ProcessCompletion`] event when the process completes.\n\n#[derive(Debug)]\n\npub struct Supervisor {\n\n\tid: u32,\n\n\tintervene: Sender<Intervention>,\n\n\n\n\t#[allow(dead_code)]\n\n\thandle: JoinHandle<()>, // see TODO in ::spawn()\n\n\n\n\t// why this and not a watch::channel? two reasons:\n\n\t// 1. I tried the watch and ran into some race conditions???\n", "file_path": "lib/src/command/supervisor.rs", "rank": 18, "score": 61486.66250193455 }, { "content": "pub trait Applies {\n\n\tfn applies_in(self, origin: &str) -> Self;\n\n\tfn applies_to(self, project_type: ProjectType) -> Self;\n\n}\n\n\n\nimpl Applies for IgnoreFile {\n\n\tfn applies_in(mut self, origin: &str) -> Self {\n\n\t\tlet origin = dunce::canonicalize(\".\").unwrap().join(origin);\n\n\t\tself.applies_in = Some(origin);\n\n\t\tself\n\n\t}\n\n\n\n\tfn applies_to(mut self, project_type: ProjectType) -> Self {\n\n\t\tself.applies_to = Some(project_type);\n\n\t\tself\n\n\t}\n\n}\n\n\n\nimpl Applies for FilterFile {\n\n\tfn applies_in(self, origin: &str) -> Self {\n\n\t\tSelf(self.0.applies_in(origin))\n\n\t}\n\n\n\n\tfn applies_to(self, project_type: ProjectType) -> Self {\n\n\t\tSelf(self.0.applies_to(project_type))\n\n\t}\n\n}\n\n\n", "file_path": "lib/tests/helpers.rs", "rank": 19, "score": 57507.464321237276 }, { "content": "pub trait TaggedHarness {\n\n\tfn check_tag(&self, tag: Tag) -> std::result::Result<bool, RuntimeError>;\n\n\n\n\tfn tag_pass(&self, tag: Tag, pass: bool) {\n\n\t\ttracing::info!(?tag, ?pass, \"check\");\n\n\n\n\t\tassert_eq!(\n\n\t\t\tself.check_tag(tag.clone()).unwrap(),\n\n\t\t\tpass,\n\n\t\t\t\"{:?} (expected {})\",\n\n\t\t\ttag,\n\n\t\t\tif pass { \"pass\" } else { \"fail\" }\n\n\t\t);\n\n\t}\n\n\n\n\tfn fek_does_pass(&self, fek: FileEventKind) {\n\n\t\tself.tag_pass(Tag::FileEventKind(fek), true);\n\n\t}\n\n\n\n\tfn fek_doesnt_pass(&self, fek: FileEventKind) {\n", "file_path": "lib/tests/helpers.rs", "rank": 20, "score": 56205.07465608335 }, { "content": "pub trait FilterExt {\n\n\tfn in_path(self) -> Self\n\n\twhere\n\n\t\tSelf: Sized,\n\n\t{\n\n\t\tself.in_subpath(\"\")\n\n\t}\n\n\n\n\tfn in_subpath(self, sub: impl AsRef<Path>) -> Self;\n\n}\n\n\n\nimpl FilterExt for Filter {\n\n\tfn in_subpath(mut self, sub: impl AsRef<Path>) -> Self {\n\n\t\tlet origin = dunce::canonicalize(\".\").unwrap();\n\n\t\tself.in_path = Some(origin.join(sub));\n\n\t\tself\n\n\t}\n\n}\n", "file_path": "lib/tests/helpers.rs", "rank": 21, "score": 56205.07465608335 }, { "content": "fn main() {\n\n\tembed_resource::compile(\"watchexec-manifest.rc\");\n\n}\n", "file_path": "cli/build.rs", "rank": 22, "score": 54308.77534554424 }, { "content": "/// A callable that can be used to hook into watchexec.\n\npub trait Handler<T> {\n\n\t/// Call the handler with the given data.\n\n\tfn handle(&mut self, _data: T) -> Result<(), Box<dyn Error>>;\n\n}\n\n\n\npub(crate) fn rte(ctx: &'static str, err: Box<dyn Error>) -> RuntimeError {\n\n\tRuntimeError::Handler {\n\n\t\tctx,\n\n\t\terr: err.to_string(),\n\n\t}\n\n}\n\n\n\n/// Wrapper for [`Handler`]s that are non-future [`FnMut`]s.\n\n///\n\n/// Construct using [`Into::into`]:\n\n///\n\n/// ```\n\n/// # use watchexec::handler::{Handler as _, SyncFnHandler};\n\n/// # let f: SyncFnHandler<(), std::io::Error, _> =\n\n/// (|data| { dbg!(data); Ok(()) }).into()\n", "file_path": "lib/src/handler.rs", "rank": 23, "score": 54064.15190451678 }, { "content": "pub trait PathHarness: Filterer {\n\n\tfn check_path(\n\n\t\t&self,\n\n\t\tpath: PathBuf,\n\n\t\tfile_type: Option<FileType>,\n\n\t) -> std::result::Result<bool, RuntimeError> {\n\n\t\tlet event = Event {\n\n\t\t\ttags: vec![Tag::Path { path, file_type }],\n\n\t\t\tmetadata: Default::default(),\n\n\t\t};\n\n\n\n\t\tself.check_event(&event)\n\n\t}\n\n\n\n\tfn path_pass(&self, path: &str, file_type: Option<FileType>, pass: bool) {\n\n\t\tlet origin = dunce::canonicalize(\".\").unwrap();\n\n\t\tlet full_path = if let Some(suf) = path.strip_prefix(\"/test/\") {\n\n\t\t\torigin.join(suf)\n\n\t\t} else if Path::new(path).has_root() {\n\n\t\t\tpath.into()\n", "file_path": "lib/tests/helpers.rs", "rank": 24, "score": 52849.73338372886 }, { "content": "#[test]\n\nfn help() {\n\n\tlet output = Command::cargo_bin(\"watchexec\")\n\n\t\t.unwrap()\n\n\t\t.arg(\"--help\")\n\n\t\t.output()\n\n\t\t.unwrap();\n\n\n\n\tassert!(output.status.success(), \"--help returns 0\");\n\n\tassert_eq!(output.stderr, Vec::<u8>::new(), \"--help stderr is empty\");\n\n\tassert_snapshot!(\n\n\t\tif cfg!(windows) {\n\n\t\t\t\"help_windows\"\n\n\t\t} else {\n\n\t\t\t\"help_unix\"\n\n\t\t},\n\n\t\tString::from_utf8(output.stdout).unwrap()\n\n\t);\n\n}\n\n\n", "file_path": "cli/tests/help.rs", "rank": 25, "score": 52811.74974757318 }, { "content": "#[test]\n\nfn all_types_once() {\n\n\tlet events = vec![\n\n\t\tevent(\"create.txt\", FileEventKind::Create(CreateKind::File)),\n\n\t\tevent(\n\n\t\t\t\"metadata.txt\",\n\n\t\t\tFileEventKind::Modify(ModifyKind::Metadata(MetadataKind::Any)),\n\n\t\t),\n\n\t\tevent(\"remove.txt\", FileEventKind::Remove(RemoveKind::File)),\n\n\t\tevent(\n\n\t\t\t\"rename.txt\",\n\n\t\t\tFileEventKind::Modify(ModifyKind::Name(RenameMode::Any)),\n\n\t\t),\n\n\t\tevent(\n\n\t\t\t\"modify.txt\",\n\n\t\t\tFileEventKind::Modify(ModifyKind::Data(DataChange::Any)),\n\n\t\t),\n\n\t\tevent(\"any.txt\", FileEventKind::Any),\n\n\t];\n\n\tassert_eq!(\n\n\t\tsummarise_events_to_env(&events),\n", "file_path": "lib/tests/env_reporting.rs", "rank": 26, "score": 51428.83350115392 }, { "content": "#[test]\n\nfn help_short() {\n\n\tlet long = Command::cargo_bin(\"watchexec\")\n\n\t\t.unwrap()\n\n\t\t.arg(\"--help\")\n\n\t\t.output()\n\n\t\t.unwrap();\n\n\n\n\tlet short = Command::cargo_bin(\"watchexec\")\n\n\t\t.unwrap()\n\n\t\t.arg(\"--help\")\n\n\t\t.output()\n\n\t\t.unwrap();\n\n\n\n\tassert!(short.status.success(), \"-h returns 0\");\n\n\tassert_eq!(short.stderr, Vec::<u8>::new(), \"-h stderr is empty\");\n\n\tassert_eq!(\n\n\t\tlong.stdout, short.stdout,\n\n\t\t\"--help and -h output are the same\"\n\n\t);\n\n}\n", "file_path": "cli/tests/help.rs", "rank": 27, "score": 51428.83350115392 }, { "content": "#[test]\n\nfn no_events_no_env() {\n\n\tlet events = Vec::<Event>::new();\n\n\tassert_eq!(summarise_events_to_env(&events), HashMap::new());\n\n}\n\n\n", "file_path": "lib/tests/env_reporting.rs", "rank": 28, "score": 50147.45877662071 }, { "content": "#[test]\n\nfn multitype_multipath() {\n\n\tlet events = vec![\n\n\t\tevent(\"root.txt\", FileEventKind::Create(CreateKind::File)),\n\n\t\tevent(\"sibling.txt\", FileEventKind::Create(CreateKind::Any)),\n\n\t\tevent(\n\n\t\t\t\"sub/folder.txt\",\n\n\t\t\tFileEventKind::Modify(ModifyKind::Metadata(MetadataKind::Ownership)),\n\n\t\t),\n\n\t\tevent(\"dom/folder.txt\", FileEventKind::Remove(RemoveKind::Folder)),\n\n\t\tevent(\"deeper/sub/folder.txt\", FileEventKind::Other),\n\n\t];\n\n\tassert_eq!(\n\n\t\tsummarise_events_to_env(&events),\n\n\t\tHashMap::from([\n\n\t\t\t(\n\n\t\t\t\t\"CREATED\",\n\n\t\t\t\tOsString::from(\"\".to_string() + \"root.txt\" + ENV_SEP + \"sibling.txt\"),\n\n\t\t\t),\n\n\t\t\t(\"META_CHANGED\", OsString::from(\"sub/folder.txt\"),),\n\n\t\t\t(\"REMOVED\", OsString::from(\"dom/folder.txt\"),),\n\n\t\t\t(\"OTHERWISE_CHANGED\", OsString::from(\"deeper/sub/folder.txt\"),),\n\n\t\t\t(\"COMMON\", ospath(\"\")),\n\n\t\t])\n\n\t);\n\n}\n\n\n", "file_path": "lib/tests/env_reporting.rs", "rank": 29, "score": 50147.45877662071 }, { "content": "#[test]\n\nfn single_meta() {\n\n\tlet events = vec![event(\n\n\t\t\"file.txt\",\n\n\t\tFileEventKind::Modify(ModifyKind::Metadata(MetadataKind::Any)),\n\n\t)];\n\n\tassert_eq!(\n\n\t\tsummarise_events_to_env(&events),\n\n\t\tHashMap::from([\n\n\t\t\t(\"META_CHANGED\", OsString::from(\"file.txt\")),\n\n\t\t\t(\"COMMON\", ospath(\"\")),\n\n\t\t])\n\n\t);\n\n}\n\n\n", "file_path": "lib/tests/env_reporting.rs", "rank": 30, "score": 50147.45877662071 }, { "content": "#[test]\n\nfn multipath_is_sorted() {\n\n\tlet events = vec![\n\n\t\tevent(\"0123.txt\", FileEventKind::Any),\n\n\t\tevent(\"a.txt\", FileEventKind::Any),\n\n\t\tevent(\"b.txt\", FileEventKind::Any),\n\n\t\tevent(\"c.txt\", FileEventKind::Any),\n\n\t\tevent(\"ᄁ.txt\", FileEventKind::Any),\n\n\t];\n\n\tassert_eq!(\n\n\t\tsummarise_events_to_env(&events),\n\n\t\tHashMap::from([\n\n\t\t\t(\n\n\t\t\t\t\"OTHERWISE_CHANGED\",\n\n\t\t\t\tOsString::from(\n\n\t\t\t\t\t\"\".to_string()\n\n\t\t\t\t\t\t+ \"0123.txt\" + ENV_SEP + \"a.txt\"\n\n\t\t\t\t\t\t+ ENV_SEP + \"b.txt\" + ENV_SEP\n\n\t\t\t\t\t\t+ \"c.txt\" + ENV_SEP + \"ᄁ.txt\"\n\n\t\t\t\t)\n\n\t\t\t),\n\n\t\t\t(\"COMMON\", ospath(\"\")),\n\n\t\t])\n\n\t);\n\n}\n", "file_path": "lib/tests/env_reporting.rs", "rank": 31, "score": 50147.45877662071 }, { "content": "#[test]\n\nfn negate() {\n\n\tassert_eq!(\n\n\t\tfilter(\"!path~=^f[om]+$\"),\n\n\t\tFilter {\n\n\t\t\tin_path: None,\n\n\t\t\ton: Matcher::Path,\n\n\t\t\top: Op::Regex,\n\n\t\t\tpat: Pattern::Regex(Regex::new(\"^f[om]+$\").unwrap()),\n\n\t\t\tnegate: true,\n\n\t\t}\n\n\t);\n\n}\n", "file_path": "lib/tests/filter_tagged_parser.rs", "rank": 32, "score": 50147.45877662071 }, { "content": "#[test]\n\nfn only_bang() {\n\n\tassert!(matches!(\n\n\t\tFilter::from_str(\"!\"),\n\n\t\tErr(TaggedFiltererError::Parse { .. })\n\n\t));\n\n}\n\n\n", "file_path": "lib/tests/filter_tagged_parser.rs", "rank": 33, "score": 50147.45877662071 }, { "content": "#[test]\n\nfn no_op() {\n\n\tassert!(matches!(\n\n\t\tFilter::from_str(\"foobar\"),\n\n\t\tErr(TaggedFiltererError::Parse { .. })\n\n\t));\n\n}\n\n\n", "file_path": "lib/tests/filter_tagged_parser.rs", "rank": 34, "score": 50147.45877662071 }, { "content": "#[cfg(test)]\n\n#[test]\n\nfn os_strip_only_once() {\n\n\tlet os = OsString::from(\"..abc\");\n\n\tassert_eq!(os_strip_prefix(os, b'.'), OsString::from(\".abc\"));\n\n}\n", "file_path": "cli/src/filterer/globset.rs", "rank": 35, "score": 50147.45877662071 }, { "content": "#[test]\n\nfn single_written() {\n\n\tlet events = vec![event(\n\n\t\t\"file.txt\",\n\n\t\tFileEventKind::Modify(ModifyKind::Data(DataChange::Any)),\n\n\t)];\n\n\tassert_eq!(\n\n\t\tsummarise_events_to_env(&events),\n\n\t\tHashMap::from([\n\n\t\t\t(\"WRITTEN\", OsString::from(\"file.txt\")),\n\n\t\t\t(\"COMMON\", ospath(\"\")),\n\n\t\t])\n\n\t);\n\n}\n\n\n", "file_path": "lib/tests/env_reporting.rs", "rank": 36, "score": 50147.45877662071 }, { "content": "#[test]\n\nfn single_removed() {\n\n\tlet events = vec![event(\"file.txt\", FileEventKind::Remove(RemoveKind::File))];\n\n\tassert_eq!(\n\n\t\tsummarise_events_to_env(&events),\n\n\t\tHashMap::from([\n\n\t\t\t(\"REMOVED\", OsString::from(\"file.txt\")),\n\n\t\t\t(\"COMMON\", ospath(\"\")),\n\n\t\t])\n\n\t);\n\n}\n\n\n", "file_path": "lib/tests/env_reporting.rs", "rank": 37, "score": 50147.45877662071 }, { "content": "#[test]\n\nfn single_renamed() {\n\n\tlet events = vec![event(\n\n\t\t\"file.txt\",\n\n\t\tFileEventKind::Modify(ModifyKind::Name(RenameMode::Any)),\n\n\t)];\n\n\tassert_eq!(\n\n\t\tsummarise_events_to_env(&events),\n\n\t\tHashMap::from([\n\n\t\t\t(\"RENAMED\", OsString::from(\"file.txt\")),\n\n\t\t\t(\"COMMON\", ospath(\"\")),\n\n\t\t])\n\n\t);\n\n}\n\n\n", "file_path": "lib/tests/env_reporting.rs", "rank": 38, "score": 50147.45877662071 }, { "content": "#[test]\n\nfn single_created() {\n\n\tlet events = vec![event(\"file.txt\", FileEventKind::Create(CreateKind::File))];\n\n\tassert_eq!(\n\n\t\tsummarise_events_to_env(&events),\n\n\t\tHashMap::from([\n\n\t\t\t(\"CREATED\", OsString::from(\"file.txt\")),\n\n\t\t\t(\"COMMON\", ospath(\"\")),\n\n\t\t])\n\n\t);\n\n}\n\n\n", "file_path": "lib/tests/env_reporting.rs", "rank": 39, "score": 50147.45877662071 }, { "content": "#[test]\n\nfn single_otherwise() {\n\n\tlet events = vec![event(\"file.txt\", FileEventKind::Any)];\n\n\tassert_eq!(\n\n\t\tsummarise_events_to_env(&events),\n\n\t\tHashMap::from([\n\n\t\t\t(\"OTHERWISE_CHANGED\", OsString::from(\"file.txt\")),\n\n\t\t\t(\"COMMON\", ospath(\"\")),\n\n\t\t])\n\n\t);\n\n}\n\n\n", "file_path": "lib/tests/env_reporting.rs", "rank": 40, "score": 50147.45877662071 }, { "content": "#[test]\n\nfn empty_filter() {\n\n\tassert!(matches!(\n\n\t\tFilter::from_str(\"\"),\n\n\t\tErr(TaggedFiltererError::Parse { .. })\n\n\t));\n\n}\n\n\n", "file_path": "lib/tests/filter_tagged_parser.rs", "rank": 41, "score": 48956.837988593354 }, { "content": "#[test]\n\nfn other_auto_op() {\n\n\tassert_eq!(\n\n\t\tfilter(\"type=foo\"),\n\n\t\tFilter {\n\n\t\t\tin_path: None,\n\n\t\t\ton: Matcher::FileType,\n\n\t\t\top: Op::InSet,\n\n\t\t\tpat: Pattern::Set(HashSet::from([\"foo\".to_string()])),\n\n\t\t\tnegate: false,\n\n\t\t}\n\n\t);\n\n}\n\n\n", "file_path": "lib/tests/filter_tagged_parser.rs", "rank": 42, "score": 48956.837988593354 }, { "content": "#[cfg(test)]\n\n#[test]\n\nfn os_split_multi() {\n\n\tlet os = OsString::from(\"a,b,c\");\n\n\tassert_eq!(\n\n\t\tos.split(b',').collect::<Vec<OsString>>(),\n\n\t\tvec![\n\n\t\t\tOsString::from(\"a\"),\n\n\t\t\tOsString::from(\"b\"),\n\n\t\t\tOsString::from(\"c\"),\n\n\t\t]\n\n\t);\n\n\n\n\tlet mut split = os.split(b',');\n\n\tassert_eq!(split.next(), Some(OsString::from(\"a\")));\n\n\tassert_eq!(split.next(), Some(OsString::from(\"b\")));\n\n\tassert_eq!(split.next(), Some(OsString::from(\"c\")));\n\n\tassert_eq!(split.next(), None);\n\n}\n\n\n", "file_path": "cli/src/filterer/globset.rs", "rank": 43, "score": 48956.837988593354 }, { "content": "#[test]\n\nfn op_in_set() {\n\n\tassert_eq!(\n\n\t\tfilter(\"path:=foo,bar\"),\n\n\t\tFilter {\n\n\t\t\tin_path: None,\n\n\t\t\ton: Matcher::Path,\n\n\t\t\top: Op::InSet,\n\n\t\t\tpat: Pattern::Set(HashSet::from([\"foo\".to_string(), \"bar\".to_string()])),\n\n\t\t\tnegate: false,\n\n\t\t}\n\n\t);\n\n}\n\n\n", "file_path": "lib/tests/filter_tagged_parser.rs", "rank": 44, "score": 48956.837988593354 }, { "content": "#[test]\n\nfn single_type_multipath() {\n\n\tlet events = vec![\n\n\t\tevent(\"root.txt\", FileEventKind::Create(CreateKind::File)),\n\n\t\tevent(\"sub/folder.txt\", FileEventKind::Create(CreateKind::File)),\n\n\t\tevent(\"dom/folder.txt\", FileEventKind::Create(CreateKind::File)),\n\n\t\tevent(\n\n\t\t\t\"deeper/sub/folder.txt\",\n\n\t\t\tFileEventKind::Create(CreateKind::File),\n\n\t\t),\n\n\t];\n\n\tassert_eq!(\n\n\t\tsummarise_events_to_env(&events),\n\n\t\tHashMap::from([\n\n\t\t\t(\n\n\t\t\t\t\"CREATED\",\n\n\t\t\t\tOsString::from(\n\n\t\t\t\t\t\"\".to_string()\n\n\t\t\t\t\t\t+ \"deeper/sub/folder.txt\"\n\n\t\t\t\t\t\t+ ENV_SEP + \"dom/folder.txt\"\n\n\t\t\t\t\t\t+ ENV_SEP + \"root.txt\" + ENV_SEP\n\n\t\t\t\t\t\t+ \"sub/folder.txt\"\n\n\t\t\t\t)\n\n\t\t\t),\n\n\t\t\t(\"COMMON\", ospath(\"\")),\n\n\t\t])\n\n\t);\n\n}\n\n\n", "file_path": "lib/tests/env_reporting.rs", "rank": 45, "score": 48956.837988593354 }, { "content": "#[test]\n\nfn op_not_in_set() {\n\n\tassert_eq!(\n\n\t\tfilter(\"path:!baz,qux\"),\n\n\t\tFilter {\n\n\t\t\tin_path: None,\n\n\t\t\ton: Matcher::Path,\n\n\t\t\top: Op::NotInSet,\n\n\t\t\tpat: Pattern::Set(HashSet::from([\"baz\".to_string(), \"qux\".to_string()])),\n\n\t\t\tnegate: false,\n\n\t\t}\n\n\t);\n\n}\n\n\n", "file_path": "lib/tests/filter_tagged_parser.rs", "rank": 46, "score": 48956.837988593354 }, { "content": "#[test]\n\nfn only_non_paths_events() {\n\n\tlet events = vec![\n\n\t\tEvent {\n\n\t\t\ttags: vec![Tag::Process(1234)],\n\n\t\t\tmetadata: Default::default(),\n\n\t\t},\n\n\t\tEvent {\n\n\t\t\ttags: vec![Tag::FileEventKind(FileEventKind::Any)],\n\n\t\t\tmetadata: Default::default(),\n\n\t\t},\n\n\t];\n\n\tassert_eq!(summarise_events_to_env(&events), HashMap::new());\n\n}\n\n\n", "file_path": "lib/tests/env_reporting.rs", "rank": 47, "score": 48956.837988593354 }, { "content": "#[cfg(test)]\n\n#[test]\n\nfn os_strip_not_right() {\n\n\tlet os = OsString::from(\"abc.\");\n\n\tassert_eq!(os_strip_prefix(os, b'.'), OsString::from(\"abc.\"));\n\n}\n\n\n", "file_path": "cli/src/filterer/globset.rs", "rank": 48, "score": 48956.837988593354 }, { "content": "#[test]\n\nfn op_not_regex() {\n\n\tassert_eq!(\n\n\t\tfilter(\"path~!f(o|al)+\"),\n\n\t\tFilter {\n\n\t\t\tin_path: None,\n\n\t\t\ton: Matcher::Path,\n\n\t\t\top: Op::NotRegex,\n\n\t\t\tpat: Pattern::Regex(Regex::new(\"f(o|al)+\").unwrap()),\n\n\t\t\tnegate: false,\n\n\t\t}\n\n\t);\n\n}\n\n\n", "file_path": "lib/tests/filter_tagged_parser.rs", "rank": 49, "score": 48956.837988593354 }, { "content": "#[cfg(test)]\n\n#[test]\n\nfn os_strip_left() {\n\n\tlet os = OsString::from(\".abc\");\n\n\tassert_eq!(os_strip_prefix(os, b'.'), OsString::from(\"abc\"));\n\n}\n\n\n", "file_path": "cli/src/filterer/globset.rs", "rank": 50, "score": 48956.837988593354 }, { "content": "#[test]\n\nfn op_not_equal() {\n\n\tassert_eq!(\n\n\t\tfilter(\"path!=foo\"),\n\n\t\tFilter {\n\n\t\t\tin_path: None,\n\n\t\t\ton: Matcher::Path,\n\n\t\t\top: Op::NotEqual,\n\n\t\t\tpat: Pattern::Exact(\"foo\".to_string()),\n\n\t\t\tnegate: false,\n\n\t\t}\n\n\t);\n\n}\n\n\n", "file_path": "lib/tests/filter_tagged_parser.rs", "rank": 51, "score": 48956.837988593354 }, { "content": "#[cfg(test)]\n\n#[test]\n\nfn os_split_one() {\n\n\tlet os = OsString::from(\"abc\");\n\n\tassert_eq!(\n\n\t\tos.split(b',').collect::<Vec<OsString>>(),\n\n\t\tvec![OsString::from(\"abc\")]\n\n\t);\n\n\n\n\tlet mut split = os.split(b',');\n\n\tassert_eq!(split.next(), Some(OsString::from(\"abc\")));\n\n\tassert_eq!(split.next(), None);\n\n}\n\n\n", "file_path": "cli/src/filterer/globset.rs", "rank": 52, "score": 48956.837988593354 }, { "content": "#[test]\n\nfn op_not_glob() {\n\n\tassert_eq!(\n\n\t\tfilter(\"path*!foo.*\"),\n\n\t\tFilter {\n\n\t\t\tin_path: None,\n\n\t\t\ton: Matcher::Path,\n\n\t\t\top: Op::NotGlob,\n\n\t\t\tpat: Pattern::Glob(\"foo.*\".to_string()),\n\n\t\t\tnegate: false,\n\n\t\t}\n\n\t);\n\n}\n\n\n", "file_path": "lib/tests/filter_tagged_parser.rs", "rank": 53, "score": 48956.837988593354 }, { "content": "#[test]\n\nfn op_regex() {\n\n\tassert_eq!(\n\n\t\tfilter(\"path~=^fo+$\"),\n\n\t\tFilter {\n\n\t\t\tin_path: None,\n\n\t\t\ton: Matcher::Path,\n\n\t\t\top: Op::Regex,\n\n\t\t\tpat: Pattern::Regex(Regex::new(\"^fo+$\").unwrap()),\n\n\t\t\tnegate: false,\n\n\t\t}\n\n\t);\n\n}\n\n\n", "file_path": "lib/tests/filter_tagged_parser.rs", "rank": 54, "score": 48956.837988593354 }, { "content": "#[test]\n\nfn op_equal() {\n\n\tassert_eq!(\n\n\t\tfilter(\"path==foo\"),\n\n\t\tFilter {\n\n\t\t\tin_path: None,\n\n\t\t\ton: Matcher::Path,\n\n\t\t\top: Op::Equal,\n\n\t\t\tpat: Pattern::Exact(\"foo\".to_string()),\n\n\t\t\tnegate: false,\n\n\t\t}\n\n\t);\n\n}\n\n\n", "file_path": "lib/tests/filter_tagged_parser.rs", "rank": 55, "score": 48956.837988593354 }, { "content": "fn notify_multi_path_errors(\n\n\tkind: Watcher,\n\n\tpath: WatchedPath,\n\n\tmut err: notify::Error,\n\n\trm: bool,\n\n) -> Vec<RuntimeError> {\n\n\tlet mut paths = take(&mut err.paths);\n\n\tif paths.is_empty() {\n\n\t\tpaths.push(path.into());\n\n\t}\n\n\n\n\tlet generic = err.to_string();\n\n\tlet mut err = Some(err);\n\n\n\n\tlet mut errs = Vec::with_capacity(paths.len());\n\n\tfor path in paths {\n\n\t\tlet e = err\n\n\t\t\t.take()\n\n\t\t\t.unwrap_or_else(|| notify::Error::generic(&generic))\n\n\t\t\t.add_path(path.clone());\n", "file_path": "lib/src/fs.rs", "rank": 56, "score": 48956.837988593354 }, { "content": "#[cfg(test)]\n\n#[test]\n\nfn os_strip_only_left() {\n\n\tlet os = OsString::from(\".abc.\");\n\n\tassert_eq!(os_strip_prefix(os, b'.'), OsString::from(\"abc.\"));\n\n}\n\n\n", "file_path": "cli/src/filterer/globset.rs", "rank": 57, "score": 48956.837988593354 }, { "content": "#[cfg(test)]\n\n#[test]\n\nfn os_split_leading() {\n\n\tlet os = OsString::from(\",a,b,c\");\n\n\tassert_eq!(\n\n\t\tos.split(b',').collect::<Vec<OsString>>(),\n\n\t\tvec![\n\n\t\t\tOsString::from(\"\"),\n\n\t\t\tOsString::from(\"a\"),\n\n\t\t\tOsString::from(\"b\"),\n\n\t\t\tOsString::from(\"c\"),\n\n\t\t]\n\n\t);\n\n\n\n\tlet mut split = os.split(b',');\n\n\tassert_eq!(split.next(), Some(OsString::from(\"\")));\n\n\tassert_eq!(split.next(), Some(OsString::from(\"a\")));\n\n\tassert_eq!(split.next(), Some(OsString::from(\"b\")));\n\n\tassert_eq!(split.next(), Some(OsString::from(\"c\")));\n\n\tassert_eq!(split.next(), None);\n\n}\n\n\n", "file_path": "cli/src/filterer/globset.rs", "rank": 58, "score": 48956.837988593354 }, { "content": "#[test]\n\nfn quoted_single() {\n\n\tassert_eq!(\n\n\t\tfilter(\"path='blanche neige'\"),\n\n\t\tFilter {\n\n\t\t\tin_path: None,\n\n\t\t\ton: Matcher::Path,\n\n\t\t\top: Op::Glob,\n\n\t\t\tpat: Pattern::Glob(\"blanche neige\".to_string()),\n\n\t\t\tnegate: false,\n\n\t\t}\n\n\t);\n\n}\n\n\n", "file_path": "lib/tests/filter_tagged_parser.rs", "rank": 59, "score": 48956.837988593354 }, { "content": "#[test]\n\nfn op_glob() {\n\n\tassert_eq!(\n\n\t\tfilter(\"path*=**/foo\"),\n\n\t\tFilter {\n\n\t\t\tin_path: None,\n\n\t\t\ton: Matcher::Path,\n\n\t\t\top: Op::Glob,\n\n\t\t\tpat: Pattern::Glob(\"**/foo\".to_string()),\n\n\t\t\tnegate: false,\n\n\t\t}\n\n\t);\n\n}\n\n\n", "file_path": "lib/tests/filter_tagged_parser.rs", "rank": 60, "score": 48956.837988593354 }, { "content": "#[test]\n\nfn quoted_double() {\n\n\tassert_eq!(\n\n\t\tfilter(\"path=\\\"et les sept nains\\\"\"),\n\n\t\tFilter {\n\n\t\t\tin_path: None,\n\n\t\t\ton: Matcher::Path,\n\n\t\t\top: Op::Glob,\n\n\t\t\tpat: Pattern::Glob(\"et les sept nains\".to_string()),\n\n\t\t\tnegate: false,\n\n\t\t}\n\n\t);\n\n}\n\n\n", "file_path": "lib/tests/filter_tagged_parser.rs", "rank": 61, "score": 48956.837988593354 }, { "content": "#[test]\n\nfn fek_auto_op() {\n\n\tassert_eq!(\n\n\t\tfilter(\"fek=foo\"),\n\n\t\tFilter {\n\n\t\t\tin_path: None,\n\n\t\t\ton: Matcher::FileEventKind,\n\n\t\t\top: Op::Glob,\n\n\t\t\tpat: Pattern::Glob(\"foo\".to_string()),\n\n\t\t\tnegate: false,\n\n\t\t}\n\n\t);\n\n}\n\n\n", "file_path": "lib/tests/filter_tagged_parser.rs", "rank": 62, "score": 47847.65936038135 }, { "content": "#[test]\n\nfn multiple_paths_in_one_event() {\n\n\tlet events = vec![Event {\n\n\t\ttags: vec![\n\n\t\t\tTag::Path {\n\n\t\t\t\tpath: ospath(\"one.txt\").into(),\n\n\t\t\t\tfile_type: None,\n\n\t\t\t},\n\n\t\t\tTag::Path {\n\n\t\t\t\tpath: ospath(\"two.txt\").into(),\n\n\t\t\t\tfile_type: None,\n\n\t\t\t},\n\n\t\t\tTag::FileEventKind(FileEventKind::Any),\n\n\t\t],\n\n\t\tmetadata: Default::default(),\n\n\t}];\n\n\tassert_eq!(\n\n\t\tsummarise_events_to_env(&events),\n\n\t\tHashMap::from([\n\n\t\t\t(\n\n\t\t\t\t\"OTHERWISE_CHANGED\",\n\n\t\t\t\tOsString::from(\"\".to_string() + \"one.txt\" + ENV_SEP + \"two.txt\")\n\n\t\t\t),\n\n\t\t\t(\"COMMON\", ospath(\"\")),\n\n\t\t])\n\n\t);\n\n}\n\n\n", "file_path": "lib/tests/env_reporting.rs", "rank": 63, "score": 47847.65936038135 }, { "content": "#[test]\n\nfn single_type_divergent_paths() {\n\n\tlet events = vec![\n\n\t\tevent(\"sub/folder.txt\", FileEventKind::Create(CreateKind::File)),\n\n\t\tevent(\"dom/folder.txt\", FileEventKind::Create(CreateKind::File)),\n\n\t];\n\n\tassert_eq!(\n\n\t\tsummarise_events_to_env(&events),\n\n\t\tHashMap::from([\n\n\t\t\t(\n\n\t\t\t\t\"CREATED\",\n\n\t\t\t\tOsString::from(\"\".to_string() + \"dom/folder.txt\" + ENV_SEP + \"sub/folder.txt\")\n\n\t\t\t),\n\n\t\t\t(\"COMMON\", ospath(\"\")),\n\n\t\t])\n\n\t);\n\n}\n\n\n", "file_path": "lib/tests/env_reporting.rs", "rank": 64, "score": 47847.65936038135 }, { "content": "#[test]\n\nfn path_auto_op() {\n\n\tassert_eq!(\n\n\t\tfilter(\"path=foo\"),\n\n\t\tFilter {\n\n\t\t\tin_path: None,\n\n\t\t\ton: Matcher::Path,\n\n\t\t\top: Op::Glob,\n\n\t\t\tpat: Pattern::Glob(\"foo\".to_string()),\n\n\t\t\tnegate: false,\n\n\t\t}\n\n\t);\n\n}\n\n\n", "file_path": "lib/tests/filter_tagged_parser.rs", "rank": 65, "score": 47847.65936038135 }, { "content": "#[test]\n\nfn mixed_non_paths_events() {\n\n\tlet events = vec![\n\n\t\tevent(\"one.txt\", FileEventKind::Any),\n\n\t\tEvent {\n\n\t\t\ttags: vec![Tag::Process(1234)],\n\n\t\t\tmetadata: Default::default(),\n\n\t\t},\n\n\t\tevent(\"two.txt\", FileEventKind::Any),\n\n\t\tEvent {\n\n\t\t\ttags: vec![Tag::FileEventKind(FileEventKind::Any)],\n\n\t\t\tmetadata: Default::default(),\n\n\t\t},\n\n\t];\n\n\tassert_eq!(\n\n\t\tsummarise_events_to_env(&events),\n\n\t\tHashMap::from([\n\n\t\t\t(\n\n\t\t\t\t\"OTHERWISE_CHANGED\",\n\n\t\t\t\tOsString::from(\"\".to_string() + \"one.txt\" + ENV_SEP + \"two.txt\")\n\n\t\t\t),\n\n\t\t\t(\"COMMON\", ospath(\"\")),\n\n\t\t])\n\n\t);\n\n}\n\n\n", "file_path": "lib/tests/env_reporting.rs", "rank": 66, "score": 47847.65936038135 }, { "content": "/// An interface for filtering events.\n\npub trait Filterer: std::fmt::Debug + Send + Sync {\n\n\t/// Called on (almost) every event, and should return `false` if the event is to be discarded.\n\n\t///\n\n\t/// Checking whether an event passes a filter is synchronous, should be fast, and must not block\n\n\t/// the thread. Do any expensive stuff upfront during construction of your filterer, or in a\n\n\t/// separate thread/task, as needed.\n\n\t///\n\n\t/// Returning an error will also fail the event processing, but the error will be propagated to\n\n\t/// the watchexec error handler. While the type signature supports any [`RuntimeError`], it's\n\n\t/// preferred that you create your own error type and return it wrapped in the\n\n\t/// [`RuntimeError::Filterer`] variant with the name of your filterer as `kind`.\n\n\tfn check_event(&self, event: &Event) -> Result<bool, RuntimeError>;\n\n}\n\n\n\nimpl Filterer for () {\n\n\tfn check_event(&self, _event: &Event) -> Result<bool, RuntimeError> {\n\n\t\tOk(true)\n\n\t}\n\n}\n\n\n\nimpl<T: Filterer> Filterer for Arc<T> {\n\n\tfn check_event(&self, event: &Event) -> Result<bool, RuntimeError> {\n\n\t\tArc::as_ref(self).check_event(event)\n\n\t}\n\n}\n\n\n", "file_path": "lib/src/filter.rs", "rank": 67, "score": 44109.83901073749 }, { "content": "#[cfg(windows)]\n\nfn cmd_shell(_: String) -> Shell {\n\n\tShell::Cmd\n\n}\n\n\n", "file_path": "cli/src/config/runtime.rs", "rank": 68, "score": 43448.72650824336 }, { "content": "#[cfg(not(windows))]\n\nfn cmd_shell(s: String) -> Shell {\n\n\tShell::Unix(s)\n\n}\n", "file_path": "cli/src/config/runtime.rs", "rank": 69, "score": 43448.72650824336 }, { "content": "fn ospath(path: &str) -> OsString {\n\n\tlet root = dunce::canonicalize(\".\").unwrap();\n\n\tif path.is_empty() {\n\n\t\troot\n\n\t} else {\n\n\t\troot.join(path)\n\n\t}\n\n\t.into()\n\n}\n\n\n", "file_path": "lib/tests/env_reporting.rs", "rank": 70, "score": 42412.91004325748 }, { "content": "fn folders_suite(filterer: &IgnoreFilterer, name: &str) {\n\n\tfilterer.file_does_pass(\"apples\");\n\n\tfilterer.file_does_pass(\"apples/carrots/cauliflowers/oranges\");\n\n\tfilterer.file_does_pass(\"apples/carrots/cauliflowers/artichokes/oranges\");\n\n\tfilterer.file_does_pass(\"apples/oranges/bananas\");\n\n\tfilterer.dir_does_pass(\"apples\");\n\n\tfilterer.dir_does_pass(\"apples/carrots/cauliflowers/oranges\");\n\n\tfilterer.dir_does_pass(\"apples/carrots/cauliflowers/artichokes/oranges\");\n\n\n\n\tfilterer.file_does_pass(&format!(\"raw-{}\", name));\n\n\tfilterer.dir_does_pass(&format!(\"raw-{}\", name));\n\n\tfilterer.file_does_pass(&format!(\"raw-{}/carrots/cauliflowers/oranges\", name));\n\n\tfilterer.file_does_pass(&format!(\"raw-{}/oranges/bananas\", name));\n\n\tfilterer.dir_does_pass(&format!(\"raw-{}/carrots/cauliflowers/oranges\", name));\n\n\tfilterer.file_does_pass(&format!(\n\n\t\t\"raw-{}/carrots/cauliflowers/artichokes/oranges\",\n\n\t\tname\n\n\t));\n\n\tfilterer.dir_does_pass(&format!(\n\n\t\t\"raw-{}/carrots/cauliflowers/artichokes/oranges\",\n", "file_path": "lib/tests/filter_ignorefiles.rs", "rank": 71, "score": 39545.73737798694 }, { "content": "fn watchexec_v1_confusing_suite(filterer: Arc<TaggedFilterer>) {\n\n\tfilterer.file_does_pass(\"apples\");\n\n\tfilterer.file_does_pass(\"apples/carrots/cauliflowers/oranges\");\n\n\tfilterer.file_does_pass(\"apples/carrots/cauliflowers/artichokes/oranges\");\n\n\tfilterer.file_does_pass(\"apples/oranges/bananas\");\n\n\tfilterer.dir_does_pass(\"apples\");\n\n\tfilterer.dir_does_pass(\"apples/carrots/cauliflowers/oranges\");\n\n\tfilterer.dir_does_pass(\"apples/carrots/cauliflowers/artichokes/oranges\");\n\n\n\n\tfilterer.file_does_pass(\"raw-prunes\");\n\n\tfilterer.dir_does_pass(\"raw-prunes\");\n\n\tfilterer.file_does_pass(\"raw-prunes/carrots/cauliflowers/oranges\");\n\n\tfilterer.file_does_pass(\"raw-prunes/carrots/cauliflowers/artichokes/oranges\");\n\n\tfilterer.file_does_pass(\"raw-prunes/oranges/bananas\");\n\n\tfilterer.dir_does_pass(\"raw-prunes/carrots/cauliflowers/oranges\");\n\n\tfilterer.dir_does_pass(\"raw-prunes/carrots/cauliflowers/artichokes/oranges\");\n\n\n\n\tfilterer.dir_doesnt_pass(\"prunes/carrots/cauliflowers/oranges\");\n\n\tfilterer.dir_doesnt_pass(\"prunes/carrots/cauliflowers/artichokes/oranges\");\n\n\tfilterer.file_doesnt_pass(\"prunes/carrots/cauliflowers/oranges\");\n", "file_path": "lib/tests/filter_tagged_paths.rs", "rank": 72, "score": 38874.70475980511 }, { "content": "fn event(path: &str, kind: FileEventKind) -> Event {\n\n\tEvent {\n\n\t\ttags: vec![\n\n\t\t\tTag::Path {\n\n\t\t\t\tpath: ospath(path).into(),\n\n\t\t\t\tfile_type: None,\n\n\t\t\t},\n\n\t\t\tTag::FileEventKind(kind),\n\n\t\t],\n\n\t\tmetadata: Default::default(),\n\n\t}\n\n}\n\n\n", "file_path": "lib/tests/env_reporting.rs", "rank": 73, "score": 37851.73017418847 }, { "content": "\t/// # // we don't have a direct nix dependency, so we fake it... rather horribly\n\n\t/// # mod nix { pub mod sys { pub mod signal { pub use command_group::Signal; } } }\n\n\t/// use watchexec::signal::process::SubSignal;\n\n\t/// use nix::sys::signal::Signal;\n\n\t/// assert_eq!(SubSignal::Custom(6), SubSignal::from_nix(Signal::SIGABRT));\n\n\t/// # }\n\n\t/// ```\n\n\tCustom(i32),\n\n}\n\n\n\nimpl SubSignal {\n\n\t/// Converts to a [`nix::Signal`][command_group::Signal] if possible.\n\n\t///\n\n\t/// This will return `None` if the signal is not supported on the current platform (only for\n\n\t/// [`Custom`][SubSignal::Custom], as the first-class ones are always supported).\n\n\t#[cfg(unix)]\n\n\tpub fn to_nix(self) -> Option<NixSignal> {\n\n\t\tmatch self {\n\n\t\t\tSelf::Hangup => Some(NixSignal::SIGHUP),\n\n\t\t\tSelf::ForceStop => Some(NixSignal::SIGKILL),\n", "file_path": "lib/src/signal/process.rs", "rank": 79, "score": 36876.20802857025 }, { "content": "\tfn from_str(s: &str) -> Result<Self, Self::Err> {\n\n\t\tif let Ok(sig) = i32::from_str(s) {\n\n\t\t\tif let Ok(sig) = NixSignal::try_from(sig) {\n\n\t\t\t\treturn Ok(Self::from_nix(sig));\n\n\t\t\t}\n\n\t\t}\n\n\n\n\t\tif let Ok(sig) = NixSignal::from_str(&s.to_ascii_uppercase())\n\n\t\t\t.or_else(|_| NixSignal::from_str(&format!(\"SIG{}\", s.to_ascii_uppercase())))\n\n\t\t{\n\n\t\t\treturn Ok(Self::from_nix(sig));\n\n\t\t}\n\n\n\n\t\tErr(SignalParseError::new(s, \"unsupported signal\"))\n\n\t}\n\n\n\n\t#[cfg(windows)]\n\n\tfn from_str(s: &str) -> Result<Self, Self::Err> {\n\n\t\tmatch s.to_ascii_uppercase().as_str() {\n\n\t\t\t\"CTRL-CLOSE\" | \"CTRL+CLOSE\" | \"CLOSE\" => Ok(Self::Hangup),\n", "file_path": "lib/src/signal/process.rs", "rank": 80, "score": 36872.50813866565 }, { "content": "\t\t\tsig => Self::Custom(sig as _),\n\n\t\t}\n\n\t}\n\n}\n\n\n\nimpl From<MainSignal> for SubSignal {\n\n\tfn from(main: MainSignal) -> Self {\n\n\t\tmatch main {\n\n\t\t\tMainSignal::Hangup => Self::Hangup,\n\n\t\t\tMainSignal::Interrupt => Self::Interrupt,\n\n\t\t\tMainSignal::Quit => Self::Quit,\n\n\t\t\tMainSignal::Terminate => Self::Terminate,\n\n\t\t\tMainSignal::User1 => Self::User1,\n\n\t\t\tMainSignal::User2 => Self::User2,\n\n\t\t}\n\n\t}\n\n}\n\n\n\nimpl From<i32> for SubSignal {\n\n\t/// Converts from a raw signal number.\n", "file_path": "lib/src/signal/process.rs", "rank": 81, "score": 36871.68771652509 }, { "content": "\t\t\tSelf::Interrupt => Some(NixSignal::SIGINT),\n\n\t\t\tSelf::Quit => Some(NixSignal::SIGQUIT),\n\n\t\t\tSelf::Terminate => Some(NixSignal::SIGTERM),\n\n\t\t\tSelf::User1 => Some(NixSignal::SIGUSR1),\n\n\t\t\tSelf::User2 => Some(NixSignal::SIGUSR2),\n\n\t\t\tSelf::Custom(sig) => NixSignal::try_from(sig).ok(),\n\n\t\t}\n\n\t}\n\n\n\n\t/// Converts from a [`nix::Signal`][command_group::Signal].\n\n\t#[cfg(unix)]\n\n\tpub fn from_nix(sig: NixSignal) -> Self {\n\n\t\tmatch sig {\n\n\t\t\tNixSignal::SIGHUP => Self::Hangup,\n\n\t\t\tNixSignal::SIGKILL => Self::ForceStop,\n\n\t\t\tNixSignal::SIGINT => Self::Interrupt,\n\n\t\t\tNixSignal::SIGQUIT => Self::Quit,\n\n\t\t\tNixSignal::SIGTERM => Self::Terminate,\n\n\t\t\tNixSignal::SIGUSR1 => Self::User1,\n\n\t\t\tNixSignal::SIGUSR2 => Self::User2,\n", "file_path": "lib/src/signal/process.rs", "rank": 84, "score": 36870.64147907375 }, { "content": "\t///\n\n\t/// This uses hardcoded numbers for the first-class signals.\n\n\tfn from(raw: i32) -> Self {\n\n\t\tmatch raw {\n\n\t\t\t1 => Self::Hangup,\n\n\t\t\t2 => Self::Interrupt,\n\n\t\t\t3 => Self::Quit,\n\n\t\t\t9 => Self::ForceStop,\n\n\t\t\t10 => Self::User1,\n\n\t\t\t12 => Self::User2,\n\n\t\t\t15 => Self::Terminate,\n\n\t\t\t_ => Self::Custom(raw),\n\n\t\t}\n\n\t}\n\n}\n\n\n\nimpl FromStr for SubSignal {\n\n\ttype Err = SignalParseError;\n\n\n\n\t#[cfg(unix)]\n", "file_path": "lib/src/signal/process.rs", "rank": 85, "score": 36870.414737408086 }, { "content": "\t///\n\n\t/// # Examples\n\n\t///\n\n\t/// ```\n\n\t/// # // we don't have a direct nix dependency, so we fake it... rather horribly\n\n\t/// # mod nix { pub mod sys { pub mod signal {\n\n\t/// # #[cfg(unix)] pub use command_group::Signal;\n\n\t/// # #[cfg(not(unix))] #[repr(i32)] pub enum Signal { SIGABRT = 6 }\n\n\t/// # } } }\n\n\t/// use watchexec::signal::process::SubSignal;\n\n\t/// use nix::sys::signal::Signal;\n\n\t/// assert_eq!(SubSignal::Custom(6), SubSignal::from(Signal::SIGABRT as i32));\n\n\t/// ```\n\n\t///\n\n\t/// On Unix the [`from_nix`][SubSignal::from_nix] method should be preferred if converting from\n\n\t/// Nix's `Signal` type:\n\n\t///\n\n\t/// ```\n\n\t/// # #[cfg(unix)]\n\n\t/// # {\n", "file_path": "lib/src/signal/process.rs", "rank": 86, "score": 36869.77184873836 }, { "content": "\t\t\t\"CTRL-BREAK\" | \"CTRL+BREAK\" | \"BREAK\" => Ok(Self::Terminate),\n\n\t\t\t\"CTRL-C\" | \"CTRL+C\" | \"C\" => Ok(Self::Interrupt),\n\n\t\t\t\"KILL\" | \"SIGKILL\" | \"FORCE-STOP\" | \"STOP\" => Ok(Self::ForceStop),\n\n\t\t\t_ => Err(SignalParseError::new(s, \"unknown control name\")),\n\n\t\t}\n\n\t}\n\n\n\n\t#[cfg(not(any(unix, windows)))]\n\n\tfn from_str(s: &str) -> Result<Self, Self::Err> {\n\n\t\tErr(SignalParseError::new(s, \"no signals supported\"))\n\n\t}\n\n}\n", "file_path": "lib/src/signal/process.rs", "rank": 87, "score": 36866.55519197176 }, { "content": "//! Types for cross-platform and cross-purpose handling of subprocess signals.\n\n\n\nuse std::str::FromStr;\n\n\n\n#[cfg(unix)]\n\nuse command_group::Signal as NixSignal;\n\n\n\nuse crate::error::SignalParseError;\n\n\n\nuse super::source::MainSignal;\n\n\n\n/// A notification sent to a subprocess.\n\n///\n\n/// On Windows, only some signals are supported, as described. Others will be ignored.\n\n///\n\n/// On Unix, there are several \"first-class\" signals which have their own variants, and a generic\n\n/// [`Custom`][SubSignal::Custom] variant which can be used to send arbitrary signals.\n\n#[derive(Clone, Copy, Debug, PartialEq, Eq)]\n\npub enum SubSignal {\n\n\t/// Indicate that the terminal is disconnected.\n", "file_path": "lib/src/signal/process.rs", "rank": 88, "score": 36865.67845773017 }, { "content": "\t///\n\n\t/// On Unix, this is `SIGHUP`. On Windows, this is ignored for now but may be supported in the\n\n\t/// future (see [#219](https://github.com/watchexec/watchexec/issues/219)).\n\n\t///\n\n\t/// Despite its nominal purpose, on Unix this signal is often used to reload configuration files.\n\n\tHangup,\n\n\n\n\t/// Indicate to the kernel that the process should stop.\n\n\t///\n\n\t/// On Unix, this is `SIGKILL`. On Windows, this is `TerminateProcess`.\n\n\t///\n\n\t/// This signal is not handled by the process, but directly by the kernel, and thus cannot be\n\n\t/// intercepted. Subprocesses may exit in inconsistent states.\n\n\tForceStop,\n\n\n\n\t/// Indicate that the process should stop.\n\n\t///\n\n\t/// On Unix, this is `SIGINT`. On Windows, this is ignored for now but may be supported in the\n\n\t/// future (see [#219](https://github.com/watchexec/watchexec/issues/219)).\n\n\t///\n", "file_path": "lib/src/signal/process.rs", "rank": 89, "score": 36865.569947063916 }, { "content": "\t/// This signal generally indicates an action taken by the user, so it may be handled\n\n\t/// differently than a termination.\n\n\tInterrupt,\n\n\n\n\t/// Indicate that the process is to stop, the kernel will then dump its core.\n\n\t///\n\n\t/// On Unix, this is `SIGQUIT`. On Windows, it is ignored.\n\n\t///\n\n\t/// This is rarely used.\n\n\tQuit,\n\n\n\n\t/// Indicate that the process should stop.\n\n\t///\n\n\t/// On Unix, this is `SIGTERM`. On Windows, this is ignored for now but may be supported in the\n\n\t/// future (see [#219](https://github.com/watchexec/watchexec/issues/219)).\n\n\t///\n\n\t/// On Unix, this signal generally indicates an action taken by the system, so it may be handled\n\n\t/// differently than an interruption.\n\n\tTerminate,\n\n\n", "file_path": "lib/src/signal/process.rs", "rank": 90, "score": 36865.073260491874 }, { "content": "\t/// Indicate an application-defined behaviour should happen.\n\n\t///\n\n\t/// On Unix, this is `SIGUSR1`. On Windows, it is ignored.\n\n\t///\n\n\t/// This signal is generally used to start debugging.\n\n\tUser1,\n\n\n\n\t/// Indicate an application-defined behaviour should happen.\n\n\t///\n\n\t/// On Unix, this is `SIGUSR2`. On Windows, it is ignored.\n\n\t///\n\n\t/// This signal is generally used to reload configuration.\n\n\tUser2,\n\n\n\n\t/// Indicate using a custom signal.\n\n\t///\n\n\t/// Internally, this is converted to a [`nix::Signal`](https://docs.rs/nix/*/nix/sys/signal/enum.Signal.html)\n\n\t/// but for portability this variant is a raw `i32`.\n\n\t///\n\n\t/// Invalid signals on the current platform will be ignored. Does nothing on Windows.\n", "file_path": "lib/src/signal/process.rs", "rank": 91, "score": 36862.90069731045 }, { "content": "#[cfg(windows)]\n\nfn os_strip_prefix(os: OsString, prefix: u8) -> OsString {\n\n\tuse std::os::windows::ffi::{OsStrExt, OsStringExt};\n\n\tlet wides: Vec<u16> = os.encode_wide().collect();\n\n\tif wides.first().copied() == Some(u16::from(prefix)) {\n\n\t\tOsString::from_wide(&wides[1..])\n\n\t} else {\n\n\t\tos\n\n\t}\n\n}\n\n\n", "file_path": "cli/src/filterer/globset.rs", "rank": 92, "score": 36287.97387277101 }, { "content": "\tpub fn signals(&self) -> impl Iterator<Item = MainSignal> + '_ {\n\n\t\tself.tags.iter().filter_map(|p| match p {\n\n\t\t\tTag::Signal(s) => Some(*s),\n\n\t\t\t_ => None,\n\n\t\t})\n\n\t}\n\n\n\n\t/// Return all process completions in the event's tags.\n\n\tpub fn completions(&self) -> impl Iterator<Item = Option<ProcessEnd>> + '_ {\n\n\t\tself.tags.iter().filter_map(|p| match p {\n\n\t\t\tTag::ProcessCompletion(s) => Some(*s),\n\n\t\t\t_ => None,\n\n\t\t})\n\n\t}\n\n}\n\n\n\nimpl fmt::Display for Event {\n\n\tfn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {\n\n\t\twrite!(f, \"Event\")?;\n\n\t\tfor p in &self.tags {\n", "file_path": "lib/src/event.rs", "rank": 93, "score": 18.962950788355286 }, { "content": "\t/// Create a new `SwapLock` with the given value.\n\n\tpub fn new(inner: T) -> Self {\n\n\t\tlet (s, r) = channel(inner);\n\n\t\tSelf { r, s }\n\n\t}\n\n\n\n\t/// Get a reference to the value.\n\n\tpub fn borrow(&self) -> Ref<'_, T> {\n\n\t\tself.r.borrow()\n\n\t}\n\n\n\n\t/// Rewrite the value using a closure.\n\n\t///\n\n\t/// This obtains a clone of the value, and then calls the closure with a mutable reference to\n\n\t/// it. Once the closure returns, the value is swapped in.\n\n\tpub async fn change(&self, f: impl FnOnce(&mut T)) -> Result<(), SendError<T>> {\n\n\t\tlet mut new = { self.r.borrow().clone() };\n\n\n\n\t\tf(&mut new);\n\n\t\tself.s.send(new)\n", "file_path": "lib/src/filter/tagged/swaplock.rs", "rank": 94, "score": 18.50294772405286 }, { "content": "\tpub fn action_throttle(&mut self, throttle: impl Into<Duration>) -> &mut Self {\n\n\t\tself.action.throttle = throttle.into();\n\n\t\tself\n\n\t}\n\n\n\n\t/// Set the shell to use to invoke commands.\n\n\tpub fn command_shell(&mut self, shell: Shell) -> &mut Self {\n\n\t\tself.action.shell = shell;\n\n\t\tself\n\n\t}\n\n\n\n\t/// Toggle whether to use process groups or not.\n\n\tpub fn command_grouped(&mut self, grouped: bool) -> &mut Self {\n\n\t\tself.action.grouped = grouped;\n\n\t\tself\n\n\t}\n\n\n\n\t/// Set the command to run on action.\n\n\tpub fn command<I, S>(&mut self, command: I) -> &mut Self\n\n\twhere\n", "file_path": "lib/src/config.rs", "rank": 95, "score": 18.054832915491335 }, { "content": "\tPowershell,\n\n}\n\n\n\nimpl Default for Shell {\n\n\tfn default() -> Self {\n\n\t\tSelf::None\n\n\t}\n\n}\n\n\n\nimpl Shell {\n\n\t/// Obtain a [`Command`] given a list of command parts.\n\n\t///\n\n\t/// Behaves as described in the enum documentation.\n\n\t///\n\n\t/// # Panics\n\n\t///\n\n\t/// - Panics if `cmd` is empty.\n\n\t/// - Panics if the string in the `Unix` variant is empty or only whitespace.\n\n\tpub fn to_command(&self, cmd: &[String]) -> Command {\n\n\t\tassert!(!cmd.is_empty(), \"cmd was empty\");\n", "file_path": "lib/src/command/shell.rs", "rank": 96, "score": 17.250514865781465 }, { "content": "\tevent_input: mpsc::Sender<Event>,\n\n}\n\n\n\nimpl fmt::Debug for Watchexec {\n\n\tfn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {\n\n\t\tf.debug_struct(\"Watchexec\").finish_non_exhaustive()\n\n\t}\n\n}\n\n\n\nimpl Watchexec {\n\n\t/// Instantiates a new `Watchexec` runtime from configuration.\n\n\t///\n\n\t/// Returns an [`Arc`] for convenience; use [`try_unwrap`][Arc::try_unwrap()] to get the value\n\n\t/// directly if needed.\n\n\tpub fn new(\n\n\t\tmut init: InitConfig,\n\n\t\tmut runtime: RuntimeConfig,\n\n\t) -> Result<Arc<Self>, CriticalError> {\n\n\t\tdebug!(?init, ?runtime, pid=%std::process::id(), \"initialising\");\n\n\n", "file_path": "lib/src/watchexec.rs", "rank": 97, "score": 17.050659779305054 }, { "content": "#[derive(Clone, Debug, Default)]\n\n#[non_exhaustive]\n\npub struct WorkingData {\n\n\t/// The set of paths to be watched.\n\n\tpub pathset: Vec<WatchedPath>,\n\n\n\n\t/// The kind of watcher to be used.\n\n\tpub watcher: Watcher,\n\n}\n\n\n\n/// A path to watch.\n\n///\n\n/// This is currently only a wrapper around a [`PathBuf`], but may be augmented in the future.\n\n#[derive(Clone, Debug, Default, PartialEq, Eq, PartialOrd, Ord, Hash)]\n\npub struct WatchedPath(PathBuf);\n\n\n\nimpl From<PathBuf> for WatchedPath {\n\n\tfn from(path: PathBuf) -> Self {\n\n\t\tSelf(path)\n\n\t}\n", "file_path": "lib/src/fs.rs", "rank": 98, "score": 16.777059675746646 }, { "content": "\t\tself.tag_pass(Tag::Signal(sig), true);\n\n\t}\n\n\n\n\tfn signal_doesnt_pass(&self, sig: MainSignal) {\n\n\t\tself.tag_pass(Tag::Signal(sig), false);\n\n\t}\n\n\n\n\tfn complete_does_pass(&self, exit: Option<ProcessEnd>) {\n\n\t\tself.tag_pass(Tag::ProcessCompletion(exit), true);\n\n\t}\n\n\n\n\tfn complete_doesnt_pass(&self, exit: Option<ProcessEnd>) {\n\n\t\tself.tag_pass(Tag::ProcessCompletion(exit), false);\n\n\t}\n\n}\n\n\n\nimpl TaggedHarness for TaggedFilterer {\n\n\tfn check_tag(&self, tag: Tag) -> std::result::Result<bool, RuntimeError> {\n\n\t\tlet event = Event {\n\n\t\t\ttags: vec![tag],\n\n\t\t\tmetadata: Default::default(),\n\n\t\t};\n\n\n\n\t\tself.check_event(&event)\n\n\t}\n\n}\n\n\n", "file_path": "lib/tests/helpers.rs", "rank": 99, "score": 16.5246013419574 } ]
Rust
web_glitz/src/rendering/attachment.rs
RSSchermer/web_glitz.rs
a2e26ef0156705f0b5ac7707c4fc24a4a994d84b
use std::marker; use std::sync::Arc; use web_sys::WebGl2RenderingContext as Gl; use crate::image::format::{ InternalFormat, Multisamplable, Multisample, RenderbufferFormat, TextureFormat, }; use crate::image::renderbuffer::{Renderbuffer, RenderbufferData}; use crate::image::texture_2d::{ Level as Texture2DLevel, LevelMut as Texture2DLevelMut, Texture2DData, }; use crate::image::texture_2d_array::{ LevelLayer as Texture2DArrayLevelLayer, LevelLayerMut as Texture2DArrayLevelLayerMut, Texture2DArrayData, }; use crate::image::texture_3d::{ LevelLayer as Texture3DLevelLayer, LevelLayerMut as Texture3DLevelLayerMut, Texture3DData, }; use crate::image::texture_cube::{ CubeFace, LevelFace as TextureCubeLevelFace, LevelFaceMut as TextureCubeLevelFaceMut, TextureCubeData, }; use crate::util::JsId; pub trait AsAttachment { type Format: InternalFormat; fn as_attachment(&mut self) -> Attachment<Self::Format>; } impl<'a, T> AsAttachment for &'a mut T where T: AsAttachment, { type Format = T::Format; fn as_attachment(&mut self) -> Attachment<Self::Format> { (*self).as_attachment() } } impl<'a, F> AsAttachment for Texture2DLevelMut<'a, F> where F: TextureFormat, { type Format = F; fn as_attachment(&mut self) -> Attachment<Self::Format> { Attachment::from_texture_2d_level(&self) } } impl<'a, F> AsAttachment for Texture2DArrayLevelLayerMut<'a, F> where F: TextureFormat, { type Format = F; fn as_attachment(&mut self) -> Attachment<Self::Format> { Attachment::from_texture_2d_array_level_layer(&self) } } impl<'a, F> AsAttachment for Texture3DLevelLayerMut<'a, F> where F: TextureFormat, { type Format = F; fn as_attachment(&mut self) -> Attachment<Self::Format> { Attachment::from_texture_3d_level_layer(&self) } } impl<'a, F> AsAttachment for TextureCubeLevelFaceMut<'a, F> where F: TextureFormat, { type Format = F; fn as_attachment(&mut self) -> Attachment<Self::Format> { Attachment::from_texture_cube_level_face(&self) } } impl<F> AsAttachment for Renderbuffer<F> where F: RenderbufferFormat + 'static, { type Format = F; fn as_attachment(&mut self) -> Attachment<Self::Format> { Attachment::from_renderbuffer(self) } } pub struct Attachment<'a, F> { data: AttachmentData, marker: marker::PhantomData<&'a F>, } impl<'a, F> Attachment<'a, F> { pub(crate) fn from_texture_2d_level(image: &Texture2DLevel<'a, F>) -> Self where F: TextureFormat, { Attachment { data: AttachmentData { context_id: image.texture_data().context_id(), kind: AttachableImageRefKind::Texture2DLevel { data: image.texture_data().clone(), level: image.level() as u8, }, width: image.width(), height: image.height(), }, marker: marker::PhantomData, } } pub(crate) fn from_texture_2d_array_level_layer(image: &Texture2DArrayLevelLayer<'a, F>) -> Self where F: TextureFormat, { Attachment { data: AttachmentData { context_id: image.texture_data().context_id(), kind: AttachableImageRefKind::Texture2DArrayLevelLayer { data: image.texture_data().clone(), level: image.level() as u8, layer: image.layer() as u16, }, width: image.width(), height: image.height(), }, marker: marker::PhantomData, } } pub(crate) fn from_texture_3d_level_layer(image: &Texture3DLevelLayer<'a, F>) -> Self where F: TextureFormat, { Attachment { data: AttachmentData { context_id: image.texture_data().context_id(), kind: AttachableImageRefKind::Texture3DLevelLayer { data: image.texture_data().clone(), level: image.level() as u8, layer: image.layer() as u16, }, width: image.width(), height: image.height(), }, marker: marker::PhantomData, } } pub(crate) fn from_texture_cube_level_face(image: &TextureCubeLevelFace<'a, F>) -> Self where F: TextureFormat, { Attachment { data: AttachmentData { context_id: image.texture_data().context_id(), kind: AttachableImageRefKind::TextureCubeLevelFace { data: image.texture_data().clone(), level: image.level() as u8, face: image.face(), }, width: image.width(), height: image.height(), }, marker: marker::PhantomData, } } pub(crate) fn from_renderbuffer(render_buffer: &'a Renderbuffer<F>) -> Self { Attachment { data: AttachmentData { context_id: render_buffer.data().context_id(), kind: AttachableImageRefKind::Renderbuffer { data: render_buffer.data().clone(), }, width: render_buffer.width(), height: render_buffer.height(), }, marker: marker::PhantomData, } } pub(crate) fn into_data(self) -> AttachmentData { self.data } } pub trait AsMultisampleAttachment { type SampleFormat: InternalFormat + Multisamplable; fn as_multisample_attachment(&mut self) -> MultisampleAttachment<Self::SampleFormat>; } impl<'a, T> AsMultisampleAttachment for &'a mut T where T: AsMultisampleAttachment, { type SampleFormat = T::SampleFormat; fn as_multisample_attachment(&mut self) -> MultisampleAttachment<Self::SampleFormat> { (*self).as_multisample_attachment() } } impl<F> AsMultisampleAttachment for Renderbuffer<Multisample<F>> where F: RenderbufferFormat + Multisamplable + 'static, { type SampleFormat = F; fn as_multisample_attachment(&mut self) -> MultisampleAttachment<Self::SampleFormat> { MultisampleAttachment::from_renderbuffer(self) } } pub struct MultisampleAttachment<'a, F> where F: Multisamplable, { internal: MultisampleAttachmentInternal<'a, F>, } impl<'a, F> MultisampleAttachment<'a, F> where F: Multisamplable, { pub(crate) fn from_renderbuffer(renderbuffer: &'a Renderbuffer<Multisample<F>>) -> Self { MultisampleAttachment { internal: renderbuffer.into(), } } pub fn samples(&self) -> u8 { self.internal.samples() } pub(crate) fn into_data(self) -> AttachmentData { self.internal.into_data() } } enum MultisampleAttachmentInternal<'a, F> where F: Multisamplable, { Renderbuffer(&'a Renderbuffer<Multisample<F>>), } impl<'a, F> MultisampleAttachmentInternal<'a, F> where F: Multisamplable, { fn samples(&self) -> u8 { match self { MultisampleAttachmentInternal::Renderbuffer(renderbufer) => renderbufer.samples(), } } fn into_data(self) -> AttachmentData { match self { MultisampleAttachmentInternal::Renderbuffer(renderbuffer) => AttachmentData { context_id: renderbuffer.data().context_id(), kind: AttachableImageRefKind::Renderbuffer { data: renderbuffer.data().clone(), }, width: renderbuffer.width(), height: renderbuffer.height(), }, } } } impl<'a, F> From<&'a Renderbuffer<Multisample<F>>> for MultisampleAttachmentInternal<'a, F> where F: Multisamplable, { fn from(renderbuffer: &'a Renderbuffer<Multisample<F>>) -> Self { MultisampleAttachmentInternal::Renderbuffer(renderbuffer) } } #[derive(Clone, Hash, PartialEq)] pub(crate) struct AttachmentData { pub(crate) context_id: u64, pub(crate) kind: AttachableImageRefKind, pub(crate) width: u32, pub(crate) height: u32, } impl AttachmentData { pub(crate) fn id(&self) -> JsId { match &self.kind { AttachableImageRefKind::Texture2DLevel { data, .. } => data.id().unwrap(), AttachableImageRefKind::Texture2DArrayLevelLayer { data, .. } => data.id().unwrap(), AttachableImageRefKind::Texture3DLevelLayer { data, .. } => data.id().unwrap(), AttachableImageRefKind::TextureCubeLevelFace { data, .. } => data.id().unwrap(), AttachableImageRefKind::Renderbuffer { data, .. } => data.id().unwrap(), } } pub(crate) fn attach(&self, gl: &Gl, target: u32, slot: u32) { unsafe { match &self.kind { AttachableImageRefKind::Texture2DLevel { data, level } => { data.id().unwrap().with_value_unchecked(|texture_object| { gl.framebuffer_texture_2d( target, slot, Gl::TEXTURE_2D, Some(&texture_object), *level as i32, ); }); } AttachableImageRefKind::Texture2DArrayLevelLayer { data, level, layer } => { data.id().unwrap().with_value_unchecked(|texture_object| { gl.framebuffer_texture_layer( target, slot, Some(&texture_object), *level as i32, *layer as i32, ); }); } AttachableImageRefKind::Texture3DLevelLayer { data, level, layer } => { data.id().unwrap().with_value_unchecked(|texture_object| { gl.framebuffer_texture_layer( target, slot, Some(&texture_object), *level as i32, *layer as i32, ); }); } AttachableImageRefKind::TextureCubeLevelFace { data, level, face } => { data.id().unwrap().with_value_unchecked(|texture_object| { gl.framebuffer_texture_2d( target, slot, face.id(), Some(&texture_object), *level as i32, ); }); } AttachableImageRefKind::Renderbuffer { data } => { data.id() .unwrap() .with_value_unchecked(|renderbuffer_object| { gl.framebuffer_renderbuffer( target, slot, Gl::RENDERBUFFER, Some(&renderbuffer_object), ); }); } } } } } #[derive(Clone, Hash, PartialEq)] pub(crate) enum AttachableImageRefKind { Texture2DLevel { data: Arc<Texture2DData>, level: u8, }, Texture2DArrayLevelLayer { data: Arc<Texture2DArrayData>, level: u8, layer: u16, }, Texture3DLevelLayer { data: Arc<Texture3DData>, level: u8, layer: u16, }, TextureCubeLevelFace { data: Arc<TextureCubeData>, level: u8, face: CubeFace, }, Renderbuffer { data: Arc<RenderbufferData>, }, }
use std::marker; use std::sync::Arc; use web_sys::WebGl2RenderingContext as Gl; use crate::image::format::{ InternalFormat, Multisamplable, Multisample, RenderbufferFormat, TextureFormat, }; use crate::image::renderbuffer::{Renderbuffer, RenderbufferData}; use crate::image::texture_2d::{ Level as Texture2DLevel, LevelMut as Texture2DLevelMut, Texture2DData, }; use crate::image::texture_2d_array::{ LevelLayer as Texture2DArrayLevelLayer, LevelLayerMut as Texture2DArrayLevelLayerMut, Texture2DArrayData, }; use crate::image::texture_3d::{ LevelLayer as Texture3DLevelLayer, LevelLayerMut as Texture3DLevelLayerMut, Texture3DData, }; use crate::image::texture_cube::{ CubeFace, LevelFace as TextureCubeLevelFace, LevelFaceMut as TextureCubeLevelFaceMut, TextureCubeData, }; use crate::util::JsId; pub trait AsAttachment { type Format: InternalFormat; fn as_attachment(&mut self) -> Attachment<Self::Format>; } impl<'a, T> AsAttachment for &'a mut T where T: AsAttachment, { type Format = T::Format; fn as_attachment(&mut self) -> Attachment<Self::Format> { (*self).as_attachment() } } impl<'a, F> AsAttachment for Texture2DLevelMut<'a, F> where F: TextureFormat, { type Format = F; fn as_attachment(&mut self) -> Attachment<Self::Format> { Attachment::from_texture_2d_level(&self) } } impl<'a, F> AsAttachment for Texture2DArrayLevelLayerMut<'a, F> where F: TextureFormat, { type Format = F; fn as_attachment(&mut self) -> Attachment<Self::Format> { Attachment::from_texture_2d_array_level_layer(&self) } } impl<'a, F> AsAttachment for Texture3DLevelLayerMut<'a, F> where F: TextureFormat, { type Format = F; fn as_attachment(&mut self) -> Attachment<Self::Format> { Attachment::from_texture_3d_level_layer(&self) } } impl<'a, F> AsAttachment for TextureCubeLevelFaceMut<'a, F> where F: TextureFormat, { type Format = F; fn as_attachment(&mut self) -> Attachment<Self::Format> { Attachment::from_texture_cube_level_face(&self) } } impl<F> AsAttachment for Renderbuffer<F> where F: RenderbufferFormat + 'static, { type Format = F; fn as_attachment(&mut self) -> Attachment<Self::Format> { Attachment::from_renderbuffer(self) } } pub struct Attachment<'a, F> { data: AttachmentData, marker: marker::PhantomData<&'a F>, } impl<'a, F> Attachment<'a, F> {
pub(crate) fn from_texture_2d_array_level_layer(image: &Texture2DArrayLevelLayer<'a, F>) -> Self where F: TextureFormat, { Attachment { data: AttachmentData { context_id: image.texture_data().context_id(), kind: AttachableImageRefKind::Texture2DArrayLevelLayer { data: image.texture_data().clone(), level: image.level() as u8, layer: image.layer() as u16, }, width: image.width(), height: image.height(), }, marker: marker::PhantomData, } } pub(crate) fn from_texture_3d_level_layer(image: &Texture3DLevelLayer<'a, F>) -> Self where F: TextureFormat, { Attachment { data: AttachmentData { context_id: image.texture_data().context_id(), kind: AttachableImageRefKind::Texture3DLevelLayer { data: image.texture_data().clone(), level: image.level() as u8, layer: image.layer() as u16, }, width: image.width(), height: image.height(), }, marker: marker::PhantomData, } } pub(crate) fn from_texture_cube_level_face(image: &TextureCubeLevelFace<'a, F>) -> Self where F: TextureFormat, { Attachment { data: AttachmentData { context_id: image.texture_data().context_id(), kind: AttachableImageRefKind::TextureCubeLevelFace { data: image.texture_data().clone(), level: image.level() as u8, face: image.face(), }, width: image.width(), height: image.height(), }, marker: marker::PhantomData, } } pub(crate) fn from_renderbuffer(render_buffer: &'a Renderbuffer<F>) -> Self { Attachment { data: AttachmentData { context_id: render_buffer.data().context_id(), kind: AttachableImageRefKind::Renderbuffer { data: render_buffer.data().clone(), }, width: render_buffer.width(), height: render_buffer.height(), }, marker: marker::PhantomData, } } pub(crate) fn into_data(self) -> AttachmentData { self.data } } pub trait AsMultisampleAttachment { type SampleFormat: InternalFormat + Multisamplable; fn as_multisample_attachment(&mut self) -> MultisampleAttachment<Self::SampleFormat>; } impl<'a, T> AsMultisampleAttachment for &'a mut T where T: AsMultisampleAttachment, { type SampleFormat = T::SampleFormat; fn as_multisample_attachment(&mut self) -> MultisampleAttachment<Self::SampleFormat> { (*self).as_multisample_attachment() } } impl<F> AsMultisampleAttachment for Renderbuffer<Multisample<F>> where F: RenderbufferFormat + Multisamplable + 'static, { type SampleFormat = F; fn as_multisample_attachment(&mut self) -> MultisampleAttachment<Self::SampleFormat> { MultisampleAttachment::from_renderbuffer(self) } } pub struct MultisampleAttachment<'a, F> where F: Multisamplable, { internal: MultisampleAttachmentInternal<'a, F>, } impl<'a, F> MultisampleAttachment<'a, F> where F: Multisamplable, { pub(crate) fn from_renderbuffer(renderbuffer: &'a Renderbuffer<Multisample<F>>) -> Self { MultisampleAttachment { internal: renderbuffer.into(), } } pub fn samples(&self) -> u8 { self.internal.samples() } pub(crate) fn into_data(self) -> AttachmentData { self.internal.into_data() } } enum MultisampleAttachmentInternal<'a, F> where F: Multisamplable, { Renderbuffer(&'a Renderbuffer<Multisample<F>>), } impl<'a, F> MultisampleAttachmentInternal<'a, F> where F: Multisamplable, { fn samples(&self) -> u8 { match self { MultisampleAttachmentInternal::Renderbuffer(renderbufer) => renderbufer.samples(), } } fn into_data(self) -> AttachmentData { match self { MultisampleAttachmentInternal::Renderbuffer(renderbuffer) => AttachmentData { context_id: renderbuffer.data().context_id(), kind: AttachableImageRefKind::Renderbuffer { data: renderbuffer.data().clone(), }, width: renderbuffer.width(), height: renderbuffer.height(), }, } } } impl<'a, F> From<&'a Renderbuffer<Multisample<F>>> for MultisampleAttachmentInternal<'a, F> where F: Multisamplable, { fn from(renderbuffer: &'a Renderbuffer<Multisample<F>>) -> Self { MultisampleAttachmentInternal::Renderbuffer(renderbuffer) } } #[derive(Clone, Hash, PartialEq)] pub(crate) struct AttachmentData { pub(crate) context_id: u64, pub(crate) kind: AttachableImageRefKind, pub(crate) width: u32, pub(crate) height: u32, } impl AttachmentData { pub(crate) fn id(&self) -> JsId { match &self.kind { AttachableImageRefKind::Texture2DLevel { data, .. } => data.id().unwrap(), AttachableImageRefKind::Texture2DArrayLevelLayer { data, .. } => data.id().unwrap(), AttachableImageRefKind::Texture3DLevelLayer { data, .. } => data.id().unwrap(), AttachableImageRefKind::TextureCubeLevelFace { data, .. } => data.id().unwrap(), AttachableImageRefKind::Renderbuffer { data, .. } => data.id().unwrap(), } } pub(crate) fn attach(&self, gl: &Gl, target: u32, slot: u32) { unsafe { match &self.kind { AttachableImageRefKind::Texture2DLevel { data, level } => { data.id().unwrap().with_value_unchecked(|texture_object| { gl.framebuffer_texture_2d( target, slot, Gl::TEXTURE_2D, Some(&texture_object), *level as i32, ); }); } AttachableImageRefKind::Texture2DArrayLevelLayer { data, level, layer } => { data.id().unwrap().with_value_unchecked(|texture_object| { gl.framebuffer_texture_layer( target, slot, Some(&texture_object), *level as i32, *layer as i32, ); }); } AttachableImageRefKind::Texture3DLevelLayer { data, level, layer } => { data.id().unwrap().with_value_unchecked(|texture_object| { gl.framebuffer_texture_layer( target, slot, Some(&texture_object), *level as i32, *layer as i32, ); }); } AttachableImageRefKind::TextureCubeLevelFace { data, level, face } => { data.id().unwrap().with_value_unchecked(|texture_object| { gl.framebuffer_texture_2d( target, slot, face.id(), Some(&texture_object), *level as i32, ); }); } AttachableImageRefKind::Renderbuffer { data } => { data.id() .unwrap() .with_value_unchecked(|renderbuffer_object| { gl.framebuffer_renderbuffer( target, slot, Gl::RENDERBUFFER, Some(&renderbuffer_object), ); }); } } } } } #[derive(Clone, Hash, PartialEq)] pub(crate) enum AttachableImageRefKind { Texture2DLevel { data: Arc<Texture2DData>, level: u8, }, Texture2DArrayLevelLayer { data: Arc<Texture2DArrayData>, level: u8, layer: u16, }, Texture3DLevelLayer { data: Arc<Texture3DData>, level: u8, layer: u16, }, TextureCubeLevelFace { data: Arc<TextureCubeData>, level: u8, face: CubeFace, }, Renderbuffer { data: Arc<RenderbufferData>, }, }
pub(crate) fn from_texture_2d_level(image: &Texture2DLevel<'a, F>) -> Self where F: TextureFormat, { Attachment { data: AttachmentData { context_id: image.texture_data().context_id(), kind: AttachableImageRefKind::Texture2DLevel { data: image.texture_data().clone(), level: image.level() as u8, }, width: image.width(), height: image.height(), }, marker: marker::PhantomData, } }
function_block-full_function
[ { "content": "/// A helper trait for indexing a [LevelsMut].\n\n///\n\n/// See [LevelsMut::get_mut] and [LevelsMut::get_unchecked_mut].\n\npub trait LevelsMutIndex<'a, F> {\n\n /// The output type returned by the indexing operations.\n\n type Output;\n\n\n\n /// Returns the output for this operation if in bounds, or `None` otherwise.\n\n fn get_mut(self, levels: &'a mut LevelsMut<F>) -> Option<Self::Output>;\n\n\n\n /// Returns the output for this operation, without performing any bounds checking.\n\n unsafe fn get_unchecked_mut(self, levels: &'a mut LevelsMut<F>) -> Self::Output;\n\n}\n\n\n\nimpl<'a, F> LevelsMutIndex<'a, F> for usize\n\nwhere\n\n F: 'a,\n\n{\n\n type Output = LevelMut<'a, F>;\n\n\n\n fn get_mut(self, levels: &'a mut LevelsMut<F>) -> Option<Self::Output> {\n\n if self < levels.inner.len {\n\n Some(LevelMut {\n", "file_path": "web_glitz/src/image/texture_2d.rs", "rank": 0, "score": 298909.62108883227 }, { "content": "/// A helper trait for indexing a [LevelsMut].\n\n///\n\n/// See [LevelsMut::get_mut] and [LevelsMut::get_unchecked_mut].\n\npub trait LevelsMutIndex<'a, F> {\n\n /// The output type returned by the indexing operations.\n\n type Output;\n\n\n\n /// Returns the output for this operation if in bounds, or `None` otherwise.\n\n fn get_mut(self, levels: &'a mut LevelsMut<F>) -> Option<Self::Output>;\n\n\n\n /// Returns the output for this operation, without performing any bounds checking.\n\n unsafe fn get_unchecked_mut(self, levels: &'a mut LevelsMut<F>) -> Self::Output;\n\n}\n\n\n\nimpl<'a, F> LevelsMutIndex<'a, F> for usize\n\nwhere\n\n F: 'a,\n\n{\n\n type Output = LevelMut<'a, F>;\n\n\n\n fn get_mut(self, levels: &'a mut LevelsMut<F>) -> Option<Self::Output> {\n\n if self < levels.len {\n\n Some(LevelMut {\n", "file_path": "web_glitz/src/image/texture_3d.rs", "rank": 1, "score": 298909.62108883227 }, { "content": "/// A helper trait for indexing a [LevelsMut].\n\n///\n\n/// See [LevelsMut::get_mut] and [LevelsMut::get_unchecked_mut].\n\npub trait LevelsMutIndex<'a, F> {\n\n /// The output type returned by the indexing operations.\n\n type Output;\n\n\n\n /// Returns the output for this operation if in bounds, or `None` otherwise.\n\n fn get_mut(self, levels: &'a mut LevelsMut<F>) -> Option<Self::Output>;\n\n\n\n /// Returns the output for this operation, without performing any bounds checking.\n\n unsafe fn get_unchecked_mut(self, levels: &'a mut LevelsMut<F>) -> Self::Output;\n\n}\n\n\n\nimpl<'a, F> LevelsMutIndex<'a, F> for usize\n\nwhere\n\n F: 'a,\n\n{\n\n type Output = LevelMut<'a, F>;\n\n\n\n fn get_mut(self, levels: &'a mut LevelsMut<F>) -> Option<Self::Output> {\n\n if self < levels.len {\n\n Some(LevelMut {\n", "file_path": "web_glitz/src/image/texture_2d_array.rs", "rank": 2, "score": 294345.4176281719 }, { "content": "/// A helper trait for indexing a [LevelsMut].\n\n///\n\n/// See [LevelsMut::get_mut] and [LevelsMut::get_unchecked_mut].\n\npub trait LevelsMutIndex<'a, F> {\n\n /// The output type returned by the indexing operations.\n\n type Output;\n\n\n\n /// Returns the output for this operation if in bounds, or `None` otherwise.\n\n fn get_mut(self, levels: &'a mut LevelsMut<F>) -> Option<Self::Output>;\n\n\n\n /// Returns the output for this operation, without performing any bounds checking.\n\n unsafe fn get_unchecked_mut(self, levels: &'a mut LevelsMut<F>) -> Self::Output;\n\n}\n\n\n\nimpl<'a, F> LevelsMutIndex<'a, F> for usize\n\nwhere\n\n F: 'a,\n\n{\n\n type Output = LevelMut<'a, F>;\n\n\n\n fn get_mut(self, levels: &'a mut LevelsMut<F>) -> Option<Self::Output> {\n\n if self < levels.inner.len {\n\n Some(LevelMut {\n", "file_path": "web_glitz/src/image/texture_cube.rs", "rank": 3, "score": 294345.41762817185 }, { "content": "/// A helper trait for indexing a [LevelLayersMut].\n\n///\n\n/// See [LevelsMut::get_mut] and [LevelsMut::get_unchecked_mut].\n\npub trait LevelLayersMutIndex<'a, F> {\n\n /// The output type returned by the indexing operations.\n\n type Output;\n\n\n\n /// Returns the output for this operation if in bounds, or `None` otherwise.\n\n fn get_mut(self, layers: &'a mut LevelLayersMut<F>) -> Option<Self::Output>;\n\n\n\n /// Returns the output for this operation, without performing any bounds checking.\n\n unsafe fn get_unchecked_mut(self, layers: &'a mut LevelLayersMut<F>) -> Self::Output;\n\n}\n\n\n\nimpl<'a, F> LevelLayersMutIndex<'a, F> for usize\n\nwhere\n\n F: 'a,\n\n{\n\n type Output = LevelLayerMut<'a, F>;\n\n\n\n fn get_mut(self, layers: &'a mut LevelLayersMut<F>) -> Option<Self::Output> {\n\n if self < layers.len {\n\n Some(LevelLayerMut {\n", "file_path": "web_glitz/src/image/texture_3d.rs", "rank": 4, "score": 294345.3333286685 }, { "content": "/// A helper trait for indexing a [LevelLayersMut].\n\n///\n\n/// See [LevelsMut::get_mut] and [LevelsMut::get_unchecked_mut].\n\npub trait LevelLayersMutIndex<'a, F> {\n\n /// The output type returned by the indexing operations.\n\n type Output;\n\n\n\n /// Returns the output for this operation if in bounds, or `None` otherwise.\n\n fn get_mut(self, layers: &'a mut LevelLayersMut<F>) -> Option<Self::Output>;\n\n\n\n /// Returns the output for this operation, without performing any bounds checking.\n\n unsafe fn get_unchecked_mut(self, layers: &'a mut LevelLayersMut<F>) -> Self::Output;\n\n}\n\n\n\nimpl<'a, F> LevelLayersMutIndex<'a, F> for usize\n\nwhere\n\n F: 'a,\n\n{\n\n type Output = LevelLayerMut<'a, F>;\n\n\n\n fn get_mut(self, layers: &'a mut LevelLayersMut<F>) -> Option<Self::Output> {\n\n if self < layers.len {\n\n Some(LevelLayerMut {\n", "file_path": "web_glitz/src/image/texture_2d_array.rs", "rank": 5, "score": 289960.2253723804 }, { "content": "/// A helper trait for indexing [Levels].\n\n///\n\n/// See [Levels::get] and [Levels::get_unchecked].\n\npub trait LevelsIndex<'a, F> {\n\n /// The output type returned by the indexing operations.\n\n type Output;\n\n\n\n /// Returns the output for this operation if in bounds, or `None` otherwise.\n\n fn get(self, levels: &'a Levels<F>) -> Option<Self::Output>;\n\n\n\n /// Returns the output for this operation, without performing any bounds checking.\n\n unsafe fn get_unchecked(self, levels: &'a Levels<F>) -> Self::Output;\n\n}\n\n\n\nimpl<'a, F> LevelsIndex<'a, F> for usize\n\nwhere\n\n F: 'a,\n\n{\n\n type Output = Level<'a, F>;\n\n\n\n fn get(self, levels: &'a Levels<F>) -> Option<Self::Output> {\n\n if self < levels.len {\n\n Some(Level {\n", "file_path": "web_glitz/src/image/texture_2d.rs", "rank": 6, "score": 257020.65302141276 }, { "content": "/// A helper trait for indexing [Levels].\n\n///\n\n/// See [Levels::get] and [Levels::get_unchecked].\n\npub trait LevelsIndex<'a, F> {\n\n /// The output type returned by the indexing operations.\n\n type Output;\n\n\n\n /// Returns the output for this operation if in bounds, or `None` otherwise.\n\n fn get(self, levels: &'a Levels<F>) -> Option<Self::Output>;\n\n\n\n /// Returns the output for this operation, without performing any bounds checking.\n\n unsafe fn get_unchecked(self, levels: &'a Levels<F>) -> Self::Output;\n\n}\n\n\n\nimpl<'a, F> LevelsIndex<'a, F> for usize\n\nwhere\n\n F: 'a,\n\n{\n\n type Output = Level<'a, F>;\n\n\n\n fn get(self, levels: &'a Levels<F>) -> Option<Self::Output> {\n\n if self < levels.len {\n\n Some(Level {\n", "file_path": "web_glitz/src/image/texture_3d.rs", "rank": 7, "score": 257020.65302141276 }, { "content": "/// A helper trait for indexing [Levels].\n\n///\n\n/// See [Levels::get] and [Levels::get_unchecked].\n\npub trait LevelsIndex<'a, F> {\n\n /// The output type returned by the indexing operations.\n\n type Output;\n\n\n\n /// Returns the output for this operation if in bounds, or `None` otherwise.\n\n fn get(self, levels: &'a Levels<F>) -> Option<Self::Output>;\n\n\n\n /// Returns the output for this operation, without performing any bounds checking.\n\n unsafe fn get_unchecked(self, levels: &'a Levels<F>) -> Self::Output;\n\n}\n\n\n\nimpl<'a, F> LevelsIndex<'a, F> for usize\n\nwhere\n\n F: 'a,\n\n{\n\n type Output = Level<'a, F>;\n\n\n\n fn get(self, levels: &'a Levels<F>) -> Option<Self::Output> {\n\n if self < levels.len {\n\n Some(Level {\n", "file_path": "web_glitz/src/image/texture_cube.rs", "rank": 8, "score": 253218.52113082955 }, { "content": "/// A helper trait for indexing [Levels].\n\n///\n\n/// See [Levels::get] and [Levels::get_unchecked].\n\npub trait LevelsIndex<'a, F> {\n\n /// The output type returned by the indexing operations.\n\n type Output;\n\n\n\n /// Returns the output for this operation if in bounds, or `None` otherwise.\n\n fn get(self, levels: &'a Levels<F>) -> Option<Self::Output>;\n\n\n\n /// Returns the output for this operation, without performing any bounds checking.\n\n unsafe fn get_unchecked(self, levels: &'a Levels<F>) -> Self::Output;\n\n}\n\n\n\nimpl<'a, F> LevelsIndex<'a, F> for usize\n\nwhere\n\n F: 'a,\n\n{\n\n type Output = Level<'a, F>;\n\n\n\n fn get(self, levels: &'a Levels<F>) -> Option<Self::Output> {\n\n if self < levels.len {\n\n Some(Level {\n", "file_path": "web_glitz/src/image/texture_2d_array.rs", "rank": 9, "score": 253218.52113082955 }, { "content": "/// A helper trait for indexing [LevelLayers].\n\n///\n\n/// See [LevelLayers::get] and [LevelLayers::get_unchecked].\n\npub trait LevelLayersIndex<'a, F> {\n\n /// The output type returned by the indexing operations.\n\n type Output;\n\n\n\n /// Returns the output for this operation if in bounds, or `None` otherwise.\n\n fn get(self, layers: &'a LevelLayers<F>) -> Option<Self::Output>;\n\n\n\n /// Returns the output for this operation, without performing any bounds checking.\n\n unsafe fn get_unchecked(self, layers: &'a LevelLayers<F>) -> Self::Output;\n\n}\n\n\n\nimpl<'a, F> LevelLayersIndex<'a, F> for usize\n\nwhere\n\n F: 'a,\n\n{\n\n type Output = LevelLayer<'a, F>;\n\n\n\n fn get(self, layers: &'a LevelLayers<F>) -> Option<Self::Output> {\n\n if self < layers.len {\n\n Some(LevelLayer {\n", "file_path": "web_glitz/src/image/texture_3d.rs", "rank": 10, "score": 253218.304457494 }, { "content": "/// A helper trait for indexing [LevelLayers].\n\n///\n\n/// See [LevelLayers::get] and [LevelLayers::get_unchecked].\n\npub trait LevelLayersIndex<'a, F> {\n\n /// The output type returned by the indexing operations.\n\n type Output;\n\n\n\n /// Returns the output for this operation if in bounds, or `None` otherwise.\n\n fn get(self, layers: &'a LevelLayers<F>) -> Option<Self::Output>;\n\n\n\n /// Returns the output for this operation, without performing any bounds checking.\n\n unsafe fn get_unchecked(self, layers: &'a LevelLayers<F>) -> Self::Output;\n\n}\n\n\n\nimpl<'a, F> LevelLayersIndex<'a, F> for usize\n\nwhere\n\n F: 'a,\n\n{\n\n type Output = LevelLayer<'a, F>;\n\n\n\n fn get(self, layers: &'a LevelLayers<F>) -> Option<Self::Output> {\n\n if self < layers.len {\n\n Some(LevelLayer {\n", "file_path": "web_glitz/src/image/texture_2d_array.rs", "rank": 11, "score": 249568.35069479313 }, { "content": "/// A helper trait for indexing [LevelSubImageLayers].\n\n///\n\n/// See [LevelSubImageLayers::get] and [LevelSubImageLayers::get_unchecked].\n\npub trait LevelSubImageLayersIndex<'a, F> {\n\n /// The output type returned by the indexing operations.\n\n type Output;\n\n\n\n /// Returns the output for this operation if in bounds, or `None` otherwise.\n\n fn get(self, layers: &'a LevelSubImageLayers<F>) -> Option<Self::Output>;\n\n\n\n /// Returns the output for this operation, without performing any bounds checking.\n\n unsafe fn get_unchecked(self, layers: &'a LevelSubImageLayers<F>) -> Self::Output;\n\n}\n\n\n\nimpl<'a, F> LevelSubImageLayersIndex<'a, F> for usize\n\nwhere\n\n F: 'a,\n\n{\n\n type Output = LevelLayerSubImage<'a, F>;\n\n\n\n fn get(self, layers: &'a LevelSubImageLayers<F>) -> Option<Self::Output> {\n\n if self < layers.len {\n\n Some(LevelLayerSubImage {\n", "file_path": "web_glitz/src/image/texture_3d.rs", "rank": 12, "score": 246061.21089539555 }, { "content": "/// A helper trait for indexing [LevelSubImageLayers].\n\n///\n\n/// See [LevelSubImageLayers::get] and [LevelSubImageLayers::get_unchecked].\n\npub trait LevelSubImageLayersIndex<'a, F> {\n\n /// The output type returned by the indexing operations.\n\n type Output;\n\n\n\n /// Returns the output for this operation if in bounds, or `None` otherwise.\n\n fn get(self, layers: &'a LevelSubImageLayers<F>) -> Option<Self::Output>;\n\n\n\n /// Returns the output for this operation, without performing any bounds checking.\n\n unsafe fn get_unchecked(self, layers: &'a LevelSubImageLayers<F>) -> Self::Output;\n\n}\n\n\n\nimpl<'a, F> LevelSubImageLayersIndex<'a, F> for usize\n\nwhere\n\n F: 'a,\n\n{\n\n type Output = LevelLayerSubImage<'a, F>;\n\n\n\n fn get(self, layers: &'a LevelSubImageLayers<F>) -> Option<Self::Output> {\n\n if self < layers.len {\n\n Some(LevelLayerSubImage {\n", "file_path": "web_glitz/src/image/texture_2d_array.rs", "rank": 13, "score": 242689.43175612943 }, { "content": "/// Trait implemented by attribute format identifiers.\n\n///\n\n/// Helper trait which, in conjunction with [FormatCompatible], allows the derive macro for the\n\n/// [Vertex] trait to verify at compile time that an attribute field type is compatible with the\n\n/// specified attribute format.\n\npub trait VertexAttributeFormatIdentifier {\n\n /// The [AttributeFormat] associated with this [AttributeFormatIdentifier].\n\n const FORMAT: VertexAttributeFormat;\n\n}\n\n\n\npub struct Float_f32;\n\n\n\nimpl VertexAttributeFormatIdentifier for Float_f32 {\n\n const FORMAT: VertexAttributeFormat = VertexAttributeFormat::Float_f32;\n\n}\n\n\n\npub struct Float_i8_fixed;\n\n\n\nimpl VertexAttributeFormatIdentifier for Float_i8_fixed {\n\n const FORMAT: VertexAttributeFormat = VertexAttributeFormat::Float_i8_fixed;\n\n}\n\n\n\npub struct Float_i8_norm;\n\n\n\nimpl VertexAttributeFormatIdentifier for Float_i8_norm {\n", "file_path": "web_glitz/src/pipeline/graphics/vertex/attribute_format.rs", "rank": 15, "score": 196334.13959440918 }, { "content": "struct MultisampleRenderbufferAllocateCommand<F> {\n\n data: Arc<RenderbufferData>,\n\n samples: u8,\n\n _marker: marker::PhantomData<[F]>,\n\n}\n\n\n\nunsafe impl<F> GpuTask<Connection> for MultisampleRenderbufferAllocateCommand<F>\n\nwhere\n\n F: RenderbufferFormat,\n\n{\n\n type Output = ();\n\n\n\n fn context_id(&self) -> ContextId {\n\n ContextId::Any\n\n }\n\n\n\n fn progress(&mut self, connection: &mut Connection) -> Progress<Self::Output> {\n\n let (gl, state) = unsafe { connection.unpack_mut() };\n\n let data = &self.data;\n\n let object = gl.create_renderbuffer().unwrap();\n", "file_path": "web_glitz/src/image/renderbuffer.rs", "rank": 16, "score": 194465.28517696663 }, { "content": "/// Describes a data source that can be used to provide indexing data to a draw command.\n\npub trait IndexData {\n\n /// Returns a descriptor of the index data.\n\n fn descriptor(&self) -> IndexDataDescriptor;\n\n}\n\n\n\nimpl<'a, T> IndexData for &'a IndexBuffer<T>\n\nwhere\n\n T: IndexFormat,\n\n{\n\n fn descriptor(&self) -> IndexDataDescriptor {\n\n IndexDataDescriptor {\n\n buffer_data: self.data.clone(),\n\n index_type: T::TYPE,\n\n offset: 0,\n\n len: self.len() as u32,\n\n }\n\n }\n\n}\n\n\n\nimpl<'a, T> IndexData for IndexBufferView<'a, T>\n", "file_path": "web_glitz/src/pipeline/graphics/vertex/index_buffer.rs", "rank": 17, "score": 189366.87403869838 }, { "content": "/// A resource bindings layout description attached to a type.\n\n///\n\n/// See also [TypedResourceBindingsLayoutDescriptor].\n\n///\n\n/// This trait becomes useful in combination with the [TypedResourceBindings] trait. If a\n\n/// [TypedResourceBindingsLayout] is attached to a [GraphicsPipeline] (see\n\n/// [GraphicsPipelineDescriptorBuilder::typed_resource_bindings_layout]), then\n\n/// [TypedResourceBindings] with a matching [TypedResourceBindings::Layout] may be bound to the\n\n/// pipeline without further runtime checks.\n\n///\n\n/// Note that [TypedResourceBindingsLayout] is safe to implement, but implementing\n\n/// [TypedResourceBindings] is unsafe: the resource bindings encoded by a [TypedResourceBindings]\n\n/// implementation must always be compatible with the bindings layout specified by its\n\n/// [TypedResourceBindings::Layout], see [TypedResourceBindings] for details.\n\npub trait TypedResourceBindingsLayout {\n\n const LAYOUT: TypedResourceBindingsLayoutDescriptor;\n\n}\n\n\n\nmacro_rules! implement_typed_resource_bindings_layout {\n\n ($($T:ident: $i:tt),*) => {\n\n #[allow(unused_parens)]\n\n impl<$($T),*> TypedResourceBindingsLayout for ($($T),*)\n\n where\n\n $($T: TypedBindGroupLayout),*\n\n {\n\n const LAYOUT: TypedResourceBindingsLayoutDescriptor = unsafe {\n\n TypedResourceBindingsLayoutDescriptor::new(&[\n\n $(TypedBindGroupLayoutDescriptor::new($i, $T::LAYOUT)),*\n\n ])\n\n };\n\n }\n\n }\n\n}\n\n\n", "file_path": "web_glitz/src/pipeline/resources/resources.rs", "rank": 18, "score": 189358.84200992997 }, { "content": "/// A description of the resource slot layout of a bind group, attached to a type.\n\n///\n\n/// See also [TypedResourceSlotDescriptor].\n\n///\n\n/// This trait becomes useful in combination with the [TypedBindableResourceGroup] and\n\n/// [TypedResourceBindings] traits, the later of which is implemented for any tuple of [BindGroup]s\n\n/// where each [BindGroup] holds resources that implement [TypedBindableResourceGroup]. If a\n\n/// pipeline (or a tuple of such bind groups) declares a typed resource bindings layout, then a\n\n/// (tuple of) bind group(s) with a matching resource layout may be safely bound to the pipeline\n\n/// without additional runtime checks.\n\n///\n\n/// Note that [TypedBindGroupLayout] is safe to implement, but implementing\n\n/// [TypedBindableResourceGroup] is unsafe: the resource bindings encoded by the\n\n/// [TypedBindableResourceGroup] implementation must always be compatible with the bind group\n\n/// layout specified by its [TypedBindableResourceGroup::Layout], see [TypedBindableResourceGroup]\n\n/// for details.\n\npub trait TypedBindGroupLayout {\n\n const LAYOUT: &'static [TypedResourceSlotDescriptor];\n\n}\n\n\n", "file_path": "web_glitz/src/pipeline/resources/resources.rs", "rank": 19, "score": 189358.11698866624 }, { "content": "/// Helper trait implemented by types that describe a multisample color image attachment for a\n\n/// [MultisampleRenderTarget].\n\npub trait EncodeMultisampleColorBuffer {\n\n /// The type of [RenderingOutputBuffer] that is allocated in the framebuffer to buffer\n\n /// modifications to the attached image.\n\n type Buffer: RenderingOutputBuffer;\n\n\n\n /// Returns an encoding of the information needed by a [RenderPass] to load data from the\n\n /// attached image into the framebuffer before the render pass, and to store data from the\n\n /// framebuffer back into the attached image after the render pass.\n\n fn encode_multisample_color_buffer<'a, 'b>(\n\n &'a mut self,\n\n context: &'b mut ColorBufferEncodingContext,\n\n ) -> ColorBufferEncoding<'b, 'a, Self::Buffer>;\n\n}\n\n\n\n/// Provides the context for encoding a [ColorAttachmentDescription].\n\n///\n\n/// See [ColorAttachmentDescription::encode].\n\npub struct ColorBufferEncodingContext {\n\n pub(crate) render_pass_id: u64,\n\n pub(crate) buffer_index: i32,\n", "file_path": "web_glitz/src/rendering/encode_color_buffer.rs", "rank": 20, "score": 186701.78357755876 }, { "content": "/// A vertex input layout description attached to a type.\n\n///\n\n/// See also [VertexInputLayoutDescriptor].\n\n///\n\n/// This trait becomes useful in combination with the [TypedVertexBuffers] trait. If a\n\n/// [TypedVertexInputLayout] is attached to a [GraphicsPipeline] (see\n\n/// [GraphicsPipelineDescriptorBuilder::typed_vertex_input_layout]), then [TypedVertexBuffers] with\n\n/// a matching [TypedVertexBuffers::Layout] may be bound to the pipeline without further runtime\n\n/// checks.\n\n///\n\n/// Note that [TypedVertexInputLayout] is safe to implement, but implementing [TypedVertexBuffers]\n\n/// is unsafe: the data in the buffer representation for which [TypedVertexBuffers] is implemented\n\n/// must always be compatible with the vertex input layout specified by the\n\n/// [TypedVertexBuffers::Layout], see [TypedVertexBuffers] for details.\n\npub trait TypedVertexInputLayout {\n\n type LayoutDescription: Into<VertexInputLayoutDescriptor>;\n\n\n\n const LAYOUT_DESCRIPTION: Self::LayoutDescription;\n\n}\n\n\n\nimpl TypedVertexInputLayout for () {\n\n type LayoutDescription = ();\n\n\n\n const LAYOUT_DESCRIPTION: Self::LayoutDescription = ();\n\n}\n\n\n\nmacro_rules! impl_typed_vertex_input_layout {\n\n ($n:tt, $($T:ident),*) => {\n\n #[allow(unused_parens)]\n\n impl<$($T),*> TypedVertexInputLayout for ($($T),*) where $($T: Vertex),* {\n\n type LayoutDescription = [StaticVertexBufferSlotDescriptor; $n];\n\n\n\n const LAYOUT_DESCRIPTION: Self::LayoutDescription = [\n\n $(\n", "file_path": "web_glitz/src/pipeline/graphics/vertex/layout_descriptor.rs", "rank": 21, "score": 184204.5804292092 }, { "content": "/// Helper trait implemented by types that describe a multisampledepth-stencil image attachment for\n\n/// a [MultisampleRenderTarget].\n\npub trait EncodeMultisampleDepthStencilBuffer {\n\n /// The type of [RenderingOutputBuffer] that is allocated in the framebuffer to buffer\n\n /// modifications to the attached image.\n\n type Buffer: RenderingOutputBuffer;\n\n\n\n /// Returns an encoding of the information needed by a [RenderPass] to load data from the\n\n /// attached image into the framebuffer before the render pass, and to store data from the\n\n /// framebuffer back into the attached image after the render pass.\n\n fn encode_multisample_depth_stencil_buffer<'a, 'b>(\n\n &'a mut self,\n\n context: &'b mut DepthStencilBufferEncodingContext,\n\n ) -> DepthStencilBufferEncoding<'b, 'a, Self::Buffer>;\n\n}\n\n\n\npub struct DepthStencilBufferEncodingContext {\n\n pub(crate) render_pass_id: u64,\n\n}\n\n\n\npub struct DepthStencilBufferEncoding<'a, 'b, B> {\n\n pub(crate) buffer: B,\n", "file_path": "web_glitz/src/rendering/encode_depth_stencil_buffer.rs", "rank": 22, "score": 181741.23342150293 }, { "content": "/// A helper trait type for indexing operations on a [BufferViewMut] that contains a slice.\n\npub trait BufferViewMutSliceIndex<T>: BufferViewSliceIndex<T> {\n\n /// Returns a mutable view on the output for this operation if in bounds, or `None` otherwise.\n\n fn get_mut<'a>(\n\n self,\n\n view: &'a mut BufferViewMut<[T]>,\n\n ) -> Option<BufferViewMut<'a, Self::Output>> {\n\n self.get(view).map(|view| BufferViewMut {\n\n inner: view,\n\n _marker: marker::PhantomData,\n\n })\n\n }\n\n\n\n /// Returns a mutable view the output for this operation, without performing any bounds\n\n /// checking.\n\n unsafe fn get_unchecked_mut<'a>(\n\n self,\n\n view: &'a mut BufferViewMut<[T]>,\n\n ) -> BufferViewMut<'a, Self::Output> {\n\n BufferViewMut {\n\n inner: self.get_unchecked(view),\n", "file_path": "web_glitz/src/buffer.rs", "rank": 23, "score": 164674.37056117403 }, { "content": "#[wasm_bindgen(start)]\n\npub fn start() {\n\n // Obtain a reference to the `web_sys::HtmlCanvasElement` we want to render to.\n\n let canvas: HtmlCanvasElement = window()\n\n .unwrap()\n\n .document()\n\n .unwrap()\n\n .get_element_by_id(\"canvas\")\n\n .unwrap()\n\n .dyn_into()\n\n .unwrap();\n\n\n\n // Initialize a single threaded WebGlitz context for the canvas. This is unsafe: WebGlitz tracks\n\n // various bits of state for the context. There is currently no way to prevent you from simply\n\n // obtaining another copy of the WebGL 2.0 context and modifying the state while bypassing\n\n // WebGlitz's state tracking. Therefore, obtaining a WebGlitz context is only safe if:\n\n //\n\n // - the canvas context is in its default state (you've not previously obtained another context\n\n // and modified the state), and;\n\n // - you will not modify the context state through another copy of the context for as long as\n\n // the WebGlitz context remains alive.\n", "file_path": "examples/0_triangle/src/lib.rs", "rank": 24, "score": 154625.96568822145 }, { "content": "#[wasm_bindgen(start)]\n\npub fn start() {\n\n let canvas: HtmlCanvasElement = window()\n\n .unwrap()\n\n .document()\n\n .unwrap()\n\n .get_element_by_id(\"canvas\")\n\n .unwrap()\n\n .dyn_into()\n\n .unwrap();\n\n\n\n // We won't use use the default context options this time. Instead we build our own options for\n\n // which we enable the depth buffer: without a depth buffer a depth test can't be performed (see\n\n // below).\n\n let (context, mut render_target) = unsafe {\n\n single_threaded::init(&canvas, &ContextOptions::begin().enable_depth().finish()).unwrap()\n\n };\n\n\n\n let vertex_shader = context\n\n .try_create_vertex_shader(include_str!(\"vertex.glsl\"))\n\n .unwrap();\n", "file_path": "examples/6_cube_3d/src/lib.rs", "rank": 25, "score": 154625.96568822145 }, { "content": "#[wasm_bindgen(start)]\n\npub fn start() {\n\n let canvas: HtmlCanvasElement = window()\n\n .unwrap()\n\n .document()\n\n .unwrap()\n\n .get_element_by_id(\"canvas\")\n\n .unwrap()\n\n .dyn_into()\n\n .unwrap();\n\n\n\n // We'll disable antialiasing on the default render target for this example, as blit operations\n\n // are only available on single-sample render targets.\n\n let options = ContextOptions::begin().disable_antialias().finish();\n\n\n\n let (context, mut default_render_target) =\n\n unsafe { single_threaded::init(&canvas, &options).unwrap() };\n\n\n\n let vertex_shader = context\n\n .try_create_vertex_shader(include_str!(\"vertex.glsl\"))\n\n .unwrap();\n", "file_path": "examples/4_blit/src/lib.rs", "rank": 26, "score": 154625.96568822145 }, { "content": "#[wasm_bindgen(start)]\n\npub fn start() {\n\n let canvas: HtmlCanvasElement = window()\n\n .unwrap()\n\n .document()\n\n .unwrap()\n\n .get_element_by_id(\"canvas\")\n\n .unwrap()\n\n .dyn_into()\n\n .unwrap();\n\n\n\n // We'll disable antialiasing on the default render target for this example, as resolve\n\n // operations require the destination to be a single-sample render target.\n\n let options = ContextOptions::begin()\n\n .enable_depth()\n\n .disable_antialias()\n\n .finish();\n\n\n\n let (context, mut default_render_target) =\n\n unsafe { single_threaded::init(&canvas, &options).unwrap() };\n\n\n", "file_path": "examples/8_resolve/src/lib.rs", "rank": 27, "score": 154625.96568822145 }, { "content": "struct AllocateCommand<F> {\n\n data: Arc<Texture2DData>,\n\n _marker: marker::PhantomData<[F]>,\n\n}\n\n\n\nunsafe impl<F> GpuTask<Connection> for AllocateCommand<F>\n\nwhere\n\n F: TextureFormat,\n\n{\n\n type Output = ();\n\n\n\n fn context_id(&self) -> ContextId {\n\n ContextId::Id(self.data.context_id)\n\n }\n\n\n\n fn progress(&mut self, connection: &mut Connection) -> Progress<Self::Output> {\n\n let (gl, state) = unsafe { connection.unpack_mut() };\n\n let data = &self.data;\n\n\n\n let texture_object = gl.create_texture().unwrap();\n", "file_path": "web_glitz/src/image/texture_2d.rs", "rank": 28, "score": 152696.58191298397 }, { "content": "struct AllocateCommand<F> {\n\n data: Arc<Texture3DData>,\n\n _marker: marker::PhantomData<[F]>,\n\n}\n\n\n\nunsafe impl<F> GpuTask<Connection> for AllocateCommand<F>\n\nwhere\n\n F: TextureFormat,\n\n{\n\n type Output = ();\n\n\n\n fn context_id(&self) -> ContextId {\n\n ContextId::Id(self.data.context_id)\n\n }\n\n\n\n fn progress(&mut self, connection: &mut Connection) -> Progress<Self::Output> {\n\n let (gl, state) = unsafe { connection.unpack_mut() };\n\n let data = &self.data;\n\n\n\n let texture_object = gl.create_texture().unwrap();\n", "file_path": "web_glitz/src/image/texture_3d.rs", "rank": 29, "score": 152696.58191298397 }, { "content": "#[wasm_bindgen(start)]\n\npub fn start() {\n\n let document = window().unwrap().document().unwrap();\n\n\n\n let canvas: HtmlCanvasElement = document\n\n .get_element_by_id(\"canvas\")\n\n .unwrap()\n\n .dyn_into()\n\n .unwrap();\n\n\n\n let (context, mut render_target) =\n\n unsafe { single_threaded::init(&canvas, &ContextOptions::default()).unwrap() };\n\n\n\n let vertex_shader = context\n\n .try_create_vertex_shader(include_str!(\"vertex.glsl\"))\n\n .unwrap();\n\n\n\n let fragment_shader = context\n\n .try_create_fragment_shader(include_str!(\"fragment.glsl\"))\n\n .unwrap();\n\n\n", "file_path": "examples/2_textured_triangle/src/lib.rs", "rank": 30, "score": 152468.57564770157 }, { "content": "#[wasm_bindgen(start)]\n\npub fn start() {\n\n let document = window().unwrap().document().unwrap();\n\n\n\n let canvas: HtmlCanvasElement = document\n\n .get_element_by_id(\"canvas\")\n\n .unwrap()\n\n .dyn_into()\n\n .unwrap();\n\n\n\n let (context, mut default_render_target) =\n\n unsafe { single_threaded::init(&canvas, &ContextOptions::default()).unwrap() };\n\n\n\n let primary_vertex_shader = context\n\n .try_create_vertex_shader(include_str!(\"primary_vertex.glsl\"))\n\n .unwrap();\n\n\n\n let primary_fragment_shader = context\n\n .try_create_fragment_shader(include_str!(\"primary_fragment.glsl\"))\n\n .unwrap();\n\n\n", "file_path": "examples/3_render_to_texture/src/lib.rs", "rank": 31, "score": 152468.57564770157 }, { "content": "#[wasm_bindgen(start)]\n\npub fn start() {\n\n let canvas: HtmlCanvasElement = window()\n\n .unwrap()\n\n .document()\n\n .unwrap()\n\n .get_element_by_id(\"canvas\")\n\n .unwrap()\n\n .dyn_into()\n\n .unwrap();\n\n\n\n let (context, mut render_target) =\n\n unsafe { single_threaded::init(&canvas, &ContextOptions::default()).unwrap() };\n\n\n\n let vertex_shader = context\n\n .try_create_vertex_shader(include_str!(\"vertex.glsl\"))\n\n .unwrap();\n\n\n\n let fragment_shader = context\n\n .try_create_fragment_shader(include_str!(\"fragment.glsl\"))\n\n .unwrap();\n", "file_path": "examples/5_transform_feedback/src/lib.rs", "rank": 32, "score": 152468.57564770157 }, { "content": "#[wasm_bindgen(start)]\n\npub fn start() {\n\n let canvas: HtmlCanvasElement = window()\n\n .unwrap()\n\n .document()\n\n .unwrap()\n\n .get_element_by_id(\"canvas\")\n\n .unwrap()\n\n .dyn_into()\n\n .unwrap();\n\n\n\n let (context, mut render_target) =\n\n unsafe { single_threaded::init(&canvas, &ContextOptions::default()).unwrap() };\n\n\n\n let vertex_shader = context\n\n .try_create_vertex_shader(include_str!(\"vertex.glsl\"))\n\n .unwrap();\n\n\n\n let fragment_shader = context\n\n .try_create_fragment_shader(include_str!(\"fragment.glsl\"))\n\n .unwrap();\n", "file_path": "examples/1_uniform_block/src/lib.rs", "rank": 33, "score": 152468.57564770157 }, { "content": "#[wasm_bindgen(start)]\n\npub fn start() {\n\n let window = window().unwrap();\n\n let document = window.document().unwrap();\n\n\n\n let canvas: HtmlCanvasElement = document\n\n .query_id(\"canvas\")\n\n .expect(\"No element with id `canvas`.\")\n\n .try_into()\n\n .expect(\"Element is not a canvas element.\");\n\n\n\n let (context, mut render_target) = unsafe {\n\n single_threaded::init(\n\n canvas.as_ref(),\n\n &ContextOptions::begin().enable_depth().finish(),\n\n )\n\n .unwrap()\n\n };\n\n\n\n let vertex_shader = context\n\n .try_create_vertex_shader(include_str!(\"vertex.glsl\"))\n", "file_path": "examples/7_cube_3d_animated/src/lib.rs", "rank": 34, "score": 152468.57564770157 }, { "content": "#[wasm_bindgen(start)]\n\npub fn start() {\n\n let canvas: HtmlCanvasElement = window()\n\n .unwrap()\n\n .document()\n\n .unwrap()\n\n .get_element_by_id(\"canvas\")\n\n .unwrap()\n\n .dyn_into()\n\n .unwrap();\n\n\n\n let options = ContextOptions::begin()\n\n .enable_depth()\n\n .disable_antialias()\n\n .finish();\n\n\n\n let (context, _default_render_target) =\n\n unsafe { single_threaded::init(&canvas, &options).unwrap() };\n\n\n\n let buffer_a: Buffer<[u32]> = context.create_buffer([0, 1, 2, 3, 4], UsageHint::StreamRead);\n\n let buffer_b: Buffer<[u32]> = context.create_buffer([0, 0, 0, 0, 0], UsageHint::StreamCopy);\n", "file_path": "examples/9_buffer_copy_from/src/lib.rs", "rank": 35, "score": 152468.57564770157 }, { "content": " pub trait Seal {}\n\n\n\n impl Seal for Nearest {}\n\n impl Seal for Linear {}\n\n impl Seal for NearestMipmapNearest {}\n\n impl Seal for NearestMipmapLinear {}\n\n impl Seal for LinearMipmapNearest {}\n\n impl Seal for LinearMipmapLinear {}\n\n}\n\n\n", "file_path": "web_glitz/src/image/sampler.rs", "rank": 37, "score": 152339.15422861022 }, { "content": "struct RenderbufferAllocateCommand<F> {\n\n data: Arc<RenderbufferData>,\n\n _marker: marker::PhantomData<[F]>,\n\n}\n\n\n\nunsafe impl<F> GpuTask<Connection> for RenderbufferAllocateCommand<F>\n\nwhere\n\n F: RenderbufferFormat,\n\n{\n\n type Output = ();\n\n\n\n fn context_id(&self) -> ContextId {\n\n ContextId::Any\n\n }\n\n\n\n fn progress(&mut self, connection: &mut Connection) -> Progress<Self::Output> {\n\n let (gl, state) = unsafe { connection.unpack_mut() };\n\n let data = &self.data;\n\n let object = gl.create_renderbuffer().unwrap();\n\n\n", "file_path": "web_glitz/src/image/renderbuffer.rs", "rank": 38, "score": 150713.81841954653 }, { "content": "struct AllocateCommand<F> {\n\n data: Arc<TextureCubeData>,\n\n _marker: marker::PhantomData<[F]>,\n\n}\n\n\n\nunsafe impl<F> GpuTask<Connection> for AllocateCommand<F>\n\nwhere\n\n F: TextureFormat,\n\n{\n\n type Output = ();\n\n\n\n fn context_id(&self) -> ContextId {\n\n ContextId::Id(self.data.context_id)\n\n }\n\n\n\n fn progress(&mut self, connection: &mut Connection) -> Progress<Self::Output> {\n\n let (gl, state) = unsafe { connection.unpack_mut() };\n\n let data = &self.data;\n\n\n\n let texture_object = gl.create_texture().unwrap();\n", "file_path": "web_glitz/src/image/texture_cube.rs", "rank": 39, "score": 150713.81841954653 }, { "content": "struct AllocateCommand<F> {\n\n data: Arc<Texture2DArrayData>,\n\n _marker: marker::PhantomData<[F]>,\n\n}\n\n\n\nunsafe impl<F> GpuTask<Connection> for AllocateCommand<F>\n\nwhere\n\n F: TextureFormat,\n\n{\n\n type Output = ();\n\n\n\n fn context_id(&self) -> ContextId {\n\n ContextId::Id(self.data.context_id)\n\n }\n\n\n\n fn progress(&mut self, connection: &mut Connection) -> Progress<Self::Output> {\n\n let (gl, state) = unsafe { connection.unpack_mut() };\n\n let data = &self.data;\n\n\n\n let texture_object = gl.create_texture().unwrap();\n", "file_path": "web_glitz/src/image/texture_2d_array.rs", "rank": 40, "score": 150713.81841954653 }, { "content": "pub trait Options {\n\n type Output;\n\n\n\n unsafe fn get_context(&self, canvas: &HtmlCanvasElement) -> Self::Output;\n\n}\n\n\n\nimpl Options for ContextOptions<DefaultMultisampleRenderTarget<DefaultRGBABuffer, ()>> {\n\n type Output = Result<\n\n (\n\n SingleThreadedContext,\n\n DefaultMultisampleRenderTarget<DefaultRGBABuffer, ()>,\n\n ),\n\n String,\n\n >;\n\n\n\n unsafe fn get_context(&self, canvas: &HtmlCanvasElement) -> Self::Output {\n\n let options = JsValue::from_serde(&OptionsJson {\n\n alpha: true,\n\n antialias: true,\n\n depth: false,\n", "file_path": "web_glitz/src/runtime/single_threaded.rs", "rank": 41, "score": 150273.83331648534 }, { "content": "/// Encodes a description of how a set of resources is bound to a pipeline, such that the pipeline\n\n/// may access these resources during its execution.\n\n///\n\n/// # Example\n\n///\n\n/// ```\n\n/// use web_glitz::buffer::Buffer;\n\n/// use web_glitz::image::texture_2d::FloatSampledTexture2D;\n\n/// use web_glitz::pipeline::resources::{ResourceBindings, ResourceBindingsEncodingContext, ResourceBindingsEncoding, StaticResourceBindingsEncoder, BindGroup, BindGroupDescriptor};\n\n///\n\n/// struct Resources<T0, T1> {\n\n/// bind_group_0: BindGroup<T0>,\n\n/// bind_group_1: BindGroup<T1>,\n\n/// }\n\n///\n\n/// impl<T0, T1> ResourceBindings for &'_ Resources<T0, T1> {\n\n/// type BindGroups = [BindGroupDescriptor; 2];\n\n///\n\n/// fn encode(\n\n/// self,\n\n/// encoding_context: &mut ResourceBindingsEncodingContext\n\n/// ) -> ResourceBindingsEncoding<Self::BindGroups> {\n\n/// let encoder = StaticResourceBindingsEncoder::new(encoding_context);\n\n///\n\n/// let encoder = encoder.add_bind_group(0, &self.bind_group_0);\n\n/// let encoder = encoder.add_bind_group(1, &self.bind_group_1);\n\n///\n\n/// encoder.finish()\n\n/// }\n\n/// }\n\n/// ```\n\n///\n\n/// See also [StaticResourceBindingsEncoder].\n\n///\n\n/// Note that when multiple bindings of the same type bind to the same slot-index, then only the\n\n/// binding that was added last will be used. However, buffer resources and texture resources belong\n\n/// to distinct bind groups, their slot-indices do not interact.\n\n///\n\n/// This trait is automatically implemented for any type that derives the [Resources] trait.\n\npub trait ResourceBindings {\n\n /// Type that describes the collection of bindings.\n\n type BindGroups: Borrow<[BindGroupDescriptor]> + 'static;\n\n\n\n /// Encodes a description of how this set of resources is bound to a pipeline.\n\n fn encode(\n\n self,\n\n encoding_context: &mut ResourceBindingsEncodingContext,\n\n ) -> ResourceBindingsEncoding<Self::BindGroups>;\n\n}\n\n\n\nimpl ResourceBindings for () {\n\n type BindGroups = [BindGroupDescriptor; 0];\n\n\n\n fn encode(\n\n self,\n\n encoding_context: &mut ResourceBindingsEncodingContext,\n\n ) -> ResourceBindingsEncoding<Self::BindGroups> {\n\n ResourceBindingsEncoding::empty(encoding_context)\n\n }\n", "file_path": "web_glitz/src/pipeline/resources/resources.rs", "rank": 42, "score": 148323.3926870732 }, { "content": "/// Trait implemented by types that represent a rendering output buffer in the framebuffer for a\n\n/// custom render target.\n\npub trait RenderingOutputBuffer {\n\n /// The type image storage format used by the buffer.\n\n type Format: InternalFormat;\n\n\n\n /// The width of the buffer (in pixels).\n\n fn width(&self) -> u32;\n\n\n\n /// The height of the buffer (in pixels).\n\n fn height(&self) -> u32;\n\n}\n\n\n\n/// Represents a color buffer that stores floating point values in a framebuffer for a custom render\n\n/// target.\n\npub struct FloatBuffer<F> {\n\n render_pass_id: u64,\n\n index: i32,\n\n width: u32,\n\n height: u32,\n\n _marker: marker::PhantomData<Box<F>>,\n\n}\n", "file_path": "web_glitz/src/rendering/framebuffer.rs", "rank": 43, "score": 148305.35203479245 }, { "content": "/// Trait implemented by types that can serve as a WebGlitz rendering context.\n\n///\n\n/// The rendering context is the main interface of interaction with the Graphics Processing Unit\n\n/// (GPU). It has 4 main roles:\n\n///\n\n/// 1. Provide information about the abilities of the current GPU connection, see\n\n/// [max_supported_samples].\n\n/// 2. Act as a factory for the following WebGlitz objects:\n\n/// - [Buffer]s, see [create_buffer].\n\n/// - [Texture2D]s, see [try_create_texture_2d].\n\n/// - [Texture2DArray]s, see [try_create_texture_2d_array].\n\n/// - [Texture3D]s, see [try_create_texture_3d].\n\n/// - [TextureCube]s, see [try_create_texture_cube].\n\n/// - [Sampler]s, see [create_sampler].\n\n/// - [ShadowSampler]s, see [create_shadow_sampler].\n\n/// - [Renderbuffer]s, see [create_renderbuffer] and [try_create_multisample_renderbuffer].\n\n/// - [VertexShader]s, see [try_create_vertex_shader].\n\n/// - [FragmentShader]s, see [try_create_fragment_shader].\n\n/// - [GraphicsPipeline]s, see [try_create_graphics_pipeline].\n\n/// - [BindGroup]s, see [create_bind_group].\n\n/// - [RenderTarget]s, see [create_render_target], [try_create_render_target],\n\n/// [create_multisample_render_target] and [try_create_multisample_render_target].\n\n/// 3. Submission of [GpuTask]s to the GPU with [submit].\n\n/// 4. Extension initialization, see [get_extension].\n\npub trait RenderingContext {\n\n /// Identifier that uniquely identifies this rendering context.\n\n fn id(&self) -> u64;\n\n\n\n /// Returns the requested extension, or `None` if the extension is not available on this\n\n /// context.\n\n ///\n\n /// See the [web_glitz::extensions] module for the available extensions.\n\n fn get_extension<T>(&self) -> Option<T>\n\n where\n\n T: Extension;\n\n\n\n /// Returns information about the sampling grid sizes that are supported for the `format` in\n\n /// descending order of size.\n\n ///\n\n /// # Example\n\n ///\n\n /// ```\n\n /// # use web_glitz::runtime::{RenderingContext, SupportedSamples};\n\n /// # fn wrapper<Rc>(context: &Rc) where Rc: RenderingContext {\n", "file_path": "web_glitz/src/runtime/rendering_context.rs", "rank": 44, "score": 148304.15243582247 }, { "content": "/// Helper trait implemented by color buffers that can serve as a target for a [BlitCommand],\n\n/// see [Framebuffer::blit_color_nearest_command] and [Framebuffer::blit_color_linear_command].\n\npub trait BlitColorTarget {\n\n /// Encapsulates the information about the color target needed by the [BlitCommand].\n\n fn descriptor(&self) -> BlitTargetDescriptor;\n\n}\n\n\n\nimpl BlitColorTarget for DefaultRGBBuffer {\n\n fn descriptor(&self) -> BlitTargetDescriptor {\n\n BlitTargetDescriptor {\n\n internal: BlitTargetDescriptorInternal::Default,\n\n }\n\n }\n\n}\n\n\n\nimpl BlitColorTarget for DefaultRGBABuffer {\n\n fn descriptor(&self) -> BlitTargetDescriptor {\n\n BlitTargetDescriptor {\n\n internal: BlitTargetDescriptorInternal::Default,\n\n }\n\n }\n\n}\n", "file_path": "web_glitz/src/rendering/framebuffer.rs", "rank": 45, "score": 148299.57085160812 }, { "content": "/// Trait implemented for types that represent or contain data that may be stored in a [Buffer].\n\n///\n\n/// Uploading data to a buffer involves doing a bitwise copy, as does downloading data from a\n\n/// buffer. WebGlitz relies on the semantics associated with the `Copy` trait to ensure that this\n\n/// is safe and does not result in memory leaks.\n\npub trait IntoBuffer<T>\n\nwhere\n\n T: ?Sized,\n\n{\n\n /// Stores the data in a buffer belonging to the given `context`, using the given `usage_hint`.\n\n ///\n\n /// This consumes the Rust value and produces a GPU-accessible [Buffer] containing a bitwise\n\n /// copy of data.\n\n ///\n\n /// The usage hint may be used by the GPU driver for performance optimizations, see [UsageHint]\n\n /// for details.\n\n fn into_buffer<Rc>(self, context: &Rc, buffer_id: BufferId, usage_hint: UsageHint) -> Buffer<T>\n\n where\n\n Rc: RenderingContext + Clone + 'static;\n\n}\n\n\n\nimpl<D, T> IntoBuffer<T> for D\n\nwhere\n\n D: Borrow<T> + 'static,\n\n T: Copy + 'static,\n", "file_path": "web_glitz/src/buffer.rs", "rank": 46, "score": 147451.89839596226 }, { "content": "/// Helper trait for [Buffer::copy_from_command] and [BufferView::copy_from_command], implemented\n\n/// for types that can be copied from.\n\npub trait CopyFrom<T>\n\nwhere\n\n T: ?Sized,\n\n{\n\n fn command(self, target_view: BufferView<T>) -> CopyCommand<T>;\n\n}\n\n\n\nimpl<'a, T> CopyFrom<T> for &'a Buffer<T> {\n\n fn command(self, target_view: BufferView<T>) -> CopyCommand<T> {\n\n if self.data.context_id != target_view.buffer.data.context_id {\n\n panic!(\"Source and target buffer must belong to the same context.\");\n\n }\n\n\n\n CopyCommand {\n\n target: target_view.buffer.data.clone(),\n\n source: self.data.clone(),\n\n target_offset_in_bytes: target_view.offset_in_bytes(),\n\n source_offset_in_bytes: 0,\n\n size_in_bytes: mem::size_of::<T>(),\n\n _marker: marker::PhantomData,\n", "file_path": "web_glitz/src/buffer.rs", "rank": 47, "score": 147445.9732866123 }, { "content": "/// Trait implemented for extension objects, used by [RenderingContext::get_extension] to\n\n/// initialize the extension.\n\npub trait Extension: Sized {\n\n /// Attempts to initialize the extension on the current [Connection] and return the extension\n\n /// object, or returns `None` if it fails.\n\n fn try_init(connection: &mut Connection, context_id: u64) -> Option<Self>;\n\n}\n", "file_path": "web_glitz/src/extensions/mod.rs", "rank": 48, "score": 145380.7608152395 }, { "content": "/// A group of resources that may be used to encode a [BindGroup].\n\n///\n\n/// See also [RenderingContext::create_bind_group] for details on how a [BindGroup] is created.\n\n///\n\n/// This trait is implemented for any type that implements the [Resources] trait. The [Resources]\n\n/// trait may automatically derived (see the documentation for the [Resources] trait for details).\n\n///\n\n/// # Example\n\n///\n\n/// ```\n\n/// use web_glitz::buffer::{Buffer, BufferView};\n\n/// use web_glitz::image::texture_2d::FloatSampledTexture2D;\n\n/// use web_glitz::pipeline::resources::{EncodeBindableResourceGroup, BindGroupEncodingContext, BindGroupEncoding, BindGroupEncoder};\n\n///\n\n/// struct Resources<'a, 'b> {\n\n/// uniform_buffer: &'a Buffer<std140::mat4x4>,\n\n/// texture: FloatSampledTexture2D<'b>\n\n/// }\n\n///\n\n/// impl<'a, 'b> EncodeBindableResourceGroup for Resources<'a, 'b> {\n\n/// type Encoding = (\n\n/// BufferView<'a, std140::mat4x4>,\n\n/// FloatSampledTexture2D<'b>,\n\n/// );\n\n///\n\n/// fn encode_bindable_resource_group(\n\n/// self,\n\n/// encoding_context: &mut BindGroupEncodingContext\n\n/// ) -> BindGroupEncoding<Self::Encoding> {\n\n/// BindGroupEncoder::new(encoding_context, Some(2))\n\n/// .add_buffer_view(0, self.uniform_buffer.into())\n\n/// .add_float_sampled_texture_2d(1, self.texture)\n\n/// .finish()\n\n/// }\n\n/// }\n\n/// ```\n\npub trait EncodeBindableResourceGroup {\n\n type Encoding;\n\n\n\n /// Encodes a description of the bindings for the resources in the group.\n\n fn encode_bindable_resource_group(\n\n self,\n\n encoding_context: &mut BindGroupEncodingContext,\n\n ) -> BindGroupEncoding<Self::Encoding>;\n\n}\n\n\n\n/// Sub-trait of [EncodeBindGroup], where a type statically describes the layout for the bind group.\n\n///\n\n/// A [BindGroup] for resources that implement this trait may be bound to pipeline's with a matching\n\n/// typed resource bindings layout without additional runtime checks.\n\n///\n\n/// # Unsafe\n\n///\n\n/// Any instance of a type that implements this trait must encode a bind group (see\n\n/// [EncodeBindGroup::encode_bind_group]) with a layout that matches the bind group layout declared\n\n/// by [Layout].\n\npub unsafe trait TypedBindableResourceGroup: EncodeBindableResourceGroup {\n\n type Layout: TypedBindGroupLayout;\n\n}\n\n\n", "file_path": "web_glitz/src/pipeline/resources/resources.rs", "rank": 49, "score": 144600.54661665595 }, { "content": "/// Helper trait for the implementation of [VertexBuffers] for tuple types.\n\npub trait VertexBuffer {\n\n fn encode(self, encoding: &mut VertexBuffersEncoding);\n\n}\n\n\n\n/// Sub-trait of [VertexBuffers], where a type statically describes the vertex attribute layout\n\n/// supported by the vertex buffers.\n\n///\n\n/// Vertex buffers that implement this trait may be bound to graphics pipelines with a matching\n\n/// [TypedVertexAttributeLayout] without further runtime checks.\n\n///\n\n/// # Unsafe\n\n///\n\n/// This trait must only by implemented for [VertexBuffers] types if the vertex buffers encoding\n\n/// for any instance of the the type is guaranteed to provide compatible vertex input data for\n\n/// each of the [VertexAttributeDescriptors] specified by the [Layout].\n\npub unsafe trait TypedVertexBuffers: VertexBuffers {\n\n /// A type statically associated with a vertex attribute layout with which any instance of these\n\n /// [TypedVertexBuffers] is compatible.\n\n type Layout: TypedVertexInputLayout;\n\n}\n", "file_path": "web_glitz/src/pipeline/graphics/vertex/vertex_buffers.rs", "rank": 50, "score": 144584.9765972176 }, { "content": "/// Helper trait implemented by types that describe a color image attachment for a [RenderTarget].\n\npub trait EncodeColorBuffer {\n\n /// The type of [RenderingOutputBuffer] that is allocated in the framebuffer to buffer\n\n /// modifications to the attached image.\n\n type Buffer: RenderingOutputBuffer;\n\n\n\n /// Returns an encoding of the information needed by a [RenderPass] to load data from the\n\n /// attached image into the framebuffer before the render pass, and to store data from the\n\n /// framebuffer back into the attached image after the render pass.\n\n fn encode_color_buffer<'a, 'b>(\n\n &'a mut self,\n\n context: &'b mut ColorBufferEncodingContext,\n\n ) -> ColorBufferEncoding<'b, 'a, Self::Buffer>;\n\n}\n\n\n", "file_path": "web_glitz/src/rendering/encode_color_buffer.rs", "rank": 51, "score": 144584.67654086972 }, { "content": "/// Encodes a description of a (set of) buffer(s) or buffer region(s) that can serve as the vertex\n\n/// input data source(s) for a graphics pipeline.\n\npub trait VertexBuffers {\n\n fn encode<'a>(self, context: &'a mut VertexBuffersEncodingContext)\n\n -> VertexBuffersEncoding<'a>;\n\n}\n\n\n", "file_path": "web_glitz/src/pipeline/graphics/vertex/vertex_buffers.rs", "rank": 52, "score": 144578.92601199076 }, { "content": "/// Helper trait implemented by types that describe a depth-stencil image attachment for a\n\n/// [RenderTarget].\n\npub trait EncodeDepthStencilBuffer {\n\n /// The type of [RenderingOutputBuffer] that is allocated in the framebuffer to buffer\n\n /// modifications to the attached image.\n\n type Buffer: RenderingOutputBuffer;\n\n\n\n /// Returns an encoding of the information needed by a [RenderPass] to load data from the\n\n /// attached image into the framebuffer before the render pass, and to store data from the\n\n /// framebuffer back into the attached image after the render pass.\n\n fn encode_depth_stencil_buffer<'a, 'b>(\n\n &'a mut self,\n\n context: &'b mut DepthStencilBufferEncodingContext,\n\n ) -> DepthStencilBufferEncoding<'b, 'a, Self::Buffer>;\n\n}\n\n\n", "file_path": "web_glitz/src/rendering/encode_depth_stencil_buffer.rs", "rank": 53, "score": 141150.18938123854 }, { "content": "/// Helper trait for the implementation of [FeedbackBuffers] for tuple types.\n\npub trait TransformFeedbackBuffer {\n\n fn encode(self, encoding: &mut TransformFeedbackBuffersEncoding);\n\n}\n\n\n\n/// Sub-trait of [TransformFeedbackBuffers], where a type statically describes the feedback\n\n/// attribute layout supported by the feedback buffers.\n\n///\n\n/// Transform feedback buffers that implement this trait may be bound to graphics pipelines with a\n\n/// matching [TypedTransformFeedbackLayout] without further runtime checks.\n\n///\n\n/// # Unsafe\n\n///\n\n/// This trait must only by implemented for [FeedbackBuffers] types if the feedback buffers encoding\n\n/// for any instance of the the type is guaranteed to be bit-wise compatible with the output\n\n/// feedback recorded from the graphics pipeline.\n\npub unsafe trait TypedTransformFeedbackBuffers: TransformFeedbackBuffers {\n\n /// A type statically associated with a feedback attribute layout with which any instance of\n\n /// these [TypedFeedbackBuffers] is compatible.\n\n type Layout: TypedTransformFeedbackLayout;\n\n}\n", "file_path": "web_glitz/src/pipeline/graphics/transform_feedback/transform_feedback_buffers.rs", "rank": 54, "score": 139530.6462584717 }, { "content": "/// Encodes a description of a (set of) buffer(s) or buffer region(s) that can record the output\n\n/// feedback from the transform stage of a graphics pipeline.\n\npub trait TransformFeedbackBuffers {\n\n fn encode<'a>(\n\n self,\n\n context: &'a mut TransformFeedbackBuffersEncodingContext,\n\n ) -> TransformFeedbackBuffersEncoding<'a>;\n\n}\n\n\n", "file_path": "web_glitz/src/pipeline/graphics/transform_feedback/transform_feedback_buffers.rs", "rank": 55, "score": 139519.5198847779 }, { "content": "pub trait ContextUpdate<'a, E> {\n\n fn apply(self, context: &Gl) -> Result<(), E>;\n\n}\n\n\n\nimpl<'a, F, E> ContextUpdate<'a, E> for Option<F>\n\nwhere\n\n F: FnOnce(&Gl) -> Result<(), E> + 'a,\n\n{\n\n fn apply(self, context: &Gl) -> Result<(), E> {\n\n self.map(|f| f(context)).unwrap_or(Ok(()))\n\n }\n\n}\n\n\n\n#[derive(Clone, Copy)]\n\npub enum BufferRange<T> {\n\n None,\n\n Full(T),\n\n OffsetSize(T, u32, u32),\n\n}\n\n\n", "file_path": "web_glitz/src/runtime/state.rs", "rank": 56, "score": 139285.58841628264 }, { "content": "fn run_mode(mode: &'static str) {\n\n let mut config = compiletest::Config::default();\n\n\n\n config.mode = mode.parse().expect(\"Invalid mode\");\n\n config.src_base = PathBuf::from(format!(\"tests/{}\", mode));\n\n config.link_deps(); // Populate config.target_rustcflags with dependencies on the path\n\n config.clean_rmeta(); // If your tests import the parent crate, this helps with E0464\n\n\n\n compiletest::run_tests(&config);\n\n}\n\n\n", "file_path": "web_glitz_test/tests/compile_test.rs", "rank": 57, "score": 138150.53701690043 }, { "content": "/// A helper trait type for indexing operations on a [Buffer] that contains a slice.\n\npub trait BufferSliceIndex<T>: Sized {\n\n /// The output type returned by the indexing operations.\n\n type Output: ?Sized;\n\n\n\n /// Returns a view on the output for this operation if in bounds, or `None` otherwise.\n\n fn get(self, buffer: &Buffer<[T]>) -> Option<BufferView<Self::Output>>;\n\n\n\n /// Returns a view on the output for this operation, without performing any bounds checking.\n\n unsafe fn get_unchecked(self, buffer: &Buffer<[T]>) -> BufferView<Self::Output>;\n\n\n\n /// Returns a mutable view on the output for this operation if in bounds, or `None` otherwise.\n\n fn get_mut(self, buffer: &mut Buffer<[T]>) -> Option<BufferViewMut<Self::Output>> {\n\n self.get(buffer).map(|view| BufferViewMut {\n\n inner: view,\n\n _marker: marker::PhantomData,\n\n })\n\n }\n\n\n\n /// Returns a mutable view the output for this operation, without performing any bounds\n\n /// checking.\n", "file_path": "web_glitz/src/buffer.rs", "rank": 58, "score": 137398.23625190862 }, { "content": "/// Sealed trait implemented for marker types that identify magnification filtering operations used\n\n/// by [Sampler]s.\n\n///\n\n/// Magnification filtering is used when a sampling a texture value for a fragment that is smaller\n\n/// than the candidate texels. See [Nearest] and [Linear] for details on how these filtering\n\n/// operations resolve to sampling values.\n\npub trait MagnificationFilter: filter_seal::Seal {\n\n const ID: u32;\n\n}\n\n\n", "file_path": "web_glitz/src/image/sampler.rs", "rank": 59, "score": 135584.22612540118 }, { "content": "/// Sealed trait implemented for marker types that identify minification filtering operations used\n\n/// by [Sampler]s.\n\n///\n\n/// Minification filtering is used when a sampling a texture value for a fragment that is larger\n\n/// than the candidate texels.\n\n///\n\n/// # Minification Filtering and Mipmapping\n\n///\n\n/// Some of the filtering methods involve mipmapping. When a fragment is larger than the candidate\n\n/// texels, the fragment surface might span multiple texels. The most appropriate sample value might\n\n/// then be obtained by interpolating between these texels. However, doing this for each sampling\n\n/// operation can be very expensive.\n\n///\n\n/// This is instead solved by using a mipmap, which produces similar results with much better\n\n/// performance. A mipmap is a pre-calculated sequence of images, starting with the original image.\n\n/// Each subsequent image is half the width and half the height of the previous image (rounded\n\n/// down). The sequence ends when the width or height reaches 1. Each image in the mipmap sequence\n\n/// is identified by a mipmap level: the base image has a mipmap level of 0, the subsequent image\n\n/// has a mipmap level of 1, etc. For example, a mipmap of a base image of size 256 by 256 has 9\n\n/// mipmap levels: 256x256 (level 0), 128x128 (level 1), 64x64 (level 2), 32x32 (level 3), 16x16\n\n/// (level 4), 8x8 (level 5), 4x4 (level 6), 2x2 (level 7), 1x1 (level 8).\n\n///\n\n/// See the documentation for [NearestMipmapNearest], [NearestMipmapLinear], [LinearMipmapNearest]\n\n/// and [LinearMipmapLinear] for details on how these filtering operations will make use of a\n\n/// mipmap. See [Nearest] and [Linear] for details on filtering operations that don't use a mipmap.\n\npub trait MinificationFilter: filter_seal::Seal {\n\n const ID: u32;\n\n}\n\n\n\n/// Marker trait for valid filter and texture format combinations\n\npub unsafe trait CompatibleFilter<F>\n\nwhere\n\n F: TextureFormat,\n\n{\n\n}\n\n\n\n/// The sampled value is chosen to be the value of the texel whose coordinates are closest to\n\n/// the sampling coordinates.\n\n#[derive(Clone, Copy, PartialEq, Eq, Hash, Debug)]\n\npub struct Nearest;\n\n\n\nimpl MinificationFilter for Nearest {\n\n const ID: u32 = Gl::NEAREST;\n\n}\n\n\n", "file_path": "web_glitz/src/image/sampler.rs", "rank": 60, "score": 135583.65276949335 }, { "content": "/// A helper trait type for indexing operations on a [BufferView] that contains a slice.\n\npub trait BufferViewSliceIndex<T>: Sized {\n\n /// The output type returned by the indexing operations.\n\n type Output: ?Sized;\n\n\n\n /// Returns a view on the output for this operation if in bounds, or `None` otherwise.\n\n fn get<'a>(self, view: &'a BufferView<[T]>) -> Option<BufferView<'a, Self::Output>>;\n\n\n\n /// Returns a view on the output for this operation, without performing any bounds checking.\n\n unsafe fn get_unchecked<'a>(self, view: &'a BufferView<[T]>) -> BufferView<'a, Self::Output>;\n\n}\n\n\n\nimpl<T> BufferViewSliceIndex<T> for usize {\n\n type Output = T;\n\n\n\n fn get<'a>(self, view: &'a BufferView<[T]>) -> Option<BufferView<'a, Self::Output>> {\n\n if self < view.len {\n\n Some(BufferView {\n\n buffer: unsafe { mem::transmute(view.buffer) },\n\n offset_in_bytes: view.offset_in_bytes + self * mem::size_of::<T>(),\n\n len: 1,\n", "file_path": "web_glitz/src/buffer.rs", "rank": 61, "score": 135575.74098955933 }, { "content": "/// Helper trait for implementing [Framebuffer::pipeline_task] for both a plain graphics pipeline\n\n/// and a graphics pipeline that will record transform feedback.\n\npub trait GraphicsPipelineState<V, R, Tf> {\n\n /// Creates a new pipeline task.\n\n ///\n\n /// See [Framebuffer::pipeline_task] for details.\n\n fn pipeline_task<F, T>(&self, target: &GraphicsPipelineTarget, f: F) -> PipelineTask<T>\n\n where\n\n F: Fn(ActiveGraphicsPipeline<V, R, Tf>) -> T,\n\n T: GpuTask<PipelineTaskContext>;\n\n}\n\n\n\nimpl<V, R, Tf> GraphicsPipelineState<V, R, Tf> for GraphicsPipeline<V, R, Tf> {\n\n fn pipeline_task<F, T>(&self, target: &GraphicsPipelineTarget, f: F) -> PipelineTask<T>\n\n where\n\n F: Fn(ActiveGraphicsPipeline<V, R, Tf>) -> T,\n\n T: GpuTask<PipelineTaskContext>,\n\n {\n\n PipelineTask::new(target, self, None, f)\n\n }\n\n}\n\n\n", "file_path": "web_glitz/src/rendering/framebuffer.rs", "rank": 62, "score": 130331.92183022993 }, { "content": "/// A helper trait type for indexing operations on a [IndexBuffer].\n\npub trait IndexBufferSliceRange<T>: Sized {\n\n /// Returns a view on the index buffer if in bounds, or `None` otherwise.\n\n fn get(self, index_buffer: &IndexBuffer<T>) -> Option<IndexBufferView<T>>;\n\n\n\n /// Returns a view on the index buffer, without performing any bounds checking.\n\n unsafe fn get_unchecked(self, index_buffer: &IndexBuffer<T>) -> IndexBufferView<T>;\n\n}\n\n\n\nimpl<T> IndexBufferSliceRange<T> for RangeFull {\n\n fn get(self, index_buffer: &IndexBuffer<T>) -> Option<IndexBufferView<T>> {\n\n Some(IndexBufferView {\n\n buffer: index_buffer,\n\n offset_in_bytes: 0,\n\n len: index_buffer.data.len,\n\n })\n\n }\n\n\n\n unsafe fn get_unchecked(self, index_buffer: &IndexBuffer<T>) -> IndexBufferView<T> {\n\n IndexBufferView {\n\n buffer: index_buffer,\n", "file_path": "web_glitz/src/pipeline/graphics/vertex/index_buffer.rs", "rank": 63, "score": 128961.70454897708 }, { "content": "#[proc_macro_derive(Resources, attributes(resource))]\n\npub fn derive_resources(input: TokenStream) -> TokenStream {\n\n let input = parse_macro_input!(input as DeriveInput);\n\n\n\n resources::expand_derive_resources(&input)\n\n .unwrap_or_else(compile_error)\n\n .into()\n\n}\n\n\n", "file_path": "web_glitz_macros/src/lib.rs", "rank": 64, "score": 128744.4721545403 }, { "content": "#[proc_macro_derive(Vertex, attributes(vertex_per_instance, vertex_attribute))]\n\npub fn derive_vertex(input: TokenStream) -> TokenStream {\n\n let input = parse_macro_input!(input as DeriveInput);\n\n\n\n vertex::expand_derive_vertex(&input)\n\n .unwrap_or_else(compile_error)\n\n .into()\n\n}\n\n\n", "file_path": "web_glitz_macros/src/lib.rs", "rank": 65, "score": 128744.4721545403 }, { "content": "/// A helper trait type for indexing operations on an [IndexBufferView].\n\npub trait IndexBufferViewSliceIndex<T>: Sized {\n\n /// Returns a view on the [IndexBufferView] if in bounds, or `None` otherwise.\n\n fn get<'a>(self, view: &'a IndexBufferView<T>) -> Option<IndexBufferView<'a, T>>;\n\n\n\n /// Returns a view on the [IndexBufferView], without performing any bounds checking.\n\n unsafe fn get_unchecked<'a>(self, view: &'a IndexBufferView<T>) -> IndexBufferView<'a, T>;\n\n}\n\n\n\nimpl<T> IndexBufferViewSliceIndex<T> for RangeFull {\n\n fn get<'a>(self, view: &'a IndexBufferView<T>) -> Option<IndexBufferView<'a, T>> {\n\n Some(IndexBufferView {\n\n buffer: view.buffer,\n\n offset_in_bytes: view.offset_in_bytes,\n\n len: view.len,\n\n })\n\n }\n\n\n\n unsafe fn get_unchecked<'a>(self, view: &'a IndexBufferView<T>) -> IndexBufferView<'a, T> {\n\n IndexBufferView {\n\n buffer: view.buffer,\n", "file_path": "web_glitz/src/pipeline/graphics/vertex/index_buffer.rs", "rank": 66, "score": 127458.45015219986 }, { "content": "#[proc_macro_derive(InterfaceBlock)]\n\npub fn derive_interface_block(input: TokenStream) -> TokenStream {\n\n let input = parse_macro_input!(input as DeriveInput);\n\n\n\n interface_block::expand_derive_interface_block(&input)\n\n .unwrap_or_else(compile_error)\n\n .into()\n\n}\n\n\n", "file_path": "web_glitz_macros/src/lib.rs", "rank": 67, "score": 127124.3712046418 }, { "content": "#[proc_macro_derive(TransformFeedback)]\n\npub fn derive_transform_feedback(input: TokenStream) -> TokenStream {\n\n let input = parse_macro_input!(input as DeriveInput);\n\n\n\n transform_feedback::expand_derive_transform_feedback(&input).into()\n\n}\n\n\n", "file_path": "web_glitz_macros/src/lib.rs", "rank": 68, "score": 127124.3712046418 }, { "content": "pub trait GpuTaskExt<Ec>: GpuTask<Ec> {\n\n fn map<F, U>(self, f: F) -> Map<Self, F>\n\n where\n\n F: FnOnce(Self::Output) -> U,\n\n Self: Sized;\n\n\n\n /// Combines this task with another task `b`, waiting for both tasks to complete in no\n\n /// particular order.\n\n ///\n\n /// This returns a new \"joined\" task. This joined task may progress the its sub-tasks in any\n\n /// order. The joined task will finish when both sub-tasks have finished. When it finishes, it\n\n /// will output a tuple `(A, B)` where `A` is this tasks output and `B` is task `b`'s output.\n\n ///\n\n /// # Panics\n\n ///\n\n /// Panics if the [ContextId] of `b` is not compatible with this task's [ContextId].\n\n fn join<B>(self, b: B) -> Join<Self, B, Ec>\n\n where\n\n B: GpuTask<Ec>,\n\n Self: Sized;\n", "file_path": "web_glitz/src/task/gpu_task.rs", "rank": 69, "score": 127023.27338345101 }, { "content": "pub fn expand_derive_transform_feedback(input: &DeriveInput) -> TokenStream {\n\n if let Data::Struct(data) = &input.data {\n\n let struct_name = &input.ident;\n\n let mod_path = quote!(web_glitz::pipeline::graphics);\n\n\n\n let recurse = data.fields.iter().map(|field| {\n\n let name = field\n\n .ident\n\n .clone()\n\n .expect(\"`TransformFeedback` can only be derived for a struct with named fields.\")\n\n .to_string();\n\n let ty = &field.ty;\n\n let span = field.span();\n\n\n\n quote_spanned!(span=> {\n\n #mod_path::TransformFeedbackAttributeDescriptor {\n\n ident: #mod_path::TransformFeedbackAttributeIdentifier::Static(#name),\n\n attribute_type: <#ty as #mod_path::TransformFeedbackAttribute>::TYPE,\n\n size: <#ty as #mod_path::TransformFeedbackAttribute>::SIZE\n\n }\n", "file_path": "web_glitz_macros/src/transform_feedback.rs", "rank": 70, "score": 124061.00567902773 }, { "content": "fn main() {\n\n\n\n}\n\n\n", "file_path": "web_glitz_test/tests/compile-fail/vertex_attribute_invalid_type.rs", "rank": 71, "score": 120914.73321500627 }, { "content": "/// Combines task `a`, `b`, `c`, `d` and `e`, waiting for all tasks to complete in order, with the\n\n/// output of task `e`.\n\n///\n\n/// Similar to [sequence5], except that instead of returning a tuple of the outputs of `a`, `b`,\n\n/// `c`, `d` and `e`, it only returns the output of `e`.\n\n///\n\n/// See also [sequence5_left].\n\n///\n\n/// # Panics\n\n///\n\n/// Panics if the [ContextId]s `a`, `b`, `c`, `d` and `e` are not compatible.\n\npub fn sequence5_right<A, B, C, D, E, Ec>(\n\n a: A,\n\n b: B,\n\n c: C,\n\n d: D,\n\n e: E,\n\n) -> Sequence5Right<A, B, C, D, E, Ec>\n\nwhere\n\n A: GpuTask<Ec>,\n\n B: GpuTask<Ec>,\n\n C: GpuTask<Ec>,\n\n D: GpuTask<Ec>,\n\n E: GpuTask<Ec>,\n\n{\n\n Sequence5Right::new(a, b, c, d, e)\n\n}\n\n\n", "file_path": "web_glitz/src/task/sequence.rs", "rank": 72, "score": 120835.59777644032 }, { "content": "/// Combines task `a`, `b`, `c`, `d` and `e`, waiting for all tasks to complete in order, with the\n\n/// output of task `a`.\n\n///\n\n/// Similar to [sequence5], except that instead of returning a tuple of the outputs of `a`, `b`,\n\n/// `c`, `d` and `e`, it only returns the output of `a`.\n\n///\n\n/// See also [sequence5_right].\n\n///\n\n/// # Panics\n\n///\n\n/// Panics if the [ContextId]s `a`, `b`, `c`, `d` and `e` are not compatible.\n\npub fn sequence5_left<A, B, C, D, E, Ec>(\n\n a: A,\n\n b: B,\n\n c: C,\n\n d: D,\n\n e: E,\n\n) -> Sequence5Left<A, B, C, D, E, Ec>\n\nwhere\n\n A: GpuTask<Ec>,\n\n B: GpuTask<Ec>,\n\n C: GpuTask<Ec>,\n\n D: GpuTask<Ec>,\n\n E: GpuTask<Ec>,\n\n{\n\n Sequence5Left::new(a, b, c, d, e)\n\n}\n\n\n", "file_path": "web_glitz/src/task/sequence.rs", "rank": 73, "score": 120835.59777644032 }, { "content": "#[derive(web_glitz::derive::Vertex)]\n\nstruct VertexA {\n\n #[vertex_attribute(location = 0, format = \"Float4_f32\")]\n\n position: String //~ ERROR: the trait bound `String: VertexAttributeFormatCompatible<web_glitz::pipeline::graphics::attribute_format::Float4_f32>` is not satisfied\n\n}\n\n\n", "file_path": "web_glitz_test/tests/compile-fail/vertex_attribute_invalid_type.rs", "rank": 74, "score": 120806.62434238312 }, { "content": "#[test]\n\nfn test_struct_attribute_descriptors() {\n\n let descriptors = VertexA::ATTRIBUTE_DESCRIPTORS;\n\n\n\n assert_eq!(\n\n descriptors,\n\n &[\n\n VertexAttributeDescriptor {\n\n location: 0,\n\n format: VertexAttributeFormat::Float4_f32,\n\n offset_in_bytes: 0\n\n },\n\n VertexAttributeDescriptor {\n\n location: 1,\n\n format: VertexAttributeFormat::Float3_i8_norm,\n\n offset_in_bytes: 16\n\n },\n\n VertexAttributeDescriptor {\n\n location: 2,\n\n format: VertexAttributeFormat::Float4x4_f32,\n\n offset_in_bytes: 24\n", "file_path": "web_glitz_test/tests/vertex_macro_derive_test.rs", "rank": 76, "score": 119054.01982853175 }, { "content": "fn main() {\n\n\n\n}\n", "file_path": "web_glitz_test/tests/compile-fail/vertex_attribute_invalid_format_override.rs", "rank": 77, "score": 118790.71444430077 }, { "content": "#[derive(web_glitz::derive::Vertex)] //~ ERROR: cannot find type `unknown_format` in this scope\n\nstruct VertexA {\n\n #[vertex_attribute(location = 0, format = \"unknown_format\")]\n\n position: [i8; 3]\n\n}\n\n\n", "file_path": "web_glitz_test/tests/compile-fail/vertex_attribute_invalid_format_override.rs", "rank": 78, "score": 118693.38040378256 }, { "content": "pub fn expand_derive_vertex(input: &DeriveInput) -> Result<TokenStream, String> {\n\n if let Data::Struct(ref data) = input.data {\n\n let struct_name = &input.ident;\n\n let mod_path = quote!(web_glitz::pipeline::graphics);\n\n let mut log = ErrorLog::new();\n\n\n\n let mut per_instance = false;\n\n\n\n for attribute in &input.attrs {\n\n if attribute.path.is_ident(\"vertex_per_instance\") {\n\n if !attribute.tokens.is_empty() {\n\n log.log_error(\"The `vertex_per_instance` attribute does not take parameters.\");\n\n } else {\n\n per_instance = true;\n\n }\n\n }\n\n }\n\n\n\n let input_rate = if per_instance {\n\n quote!(#mod_path::InputRate::PerInstance)\n", "file_path": "web_glitz_macros/src/vertex.rs", "rank": 79, "score": 118443.44169693411 }, { "content": "pub fn expand_derive_resources(input: &DeriveInput) -> Result<TokenStream, String> {\n\n if let Data::Struct(ref data) = input.data {\n\n let struct_name = &input.ident;\n\n let mod_path = quote!(web_glitz::pipeline::resources);\n\n let mut log = ErrorLog::new();\n\n\n\n let mut resource_fields: Vec<ResourceField> = Vec::new();\n\n\n\n for (position, field) in data.fields.iter().enumerate() {\n\n match ResourcesField::from_ast(field, position, &mut log) {\n\n ResourcesField::Resource(resource_field) => {\n\n for field in resource_fields.iter() {\n\n if field.binding == resource_field.binding {\n\n log.log_error(format!(\n\n \"Fields `{}` and `{}` cannot both use binding `{}`.\",\n\n field.name, resource_field.name, field.binding\n\n ));\n\n }\n\n }\n\n\n", "file_path": "web_glitz_macros/src/resources.rs", "rank": 80, "score": 118443.44169693411 }, { "content": "pub fn expand_derive_interface_block(input: &DeriveInput) -> Result<TokenStream, String> {\n\n if let Data::Struct(data) = &input.data {\n\n let mod_path = quote!(web_glitz::pipeline::interface_block);\n\n let struct_name = &input.ident;\n\n\n\n let recurse_len = data.fields.iter().map(|field| {\n\n let ty = &field.ty;\n\n let span = field.span();\n\n\n\n quote_spanned! {span=>\n\n <#ty as #mod_path::InterfaceBlockComponent>::MEMORY_UNITS.len()\n\n }\n\n });\n\n\n\n let recurse_array = data.fields.iter().enumerate().map(|(position, field)| {\n\n let ty = &field.ty;\n\n let ident = field\n\n .ident\n\n .clone()\n\n .map(|i| i.into_token_stream())\n", "file_path": "web_glitz_macros/src/interface_block.rs", "rank": 81, "score": 115595.16431094456 }, { "content": "/// Combines all tasks in an iterator, waiting for all tasks to complete in order.\n\n///\n\n/// This returns a new \"sequenced\" task. This sequenced task must progress its sub-tasks in order.\n\n/// The sequenced task will finish when all sub-tasks have finished. When it finishes, it will\n\n/// output `()`. All tasks in the iterator must also output `()`.\n\n///\n\n/// This combinator allocates. See also the [sequence_all] macro for an alternative that does not\n\n/// allocate if the set of tasks that are to be joined is statically known.\n\n///\n\n/// # Panics\n\n///\n\n/// Panics if the [ContextId]s of any of the tasks in the iterator are not compatible.\n\npub fn sequence_iter<I, Ec>(iterator: I) -> SequenceIter<I::Item, Ec>\n\nwhere\n\n I: IntoIterator,\n\n I::Item: GpuTask<Ec, Output = ()>,\n\n{\n\n SequenceIter::new(iterator)\n\n}\n", "file_path": "web_glitz/src/task/sequence.rs", "rank": 82, "score": 115388.69216870448 }, { "content": "/// Combines all tasks in an iterator, waiting for all tasks to complete in no particular order.\n\n///\n\n/// This returns a new \"joined\" task. This joined task may progress the its sub-tasks in any order.\n\n/// The joined task will finish when both sub-tasks have finished. When it finishes, it will output\n\n/// `()`. All tasks in the iterator must also output `()`.\n\n///\n\n/// This combinator allocates. See also the [join_all] macro for an alternative that does not\n\n/// allocate if the set of tasks that are to be sequenced is statically known.\n\n///\n\n/// # Panics\n\n///\n\n/// Panics if the [ContextId]s of any of the tasks in the iterator are not compatible.\n\npub fn join_iter<I, Ec>(iterator: I) -> JoinIter<I::Item, Ec>\n\nwhere\n\n I: IntoIterator,\n\n I::Item: GpuTask<Ec, Output = ()>,\n\n{\n\n JoinIter::new(iterator)\n\n}\n", "file_path": "web_glitz/src/task/join.rs", "rank": 83, "score": 115388.66706876426 }, { "content": "/// Combines task `a` with another task `b`, waiting for both tasks to complete in no particular\n\n/// order.\n\n///\n\n/// This returns a new \"joined\" task. This joined task may progress the its sub-tasks in any order.\n\n/// The joined task will finish when both sub-tasks have finished. When it finishes, it will output\n\n/// a tuple `(A, B)` where `A` is this task's output and `B` is task `b`'s output.\n\n///\n\n/// # Panics\n\n///\n\n/// Panics if the [ContextId]s of `a` and `b` are not compatible.\n\npub fn join<A, B, Ec>(a: A, b: B) -> Join<A, B, Ec>\n\nwhere\n\n A: GpuTask<Ec>,\n\n B: GpuTask<Ec>,\n\n{\n\n Join::new(a, b)\n\n}\n\n\n", "file_path": "web_glitz/src/task/join.rs", "rank": 84, "score": 112608.71689774362 }, { "content": "/// Combines task `a` with another task `b`, waiting for both tasks to complete in order.\n\n///\n\n/// This returns a new \"sequenced\" task. This sequenced task must progress its sub-tasks in order.\n\n/// The sequenced task will finish when both sub-tasks have finished. When it finishes, it will\n\n/// output a tuple `(A, B)` where `A` is this tasks output and `B` is task `b`'s output.\n\n///\n\n/// # Panics\n\n///\n\n/// Panics if the [ContextId]s of `a` and `b` are not compatible.\n\npub fn sequence<A, B, Ec>(a: A, b: B) -> Sequence<A, B, Ec>\n\nwhere\n\n A: GpuTask<Ec>,\n\n B: GpuTask<Ec>,\n\n{\n\n Sequence::new(a, b)\n\n}\n\n\n", "file_path": "web_glitz/src/task/sequence.rs", "rank": 85, "score": 112608.71689774362 }, { "content": "/// Combines task `a` with another task `b`, waiting for both tasks to complete in no particular\n\n/// order, with the output of task `a`.\n\n///\n\n/// Similar to [join], except that instead of returning a tuple of the outputs of `a` and `b`, it\n\n/// only returns the output of `b`.\n\n///\n\n/// See also [join_left].\n\n///\n\n/// # Panics\n\n///\n\n/// Panics if the [ContextId]s of `a` and `b` are not compatible.\n\npub fn join_right<A, B, Ec>(a: A, b: B) -> JoinRight<A, B, Ec>\n\nwhere\n\n A: GpuTask<Ec>,\n\n B: GpuTask<Ec>,\n\n{\n\n JoinRight::new(a, b)\n\n}\n\n\n", "file_path": "web_glitz/src/task/join.rs", "rank": 86, "score": 109428.55265561161 }, { "content": "/// Combines task `a` with another task `b`, waiting for both tasks to complete in no particular\n\n/// order, with the output of task `a`.\n\n///\n\n/// Similar to [join], except that instead of returning a tuple of the outputs of `a` and `b`, it\n\n/// only returns the output of `a`.\n\n///\n\n/// See also [join_right].\n\n///\n\n/// # Panics\n\n///\n\n/// Panics if the [ContextId]s of `a` and `b` are not compatible.\n\npub fn join_left<A, B, Ec>(a: A, b: B) -> JoinLeft<A, B, Ec>\n\nwhere\n\n A: GpuTask<Ec>,\n\n B: GpuTask<Ec>,\n\n{\n\n JoinLeft::new(a, b)\n\n}\n\n\n", "file_path": "web_glitz/src/task/join.rs", "rank": 87, "score": 109428.55265561161 }, { "content": "/// Combines task `a` with another task `b`, waiting for both tasks to complete in order, with the\n\n/// output of task `a`.\n\n///\n\n/// Similar to [sequence], except that instead of returning a tuple of the outputs of `a` and `b`,\n\n/// it only returns the output of `b`.\n\n///\n\n/// See also [sequence_left].\n\n///\n\n/// # Panics\n\n///\n\n/// Panics if the [ContextId]s of `a` and `b` are not compatible.\n\npub fn sequence_right<A, B, Ec>(a: A, b: B) -> SequenceRight<A, B, Ec>\n\nwhere\n\n A: GpuTask<Ec>,\n\n B: GpuTask<Ec>,\n\n{\n\n SequenceRight::new(a, b)\n\n}\n\n\n", "file_path": "web_glitz/src/task/sequence.rs", "rank": 88, "score": 109428.55265561161 }, { "content": "/// Combines task `a` with another task `b`, waiting for both tasks to complete in order, with the\n\n/// output of task `a`.\n\n///\n\n/// Similar to [sequence], except that instead of returning a tuple of the outputs of `a` and `b`,\n\n/// it only returns the output of `a`.\n\n///\n\n/// See also [sequence_right].\n\n///\n\n/// # Panics\n\n///\n\n/// Panics if the [ContextId]s of `a` and `b` are not compatible.\n\npub fn sequence_left<A, B, Ec>(a: A, b: B) -> SequenceLeft<A, B, Ec>\n\nwhere\n\n A: GpuTask<Ec>,\n\n B: GpuTask<Ec>,\n\n{\n\n SequenceLeft::new(a, b)\n\n}\n\n\n", "file_path": "web_glitz/src/task/sequence.rs", "rank": 89, "score": 109428.55265561161 }, { "content": "/// Combines task `a`, `b` and `c`, waiting for all tasks to complete in order.\n\n///\n\n/// This returns a new \"sequenced\" task. This sequenced task must progress its sub-tasks in order.\n\n/// The sequenced task will finish when all sub-tasks have finished. When it finishes, it will\n\n/// output a tuple `(A, B, C)` where `A` is this task's output, `B` is task `b`'s output and `C` is\n\n/// task `c`'s output.\n\n///\n\n/// # Panics\n\n///\n\n/// Panics if the [ContextId]s `a`, `b` and `c` are not compatible.\n\npub fn sequence3<A, B, C, Ec>(a: A, b: B, c: C) -> Sequence3<A, B, C, Ec>\n\nwhere\n\n A: GpuTask<Ec>,\n\n B: GpuTask<Ec>,\n\n C: GpuTask<Ec>,\n\n{\n\n Sequence3::new(a, b, c)\n\n}\n\n\n", "file_path": "web_glitz/src/task/sequence.rs", "rank": 90, "score": 103686.50293331376 }, { "content": "/// Combines task `a`, `b` and `c`, waiting for all tasks to complete in no particular order.\n\n///\n\n/// This returns a new \"joined\" task. This joined task may progress the its sub-tasks in any order.\n\n/// The joined task will finish when all sub-tasks have finished. When it finishes, it will output a\n\n/// tuple `(A, B, C)` where `A` is this task's output, `B` is task `b`'s output and `C` is task\n\n/// `c`'s output.\n\n///\n\n/// # Panics\n\n///\n\n/// Panics if the [ContextId]s `a`, `b` and `c` are not compatible.\n\npub fn join3<A, B, C, Ec>(a: A, b: B, c: C) -> Join3<A, B, C, Ec>\n\nwhere\n\n A: GpuTask<Ec>,\n\n B: GpuTask<Ec>,\n\n C: GpuTask<Ec>,\n\n{\n\n Join3::new(a, b, c)\n\n}\n\n\n", "file_path": "web_glitz/src/task/join.rs", "rank": 91, "score": 103686.50293331376 }, { "content": "/// Combines task `a`, `b` and `c`, waiting for all tasks to complete in no particular order, with\n\n/// the output of task `a`.\n\n///\n\n/// Similar to [join3], except that instead of returning a tuple of the outputs of `a`, `b` and `c`,\n\n/// it only returns the output of `a`.\n\n///\n\n/// See also [join3_right].\n\n///\n\n/// # Panics\n\n///\n\n/// Panics if the [ContextId]s `a`, `b` and `c` are not compatible.\n\npub fn join3_left<A, B, C, Ec>(a: A, b: B, c: C) -> Join3Left<A, B, C, Ec>\n\nwhere\n\n A: GpuTask<Ec>,\n\n B: GpuTask<Ec>,\n\n C: GpuTask<Ec>,\n\n{\n\n Join3Left::new(a, b, c)\n\n}\n\n\n", "file_path": "web_glitz/src/task/join.rs", "rank": 92, "score": 100838.22554732421 }, { "content": "/// Combines task `a`, `b` and `c`, waiting for all tasks to complete in order, with the output of\n\n/// task `a`.\n\n///\n\n/// Similar to [sequence3], except that instead of returning a tuple of the outputs of `a`, `b` and\n\n/// `c`, it only returns the output of `a`.\n\n///\n\n/// See also [sequence3_right].\n\n///\n\n/// # Panics\n\n///\n\n/// Panics if the [ContextId]s `a`, `b` and `c` are not compatible.\n\npub fn sequence3_left<A, B, C, Ec>(a: A, b: B, c: C) -> Sequence3Left<A, B, C, Ec>\n\nwhere\n\n A: GpuTask<Ec>,\n\n B: GpuTask<Ec>,\n\n C: GpuTask<Ec>,\n\n{\n\n Sequence3Left::new(a, b, c)\n\n}\n\n\n", "file_path": "web_glitz/src/task/sequence.rs", "rank": 93, "score": 100838.22554732421 }, { "content": "/// Combines task `a`, `b` and `c`, waiting for all tasks to complete in order, with\n\n/// the output of task `c`.\n\n///\n\n/// Similar to [sequence3], except that instead of returning a tuple of the outputs of `a`, `b` and\n\n/// `c`, it only returns the output of `c`.\n\n///\n\n/// See also [sequence3_left].\n\n///\n\n/// # Panics\n\n///\n\n/// Panics if the [ContextId]s `a`, `b` and `c` are not compatible.\n\npub fn sequence3_right<A, B, C, Ec>(a: A, b: B, c: C) -> Sequence3Right<A, B, C, Ec>\n\nwhere\n\n A: GpuTask<Ec>,\n\n B: GpuTask<Ec>,\n\n C: GpuTask<Ec>,\n\n{\n\n Sequence3Right::new(a, b, c)\n\n}\n\n\n", "file_path": "web_glitz/src/task/sequence.rs", "rank": 94, "score": 100838.22554732421 }, { "content": "/// Combines task `a`, `b` and `c`, waiting for all tasks to complete in no particular order, with\n\n/// the output of task `c`.\n\n///\n\n/// Similar to [join3], except that instead of returning a tuple of the outputs of `a`, `b` and `c`,\n\n/// it only returns the output of `c`.\n\n///\n\n/// See also [join3_left].\n\n///\n\n/// # Panics\n\n///\n\n/// Panics if the [ContextId]s `a`, `b` and `c` are not compatible.\n\npub fn join3_right<A, B, C, Ec>(a: A, b: B, c: C) -> Join3Right<A, B, C, Ec>\n\nwhere\n\n A: GpuTask<Ec>,\n\n B: GpuTask<Ec>,\n\n C: GpuTask<Ec>,\n\n{\n\n Join3Right::new(a, b, c)\n\n}\n\n\n", "file_path": "web_glitz/src/task/join.rs", "rank": 95, "score": 100838.22554732421 }, { "content": "/// Combines task `a`, `b`, `c` and `d`, waiting for all tasks to complete in order.\n\n///\n\n/// This returns a new \"sequenced\" task. This sequenced task must progress its sub-tasks in order.\n\n/// The sequenced task will finish when all sub-tasks have finished. When it finishes, it will\n\n/// output a tuple `(A, B, C, D)` where `A` is this tasks output, `B` is task `b`'s output, `C` is\n\n/// task `c`'s output and `D` is task `d`'s output.\n\n///\n\n/// # Panics\n\n///\n\n/// Panics if the [ContextId]s `a`, `b`, `c` and `d` are not compatible.\n\npub fn sequence4<A, B, C, D, Ec>(a: A, b: B, c: C, d: D) -> Sequence4<A, B, C, D, Ec>\n\nwhere\n\n A: GpuTask<Ec>,\n\n B: GpuTask<Ec>,\n\n C: GpuTask<Ec>,\n\n D: GpuTask<Ec>,\n\n{\n\n Sequence4::new(a, b, c, d)\n\n}\n\n\n", "file_path": "web_glitz/src/task/sequence.rs", "rank": 96, "score": 96407.02235443675 }, { "content": "/// Combines task `a`, `b`, `c` and `d`, waiting for all tasks to complete in no particular order.\n\n///\n\n/// This returns a new \"joined\" task. This joined task may progress the its sub-tasks in any order.\n\n/// The joined task will finish when all sub-tasks have finished. When it finishes, it will output a\n\n/// tuple `(A, B, C, D)` where `A` is this task's output, `B` is task `b`'s output, `C` is task\n\n/// `c`'s output and `D` is task `d`'s output.\n\n///\n\n/// # Panics\n\n///\n\n/// Panics if the [ContextId]s `a`, `b`, `c` and `d` are not compatible.\n\npub fn join4<A, B, C, D, Ec>(a: A, b: B, c: C, d: D) -> Join4<A, B, C, D, Ec>\n\nwhere\n\n A: GpuTask<Ec>,\n\n B: GpuTask<Ec>,\n\n C: GpuTask<Ec>,\n\n D: GpuTask<Ec>,\n\n{\n\n Join4::new(a, b, c, d)\n\n}\n\n\n", "file_path": "web_glitz/src/task/join.rs", "rank": 97, "score": 96407.02235443675 }, { "content": "/// Combines task `a`, `b`, `c` and `d`, waiting for all tasks to complete in no particular order,\n\n/// with the output of task `a`.\n\n///\n\n/// Similar to [join4], except that instead of returning a tuple of the outputs of `a`, `b`, `c` and\n\n/// `d`, it only returns the output of `a`.\n\n///\n\n/// See also [join4_right].\n\n///\n\n/// # Panics\n\n///\n\n/// Panics if the [ContextId]s `a`, `b`, `c` and `d` are not compatible.\n\npub fn join4_left<A, B, C, D, Ec>(a: A, b: B, c: C, d: D) -> Join4Left<A, B, C, D, Ec>\n\nwhere\n\n A: GpuTask<Ec>,\n\n B: GpuTask<Ec>,\n\n C: GpuTask<Ec>,\n\n D: GpuTask<Ec>,\n\n{\n\n Join4Left::new(a, b, c, d)\n\n}\n\n\n", "file_path": "web_glitz/src/task/join.rs", "rank": 98, "score": 93841.25965143347 }, { "content": "/// Combines task `a`, `b`, `c` and `d`, waiting for all tasks to complete in no particular order,\n\n/// with the output of task `d`.\n\n///\n\n/// Similar to [join4], except that instead of returning a tuple of the outputs of `a`, `b`, `c` and\n\n/// `d`, it only returns the output of `d`.\n\n///\n\n/// See also [join4_left].\n\n///\n\n/// # Panics\n\n///\n\n/// Panics if the [ContextId]s `a`, `b`, `c` and `d` are not compatible.\n\npub fn join4_right<A, B, C, D, Ec>(a: A, b: B, c: C, d: D) -> Join4Right<A, B, C, D, Ec>\n\nwhere\n\n A: GpuTask<Ec>,\n\n B: GpuTask<Ec>,\n\n C: GpuTask<Ec>,\n\n D: GpuTask<Ec>,\n\n{\n\n Join4Right::new(a, b, c, d)\n\n}\n\n\n", "file_path": "web_glitz/src/task/join.rs", "rank": 99, "score": 93841.25965143347 } ]
Rust
src/ffi/ffi.rs
ives9638/arrow2
b86508e67ca4b08c4544626f7bbe55cf5bd02961
use std::{ptr::NonNull, sync::Arc}; use crate::{ array::{buffers_children_dictionary, Array}, bitmap::{utils::bytes_for, Bitmap}, buffer::{ bytes::{Bytes, Deallocation}, Buffer, }, datatypes::{DataType, Field, PhysicalType}, error::{ArrowError, Result}, ffi::schema::get_field_child, types::NativeType, }; #[repr(C)] #[derive(Debug, Clone)] pub struct Ffi_ArrowArray { pub(crate) length: i64, pub(crate) null_count: i64, pub(crate) offset: i64, pub(crate) n_buffers: i64, pub(crate) n_children: i64, pub(crate) buffers: *mut *const ::std::os::raw::c_void, children: *mut *mut Ffi_ArrowArray, dictionary: *mut Ffi_ArrowArray, release: ::std::option::Option<unsafe extern "C" fn(arg1: *mut Ffi_ArrowArray)>, private_data: *mut ::std::os::raw::c_void, } impl Drop for Ffi_ArrowArray { fn drop(&mut self) { match self.release { None => (), Some(release) => unsafe { release(self) }, }; } } unsafe extern "C" fn c_release_array(array: *mut Ffi_ArrowArray) { if array.is_null() { return; } let array = &mut *array; let private = Box::from_raw(array.private_data as *mut PrivateData); for child in private.children_ptr.iter() { let _ = Box::from_raw(*child); } if let Some(ptr) = private.dictionary_ptr { let _ = Box::from_raw(ptr); } array.release = None; } #[allow(dead_code)] struct PrivateData { array: Arc<dyn Array>, buffers_ptr: Box<[*const std::os::raw::c_void]>, children_ptr: Box<[*mut Ffi_ArrowArray]>, dictionary_ptr: Option<*mut Ffi_ArrowArray>, } impl Ffi_ArrowArray { pub(crate) fn new(array: Arc<dyn Array>) -> Self { let (buffers, children, dictionary) = buffers_children_dictionary(array.as_ref()); let buffers_ptr = buffers .iter() .map(|maybe_buffer| match maybe_buffer { Some(b) => b.as_ptr() as *const std::os::raw::c_void, None => std::ptr::null(), }) .collect::<Box<[_]>>(); let n_buffers = buffers.len() as i64; let children_ptr = children .into_iter() .map(|child| Box::into_raw(Box::new(Ffi_ArrowArray::new(child)))) .collect::<Box<_>>(); let n_children = children_ptr.len() as i64; let dictionary_ptr = dictionary.map(|array| Box::into_raw(Box::new(Ffi_ArrowArray::new(array)))); let length = array.len() as i64; let null_count = array.null_count() as i64; let mut private_data = Box::new(PrivateData { array, buffers_ptr, children_ptr, dictionary_ptr, }); Self { length, null_count, offset: 0i64, n_buffers, n_children, buffers: private_data.buffers_ptr.as_mut_ptr(), children: private_data.children_ptr.as_mut_ptr(), dictionary: private_data.dictionary_ptr.unwrap_or(std::ptr::null_mut()), release: Some(c_release_array), private_data: Box::into_raw(private_data) as *mut ::std::os::raw::c_void, } } pub fn empty() -> Self { Self { length: 0, null_count: 0, offset: 0, n_buffers: 0, n_children: 0, buffers: std::ptr::null_mut(), children: std::ptr::null_mut(), dictionary: std::ptr::null_mut(), release: None, private_data: std::ptr::null_mut(), } } pub(crate) fn len(&self) -> usize { self.length as usize } pub(crate) fn offset(&self) -> usize { self.offset as usize } pub(crate) fn null_count(&self) -> usize { self.null_count as usize } } unsafe fn create_buffer<T: NativeType>( array: &Ffi_ArrowArray, data_type: &DataType, deallocation: Deallocation, index: usize, ) -> Result<Buffer<T>> { if array.buffers.is_null() { return Err(ArrowError::Ffi("The array buffers are null".to_string())); } let buffers = array.buffers as *mut *const u8; let len = buffer_len(array, data_type, index)?; assert!(index < array.n_buffers as usize); let ptr = *buffers.add(index); let ptr = NonNull::new(ptr as *mut T); let bytes = ptr .map(|ptr| Bytes::new(ptr, len, deallocation)) .ok_or_else(|| ArrowError::Ffi(format!("The buffer at position {} is null", index))); bytes.map(Buffer::from_bytes) } unsafe fn create_bitmap( array: &Ffi_ArrowArray, deallocation: Deallocation, index: usize, ) -> Result<Bitmap> { if array.buffers.is_null() { return Err(ArrowError::Ffi("The array buffers are null".to_string())); } let len = array.length as usize; let buffers = array.buffers as *mut *const u8; assert!(index < array.n_buffers as usize); let ptr = *buffers.add(index); let bytes_len = bytes_for(len); let ptr = NonNull::new(ptr as *mut u8); let bytes = ptr .map(|ptr| Bytes::new(ptr, bytes_len, deallocation)) .ok_or_else(|| { ArrowError::Ffi(format!( "The buffer {} is a null pointer and cannot be interpreted as a bitmap", index )) })?; Ok(Bitmap::from_bytes(bytes, len)) } fn buffer_len(array: &Ffi_ArrowArray, data_type: &DataType, i: usize) -> Result<usize> { Ok(match (data_type.to_physical_type(), i) { (PhysicalType::Utf8, 1) | (PhysicalType::LargeUtf8, 1) | (PhysicalType::Binary, 1) | (PhysicalType::LargeBinary, 1) | (PhysicalType::List, 1) | (PhysicalType::LargeList, 1) | (PhysicalType::Map, 1) => { array.length as usize + 1 } (PhysicalType::Utf8, 2) | (PhysicalType::Binary, 2) => { let len = buffer_len(array, data_type, 1)?; let offset_buffer = unsafe { *(array.buffers as *mut *const u8).add(1) }; let offset_buffer = offset_buffer as *const i32; (unsafe { *offset_buffer.add(len - 1) }) as usize } (PhysicalType::LargeUtf8, 2) | (PhysicalType::LargeBinary, 2) => { let len = buffer_len(array, data_type, 1)?; let offset_buffer = unsafe { *(array.buffers as *mut *const u8).add(1) }; let offset_buffer = offset_buffer as *const i64; (unsafe { *offset_buffer.add(len - 1) }) as usize } _ => array.length as usize, }) } fn create_child( array: &Ffi_ArrowArray, field: &Field, parent: Arc<ArrowArray>, index: usize, ) -> Result<ArrowArrayChild<'static>> { let field = get_field_child(field, index)?; assert!(index < array.n_children as usize); assert!(!array.children.is_null()); unsafe { let arr_ptr = *array.children.add(index); assert!(!arr_ptr.is_null()); let arr_ptr = &*arr_ptr; Ok(ArrowArrayChild::from_raw(arr_ptr, field, parent)) } } fn create_dictionary( array: &Ffi_ArrowArray, field: &Field, parent: Arc<ArrowArray>, ) -> Result<Option<ArrowArrayChild<'static>>> { if let DataType::Dictionary(_, values) = field.data_type() { let field = Field::new("", values.as_ref().clone(), true); assert!(!array.dictionary.is_null()); let array = unsafe { &*array.dictionary }; Ok(Some(ArrowArrayChild::from_raw(array, field, parent))) } else { Ok(None) } } pub trait ArrowArrayRef { fn deallocation(&self) -> Deallocation { Deallocation::Foreign(self.parent().clone()) } unsafe fn validity(&self) -> Result<Option<Bitmap>> { if self.array().null_count() == 0 { Ok(None) } else { create_bitmap(self.array(), self.deallocation(), 0).map(Some) } } unsafe fn buffer<T: NativeType>(&self, index: usize) -> Result<Buffer<T>> { create_buffer::<T>( self.array(), self.field().data_type(), self.deallocation(), index + 1, ) } unsafe fn bitmap(&self, index: usize) -> Result<Bitmap> { create_bitmap(self.array(), self.deallocation(), index + 1) } fn child(&self, index: usize) -> Result<ArrowArrayChild> { create_child(self.array(), self.field(), self.parent().clone(), index) } fn dictionary(&self) -> Result<Option<ArrowArrayChild>> { create_dictionary(self.array(), self.field(), self.parent().clone()) } fn parent(&self) -> &Arc<ArrowArray>; fn array(&self) -> &Ffi_ArrowArray; fn field(&self) -> &Field; } #[derive(Debug)] pub struct ArrowArray { array: Box<Ffi_ArrowArray>, field: Field, } impl ArrowArray { pub fn new(array: Box<Ffi_ArrowArray>, field: Field) -> Self { Self { array, field } } } impl ArrowArrayRef for Arc<ArrowArray> { fn field(&self) -> &Field { &self.field } fn parent(&self) -> &Arc<ArrowArray> { self } fn array(&self) -> &Ffi_ArrowArray { self.array.as_ref() } } #[derive(Debug)] pub struct ArrowArrayChild<'a> { array: &'a Ffi_ArrowArray, field: Field, parent: Arc<ArrowArray>, } impl<'a> ArrowArrayRef for ArrowArrayChild<'a> { fn field(&self) -> &Field { &self.field } fn parent(&self) -> &Arc<ArrowArray> { &self.parent } fn array(&self) -> &Ffi_ArrowArray { self.array } } impl<'a> ArrowArrayChild<'a> { fn from_raw(array: &'a Ffi_ArrowArray, field: Field, parent: Arc<ArrowArray>) -> Self { Self { array, field, parent, } } }
use std::{ptr::NonNull, sync::Arc}; use crate::{ array::{buffers_children_dictionary, Array}, bitmap::{utils::bytes_for, Bitmap}, buffer::{ bytes::{Bytes, Deallocation}, Buffer, }, datatypes::{DataType, Field, PhysicalType}, error::{ArrowError, Result}, ffi::schema::get_field_child, types::NativeType, }; #[repr(C)] #[derive(Debug, Clone)] pub struct Ffi_ArrowArray { pub(crate) length: i64, pub(crate) null_count: i64, pub(crate) offset: i64, pub(crate) n_buffers: i64, pub(crate) n_children: i64, pub(crate) buffers: *mut *const ::std::os::raw::c_void, children: *mut *mut Ffi_ArrowArray, dictionary: *mut Ffi_ArrowArray, release: ::std::option::Option<unsafe extern "C" fn(arg1: *mut Ffi_ArrowArray)>, private_data: *mut ::std::os::raw::c_void, } impl Drop for Ffi_ArrowArray { fn drop(&mut self) { match self.release { None => (), Some(release) => unsafe { release(self) }, }; } } unsafe extern "C" fn c_release_array(array: *mut Ffi_ArrowArray) { if array.is_null() { return; } let array = &mut *array; let private = Box::from_raw(array.private_data as *mut PrivateData); for child in private.children_ptr.iter() { let _ = Box::from_raw(*child); } if let Some(ptr) = private.dictionary_ptr { let _ = Box::from_raw(ptr); } array.release = None; } #[allow(dead_code)] struct PrivateData { array: Arc<dyn Array>, buffers_ptr: Box<[*const std::os::raw::c_void]>, children_ptr: Box<[*mut Ffi_ArrowArray]>, dictionary_ptr: Option<*mut Ffi_ArrowArray>, } impl Ffi_ArrowArray { pub(crate) fn new(array: Arc<dyn Array>) -> Self { let (buffers, children, dictionary) = buffers_children_dictionary(array.as_ref()); let buffers_ptr = buffers .iter() .map(|maybe_buffer| match maybe_buffer { Some(b) => b.as_ptr() as *const std::os::raw::c_void, None => std::ptr::null(), }) .collect::<Box<[_]>>(); let n_buffers = buffers.len() as i64; let children_ptr = children .into_iter() .map(|child| Box::into_raw(Box::new(Ffi_ArrowArray::new(child)))) .collect::<Box<_>>(); let n_children = children_ptr.len() as i64; let dictionary_ptr = dictionary.map(|array| Box::into_raw(Box::new(Ffi_ArrowArray::new(array)))); let length = array.len() as i64; let null_count = array.null_count() as i64; let mut private_data = Box::new(PrivateData { array, buffers_ptr, children_ptr, dictionary_ptr, }); Self { length, null_count, offset: 0i64, n_buffers, n_children, buffers: private_data.buffers_ptr.as_mut_ptr(), children: private_data.children_ptr.as_mut_ptr(), dictionary: private_data.dictionary_ptr.unwrap_or(std::ptr::null_mut()), release: Some(c_release_array), private_data: Box::into_raw(private_data) as *mut ::std::os::raw::c_void, } } pub fn empty() -> Self { Self { length: 0, null_count: 0, offset: 0, n_buffers: 0, n_children: 0, buffers: std::ptr::null_mut(), children: std::ptr::null_mut(), dictionary: std::ptr::null_mut(), release: None, private_data: std::ptr::null_mut(), } } pub(crate) fn len(&self) -> usize { self.length as usize } pub(crate) fn offset(&self) -> usize { self.offset as usize } pub(crate) fn null_count(&self) -> usize { self.null_count as usize } } unsafe fn create_buffer<T: NativeType>( array: &Ffi_ArrowArray, data_type: &DataType, deallocation: Deallocation, index: usize, ) -> Result<Buffer<T>> { if array.buffers.is_null() { return Err(ArrowError::Ffi("The array buffers are null".to_strin
unsafe fn create_bitmap( array: &Ffi_ArrowArray, deallocation: Deallocation, index: usize, ) -> Result<Bitmap> { if array.buffers.is_null() { return Err(ArrowError::Ffi("The array buffers are null".to_string())); } let len = array.length as usize; let buffers = array.buffers as *mut *const u8; assert!(index < array.n_buffers as usize); let ptr = *buffers.add(index); let bytes_len = bytes_for(len); let ptr = NonNull::new(ptr as *mut u8); let bytes = ptr .map(|ptr| Bytes::new(ptr, bytes_len, deallocation)) .ok_or_else(|| { ArrowError::Ffi(format!( "The buffer {} is a null pointer and cannot be interpreted as a bitmap", index )) })?; Ok(Bitmap::from_bytes(bytes, len)) } fn buffer_len(array: &Ffi_ArrowArray, data_type: &DataType, i: usize) -> Result<usize> { Ok(match (data_type.to_physical_type(), i) { (PhysicalType::Utf8, 1) | (PhysicalType::LargeUtf8, 1) | (PhysicalType::Binary, 1) | (PhysicalType::LargeBinary, 1) | (PhysicalType::List, 1) | (PhysicalType::LargeList, 1) | (PhysicalType::Map, 1) => { array.length as usize + 1 } (PhysicalType::Utf8, 2) | (PhysicalType::Binary, 2) => { let len = buffer_len(array, data_type, 1)?; let offset_buffer = unsafe { *(array.buffers as *mut *const u8).add(1) }; let offset_buffer = offset_buffer as *const i32; (unsafe { *offset_buffer.add(len - 1) }) as usize } (PhysicalType::LargeUtf8, 2) | (PhysicalType::LargeBinary, 2) => { let len = buffer_len(array, data_type, 1)?; let offset_buffer = unsafe { *(array.buffers as *mut *const u8).add(1) }; let offset_buffer = offset_buffer as *const i64; (unsafe { *offset_buffer.add(len - 1) }) as usize } _ => array.length as usize, }) } fn create_child( array: &Ffi_ArrowArray, field: &Field, parent: Arc<ArrowArray>, index: usize, ) -> Result<ArrowArrayChild<'static>> { let field = get_field_child(field, index)?; assert!(index < array.n_children as usize); assert!(!array.children.is_null()); unsafe { let arr_ptr = *array.children.add(index); assert!(!arr_ptr.is_null()); let arr_ptr = &*arr_ptr; Ok(ArrowArrayChild::from_raw(arr_ptr, field, parent)) } } fn create_dictionary( array: &Ffi_ArrowArray, field: &Field, parent: Arc<ArrowArray>, ) -> Result<Option<ArrowArrayChild<'static>>> { if let DataType::Dictionary(_, values) = field.data_type() { let field = Field::new("", values.as_ref().clone(), true); assert!(!array.dictionary.is_null()); let array = unsafe { &*array.dictionary }; Ok(Some(ArrowArrayChild::from_raw(array, field, parent))) } else { Ok(None) } } pub trait ArrowArrayRef { fn deallocation(&self) -> Deallocation { Deallocation::Foreign(self.parent().clone()) } unsafe fn validity(&self) -> Result<Option<Bitmap>> { if self.array().null_count() == 0 { Ok(None) } else { create_bitmap(self.array(), self.deallocation(), 0).map(Some) } } unsafe fn buffer<T: NativeType>(&self, index: usize) -> Result<Buffer<T>> { create_buffer::<T>( self.array(), self.field().data_type(), self.deallocation(), index + 1, ) } unsafe fn bitmap(&self, index: usize) -> Result<Bitmap> { create_bitmap(self.array(), self.deallocation(), index + 1) } fn child(&self, index: usize) -> Result<ArrowArrayChild> { create_child(self.array(), self.field(), self.parent().clone(), index) } fn dictionary(&self) -> Result<Option<ArrowArrayChild>> { create_dictionary(self.array(), self.field(), self.parent().clone()) } fn parent(&self) -> &Arc<ArrowArray>; fn array(&self) -> &Ffi_ArrowArray; fn field(&self) -> &Field; } #[derive(Debug)] pub struct ArrowArray { array: Box<Ffi_ArrowArray>, field: Field, } impl ArrowArray { pub fn new(array: Box<Ffi_ArrowArray>, field: Field) -> Self { Self { array, field } } } impl ArrowArrayRef for Arc<ArrowArray> { fn field(&self) -> &Field { &self.field } fn parent(&self) -> &Arc<ArrowArray> { self } fn array(&self) -> &Ffi_ArrowArray { self.array.as_ref() } } #[derive(Debug)] pub struct ArrowArrayChild<'a> { array: &'a Ffi_ArrowArray, field: Field, parent: Arc<ArrowArray>, } impl<'a> ArrowArrayRef for ArrowArrayChild<'a> { fn field(&self) -> &Field { &self.field } fn parent(&self) -> &Arc<ArrowArray> { &self.parent } fn array(&self) -> &Ffi_ArrowArray { self.array } } impl<'a> ArrowArrayChild<'a> { fn from_raw(array: &'a Ffi_ArrowArray, field: Field, parent: Arc<ArrowArray>) -> Self { Self { array, field, parent, } } }
g())); } let buffers = array.buffers as *mut *const u8; let len = buffer_len(array, data_type, index)?; assert!(index < array.n_buffers as usize); let ptr = *buffers.add(index); let ptr = NonNull::new(ptr as *mut T); let bytes = ptr .map(|ptr| Bytes::new(ptr, len, deallocation)) .ok_or_else(|| ArrowError::Ffi(format!("The buffer at position {} is null", index))); bytes.map(Buffer::from_bytes) }
function_block-function_prefixed
[ { "content": "/// Shifts array by defined number of items (to left or right)\n\n/// A positive value for `offset` shifts the array to the right\n\n/// a negative value shifts the array to the left.\n\n/// # Examples\n\n/// ```\n\n/// use arrow2::array::Int32Array;\n\n/// use arrow2::compute::window::shift;\n\n///\n\n/// let array = Int32Array::from(&[Some(1), None, Some(3)]);\n\n/// let result = shift(&array, -1).unwrap();\n\n/// let expected = Int32Array::from(&[None, Some(3), None]);\n\n/// assert_eq!(expected, result.as_ref());\n\n/// ```\n\npub fn shift(array: &dyn Array, offset: i64) -> Result<Box<dyn Array>> {\n\n if abs(offset) as usize > array.len() {\n\n return Err(ArrowError::InvalidArgumentError(format!(\n\n \"Shift's absolute offset must be smaller or equal to the arrays length. Offset is {}, length is {}\",\n\n abs(offset), array.len()\n\n )));\n\n }\n\n\n\n // Compute slice\n\n let slice_offset = clamp(-offset, 0, array.len() as i64) as usize;\n\n let length = array.len() - abs(offset) as usize;\n\n let slice = array.slice(slice_offset, length);\n\n\n\n // Generate array with remaining `null` items\n\n let nulls = abs(offset as i64) as usize;\n\n\n\n let null_array = new_null_array(array.data_type().clone(), nulls);\n\n\n\n // Concatenate both arrays, add nulls after if shift > 0 else before\n\n if offset > 0 {\n\n concat::concatenate(&[null_array.as_ref(), slice.as_ref()])\n\n } else {\n\n concat::concatenate(&[slice.as_ref(), null_array.as_ref()])\n\n }\n\n}\n", "file_path": "src/compute/window.rs", "rank": 0, "score": 436797.5624148905 }, { "content": "#[inline]\n\nfn extend<I: Iterator<Item = bool>>(buffer: &mut [u8], length: usize, mut iterator: I) {\n\n let chunks = length / 8;\n\n let reminder = length % 8;\n\n\n\n buffer[..chunks].iter_mut().for_each(|byte| {\n\n (0..8).for_each(|i| {\n\n *byte = set(*byte, i, iterator.next().unwrap());\n\n })\n\n });\n\n\n\n if reminder != 0 {\n\n let last = &mut buffer[chunks];\n\n iterator.enumerate().for_each(|(i, value)| {\n\n *last = set(*last, i, value);\n\n });\n\n }\n\n}\n\n\n\nimpl MutableBitmap {\n\n /// Extends `self` from a [`TrustedLen`] iterator.\n", "file_path": "src/bitmap/mutable.rs", "rank": 1, "score": 414386.06997251103 }, { "content": "/// Returns an array of integers with the number of bytes on each string of the array.\n\npub fn length(array: &dyn Array) -> Result<Box<dyn Array>> {\n\n match array.data_type() {\n\n DataType::Utf8 => {\n\n let array = array.as_any().downcast_ref::<Utf8Array<i32>>().unwrap();\n\n Ok(Box::new(unary_offsets_string::<i32, _>(array, |x| x)))\n\n }\n\n DataType::LargeUtf8 => {\n\n let array = array.as_any().downcast_ref::<Utf8Array<i64>>().unwrap();\n\n Ok(Box::new(unary_offsets_string::<i64, _>(array, |x| x)))\n\n }\n\n _ => Err(ArrowError::InvalidArgumentError(format!(\n\n \"length not supported for {:?}\",\n\n array.data_type()\n\n ))),\n\n }\n\n}\n\n\n", "file_path": "src/compute/length.rs", "rank": 2, "score": 403991.16025843145 }, { "content": "/// Returns an ArrayRef with a substring starting from `start` and with optional length `length` of each of the elements in `array`.\n\n/// `start` can be negative, in which case the start counts from the end of the string.\n\n/// this function errors when the passed array is not a \\[Large\\]String array.\n\npub fn substring(array: &dyn Array, start: i64, length: &Option<u64>) -> Result<Box<dyn Array>> {\n\n match array.data_type() {\n\n DataType::Binary => Ok(Box::new(binary_substring(\n\n array\n\n .as_any()\n\n .downcast_ref::<BinaryArray<i32>>()\n\n .expect(\"A binary is expected\"),\n\n start as i32,\n\n &length.map(|e| e as i32),\n\n ))),\n\n DataType::LargeBinary => Ok(Box::new(binary_substring(\n\n array\n\n .as_any()\n\n .downcast_ref::<BinaryArray<i64>>()\n\n .expect(\"A large binary is expected\"),\n\n start,\n\n &length.map(|e| e as i64),\n\n ))),\n\n DataType::LargeUtf8 => Ok(Box::new(utf8_substring(\n\n array\n", "file_path": "src/compute/substring.rs", "rank": 3, "score": 403792.545083308 }, { "content": "pub fn buffers_children_dictionary(array: &dyn Array) -> BuffersChildren {\n\n use PhysicalType::*;\n\n match array.data_type().to_physical_type() {\n\n Null => ffi_dyn!(array, NullArray),\n\n Boolean => ffi_dyn!(array, BooleanArray),\n\n Primitive(primitive) => with_match_primitive_type!(primitive, |$T| {\n\n ffi_dyn!(array, PrimitiveArray<$T>)\n\n }),\n\n Binary => ffi_dyn!(array, BinaryArray<i32>),\n\n LargeBinary => ffi_dyn!(array, BinaryArray<i64>),\n\n FixedSizeBinary => ffi_dyn!(array, FixedSizeBinaryArray),\n\n Utf8 => ffi_dyn!(array, Utf8Array::<i32>),\n\n LargeUtf8 => ffi_dyn!(array, Utf8Array::<i64>),\n\n List => ffi_dyn!(array, ListArray::<i32>),\n\n LargeList => ffi_dyn!(array, ListArray::<i64>),\n\n FixedSizeList => ffi_dyn!(array, FixedSizeListArray),\n\n Struct => ffi_dyn!(array, StructArray),\n\n Union => ffi_dyn!(array, UnionArray),\n\n Map => ffi_dyn!(array, MapArray),\n\n Dictionary(key_type) => {\n", "file_path": "src/array/ffi.rs", "rank": 4, "score": 402714.527359706 }, { "content": "pub fn take<I: Index>(array: &StructArray, indices: &PrimitiveArray<I>) -> Result<StructArray> {\n\n let values: Vec<Arc<dyn Array>> = array\n\n .values()\n\n .iter()\n\n .map(|a| super::take(a.as_ref(), indices).map(|x| x.into()))\n\n .collect::<Result<_>>()?;\n\n let validity = take_validity(array.validity(), indices)?;\n\n Ok(StructArray::from_data(\n\n array.data_type().clone(),\n\n values,\n\n validity,\n\n ))\n\n}\n", "file_path": "src/compute/take/structure.rs", "rank": 5, "score": 396307.8437666892 }, { "content": "fn unary_impl<F, I>(iter: I, op: F, length: usize) -> Bitmap\n\nwhere\n\n I: BitChunkIterExact<u64>,\n\n F: Fn(u64) -> u64,\n\n{\n\n let rem = op(iter.remainder());\n\n\n\n let iterator = iter.map(|left| op(left)).chain(std::iter::once(rem));\n\n\n\n let buffer = MutableBuffer::from_chunk_iter(iterator);\n\n\n\n Bitmap::from_u8_buffer(buffer, length)\n\n}\n\n\n", "file_path": "src/bitmap/bitmap_ops.rs", "rank": 6, "score": 374044.1709185561 }, { "content": "#[inline]\n\npub fn merge_reversed<T>(mut current: T, mut next: T, offset: usize) -> T\n\nwhere\n\n T: BitChunk,\n\n{\n\n // 8 _bits_:\n\n // current = [c0, c1, c2, c3, c4, c5, c6, c7]\n\n // next = [n0, n1, n2, n3, n4, n5, n6, n7]\n\n // offset = 3\n\n // expected = [n5, n6, n7, c0, c1, c2, c3, c4]\n\n\n\n // 1. unset most significants of `next` up to `offset`\n\n let inverse_offset = std::mem::size_of::<T>() * 8 - offset;\n\n next <<= inverse_offset;\n\n // next = [n5, n6, n7, 0 , 0 , 0 , 0 , 0 ]\n\n\n\n // 2. unset least significants of `current` up to `offset`\n\n current >>= offset;\n\n // current = [0 , 0 , 0 , c0, c1, c2, c3, c4]\n\n\n\n current | next\n", "file_path": "src/bitmap/utils/chunk_iterator/merge.rs", "rank": 7, "score": 372236.9160323385 }, { "content": "fn test_round_trip(expected: impl Array + Clone + 'static) -> Result<()> {\n\n let array: Arc<dyn Array> = Arc::new(expected.clone());\n\n let field = Field::new(\"a\", array.data_type().clone(), true);\n\n let expected = Box::new(expected) as Box<dyn Array>;\n\n\n\n let array_ptr = Box::new(ffi::Ffi_ArrowArray::empty());\n\n let schema_ptr = Box::new(ffi::Ffi_ArrowSchema::empty());\n\n\n\n let array_ptr = Box::into_raw(array_ptr);\n\n let schema_ptr = Box::into_raw(schema_ptr);\n\n\n\n unsafe {\n\n ffi::export_array_to_c(array, array_ptr);\n\n ffi::export_field_to_c(&field, schema_ptr);\n\n }\n\n\n\n let array_ptr = unsafe { Box::from_raw(array_ptr) };\n\n let schema_ptr = unsafe { Box::from_raw(schema_ptr) };\n\n\n\n // import references\n\n let result_field = unsafe { ffi::import_field_from_c(schema_ptr.as_ref())? };\n\n let result_array = unsafe { ffi::import_array_from_c(array_ptr, &result_field)? };\n\n\n\n assert_eq!(&result_array, &expected);\n\n assert_eq!(result_field, field);\n\n Ok(())\n\n}\n\n\n", "file_path": "tests/it/ffi.rs", "rank": 8, "score": 371625.74352597 }, { "content": "fn encode(iterator: impl Iterator<Item = bool>, buffer: &mut Vec<u8>) -> Result<()> {\n\n // encode values using bitpacking\n\n let len = buffer.len();\n\n let mut buffer = std::io::Cursor::new(buffer);\n\n buffer.set_position(len as u64);\n\n Ok(bitpacked_encode(&mut buffer, iterator)?)\n\n}\n\n\n\npub(super) fn encode_plain(\n\n array: &BooleanArray,\n\n is_optional: bool,\n\n buffer: &mut Vec<u8>,\n\n) -> Result<()> {\n\n if is_optional {\n\n let iter = array.iter().flatten().take(\n\n array\n\n .validity()\n\n .as_ref()\n\n .map(|x| x.len() - x.null_count())\n\n .unwrap_or_else(|| array.len()),\n\n );\n\n encode(iter, buffer)\n\n } else {\n\n let iter = array.values().iter();\n\n encode(iter, buffer)\n\n }\n\n}\n\n\n", "file_path": "src/io/parquet/write/boolean/basic.rs", "rank": 9, "score": 368456.19291948737 }, { "content": "pub fn iter_to_array<I, E>(mut iter: I, metadata: &ColumnChunkMetaData) -> Result<BooleanArray>\n\nwhere\n\n ArrowError: From<E>,\n\n E: Clone,\n\n I: StreamingIterator<Item = std::result::Result<DataPage, E>>,\n\n{\n\n let capacity = metadata.num_values() as usize;\n\n let mut values = MutableBitmap::with_capacity(capacity);\n\n let mut validity = MutableBitmap::with_capacity(capacity);\n\n while let Some(page) = iter.next() {\n\n extend_from_page(\n\n page.as_ref().map_err(|x| x.clone())?,\n\n metadata.descriptor(),\n\n &mut values,\n\n &mut validity,\n\n )?\n\n }\n\n\n\n Ok(BooleanArray::from_data(\n\n DataType::Boolean,\n", "file_path": "src/io/parquet/read/boolean/basic.rs", "rank": 10, "score": 365567.04762885236 }, { "content": "pub fn zigzag_i64<R: Read>(reader: &mut R) -> Result<i64> {\n\n let z = decode_variable(reader)?;\n\n Ok(if z & 0x1 == 0 {\n\n (z >> 1) as i64\n\n } else {\n\n !(z >> 1) as i64\n\n })\n\n}\n\n\n", "file_path": "src/io/avro/read/util.rs", "rank": 11, "score": 350725.49709961493 }, { "content": "/// Regex matches\n\n/// # Example\n\n/// ```\n\n/// use arrow2::array::{Utf8Array, BooleanArray};\n\n/// use arrow2::compute::regex_match::regex_match_scalar;\n\n///\n\n/// let strings = Utf8Array::<i32>::from_slice(&vec![\"ArAow\", \"A_B\", \"AAA\"]);\n\n///\n\n/// let result = regex_match_scalar(&strings, \"^A.A\").unwrap();\n\n/// assert_eq!(result, BooleanArray::from_slice(&vec![true, false, true]));\n\n/// ```\n\npub fn regex_match_scalar<O: Offset>(values: &Utf8Array<O>, regex: &str) -> Result<BooleanArray> {\n\n let regex = Regex::new(regex)\n\n .map_err(|e| ArrowError::InvalidArgumentError(format!(\"Unable to compile regex: {}\", e)))?;\n\n Ok(unary_utf8_boolean(values, |x| regex.is_match(x)))\n\n}\n", "file_path": "src/compute/regex_match.rs", "rank": 12, "score": 340545.99784068373 }, { "content": "/// Regex matches\n\npub fn regex_match<O: Offset>(values: &Utf8Array<O>, regex: &Utf8Array<O>) -> Result<BooleanArray> {\n\n if values.len() != regex.len() {\n\n return Err(ArrowError::InvalidArgumentError(\n\n \"Cannot perform comparison operation on arrays of different length\".to_string(),\n\n ));\n\n }\n\n\n\n let mut map = HashMap::new();\n\n let validity = combine_validities(values.validity(), regex.validity());\n\n\n\n let iterator = values.iter().zip(regex.iter()).map(|(haystack, regex)| {\n\n if haystack.is_none() | regex.is_none() {\n\n // regex is expensive => short-circuit if null\n\n return Result::Ok(false);\n\n };\n\n let haystack = haystack.unwrap();\n\n let regex = regex.unwrap();\n\n\n\n let regex = if let Some(regex) = map.get(regex) {\n\n regex\n", "file_path": "src/compute/regex_match.rs", "rank": 13, "score": 339654.05896554433 }, { "content": "pub fn skip_utf8(field_nodes: &mut VecDeque<Node>, buffers: &mut VecDeque<&gen::Schema::Buffer>) {\n\n let _ = field_nodes.pop_front().unwrap();\n\n\n\n let _ = buffers.pop_front().unwrap();\n\n let _ = buffers.pop_front().unwrap();\n\n let _ = buffers.pop_front().unwrap();\n\n}\n", "file_path": "src/io/ipc/read/array/utf8.rs", "rank": 14, "score": 338267.50288591825 }, { "content": "pub fn skip_binary(field_nodes: &mut VecDeque<Node>, buffers: &mut VecDeque<&gen::Schema::Buffer>) {\n\n let _ = field_nodes.pop_front().unwrap();\n\n\n\n let _ = buffers.pop_front().unwrap();\n\n let _ = buffers.pop_front().unwrap();\n\n let _ = buffers.pop_front().unwrap();\n\n}\n", "file_path": "src/io/ipc/read/array/binary.rs", "rank": 15, "score": 338267.50288591825 }, { "content": "fn encode_iter_v1<I: Iterator<Item = bool>>(buffer: &mut Vec<u8>, iter: I) -> Result<()> {\n\n buffer.extend_from_slice(&[0; 4]);\n\n let start = buffer.len();\n\n encode_bool(buffer, iter)?;\n\n let end = buffer.len();\n\n let length = end - start;\n\n\n\n // write the first 4 bytes as length\n\n let length = (length as i32).to_le_bytes();\n\n (0..4).for_each(|i| buffer[start - 4 + i] = length[i]);\n\n Ok(())\n\n}\n\n\n", "file_path": "src/io/parquet/write/utils.rs", "rank": 16, "score": 334068.9687669659 }, { "content": "fn to_data_type(item: &Value, mut children: Vec<Field>) -> Result<DataType> {\n\n let type_ = item\n\n .get(\"name\")\n\n .ok_or_else(|| ArrowError::Schema(\"type missing\".to_string()))?;\n\n\n\n let type_ = if let Value::String(name) = type_ {\n\n name.as_str()\n\n } else {\n\n return Err(ArrowError::Schema(\"type is not a string\".to_string()));\n\n };\n\n\n\n use DataType::*;\n\n Ok(match type_ {\n\n \"null\" => Null,\n\n \"bool\" => Boolean,\n\n \"binary\" => Binary,\n\n \"largebinary\" => LargeBinary,\n\n \"fixedsizebinary\" => {\n\n // return a list with any type as its child isn't defined in the map\n\n if let Some(Value::Number(size)) = item.get(\"byteWidth\") {\n", "file_path": "src/io/json_integration/schema.rs", "rank": 17, "score": 333983.76696123526 }, { "content": "/// Clones a dynamic [`Array`].\n\n/// # Implementation\n\n/// This operation is `O(1)` over `len`, as it amounts to increase two ref counts\n\n/// and moving the concrete struct under a `Box`.\n\npub fn clone(array: &dyn Array) -> Box<dyn Array> {\n\n use crate::datatypes::PhysicalType::*;\n\n match array.data_type().to_physical_type() {\n\n Null => clone_dyn!(array, NullArray),\n\n Boolean => clone_dyn!(array, BooleanArray),\n\n Primitive(primitive) => with_match_primitive_type!(primitive, |$T| {\n\n clone_dyn!(array, PrimitiveArray<$T>)\n\n }),\n\n Binary => clone_dyn!(array, BinaryArray<i32>),\n\n LargeBinary => clone_dyn!(array, BinaryArray<i64>),\n\n FixedSizeBinary => clone_dyn!(array, FixedSizeBinaryArray),\n\n Utf8 => clone_dyn!(array, Utf8Array::<i32>),\n\n LargeUtf8 => clone_dyn!(array, Utf8Array::<i64>),\n\n List => clone_dyn!(array, ListArray::<i32>),\n\n LargeList => clone_dyn!(array, ListArray::<i64>),\n\n FixedSizeList => clone_dyn!(array, FixedSizeListArray),\n\n Struct => clone_dyn!(array, StructArray),\n\n Union => clone_dyn!(array, UnionArray),\n\n Map => clone_dyn!(array, MapArray),\n\n Dictionary(key_type) => {\n", "file_path": "src/array/mod.rs", "rank": 18, "score": 331236.0426951808 }, { "content": "fn write_single_array(path: &str, array: &dyn Array, field: Field) -> Result<()> {\n\n let schema = Schema::new(vec![field]);\n\n\n\n let options = WriteOptions {\n\n write_statistics: true,\n\n compression: Compression::Uncompressed,\n\n version: Version::V2,\n\n };\n\n let encoding = Encoding::Plain;\n\n\n\n // map arrow fields to parquet fields\n\n let parquet_schema = to_parquet_schema(&schema)?;\n\n\n\n // Declare the row group iterator. This must be an iterator of iterators of iterators:\n\n // * first iterator of row groups\n\n // * second iterator of column chunks\n\n // * third iterator of pages\n\n // an array can be divided in multiple pages via `.slice(offset, length)` (`O(1)`).\n\n // All column chunks within a row group MUST have the same length.\n\n let row_groups = once(Result::Ok(DynIter::new(once(Ok(DynIter::new(\n", "file_path": "examples/parquet_write.rs", "rank": 19, "score": 331187.21153437917 }, { "content": "/// creates a new [`Scalar`] from an [`Array`].\n\npub fn new_scalar(array: &dyn Array, index: usize) -> Box<dyn Scalar> {\n\n use PhysicalType::*;\n\n match array.data_type().to_physical_type() {\n\n Null => Box::new(NullScalar::new()),\n\n Boolean => {\n\n let array = array.as_any().downcast_ref::<BooleanArray>().unwrap();\n\n let value = if array.is_valid(index) {\n\n Some(array.value(index))\n\n } else {\n\n None\n\n };\n\n Box::new(BooleanScalar::new(value))\n\n }\n\n Primitive(primitive) => with_match_primitive_type!(primitive, |$T| {\n\n let array = array\n\n .as_any()\n\n .downcast_ref::<PrimitiveArray<$T>>()\n\n .unwrap();\n\n let value = if array.is_valid(index) {\n\n Some(array.value(index))\n", "file_path": "src/scalar/mod.rs", "rank": 20, "score": 330687.94349571184 }, { "content": "/// Returns a new [`Array`] with only indices at `indices`. Null indices are taken as nulls.\n\n/// The returned array has a length equal to `indices.len()`.\n\npub fn take<O: Index>(values: &dyn Array, indices: &PrimitiveArray<O>) -> Result<Box<dyn Array>> {\n\n if indices.len() == 0 {\n\n return Ok(new_empty_array(values.data_type().clone()));\n\n }\n\n\n\n use crate::datatypes::PhysicalType::*;\n\n match values.data_type().to_physical_type() {\n\n Null => Ok(Box::new(NullArray::from_data(\n\n values.data_type().clone(),\n\n indices.len(),\n\n ))),\n\n Boolean => {\n\n let values = values.as_any().downcast_ref().unwrap();\n\n Ok(Box::new(boolean::take::<O>(values, indices)))\n\n }\n\n Primitive(primitive) => with_match_primitive_type!(primitive, |$T| {\n\n let values = values.as_any().downcast_ref().unwrap();\n\n Ok(Box::new(primitive::take::<$T, _>(&values, indices)))\n\n }),\n\n Utf8 => {\n", "file_path": "src/compute/take/mod.rs", "rank": 22, "score": 325847.98424918996 }, { "content": "/// Conversion of utf8\n\npub fn utf8_large_to_utf8(from: &Utf8Array<i64>) -> Result<Utf8Array<i32>> {\n\n let data_type = Utf8Array::<i32>::default_data_type();\n\n let values = from.values().clone();\n\n let _ =\n\n i32::try_from(*from.offsets().last().unwrap()).map_err(ArrowError::from_external_error)?;\n\n\n\n let offsets = from.offsets().iter().map(|x| *x as i32);\n\n let offsets = Buffer::from_trusted_len_iter(offsets);\n\n Ok(unsafe {\n\n Utf8Array::<i32>::from_data_unchecked(data_type, offsets, values, from.validity().cloned())\n\n })\n\n}\n", "file_path": "src/compute/cast/utf8_to.rs", "rank": 23, "score": 322492.3482463857 }, { "content": "/// Creates a new [`Array`] of [`DataType`] `data_type` and `length`.\n\n/// The array is guaranteed to have [`Array::null_count`] equal to [`Array::len`]\n\n/// for all types except Union, which does not have a validity.\n\npub fn new_null_array(data_type: DataType, length: usize) -> Box<dyn Array> {\n\n use crate::datatypes::PhysicalType::*;\n\n match data_type.to_physical_type() {\n\n Null => Box::new(NullArray::new_null(data_type, length)),\n\n Boolean => Box::new(BooleanArray::new_null(data_type, length)),\n\n Primitive(primitive) => with_match_primitive_type!(primitive, |$T| {\n\n Box::new(PrimitiveArray::<$T>::new_null(data_type, length))\n\n }),\n\n Binary => Box::new(BinaryArray::<i32>::new_null(data_type, length)),\n\n LargeBinary => Box::new(BinaryArray::<i64>::new_null(data_type, length)),\n\n FixedSizeBinary => Box::new(FixedSizeBinaryArray::new_null(data_type, length)),\n\n Utf8 => Box::new(Utf8Array::<i32>::new_null(data_type, length)),\n\n LargeUtf8 => Box::new(Utf8Array::<i64>::new_null(data_type, length)),\n\n List => Box::new(ListArray::<i32>::new_null(data_type, length)),\n\n LargeList => Box::new(ListArray::<i64>::new_null(data_type, length)),\n\n FixedSizeList => Box::new(FixedSizeListArray::new_null(data_type, length)),\n\n Struct => Box::new(StructArray::new_null(data_type, length)),\n\n Union => Box::new(UnionArray::new_null(data_type, length)),\n\n Map => Box::new(MapArray::new_null(data_type, length)),\n\n Dictionary(key_type) => {\n", "file_path": "src/array/mod.rs", "rank": 24, "score": 321366.38315581717 }, { "content": "/// Parses an offset of the form `\"+WX:YZ\"` or `\"UTC\"` into [`FixedOffset`].\n\n/// # Errors\n\n/// If the offset is not in any of the allowed forms.\n\npub fn parse_offset(offset: &str) -> Result<FixedOffset> {\n\n if offset == \"UTC\" {\n\n return Ok(FixedOffset::east(0));\n\n }\n\n let error = \"timezone offset must be of the form [-]00:00\";\n\n\n\n let mut a = offset.split(':');\n\n let first = a\n\n .next()\n\n .map(Ok)\n\n .unwrap_or_else(|| Err(ArrowError::InvalidArgumentError(error.to_string())))?;\n\n let last = a\n\n .next()\n\n .map(Ok)\n\n .unwrap_or_else(|| Err(ArrowError::InvalidArgumentError(error.to_string())))?;\n\n let hours: i32 = first\n\n .parse()\n\n .map_err(|_| ArrowError::InvalidArgumentError(error.to_string()))?;\n\n let minutes: i32 = last\n\n .parse()\n\n .map_err(|_| ArrowError::InvalidArgumentError(error.to_string()))?;\n\n\n\n Ok(FixedOffset::east(hours * 60 * 60 + minutes * 60))\n\n}\n\n\n\n/// Parses `value` to `Option<i64>` consistent with the Arrow's definition of timestamp with timezone.\n\n/// `tz` must be built from `timezone` (either via [`parse_offset`] or `chrono-tz`).\n", "file_path": "src/temporal_conversions.rs", "rank": 25, "score": 320311.0187248605 }, { "content": "/// Creates a [`ParquetType`] from a [`Field`].\n\npub fn to_parquet_type(field: &Field) -> Result<ParquetType> {\n\n let name = field.name().clone();\n\n let repetition = if field.is_nullable() {\n\n Repetition::Optional\n\n } else {\n\n Repetition::Required\n\n };\n\n // create type from field\n\n match field.data_type().to_logical_type() {\n\n DataType::Null => Ok(ParquetType::try_from_primitive(\n\n name,\n\n PhysicalType::Int32,\n\n repetition,\n\n None,\n\n Some(LogicalType::UNKNOWN(Default::default())),\n\n None,\n\n )?),\n\n DataType::Boolean => Ok(ParquetType::try_from_primitive(\n\n name,\n\n PhysicalType::Boolean,\n", "file_path": "src/io/parquet/write/schema.rs", "rank": 26, "score": 318357.02004775184 }, { "content": "fn children(children: Option<&Value>) -> Result<Vec<Field>> {\n\n children\n\n .map(|x| {\n\n if let Value::Array(values) = x {\n\n values\n\n .iter()\n\n .map(Field::try_from)\n\n .collect::<Result<Vec<_>>>()\n\n } else {\n\n Err(ArrowError::Schema(\"children must be an array\".to_string()))\n\n }\n\n })\n\n .unwrap_or_else(|| Ok(vec![]))\n\n}\n\n\n", "file_path": "src/io/json_integration/schema.rs", "rank": 27, "score": 318232.8815114872 }, { "content": "/// Casts a [`Utf8Array`] to a Date64 primitive, making any uncastable value a Null.\n\npub fn utf8_to_date64<O: Offset>(from: &Utf8Array<O>) -> PrimitiveArray<i64> {\n\n let iter = from.iter().map(|x| {\n\n x.and_then(|x| {\n\n x.parse::<chrono::NaiveDateTime>()\n\n .ok()\n\n .map(|x| x.timestamp_millis())\n\n })\n\n });\n\n PrimitiveArray::<i64>::from_trusted_len_iter(iter).to(DataType::Date64)\n\n}\n\n\n\npub(super) fn utf8_to_date64_dyn<O: Offset>(from: &dyn Array) -> Result<Box<dyn Array>> {\n\n let from = from.as_any().downcast_ref().unwrap();\n\n Ok(Box::new(utf8_to_date64::<O>(from)))\n\n}\n\n\n\npub(super) fn utf8_to_dictionary_dyn<O: Offset, K: DictionaryKey>(\n\n from: &dyn Array,\n\n) -> Result<Box<dyn Array>> {\n\n let values = from.as_any().downcast_ref().unwrap();\n\n utf8_to_dictionary::<O, K>(values).map(|x| Box::new(x) as Box<dyn Array>)\n\n}\n\n\n", "file_path": "src/compute/cast/utf8_to.rs", "rank": 28, "score": 318134.10623476416 }, { "content": "/// Extracts the years of a temporal array as [`PrimitiveArray<i32>`].\n\n/// Use [`can_year`] to check if this operation is supported for the target [`DataType`].\n\npub fn year(array: &dyn Array) -> Result<PrimitiveArray<i32>> {\n\n date_like!(year, array, DataType::Int32)\n\n}\n\n\n", "file_path": "src/compute/temporal.rs", "rank": 29, "score": 314796.90036549326 }, { "content": "/// Extracts the nanoseconds of a temporal array as [`PrimitiveArray<u32>`].\n\n/// Use [`can_nanosecond`] to check if this operation is supported for the target [`DataType`].\n\npub fn nanosecond(array: &dyn Array) -> Result<PrimitiveArray<u32>> {\n\n time_like!(nanosecond, array, DataType::UInt32)\n\n}\n\n\n", "file_path": "src/compute/temporal.rs", "rank": 30, "score": 314796.90036549326 }, { "content": "/// Extracts the seconds of a temporal array as [`PrimitiveArray<u32>`].\n\n/// Value ranges from 0 to 59.\n\n/// Use [`can_second`] to check if this operation is supported for the target [`DataType`].\n\npub fn second(array: &dyn Array) -> Result<PrimitiveArray<u32>> {\n\n time_like!(second, array, DataType::UInt32)\n\n}\n\n\n", "file_path": "src/compute/temporal.rs", "rank": 31, "score": 314796.6846256023 }, { "content": "/// Extracts the minutes of a temporal array as [`PrimitiveArray<u32>`].\n\n/// Value ranges from 0 to 59.\n\n/// Use [`can_minute`] to check if this operation is supported for the target [`DataType`].\n\npub fn minute(array: &dyn Array) -> Result<PrimitiveArray<u32>> {\n\n time_like!(minute, array, DataType::UInt32)\n\n}\n\n\n", "file_path": "src/compute/temporal.rs", "rank": 32, "score": 314796.6846256023 }, { "content": "/// Extracts the hours of a temporal array as [`PrimitiveArray<u32>`].\n\n/// Value ranges from 0 to 23.\n\n/// Use [`can_hour`] to check if this operation is supported for the target [`DataType`].\n\npub fn hour(array: &dyn Array) -> Result<PrimitiveArray<u32>> {\n\n time_like!(hour, array, DataType::UInt32)\n\n}\n\n\n", "file_path": "src/compute/temporal.rs", "rank": 33, "score": 314796.6846256023 }, { "content": "/// Extracts the months of a temporal array as [`PrimitiveArray<u32>`].\n\n/// Value ranges from 1 to 12.\n\n/// Use [`can_month`] to check if this operation is supported for the target [`DataType`].\n\npub fn month(array: &dyn Array) -> Result<PrimitiveArray<u32>> {\n\n date_like!(month, array, DataType::UInt32)\n\n}\n\n\n", "file_path": "src/compute/temporal.rs", "rank": 34, "score": 314796.6846256023 }, { "content": "/// Extracts weekday of a temporal array as [`PrimitiveArray<u32>`].\n\n/// Monday is 1, Tuesday is 2, ..., Sunday is 7.\n\n/// Use [`can_weekday`] to check if this operation is supported for the target [`DataType`]\n\npub fn weekday(array: &dyn Array) -> Result<PrimitiveArray<u32>> {\n\n date_like!(u32_weekday, array, DataType::UInt32)\n\n}\n\n\n", "file_path": "src/compute/temporal.rs", "rank": 35, "score": 314796.5800867535 }, { "content": "/// Extracts the days of a temporal array as [`PrimitiveArray<u32>`].\n\n/// Value ranges from 1 to 32 (Last day depends on month).\n\n/// Use [`can_day`] to check if this operation is supported for the target [`DataType`].\n\npub fn day(array: &dyn Array) -> Result<PrimitiveArray<u32>> {\n\n date_like!(day, array, DataType::UInt32)\n\n}\n\n\n", "file_path": "src/compute/temporal.rs", "rank": 36, "score": 314796.27896030014 }, { "content": "/// Returns the element-wise hash of an [`Array`]. Validity is preserved.\n\n/// Supported DataTypes:\n\n/// * Boolean types\n\n/// * All primitive types except `Float32` and `Float64`\n\n/// * `[Large]Utf8`;\n\n/// * `[Large]Binary`.\n\n/// # Errors\n\n/// This function errors whenever it does not support the specific `DataType`.\n\npub fn hash(array: &dyn Array) -> Result<PrimitiveArray<u64>> {\n\n use PhysicalType::*;\n\n Ok(match array.data_type().to_physical_type() {\n\n Boolean => hash_boolean(array.as_any().downcast_ref().unwrap()),\n\n Primitive(primitive) => with_match_primitive_type!(primitive, |$T| {\n\n hash_primitive::<$T>(array.as_any().downcast_ref().unwrap())\n\n }),\n\n Binary => hash_binary::<i32>(array.as_any().downcast_ref().unwrap()),\n\n LargeBinary => hash_binary::<i64>(array.as_any().downcast_ref().unwrap()),\n\n Utf8 => hash_utf8::<i32>(array.as_any().downcast_ref().unwrap()),\n\n LargeUtf8 => hash_utf8::<i64>(array.as_any().downcast_ref().unwrap()),\n\n t => {\n\n return Err(ArrowError::NotYetImplemented(format!(\n\n \"Hash not implemented for type {:?}\",\n\n t\n\n )))\n\n }\n\n })\n\n}\n\n\n\n/// Checks if an array of type `datatype` can be used in [`hash`].\n\n///\n\n/// # Examples\n\n/// ```\n\n/// use arrow2::compute::hash::can_hash;\n\n/// use arrow2::datatypes::{DataType};\n\n///\n\n/// let data_type = DataType::Int8;\n\n/// assert_eq!(can_hash(&data_type), true);\n\n\n", "file_path": "src/compute/hash.rs", "rank": 37, "score": 314794.4546141591 }, { "content": "/// Extracts ISO week of a temporal array as [`PrimitiveArray<u32>`]\n\n/// Value ranges from 1 to 53 (Last week depends on the year).\n\n/// Use [`can_iso_week`] to check if this operation is supported for the target [`DataType`]\n\npub fn iso_week(array: &dyn Array) -> Result<PrimitiveArray<u32>> {\n\n date_like!(u32_iso_week, array, DataType::UInt32)\n\n}\n\n\n\n// Macro to avoid repetition in functions, that apply\n\n// `chrono::Timelike` methods on Arrays\n\nmacro_rules! time_like {\n\n ($extract:ident, $array:ident, $data_type:path) => {\n\n match $array.data_type().to_logical_type() {\n\n DataType::Date32 | DataType::Date64 | DataType::Timestamp(_, None) => {\n\n date_variants($array, $data_type, |x| x.$extract())\n\n }\n\n DataType::Time32(_) | DataType::Time64(_) => {\n\n time_variants($array, DataType::UInt32, |x| x.$extract())\n\n }\n\n DataType::Timestamp(time_unit, Some(timezone_str)) => {\n\n let array = $array.as_any().downcast_ref().unwrap();\n\n\n\n if let Ok(timezone) = parse_offset(timezone_str) {\n\n Ok(extract_impl(array, *time_unit, timezone, |x| x.$extract()))\n", "file_path": "src/compute/temporal.rs", "rank": 38, "score": 310966.40949012904 }, { "content": "/// `take` implementation for utf8 arrays\n\npub fn take<O: Offset, I: Index>(\n\n values: &BinaryArray<O>,\n\n indices: &PrimitiveArray<I>,\n\n) -> BinaryArray<O> {\n\n let data_type = values.data_type().clone();\n\n let indices_has_validity = indices.null_count() > 0;\n\n let values_has_validity = values.null_count() > 0;\n\n\n\n let (offsets, values, validity) = match (values_has_validity, indices_has_validity) {\n\n (false, false) => {\n\n take_no_validity::<O, I>(values.offsets(), values.values(), indices.values())\n\n }\n\n (true, false) => take_values_validity(values, indices.values()),\n\n (false, true) => take_indices_validity(values.offsets(), values.values(), indices),\n\n (true, true) => take_values_indices_validity(values, indices),\n\n };\n\n BinaryArray::<O>::from_data(data_type, offsets, values, validity)\n\n}\n", "file_path": "src/compute/take/binary.rs", "rank": 39, "score": 310393.55627201346 }, { "content": "/// `take` implementation for ListArrays\n\npub fn take<I: Offset, O: Index>(\n\n values: &ListArray<I>,\n\n indices: &PrimitiveArray<O>,\n\n) -> ListArray<I> {\n\n let mut capacity = 0;\n\n let arrays = indices\n\n .values()\n\n .iter()\n\n .map(|index| {\n\n let index = index.to_usize();\n\n let slice = values.slice(index, 1);\n\n capacity += slice.len();\n\n slice\n\n })\n\n .collect::<Vec<ListArray<I>>>();\n\n\n\n let arrays = arrays.iter().collect();\n\n\n\n if let Some(validity) = indices.validity() {\n\n let mut growable: GrowableList<I> = GrowableList::new(arrays, true, capacity);\n", "file_path": "src/compute/take/list.rs", "rank": 40, "score": 310393.55627201346 }, { "content": "/// `take` implementation for utf8 arrays\n\npub fn take<O: Offset, I: Index>(\n\n values: &Utf8Array<O>,\n\n indices: &PrimitiveArray<I>,\n\n) -> Utf8Array<O> {\n\n let data_type = values.data_type().clone();\n\n let indices_has_validity = indices.null_count() > 0;\n\n let values_has_validity = values.null_count() > 0;\n\n\n\n let (offsets, values, validity) = match (values_has_validity, indices_has_validity) {\n\n (false, false) => {\n\n take_no_validity::<O, I>(values.offsets(), values.values(), indices.values())\n\n }\n\n (true, false) => take_values_validity(values, indices.values()),\n\n (false, true) => take_indices_validity(values.offsets(), values.values(), indices),\n\n (true, true) => take_values_indices_validity(values, indices),\n\n };\n\n unsafe { Utf8Array::<O>::from_data_unchecked(data_type, offsets, values, validity) }\n\n}\n\n\n\n#[cfg(test)]\n", "file_path": "src/compute/take/utf8.rs", "rank": 41, "score": 310393.55627201346 }, { "content": "/// [`crate::temporal_conversions::utf8_to_timestamp_ns`] applied for RFC3339 formatting\n\npub fn utf8_to_naive_timestamp_ns<O: Offset>(from: &Utf8Array<O>) -> PrimitiveArray<i64> {\n\n utf8_to_naive_timestamp_ns_(from, RFC3339)\n\n}\n\n\n\npub(super) fn utf8_to_timestamp_ns_dyn<O: Offset>(\n\n from: &dyn Array,\n\n timezone: String,\n\n) -> Result<Box<dyn Array>> {\n\n let from = from.as_any().downcast_ref().unwrap();\n\n utf8_to_timestamp_ns::<O>(from, timezone)\n\n .map(Box::new)\n\n .map(|x| x as Box<dyn Array>)\n\n}\n\n\n", "file_path": "src/compute/cast/utf8_to.rs", "rank": 42, "score": 309591.4008081917 }, { "content": "/// Concatenate multiple [Array] of the same type into a single [`Array`].\n\npub fn concatenate(arrays: &[&dyn Array]) -> Result<Box<dyn Array>> {\n\n if arrays.is_empty() {\n\n return Err(ArrowError::InvalidArgumentError(\n\n \"concat requires input of at least one array\".to_string(),\n\n ));\n\n }\n\n\n\n if arrays\n\n .iter()\n\n .any(|array| array.data_type() != arrays[0].data_type())\n\n {\n\n return Err(ArrowError::InvalidArgumentError(\n\n \"It is not possible to concatenate arrays of different data types.\".to_string(),\n\n ));\n\n }\n\n\n\n let lengths = arrays.iter().map(|array| array.len()).collect::<Vec<_>>();\n\n let capacity = lengths.iter().sum();\n\n\n\n let mut mutable = make_growable(arrays, false, capacity);\n\n\n\n for (i, len) in lengths.iter().enumerate() {\n\n mutable.extend(i, 0, *len)\n\n }\n\n\n\n Ok(mutable.as_box())\n\n}\n", "file_path": "src/compute/concat.rs", "rank": 43, "score": 309460.11592872976 }, { "content": "pub fn check_offsets_minimal<O: Offset>(offsets: &[O], values_len: usize) -> usize {\n\n assert!(\n\n !offsets.is_empty(),\n\n \"The length of the offset buffer must be larger than 1\"\n\n );\n\n let len = offsets.len() - 1;\n\n\n\n let last_offset = offsets[len];\n\n let last_offset = last_offset.to_usize();\n\n\n\n assert_eq!(\n\n values_len, last_offset,\n\n \"The length of the values must be equal to the last offset value\"\n\n );\n\n len\n\n}\n\n\n", "file_path": "src/array/specification.rs", "rank": 44, "score": 308418.30310233857 }, { "content": "/// # Panics iff:\n\n/// * the `offsets` is not monotonically increasing, or\n\n/// * any offset is larger or equal to `values_len`.\n\npub fn check_offsets<O: Offset>(offsets: &[O], values_len: usize) {\n\n offsets.windows(2).for_each(|window| {\n\n let start = window[0].to_usize();\n\n let end = window[1].to_usize();\n\n // assert monotonicity\n\n assert!(start <= end);\n\n // assert bound\n\n assert!(end <= values_len);\n\n });\n\n}\n", "file_path": "src/array/specification.rs", "rank": 45, "score": 307082.78645979014 }, { "content": "pub fn take_values<O: Offset>(length: O, starts: &[O], offsets: &[O], values: &[u8]) -> Buffer<u8> {\n\n let new_len = length.to_usize();\n\n let mut buffer = MutableBuffer::with_capacity(new_len);\n\n starts\n\n .iter()\n\n .zip(offsets.windows(2))\n\n .for_each(|(start_, window)| {\n\n let start = start_.to_usize();\n\n let end = (*start_ + (window[1] - window[0])).to_usize();\n\n buffer.extend_from_slice(&values[start..end]);\n\n });\n\n buffer.into()\n\n}\n\n\n", "file_path": "src/compute/take/generic_binary.rs", "rank": 46, "score": 304618.5895198187 }, { "content": "// take implementation when neither values nor indices contain nulls\n\npub fn take_no_validity<O: Offset, I: Index>(\n\n offsets: &[O],\n\n values: &[u8],\n\n indices: &[I],\n\n) -> (Buffer<O>, Buffer<u8>, Option<Bitmap>) {\n\n let mut length = O::default();\n\n let mut buffer = MutableBuffer::<u8>::new();\n\n let offsets = indices.iter().map(|index| {\n\n let index = index.to_usize();\n\n let start = offsets[index];\n\n let length_h = offsets[index + 1] - start;\n\n length += length_h;\n\n\n\n let _start = start.to_usize();\n\n let end = (start + length_h).to_usize();\n\n buffer.extend_from_slice(&values[_start..end]);\n\n length\n\n });\n\n let offsets = std::iter::once(O::default()).chain(offsets);\n\n let offsets = Buffer::from_trusted_len_iter(offsets);\n\n\n\n (offsets, buffer.into(), None)\n\n}\n\n\n", "file_path": "src/compute/take/generic_binary.rs", "rank": 47, "score": 301027.37346589286 }, { "content": "/// Filters an [Array], returning elements matching the filter (i.e. where the values are true).\n\n/// WARNING: the nulls of `filter` are ignored and the value on its slot is considered.\n\n/// Therefore, it is considered undefined behavior to pass `filter` with null values.\n\n/// # Example\n\n/// ```rust\n\n/// # use arrow2::array::{Int32Array, PrimitiveArray, BooleanArray};\n\n/// # use arrow2::error::Result;\n\n/// # use arrow2::compute::filter::filter;\n\n/// # fn main() -> Result<()> {\n\n/// let array = PrimitiveArray::from_slice([5, 6, 7, 8, 9]);\n\n/// let filter_array = BooleanArray::from_slice(&vec![true, false, false, true, false]);\n\n/// let c = filter(&array, &filter_array)?;\n\n/// let c = c.as_any().downcast_ref::<Int32Array>().unwrap();\n\n/// assert_eq!(c, &PrimitiveArray::from_slice(vec![5, 8]));\n\n/// # Ok(())\n\n/// # }\n\n/// ```\n\npub fn filter(array: &dyn Array, filter: &BooleanArray) -> Result<Box<dyn Array>> {\n\n use crate::datatypes::PhysicalType::*;\n\n match array.data_type().to_physical_type() {\n\n Primitive(primitive) => with_match_primitive_type!(primitive, |$T| {\n\n let array = array.as_any().downcast_ref().unwrap();\n\n Ok(Box::new(filter_primitive::<$T>(array, filter)))\n\n }),\n\n _ => {\n\n let iter = SlicesIterator::new(filter.values());\n\n let mut mutable = make_growable(&[array], false, iter.slots());\n\n iter.for_each(|(start, len)| mutable.extend(0, start, len));\n\n Ok(mutable.as_box())\n\n }\n\n }\n\n}\n\n\n", "file_path": "src/compute/filter.rs", "rank": 48, "score": 300676.68663992616 }, { "content": "// take implementation when only values contain nulls\n\npub fn take_values_validity<O: Offset, I: Index, A: GenericBinaryArray<O>>(\n\n values: &A,\n\n indices: &[I],\n\n) -> (Buffer<O>, Buffer<u8>, Option<Bitmap>) {\n\n let mut length = O::default();\n\n let mut validity = MutableBitmap::with_capacity(indices.len());\n\n\n\n let null_values = values.validity().unwrap();\n\n let offsets = values.offsets();\n\n let values_values = values.values();\n\n\n\n let mut starts = MutableBuffer::<O>::with_capacity(indices.len());\n\n let offsets = indices.iter().map(|index| {\n\n let index = index.to_usize();\n\n if null_values.get_bit(index) {\n\n validity.push(true);\n\n let start = offsets[index];\n\n length += offsets[index + 1] - start;\n\n starts.push(start);\n\n } else {\n", "file_path": "src/compute/take/generic_binary.rs", "rank": 49, "score": 299816.2797413575 }, { "content": "/// Returns the number of zero bits in the slice offsetted by `offset` and a length of `length`.\n\n/// # Panics\n\n/// This function panics iff `(offset + len).saturating_add(7) / 8 >= slice.len()`\n\n/// because it corresponds to the situation where `len` is beyond bounds.\n\npub fn count_zeros(slice: &[u8], offset: usize, len: usize) -> usize {\n\n if len == 0 {\n\n return 0;\n\n };\n\n\n\n let mut slice = &slice[offset / 8..(offset + len).saturating_add(7) / 8];\n\n let offset = offset % 8;\n\n\n\n if (offset + len) / 8 == 0 {\n\n // all within a single byte\n\n let byte = (slice[0] >> offset) << (8 - len);\n\n return len - byte.count_ones() as usize;\n\n }\n\n\n\n // slice: [a1,a2,a3,a4], [a5,a6,a7,a8]\n\n // offset: 3\n\n // len: 4\n\n // [__,__,__,a4], [a5,a6,a7,__]\n\n let mut set_count = 0;\n\n if offset != 0 {\n", "file_path": "src/bitmap/utils/mod.rs", "rank": 50, "score": 299711.0002824304 }, { "content": "/// Returns the sum of all elements in `array` as a [`Scalar`] of the same physical\n\n/// and logical types as `array`.\n\n/// # Error\n\n/// Errors iff the operation is not supported.\n\npub fn sum(array: &dyn Array) -> Result<Box<dyn Scalar>> {\n\n Ok(match array.data_type() {\n\n DataType::Int8 => dyn_sum!(i8, array),\n\n DataType::Int16 => dyn_sum!(i16, array),\n\n DataType::Int32\n\n | DataType::Date32\n\n | DataType::Time32(_)\n\n | DataType::Interval(IntervalUnit::YearMonth) => {\n\n dyn_sum!(i32, array)\n\n }\n\n DataType::Int64\n\n | DataType::Date64\n\n | DataType::Time64(_)\n\n | DataType::Timestamp(_, _)\n\n | DataType::Duration(_) => dyn_sum!(i64, array),\n\n DataType::UInt8 => dyn_sum!(u8, array),\n\n DataType::UInt16 => dyn_sum!(u16, array),\n\n DataType::UInt32 => dyn_sum!(u32, array),\n\n DataType::UInt64 => dyn_sum!(u64, array),\n\n DataType::Float16 => unreachable!(),\n", "file_path": "src/compute/aggregate/sum.rs", "rank": 51, "score": 298602.92614963476 }, { "content": "/// Returns whether each element in `values` is in each element from `list`\n\npub fn contains(list: &dyn Array, values: &dyn Array) -> Result<BooleanArray> {\n\n let list_data_type = list.data_type();\n\n let values_data_type = values.data_type();\n\n\n\n match (list_data_type, values_data_type) {\n\n (DataType::List(_), DataType::Utf8) => {\n\n let list = list.as_any().downcast_ref::<ListArray<i32>>().unwrap();\n\n let values = values.as_any().downcast_ref::<Utf8Array<i32>>().unwrap();\n\n contains_utf8(list, values)\n\n }\n\n (DataType::List(_), DataType::LargeUtf8) => {\n\n let list = list.as_any().downcast_ref::<ListArray<i32>>().unwrap();\n\n let values = values.as_any().downcast_ref::<Utf8Array<i64>>().unwrap();\n\n contains_utf8(list, values)\n\n }\n\n (DataType::LargeList(_), DataType::LargeUtf8) => {\n\n let list = list.as_any().downcast_ref::<ListArray<i64>>().unwrap();\n\n let values = values.as_any().downcast_ref::<Utf8Array<i64>>().unwrap();\n\n contains_utf8(list, values)\n\n }\n", "file_path": "src/compute/contains.rs", "rank": 52, "score": 297057.87406204635 }, { "content": "// take implementation when only indices contain nulls\n\npub fn take_indices_validity<O: Offset, I: Index>(\n\n offsets: &[O],\n\n values: &[u8],\n\n indices: &PrimitiveArray<I>,\n\n) -> (Buffer<O>, Buffer<u8>, Option<Bitmap>) {\n\n let mut length = O::default();\n\n\n\n let mut starts = MutableBuffer::<O>::with_capacity(indices.len());\n\n let offsets = indices.values().iter().map(|index| {\n\n let index = index.to_usize();\n\n match offsets.get(index + 1) {\n\n Some(&next) => {\n\n let start = offsets[index];\n\n length += next - start;\n\n starts.push(start);\n\n }\n\n None => starts.push(O::default()),\n\n };\n\n length\n\n });\n\n let offsets = std::iter::once(O::default()).chain(offsets);\n\n let offsets = Buffer::from_trusted_len_iter(offsets);\n\n let starts: Buffer<O> = starts.into();\n\n\n\n let buffer = take_values(length, starts.as_slice(), offsets.as_slice(), values);\n\n\n\n (offsets, buffer, indices.validity().cloned())\n\n}\n\n\n", "file_path": "src/compute/take/generic_binary.rs", "rank": 53, "score": 296709.79954975983 }, { "content": "// take implementation when both indices and values contain nulls\n\npub fn take_values_indices_validity<O: Offset, I: Index, A: GenericBinaryArray<O>>(\n\n values: &A,\n\n indices: &PrimitiveArray<I>,\n\n) -> (Buffer<O>, Buffer<u8>, Option<Bitmap>) {\n\n let mut length = O::default();\n\n let mut validity = MutableBitmap::with_capacity(indices.len());\n\n\n\n let values_validity = values.validity().unwrap();\n\n let offsets = values.offsets();\n\n let values_values = values.values();\n\n\n\n let mut starts = MutableBuffer::<O>::with_capacity(indices.len());\n\n let offsets = indices.iter().map(|index| {\n\n match index {\n\n Some(index) => {\n\n let index = index.to_usize();\n\n if values_validity.get_bit(index) {\n\n validity.push(true);\n\n length += offsets[index + 1] - offsets[index];\n\n starts.push(offsets[index]);\n", "file_path": "src/compute/take/generic_binary.rs", "rank": 54, "score": 295609.68273971975 }, { "content": "pub fn max(array: &dyn Array) -> Result<Box<dyn Scalar>> {\n\n Ok(match array.data_type() {\n\n DataType::Boolean => dyn_generic!(BooleanArray, BooleanScalar, array, max_boolean),\n\n DataType::Int8 => dyn_primitive!(i8, array, max_primitive),\n\n DataType::Int16 => dyn_primitive!(i16, array, max_primitive),\n\n DataType::Int32\n\n | DataType::Date32\n\n | DataType::Time32(_)\n\n | DataType::Interval(IntervalUnit::YearMonth) => {\n\n dyn_primitive!(i32, array, max_primitive)\n\n }\n\n DataType::Int64\n\n | DataType::Date64\n\n | DataType::Time64(_)\n\n | DataType::Timestamp(_, _)\n\n | DataType::Duration(_) => dyn_primitive!(i64, array, max_primitive),\n\n DataType::UInt8 => dyn_primitive!(u8, array, max_primitive),\n\n DataType::UInt16 => dyn_primitive!(u16, array, max_primitive),\n\n DataType::UInt32 => dyn_primitive!(u32, array, max_primitive),\n\n DataType::UInt64 => dyn_primitive!(u64, array, max_primitive),\n", "file_path": "src/compute/aggregate/min_max.rs", "rank": 55, "score": 294807.41175043327 }, { "content": "pub fn min(array: &dyn Array) -> Result<Box<dyn Scalar>> {\n\n Ok(match array.data_type() {\n\n DataType::Boolean => dyn_generic!(BooleanArray, BooleanScalar, array, min_boolean),\n\n DataType::Int8 => dyn_primitive!(i8, array, min_primitive),\n\n DataType::Int16 => dyn_primitive!(i16, array, min_primitive),\n\n DataType::Int32\n\n | DataType::Date32\n\n | DataType::Time32(_)\n\n | DataType::Interval(IntervalUnit::YearMonth) => {\n\n dyn_primitive!(i32, array, min_primitive)\n\n }\n\n DataType::Int64\n\n | DataType::Date64\n\n | DataType::Time64(_)\n\n | DataType::Timestamp(_, _)\n\n | DataType::Duration(_) => dyn_primitive!(i64, array, min_primitive),\n\n DataType::UInt8 => dyn_primitive!(u8, array, min_primitive),\n\n DataType::UInt16 => dyn_primitive!(u16, array, min_primitive),\n\n DataType::UInt32 => dyn_primitive!(u32, array, min_primitive),\n\n DataType::UInt64 => dyn_primitive!(u64, array, min_primitive),\n", "file_path": "src/compute/aggregate/min_max.rs", "rank": 56, "score": 294807.41175043327 }, { "content": "/// Returns `lhs LIKE rhs` operation.\n\n///\n\n/// There are two wildcards supported:\n\n///\n\n/// * `%` - The percent sign represents zero, one, or multiple characters\n\n/// * `_` - The underscore represents a single character\n\n///\n\n/// # Error\n\n/// Errors iff:\n\n/// * the arrays have a different length\n\n/// * any of the patterns is not valid\n\n/// # Example\n\n/// ```\n\n/// use arrow2::array::{Utf8Array, BooleanArray};\n\n/// use arrow2::compute::like::like_utf8_scalar;\n\n///\n\n/// let array = Utf8Array::<i32>::from_slice(&[\"Arrow\", \"Arrow\", \"Arrow\", \"BA\"]);\n\n///\n\n/// let result = like_utf8_scalar(&array, &\"A%\").unwrap();\n\n/// assert_eq!(result, BooleanArray::from_slice(&[true, true, true, false]));\n\n/// ```\n\npub fn like_utf8_scalar<O: Offset>(lhs: &Utf8Array<O>, rhs: &str) -> Result<BooleanArray> {\n\n a_like_utf8_scalar(lhs, rhs, |x| x)\n\n}\n\n\n", "file_path": "src/compute/like.rs", "rank": 57, "score": 294761.8088491722 }, { "content": "/// Returns `lhs LIKE rhs` operation.\n\n///\n\n/// There are two wildcards supported:\n\n///\n\n/// * `%` - The percent sign represents zero, one, or multiple characters\n\n/// * `_` - The underscore represents a single character\n\n///\n\n/// # Error\n\n/// Errors iff:\n\n/// * the arrays have a different length\n\n/// * any of the patterns is not valid\n\n/// # Example\n\n/// ```\n\n/// use arrow2::array::{BinaryArray, BooleanArray};\n\n/// use arrow2::compute::like::like_binary_scalar;\n\n///\n\n/// let array = BinaryArray::<i32>::from_slice(&[\"Arrow\", \"Arrow\", \"Arrow\", \"BA\"]);\n\n///\n\n/// let result = like_binary_scalar(&array, b\"A%\").unwrap();\n\n/// assert_eq!(result, BooleanArray::from_slice(&[true, true, true, false]));\n\n/// ```\n\npub fn like_binary_scalar<O: Offset>(lhs: &BinaryArray<O>, rhs: &[u8]) -> Result<BooleanArray> {\n\n a_like_binary_scalar(lhs, rhs, |x| x)\n\n}\n\n\n", "file_path": "src/compute/like.rs", "rank": 58, "score": 294761.8088491722 }, { "content": "/// Returns `lhs NOT LIKE rhs` operation on two [`BinaryArray`]s.\n\n///\n\n/// There are two wildcards supported:\n\n///\n\n/// * `%` - The percent sign represents zero, one, or multiple characters\n\n/// * `_` - The underscore represents a single character\n\n///\n\npub fn nlike_binary_scalar<O: Offset>(lhs: &BinaryArray<O>, rhs: &[u8]) -> Result<BooleanArray> {\n\n a_like_binary_scalar(lhs, rhs, |x| !x)\n\n}\n", "file_path": "src/compute/like.rs", "rank": 59, "score": 294745.3431129807 }, { "content": "/// Returns `lhs NOT LIKE rhs` operation.\n\n///\n\n/// There are two wildcards supported:\n\n///\n\n/// * `%` - The percent sign represents zero, one, or multiple characters\n\n/// * `_` - The underscore represents a single character\n\npub fn nlike_utf8_scalar<O: Offset>(lhs: &Utf8Array<O>, rhs: &str) -> Result<BooleanArray> {\n\n a_like_utf8_scalar(lhs, rhs, |x| !x)\n\n}\n\n\n", "file_path": "src/compute/like.rs", "rank": 60, "score": 294741.0329358418 }, { "content": "/// Returns `lhs LIKE rhs` operation on two [`Utf8Array`].\n\n///\n\n/// There are two wildcards supported:\n\n///\n\n/// * `%` - The percent sign represents zero, one, or multiple characters\n\n/// * `_` - The underscore represents a single character\n\n///\n\n/// # Error\n\n/// Errors iff:\n\n/// * the arrays have a different length\n\n/// * any of the patterns is not valid\n\n/// # Example\n\n/// ```\n\n/// use arrow2::array::{Utf8Array, BooleanArray};\n\n/// use arrow2::compute::like::like_utf8;\n\n///\n\n/// let strings = Utf8Array::<i32>::from_slice(&[\"Arrow\", \"Arrow\", \"Arrow\", \"Arrow\", \"Ar\"]);\n\n/// let patterns = Utf8Array::<i32>::from_slice(&[\"A%\", \"B%\", \"%r_ow\", \"A_\", \"A_\"]);\n\n///\n\n/// let result = like_utf8(&strings, &patterns).unwrap();\n\n/// assert_eq!(result, BooleanArray::from_slice(&[true, false, true, false, true]));\n\n/// ```\n\npub fn like_utf8<O: Offset>(lhs: &Utf8Array<O>, rhs: &Utf8Array<O>) -> Result<BooleanArray> {\n\n a_like_utf8(lhs, rhs, |x| x)\n\n}\n\n\n", "file_path": "src/compute/like.rs", "rank": 61, "score": 294417.5466421954 }, { "content": "/// Returns `lhs LIKE rhs` operation on two [`BinaryArray`].\n\n///\n\n/// There are two wildcards supported:\n\n///\n\n/// * `%` - The percent sign represents zero, one, or multiple characters\n\n/// * `_` - The underscore represents a single character\n\n///\n\n/// # Error\n\n/// Errors iff:\n\n/// * the arrays have a different length\n\n/// * any of the patterns is not valid\n\n/// # Example\n\n/// ```\n\n/// use arrow2::array::{BinaryArray, BooleanArray};\n\n/// use arrow2::compute::like::like_binary;\n\n///\n\n/// let strings = BinaryArray::<i32>::from_slice(&[\"Arrow\", \"Arrow\", \"Arrow\", \"Arrow\", \"Ar\"]);\n\n/// let patterns = BinaryArray::<i32>::from_slice(&[\"A%\", \"B%\", \"%r_ow\", \"A_\", \"A_\"]);\n\n///\n\n/// let result = like_binary(&strings, &patterns).unwrap();\n\n/// assert_eq!(result, BooleanArray::from_slice(&[true, false, true, false, true]));\n\n/// ```\n\npub fn like_binary<O: Offset>(lhs: &BinaryArray<O>, rhs: &BinaryArray<O>) -> Result<BooleanArray> {\n\n a_like_binary(lhs, rhs, |x| x)\n\n}\n\n\n", "file_path": "src/compute/like.rs", "rank": 62, "score": 294417.5466421954 }, { "content": "/// Returns `lhs NOT LIKE rhs` operation on two [`BinaryArray`]s.\n\n///\n\n/// There are two wildcards supported:\n\n///\n\n/// * `%` - The percent sign represents zero, one, or multiple characters\n\n/// * `_` - The underscore represents a single character\n\n///\n\npub fn nlike_binary<O: Offset>(lhs: &BinaryArray<O>, rhs: &BinaryArray<O>) -> Result<BooleanArray> {\n\n a_like_binary(lhs, rhs, |x| !x)\n\n}\n\n\n", "file_path": "src/compute/like.rs", "rank": 63, "score": 294401.73878709774 }, { "content": "/// Returns `lhs NOT LIKE rhs` operation on two [`Utf8Array`].\n\n///\n\n/// There are two wildcards supported:\n\n///\n\n/// * `%` - The percent sign represents zero, one, or multiple characters\n\n/// * `_` - The underscore represents a single character\n\npub fn nlike_utf8<O: Offset>(lhs: &Utf8Array<O>, rhs: &Utf8Array<O>) -> Result<BooleanArray> {\n\n a_like_utf8(lhs, rhs, |x| !x)\n\n}\n\n\n", "file_path": "src/compute/like.rs", "rank": 64, "score": 294401.73878709774 }, { "content": "/// returns a comparison function that compares values at two different slots\n\n/// between two [`Array`].\n\n/// # Example\n\n/// ```\n\n/// use arrow2::array::{ord::build_compare, PrimitiveArray};\n\n///\n\n/// # fn main() -> arrow2::error::Result<()> {\n\n/// let array1 = PrimitiveArray::from_slice([1, 2]);\n\n/// let array2 = PrimitiveArray::from_slice([3, 4]);\n\n///\n\n/// let cmp = build_compare(&array1, &array2)?;\n\n///\n\n/// // 1 (index 0 of array1) is smaller than 4 (index 1 of array2)\n\n/// assert_eq!(std::cmp::Ordering::Less, (cmp)(0, 1));\n\n/// # Ok(())\n\n/// # }\n\n/// ```\n\n/// # Error\n\n/// The arrays' [`DataType`] must be equal and the types must have a natural order.\n\n// This is a factory of comparisons.\n\npub fn build_compare(left: &dyn Array, right: &dyn Array) -> Result<DynComparator> {\n\n use DataType::*;\n\n use IntervalUnit::*;\n\n use TimeUnit::*;\n\n Ok(match (left.data_type(), right.data_type()) {\n\n (a, b) if a != b => {\n\n return Err(ArrowError::InvalidArgumentError(\n\n \"Can't compare arrays of different types\".to_string(),\n\n ));\n\n }\n\n (Boolean, Boolean) => compare_boolean(left, right),\n\n (UInt8, UInt8) => compare_primitives::<u8>(left, right),\n\n (UInt16, UInt16) => compare_primitives::<u16>(left, right),\n\n (UInt32, UInt32) => compare_primitives::<u32>(left, right),\n\n (UInt64, UInt64) => compare_primitives::<u64>(left, right),\n\n (Int8, Int8) => compare_primitives::<i8>(left, right),\n\n (Int16, Int16) => compare_primitives::<i16>(left, right),\n\n (Int32, Int32)\n\n | (Date32, Date32)\n\n | (Time32(Second), Time32(Second))\n", "file_path": "src/array/ord.rs", "rank": 65, "score": 293578.5809676381 }, { "content": "fn test_generic<O: Offset, F: Fn(&Utf8Array<O>, &Utf8Array<O>) -> Result<BooleanArray>>(\n\n lhs: Vec<&str>,\n\n pattern: Vec<&str>,\n\n op: F,\n\n expected: Vec<bool>,\n\n) {\n\n let lhs = Utf8Array::<O>::from_slice(lhs);\n\n let pattern = Utf8Array::<O>::from_slice(pattern);\n\n let expected = BooleanArray::from_slice(expected);\n\n let result = op(&lhs, &pattern).unwrap();\n\n assert_eq!(result, expected);\n\n}\n\n\n", "file_path": "tests/it/compute/regex_match.rs", "rank": 66, "score": 293480.99126353156 }, { "content": "fn test_generic_scalar<O: Offset, F: Fn(&Utf8Array<O>, &str) -> Result<BooleanArray>>(\n\n lhs: Vec<&str>,\n\n pattern: &str,\n\n op: F,\n\n expected: Vec<bool>,\n\n) {\n\n let lhs = Utf8Array::<O>::from_slice(lhs);\n\n let expected = BooleanArray::from_slice(expected);\n\n let result = op(&lhs, pattern).unwrap();\n\n assert_eq!(result, expected);\n\n}\n\n\n", "file_path": "tests/it/compute/regex_match.rs", "rank": 67, "score": 293004.46912969486 }, { "content": "/// Cast `array` to the provided data type and return a new [`Array`] with\n\n/// type `to_type`, if possible.\n\n///\n\n/// Behavior:\n\n/// * PrimitiveArray to PrimitiveArray: overflowing cast will be None\n\n/// * Boolean to Utf8: `true` => '1', `false` => `0`\n\n/// * Utf8 to numeric: strings that can't be parsed to numbers return null, float strings\n\n/// in integer casts return null\n\n/// * Numeric to boolean: 0 returns `false`, any other value returns `true`\n\n/// * List to List: the underlying data type is cast\n\n/// * PrimitiveArray to List: a list array with 1 value per slot is created\n\n/// * Date32 and Date64: precision lost when going to higher interval\n\n/// * Time32 and Time64: precision lost when going to higher interval\n\n/// * Timestamp and Date{32|64}: precision lost when going to higher interval\n\n/// * Temporal to/from backing primitive: zero-copy with data type change\n\n/// Unsupported Casts\n\n/// * To or from `StructArray`\n\n/// * List to primitive\n\n/// * Utf8 to boolean\n\n/// * Interval and duration\n\npub fn cast(array: &dyn Array, to_type: &DataType) -> Result<Box<dyn Array>> {\n\n cast_with_options(array, to_type, CastOptions { wrapped: false })\n\n}\n\n\n", "file_path": "src/compute/cast/mod.rs", "rank": 68, "score": 292838.0130851419 }, { "content": "/// Returns an array whose validity is null iff `lhs == rhs` or `lhs` is null.\n\n/// This has the same semantics as postgres.\n\n/// # Example\n\n/// ```rust\n\n/// # use arrow2::array::Int32Array;\n\n/// # use arrow2::datatypes::DataType;\n\n/// # use arrow2::error::Result;\n\n/// # use arrow2::compute::nullif::nullif;\n\n/// # fn main() -> Result<()> {\n\n/// let lhs = Int32Array::from(&[None, None, Some(1), Some(1), Some(1)]);\n\n/// let rhs = Int32Array::from(&[None, Some(1), None, Some(1), Some(0)]);\n\n/// let result = nullif(&lhs, &rhs)?;\n\n///\n\n/// let expected = Int32Array::from(&[None, None, Some(1), None, Some(1)]);\n\n///\n\n/// assert_eq!(expected, result.as_ref());\n\n/// Ok(())\n\n/// # }\n\n/// ```\n\n/// # Errors\n\n/// This function errors iff\n\n/// * The arguments do not have the same logical type\n\n/// * The arguments do not have the same length\n\n/// * The logical type is not supported\n\npub fn nullif(lhs: &dyn Array, rhs: &dyn Array) -> Result<Box<dyn Array>> {\n\n if lhs.data_type() != rhs.data_type() {\n\n return Err(ArrowError::InvalidArgumentError(\n\n \"Nullif expects arrays of the the same logical type\".to_string(),\n\n ));\n\n }\n\n if lhs.len() != rhs.len() {\n\n return Err(ArrowError::InvalidArgumentError(\n\n \"Nullif expects arrays of the the same length\".to_string(),\n\n ));\n\n }\n\n use crate::datatypes::DataType::*;\n\n match lhs.data_type() {\n\n UInt8 => nullif_primitive::<u8>(\n\n lhs.as_any().downcast_ref().unwrap(),\n\n rhs.as_any().downcast_ref().unwrap(),\n\n )\n\n .map(|x| Box::new(x) as Box<dyn Array>),\n\n UInt16 => nullif_primitive::<u16>(\n\n lhs.as_any().downcast_ref().unwrap(),\n", "file_path": "src/compute/nullif.rs", "rank": 69, "score": 292102.5498365097 }, { "content": "/// Conversion of times\n\npub fn time64us_to_time64ns(from: &PrimitiveArray<i64>) -> PrimitiveArray<i64> {\n\n unary(from, |x| x * 1000, DataType::Time64(TimeUnit::Nanosecond))\n\n}\n\n\n", "file_path": "src/compute/cast/primitive_to.rs", "rank": 70, "score": 290805.76071059017 }, { "content": "/// Conversion of times\n\npub fn time64ns_to_time64us(from: &PrimitiveArray<i64>) -> PrimitiveArray<i64> {\n\n unary(from, |x| x / 1000, DataType::Time64(TimeUnit::Microsecond))\n\n}\n\n\n", "file_path": "src/compute/cast/primitive_to.rs", "rank": 71, "score": 290805.76071059017 }, { "content": "/// Similar to [`cast`], but overflowing cast is wrapped\n\n/// Behavior:\n\n/// * PrimitiveArray to PrimitiveArray: overflowing cast will be wrapped (i.e. `256i16 as u8 = 0` vectorized).\n\npub fn wrapping_cast(array: &dyn Array, to_type: &DataType) -> Result<Box<dyn Array>> {\n\n cast_with_options(array, to_type, CastOptions { wrapped: true })\n\n}\n\n\n", "file_path": "src/compute/cast/mod.rs", "rank": 72, "score": 289611.2913991663 }, { "content": "/// Element-wise hash of a [`BinaryArray`]. Validity is preserved.\n\npub fn hash_binary<O: Offset>(array: &BinaryArray<O>) -> PrimitiveArray<u64> {\n\n let state = new_state!();\n\n let iter = array.values_iter().map(|x| <[u8]>::get_hash(&x, &state));\n\n let values = Buffer::from_trusted_len_iter(iter);\n\n PrimitiveArray::<u64>::from_data(DataType::UInt64, values, array.validity().cloned())\n\n}\n\n\n\nmacro_rules! with_match_primitive_type {(\n\n $key_type:expr, | $_:tt $T:ident | $($body:tt)*\n\n) => ({\n\n macro_rules! __with_ty__ {( $_ $T:ident ) => ( $($body)* )}\n\n use crate::datatypes::PrimitiveType::*;\n\n use crate::types::days_ms;\n\n match $key_type {\n\n Int8 => __with_ty__! { i8 },\n\n Int16 => __with_ty__! { i16 },\n\n Int32 => __with_ty__! { i32 },\n\n Int64 => __with_ty__! { i64 },\n\n Int128 => __with_ty__! { i128 },\n\n DaysMs => __with_ty__! { days_ms },\n", "file_path": "src/compute/hash.rs", "rank": 73, "score": 286704.0018791001 }, { "content": "/// Element-wise hash of a [`Utf8Array`]. Validity is preserved.\n\npub fn hash_utf8<O: Offset>(array: &Utf8Array<O>) -> PrimitiveArray<u64> {\n\n let state = new_state!();\n\n\n\n let iter = array\n\n .values_iter()\n\n .map(|x| <[u8]>::get_hash(&x.as_bytes(), &state));\n\n let values = Buffer::from_trusted_len_iter(iter);\n\n PrimitiveArray::<u64>::from_data(DataType::UInt64, values, array.validity().cloned())\n\n}\n\n\n", "file_path": "src/compute/hash.rs", "rank": 74, "score": 286704.0018791001 }, { "content": "pub fn skip_null(field_nodes: &mut VecDeque<Node>) {\n\n let _ = field_nodes.pop_front();\n\n}\n", "file_path": "src/io/ipc/read/array/null.rs", "rank": 75, "score": 285599.3436249144 }, { "content": "/// Returns the total (heap) allocated size of the array in bytes.\n\n/// # Implementation\n\n/// This estimation is the sum of the size of its buffers, validity, including nested arrays.\n\n/// Multiple arrays may share buffers and bitmaps. Therefore, the size of 2 arrays is not the\n\n/// sum of the sizes computed from this function. In particular, [`StructArray`]'s size is an upper bound.\n\n///\n\n/// When an array is sliced, its allocated size remains constant because the buffer unchanged.\n\n/// However, this function will yield a smaller number. This is because this function returns\n\n/// the visible size of the buffer, not its total capacity.\n\n///\n\n/// FFI buffers are included in this estimation.\n\npub fn estimated_bytes_size(array: &dyn Array) -> usize {\n\n use PhysicalType::*;\n\n match array.data_type().to_physical_type() {\n\n Null => 0,\n\n Boolean => {\n\n let array = array.as_any().downcast_ref::<BooleanArray>().unwrap();\n\n array.values().as_slice().0.len() + validity_size(array.validity())\n\n }\n\n Primitive(primitive) => with_match_primitive_type!(primitive, |$T| {\n\n let array = array\n\n .as_any()\n\n .downcast_ref::<PrimitiveArray<$T>>()\n\n .unwrap();\n\n\n\n array.values().len() * std::mem::size_of::<$T>() + validity_size(array.validity())\n\n }),\n\n Binary => dyn_binary!(array, BinaryArray<i32>, i32),\n\n FixedSizeBinary => {\n\n let array = array\n\n .as_any()\n", "file_path": "src/compute/aggregate/memory.rs", "rank": 76, "score": 284779.9743843308 }, { "content": "#[inline]\n\npub fn set_bit(data: &mut [u8], i: usize, value: bool) {\n\n data[i / 8] = set(data[i / 8], i % 8, value);\n\n}\n\n\n\n/// Returns whether bit at position `i` in `data` is set or not\n", "file_path": "src/bitmap/utils/mod.rs", "rank": 77, "score": 283188.5962041355 }, { "content": "#[test]\n\nfn offset() {\n\n let values = &[0b01011011u8];\n\n let iter = BitmapIter::new(values, 2, 4);\n\n let result = iter.collect::<Vec<_>>();\n\n assert_eq!(result, vec![false, true, true, false])\n\n}\n\n\n", "file_path": "tests/it/bitmap/utils/iterator.rs", "rank": 78, "score": 282211.55782688945 }, { "content": "#[test]\n\nfn offset() {\n\n let (fields, values) = some_values();\n\n\n\n let array = StructArray::from_data(fields.clone(), values.clone(), None).slice(1, 3);\n\n\n\n let mut a = GrowableStruct::new(vec![&array], false, 0);\n\n\n\n a.extend(0, 1, 2);\n\n let result: StructArray = a.into();\n\n\n\n let expected = StructArray::from_data(\n\n fields,\n\n vec![values[0].slice(2, 2).into(), values[1].slice(2, 2).into()],\n\n None,\n\n );\n\n\n\n assert_eq!(result, expected);\n\n}\n\n\n", "file_path": "tests/it/array/growable/struct_.rs", "rank": 79, "score": 280906.6093394299 }, { "content": "/// Returns a function of index returning the string representation of the item of `array`.\n\n/// This outputs an empty string on nulls.\n\npub fn get_display<'a>(array: &'a dyn Array) -> Box<dyn Fn(usize) -> String + 'a> {\n\n let value_display = get_value_display(array);\n\n Box::new(move |row| {\n\n if array.is_null(row) {\n\n \"\".to_string()\n\n } else {\n\n value_display(row)\n\n }\n\n })\n\n}\n", "file_path": "src/array/display.rs", "rank": 80, "score": 280787.1127577174 }, { "content": "fn write_ipc<W: Write + Seek>(writer: W, array: impl Array + 'static) -> Result<W> {\n\n let schema = Schema::new(vec![Field::new(\"a\", array.data_type().clone(), false)]);\n\n\n\n let mut writer = write::FileWriter::try_new(writer, &schema)?;\n\n\n\n let batch = RecordBatch::try_new(Arc::new(schema), vec![Arc::new(array)])?;\n\n\n\n writer.write(&batch)?;\n\n\n\n Ok(writer.into_inner())\n\n}\n\n\n", "file_path": "examples/extension.rs", "rank": 81, "score": 279382.56423755095 }, { "content": "/// Creates an random (but fixed-seeded) [`Utf8Array`] of a given length, number of characters and null density.\n\npub fn create_string_array<O: Offset>(\n\n length: usize,\n\n size: usize,\n\n null_density: f32,\n\n seed: u64,\n\n) -> Utf8Array<O> {\n\n let mut rng = StdRng::seed_from_u64(seed);\n\n\n\n (0..length)\n\n .map(|_| {\n\n if rng.gen::<f32>() < null_density {\n\n None\n\n } else {\n\n let value = (&mut rng)\n\n .sample_iter(&Alphanumeric)\n\n .take(size)\n\n .map(char::from)\n\n .collect::<String>();\n\n Some(value)\n\n }\n\n })\n\n .collect()\n\n}\n", "file_path": "src/util/bench_util.rs", "rank": 82, "score": 278380.27534677286 }, { "content": "/// Compares each slot of `lhs` against each slot of `rhs`.\n\n/// # Error\n\n/// Errors iff:\n\n/// * `lhs.data_type() != rhs.data_type()` or\n\n/// * `lhs.len() != rhs.len()` or\n\n/// * the datatype is not supported (use [`can_compare`] to tell whether it is supported)\n\npub fn compare(lhs: &dyn Array, rhs: &dyn Array, operator: Operator) -> Result<BooleanArray> {\n\n let data_type = lhs.data_type();\n\n if data_type != rhs.data_type() {\n\n return Err(ArrowError::InvalidArgumentError(\n\n \"Comparison is only supported for arrays of the same logical type\".to_string(),\n\n ));\n\n }\n\n match data_type {\n\n DataType::Boolean => {\n\n let lhs = lhs.as_any().downcast_ref().unwrap();\n\n let rhs = rhs.as_any().downcast_ref().unwrap();\n\n boolean::compare(lhs, rhs, operator)\n\n }\n\n DataType::Int8 => {\n\n let lhs = lhs.as_any().downcast_ref().unwrap();\n\n let rhs = rhs.as_any().downcast_ref().unwrap();\n\n primitive::compare::<i8>(lhs, rhs, operator)\n\n }\n\n DataType::Int16 => {\n\n let lhs = lhs.as_any().downcast_ref().unwrap();\n", "file_path": "src/compute/comparison/mod.rs", "rank": 83, "score": 278238.8350519674 }, { "content": "pub fn deserialize(mut block: &[u8], rows: usize, schema: Arc<Schema>) -> Result<RecordBatch> {\n\n // create mutables, one per field\n\n let mut arrays: Vec<Box<dyn MutableArray>> = schema\n\n .fields()\n\n .iter()\n\n .map(|field| match field.data_type().to_physical_type() {\n\n PhysicalType::Boolean => {\n\n Ok(Box::new(MutableBooleanArray::with_capacity(rows)) as Box<dyn MutableArray>)\n\n }\n\n PhysicalType::Primitive(primitive) => with_match_primitive_type!(primitive, |$T| {\n\n Ok(Box::new(MutablePrimitiveArray::<$T>::with_capacity(rows)) as Box<dyn MutableArray>)\n\n }),\n\n PhysicalType::Utf8 => {\n\n Ok(Box::new(MutableUtf8Array::<i32>::with_capacity(rows)) as Box<dyn MutableArray>)\n\n }\n\n PhysicalType::Binary => {\n\n Ok(Box::new(MutableBinaryArray::<i32>::with_capacity(rows))\n\n as Box<dyn MutableArray>)\n\n }\n\n other => {\n", "file_path": "src/io/avro/read/deserialize.rs", "rank": 84, "score": 278048.45324542973 }, { "content": "/// Returns a function of index returning the string representation of the _value_ of `array`.\n\n/// This does not take nulls into account.\n\npub fn get_value_display<'a>(array: &'a dyn Array) -> Box<dyn Fn(usize) -> String + 'a> {\n\n use DataType::*;\n\n match array.data_type() {\n\n Null => Box::new(|_: usize| \"\".to_string()),\n\n Boolean => {\n\n let a = array.as_any().downcast_ref::<BooleanArray>().unwrap();\n\n Box::new(move |row: usize| format!(\"{}\", a.value(row)))\n\n }\n\n Int8 => dyn_primitive!(array, i8, |x| x),\n\n Int16 => dyn_primitive!(array, i16, |x| x),\n\n Int32 => dyn_primitive!(array, i32, |x| x),\n\n Int64 => dyn_primitive!(array, i64, |x| x),\n\n UInt8 => dyn_primitive!(array, u8, |x| x),\n\n UInt16 => dyn_primitive!(array, u16, |x| x),\n\n UInt32 => dyn_primitive!(array, u32, |x| x),\n\n UInt64 => dyn_primitive!(array, u64, |x| x),\n\n Float16 => unreachable!(),\n\n Float32 => dyn_primitive!(array, f32, |x| x),\n\n Float64 => dyn_primitive!(array, f64, |x| x),\n\n Date32 => dyn_primitive!(array, i32, temporal_conversions::date32_to_date),\n", "file_path": "src/array/display.rs", "rank": 85, "score": 277327.3287537109 }, { "content": "#[test]\n\nfn i64() -> Result<()> {\n\n let data = Int64Array::from(&[Some(2), None, Some(1), None]);\n\n test_round_trip(data)\n\n}\n\n\n", "file_path": "tests/it/ffi.rs", "rank": 86, "score": 276533.86459375935 }, { "content": "/// Returns the maximum value in the binary array, according to the natural order.\n\npub fn max_binary<O: Offset>(array: &BinaryArray<O>) -> Option<&[u8]> {\n\n min_max_binary(array, |a, b| a < b)\n\n}\n\n\n", "file_path": "src/compute/aggregate/min_max.rs", "rank": 87, "score": 275973.90945737535 }, { "content": "/// Returns the maximum value in the string array, according to the natural order.\n\npub fn max_string<O: Offset>(array: &Utf8Array<O>) -> Option<&str> {\n\n min_max_string(array, |a, b| a < b)\n\n}\n\n\n", "file_path": "src/compute/aggregate/min_max.rs", "rank": 88, "score": 275973.90945737535 }, { "content": "/// Returns the minimum value in the string array, according to the natural order.\n\npub fn min_string<O: Offset>(array: &Utf8Array<O>) -> Option<&str> {\n\n min_max_string(array, |a, b| a > b)\n\n}\n\n\n", "file_path": "src/compute/aggregate/min_max.rs", "rank": 89, "score": 275973.90945737535 }, { "content": "/// Returns the minimum value in the binary array, according to the natural order.\n\npub fn min_binary<O: Offset>(array: &BinaryArray<O>) -> Option<&[u8]> {\n\n min_max_binary(array, |a, b| a > b)\n\n}\n\n\n", "file_path": "src/compute/aggregate/min_max.rs", "rank": 90, "score": 275973.90945737535 }, { "content": "/// Execute an arithmetic operation with two arrays. It uses the enum Operator\n\n/// to select the type of operation that is going to be performed with the two\n\n/// arrays\n\npub fn arithmetic(lhs: &dyn Array, op: Operator, rhs: &dyn Array) -> Result<Box<dyn Array>> {\n\n use DataType::*;\n\n use Operator::*;\n\n match (lhs.data_type(), op, rhs.data_type()) {\n\n (Int8, _, Int8) => primitive!(lhs, rhs, op, i8),\n\n (Int16, _, Int16) => primitive!(lhs, rhs, op, i16),\n\n (Int32, _, Int32) => primitive!(lhs, rhs, op, i32),\n\n (Int64, _, Int64) | (Duration(_), _, Duration(_)) => {\n\n primitive!(lhs, rhs, op, i64)\n\n }\n\n (UInt8, _, UInt8) => primitive!(lhs, rhs, op, u8),\n\n (UInt16, _, UInt16) => primitive!(lhs, rhs, op, u16),\n\n (UInt32, _, UInt32) => primitive!(lhs, rhs, op, u32),\n\n (UInt64, _, UInt64) => primitive!(lhs, rhs, op, u64),\n\n (Float32, _, Float32) => primitive!(lhs, rhs, op, f32),\n\n (Float64, _, Float64) => primitive!(lhs, rhs, op, f64),\n\n (Decimal(_, _), _, Decimal(_, _)) => {\n\n let lhs = lhs.as_any().downcast_ref().unwrap();\n\n let rhs = rhs.as_any().downcast_ref().unwrap();\n\n\n", "file_path": "src/compute/arithmetics/mod.rs", "rank": 91, "score": 274990.85439192597 }, { "content": "/// Returns the [`Array`] limited by `num_elements`.\n\n///\n\n/// Limit performs a zero-copy slice of the array, and is a convenience method on slice\n\n/// where:\n\n/// * it performs a bounds-check on the array\n\n/// * it slices from offset 0\n\npub fn limit(array: &dyn Array, num_elements: usize) -> Box<dyn Array> {\n\n let lim = num_elements.min(array.len());\n\n array.slice(0, lim)\n\n}\n", "file_path": "src/compute/limit.rs", "rank": 92, "score": 274906.57657950895 }, { "content": "pub fn array_to_page<O: Offset>(\n\n array: &Utf8Array<O>,\n\n options: WriteOptions,\n\n descriptor: ColumnDescriptor,\n\n encoding: Encoding,\n\n) -> Result<CompressedDataPage> {\n\n let validity = array.validity();\n\n let is_optional = is_type_nullable(descriptor.type_());\n\n\n\n let mut buffer = vec![];\n\n utils::write_def_levels(\n\n &mut buffer,\n\n is_optional,\n\n validity,\n\n array.len(),\n\n options.version,\n\n )?;\n\n\n\n let definition_levels_byte_length = buffer.len();\n\n\n", "file_path": "src/io/parquet/write/utf8/basic.rs", "rank": 93, "score": 273855.8073646435 }, { "content": "pub fn skip_list<O: Offset>(\n\n field_nodes: &mut VecDeque<Node>,\n\n data_type: &DataType,\n\n buffers: &mut VecDeque<&gen::Schema::Buffer>,\n\n) {\n\n let _ = field_nodes.pop_front().unwrap();\n\n\n\n let _ = buffers.pop_front().unwrap();\n\n let _ = buffers.pop_front().unwrap();\n\n\n\n let data_type = ListArray::<O>::get_child_type(data_type);\n\n\n\n skip(field_nodes, data_type, buffers)\n\n}\n", "file_path": "src/io/ipc/read/array/list.rs", "rank": 94, "score": 273855.8073646435 }, { "content": "pub fn array_to_page<O: Offset>(\n\n array: &BinaryArray<O>,\n\n options: WriteOptions,\n\n descriptor: ColumnDescriptor,\n\n encoding: Encoding,\n\n) -> Result<CompressedDataPage> {\n\n let validity = array.validity();\n\n let is_optional = is_type_nullable(descriptor.type_());\n\n\n\n let mut buffer = vec![];\n\n utils::write_def_levels(\n\n &mut buffer,\n\n is_optional,\n\n validity,\n\n array.len(),\n\n options.version,\n\n )?;\n\n\n\n let definition_levels_byte_length = buffer.len();\n\n\n", "file_path": "src/io/parquet/write/binary/basic.rs", "rank": 95, "score": 273855.8073646435 }, { "content": "/// Cast [`BinaryArray`] to [`DictionaryArray`], also known as packing.\n\n/// # Errors\n\n/// This function errors if the maximum key is smaller than the number of distinct elements\n\n/// in the array.\n\npub fn binary_to_dictionary<O: Offset, K: DictionaryKey>(\n\n from: &BinaryArray<O>,\n\n) -> Result<DictionaryArray<K>> {\n\n let mut array = MutableDictionaryArray::<K, MutableBinaryArray<O>>::new();\n\n array.try_extend(from.iter())?;\n\n\n\n Ok(array.into())\n\n}\n\n\n\npub(super) fn binary_to_dictionary_dyn<O: Offset, K: DictionaryKey>(\n\n from: &dyn Array,\n\n) -> Result<Box<dyn Array>> {\n\n let values = from.as_any().downcast_ref().unwrap();\n\n binary_to_dictionary::<O, K>(values).map(|x| Box::new(x) as Box<dyn Array>)\n\n}\n", "file_path": "src/compute/cast/binary_to.rs", "rank": 96, "score": 273848.09741627134 }, { "content": "/// Cast [`Utf8Array`] to [`DictionaryArray`], also known as packing.\n\n/// # Errors\n\n/// This function errors if the maximum key is smaller than the number of distinct elements\n\n/// in the array.\n\npub fn utf8_to_dictionary<O: Offset, K: DictionaryKey>(\n\n from: &Utf8Array<O>,\n\n) -> Result<DictionaryArray<K>> {\n\n let mut array = MutableDictionaryArray::<K, MutableUtf8Array<O>>::new();\n\n array.try_extend(from.iter())?;\n\n\n\n Ok(array.into())\n\n}\n\n\n\npub(super) fn utf8_to_naive_timestamp_ns_dyn<O: Offset>(\n\n from: &dyn Array,\n\n) -> Result<Box<dyn Array>> {\n\n let from = from.as_any().downcast_ref().unwrap();\n\n Ok(Box::new(utf8_to_naive_timestamp_ns::<O>(from)))\n\n}\n\n\n", "file_path": "src/compute/cast/utf8_to.rs", "rank": 97, "score": 273848.09741627134 }, { "content": "/// Casts a [`DictionaryArray`] to its values' [`DataType`], also known as unpacking.\n\n/// The resulting array has the same length.\n\npub fn dictionary_to_values<K>(from: &DictionaryArray<K>) -> Box<dyn Array>\n\nwhere\n\n K: DictionaryKey,\n\n{\n\n // take requires first casting i64\n\n let indices = primitive_to_primitive::<_, i64>(from.keys(), &DataType::Int64);\n\n\n\n // unwrap: The dictionary guarantees that the keys are not out-of-bounds.\n\n take(from.values().as_ref(), &indices).unwrap()\n\n}\n", "file_path": "src/compute/cast/dictionary_to.rs", "rank": 98, "score": 273139.69433694985 }, { "content": "/// Conversion of timestamp\n\npub fn timestamp_to_date64(from: &PrimitiveArray<i64>, from_unit: TimeUnit) -> PrimitiveArray<i64> {\n\n let from_size = time_unit_multiple(from_unit);\n\n let to_size = MILLISECONDS;\n\n let to_type = DataType::Date64;\n\n\n\n // Scale time_array by (to_size / from_size) using a\n\n // single integer operation, but need to avoid integer\n\n // math rounding down to zero\n\n\n\n match to_size.cmp(&from_size) {\n\n std::cmp::Ordering::Less => unary(from, |x| (x / (from_size / to_size)), to_type),\n\n std::cmp::Ordering::Equal => primitive_to_same_primitive(from, &to_type),\n\n std::cmp::Ordering::Greater => unary(from, |x| (x * (to_size / from_size)), to_type),\n\n }\n\n}\n\n\n", "file_path": "src/compute/cast/primitive_to.rs", "rank": 99, "score": 271967.67969892104 } ]
Rust
flow-rs/src/node/transform.rs
MegEngine/MegFlow
4bbf15acc21fb1f51e95311e28fb0a10fe4a91d3
/** * \file flow-rs/src/node/transform.rs * MegFlow is Licensed under the Apache License, Version 2.0 (the "License") * * Copyright (c) 2019-2021 Megvii Inc. All rights reserved. * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT ARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. */ use crate::rt; use anyhow::Result; use flow_rs::prelude::*; use toml::value::Table; #[inputs(inp)] #[outputs(out)] #[derive(Node, Actor, Default)] struct Transform {} impl Transform { fn new(_name: String, _args: &Table) -> Transform { Default::default() } async fn initialize(&mut self, _: ResourceCollection) {} async fn finalize(&mut self) {} async fn exec(&mut self, _: &Context) -> Result<()> { if let Ok(msg) = self.inp.recv_any().await { self.out.send_any(msg).await.ok(); } Ok(()) } } node_register!("Transform", Transform); #[inputs(inp)] #[outputs(out:dyn)] #[derive(Node, Default)] struct DynOutTransform {} impl DynOutTransform { fn new(_name: String, _args: &Table) -> DynOutTransform { Default::default() } } impl Actor for DynOutTransform { fn start( mut self: Box<Self>, _: Context, _: ResourceCollection, ) -> rt::task::JoinHandle<Result<()>> { let (s, r) = rt::channel::unbounded(); rt::task::spawn(async move { while let Ok((_, out)) = self.out.fetch().await { let inp = self.inp.clone(); s.send(rt::task::spawn(async move { let mut empty_n = 0; loop { while let Ok(msg) = inp.recv_any().await { out.send_any(msg).await.ok(); } if inp.is_closed() { break; } let n = inp.empty_n(); for _ in empty_n..n { out.send_any(DummyEnvelope {}.seal()).await.ok(); } empty_n = n; } })) .await .ok(); } }); rt::task::spawn(async move { while let Ok(handle) = r.recv().await { handle.await; } Ok(()) }) } } node_register!("DynOutTransform", DynOutTransform); #[inputs(inp: dyn)] #[outputs(out)] #[derive(Node, Default)] struct DynInTransform {} impl DynInTransform { fn new(_name: String, _args: &Table) -> DynInTransform { Default::default() } } impl Actor for DynInTransform { fn start( self: Box<Self>, _: Context, _: ResourceCollection, ) -> rt::task::JoinHandle<Result<()>> { let (s, r) = rt::channel::unbounded(); rt::task::spawn(async move { while let Ok((_, inp)) = self.inp.fetch().await { let out = self.out.clone(); s.send(rt::task::spawn(async move { while !inp.is_closed() { while let Ok(msg) = inp.recv_any().await { out.send_any(msg).await.ok(); } assert!( inp.empty_n() == 0, "DynInTransform is not supported in a shared subgraph" ); } })) .await .ok(); } }); rt::task::spawn(async move { while let Ok(handle) = r.recv().await { handle.await; } Ok(()) }) } } node_register!("DynInTransform", DynInTransform);
/** * \file flow-rs/src/node/transform.rs * MegFlow is Licensed under the Apache License, Version 2.0 (the "License") * * Copyright (c) 2019-2021 Megvii Inc. All rights reserved. * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT ARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. */ use crate::rt; use anyhow::Result; use flow_rs::prelude::*; use toml::value::Table; #[inputs(inp)] #[outputs(out)] #[derive(Node, Actor, Default)] struct Transform {} impl Transform { fn new(_name: String, _args: &Table) -> Transform { Default::default() } async fn initialize(&mut self, _: ResourceCollection) {} async fn finalize(&mut self) {}
} node_register!("Transform", Transform); #[inputs(inp)] #[outputs(out:dyn)] #[derive(Node, Default)] struct DynOutTransform {} impl DynOutTransform { fn new(_name: String, _args: &Table) -> DynOutTransform { Default::default() } } impl Actor for DynOutTransform { fn start( mut self: Box<Self>, _: Context, _: ResourceCollection, ) -> rt::task::JoinHandle<Result<()>> { let (s, r) = rt::channel::unbounded(); rt::task::spawn(async move { while let Ok((_, out)) = self.out.fetch().await { let inp = self.inp.clone(); s.send(rt::task::spawn(async move { let mut empty_n = 0; loop { while let Ok(msg) = inp.recv_any().await { out.send_any(msg).await.ok(); } if inp.is_closed() { break; } let n = inp.empty_n(); for _ in empty_n..n { out.send_any(DummyEnvelope {}.seal()).await.ok(); } empty_n = n; } })) .await .ok(); } }); rt::task::spawn(async move { while let Ok(handle) = r.recv().await { handle.await; } Ok(()) }) } } node_register!("DynOutTransform", DynOutTransform); #[inputs(inp: dyn)] #[outputs(out)] #[derive(Node, Default)] struct DynInTransform {} impl DynInTransform { fn new(_name: String, _args: &Table) -> DynInTransform { Default::default() } } impl Actor for DynInTransform { fn start( self: Box<Self>, _: Context, _: ResourceCollection, ) -> rt::task::JoinHandle<Result<()>> { let (s, r) = rt::channel::unbounded(); rt::task::spawn(async move { while let Ok((_, inp)) = self.inp.fetch().await { let out = self.out.clone(); s.send(rt::task::spawn(async move { while !inp.is_closed() { while let Ok(msg) = inp.recv_any().await { out.send_any(msg).await.ok(); } assert!( inp.empty_n() == 0, "DynInTransform is not supported in a shared subgraph" ); } })) .await .ok(); } }); rt::task::spawn(async move { while let Ok(handle) = r.recv().await { handle.await; } Ok(()) }) } } node_register!("DynInTransform", DynInTransform);
async fn exec(&mut self, _: &Context) -> Result<()> { if let Ok(msg) = self.inp.recv_any().await { self.out.send_any(msg).await.ok(); } Ok(()) }
function_block-full_function
[ { "content": "#[pyfunction]\n\nfn version() -> &'static str {\n\n env!(\"CARGO_PKG_VERSION\")\n\n}\n\n\n\n#[pymethods]\n\nimpl Graph {\n\n fn wait(&mut self, py: Python) {\n\n self.inps.clear();\n\n self.outs.clear();\n\n if let Some(graph) = self.graph.take() {\n\n graph.stop();\n\n }\n\n if let Some(handle) = self.handle.take() {\n\n py.allow_threads(|| {\n\n flow_rs::rt::task::block_on(async {\n\n handle.await.unwrap();\n\n });\n\n });\n\n }\n\n }\n", "file_path": "flow-python/src/lib.rs", "rank": 1, "score": 142488.9801800314 }, { "content": "pub fn as_bool(map: &Table, key: &str, default: bool) -> bool {\n\n map.get(key)\n\n .map(|x| {\n\n x.as_bool()\n\n .unwrap_or_else(|| panic!(\"Invalid arguments in field {}\", key))\n\n })\n\n .unwrap_or(default)\n\n}\n\n\n", "file_path": "flow-plugins/src/utils/args_parser.rs", "rank": 2, "score": 142195.78728539334 }, { "content": "fn scan_all_placeholder(project_dir: &Path) -> HashMap<String, String> {\n\n let mut map = HashMap::new();\n\n let files = WalkDir::new(project_dir)\n\n .sort_by_file_name()\n\n .contents_first(true)\n\n .into_iter()\n\n .filter_map(Result::ok)\n\n .filter(|e| !is_git_metadata(e))\n\n .filter(|e| !e.path().is_dir())\n\n .filter(|e| e.path() != project_dir)\n\n .collect::<Vec<_>>();\n\n\n\n // match something like ##INP##\n\n let re = Regex::new(r\"##[_\\-a-zA-Z0-9]*##\").unwrap();\n\n for entry in files {\n\n let file = std::fs::File::open(&entry.path()).unwrap();\n\n let reader = BufReader::new(file);\n\n // Read the file line by line using the lines() iterator from std::io::BufRead.\n\n for (_, line) in reader.lines().enumerate() {\n\n for cap in re.captures_iter(&line.unwrap()) {\n", "file_path": "flow-quickstart/src/main.rs", "rank": 3, "score": 140526.09176199685 }, { "content": "pub fn as_integer<T>(map: &Table, key: &str, default: T) -> T\n\nwhere\n\n T: 'static + Copy,\n\n i64: AsPrimitive<T>,\n\n{\n\n map.get(key)\n\n .map(|x| {\n\n x.as_integer()\n\n .unwrap_or_else(|| panic!(\"Invalid arguments in field {}\", key))\n\n .as_()\n\n })\n\n .unwrap_or(default)\n\n}\n\n\n", "file_path": "flow-plugins/src/utils/args_parser.rs", "rank": 4, "score": 137927.91227057762 }, { "content": "pub fn as_str<'a>(map: &'a Table, key: &str, default: &'a str) -> &'a str {\n\n map.get(key)\n\n .map(|x| {\n\n x.as_str()\n\n .unwrap_or_else(|| panic!(\"Invalid arguments in field {}\", key))\n\n })\n\n .unwrap_or(default)\n\n}\n\n\n", "file_path": "flow-plugins/src/utils/args_parser.rs", "rank": 5, "score": 134918.81635976495 }, { "content": "fn dump_dot(config: &Config) -> String {\n\n let mut buf = vec![];\n\n let mut rename = HashMap::new();\n\n let mut flatten_ports = HashMap::new();\n\n let mut dc = 0;\n\n let mut nc = 0;\n\n let mut mapping = |name| {\n\n let id = rename.entry(name).or_insert(nc);\n\n if id == &nc {\n\n nc += 1;\n\n }\n\n *id\n\n };\n\n let is_graph = |name: &str| config.graphs.iter().any(|x| x.name == name);\n\n // flatten subgraph i/o ports\n\n for graph in &config.graphs {\n\n for pname in graph.inputs.iter().chain(graph.outputs.iter()) {\n\n let conn = graph.connections.get(pname).unwrap();\n\n flatten_ports.insert(\n\n format!(\"{}:{}\", graph.name, pname),\n", "file_path": "flow-rs/src/config/graphviz.rs", "rank": 8, "score": 131307.9035784499 }, { "content": "/// prevents from long stupid paths, and replace the home path by the literal `$HOME`\n\nfn pretty_path(a: &Path) -> Result<String> {\n\n #[cfg(unix)]\n\n let home_var = \"$HOME\";\n\n #[cfg(windows)]\n\n let home_var = \"%userprofile%\";\n\n Ok(a.display()\n\n .to_string()\n\n .replace(&home()?.display().to_string(), home_var))\n\n}\n\n\n", "file_path": "flow-quickstart/src/git.rs", "rank": 9, "score": 128724.7752789045 }, { "content": "fn copy_dir_all(src: impl AsRef<Path>, dst: impl AsRef<Path>) -> Result<()> {\n\n fn check_dir_all(src: impl AsRef<Path>, dst: impl AsRef<Path>) -> Result<()> {\n\n if !dst.as_ref().exists() {\n\n return Ok(());\n\n }\n\n\n\n for src_entry in fs::read_dir(src)? {\n\n let src_entry = src_entry?;\n\n let dst_path = dst.as_ref().join(src_entry.file_name());\n\n let entry_type = src_entry.file_type()?;\n\n\n\n if entry_type.is_dir() {\n\n check_dir_all(src_entry.path(), dst_path)?;\n\n } else if entry_type.is_file() {\n\n if dst_path.exists() {\n\n warn!(\n\n \"{} {}\",\n\n style(\"File already exists:\").bold().red(),\n\n style(dst_path.display()).bold().red(),\n\n )\n", "file_path": "flow-quickstart/src/git.rs", "rank": 10, "score": 126355.83679106092 }, { "content": "/// thanks to @extrawurst for pointing this out\n\n/// <https://github.com/extrawurst/gitui/blob/master/asyncgit/src/sync/branch/mod.rs#L38>\n\nfn get_branch_name_repo(repo: &Repository) -> Result<String> {\n\n let iter = repo.branches(None)?;\n\n\n\n for b in iter {\n\n let b = b?;\n\n\n\n if b.0.is_head() {\n\n let name = b.0.name()?.unwrap_or(\"\");\n\n return Ok(name.into());\n\n }\n\n }\n\n\n\n anyhow::bail!(\"A repo has no Head\")\n\n}\n\n\n", "file_path": "flow-quickstart/src/git.rs", "rank": 11, "score": 123462.67170457442 }, { "content": "#[pymodule]\n\nfn megflow(_py: Python, m: &PyModule) -> PyResult<()> {\n\n m.add_class::<Graph>()?;\n\n m.add_function(wrap_pyfunction!(version, m)?)?;\n\n utils_register(m)?;\n\n envelope_register(m)?;\n\n Ok(())\n\n}\n", "file_path": "flow-python/src/lib.rs", "rank": 12, "score": 120916.71346387896 }, { "content": "pub fn ident(lit: impl AsRef<str>) -> Ident {\n\n Ident::new(lit.as_ref(), Span::call_site())\n\n}\n", "file_path": "flow-derive/src/lit.rs", "rank": 13, "score": 118249.03483140079 }, { "content": "pub fn string<T: Display>(lit: T) -> LitStr {\n\n LitStr::new(lit.to_string().as_str(), Span::call_site())\n\n}\n\n\n", "file_path": "flow-derive/src/lit.rs", "rank": 14, "score": 116526.43046173186 }, { "content": "pub fn merge_table(base: Table, mut patch: Table) -> Table {\n\n for (k, v) in base.into_iter() {\n\n match try_table(v) {\n\n Ok(table) => {\n\n if let Some(patch_value) = patch.remove(&k) {\n\n match try_table(patch_value) {\n\n Ok(patch_table) => {\n\n patch.insert(k, Value::Table(merge_table(table, patch_table)));\n\n }\n\n Err(patch_value) => {\n\n patch.insert(k, patch_value);\n\n }\n\n }\n\n } else {\n\n patch.insert(k, Value::Table(table));\n\n }\n\n }\n\n Err(value) => {\n\n let entry = patch.entry(k);\n\n entry.or_insert(value);\n\n }\n\n }\n\n }\n\n patch\n\n}\n\n\n", "file_path": "flow-rs/src/config/table.rs", "rank": 15, "score": 114168.80912927905 }, { "content": "pub fn substitute_file_by_placeholder(\n\n dir: &str,\n\n filename: &str,\n\n from: &str,\n\n to: &str,\n\n) -> Result<Action, &'static str> {\n\n let pp = Path::new(dir).join(filename);\n\n if !pp.exists() {\n\n error!(\n\n \"critical file {} not exists in the template branch\",\n\n filename\n\n );\n\n\n\n return Ok(Action::Quit);\n\n }\n\n\n\n let mut contents: Vec<String> = Vec::new();\n\n\n\n {\n\n let fromfile = std::fs::File::open(&pp).unwrap();\n", "file_path": "flow-quickstart/src/lib.rs", "rank": 16, "score": 114119.75112545633 }, { "content": "fn global_res_impl<'a>(\n\n name: String,\n\n cfg: &'a mut interlayer::Config,\n\n global: &[String],\n\n visit: &mut HashMap<String, bool>,\n\n) -> Vec<String> {\n\n let graph = cfg.graphs.iter().find(|graph| graph.name == name).unwrap();\n\n if visit[&graph.name] {\n\n return graph.global_res.clone();\n\n }\n\n *visit.get_mut(&graph.name).unwrap() = true;\n\n\n\n let mut capture = BTreeSet::new();\n\n let mut tmp_mapping = HashMap::new();\n\n\n\n for node in graph.nodes.values() {\n\n for ty in &node.entity.ty {\n\n if !visit.contains_key(ty) {\n\n node.res\n\n .iter()\n", "file_path": "flow-rs/src/config/insert.rs", "rank": 17, "score": 114093.74568148071 }, { "content": "fn try_table(value: Value) -> Result<Table, Value> {\n\n match value {\n\n Value::Table(table) => Ok(table),\n\n _ => Err(value),\n\n }\n\n}\n\n\n\n#[cfg(test)]\n\nmod test {\n\n use super::*;\n\n use toml::toml;\n\n\n\n fn table(value: Value) -> Table {\n\n match value {\n\n Value::Table(table) => table,\n\n _ => unreachable!(),\n\n }\n\n }\n\n\n\n #[test]\n", "file_path": "flow-rs/src/config/table.rs", "rank": 18, "score": 114074.75462813796 }, { "content": "fn git_clone_all(project_dir: &Path, args: GitConfig) -> Result<String> {\n\n let mut builder = RepoBuilder::new();\n\n if let GitReference::Branch(branch_name) = &args.branch {\n\n builder.branch(branch_name.as_str());\n\n }\n\n\n\n let mut fo = FetchOptions::new();\n\n match args.kind {\n\n RepoKind::LocalFolder => {}\n\n RepoKind::RemoteHttp | RepoKind::RemoteHttps => {\n\n let mut proxy = ProxyOptions::new();\n\n proxy.auto();\n\n fo.proxy_options(proxy);\n\n }\n\n RepoKind::RemoteSsh => {\n\n let callbacks = git_ssh_credentials_callback(args.identity)?;\n\n fo.remote_callbacks(callbacks);\n\n }\n\n RepoKind::Invalid => {\n\n unreachable!()\n", "file_path": "flow-quickstart/src/git.rs", "rank": 19, "score": 113385.44745592913 }, { "content": "fn path_to_module(root: &Path, path: &Path) -> Result<String> {\n\n let abs_root = std::fs::canonicalize(root)?;\n\n let abs_path = std::fs::canonicalize(path)?;\n\n\n\n if abs_path.starts_with(&abs_root) && abs_path != abs_root {\n\n let relative = abs_path.strip_prefix(&abs_root)?;\n\n let relative = relative.to_str().unwrap().to_owned();\n\n if relative.ends_with(\".py\") {\n\n Ok(relative[..relative.len() - 3].replace(\"/\", \".\"))\n\n } else if relative.ends_with('/') {\n\n Ok(relative[..relative.len() - 1].replace(\"/\", \".\"))\n\n } else {\n\n Ok(relative.replace(\"/\", \".\"))\n\n }\n\n } else {\n\n Err(anyhow::anyhow!(\"module not found\"))\n\n }\n\n}\n\n\n\n#[cfg(test)]\n", "file_path": "flow-rs/src/loader/python/mod.rs", "rank": 20, "score": 113385.44745592913 }, { "content": "/// determines what kind of repository we got\n\nfn determine_repo_kind(remote_url: &str) -> RepoKind {\n\n if remote_url.starts_with(\"git@\") {\n\n RepoKind::RemoteSsh\n\n } else if remote_url.starts_with(\"http://\") {\n\n RepoKind::RemoteHttp\n\n } else if remote_url.starts_with(\"https://\") {\n\n RepoKind::RemoteHttps\n\n } else if Path::new(remote_url).exists() {\n\n RepoKind::LocalFolder\n\n } else {\n\n RepoKind::Invalid\n\n }\n\n}\n\n\n\n#[cfg(test)]\n\nmod tests {\n\n use super::*;\n\n use std::env::current_dir;\n\n use url::Url;\n\n\n", "file_path": "flow-quickstart/src/git.rs", "rank": 21, "score": 112599.95965670224 }, { "content": "def transform(image, target_shape=(960, 960)):\n\n image_height, image_width, _ = image.shape\n\n ratio_h = target_shape[1] * 1.0 / image_height\n\n ratio_w = target_shape[0] * 1.0 / image_width\n\n image = cv2.resize(image, target_shape)\n", "file_path": "flow-python/examples/application/warehouse/detection_memd/onnx_model.py", "rank": 22, "score": 112115.23751377975 }, { "content": "pub fn create(project_dir: &Path, config: GitConfig) -> Result<String> {\n\n info!(\"fetching remote template, please wait...\");\n\n let branch = git_clone_all(project_dir, config)?;\n\n remove_history(project_dir, None)?;\n\n Ok(branch)\n\n}\n\n\n", "file_path": "flow-quickstart/src/git.rs", "rank": 23, "score": 110612.73243407588 }, { "content": "pub fn expand(input: DeriveInput) -> TokenStream {\n\n let ident = input.ident;\n\n let is_local = attr(&input.attrs, \"local\").is_some();\n\n let spawn_func = if is_local {\n\n lit::ident(\"spawn_local\")\n\n } else {\n\n lit::ident(\"spawn\")\n\n };\n\n\n\n fn send_empty_f((_, ident, ty): ExtractParams) -> TokenStream {\n\n if match_last_ty(ty, \"Vec\") {\n\n quote_spanned! {ident.span()=>\n\n for chan in &self.#ident {\n\n chan.send_any(flow_rs::envelope::DummyEnvelope{}.seal()).await.ok();\n\n }\n\n }\n\n } else if match_last_ty(ty, \"HashMap\") {\n\n quote_spanned! {ident.span()=>\n\n for chan in self.#ident.values() {\n\n chan.send_any(flow_rs::envelope::DummyEnvelope{}.seal()).await.ok();\n", "file_path": "flow-derive/src/actor.rs", "rank": 24, "score": 100534.97948774342 }, { "content": "#[proc_macro_derive(Actor, attributes(local))]\n\npub fn actor_derive(input: TokenStream) -> TokenStream {\n\n let input = parse_macro_input!(input as DeriveInput);\n\n actor::expand(input).into()\n\n}\n\n\n", "file_path": "flow-derive/src/lib.rs", "rank": 25, "score": 98864.99977789595 }, { "content": "fn write_branch_name(s: &str) -> Result<Action, &'static str> {\n\n CONTEXT.lock().unwrap().custom_branch = s.to_string();\n\n Ok(Action::Next)\n\n}\n\n\n", "file_path": "flow-quickstart/src/main.rs", "rank": 26, "score": 95524.93442783598 }, { "content": "fn from_data(py: Python, data: impl std::ops::Deref<Target = data::Data>) -> PyResult<PyObject> {\n\n match data.ty() {\n\n data::DataType::Value(data::ValueType::Int) => {\n\n let value: i64 = data::Get::get(&*data);\n\n Ok(value.to_object(py))\n\n }\n\n data::DataType::Value(data::ValueType::Float) => {\n\n let value: f64 = data::Get::get(&*data);\n\n Ok(value.to_object(py))\n\n }\n\n data::DataType::Value(data::ValueType::Bool) => {\n\n let value: bool = data::Get::get(&*data);\n\n Ok(value.to_object(py))\n\n }\n\n data::DataType::Value(data::ValueType::Byte) => {\n\n let value: u8 = data::Get::get(&*data);\n\n Ok(value.to_object(py))\n\n }\n\n data::DataType::Collection(data::CollectionType::List(_)) => {\n\n let list = data.clone();\n", "file_path": "flow-message/src/cross/python/mod.rs", "rank": 27, "score": 91763.3196468176 }, { "content": "pub fn add_field(item: &mut ItemStruct, field: TokenStream) -> Result<()> {\n\n match item.fields {\n\n Fields::Named(ref mut fields) => fields.named.push(Field::parse_named.parse2(field)?),\n\n Fields::Unnamed(ref mut fields) => fields.unnamed.push(Field::parse_unnamed.parse2(field)?),\n\n _ => unreachable!(),\n\n }\n\n Ok(())\n\n}\n\n\n\npub type ExtractParams<'a> = (&'a Ident, &'a Option<Ident>, &'a Type);\n\n\n", "file_path": "flow-derive/src/utils.rs", "rank": 28, "score": 89345.83530922397 }, { "content": "fn range_impl(start: i64, end: i64, step: i64) -> Vec<i64> {\n\n (start..end).step_by(step as usize).collect()\n\n}\n\n\n", "file_path": "flow-rs/src/config/parser.rs", "rank": 29, "score": 88323.65634832259 }, { "content": "pub fn as_list<'a>(map: &'a Table, key: &str) -> Vec<&'a Value> {\n\n map.get(key)\n\n .map(|x| {\n\n x.as_array()\n\n .unwrap_or_else(|| panic!(\"Invalid arguments in field {}\", key))\n\n .iter()\n\n .collect()\n\n })\n\n .unwrap_or_default()\n\n}\n", "file_path": "flow-plugins/src/utils/args_parser.rs", "rank": 30, "score": 87789.03627583706 }, { "content": "fn load_impl(local_key: u64, config: config::presentation::Config) -> Result<graph::MainGraph> {\n\n // register subgraph info\n\n for cfg in &config.graphs {\n\n let info = NodeInfo {\n\n inputs: cfg.inputs.iter().map(|conn| conn.name.clone()).collect(),\n\n outputs: cfg.outputs.iter().map(|conn| conn.name.clone()).collect(),\n\n };\n\n graph::GraphSlice::registry_local().get(local_key).insert(\n\n cfg.name.clone(),\n\n graph::GraphSlice {\n\n cons: Box::new(move |_, _| Err(anyhow!(\"graph is not loaded\"))),\n\n info,\n\n },\n\n );\n\n }\n\n let global_nodes_keys: Vec<_> = config\n\n .nodes\n\n .iter()\n\n .map(|n| &n.entity.name)\n\n .cloned()\n", "file_path": "flow-rs/src/lib.rs", "rank": 31, "score": 84495.12192515872 }, { "content": "#[inputs(inp)]\n\n#[outputs(out)]\n\n#[derive(Node, Actor)]\n\nstruct Transport {\n\n _name: String,\n\n}\n\n\n\nimpl Transport {\n\n fn new(name: String, _: &toml::value::Table) -> Transport {\n\n Transport {\n\n _name: name,\n\n inp: Default::default(),\n\n out: Default::default(),\n\n }\n\n }\n\n\n\n async fn initialize(&mut self, _: ResourceCollection) {}\n\n async fn finalize(&mut self) {}\n\n\n\n async fn exec(&mut self, _: &Context) -> Result<()> {\n\n if let Ok(envelope) = self.inp.recv::<u32>().await {\n\n self.out.send(envelope).await.ok();\n\n }\n", "file_path": "flow-rs/examples/graph.rs", "rank": 32, "score": 80917.0817491639 }, { "content": "struct Port {\n\n name: syn::Ident,\n\n ty: PortType,\n\n}\n\n\n\nimpl Parse for Port {\n\n fn parse(input: ParseStream) -> Result<Self> {\n\n let name: syn::Ident = input.parse()?;\n\n Ok(if input.peek(Token![:]) {\n\n input.parse::<Token![:]>()?;\n\n if input.peek(syn::token::Dyn) {\n\n input.parse::<syn::token::Dyn>()?;\n\n Port {\n\n name,\n\n ty: PortType::Dyn,\n\n }\n\n } else if input.peek(syn::token::Bracket) {\n\n let _content;\n\n bracketed!(_content in input);\n\n Port {\n", "file_path": "flow-derive/src/ports.rs", "rank": 33, "score": 80912.38253559664 }, { "content": "pub fn toml2dict<'a>(py: Python<'a>, args: &toml::value::Table) -> PyResult<&'a PyDict> {\n\n fn append_list(py: Python, value: &toml::Value, list: &PyList) -> PyResult<()> {\n\n match value {\n\n toml::Value::String(s) => list.append(s),\n\n toml::Value::Float(f) => list.append(f),\n\n toml::Value::Integer(i) => list.append(i),\n\n toml::Value::Boolean(b) => list.append(b),\n\n toml::Value::Datetime(t) => list.append(t.to_string()),\n\n toml::Value::Array(l) => {\n\n let pylist = PyList::empty(py);\n\n for e in l {\n\n append_list(py, e, pylist)?;\n\n }\n\n list.append(pylist)\n\n }\n\n toml::Value::Table(d) => {\n\n let pydict = PyDict::new(py);\n\n for (key, value) in d {\n\n fill_dict(py, key, value, pydict)?;\n\n }\n", "file_path": "flow-rs/src/loader/python/node.rs", "rank": 34, "score": 80643.01933659567 }, { "content": "fn main() {\n\n let matches = App::new(\"megflow_quickstart\")\n\n .version(\"1.0.0\")\n\n .author(\"megengine <[email protected]>\")\n\n .about(\"interactive construct pipeline, for github user just type `megflow_quickstart`.\")\n\n .arg(\n\n Arg::new(\"GIT\")\n\n .short('g')\n\n .long(\"git\")\n\n .value_name(\"GIT\")\n\n .about(\"User-defined git repo, use https://github.com/MegEngine/MegFlow.git by default\")\n\n .multiple_occurrences(false)\n\n .required(false),\n\n )\n\n .get_matches();\n\n\n\n if let Some(repo) = matches.value_of(\"GIT\") {\n\n CONTEXT.lock().unwrap().git_repo = repo.to_owned();\n\n } else {\n\n CONTEXT.lock().unwrap().git_repo = \"https://github.com/MegEngine/MegFlow.git\".to_owned();\n\n }\n\n\n\n println!(\"{}\", style(\"Welcome to MegFlow quickstart utility.\").bold());\n\n println!(\"{}\", style(\"Please enter values for the following settings (just press Enter to accept a default value, if one is given in brackets).\").bold());\n\n\n\n let commands: Vec<Node<'static>> = start();\n\n exec(&commands);\n\n info!(\"Project created, read ${{PROJECT_dir}}/README.md to run it.\");\n\n}\n", "file_path": "flow-quickstart/src/main.rs", "rank": 35, "score": 79866.63245478194 }, { "content": "#[test]\n\nfn should_canonicalize() {\n\n #[cfg(target_os = \"macos\")]\n\n assert!(canonicalize_path(&PathBuf::from(\"../\"))\n\n .unwrap()\n\n .starts_with(\"/Users/\"));\n\n #[cfg(target_os = \"linux\")]\n\n assert_eq!(\n\n canonicalize_path(&PathBuf::from(\"../\")).ok(),\n\n std::env::current_dir()\n\n .unwrap()\n\n .parent()\n\n .map(|p| p.to_path_buf())\n\n );\n\n #[cfg(windows)]\n\n assert!(canonicalize_path(&PathBuf::from(\"../\"))\n\n .unwrap()\n\n // not a bug, a feature:\n\n // https://stackoverflow.com/questions/41233684/why-does-my-canonicalized-path-get-prefixed-with\n\n .to_str()\n\n .unwrap()\n\n .starts_with(\"\\\\\\\\?\\\\\"));\n\n}\n\n\n", "file_path": "flow-quickstart/src/git.rs", "rank": 36, "score": 79866.63245478194 }, { "content": "#[inputs]\n\n#[outputs]\n\n#[derive(Node, Actor, Default)]\n\nstruct Isolated {}\n\n\n\nimpl Isolated {\n\n fn new(_name: String, _: &Table) -> Self {\n\n Default::default()\n\n }\n\n\n\n async fn initialize(&mut self, _: ResourceCollection) {}\n\n async fn finalize(&mut self) {}\n\n async fn exec(&mut self, _: &Context) -> Result<()> {\n\n Ok(())\n\n }\n\n}\n\n\n\nnode_register!(\"Isolated\", Isolated);\n\n\n", "file_path": "flow-rs/tests/nodes_ext.rs", "rank": 37, "score": 79806.380931399 }, { "content": "#[inputs(inp)]\n\n#[outputs(out:[])]\n\n#[derive(Node, Actor, Default)]\n\nstruct Bcast {}\n\n\n\nimpl Bcast {\n\n fn new(_: String, _: &Table) -> Bcast {\n\n Default::default()\n\n }\n\n\n\n async fn initialize(&mut self, _: ResourceCollection) {}\n\n async fn finalize(&mut self) {}\n\n\n\n async fn exec(&mut self, _: &Context) -> Result<()> {\n\n if let Ok(msg) = self.inp.recv_any().await {\n\n for out in &self.out[0..self.out.len() - 1] {\n\n let msg_cloned = msg.clone();\n\n out.send_any(msg_cloned).await.ok();\n\n }\n\n if let Some(out) = self.out.last() {\n\n out.send_any(msg).await.ok();\n\n }\n\n }\n", "file_path": "flow-rs/src/node/bcast.rs", "rank": 38, "score": 79806.30269876996 }, { "content": "#[inputs(inp)]\n\n#[outputs(out)]\n\n#[derive(Node, Actor, Default)]\n\nstruct Reorder {\n\n cache: BTreeMap<u64, SealedEnvelope>,\n\n seq_id: u64,\n\n}\n\n\n\nimpl Reorder {\n\n fn new(_: String, _: &Table) -> Reorder {\n\n Default::default()\n\n }\n\n\n\n async fn initialize(&mut self, _: ResourceCollection) {}\n\n async fn finalize(&mut self) {}\n\n\n\n async fn exec(&mut self, _: &Context) -> Result<()> {\n\n if let Ok(msg) = self.inp.recv_any().await {\n\n let id = msg\n\n .info()\n\n .partial_id\n\n .expect(\"partial_id required by reorder\");\n\n assert!(id >= self.seq_id);\n", "file_path": "flow-rs/src/node/reorder.rs", "rank": 39, "score": 79806.30269876996 }, { "content": "#[inputs(inp)]\n\n#[outputs(out:{})]\n\n#[derive(Node, Actor, Default)]\n\nstruct Demux {}\n\n\n\nimpl Demux {\n\n fn new(_: String, _: &Table) -> Demux {\n\n Default::default()\n\n }\n\n\n\n async fn initialize(&mut self, _: ResourceCollection) {}\n\n async fn finalize(&mut self) {}\n\n\n\n async fn exec(&mut self, _: &Context) -> Result<()> {\n\n if let Ok(msg) = self.inp.recv_any().await {\n\n let id = msg\n\n .info()\n\n .to_addr\n\n .expect(\"the envelope has no destination address\");\n\n if let Some(out) = self.out.get(&id) {\n\n out.send_any(msg).await.ok();\n\n }\n\n }\n", "file_path": "flow-rs/src/node/demux.rs", "rank": 40, "score": 79806.30269876996 }, { "content": "#[derive(Clone)]\n\nstruct State {\n\n mapping: Arc<Mutex<HashMap<u64, (VideoDescp, Sender)>>>,\n\n sender: flow_rs::rt::channel::Sender<(u64, String, oneshot::Sender<RwebResult>)>,\n\n counter: Arc<AtomicU64>,\n\n}\n\n\n", "file_path": "flow-plugins/src/video_server.rs", "rank": 41, "score": 79797.02597772182 }, { "content": "#[derive(Clone)]\n\nstruct State {\n\n ty: RespTy,\n\n mapping: Arc<Mutex<Mapping>>,\n\n out: Sender,\n\n counter: Arc<AtomicU64>,\n\n}\n\n\n\n#[post(\"/analyze/{extra_data}\")]\n\n#[openapi(summary = \"analyze an image\")]\n\nasync fn analyze(\n\n #[data] state: State,\n\n img: Image,\n\n extra_data: String,\n\n) -> Result<Either<Image, impl Reply>, Rejection> {\n\n let img = img.into_bgr8();\n\n let id = state.id();\n\n\n\n let pyobject: PyObject = Python::with_gil(|py| -> PyResult<_> {\n\n let data = img.as_raw();\n\n let ndarray =\n", "file_path": "flow-plugins/src/image_server.rs", "rank": 42, "score": 79797.02597772182 }, { "content": "struct Shared {\n\n nodes: Vec<Box<dyn Actor>>,\n\n rx: ReceiverT<SharedConns>,\n\n inputs: HashMap<String, Arc<Sender>>,\n\n outputs: HashMap<String, Receiver>,\n\n}\n\n\n\npub struct SharedHandle(pub rt::task::JoinHandle<Result<()>>);\n\n// is safe because we visit it only in single thread\n\nunsafe impl Sync for SharedHandle {}\n\ncrate::collect!(String, SharedHandle);\n\n\n\n#[derive(Clone)]\n\npub struct SharedProxy {\n\n conns: SharedConns,\n\n tx: SenderT<SharedConns>,\n\n inputs: Vec<String>,\n\n outputs: Vec<String>,\n\n}\n\n\n", "file_path": "flow-rs/src/node/shared.rs", "rank": 43, "score": 79797.02597772182 }, { "content": "struct Messages {\n\n mapping: HashMap<u64, Vec<String>>,\n\n}\n\n\n", "file_path": "flow-plugins/src/video_server.rs", "rank": 44, "score": 79797.02597772182 }, { "content": "#[derive(Clone)]\n\nstruct State {\n\n mapping: Arc<Mutex<Mapping>>,\n\n out: Sender,\n\n counter: Arc<AtomicU64>,\n\n}\n\n\n\n#[post(\"/analyze/bytes\")]\n\n#[openapi(summary = \"analyze user define bytes\")]\n\nasync fn analyze(#[data] state: State, #[body] body: Bytes) -> Result<impl Reply, Rejection> {\n\n let id = state.id();\n\n\n\n let pyobject: PyObject = Python::with_gil(|py| -> PyResult<_> {\n\n let ndarray = body.to_pyarray(py);\n\n\n\n Ok([(\"data\", ndarray.to_object(py))].into_py_dict(py).into())\n\n })\n\n .map_err(reject_cause)?;\n\n\n\n let r = {\n\n let (s, r) = oneshot::channel();\n", "file_path": "flow-plugins/src/bytes_server.rs", "rank": 45, "score": 79797.02597772182 }, { "content": "fn ports_expand(\n\n prefix: &str,\n\n mut item_struct: ItemStruct,\n\n fields: Vec<proc_macro2::TokenStream>,\n\n names: Vec<syn::LitStr>,\n\n) -> proc_macro2::TokenStream {\n\n for field in fields {\n\n utils::add_field(&mut item_struct, field).unwrap();\n\n }\n\n let ident = &item_struct.ident;\n\n let func_ident = lit::ident(format!(\"{}_name\", prefix));\n\n let (imp_g, ty_g, where_g) = item_struct.generics.split_for_impl();\n\n quote! {\n\n #item_struct\n\n impl#imp_g #ident#ty_g #where_g {\n\n fn #func_ident() -> Vec<String> {\n\n vec![#(#names),*].into_iter().map(|n: &str| n.to_owned()).collect()\n\n }\n\n }\n\n }\n\n}\n", "file_path": "flow-derive/src/lib.rs", "rank": 46, "score": 78760.28490529003 }, { "content": "fn main() {}\n", "file_path": "flow-derive/examples/node_derive.rs", "rank": 47, "score": 78760.28490529003 }, { "content": "#[inputs]\n\n#[outputs(out)]\n\n#[derive(Node, Actor, Default)]\n\nstruct NoopProducer {}\n\n\n\nimpl NoopProducer {\n\n fn new(_name: String, _args: &Table) -> NoopProducer {\n\n Default::default()\n\n }\n\n\n\n async fn initialize(&mut self, _: ResourceCollection) {}\n\n async fn finalize(&mut self) {}\n\n async fn exec(&mut self, _: &Context) -> Result<()> {\n\n Ok(())\n\n }\n\n}\n\n\n\nnode_register!(\"NoopProducer\", NoopProducer);\n\n\n", "file_path": "flow-rs/src/node/noop.rs", "rank": 48, "score": 78745.72196973584 }, { "content": "#[inputs(a, b)]\n\n#[outputs(c)]\n\n#[derive(Node, Actor, Default)]\n\nstruct BinaryOpr {}\n\n\n\nimpl BinaryOpr {\n\n fn new(_name: String, _args: &Table) -> BinaryOpr {\n\n Default::default()\n\n }\n\n\n\n async fn initialize(&mut self, _: ResourceCollection) {}\n\n async fn finalize(&mut self) {}\n\n async fn exec(&mut self, _: &Context) -> Result<()> {\n\n let mut recv_a = FuturesUnordered::new();\n\n recv_a.push(self.a.recv_any());\n\n let mut recv_b = FuturesUnordered::new();\n\n recv_b.push(self.b.recv_any());\n\n loop {\n\n select! {\n\n a = recv_a.select_next_some() => {\n\n if let Ok(a) = a {\n\n self.c.send_any(a).await.ok();\n\n recv_a.push(self.a.recv_any());\n", "file_path": "flow-rs/tests/nodes_ext.rs", "rank": 49, "score": 78745.72196973584 }, { "content": "#[inputs]\n\n#[outputs]\n\n#[derive(Node, Actor, Default)]\n\nstruct IsolatedNever {}\n\n\n\nimpl IsolatedNever {\n\n fn new(_name: String, _: &Table) -> Self {\n\n Default::default()\n\n }\n\n\n\n async fn initialize(&mut self, _: ResourceCollection) {}\n\n async fn finalize(&mut self) {}\n\n async fn exec(&mut self, ctx: &Context) -> Result<()> {\n\n ctx.wait().await;\n\n Ok(())\n\n }\n\n}\n\n\n\nnode_register!(\"IsolatedNever\", IsolatedNever);\n", "file_path": "flow-rs/tests/nodes_ext.rs", "rank": 50, "score": 78745.72196973584 }, { "content": "#[inputs]\n\n#[outputs(out)]\n\n#[derive(Node, Actor, Default)]\n\nstruct NeverOpr {}\n\n\n\nimpl NeverOpr {\n\n fn new(_name: String, _: &Table) -> NeverOpr {\n\n Default::default()\n\n }\n\n\n\n async fn initialize(&mut self, _: ResourceCollection) {}\n\n async fn finalize(&mut self) {}\n\n async fn exec(&mut self, ctx: &Context) -> Result<()> {\n\n ctx.wait().await;\n\n Ok(())\n\n }\n\n}\n\n\n\nnode_register!(\"NeverOpr\", NeverOpr);\n\n\n", "file_path": "flow-rs/tests/nodes_ext.rs", "rank": 51, "score": 78745.72196973584 }, { "content": "#[inputs(inp)]\n\n#[outputs(out)]\n\n#[derive(Node, Actor, Default)]\n\nstruct ErrorOpr {}\n\n\n\nimpl ErrorOpr {\n\n fn new(_name: String, _: &Table) -> ErrorOpr {\n\n Default::default()\n\n }\n\n\n\n async fn initialize(&mut self, _: ResourceCollection) {}\n\n async fn finalize(&mut self) {}\n\n async fn exec(&mut self, _: &Context) -> Result<()> {\n\n Err(anyhow::anyhow!(\"error\"))\n\n }\n\n}\n\n\n\nnode_register!(\"ErrorOpr\", ErrorOpr);\n\n\n", "file_path": "flow-rs/tests/nodes_ext.rs", "rank": 52, "score": 78745.6437371068 }, { "content": "#[inputs(inp)]\n\n#[outputs]\n\n#[derive(Node, Actor, Default)]\n\nstruct NoopConsumer {}\n\n\n\nimpl NoopConsumer {\n\n fn new(_name: String, _args: &Table) -> NoopConsumer {\n\n Default::default()\n\n }\n\n\n\n async fn initialize(&mut self, _: ResourceCollection) {}\n\n async fn finalize(&mut self) {}\n\n async fn exec(&mut self, _: &Context) -> Result<()> {\n\n self.inp.recv_any().await.ok();\n\n Ok(())\n\n }\n\n}\n\n\n\nnode_register!(\"NoopConsumer\", NoopConsumer);\n", "file_path": "flow-rs/src/node/noop.rs", "rank": 53, "score": 78745.6437371068 }, { "content": "#[inputs(inp)]\n\n#[outputs(out:dyn)]\n\n#[derive(Node, Actor, Default)]\n\nstruct DynDemux {\n\n tasks: HashMap<u64, JoinHandle<Result<()>>>,\n\n resources: Option<ResourceCollection>,\n\n}\n\n\n\nimpl DynDemux {\n\n fn new(_: String, _: &Table) -> DynDemux {\n\n Default::default()\n\n }\n\n\n\n async fn initialize(&mut self, resources: ResourceCollection) {\n\n self.resources = Some(resources);\n\n }\n\n async fn finalize(&mut self) {\n\n for (_, task) in std::mem::take(&mut self.tasks) {\n\n task.await.ok();\n\n }\n\n }\n\n\n\n async fn exec(&mut self, _: &Context) -> Result<()> {\n", "file_path": "flow-rs/src/node/demux.rs", "rank": 54, "score": 78745.56680209747 }, { "content": "#[inputs(inp:dyn)]\n\n#[outputs(out:dyn)]\n\n#[derive(Node, Actor, Default)]\n\nstruct VideoServer {\n\n port: u16,\n\n resources: Option<ResourceCollection>,\n\n}\n\n\n", "file_path": "flow-plugins/src/video_server.rs", "rank": 55, "score": 78745.49113268859 }, { "content": "#[allow(dead_code)]\n\n#[inputs(first, second:dyn, third:[], fourth:{})]\n\n#[outputs(front, last:dyn)]\n\n#[derive(Node, Actor, Default)]\n\nstruct SubNode {}\n\n\n\nimpl SubNode {\n\n fn new(_: String, _args: &toml::value::Table) -> Self {\n\n SubNode {\n\n ..Default::default()\n\n }\n\n }\n\n\n\n async fn initialize(&mut self, _: ResourceCollection) {}\n\n async fn finalize(&mut self) {}\n\n\n\n async fn exec(&mut self, _: &Context) -> Result<()> {\n\n let _: Envelope<f32> = self.first.recv::<f32>().await.unwrap();\n\n Ok(())\n\n }\n\n}\n\n\n\nnode_register!(\"sub\", SubNode);\n\n\n", "file_path": "flow-derive/examples/node_derive.rs", "rank": 56, "score": 78744.92782289826 }, { "content": "#[inputs(inp)]\n\n#[outputs(out)]\n\n#[derive(Node, Actor)]\n\nstruct ImageServer {\n\n port: u16,\n\n ty: RespTy,\n\n}\n\n\n", "file_path": "flow-plugins/src/image_server.rs", "rank": 57, "score": 78741.06622962594 }, { "content": "#[inputs(inp)]\n\n#[outputs(out)]\n\n#[derive(Node, Actor)]\n\nstruct BytesServer {\n\n port: u16,\n\n}\n\n\n", "file_path": "flow-plugins/src/bytes_server.rs", "rank": 58, "score": 78741.06622962594 }, { "content": "#[inputs(inp)]\n\n#[outputs(out)]\n\n#[derive(Node, Actor)]\n\nstruct ImageInput {\n\n urls: Vec<String>,\n\n}\n\n\n\nimpl ImageInput {\n\n fn new(_: String, args: &Table) -> ImageInput {\n\n ImageInput {\n\n urls: args[\"urls\"]\n\n .as_array()\n\n .expect(\"expect string array for urls\")\n\n .iter()\n\n .map(|n| n.as_str().unwrap().to_owned())\n\n .collect(),\n\n inp: Default::default(),\n\n out: Default::default(),\n\n }\n\n }\n\n\n\n async fn initialize(&mut self, _: ResourceCollection) {}\n\n async fn finalize(&mut self) {}\n", "file_path": "flow-plugins/src/image_input.rs", "rank": 59, "score": 78741.06622962594 }, { "content": "#[inputs(inp:dyn)]\n\n#[outputs(out:dyn)]\n\n#[derive(Node, Default)]\n\nstruct VideoInput {\n\n urls: Vec<String>,\n\n repeat: u32,\n\n}\n\n\n", "file_path": "flow-plugins/src/video_input.rs", "rank": 60, "score": 78740.94553288959 }, { "content": "#[derive(Serialize)]\n\nstruct VideoDescp {\n\n id: u64,\n\n url: String,\n\n}\n\n\n\nimpl VideoInput {\n\n fn new(_: String, args: &Table) -> VideoInput {\n\n VideoInput {\n\n urls: args[\"urls\"]\n\n .as_array()\n\n .expect(\"expect string array for urls\")\n\n .iter()\n\n .map(|n| n.as_str().unwrap().to_owned())\n\n .collect(),\n\n repeat: args[\"repeat\"]\n\n .as_integer()\n\n .expect(\"expect args[repeat] in node[VideoInput]\")\n\n .to_owned() as u32,\n\n ..Default::default()\n\n }\n", "file_path": "flow-plugins/src/video_input.rs", "rank": 61, "score": 78736.36701605868 }, { "content": "#[derive(Serialize)]\n\nstruct VideoDescp {\n\n id: u64,\n\n url: String,\n\n}\n\n\n", "file_path": "flow-plugins/src/video_server.rs", "rank": 62, "score": 78736.36701605868 }, { "content": "struct Context {\n\n thread: *mut ffi::PyThreadState,\n\n ctx: PyThreadStateUnlimited,\n\n}\n\n\n", "file_path": "flow-rs/src/loader/python/context.rs", "rank": 63, "score": 78736.36701605868 }, { "content": "#[derive(Serialize)]\n\nstruct NodeQps {\n\n name: String,\n\n qps: HashMap<String, (usize, usize)>, // size, qps\n\n is_block: bool,\n\n}\n\n\n\nimpl Graph {\n\n pub(super) fn dmon(&self) -> JoinHandle<anyhow::Result<()>> {\n\n let conns: Vec<_> = self.conns.values().cloned().collect();\n\n let ctx = self.ctx.clone();\n\n let mut first = true; // drop qps result fetched first\n\n crate::rt::task::spawn(async move {\n\n let wait_graph = ctx.wait().fuse();\n\n pin_mut!(wait_graph);\n\n 'start: while !ctx.is_closed() {\n\n if !crate::debug::QPS.enable() {\n\n first = true;\n\n }\n\n let wait_qps = crate::debug::QPS.wait().fuse();\n\n pin_mut!(wait_qps);\n", "file_path": "flow-rs/src/graph/debug.rs", "rank": 64, "score": 78736.36701605868 }, { "content": "#[derive(Clone)]\n\nstruct DynConns {\n\n name: u64,\n\n inputs: HashMap<String, Sender>,\n\n outputs: HashMap<String, Receiver>,\n\n}\n\n\n\npub struct DynPortsConfig {\n\n pub(crate) local_key: u64,\n\n pub(crate) target: String,\n\n pub(crate) cap: usize,\n\n pub(crate) brokers: Vec<BrokerClient>,\n\n pub(crate) args: Table,\n\n}\n\n\n\n#[derive(Default)]\n\npub struct DynPorts<V> {\n\n local_key: u64,\n\n target: String,\n\n cap: usize,\n\n brokers: HashMap<String, BrokerClient>,\n", "file_path": "flow-rs/src/node/port.rs", "rank": 65, "score": 78736.36701605868 }, { "content": "#[derive(Clone)]\n\nstruct SharedConns {\n\n inputs: HashMap<String, Receiver>,\n\n outputs: HashMap<String, Sender>,\n\n}\n\n\n", "file_path": "flow-rs/src/node/shared.rs", "rank": 66, "score": 78736.36701605868 }, { "content": "struct PythonLoader;\n\nconst ERR_MSG: &str = \"python plugin parse fault\";\n\n\n\nimpl Loader for PythonLoader {\n\n fn load_from_scope(&self, local_key: u64) -> Result<Vec<Box<dyn Plugin>>> {\n\n pyo3::prepare_freethreaded_python();\n\n let mut plugins = vec![];\n\n Python::with_gil(|py| -> PyResult<()> {\n\n let plugins_param: HashMap<String, Vec<&PyDict>> = py\n\n .import(\"megflow\")?\n\n .getattr(\"collect\")?\n\n .call0()?\n\n .extract()?;\n\n for plugin_param in &plugins_param[\"nodes\"] {\n\n let name: String = plugin_param.get_item(\"name\").expect(ERR_MSG).extract()?;\n\n let inputs: Vec<String> =\n\n plugin_param.get_item(\"inputs\").expect(ERR_MSG).extract()?;\n\n let outputs: Vec<String> =\n\n plugin_param.get_item(\"outputs\").expect(ERR_MSG).extract()?;\n\n let code: PyObject = plugin_param.get_item(\"code\").expect(ERR_MSG).extract()?;\n", "file_path": "flow-rs/src/loader/python/mod.rs", "rank": 67, "score": 77726.47835603074 }, { "content": "struct NodePlugin {\n\n local_key: u64,\n\n params: RegistryNodeParams,\n\n}\n\n\n\nimpl NodePlugin {\n\n fn new(local_key: u64, params: RegistryNodeParams) -> NodePlugin {\n\n NodePlugin { local_key, params }\n\n }\n\n\n\n fn boxed(self) -> Box<dyn Plugin> {\n\n Box::new(self)\n\n }\n\n}\n\n\n\nimpl Plugin for NodePlugin {\n\n fn submit(&self) {\n\n let params = self.params.clone();\n\n crate::node::NodeSlice::registry_local()\n\n .get(self.local_key)\n", "file_path": "flow-rs/src/loader/python/mod.rs", "rank": 68, "score": 77726.47835603074 }, { "content": "#[pyclass(name = \"Waker\")]\n\nstruct PyWaker {\n\n chan: Option<oneshot::Sender<PyObject>>,\n\n}\n\n\n\n#[pymethods]\n\nimpl PyFuture {\n\n fn wait(&mut self, py: Python) -> PyObject {\n\n if let Some(chan) = std::mem::take(&mut self.chan) {\n\n with_context(py, || wait(chan)).unwrap()\n\n } else {\n\n py.None()\n\n }\n\n }\n\n\n\n fn cancel(&mut self) {\n\n self.chan = None;\n\n }\n\n}\n\n\n\n#[pymethods]\n\nimpl PyWaker {\n\n fn wake(&mut self, py: Python, result: PyObject) {\n\n if let Some(chan) = std::mem::take(&mut self.chan) {\n\n let _ = chan.send(result.clone_ref(py)).is_ok();\n\n }\n\n }\n\n}\n\n\n", "file_path": "flow-rs/src/loader/python/utils.rs", "rank": 69, "score": 77726.47835603074 }, { "content": "#[pyclass(name = \"Future\", unsendable)]\n\nstruct PyFuture {\n\n chan: Option<oneshot::Receiver<PyObject>>,\n\n}\n\n\n", "file_path": "flow-rs/src/loader/python/utils.rs", "rank": 70, "score": 77726.47835603074 }, { "content": "struct ContextPool {\n\n pool: Vec<Context>,\n\n freelist: Vec<usize>,\n\n}\n\n\n\nimpl ContextPool {\n\n fn store(&mut self) -> usize {\n\n let id = self.freelist.pop().unwrap_or(self.pool.len());\n\n if id == self.pool.len() {\n\n self.pool.push(Context {\n\n thread: std::ptr::null_mut(),\n\n ctx: Default::default(),\n\n })\n\n }\n\n unsafe {\n\n let context = self.pool.get_unchecked_mut(id);\n\n context.thread = ffi::PyThreadState_Get();\n\n context.ctx = unlimited::store(context.thread);\n\n }\n\n id\n", "file_path": "flow-rs/src/loader/python/context.rs", "rank": 71, "score": 77726.47835603074 }, { "content": "struct ResourcePlugin {\n\n local_key: u64,\n\n name: String,\n\n res: PyObject,\n\n}\n\n\n\nimpl ResourcePlugin {\n\n fn boxed(self) -> Box<dyn Plugin> {\n\n Box::new(self)\n\n }\n\n}\n\n\n\nimpl Resource for PyObject {\n\n fn to_python(&self, py: pyo3::Python) -> pyo3::PyObject {\n\n self.clone_ref(py)\n\n }\n\n}\n\n\n\nimpl Plugin for ResourcePlugin {\n\n fn submit(&self) {\n", "file_path": "flow-rs/src/loader/python/mod.rs", "rank": 72, "score": 77726.47835603074 }, { "content": "fn translate_node(\n\n local_key: u64,\n\n is_shared: bool,\n\n p: presentation::Node,\n\n) -> Result<interlayer::Node> {\n\n let ty = p.entity.ty.split('|').next().unwrap().trim();\n\n let inputs = inputs(local_key, ty)?.into_iter().collect();\n\n let outputs = outputs(local_key, ty)?.into_iter().collect();\n\n Ok(interlayer::Node {\n\n entity: interlayer::Entity {\n\n name: p.entity.name,\n\n ty: p\n\n .entity\n\n .ty\n\n .split('|')\n\n .map(|x| x.trim().to_owned())\n\n .collect(),\n\n args: p.entity.args,\n\n },\n\n res: p.res,\n\n cloned: p.cloned,\n\n inputs,\n\n outputs,\n\n is_dyn: false,\n\n is_shared,\n\n })\n\n}\n\n\n", "file_path": "flow-rs/src/config/mod.rs", "rank": 73, "score": 77708.19314611431 }, { "content": "fn translate_conn(\n\n p: presentation::Connection,\n\n nodes: &mut HashMap<String, interlayer::Node>,\n\n shared_nodes: &mut HashMap<String, interlayer::Node>,\n\n) -> Result<interlayer::Connection> {\n\n let mut rx = vec![];\n\n let mut tx = vec![];\n\n\n\n if p.ports.is_empty() {\n\n return Err(anyhow!(\"encountered an unused connections\"));\n\n }\n\n\n\n for port_s in p.ports {\n\n let ((n, p), tag) = interlayer::Port::parse(port_s.as_str())?;\n\n let mut parse = |node: &mut interlayer::Node| {\n\n let mut find = false;\n\n for utility in MAPPING {\n\n let p = (utility.mapping)(p);\n\n let port = interlayer::Port {\n\n node_type: node.entity.ty.clone(),\n", "file_path": "flow-rs/src/config/mod.rs", "rank": 74, "score": 77708.19314611431 }, { "content": "#[test]\n\n#[should_panic]\n\nfn test_empty() {\n\n let _ = Builder::default()\n\n .template(\n\n r#\"\n\nmain=\"test\"\n\nnodes=[\n\n {name=\"gb\",ty=\"BinaryOpr\"},\n\n {name=\"sub\",ty=\"sub\"}\n\n]\n\n[[graphs]]\n\nname=\"sub\"\n\ninputs=[\n\n {name=\"a\",cap=1,ports=[\"gb:a\"]},\n\n {name=\"b\",cap=1,ports=[\"gb:b\"]}\n\n]\n\noutputs=[{name=\"c\",cap=1,ports=[\"gb:c\"]}]\n\n[[graphs]]\n\nname=\"test\"\n\ninputs=[{name=\"inp\",cap=1,ports=[\"t1:inp\",\"t2:inp\"]}]\n\noutputs=[{name=\"out\",cap=1,ports=[\"t3:out\"]}]\n", "file_path": "flow-rs/tests/03-share-subgraph.rs", "rank": 75, "score": 77708.19314611431 }, { "content": "// lifetime of question should not exceed Node.\n\n// If Node destroyed, question and default &str destroyed.\n\nstruct Node<'a> {\n\n question: &'a str,\n\n default: &'a str,\n\n callback: fn(&str) -> Result<Action, &'static str>,\n\n}\n\n\n", "file_path": "flow-quickstart/src/main.rs", "rank": 76, "score": 76839.41716813877 }, { "content": "#[repr(C)]\n\n#[derive(Copy, Clone)]\n\nstruct PyThreadStateUnlimited3_789 {\n\n ob_base: ffi::PyObject,\n\n interp: *mut ffi::PyInterpreterState,\n\n frame: *mut ffi::PyFrameObject,\n\n recursion_depth: i32,\n\n overflowed: i8,\n\n recursion_critical: i8,\n\n stackcheck_counter: i32,\n\n tracing: i32,\n\n use_tracing: i32,\n\n c_profilefunc: *mut c_void,\n\n c_tracefunc: *mut c_void,\n\n c_profileobj: *mut ffi::PyObject,\n\n c_traceobj: *mut ffi::PyObject,\n\n curexc_type: *mut ffi::PyObject,\n\n curexc_value: *mut ffi::PyObject,\n\n curexc_traceback: *mut ffi::PyObject,\n\n exc_state: PyErrStackItem,\n\n exc_info: *mut PyErrStackItem,\n\n dict: *mut ffi::PyObject,\n", "file_path": "flow-rs/src/loader/python/unlimited.rs", "rank": 77, "score": 75849.87397215515 }, { "content": "#[repr(C)]\n\n#[derive(Copy, Clone)]\n\nstruct PyThreadStateUnlimited3_10 {\n\n ob_base: ffi::PyObject,\n\n interp: *mut ffi::PyInterpreterState,\n\n frame: *mut ffi::PyFrameObject,\n\n recursion_depth: i32,\n\n recursion_headroom: i32,\n\n stackcheck_counter: i32,\n\n\n\n tracing: i32,\n\n cframe: *mut CFrame,\n\n\n\n c_profilefunc: *mut c_void,\n\n c_tracefunc: *mut c_void,\n\n c_profileobj: *mut ffi::PyObject,\n\n c_traceobj: *mut ffi::PyObject,\n\n curexc_type: *mut ffi::PyObject,\n\n curexc_value: *mut ffi::PyObject,\n\n curexc_traceback: *mut ffi::PyObject,\n\n exc_state: PyErrStackItem,\n\n exc_info: *mut PyErrStackItem,\n", "file_path": "flow-rs/src/loader/python/unlimited.rs", "rank": 78, "score": 75849.87397215515 }, { "content": "#[repr(C)]\n\n#[derive(Copy, Clone)]\n\nstruct PyThreadStateUnlimited3_6 {\n\n ob_base: ffi::PyObject,\n\n interp: *mut ffi::PyInterpreterState,\n\n frame: *mut ffi::PyFrameObject,\n\n recursion_depth: i32,\n\n tracing: i32,\n\n use_tracing: i32,\n\n c_profilefunc: *mut c_void,\n\n c_tracefunc: *mut c_void,\n\n c_profileobj: *mut ffi::PyObject,\n\n c_traceobj: *mut ffi::PyObject,\n\n curexc_type: *mut ffi::PyObject,\n\n curexc_value: *mut ffi::PyObject,\n\n curexc_traceback: *mut ffi::PyObject,\n\n exc_type: *mut ffi::PyObject,\n\n exc_value: *mut ffi::PyObject,\n\n exc_traceback: *mut ffi::PyObject,\n\n}\n\n\n\n#[derive(Copy, Clone)]\n", "file_path": "flow-rs/src/loader/python/unlimited.rs", "rank": 79, "score": 75849.87397215515 }, { "content": "#[doc(hidden)]\n\npub fn export() {\n\n pretty_env_logger::init();\n\n #[cfg(feature = \"python\")]\n\n python::export();\n\n}\n", "file_path": "flow-plugins/src/lib.rs", "rank": 80, "score": 74759.51518290243 }, { "content": "pub fn bcast(\n\n id: &str,\n\n src: &mut interlayer::Connection,\n\n connections: &mut HashMap<String, interlayer::Connection>,\n\n nodes: &mut HashMap<String, interlayer::Node>,\n\n) {\n\n if src.rx.len() > 1 {\n\n let node_name = format!(\"__{}xBcast__\", id);\n\n let bcast_p = |port_name: &str| interlayer::Port {\n\n node_type: vec![\"Bcast\".to_owned()],\n\n node_name: node_name.clone(),\n\n port_type: interlayer::PortTy::Unit,\n\n port_name: port_name.to_owned(),\n\n port_tag: None,\n\n };\n\n\n\n let rx = std::mem::replace(&mut src.rx, vec![bcast_p(\"inp\")]);\n\n\n\n for (i, p) in rx.into_iter().enumerate() {\n\n let name = format!(\"__{}xBcastxOut{}__\", id, i);\n", "file_path": "flow-rs/src/config/insert.rs", "rank": 81, "score": 73707.42342372672 }, { "content": "pub fn extract_ports(\n\n data: &syn::Data,\n\n ty_name: &str,\n\n f: fn(ExtractParams) -> TokenStream,\n\n) -> Vec<TokenStream> {\n\n let port_func = lit::ident(ty_name.to_lowercase());\n\n fields(data)\n\n .filter(|field| {\n\n match_last_ty(&field.ty, ty_name)\n\n || last_inner_ty(&field.ty)\n\n .map(|inner_ty| match_last_ty(inner_ty, ty_name))\n\n .unwrap_or(false)\n\n })\n\n .map(|field| (&port_func, &field.ident, &field.ty))\n\n .map(f)\n\n .collect()\n\n}\n", "file_path": "flow-derive/src/utils.rs", "rank": 82, "score": 73707.42342372672 }, { "content": "#[derive(Debug)]\n\nstruct RejectCause<T>\n\nwhere\n\n T: 'static + Debug + Send + Sync,\n\n{\n\n err: T,\n\n}\n\n\n\nimpl<T> rweb::reject::Reject for RejectCause<T> where T: 'static + Debug + Send + Sync {}\n\n\n\nimpl<T> From<T> for RejectCause<T>\n\nwhere\n\n T: 'static + Debug + Send + Sync,\n\n{\n\n fn from(err: T) -> Self {\n\n RejectCause { err }\n\n }\n\n}\n\n\n", "file_path": "flow-plugins/src/utils/error.rs", "rank": 83, "score": 73649.0091750628 }, { "content": "# MegFlow is Licensed under the Apache License, Version 2.0 (the \"License\")\n\n#\n\n# Copyright (c) 2019-2021 Megvii Inc. All rights reserved.\n\n#\n\n# Unless required by applicable law or agreed to in writing,\n\n# software distributed under the License is distributed on an\n\n# \"AS IS\" BASIS, WITHOUT ARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n\n\n\n#!/usr/bin/env python\n\n# coding=utf-8\n\nfrom collections import Iterable\n\n\n\ndef __register(name, inputs, outputs, exclusive, func):\n\n params = {}\n\n\n\n params['name'] = name\n\n params['code'] = func\n\n params['inputs'] = inputs\n\n params['outputs'] = outputs\n\n params['exclusive'] = exclusive\n\n\n\n return params\n\n\n\n\n\ndef __res_register(name, func):\n\n params = {}\n\n params['name'] = name\n\n params['code'] = func\n\n\n\n return params\n\n\n\n\n\n__NODES_PLUGINS = 'nodes'\n\n__RESOURCE_PLUGINS = 'resources'\n\n__PLUGINS_DEFAULT = {\n\n __NODES_PLUGINS: [],\n\n __RESOURCE_PLUGINS: [],\n\n}\n\n_PLUGINS_REGISTRY = __PLUGINS_DEFAULT.copy()\n\n\n\ndef register(name=None, inputs=[], outputs=[], exclusive=False):\n\n def decorator(func):\n\n nonlocal name\n\n global _PLUGINS_REGISTRY\n\n if name is None:\n\n name = func.__name__\n\n _PLUGINS_REGISTRY[__NODES_PLUGINS].append(__register(name, inputs, outputs, exclusive, func))\n\n return func\n\n\n\n return decorator\n\n\n\n\n\ndef res_register(name=None):\n\n def decorator(func):\n\n nonlocal name\n\n global _PLUGINS_REGISTRY\n\n if name is None:\n\n name = func.__name__\n\n _PLUGINS_REGISTRY[__RESOURCE_PLUGINS].append(__res_register(name, func))\n\n return func\n\n\n\n return decorator\n\n\n\n\n\ndef collect():\n\n global _PLUGINS_REGISTRY\n\n plugins = _PLUGINS_REGISTRY.copy()\n\n _PLUGINS_REGISTRY = __PLUGINS_DEFAULT.copy()\n\n return plugins\n", "file_path": "flow-python/megflow/registry.py", "rank": 84, "score": 73211.70102529318 }, { "content": "pub fn translate_graph(\n\n local_key: u64,\n\n mut p: presentation::Graph,\n\n shared_nodes: &mut HashMap<String, interlayer::Node>,\n\n) -> Result<interlayer::Graph> {\n\n let mut nodes = HashMap::new();\n\n let mut resources = HashMap::new();\n\n let mut inputs = vec![];\n\n let mut outputs = vec![];\n\n let mut connections = HashMap::new();\n\n\n\n for node in std::mem::take(&mut p.nodes) {\n\n nodes.insert(\n\n node.entity.name.clone(),\n\n translate_node(local_key, false, node)?,\n\n );\n\n }\n\n for res in std::mem::take(&mut p.resources) {\n\n resources.insert(res.name.clone(), res);\n\n }\n", "file_path": "flow-rs/src/config/mod.rs", "rank": 85, "score": 72705.69188201198 }, { "content": "#[allow(unused_variables)]\n\n#[allow(unused_labels)]\n\npub fn decode_video(\n\n id: u64,\n\n path: impl AsRef<Path>,\n\n sender: &Sender,\n\n) -> Result<(), ffmpeg_next::Error> {\n\n ONCE_INIT.call_once(|| {\n\n ffmpeg_next::init().unwrap();\n\n });\n\n\n\n let mut ictx = input(&path)?;\n\n\n\n let input = ictx\n\n .streams()\n\n .best(Type::Video)\n\n .ok_or(ffmpeg_next::Error::StreamNotFound)?;\n\n\n\n let video_stream_index = input.index();\n\n\n\n let mut decoder = input.codec().decoder().video()?;\n\n\n", "file_path": "flow-plugins/src/utils/codec.rs", "rank": 86, "score": 72705.69188201198 }, { "content": "pub fn dyn_out_trans(\n\n src: &mut presentation::NamedConn,\n\n connections: &mut HashMap<String, interlayer::Connection>,\n\n nodes: &mut HashMap<String, interlayer::Node>,\n\n shared_nodes: &mut HashMap<String, interlayer::Node>,\n\n) -> Result<()> {\n\n for p in &mut src.conn.ports {\n\n let ((n, _), _) = interlayer::Port::parse(p.as_str())?;\n\n if let Some(node) = nodes.get_mut(n) {\n\n if node.is_dyn {\n\n let conn_name = format!(\"__{}xDynInTransform__\", src.name);\n\n let node_name = conn_name.clone();\n\n *p = format!(\"{}:inp\", node_name);\n\n let mut tmp_conn = presentation::Connection {\n\n cap: src.conn.cap,\n\n ports: vec![],\n\n };\n\n let tmp_node = interlayer::Node {\n\n entity: interlayer::Entity {\n\n name: node_name,\n", "file_path": "flow-rs/src/config/insert.rs", "rank": 87, "score": 72705.69188201198 }, { "content": "pub fn substitute_dir_by_placeholder(\n\n project_dir: &Path,\n\n map: &HashMap<String, String>,\n\n) -> Result<Action, &'static str> {\n\n let files = WalkDir::new(project_dir)\n\n .sort_by_file_name()\n\n .contents_first(true)\n\n .into_iter()\n\n .filter_map(Result::ok)\n\n .filter(|e| !is_git_metadata(e))\n\n .filter(|e| !e.path().is_dir())\n\n .filter(|e| e.path() != project_dir)\n\n .collect::<Vec<_>>();\n\n\n\n let pb = ProgressBar::new(files.len() as u64);\n\n pb.set_style(\n\n ProgressStyle::default_bar()\n\n .template(\"[{elapsed_precise}] {bar:40.cyan/blue} {pos:>7}/{len:7} {msg}\")\n\n .progress_chars(\"##-\"),\n\n );\n", "file_path": "flow-quickstart/src/lib.rs", "rank": 88, "score": 72705.69188201198 }, { "content": "pub fn load_shared(\n\n cfg: &crate::config::interlayer::Node,\n\n graphs: &crate::config::interlayer::Config,\n\n ctx: Context,\n\n resources: ResourceCollection,\n\n) -> Result<SharedProxy> {\n\n let local_key = ctx.local_key;\n\n let (s, r) = unbounded();\n\n let shared = Shared::new(ctx.local_key, r, cfg, graphs)?.boxed();\n\n let handle = shared.start(ctx, resources);\n\n SharedHandle::registry_local()\n\n .get(local_key)\n\n .insert(cfg.entity.name.clone(), SharedHandle(handle));\n\n SharedProxy::new(local_key, s, cfg)\n\n}\n", "file_path": "flow-rs/src/node/shared.rs", "rank": 89, "score": 72705.69188201198 }, { "content": "#!/usr/bin/env python\n\n# coding=utf-8\n\n\n\nimport sys\n\nimport os\n\nimport subprocess\n\nimport pkg_resources\n\n\n\ndef megflow_run():\n\n if pkg_resources.resource_exists('megflow', 'lib') and pkg_resources.resource_isdir('megflow', 'lib'):\n\n if 'MGF_CMDLINE_FLAG' not in os.environ:\n\n os.environ['MGF_CMDLINE_FLAG'] = '1'\n\n if 'LD_LIBRARY_PATH' in os.environ:\n\n os.environ['LD_LIBRARY_PATH'] = pkg_resources.resource_filename('megflow', 'lib') + ':' + os.environ['LD_LIBRARY_PATH']\n\n else:\n\n os.environ['LD_LIBRARY_PATH'] = pkg_resources.resource_filename('megflow', 'lib')\n\n\t \n\n try:\n\n os.execv(sys.argv[0], sys.argv)\n\n return\n\n except Exception as exc:\n\n print('Failed re-exec:', exc)\n\n sys.exit(1)\n\n\n\n import argparse\n\n import megflow\n\n\n\n parser = argparse.ArgumentParser(prog='megflow_run', description='run a pipeline with plugins.')\n\n parser.add_argument('--dump', help='the path to dump graph', action='store_true')\n\n parser.add_argument('-p', '--plugin', required=True, type=str, help='plugin path')\n\n parser.add_argument('-m', '--module', type=str, help='module path')\n\n parser.add_argument('-c', '--config', type=str, help='config path')\n\n parser.add_argument('--dynamic', type=str, help='dynamic config path')\n\n parser.add_argument('--version', action='version', version='%(prog)s {version}'.format(version=megflow.__version__))\n\n\n\n args = parser.parse_args()\n\n\n\n megflow.Graph(\n\n dump=args.dump, \n\n plugin_path=args.plugin, \n\n module_path=args.module, \n\n config_path=args.config, \n\n dynamic_path = args.dynamic\n\n ).wait()\n\n\n\n\n\ndef run_with_plugins():\n\n print('run_with_plugins has been renamed to megflow_run.')\n\n\n\n\n\ndef megflow_quickstart():\n\n bin_path = pkg_resources.resource_filename('megflow', 'megflow_quickstart_inner')\n\n sys.argv[0] = bin_path\n\n ret = subprocess.Popen(sys.argv)\n\n ret.wait()\n\n\n\n\n\nif __name__ == '__main__':\n\n megflow_run()\n", "file_path": "flow-python/megflow/command_line.py", "rank": 90, "score": 72291.29116432587 }, { "content": "#!/usr/bin/env python\n\n# coding=utf-8\n\n\n\nfrom .registry import register\n\nimport inspect\n\nfrom functools import partial\n\nimport re\n\n\n\nclass Context:\n\n def __init__(self, **entries):\n\n self.__dict__.update(entries)\n\n\n\ndef name_convert_to_camel(name):\n\n contents = re.findall('_[a-z]+', name)\n\n for content in set(contents):\n\n name = name.replace(content, content[1:].title())\n\n return name.title()\n\n\n\n\n\ndef _with_context(func):\n\n sig = inspect.signature(func)\n\n params = sig.parameters\n\n return 'context' in params\n\n\n\n\n\ndef _common_def(inputs=[], outputs=[]):\n\n def common_def(plugin_def):\n\n def decorator(name=None, exclusive=False):\n\n def _decorator(func):\n\n nonlocal name\n\n if name is None:\n\n name = func.__name__\n\n name = name_convert_to_camel(name)\n\n with_context = _with_context(func)\n\n \n\n @register(name=name, inputs=inputs, outputs=outputs, exclusive=exclusive)\n\n class Node:\n\n def __init__(self, name, args):\n\n self.context = Context(**args)\n\n self.name = name\n\n if with_context:\n\n self.impl = partial(func, context = self.context) \n\n else:\n\n self.impl = func\n\n \n\n def exec(self):\n\n plugin_def(self, self.impl)\n\n \n\n return Node\n\n \n\n return _decorator\n\n return decorator\n\n return common_def\n\n\n\n\n\n@_common_def(inputs=[\"inp\"], outputs=[\"out\"])\n\ndef map_def(self, func):\n\n envelope = self.inp.recv()\n\n if envelope is None:\n\n return\n\n envelope.msg = func(envelope.msg)\n\n self.out.send(envelope)\n\n\n\n\n\n@_common_def(inputs=[\"inp:[]\"], outputs=[\"out\"])\n\ndef reduce_def(self, func):\n\n ret = []\n\n for inp in self.inp:\n\n ret.append(inp.recv())\n\n \n\n all_empty = True\n\n for envelope in ret:\n\n all_empty = all_empty and envelope is None\n\n if all_empty:\n\n return\n\n\n\n for envelope in ret:\n\n assert envelope is not None\n\n\n\n msgs = [ envelope.msg for envelope in ret ]\n\n\n\n self.out.send(ret[0].repack(func(msgs)))\n\n\n\n\n\n@_common_def(inputs=[\"inp\"])\n\ndef sink_def(self, func):\n\n envelope = self.inp.recv()\n\n\n\n if envelope is None:\n\n return\n\n\n\n func(envelope.msg)\n\n\n\n\n\n@_common_def(outputs=[\"out\"])\n\ndef source_def(self, func):\n\n from megflow import Envelope\n\n i = 0\n\n for msg in func():\n\n self.out.send(Envelope.pack(msg, info={'partial_id':i}))\n\n i += 1\n\n\n\n\n\n@_common_def(inputs=[\"inp\"], outputs=[\"out\"])\n\ndef batch_def(self, func):\n\n (envelopes, is_closed) = self.inp.batch_recv(self.context.batch_size, self.context.timeout)\n\n if len(envelopes) == 0:\n\n return\n\n\n\n func([envelope.msg for envelope in envelopes])\n\n\n\n for envelope in envelopes:\n\n self.out.send(envelope)\n", "file_path": "flow-python/megflow/func_op.py", "rank": 91, "score": 72291.29116432587 }, { "content": "pub fn dyn_inp_trans(\n\n src: &mut presentation::NamedConn,\n\n connections: &mut HashMap<String, interlayer::Connection>,\n\n nodes: &mut HashMap<String, interlayer::Node>,\n\n shared_nodes: &mut HashMap<String, interlayer::Node>,\n\n) -> Result<()> {\n\n for p in &mut src.conn.ports {\n\n let ((n, _), _) = interlayer::Port::parse(p.as_str())?;\n\n if let Some(node) = nodes.get_mut(n) {\n\n if node.is_dyn {\n\n let conn_name = format!(\"__{}xDynOutTransform__\", src.name);\n\n let node_name = conn_name.clone();\n\n *p = format!(\"{}:inp\", node_name);\n\n let mut tmp_conn = presentation::Connection {\n\n cap: src.conn.cap,\n\n ports: vec![],\n\n };\n\n let tmp_node = interlayer::Node {\n\n entity: interlayer::Entity {\n\n name: node_name,\n", "file_path": "flow-rs/src/config/insert.rs", "rank": 92, "score": 71750.7892047475 }, { "content": "# MegFlow is Licensed under the Apache License, Version 2.0 (the \"License\")\n\n#\n\n# Copyright (c) 2019-2021 Megvii Inc. All rights reserved.\n\n#\n\n# Unless required by applicable law or agreed to in writing,\n\n# software distributed under the License is distributed on an\n\n# \"AS IS\" BASIS, WITHOUT ARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n\n\n\n#!/usr/bin/env python\n\n# coding=utf-8\n\n\n\nfrom .registry import register, collect, res_register\n\nfrom .megflow import *\n\n\n\n__version__ = version()\n", "file_path": "flow-python/megflow/__init__.py", "rank": 93, "score": 71437.12794045554 }, { "content": "struct RegistryInner<ID, T> {\n\n elems: HashMap<ID, T>,\n\n}\n\npub struct Registry<ID, T> {\n\n inner: RwLock<RegistryInner<ID, Arc<T>>>,\n\n}\n\npub struct RegistryMap<ID, T> {\n\n inner: RwLock<HashMap<u64, Arc<Registry<ID, T>>>>,\n\n}\n\n\n\nimpl<ID: Eq + Hash, T> Default for Registry<ID, T> {\n\n fn default() -> Registry<ID, T> {\n\n Registry {\n\n inner: RwLock::new(RegistryInner {\n\n elems: HashMap::new(),\n\n }),\n\n }\n\n }\n\n}\n\n\n", "file_path": "flow-rs/src/registry.rs", "rank": 94, "score": 70390.17959056489 }, { "content": "/// home path wrapper\n\nfn home() -> Result<PathBuf> {\n\n canonicalize_path(&dirs::home_dir().context(\"$HOME was not set\")?)\n\n}\n\n\n", "file_path": "flow-quickstart/src/git.rs", "rank": 95, "score": 69508.16269088144 }, { "content": "#[pyfunction]\n\nfn yield_now(py: Python) {\n\n with_context(py, || wait(crate::rt::task::yield_now()))\n\n}\n\n\n", "file_path": "flow-rs/src/loader/python/utils.rs", "rank": 96, "score": 67641.97747355593 }, { "content": "fn range(n: Data) -> Data {\n\n let list = match &*n {\n\n Unstructured::Number(end) => range_impl(0, end.into(), 1),\n\n Unstructured::Seq(list) => match &list[..] {\n\n [start, end] => {\n\n let start = get_num(start);\n\n let end = get_num(end);\n\n range_impl(start, end, 1)\n\n }\n\n [start, end, step] => {\n\n let start = get_num(start);\n\n let end = get_num(end);\n\n let step = get_num(step);\n\n assert!(step > 0);\n\n range_impl(start, end, step)\n\n }\n\n _ => unreachable!(),\n\n },\n\n _ => unreachable!(),\n\n };\n", "file_path": "flow-rs/src/config/parser.rs", "rank": 97, "score": 66894.04047941082 }, { "content": "fn exec(commands: &[Node<'static>]) {\n\n let mut index = 0;\n\n while index < commands.len() {\n\n let cmd = &commands[index];\n\n println!(\"> {} [{}]\", cmd.question, cmd.default);\n\n\n\n let mut user_input = String::new();\n\n stdin().read_line(&mut user_input).unwrap();\n\n\n\n let inp = user_input.trim();\n\n let result: Result<Action, &'static str>;\n\n if !inp.is_empty() {\n\n result = (cmd.callback)(inp);\n\n } else {\n\n result = (cmd.callback)(cmd.default);\n\n }\n\n\n\n match result {\n\n Ok(action) => match action {\n\n Action::Retry => continue,\n\n Action::Next => index += 1,\n\n Action::Quit => break,\n\n },\n\n Err(why) => panic!(\"{:?}\", why),\n\n }\n\n }\n\n}\n\n\n", "file_path": "flow-quickstart/src/main.rs", "rank": 98, "score": 66894.04047941082 }, { "content": "fn start() -> Vec<Node<'static>> {\n\n let create_project = Node {\n\n question: \"Enter root path for the project.\",\n\n default: \"megflow-app\",\n\n callback: make_project,\n\n };\n\n let choose_type = Node {\n\n question: \"Enter project type, modelserving/image/video/custom?\",\n\n default: \"modelserving\",\n\n callback: create_with_type,\n\n };\n\n vec![create_project, choose_type]\n\n}\n\n\n", "file_path": "flow-quickstart/src/main.rs", "rank": 99, "score": 66894.04047941082 } ]
Rust
crates/ruma-events/src/room/encrypted/relation_serde.rs
MTRNord/ruma
653e4c4838fb3e5809573ce0a7e763547d5f20e4
#[cfg(feature = "unstable-pre-spec")] use ruma_identifiers::EventId; use serde::{ser::SerializeStruct as _, Deserialize, Deserializer, Serialize, Serializer}; #[cfg(feature = "unstable-pre-spec")] use super::{Annotation, Reference, Replacement}; use super::{InReplyTo, Relation}; #[cfg(feature = "unstable-pre-spec")] use crate::room::message::MessageEventContent; pub fn deserialize<'de, D>(deserializer: D) -> Result<Option<Relation>, D::Error> where D: Deserializer<'de>, { fn convert_relation(ev: EventWithRelatesToJsonRepr) -> Option<Relation> { if let Some(in_reply_to) = ev.relates_to.in_reply_to { return Some(Relation::Reply { in_reply_to }); } #[cfg(feature = "unstable-pre-spec")] if let Some(relation) = ev.relates_to.relation { let relation = match relation { RelationJsonRepr::Annotation(a) => Relation::Annotation(a), RelationJsonRepr::Reference(r) => Relation::Reference(r), RelationJsonRepr::Replacement(ReplacementJsonRepr { event_id }) => { let new_content = ev.new_content?; Relation::Replacement(Replacement { event_id, new_content }) } RelationJsonRepr::Unknown => return None, }; return Some(relation); } None } EventWithRelatesToJsonRepr::deserialize(deserializer).map(convert_relation) } pub fn serialize<S>(relation: &Option<Relation>, serializer: S) -> Result<S::Ok, S::Error> where S: Serializer, { let relation = match relation { Some(rel) => rel, None => return serializer.serialize_struct("NoRelation", 0)?.end(), }; let json_repr = match relation { #[cfg(feature = "unstable-pre-spec")] Relation::Annotation(r) => EventWithRelatesToJsonRepr::new(RelatesToJsonRepr { relation: Some(RelationJsonRepr::Annotation(r.clone())), ..Default::default() }), #[cfg(feature = "unstable-pre-spec")] Relation::Reference(r) => EventWithRelatesToJsonRepr::new(RelatesToJsonRepr { relation: Some(RelationJsonRepr::Reference(r.clone())), ..Default::default() }), #[cfg(feature = "unstable-pre-spec")] Relation::Replacement(Replacement { event_id, new_content }) => { EventWithRelatesToJsonRepr { relates_to: RelatesToJsonRepr { relation: Some(RelationJsonRepr::Replacement(ReplacementJsonRepr { event_id: event_id.clone(), })), ..Default::default() }, new_content: Some(new_content.clone()), } } Relation::Reply { in_reply_to } => EventWithRelatesToJsonRepr::new(RelatesToJsonRepr { in_reply_to: Some(in_reply_to.clone()), ..Default::default() }), }; json_repr.serialize(serializer) } #[derive(Deserialize, Serialize)] struct EventWithRelatesToJsonRepr { #[serde(rename = "m.relates_to", default, skip_serializing_if = "RelatesToJsonRepr::is_empty")] relates_to: RelatesToJsonRepr, #[cfg(feature = "unstable-pre-spec")] #[serde(rename = "m.new_content", skip_serializing_if = "Option::is_none")] new_content: Option<Box<MessageEventContent>>, } impl EventWithRelatesToJsonRepr { fn new(relates_to: RelatesToJsonRepr) -> Self { Self { relates_to, #[cfg(feature = "unstable-pre-spec")] new_content: None, } } } #[derive(Default, Deserialize, Serialize)] struct RelatesToJsonRepr { #[serde(rename = "m.in_reply_to", skip_serializing_if = "Option::is_none")] in_reply_to: Option<InReplyTo>, #[cfg(feature = "unstable-pre-spec")] #[serde(flatten, skip_serializing_if = "Option::is_none")] relation: Option<RelationJsonRepr>, } impl RelatesToJsonRepr { fn is_empty(&self) -> bool { #[cfg(not(feature = "unstable-pre-spec"))] { self.in_reply_to.is_none() } #[cfg(feature = "unstable-pre-spec")] { self.in_reply_to.is_none() && self.relation.is_none() } } } #[derive(Clone, Deserialize, Serialize)] #[cfg(feature = "unstable-pre-spec")] #[serde(tag = "rel_type")] enum RelationJsonRepr { #[serde(rename = "m.annotation")] Annotation(Annotation), #[serde(rename = "m.reference")] Reference(Reference), #[serde(rename = "m.replace")] Replacement(ReplacementJsonRepr), #[serde(other)] Unknown, } #[derive(Clone, Deserialize, Serialize)] #[cfg(feature = "unstable-pre-spec")] struct ReplacementJsonRepr { event_id: EventId, }
#[cfg(feature = "unstable-pre-spec")] use ruma_identifiers::EventId; use serde::{ser::SerializeStruct as _, Deserialize, Deserializer, Serialize, Serializer}; #[cfg(feature = "unstable-pre-spec")] use super::{Annotation, Reference, Replacement}; use super::{InReplyTo, Relation}; #[cfg(feature = "unstable-pre-spec")] use crate::room::message::MessageEventContent; pub fn deserialize<'de, D>(deserializer: D) -> Result<Option<Relation>, D::Error> where D: Deserializer<'de>, { fn convert_relation(ev: EventWithRelatesToJsonRepr) -> Option<Relation> { if let Some(in_reply_to) = ev.relates_to.in_reply_to { return Some(Relation::Reply { in_reply_to }); } #[cfg(feature = "unstable-pre-spec")] if let Some(relation) = ev.relates_to.relation { let relation = match relation { RelationJsonRepr::Annotation(a) => Relation::Annotation(a), RelationJsonRepr::Reference(r) => Relation::Reference(r), RelationJsonRepr::Replacement(ReplacementJsonRepr { event_id }) => { let new_content = ev.new_content?; Relation::Replacement(Replacement { event_id, new_content }) } RelationJsonRepr::Unknown => return None, }; return Some(relation); } None } EventWithRelatesToJsonRepr::deserialize(deserializer).map(convert_relation) } pub fn serialize<S>(relation: &Option<Relation>, serializer: S) -> Result<S::Ok, S::Error> where S: Serializer, { let relation = match relation { Some(rel) => rel, None => return serializer.serialize_struct("NoRelation", 0)?.end(), }; let json_repr = match relati
, #[serde(rename = "m.reference")] Reference(Reference), #[serde(rename = "m.replace")] Replacement(ReplacementJsonRepr), #[serde(other)] Unknown, } #[derive(Clone, Deserialize, Serialize)] #[cfg(feature = "unstable-pre-spec")] struct ReplacementJsonRepr { event_id: EventId, }
on { #[cfg(feature = "unstable-pre-spec")] Relation::Annotation(r) => EventWithRelatesToJsonRepr::new(RelatesToJsonRepr { relation: Some(RelationJsonRepr::Annotation(r.clone())), ..Default::default() }), #[cfg(feature = "unstable-pre-spec")] Relation::Reference(r) => EventWithRelatesToJsonRepr::new(RelatesToJsonRepr { relation: Some(RelationJsonRepr::Reference(r.clone())), ..Default::default() }), #[cfg(feature = "unstable-pre-spec")] Relation::Replacement(Replacement { event_id, new_content }) => { EventWithRelatesToJsonRepr { relates_to: RelatesToJsonRepr { relation: Some(RelationJsonRepr::Replacement(ReplacementJsonRepr { event_id: event_id.clone(), })), ..Default::default() }, new_content: Some(new_content.clone()), } } Relation::Reply { in_reply_to } => EventWithRelatesToJsonRepr::new(RelatesToJsonRepr { in_reply_to: Some(in_reply_to.clone()), ..Default::default() }), }; json_repr.serialize(serializer) } #[derive(Deserialize, Serialize)] struct EventWithRelatesToJsonRepr { #[serde(rename = "m.relates_to", default, skip_serializing_if = "RelatesToJsonRepr::is_empty")] relates_to: RelatesToJsonRepr, #[cfg(feature = "unstable-pre-spec")] #[serde(rename = "m.new_content", skip_serializing_if = "Option::is_none")] new_content: Option<Box<MessageEventContent>>, } impl EventWithRelatesToJsonRepr { fn new(relates_to: RelatesToJsonRepr) -> Self { Self { relates_to, #[cfg(feature = "unstable-pre-spec")] new_content: None, } } } #[derive(Default, Deserialize, Serialize)] struct RelatesToJsonRepr { #[serde(rename = "m.in_reply_to", skip_serializing_if = "Option::is_none")] in_reply_to: Option<InReplyTo>, #[cfg(feature = "unstable-pre-spec")] #[serde(flatten, skip_serializing_if = "Option::is_none")] relation: Option<RelationJsonRepr>, } impl RelatesToJsonRepr { fn is_empty(&self) -> bool { #[cfg(not(feature = "unstable-pre-spec"))] { self.in_reply_to.is_none() } #[cfg(feature = "unstable-pre-spec")] { self.in_reply_to.is_none() && self.relation.is_none() } } } #[derive(Clone, Deserialize, Serialize)] #[cfg(feature = "unstable-pre-spec")] #[serde(tag = "rel_type")] enum RelationJsonRepr { #[serde(rename = "m.annotation")] Annotation(Annotation)
random
[ { "content": "pub fn deserialize<'de, D>(deserializer: D) -> Result<Option<Relation>, D::Error>\n\nwhere\n\n D: Deserializer<'de>,\n\n{\n\n fn convert_relation(ev: EventWithRelatesToJsonRepr) -> Option<Relation> {\n\n if let Some(in_reply_to) = ev.relates_to.in_reply_to {\n\n return Some(Relation::Reply { in_reply_to });\n\n }\n\n\n\n #[cfg(feature = \"unstable-pre-spec\")]\n\n if let Some(relation) = ev.relates_to.relation {\n\n let relation = match relation {\n\n RelationJsonRepr::Replacement(ReplacementJsonRepr { event_id }) => {\n\n let new_content = ev.new_content?;\n\n Relation::Replacement(Replacement { event_id, new_content })\n\n }\n\n // FIXME: Maybe we should log this, though at this point we don't even have access\n\n // to the rel_type of the unknown relation.\n\n RelationJsonRepr::Unknown => return None,\n\n };\n\n\n\n return Some(relation);\n\n }\n\n\n\n None\n\n }\n\n\n\n EventWithRelatesToJsonRepr::deserialize(deserializer).map(convert_relation)\n\n}\n\n\n", "file_path": "crates/ruma-events/src/room/message/relation_serde.rs", "rank": 1, "score": 271651.39540593 }, { "content": "/// Deserializes an integer representing seconds into a Duration.\n\n///\n\n/// Will fail if integer is greater than the maximum integer that can be\n\n/// unambiguously represented by an f64.\n\npub fn deserialize<'de, D>(deserializer: D) -> Result<Duration, D::Error>\n\nwhere\n\n D: Deserializer<'de>,\n\n{\n\n UInt::deserialize(deserializer).map(|secs| Duration::from_secs(secs.into()))\n\n}\n\n\n\n#[cfg(test)]\n\nmod tests {\n\n use std::time::Duration;\n\n\n\n use serde::{Deserialize, Serialize};\n\n use serde_json::json;\n\n\n\n #[derive(Clone, Debug, PartialEq, Deserialize, Serialize)]\n\n struct DurationTest {\n\n #[serde(with = \"super\")]\n\n timeout: Duration,\n\n }\n\n\n", "file_path": "crates/ruma-serde/src/duration/secs.rs", "rank": 2, "score": 228902.5004261481 }, { "content": "/// Serde serializiation decorator to map None to an empty String,\n\n/// and forward Somes to the Serialize implemention for T.\n\n///\n\n/// To be used like this:\n\n/// `#[serde(serialize_with = \"empty_string_as_none\")]`\n\npub fn none_as_empty_string<T: Serialize, S>(\n\n value: &Option<T>,\n\n serializer: S,\n\n) -> Result<S::Ok, S::Error>\n\nwhere\n\n S: Serializer,\n\n{\n\n match value {\n\n Some(x) => x.serialize(serializer),\n\n None => serializer.serialize_str(\"\"),\n\n }\n\n}\n\n\n", "file_path": "crates/ruma-serde/src/strings.rs", "rank": 3, "score": 228484.6011477569 }, { "content": "pub fn deserialize<'de, D>(\n\n deserializer: D,\n\n) -> Result<BTreeMap<EventId, Result<(), String>>, D::Error>\n\nwhere\n\n D: Deserializer<'de>,\n\n{\n\n struct PduProcessResponseVisitor;\n\n\n\n impl<'de> Visitor<'de> for PduProcessResponseVisitor {\n\n type Value = BTreeMap<EventId, Result<(), String>>;\n\n\n\n fn expecting(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {\n\n formatter.write_str(\"A map of EventIds to a map of optional errors\")\n\n }\n\n\n\n fn visit_map<M>(self, mut access: M) -> Result<Self::Value, M::Error>\n\n where\n\n M: MapAccess<'de>,\n\n {\n\n let mut map = BTreeMap::new();\n", "file_path": "crates/ruma-federation-api/src/serde/pdu_process_response.rs", "rank": 4, "score": 228426.88600928822 }, { "content": "pub fn expand_deserialize_from_cow_str(ident: &Ident) -> syn::Result<TokenStream> {\n\n let ruma_serde = import_ruma_serde();\n\n\n\n Ok(quote! {\n\n impl<'de> #ruma_serde::exports::serde::de::Deserialize<'de> for #ident {\n\n fn deserialize<D>(deserializer: D) -> ::std::result::Result<Self, D::Error>\n\n where\n\n D: #ruma_serde::exports::serde::de::Deserializer<'de>,\n\n {\n\n type CowStr<'a> = ::std::borrow::Cow<'a, ::std::primitive::str>;\n\n\n\n let cow = #ruma_serde::deserialize_cow_str(deserializer)?;\n\n Ok(::std::convert::From::<CowStr<'_>>::from(cow))\n\n }\n\n }\n\n })\n\n}\n", "file_path": "crates/ruma-serde-macros/src/deserialize_from_cow_str.rs", "rank": 5, "score": 227442.87423116903 }, { "content": "/// Read a string from the input and deserialize it as a `T`.\n\npub fn deserialize<'de, T, D>(deserializer: D) -> Result<T, D::Error>\n\nwhere\n\n T: DeserializeOwned,\n\n D: Deserializer<'de>,\n\n{\n\n let s = crate::deserialize_cow_str(deserializer)?;\n\n serde_json::from_str(&s).map_err(D::Error::custom)\n\n}\n", "file_path": "crates/ruma-serde/src/json_string.rs", "rank": 6, "score": 224259.779734831 }, { "content": "/// Deserialize a list of one item and return that item.\n\npub fn deserialize<'de, T, D>(deserializer: D) -> Result<T, D::Error>\n\nwhere\n\n T: Deserialize<'de>,\n\n D: Deserializer<'de>,\n\n{\n\n <[_; 1]>::deserialize(deserializer).map(|[first]| first)\n\n}\n", "file_path": "crates/ruma-serde/src/single_element_seq.rs", "rank": 7, "score": 221528.53418603342 }, { "content": "/// Deserializes an Option<Duration>.\n\n///\n\n/// Will fail if integer is greater than the maximum integer that can be\n\n/// unambiguously represented by an f64.\n\npub fn deserialize<'de, D>(deserializer: D) -> Result<Option<Duration>, D::Error>\n\nwhere\n\n D: Deserializer<'de>,\n\n{\n\n Ok(Option::<UInt>::deserialize(deserializer)?\n\n .map(|millis| Duration::from_millis(millis.into())))\n\n}\n\n\n\n#[cfg(test)]\n\nmod tests {\n\n use std::time::Duration;\n\n\n\n use serde::{Deserialize, Serialize};\n\n use serde_json::json;\n\n\n\n #[derive(Clone, Debug, PartialEq, Deserialize, Serialize)]\n\n struct DurationTest {\n\n #[serde(with = \"super\", default, skip_serializing_if = \"Option::is_none\")]\n\n timeout: Option<Duration>,\n\n }\n", "file_path": "crates/ruma-serde/src/duration/opt_ms.rs", "rank": 8, "score": 221522.0207162191 }, { "content": "#[test]\n\nfn serialize_and_deserialize_from_display_form() {\n\n serde_json_eq(EventType::CallAnswer, json!(\"m.call.answer\"));\n\n serde_json_eq(MessageEventType::CallAnswer, json!(\"m.call.answer\"));\n\n serde_json_eq(EventType::CallCandidates, json!(\"m.call.candidates\"));\n\n serde_json_eq(EventType::CallHangup, json!(\"m.call.hangup\"));\n\n serde_json_eq(EventType::CallInvite, json!(\"m.call.invite\"));\n\n serde_json_eq(EventType::Direct, json!(\"m.direct\"));\n\n serde_json_eq(GlobalAccountDataEventType::Direct, json!(\"m.direct\"));\n\n serde_json_eq(EventType::Dummy, json!(\"m.dummy\"));\n\n serde_json_eq(EventType::ForwardedRoomKey, json!(\"m.forwarded_room_key\"));\n\n serde_json_eq(EventType::FullyRead, json!(\"m.fully_read\"));\n\n serde_json_eq(RoomAccountDataEventType::FullyRead, json!(\"m.fully_read\"));\n\n serde_json_eq(EventType::KeyVerificationAccept, json!(\"m.key.verification.accept\"));\n\n serde_json_eq(EventType::KeyVerificationCancel, json!(\"m.key.verification.cancel\"));\n\n // m.key.verification.ready is unstable-pre-spec\n\n // serde_json_eq(EventType::KeyVerificationDone, json!(\"m.key.verification.done\"));\n\n serde_json_eq(EventType::KeyVerificationKey, json!(\"m.key.verification.key\"));\n\n serde_json_eq(ToDeviceEventType::KeyVerificationKey, json!(\"m.key.verification.key\"));\n\n serde_json_eq(EventType::KeyVerificationMac, json!(\"m.key.verification.mac\"));\n\n // m.key.verification.ready is unstable-pre-spec\n", "file_path": "crates/ruma-events/tests/enums.rs", "rank": 9, "score": 220834.87437966588 }, { "content": "pub fn deserialize<'de, T, D>(deserializer: D) -> Result<T, D::Error>\n\nwhere\n\n D: Deserializer<'de>,\n\n T: Deserialize<'de>,\n\n{\n\n deserializer.deserialize_seq(PduVisitor { phantom: PhantomData })\n\n}\n\n\n", "file_path": "crates/ruma-federation-api/src/serde/v1_pdu.rs", "rank": 10, "score": 218856.11160955532 }, { "content": "pub fn serialize<S>(relation: &Option<Relation>, serializer: S) -> Result<S::Ok, S::Error>\n\nwhere\n\n S: Serializer,\n\n{\n\n let relation = match relation {\n\n Some(rel) => rel,\n\n // FIXME: If this crate ends up depending on tracing, emit a warning here.\n\n // This code path should not be reachable due to the skip_serializing_if serde attribute\n\n // that should be applied together with `with = \"relation_serde\"`.\n\n None => return serializer.serialize_struct(\"NoRelation\", 0)?.end(),\n\n };\n\n\n\n let json_repr = match relation {\n\n Relation::Reply { in_reply_to } => EventWithRelatesToJsonRepr::new(RelatesToJsonRepr {\n\n in_reply_to: Some(in_reply_to.clone()),\n\n ..Default::default()\n\n }),\n\n #[cfg(feature = \"unstable-pre-spec\")]\n\n Relation::Replacement(Replacement { event_id, new_content }) => {\n\n EventWithRelatesToJsonRepr {\n", "file_path": "crates/ruma-events/src/room/message/relation_serde.rs", "rank": 11, "score": 217909.06917435152 }, { "content": "/// Deserialize a `Cow<'de, str>`.\n\n///\n\n/// Different from serde's implementation of `Deserialize` for `Cow` since it borrows from the\n\n/// input when possible.\n\n///\n\n/// This will become unnecessary if Rust gains lifetime specialization at some point; see\n\n/// <https://github.com/serde-rs/serde/issues/1497#issuecomment-716246686>.\n\npub fn deserialize_cow_str<'de, D>(deserializer: D) -> Result<Cow<'de, str>, D::Error>\n\nwhere\n\n D: Deserializer<'de>,\n\n{\n\n deserializer.deserialize_string(CowStrVisitor)\n\n}\n\n\n", "file_path": "crates/ruma-serde/src/cow.rs", "rank": 13, "score": 217213.45881281313 }, { "content": "#[proc_macro_derive(DeserializeFromCowStr)]\n\npub fn derive_deserialize_from_cow_str(input: TokenStream) -> TokenStream {\n\n let input = parse_macro_input!(input as DeriveInput);\n\n expand_deserialize_from_cow_str(&input.ident)\n\n .unwrap_or_else(syn::Error::into_compile_error)\n\n .into()\n\n}\n\n\n", "file_path": "crates/ruma-serde-macros/src/lib.rs", "rank": 14, "score": 215047.90760664403 }, { "content": "/// Creates a *reference hash* for an event.\n\n///\n\n/// Returns the hash as a Base64-encoded string, using the standard character set, without padding.\n\n///\n\n/// The reference hash of an event covers the essential fields of an event, including content\n\n/// hashes. It is used to generate event identifiers and is described in the Matrix server-server\n\n/// specification.\n\n///\n\n/// # Parameters\n\n///\n\n/// object: A JSON object to generate a reference hash for.\n\n///\n\n/// # Errors\n\n///\n\n/// Returns an error if redaction fails.\n\npub fn reference_hash(\n\n value: &CanonicalJsonObject,\n\n version: &RoomVersionId,\n\n) -> Result<String, Error> {\n\n let redacted_value = redact(value, version)?;\n\n\n\n let json =\n\n canonical_json_with_fields_to_remove(&redacted_value, REFERENCE_HASH_FIELDS_TO_REMOVE);\n\n\n\n let hash = Sha256::digest(json.as_bytes());\n\n\n\n Ok(encode_config(\n\n &hash,\n\n match version {\n\n RoomVersionId::Version1 | RoomVersionId::Version2 | RoomVersionId::Version3 => {\n\n STANDARD_NO_PAD\n\n }\n\n // Room versions higher than version 3 are url safe base64 encoded\n\n _ => URL_SAFE_NO_PAD,\n\n },\n\n ))\n\n}\n\n\n", "file_path": "crates/ruma-signatures/src/functions.rs", "rank": 15, "score": 208405.45751399023 }, { "content": "#[test]\n\nfn deserialize_struct() {\n\n let de = Params { a: 10, b: \"Hello\", c: None };\n\n assert_eq!(urlencoded::from_str(\"a=10&b=Hello\"), Ok(de));\n\n assert_eq!(urlencoded::from_str(\"b=Hello&a=10\"), Ok(de));\n\n assert_eq!(urlencoded::from_str(\"a=10&b=Hello&d=1&d=2\"), Ok(de));\n\n}\n\n\n", "file_path": "crates/ruma-serde/tests/url_deserialize.rs", "rank": 16, "score": 200599.21787736774 }, { "content": "#[test]\n\nfn deserialize_reader() {\n\n let result = vec![(\"first\".to_owned(), 23), (\"last\".to_owned(), 42)];\n\n\n\n assert_eq!(urlencoded::from_reader(b\"first=23&last=42\" as &[_]), Ok(result));\n\n}\n\n\n", "file_path": "crates/ruma-serde/tests/url_deserialize.rs", "rank": 17, "score": 200599.21787736774 }, { "content": "#[test]\n\nfn deserialize_unit() {\n\n assert_eq!(urlencoded::from_str(\"\"), Ok(()));\n\n assert_eq!(urlencoded::from_str(\"&\"), Ok(()));\n\n assert_eq!(urlencoded::from_str(\"&&\"), Ok(()));\n\n assert!(urlencoded::from_str::<()>(\"first=23\").is_err());\n\n}\n\n\n", "file_path": "crates/ruma-serde/tests/url_deserialize.rs", "rank": 18, "score": 200599.21787736774 }, { "content": "#[test]\n\nfn deserialize_numlist() {\n\n let de = NumList { list: vec![1, 2, 3, 4] };\n\n assert_eq!(urlencoded::from_str(\"list=1&list=2&list=3&list=4\"), Ok(de));\n\n}\n\n\n", "file_path": "crates/ruma-serde/tests/url_deserialize.rs", "rank": 19, "score": 200599.21787736774 }, { "content": "#[test]\n\nfn deserialize_bytes() {\n\n let result = vec![(\"first\".to_owned(), 23), (\"last\".to_owned(), 42)];\n\n\n\n assert_eq!(urlencoded::from_bytes(b\"first=23&last=42\"), Ok(result));\n\n}\n\n\n", "file_path": "crates/ruma-serde/tests/url_deserialize.rs", "rank": 20, "score": 200599.21787736774 }, { "content": "#[test]\n\nfn deserialize_newstruct() {\n\n let de = NewStruct { list: vec![\"hello\", \"world\"] };\n\n assert_eq!(urlencoded::from_str(\"list=hello&list=world\"), Ok(de));\n\n}\n\n\n", "file_path": "crates/ruma-serde/tests/url_deserialize.rs", "rank": 21, "score": 200599.21787736774 }, { "content": "#[test]\n\nfn deserialize_str() {\n\n let result = vec![(\"first\".to_owned(), 23), (\"last\".to_owned(), 42)];\n\n\n\n assert_eq!(urlencoded::from_str(\"first=23&last=42\"), Ok(result));\n\n}\n\n\n", "file_path": "crates/ruma-serde/tests/url_deserialize.rs", "rank": 22, "score": 200599.21787736774 }, { "content": "#[test]\n\nfn deserialize_option() {\n\n let result = vec![(\"first\".to_owned(), Some(23)), (\"last\".to_owned(), Some(42))];\n\n assert_eq!(urlencoded::from_str(\"first=23&last=42\"), Ok(result));\n\n}\n\n\n", "file_path": "crates/ruma-serde/tests/url_deserialize.rs", "rank": 23, "score": 200599.21787736774 }, { "content": "#[test]\n\nfn deserialize_list_of_option() {\n\n assert_eq!(\n\n urlencoded::from_str(\"list=10&list=100\"),\n\n Ok(vec![(\"list\", vec![Some(10), Some(100)])])\n\n );\n\n}\n\n\n", "file_path": "crates/ruma-serde/tests/url_deserialize.rs", "rank": 24, "score": 197945.3073533554 }, { "content": "#[test]\n\nfn deserialize_unit_enum() {\n\n let result: Vec<(String, X)> = urlencoded::from_str(\"one=A&two=B&three=C\").unwrap();\n\n\n\n assert_eq!(result.len(), 3);\n\n assert!(result.contains(&(\"one\".to_owned(), X::A)));\n\n assert!(result.contains(&(\"two\".to_owned(), X::B)));\n\n assert!(result.contains(&(\"three\".to_owned(), X::C)));\n\n}\n\n\n", "file_path": "crates/ruma-serde/tests/url_deserialize.rs", "rank": 25, "score": 197945.3073533554 }, { "content": "#[test]\n\nfn deserialize_borrowed_str() {\n\n let result = vec![(\"first\", 23), (\"last\", 42)];\n\n\n\n assert_eq!(urlencoded::from_str(\"first=23&last=42\"), Ok(result));\n\n}\n\n\n", "file_path": "crates/ruma-serde/tests/url_deserialize.rs", "rank": 26, "score": 197945.3073533554 }, { "content": "#[test]\n\nfn deserialize_nested_list() {\n\n assert!(urlencoded::from_str::<Vec<(&str, Vec<Vec<bool>>)>>(\"a=b\").is_err());\n\n}\n\n\n", "file_path": "crates/ruma-serde/tests/url_deserialize.rs", "rank": 27, "score": 197945.3073533554 }, { "content": "#[test]\n\nfn deserialize_multiple_lists() {\n\n #[derive(Debug, PartialEq, Deserialize)]\n\n struct Lists {\n\n xs: Vec<bool>,\n\n ys: Vec<u32>,\n\n }\n\n\n\n assert_eq!(\n\n urlencoded::from_str(\"xs=true&xs=false&ys=3&ys=2&ys=1\"),\n\n Ok(Lists { xs: vec![true, false], ys: vec![3, 2, 1] })\n\n );\n\n\n\n assert_eq!(\n\n urlencoded::from_str(\"ys=3&xs=true&ys=2&xs=false&ys=1\"),\n\n Ok(Lists { xs: vec![true, false], ys: vec![3, 2, 1] })\n\n );\n\n}\n\n\n", "file_path": "crates/ruma-serde/tests/url_deserialize.rs", "rank": 28, "score": 197945.3073533554 }, { "content": "#[test]\n\nfn deserialize_list_of_enum() {\n\n assert_eq!(\n\n urlencoded::from_str(\"item=A&item=B&item=C\"),\n\n Ok(vec![(\"item\", vec![X::A, X::B, X::C])])\n\n );\n\n}\n\n\n", "file_path": "crates/ruma-serde/tests/url_deserialize.rs", "rank": 29, "score": 197945.3073533554 }, { "content": "#[test]\n\nfn deserialize_list_of_newtype() {\n\n assert_eq!(urlencoded::from_str(\"list=test\"), Ok(vec![(\"list\", vec![NewType(\"test\")])]));\n\n}\n\n\n", "file_path": "crates/ruma-serde/tests/url_deserialize.rs", "rank": 30, "score": 197945.3073533554 }, { "content": "#[test]\n\nfn deserialize_list_of_str() {\n\n // TODO: It would make sense to support this.\n\n assert_matches!(\n\n urlencoded::from_str::<Vec<(&str, &str)>>(\"a=a&a=b\"),\n\n Err(error) if error.to_string().contains(\"unsupported\")\n\n );\n\n\n\n assert_eq!(urlencoded::from_str(\"a=a&a=b\"), Ok(vec![(\"a\", vec![\"a\", \"b\"])]))\n\n}\n\n\n", "file_path": "crates/ruma-serde/tests/url_deserialize.rs", "rank": 31, "score": 197945.3073533554 }, { "content": "#[test]\n\nfn deserialize_unit_type() {\n\n assert_eq!(urlencoded::from_str(\"\"), Ok(()));\n\n}\n\n\n", "file_path": "crates/ruma-serde/tests/url_deserialize.rs", "rank": 32, "score": 197945.3073533554 }, { "content": "#[test]\n\nfn deserialize_newtype_i32() {\n\n let result = vec![(\"field\".to_owned(), NewType(11))];\n\n\n\n assert_eq!(urlencoded::from_str(\"field=11\"), Ok(result));\n\n}\n\n\n", "file_path": "crates/ruma-serde/tests/url_deserialize.rs", "rank": 33, "score": 197945.3073533554 }, { "content": "#[test]\n\nfn deserialize_with_serde_attributes() {\n\n #[derive(Debug, PartialEq, Deserialize)]\n\n struct FieldsWithAttributes {\n\n #[serde(default)]\n\n xs: Vec<bool>,\n\n #[serde(default)]\n\n def: Option<u8>,\n\n #[serde(default, deserialize_with = \"ruma_serde::empty_string_as_none\")]\n\n str: Option<String>,\n\n #[serde(default)]\n\n flag: bool,\n\n }\n\n\n\n assert_eq!(\n\n urlencoded::from_str(\"xs=true&xs=false&def=3&str=&flag=true\"),\n\n Ok(FieldsWithAttributes { xs: vec![true, false], def: Some(3), str: None, flag: true })\n\n );\n\n\n\n assert_eq!(\n\n urlencoded::from_str(\"\"),\n\n Ok(FieldsWithAttributes { xs: vec![], def: None, str: None, flag: false })\n\n );\n\n}\n\n\n", "file_path": "crates/ruma-serde/tests/url_deserialize.rs", "rank": 34, "score": 197945.3073533554 }, { "content": "#[test]\n\n#[ignore]\n\nfn deserialize_nested_struct() {\n\n let mut encoder = Encoder::new(String::new());\n\n\n\n let nested = Nested { item: Inner { c: \"hello\", a: 10, b: \"bye\" } };\n\n assert_eq!(\n\n urlencoded::from_str(\n\n &encoder.append_pair(\"item\", r#\"{\"c\":\"hello\",\"a\":10,\"b\":\"bye\"}\"#).finish(),\n\n ),\n\n Ok(nested)\n\n );\n\n}\n\n\n", "file_path": "crates/ruma-serde/tests/url_deserialize.rs", "rank": 35, "score": 197945.3073533554 }, { "content": "#[test]\n\n#[ignore]\n\nfn deserialize_nested_struct_with_list() {\n\n let mut encoder = Encoder::new(String::new());\n\n\n\n let nested = Nested { item: InnerList { list: vec![1, 2, 3] } };\n\n\n\n assert_eq!(\n\n urlencoded::from_str(&encoder.append_pair(\"item\", r#\"{\"list\":[1,2,3]}\"#).finish()),\n\n Ok(nested)\n\n );\n\n}\n\n\n", "file_path": "crates/ruma-serde/tests/url_deserialize.rs", "rank": 36, "score": 195377.59539885446 }, { "content": "#[test]\n\n#[ignore]\n\nfn deserialize_nested_list_option() {\n\n let mut encoder = Encoder::new(String::new());\n\n\n\n let nested = Nested { item: InnerList { list: vec![Some(1), Some(2), None] } };\n\n assert_eq!(\n\n urlencoded::from_str(&encoder.append_pair(\"item\", r#\"{\"list\":[1,2,null]}\"#).finish()),\n\n Ok(nested)\n\n );\n\n}\n", "file_path": "crates/ruma-serde/tests/url_deserialize.rs", "rank": 37, "score": 195377.59539885446 }, { "content": "pub fn serialize<S>(\n\n response: &BTreeMap<EventId, Result<(), String>>,\n\n serializer: S,\n\n) -> Result<S::Ok, S::Error>\n\nwhere\n\n S: Serializer,\n\n{\n\n let mut map = serializer.serialize_map(Some(response.len()))?;\n\n for (key, value) in response {\n\n let wrapped_error = WrappedError {\n\n error: match value {\n\n Ok(_) => None,\n\n Err(error) => Some(error.clone()),\n\n },\n\n };\n\n map.serialize_entry(&key, &wrapped_error)?;\n\n }\n\n map.end()\n\n}\n\n\n", "file_path": "crates/ruma-federation-api/src/serde/pdu_process_response.rs", "rank": 38, "score": 191655.20597916396 }, { "content": "#[cfg(feature = \"criterion\")]\n\nfn deserialize_any_state_event(c: &mut Criterion) {\n\n let json_data = power_levels();\n\n\n\n c.bench_function(\"deserialize to `AnyStateEvent`\", |b| {\n\n b.iter(|| {\n\n let _ = serde_json::from_value::<Raw<AnyStateEvent>>(json_data.clone())\n\n .unwrap()\n\n .deserialize()\n\n .unwrap();\n\n })\n\n });\n\n}\n\n\n", "file_path": "crates/ruma-events/benches/event_deserialize.rs", "rank": 39, "score": 185999.51852810895 }, { "content": "#[cfg(feature = \"criterion\")]\n\nfn deserialize_specific_event(c: &mut Criterion) {\n\n let json_data = power_levels();\n\n\n\n c.bench_function(\"deserialize to `StateEvent<PowerLevelsEventContent>`\", |b| {\n\n b.iter(|| {\n\n let _ = serde_json::from_value::<Raw<StateEvent<PowerLevelsEventContent>>>(\n\n json_data.clone(),\n\n )\n\n .unwrap()\n\n .deserialize()\n\n .unwrap();\n\n })\n\n });\n\n}\n\n\n\n#[cfg(feature = \"criterion\")]\n\ncriterion_group!(\n\n benches,\n\n deserialize_any_room_event,\n\n deserialize_any_state_event,\n\n deserialize_specific_event\n\n);\n\n\n\n#[cfg(feature = \"criterion\")]\n\ncriterion_main!(benches);\n\n\n", "file_path": "crates/ruma-events/benches/event_deserialize.rs", "rank": 40, "score": 185999.51852810895 }, { "content": "#[cfg(feature = \"criterion\")]\n\nfn deserialize_any_room_event(c: &mut Criterion) {\n\n let json_data = power_levels();\n\n\n\n c.bench_function(\"deserialize to `AnyRoomEvent`\", |b| {\n\n b.iter(|| {\n\n let _ = serde_json::from_value::<Raw<AnyRoomEvent>>(json_data.clone())\n\n .unwrap()\n\n .deserialize()\n\n .unwrap();\n\n })\n\n });\n\n}\n\n\n", "file_path": "crates/ruma-events/benches/event_deserialize.rs", "rank": 41, "score": 185999.51852810895 }, { "content": "#[cfg(not(feature = \"criterion\"))]\n\nfn main() {\n\n // To run the benchmarks the \"criterion\" feature must be enabled use:\n\n // `cargo bench --features criterion --bench event_deserialize`\n\n panic!(\"Enable the criterion feature to run benchmarks\");\n\n}\n", "file_path": "crates/ruma-events/benches/event_deserialize.rs", "rank": 42, "score": 179683.51395381236 }, { "content": "#[test]\n\nfn deserialize_redaction() {\n\n let json_data = redaction();\n\n\n\n assert_matches!(\n\n from_json_value::<Raw<AnyMessageEvent>>(json_data)\n\n .unwrap()\n\n .deserialize()\n\n .unwrap(),\n\n AnyMessageEvent::RoomRedaction(RedactionEvent {\n\n content: RedactionEventContent { reason: Some(reas), .. },\n\n redacts,\n\n event_id,\n\n origin_server_ts,\n\n room_id,\n\n sender,\n\n unsigned,\n\n }) if reas == \"being a turd\"\n\n && event_id == event_id!(\"$h29iv0s8:example.com\")\n\n && redacts == event_id!(\"$nomore:example.com\")\n\n && origin_server_ts == MilliSecondsSinceUnixEpoch(uint!(1))\n\n && room_id == room_id!(\"!roomid:room.com\")\n\n && sender == user_id!(\"@carl:example.com\")\n\n && unsigned.is_empty()\n\n );\n\n}\n", "file_path": "crates/ruma-events/tests/redaction.rs", "rank": 43, "score": 179683.51395381236 }, { "content": "#[test]\n\nfn deserialize() {\n\n assert_eq!(from_json_value::<MyEnum>(json!(\"first\")).unwrap(), MyEnum::First);\n\n assert_eq!(from_json_value::<MyEnum>(json!(\"hello_world\")).unwrap(), MyEnum::HelloWorld);\n\n assert_eq!(\n\n from_json_value::<MyEnum>(json!(\"\\\\\\n\\\\\")).unwrap(),\n\n MyEnum::_Custom(\"\\\\\\n\\\\\".into())\n\n );\n\n}\n", "file_path": "crates/ruma-serde/tests/enum_derive.rs", "rank": 44, "score": 179683.51395381236 }, { "content": "#[test]\n\nfn deserialize_pdu_as_v1() {\n\n let json = json!({\n\n \"room_id\": \"!n8f893n9:example.com\",\n\n \"event_id\": \"$somejoinevent:matrix.org\",\n\n \"auth_events\": [\n\n [\n\n \"$abc123:matrix.org\",\n\n {\n\n \"sha256\": \"Base64EncodedSha256HashesShouldBe43BytesLong\"\n\n }\n\n ]\n\n ],\n\n \"content\": {\n\n \"key\": \"value\"\n\n },\n\n \"depth\": 12,\n\n \"event_id\": \"$a4ecee13e2accdadf56c1025:example.com\",\n\n \"hashes\": {\n\n \"sha256\": \"ThisHashCoversAllFieldsInCaseThisIsRedacted\"\n\n },\n", "file_path": "crates/ruma-events/tests/pdu.rs", "rank": 45, "score": 176448.52763990383 }, { "content": "#[test]\n\nfn redacted_aliases_deserialize() {\n\n let redacted = json!({\n\n \"event_id\": \"$h29iv0s8:example.com\",\n\n \"origin_server_ts\": 1,\n\n \"sender\": \"@carl:example.com\",\n\n \"state_key\": \"hello\",\n\n \"unsigned\": unsigned(),\n\n \"type\": \"m.room.aliases\"\n\n });\n\n\n\n let actual = to_json_value(&redacted).unwrap();\n\n\n\n assert_matches!(\n\n from_json_value::<Raw<AnySyncRoomEvent>>(actual)\n\n .unwrap()\n\n .deserialize()\n\n .unwrap(),\n\n AnySyncRoomEvent::RedactedState(AnyRedactedSyncStateEvent::RoomAliases(\n\n RedactedSyncStateEvent {\n\n content: RedactedAliasesEventContent { aliases, .. },\n\n event_id,\n\n ..\n\n },\n\n )) if event_id == event_id!(\"$h29iv0s8:example.com\")\n\n && aliases.is_none()\n\n )\n\n}\n\n\n", "file_path": "crates/ruma-events/tests/redacted.rs", "rank": 46, "score": 176448.52763990383 }, { "content": "#[test]\n\n#[cfg(not(feature = \"unstable-pre-spec\"))]\n\nfn edit_deserialization_061() {\n\n let json_data = json!({\n\n \"body\": \"s/foo/bar\",\n\n \"msgtype\": \"m.text\",\n\n \"m.relates_to\": {\n\n \"rel_type\": \"m.replace\",\n\n \"event_id\": event_id!(\"$1598361704261elfgc:localhost\"),\n\n },\n\n \"m.new_content\": {\n\n \"body\": \"bar\",\n\n },\n\n });\n\n\n\n assert_matches!(\n\n from_json_value::<MessageEventContent>(json_data).unwrap(),\n\n MessageEventContent {\n\n msgtype: MessageType::Text(TextMessageEventContent {\n\n body,\n\n formatted: None,\n\n ..\n\n }),\n\n relates_to: None,\n\n ..\n\n } if body == \"s/foo/bar\"\n\n );\n\n}\n\n\n", "file_path": "crates/ruma-events/tests/room_message.rs", "rank": 47, "score": 176448.52763990383 }, { "content": "#[test]\n\nfn message_event_deserialization() {\n\n let json_data = message_event();\n\n\n\n assert_matches!(\n\n from_json_value::<AnyRoomEvent>(json_data),\n\n Ok(AnyRoomEvent::Message(\n\n AnyMessageEvent::RoomMessage(MessageEvent {\n\n content: MessageEventContent {\n\n msgtype: MessageType::Text(TextMessageEventContent {\n\n body,\n\n formatted: Some(formatted),\n\n ..\n\n }),\n\n ..\n\n },\n\n ..\n\n })\n\n ))\n\n if body == \"baba\" && formatted.body == \"<strong>baba</strong>\"\n\n );\n\n}\n\n\n", "file_path": "crates/ruma-events/tests/enums.rs", "rank": 48, "score": 176448.52763990383 }, { "content": "#[test]\n\nfn redacted_deserialize_any_room() {\n\n let redacted = json!({\n\n \"event_id\": \"$h29iv0s8:example.com\",\n\n \"room_id\": \"!roomid:room.com\",\n\n \"origin_server_ts\": 1,\n\n \"sender\": \"@carl:example.com\",\n\n \"unsigned\": unsigned(),\n\n \"type\": \"m.room.message\"\n\n });\n\n\n\n let actual = to_json_value(&redacted).unwrap();\n\n\n\n assert_matches!(\n\n from_json_value::<Raw<AnyRoomEvent>>(actual)\n\n .unwrap()\n\n .deserialize()\n\n .unwrap(),\n\n AnyRoomEvent::RedactedMessage(AnyRedactedMessageEvent::RoomMessage(RedactedMessageEvent {\n\n content: RedactedMessageEventContent { .. },\n\n event_id, room_id, ..\n\n })) if event_id == event_id!(\"$h29iv0s8:example.com\")\n\n && room_id == room_id!(\"!roomid:room.com\")\n\n )\n\n}\n\n\n", "file_path": "crates/ruma-events/tests/redacted.rs", "rank": 49, "score": 176448.52763990383 }, { "content": "#[test]\n\nfn alias_event_deserialization() {\n\n let json_data = aliases_event();\n\n\n\n assert_matches!(\n\n from_json_value::<AnyRoomEvent>(json_data),\n\n Ok(AnyRoomEvent::State(\n\n AnyStateEvent::RoomAliases(StateEvent {\n\n content: AliasesEventContent {\n\n aliases,\n\n ..\n\n },\n\n ..\n\n })\n\n ))\n\n if aliases == vec![ room_alias_id!(\"#somewhere:localhost\") ]\n\n );\n\n}\n\n\n", "file_path": "crates/ruma-events/tests/enums.rs", "rank": 50, "score": 176448.52763990383 }, { "content": "#[test]\n\nfn ephemeral_event_deserialization() {\n\n let json_data = json!({\n\n \"content\": {\n\n \"user_ids\": [\n\n \"@alice:matrix.org\",\n\n \"@bob:example.com\"\n\n ]\n\n },\n\n \"room_id\": \"!jEsUZKDJdhlrceRyVU:example.org\",\n\n \"type\": \"m.typing\"\n\n });\n\n\n\n assert_matches!(\n\n from_json_value::<AnyEphemeralRoomEvent>(json_data),\n\n Ok(ephem @ AnyEphemeralRoomEvent::Typing(_))\n\n if ephem.room_id() == &room_id!(\"!jEsUZKDJdhlrceRyVU:example.org\")\n\n );\n\n}\n\n\n", "file_path": "crates/ruma-events/tests/enums.rs", "rank": 51, "score": 176448.52763990383 }, { "content": "#[cfg(not(feature = \"unstable-pre-spec\"))]\n\n#[test]\n\nfn deserialize_pdu_as_v3() {\n\n let json = json!({\n\n \"room_id\": \"!n8f893n9:example.com\",\n\n \"auth_events\": [\n\n \"$abc123:matrix.org\"\n\n ],\n\n \"content\": {\n\n \"key\": \"value\"\n\n },\n\n \"depth\": 12,\n\n \"event_id\": \"$a4ecee13e2accdadf56c1025:example.com\",\n\n \"hashes\": {\n\n \"sha256\": \"ThisHashCoversAllFieldsInCaseThisIsRedacted\"\n\n },\n\n \"origin\": \"matrix.org\",\n\n \"origin_server_ts\": 1_234_567_890,\n\n \"prev_events\": [\n\n \"$abc123:matrix.org\"\n\n ],\n\n \"redacts\": \"$def456:matrix.org\",\n", "file_path": "crates/ruma-events/tests/pdu.rs", "rank": 52, "score": 176448.52763990383 }, { "content": "#[test]\n\nfn content_deserialization() {\n\n let json_data = json!({\n\n \"body\": \"test\",\n\n \"msgtype\": \"m.audio\",\n\n \"url\": \"mxc://example.org/ffed755USFFxlgbQYZGtryd\"\n\n });\n\n\n\n assert_matches!(\n\n from_json_value::<Raw<MessageEventContent>>(json_data)\n\n .unwrap()\n\n .deserialize()\n\n .unwrap(),\n\n MessageEventContent {\n\n msgtype: MessageType::Audio(AudioMessageEventContent {\n\n body,\n\n info: None,\n\n url: Some(url),\n\n file: None,\n\n ..\n\n }),\n\n ..\n\n } if body == \"test\" && url.to_string() == \"mxc://example.org/ffed755USFFxlgbQYZGtryd\"\n\n );\n\n}\n\n\n", "file_path": "crates/ruma-events/tests/room_message.rs", "rank": 53, "score": 176448.52763990383 }, { "content": "pub fn expand_serialize_as_ref_str(ident: &Ident) -> syn::Result<TokenStream> {\n\n let ruma_serde = import_ruma_serde();\n\n\n\n Ok(quote! {\n\n #[automatically_derived]\n\n impl #ruma_serde::exports::serde::ser::Serialize for #ident {\n\n fn serialize<S>(&self, serializer: S) -> ::std::result::Result<S::Ok, S::Error>\n\n where\n\n S: #ruma_serde::exports::serde::ser::Serializer,\n\n {\n\n ::std::convert::AsRef::<::std::primitive::str>::as_ref(self).serialize(serializer)\n\n }\n\n }\n\n })\n\n}\n", "file_path": "crates/ruma-serde-macros/src/serialize_as_ref_str.rs", "rank": 54, "score": 174865.4233063331 }, { "content": "#[proc_macro_derive(SerializeAsRefStr)]\n\npub fn derive_serialize_as_ref_str(input: TokenStream) -> TokenStream {\n\n let input = parse_macro_input!(input as DeriveInput);\n\n expand_serialize_as_ref_str(&input.ident).unwrap_or_else(syn::Error::into_compile_error).into()\n\n}\n\n\n", "file_path": "crates/ruma-serde-macros/src/lib.rs", "rank": 55, "score": 173836.3000943662 }, { "content": "#[test]\n\nfn relates_to_content_serialization() {\n\n let message_event_content =\n\n assign!(MessageEventContent::text_plain(\"> <@test:example.com> test\\n\\ntest reply\"), {\n\n relates_to: Some(Relation::Reply {\n\n in_reply_to: InReplyTo::new(event_id!(\"$15827405538098VGFWH:example.com\")),\n\n }),\n\n });\n\n\n\n let json_data = json!({\n\n \"body\": \"> <@test:example.com> test\\n\\ntest reply\",\n\n \"msgtype\": \"m.text\",\n\n \"m.relates_to\": {\n\n \"m.in_reply_to\": {\n\n \"event_id\": \"$15827405538098VGFWH:example.com\"\n\n }\n\n }\n\n });\n\n\n\n assert_eq!(to_json_value(&message_event_content).unwrap(), json_data);\n\n}\n\n\n", "file_path": "crates/ruma-events/tests/room_message.rs", "rank": 56, "score": 173548.222372916 }, { "content": "#[test]\n\nfn deserialize_message_sticker() {\n\n let json_data = json!({\n\n \"content\": {\n\n \"body\": \"Hello\",\n\n \"info\": {\n\n \"h\": 423,\n\n \"mimetype\": \"image/png\",\n\n \"size\": 84242,\n\n \"thumbnail_info\": {\n\n \"h\": 334,\n\n \"mimetype\": \"image/png\",\n\n \"size\": 82595,\n\n \"w\": 800\n\n },\n\n \"thumbnail_url\": \"mxc://matrix.org/irnsNRS2879\",\n\n \"w\": 1011\n\n },\n\n \"url\": \"mxc://matrix.org/jxPXTKpyydzdHJkdFNZjTZrD\"\n\n },\n\n \"event_id\": \"$h29iv0s8:example.com\",\n", "file_path": "crates/ruma-events/tests/message_event.rs", "rank": 57, "score": 173351.93972763314 }, { "content": "#[test]\n\nfn deserialize_aliases_content() {\n\n let json_data = json!({\n\n \"aliases\": [ \"#somewhere:localhost\" ]\n\n });\n\n\n\n assert_matches!(\n\n from_json_value::<Raw<AnyStateEventContent>>(json_data)\n\n .unwrap()\n\n .deserialize_content(\"m.room.aliases\")\n\n .unwrap(),\n\n AnyStateEventContent::RoomAliases(content)\n\n if content.aliases == vec![room_alias_id!(\"#somewhere:localhost\")]\n\n );\n\n}\n\n\n", "file_path": "crates/ruma-events/tests/state_event.rs", "rank": 58, "score": 173351.93972763314 }, { "content": "#[test]\n\nfn power_event_sync_deserialization() {\n\n let json_data = json!({\n\n \"content\": {\n\n \"ban\": 50,\n\n \"events\": {\n\n \"m.room.avatar\": 50,\n\n \"m.room.canonical_alias\": 50,\n\n \"m.room.history_visibility\": 100,\n\n \"m.room.name\": 50,\n\n \"m.room.power_levels\": 100\n\n },\n\n \"events_default\": 0,\n\n \"invite\": 0,\n\n \"kick\": 50,\n\n \"redact\": 50,\n\n \"state_default\": 50,\n\n \"users\": {\n\n \"@example:localhost\": 100\n\n },\n\n \"users_default\": 0\n", "file_path": "crates/ruma-events/tests/enums.rs", "rank": 59, "score": 173351.93972763314 }, { "content": "#[test]\n\nfn content_deserialization_failure() {\n\n let json_data = json!({\n\n \"body\": \"test\",\"msgtype\": \"m.location\",\n\n \"url\": \"http://example.com/audio.mp3\"\n\n });\n\n assert!(from_json_value::<Raw<MessageEventContent>>(json_data).unwrap().deserialize().is_err());\n\n}\n", "file_path": "crates/ruma-events/tests/room_message.rs", "rank": 60, "score": 173351.93972763314 }, { "content": "#[test]\n\nfn deserialize_custom_state_event() {\n\n let json_data = custom_state_event();\n\n assert_matches!(from_json_value::<AnyStateEvent>(json_data), Ok(_));\n\n}\n\n\n", "file_path": "crates/ruma-events/tests/custom.rs", "rank": 61, "score": 173351.93972763314 }, { "content": "#[test]\n\nfn deserialize_stripped_state_events() {\n\n let name_event = json!({\n\n \"type\": \"m.room.name\",\n\n \"state_key\": \"\",\n\n \"sender\": \"@example:localhost\",\n\n \"content\": { \"name\": \"Ruma\" }\n\n });\n\n\n\n let join_rules_event = json!({\n\n \"type\": \"m.room.join_rules\",\n\n \"state_key\": \"\",\n\n \"sender\": \"@example:localhost\",\n\n \"content\": { \"join_rule\": \"public\" }\n\n });\n\n\n\n let avatar_event = json!({\n\n \"type\": \"m.room.avatar\",\n\n \"state_key\": \"\",\n\n \"sender\": \"@example:localhost\",\n\n \"content\": {\n", "file_path": "crates/ruma-events/tests/stripped.rs", "rank": 62, "score": 173351.93972763314 }, { "content": "#[test]\n\nfn redacted_state_event_deserialize() {\n\n let redacted = json!({\n\n \"content\": {\n\n \"creator\": \"@carl:example.com\",\n\n },\n\n \"event_id\": \"$h29iv0s8:example.com\",\n\n \"origin_server_ts\": 1,\n\n \"sender\": \"@carl:example.com\",\n\n \"state_key\": \"hello there\",\n\n \"unsigned\": unsigned(),\n\n \"type\": \"m.room.create\"\n\n });\n\n\n\n assert_matches!(\n\n from_json_value::<Raw<AnySyncRoomEvent>>(redacted)\n\n .unwrap()\n\n .deserialize()\n\n .unwrap(),\n\n AnySyncRoomEvent::RedactedState(AnyRedactedSyncStateEvent::RoomCreate(\n\n RedactedSyncStateEvent {\n", "file_path": "crates/ruma-events/tests/redacted.rs", "rank": 63, "score": 173351.93972763314 }, { "content": "#[test]\n\nfn alias_room_event_deserialization() {\n\n let json_data = aliases_event();\n\n\n\n assert_matches!(\n\n from_json_value::<AnyRoomEvent>(json_data),\n\n Ok(AnyRoomEvent::State(\n\n AnyStateEvent::RoomAliases(StateEvent {\n\n content: AliasesEventContent {\n\n aliases,\n\n ..\n\n },\n\n ..\n\n })\n\n ))\n\n if aliases == vec![ room_alias_id!(\"#somewhere:localhost\") ]\n\n );\n\n}\n\n\n", "file_path": "crates/ruma-events/tests/enums.rs", "rank": 64, "score": 173351.93972763314 }, { "content": "#[test]\n\nfn message_event_sync_deserialization() {\n\n let json_data = message_event_sync();\n\n\n\n assert_matches!(\n\n from_json_value::<AnySyncRoomEvent>(json_data),\n\n Ok(AnySyncRoomEvent::Message(\n\n AnySyncMessageEvent::RoomMessage(SyncMessageEvent {\n\n content: MessageEventContent {\n\n msgtype: MessageType::Text(TextMessageEventContent {\n\n body,\n\n formatted: Some(formatted),\n\n ..\n\n }),\n\n ..\n\n },\n\n ..\n\n })\n\n ))\n\n if body == \"baba\" && formatted.body == \"<strong>baba</strong>\"\n\n );\n\n}\n\n\n", "file_path": "crates/ruma-events/tests/enums.rs", "rank": 65, "score": 173351.93972763314 }, { "content": "#[test]\n\nfn custom_content_deserialization() {\n\n let json_data = json!({\n\n \"msgtype\": \"my_custom_msgtype\",\n\n \"custom_field\": \"baba\",\n\n \"another_one\": \"abab\",\n\n });\n\n\n\n let expected_json_data = json_object! {\n\n \"custom_field\".into() => json!(\"baba\"),\n\n \"another_one\".into() => json!(\"abab\"),\n\n };\n\n\n\n let custom_event =\n\n from_json_value::<Raw<MessageType>>(json_data).unwrap().deserialize().unwrap();\n\n\n\n assert_eq!(custom_event.msgtype(), \"my_custom_msgtype\");\n\n assert_eq!(custom_event.data(), Cow::Owned(expected_json_data));\n\n}\n\n\n", "file_path": "crates/ruma-events/tests/room_message.rs", "rank": 66, "score": 173351.93972763314 }, { "content": "#[test]\n\nfn redacted_custom_event_deserialize() {\n\n let unsigned = unsigned();\n\n\n\n let redacted = RedactedSyncStateEvent {\n\n content: RedactedCustomEventContent { event_type: \"m.made.up\".into() },\n\n event_id: event_id!(\"$h29iv0s8:example.com\"),\n\n sender: user_id!(\"@carl:example.com\"),\n\n state_key: \"hello there\".into(),\n\n origin_server_ts: MilliSecondsSinceUnixEpoch(uint!(1)),\n\n unsigned: unsigned.clone(),\n\n };\n\n\n\n let expected = json!({\n\n \"event_id\": \"$h29iv0s8:example.com\",\n\n \"origin_server_ts\": 1,\n\n \"sender\": \"@carl:example.com\",\n\n \"state_key\": \"hello there\",\n\n \"unsigned\": unsigned,\n\n \"type\": \"m.made.up\"\n\n });\n\n\n\n let actual = to_json_value(&redacted).unwrap();\n\n assert_eq!(actual, expected);\n\n}\n\n\n", "file_path": "crates/ruma-events/tests/redacted.rs", "rank": 67, "score": 173351.93972763314 }, { "content": "#[test]\n\nfn aliases_event_sync_deserialization() {\n\n let json_data = aliases_event_sync();\n\n\n\n assert_matches!(\n\n from_json_value::<AnySyncRoomEvent>(json_data),\n\n Ok(AnySyncRoomEvent::State(\n\n AnySyncStateEvent::RoomAliases(SyncStateEvent {\n\n content: AliasesEventContent {\n\n aliases,\n\n ..\n\n },\n\n ..\n\n })\n\n ))\n\n if aliases == vec![ room_alias_id!(\"#somewhere:localhost\") ]\n\n );\n\n}\n\n\n", "file_path": "crates/ruma-events/tests/enums.rs", "rank": 68, "score": 173351.93972763314 }, { "content": "#[test]\n\nfn deserialize_ephemeral_typing() {\n\n let json_data = json!({\n\n \"content\": {\n\n \"user_ids\": [ \"@carl:example.com\" ]\n\n },\n\n \"room_id\": \"!roomid:room.com\",\n\n \"type\": \"m.typing\"\n\n });\n\n\n\n assert_matches!(\n\n from_json_value::<Raw<EphemeralRoomEvent<AnyEphemeralRoomEventContent>>>(json_data)\n\n .unwrap()\n\n .deserialize()\n\n .unwrap(),\n\n EphemeralRoomEvent {\n\n content: AnyEphemeralRoomEventContent::Typing(TypingEventContent { user_ids, .. }),\n\n room_id,\n\n } if user_ids[0] == user_id!(\"@carl:example.com\")\n\n && room_id == room_id!(\"!roomid:room.com\")\n\n );\n\n}\n\n\n", "file_path": "crates/ruma-events/tests/ephemeral_event.rs", "rank": 69, "score": 173351.93972763314 }, { "content": "fn expand_deserialize_event(\n\n input: &DeriveInput,\n\n var: &EventKindVariation,\n\n fields: &[Field],\n\n ruma_events: &TokenStream,\n\n) -> syn::Result<TokenStream> {\n\n let serde = quote! { #ruma_events::exports::serde };\n\n let serde_json = quote! { #ruma_events::exports::serde_json };\n\n\n\n let ident = &input.ident;\n\n // we know there is a content field already\n\n let content_type = fields\n\n .iter()\n\n // we also know that the fields are named and have an ident\n\n .find(|f| f.ident.as_ref().unwrap() == \"content\")\n\n .map(|f| f.ty.clone())\n\n .unwrap();\n\n\n\n let (impl_generics, ty_gen, where_clause) = input.generics.split_for_impl();\n\n let is_generic = !input.generics.params.is_empty();\n", "file_path": "crates/ruma-events-macros/src/event.rs", "rank": 70, "score": 173351.93972763314 }, { "content": "#[test]\n\nfn deserialize_ephemeral_receipt() {\n\n let event_id = event_id!(\"$h29iv0s8:example.com\");\n\n let user_id = user_id!(\"@carl:example.com\");\n\n\n\n let json_data = json!({\n\n \"content\": {\n\n \"$h29iv0s8:example.com\": {\n\n \"m.read\": {\n\n \"@carl:example.com\": { \"ts\": 1 }\n\n }\n\n }\n\n },\n\n \"room_id\": \"!roomid:room.com\",\n\n \"type\": \"m.receipt\"\n\n });\n\n\n\n assert_matches!(\n\n from_json_value::<Raw<EphemeralRoomEvent<AnyEphemeralRoomEventContent>>>(json_data)\n\n .unwrap()\n\n .deserialize()\n", "file_path": "crates/ruma-events/tests/ephemeral_event.rs", "rank": 71, "score": 173351.93972763314 }, { "content": "#[test]\n\nfn message_room_event_deserialization() {\n\n let json_data = message_event();\n\n\n\n assert_matches!(\n\n from_json_value::<AnyRoomEvent>(json_data),\n\n Ok(AnyRoomEvent::Message(\n\n AnyMessageEvent::RoomMessage(MessageEvent {\n\n content: MessageEventContent {\n\n msgtype: MessageType::Text(TextMessageEventContent {\n\n body,\n\n formatted: Some(formatted),\n\n ..\n\n }),\n\n ..\n\n },\n\n ..\n\n })\n\n ))\n\n if body == \"baba\" && formatted.body == \"<strong>baba</strong>\"\n\n );\n\n}\n\n\n", "file_path": "crates/ruma-events/tests/enums.rs", "rank": 72, "score": 173351.93972763314 }, { "content": "#[test]\n\nfn deserialize_message_event() {\n\n let json_data = json!({\n\n \"content\": {\n\n \"answer\": {\n\n \"type\": \"answer\",\n\n \"sdp\": \"Hello\"\n\n },\n\n \"call_id\": \"foofoo\",\n\n \"version\": 1\n\n },\n\n \"event_id\": \"$h29iv0s8:example.com\",\n\n \"origin_server_ts\": 1,\n\n \"room_id\": \"!roomid:room.com\",\n\n \"sender\": \"@carl:example.com\",\n\n \"type\": \"m.call.answer\"\n\n });\n\n\n\n assert_matches!(\n\n from_json_value::<AnyMessageEvent>(json_data)\n\n .unwrap(),\n", "file_path": "crates/ruma-events/tests/event_enums.rs", "rank": 73, "score": 173351.93972763314 }, { "content": "#[test]\n\nfn redacted_deserialize_any_room_sync() {\n\n let mut unsigned = RedactedUnsigned::default();\n\n // The presence of `redacted_because` triggers the event enum (AnySyncRoomEvent in this case)\n\n // to return early with `RedactedContent` instead of failing to deserialize according\n\n // to the event type string.\n\n unsigned.redacted_because = Some(Box::new(SyncRedactionEvent {\n\n content: RedactionEventContent::with_reason(\"redacted because\".into()),\n\n redacts: event_id!(\"$h29iv0s8:example.com\"),\n\n event_id: event_id!(\"$h29iv0s8:example.com\"),\n\n origin_server_ts: MilliSecondsSinceUnixEpoch(uint!(1)),\n\n sender: user_id!(\"@carl:example.com\"),\n\n unsigned: Unsigned::default(),\n\n }));\n\n\n\n let redacted = json!({\n\n \"event_id\": \"$h29iv0s8:example.com\",\n\n \"origin_server_ts\": 1,\n\n \"sender\": \"@carl:example.com\",\n\n \"unsigned\": unsigned,\n\n \"type\": \"m.room.message\"\n", "file_path": "crates/ruma-events/tests/redacted.rs", "rank": 74, "score": 173351.93972763314 }, { "content": "#[test]\n\n#[cfg(feature = \"unstable-pre-spec\")]\n\nfn verification_request_deserialization() {\n\n let user_id = user_id!(\"@example2:localhost\");\n\n let device_id: DeviceIdBox = \"XOWLHHFSWM\".into();\n\n\n\n let json_data = json!({\n\n \"body\": \"@example:localhost is requesting to verify your key, ...\",\n\n \"msgtype\": \"m.key.verification.request\",\n\n \"to\": user_id,\n\n \"from_device\": device_id,\n\n \"methods\": [\n\n \"m.sas.v1\",\n\n \"m.qr_code.show.v1\",\n\n \"m.reciprocate.v1\"\n\n ]\n\n });\n\n\n\n assert_matches!(\n\n from_json_value::<MessageEventContent>(json_data).unwrap(),\n\n MessageEventContent {\n\n msgtype: MessageType::VerificationRequest(KeyVerificationRequestEventContent {\n", "file_path": "crates/ruma-events/tests/room_message.rs", "rank": 75, "score": 173351.93972763314 }, { "content": "#[test]\n\n#[cfg(feature = \"unstable-pre-spec\")]\n\nfn edit_deserialization_future() {\n\n use ruma_events::room::message::Replacement;\n\n\n\n let ev_id = event_id!(\"$1598361704261elfgc:localhost\");\n\n let json_data = json!({\n\n \"body\": \"s/foo/bar\",\n\n \"msgtype\": \"m.text\",\n\n \"m.relates_to\": {\n\n \"rel_type\": \"m.replace\",\n\n \"event_id\": ev_id,\n\n },\n\n \"m.new_content\": {\n\n \"body\": \"bar\",\n\n \"msgtype\": \"m.text\",\n\n },\n\n });\n\n\n\n assert_matches!(\n\n from_json_value::<MessageEventContent>(json_data).unwrap(),\n\n MessageEventContent {\n", "file_path": "crates/ruma-events/tests/room_message.rs", "rank": 76, "score": 173351.93972763314 }, { "content": "#[test]\n\nfn registration_deserialization() {\n\n let registration_config = r##\"\n\n id: \"IRC Bridge\"\n\n url: \"http://127.0.0.1:1234\"\n\n as_token: \"30c05ae90a248a4188e620216fa72e349803310ec83e2a77b34fe90be6081f46\"\n\n hs_token: \"312df522183efd404ec1cd22d2ffa4bbc76a8c1ccf541dd692eef281356bb74e\"\n\n sender_localpart: \"_irc_bot\"\n\n namespaces:\n\n users:\n\n - exclusive: true\n\n regex: \"@_irc_bridge_.*\"\n\n aliases:\n\n - exclusive: false\n\n regex: \"#_irc_bridge_.*\"\n\n rooms: []\n\n \"##;\n\n let observed = serde_yaml::from_str(registration_config).unwrap();\n\n assert_matches!(\n\n observed,\n\n Registration {\n", "file_path": "crates/ruma-appservice-api/tests/appservice_registration.rs", "rank": 77, "score": 173351.93972763314 }, { "content": "#[test]\n\nfn deserialize_custom_state_sync_event() {\n\n let json_data = custom_state_event();\n\n assert_matches!(from_json_value::<AnySyncStateEvent>(json_data), Ok(_));\n\n}\n\n\n", "file_path": "crates/ruma-events/tests/custom.rs", "rank": 78, "score": 170385.05482860998 }, { "content": "#[test]\n\nfn deserialize_message_then_convert_to_full() {\n\n let rid = room_id!(\"!roomid:room.com\");\n\n let json_data = json!({\n\n \"content\": {\n\n \"answer\": {\n\n \"type\": \"answer\",\n\n \"sdp\": \"Hello\"\n\n },\n\n \"call_id\": \"foofoo\",\n\n \"version\": 1\n\n },\n\n \"event_id\": \"$h29iv0s8:example.com\",\n\n \"origin_server_ts\": 1,\n\n \"sender\": \"@carl:example.com\",\n\n \"type\": \"m.call.answer\"\n\n });\n\n\n\n let sync_ev =\n\n from_json_value::<Raw<AnySyncMessageEvent>>(json_data).unwrap().deserialize().unwrap();\n\n\n", "file_path": "crates/ruma-events/tests/message_event.rs", "rank": 79, "score": 170385.05482860998 }, { "content": "#[test]\n\nfn deserialize_initial_state_event() {\n\n assert_matches!(\n\n serde_json::from_value(json!({\n\n \"type\": \"m.room.name\",\n\n \"content\": { \"name\": \"foo\" }\n\n }))\n\n .unwrap(),\n\n AnyInitialStateEvent::RoomName(InitialStateEvent { content, state_key})\n\n if content.name() == Some(\"foo\") && state_key.is_empty()\n\n );\n\n}\n", "file_path": "crates/ruma-events/tests/initial_state.rs", "rank": 80, "score": 170385.05482860998 }, { "content": "#[test]\n\nfn deserialize_message_call_answer() {\n\n let json_data = json!({\n\n \"content\": {\n\n \"answer\": {\n\n \"type\": \"answer\",\n\n \"sdp\": \"Hello\"\n\n },\n\n \"call_id\": \"foofoo\",\n\n \"version\": 1\n\n },\n\n \"event_id\": \"$h29iv0s8:example.com\",\n\n \"origin_server_ts\": 1,\n\n \"room_id\": \"!roomid:room.com\",\n\n \"sender\": \"@carl:example.com\",\n\n \"type\": \"m.call.answer\"\n\n });\n\n\n\n assert_matches!(\n\n from_json_value::<Raw<MessageEvent<AnyMessageEventContent>>>(json_data)\n\n .unwrap()\n", "file_path": "crates/ruma-events/tests/message_event.rs", "rank": 81, "score": 170385.05482860998 }, { "content": "#[test]\n\nfn deserialize_aliases_with_prev_content() {\n\n let json_data = aliases_event_with_prev_content();\n\n\n\n assert_matches!(\n\n from_json_value::<Raw<StateEvent<AnyStateEventContent>>>(json_data)\n\n .unwrap()\n\n .deserialize()\n\n .unwrap(),\n\n StateEvent {\n\n content: AnyStateEventContent::RoomAliases(content),\n\n event_id,\n\n origin_server_ts,\n\n prev_content: Some(AnyStateEventContent::RoomAliases(prev_content)),\n\n room_id,\n\n sender,\n\n state_key,\n\n unsigned,\n\n } if content.aliases == vec![room_alias_id!(\"#somewhere:localhost\")]\n\n && event_id == event_id!(\"$h29iv0s8:example.com\")\n\n && origin_server_ts == MilliSecondsSinceUnixEpoch(uint!(1))\n\n && prev_content.aliases == vec![room_alias_id!(\"#inner:localhost\")]\n\n && room_id == room_id!(\"!roomid:room.com\")\n\n && sender == user_id!(\"@carl:example.com\")\n\n && state_key.is_empty()\n\n && unsigned.is_empty()\n\n );\n\n}\n\n\n", "file_path": "crates/ruma-events/tests/state_event.rs", "rank": 82, "score": 170385.05482860998 }, { "content": "fn get_deserialize_levels(\n\n old: &serde_json::Value,\n\n new: &serde_json::Value,\n\n name: &str,\n\n) -> Option<(i64, i64)> {\n\n Some((\n\n serde_json::from_value(old.get(name)?.clone()).ok()?,\n\n serde_json::from_value(new.get(name)?.clone()).ok()?,\n\n ))\n\n}\n\n\n", "file_path": "crates/ruma-state-res/src/event_auth.rs", "rank": 83, "score": 170385.05482860998 }, { "content": "#[test]\n\nfn deserialize_custom_message_sync_event() {\n\n let json_data = json!({\n\n \"content\": {\n\n \"body\": \"👍\"\n\n },\n\n \"event_id\": \"$h29iv0s8:example.com\",\n\n \"origin_server_ts\": 10,\n\n \"room_id\": \"!room:room.com\",\n\n \"sender\": \"@carl:example.com\",\n\n \"type\": \"m.ruma_custom\",\n\n \"unsigned\": {\n\n \"age\": 85\n\n }\n\n });\n\n\n\n assert_matches!(\n\n from_json_value::<AnySyncRoomEvent>(json_data),\n\n Ok(AnySyncRoomEvent::Message(_))\n\n );\n\n}\n", "file_path": "crates/ruma-events/tests/custom.rs", "rank": 84, "score": 170385.05482860998 }, { "content": "#[test]\n\nfn deserialize_aliases_sync_with_room_id() {\n\n // The same JSON can be used to create a sync event, it just ignores the `room_id` field\n\n let json_data = aliases_event_with_prev_content();\n\n\n\n assert_matches!(\n\n from_json_value::<SyncStateEvent<AnyStateEventContent>>(json_data)\n\n .unwrap(),\n\n SyncStateEvent {\n\n content: AnyStateEventContent::RoomAliases(content),\n\n event_id,\n\n origin_server_ts,\n\n prev_content: Some(AnyStateEventContent::RoomAliases(prev_content)),\n\n sender,\n\n state_key,\n\n unsigned,\n\n } if content.aliases == vec![room_alias_id!(\"#somewhere:localhost\")]\n\n && event_id == event_id!(\"$h29iv0s8:example.com\")\n\n && origin_server_ts == MilliSecondsSinceUnixEpoch(uint!(1))\n\n && prev_content.aliases == vec![room_alias_id!(\"#inner:localhost\")]\n\n && sender == user_id!(\"@carl:example.com\")\n\n && state_key.is_empty()\n\n && unsigned.is_empty()\n\n );\n\n}\n\n\n", "file_path": "crates/ruma-events/tests/state_event.rs", "rank": 85, "score": 167539.8910383521 }, { "content": "#[test]\n\nfn deserialize_avatar_without_prev_content() {\n\n let json_data = json!({\n\n \"content\": {\n\n \"info\": {\n\n \"h\": 423,\n\n \"mimetype\": \"image/png\",\n\n \"size\": 84242,\n\n \"thumbnail_info\": {\n\n \"h\": 334,\n\n \"mimetype\": \"image/png\",\n\n \"size\": 82595,\n\n \"w\": 800\n\n },\n\n \"thumbnail_url\": \"mxc://matrix.org/98irRSS23srs\",\n\n \"w\": 1011\n\n },\n\n \"url\": \"mxc://matrix.org/rnsldl8srs98IRrs\"\n\n },\n\n \"event_id\": \"$h29iv0s8:example.com\",\n\n \"origin_server_ts\": 1,\n", "file_path": "crates/ruma-events/tests/state_event.rs", "rank": 86, "score": 167539.8910383521 }, { "content": "#[test]\n\nfn deserialize_full_event_convert_to_sync() {\n\n let json_data = aliases_event_with_prev_content();\n\n\n\n let full_ev = from_json_value::<Raw<AnyStateEvent>>(json_data).unwrap().deserialize().unwrap();\n\n\n\n // Test conversion to sync event (without room_id field)\n\n let sync: AnySyncStateEvent = full_ev.into();\n\n let sync_json = to_json_value(sync).unwrap();\n\n\n\n assert_matches!(\n\n from_json_value::<Raw<AnySyncStateEvent>>(sync_json)\n\n .unwrap()\n\n .deserialize()\n\n .unwrap(),\n\n AnySyncStateEvent::RoomAliases(SyncStateEvent {\n\n content,\n\n event_id,\n\n origin_server_ts,\n\n prev_content: Some(prev_content),\n\n sender,\n", "file_path": "crates/ruma-events/tests/state_event.rs", "rank": 87, "score": 167539.8910383521 }, { "content": "#[test]\n\nfn deserialize_message_call_answer_content() {\n\n let json_data = json!({\n\n \"answer\": {\n\n \"type\": \"answer\",\n\n \"sdp\": \"Hello\"\n\n },\n\n \"call_id\": \"foofoo\",\n\n \"version\": 1\n\n });\n\n\n\n assert_matches!(\n\n from_json_value::<Raw<AnyMessageEventContent>>(json_data)\n\n .unwrap()\n\n .deserialize_content(\"m.call.answer\")\n\n .unwrap(),\n\n AnyMessageEventContent::CallAnswer(AnswerEventContent {\n\n answer: SessionDescription {\n\n session_type: SessionDescriptionType::Answer,\n\n sdp,\n\n ..\n\n },\n\n call_id,\n\n version,\n\n ..\n\n }) if sdp == \"Hello\" && call_id == \"foofoo\" && version == UInt::new(1).unwrap()\n\n );\n\n}\n\n\n", "file_path": "crates/ruma-events/tests/message_event.rs", "rank": 88, "score": 167539.89103835216 }, { "content": "/// Serializes a Duration to an integer representing seconds.\n\n///\n\n/// Will fail if integer is greater than the maximum integer that can be\n\n/// unambiguously represented by an f64.\n\npub fn serialize<S>(duration: &Duration, serializer: S) -> Result<S::Ok, S::Error>\n\nwhere\n\n S: Serializer,\n\n{\n\n match UInt::try_from(duration.as_secs()) {\n\n Ok(uint) => uint.serialize(serializer),\n\n Err(err) => Err(S::Error::custom(err)),\n\n }\n\n}\n\n\n", "file_path": "crates/ruma-serde/src/duration/secs.rs", "rank": 89, "score": 166653.4417449972 }, { "content": "pub fn event_id(id: &str) -> EventId {\n\n if id.contains('$') {\n\n return EventId::try_from(id).unwrap();\n\n }\n\n EventId::try_from(format!(\"${}:foo\", id)).unwrap()\n\n}\n\n\n", "file_path": "crates/ruma-state-res/tests/utils.rs", "rank": 90, "score": 166393.0654614525 }, { "content": "/// Returns a canonical JSON string according to Matrix specification.\n\n///\n\n/// This function should be preferred over `serde_json::to_string` since it checks the size of the\n\n/// canonical string. Matrix canonical JSON enforces a size limit of less than 65,535 when sending\n\n/// PDU's for the server-server protocol.\n\npub fn to_string<T: Serialize>(val: &T) -> Result<String, Error> {\n\n let s = serde_json::to_string(val).map_err(Error::SerDe)?;\n\n\n\n if s.as_bytes().len() > 65_535 {\n\n Err(Error::JsonSize)\n\n } else {\n\n Ok(s)\n\n }\n\n}\n\n\n\n/// The set of possible errors when serializing to canonical JSON.\n\n#[derive(Debug)]\n\npub enum Error {\n\n /// The numeric value failed conversion to js_int::Int.\n\n IntConvert,\n\n\n\n /// The `CanonicalJsonValue` being serialized was larger than 65,535 bytes.\n\n JsonSize,\n\n\n\n /// An error occurred while serializing/deserializing.\n", "file_path": "crates/ruma-serde/src/canonical_json.rs", "rank": 91, "score": 165385.1033488227 }, { "content": "#[proc_macro]\n\npub fn event_id(input: TokenStream) -> TokenStream {\n\n let Input { dollar_crate, id } = parse_macro_input!(input as Input);\n\n assert!(event_id::validate(&id.value()).is_ok(), \"Invalid event id\");\n\n\n\n let output = quote! {\n\n <#dollar_crate::EventId as ::std::convert::TryFrom<&str>>::try_from(#id).unwrap()\n\n };\n\n\n\n output.into()\n\n}\n\n\n", "file_path": "crates/ruma-identifiers-macros/src/lib.rs", "rank": 92, "score": 164717.63768767263 }, { "content": "/// Serialize the given value as a JSON string.\n\npub fn serialize<T, S>(value: T, serializer: S) -> Result<S::Ok, S::Error>\n\nwhere\n\n T: Serialize,\n\n S: Serializer,\n\n{\n\n let json = serde_json::to_string(&value).map_err(S::Error::custom)?;\n\n serializer.serialize_str(&json)\n\n}\n\n\n", "file_path": "crates/ruma-serde/src/json_string.rs", "rank": 93, "score": 163121.16398110386 }, { "content": "fn power_levels() -> serde_json::Value {\n\n json!({\n\n \"content\": {\n\n \"ban\": 50,\n\n \"events\": {\n\n \"m.room.avatar\": 50,\n\n \"m.room.canonical_alias\": 50,\n\n \"m.room.history_visibility\": 100,\n\n \"m.room.name\": 50,\n\n \"m.room.power_levels\": 100\n\n },\n\n \"events_default\": 0,\n\n \"invite\": 0,\n\n \"kick\": 50,\n\n \"redact\": 50,\n\n \"state_default\": 50,\n\n \"users\": {\n\n \"@example:localhost\": 100\n\n },\n\n \"users_default\": 0\n", "file_path": "crates/ruma-events/benches/event_deserialize.rs", "rank": 94, "score": 162585.89040256903 }, { "content": "#[test]\n\nfn deserialize_member_event_with_top_level_membership_field() {\n\n let json_data = json!({\n\n \"content\": {\n\n \"avatar_url\": null,\n\n \"displayname\": \"example\",\n\n \"membership\": \"join\"\n\n },\n\n \"event_id\": \"$h29iv0s8:example.com\",\n\n \"membership\": \"join\",\n\n \"room_id\": \"!room:localhost\",\n\n \"origin_server_ts\": 1,\n\n \"sender\": \"@example:localhost\",\n\n \"state_key\": \"@example:localhost\",\n\n \"type\": \"m.room.member\",\n\n \"unsigned\": {\n\n \"age\": 1,\n\n \"replaces_state\": \"$151800111315tsynI:localhost\",\n\n \"prev_content\": {\n\n \"avatar_url\": null,\n\n \"displayname\": \"example\",\n", "file_path": "crates/ruma-events/tests/state_event.rs", "rank": 95, "score": 162185.94481268933 }, { "content": "/// Redacts an event using the rules specified in the Matrix client-server specification.\n\n///\n\n/// This is part of the process of signing an event.\n\n///\n\n/// Redaction is also suggested when a verifying an event with `verify_event` returns\n\n/// `Verified::Signatures`. See the documentation for `Verified` for details.\n\n///\n\n/// Returns a new JSON object with all applicable fields redacted.\n\n///\n\n/// # Parameters\n\n///\n\n/// * object: A JSON object to redact.\n\n///\n\n/// # Errors\n\n///\n\n/// Returns an error if:\n\n///\n\n/// * `object` contains a field called `content` that is not a JSON object.\n\n/// * `object` contains a field called `hashes` that is not a JSON object.\n\n/// * `object` contains a field called `signatures` that is not a JSON object.\n\n/// * `object` is missing the `type` field or the field is not a JSON string.\n\npub fn redact(\n\n object: &CanonicalJsonObject,\n\n version: &RoomVersionId,\n\n) -> Result<CanonicalJsonObject, Error> {\n\n let mut event = object.clone();\n\n\n\n let event_type_value = match event.get(\"type\") {\n\n Some(event_type_value) => event_type_value,\n\n None => return Err(JsonError::field_missing_from_object(\"type\")),\n\n };\n\n\n\n let allowed_content_keys = match event_type_value {\n\n CanonicalJsonValue::String(event_type) => allowed_content_keys_for(event_type, version),\n\n _ => return Err(JsonError::not_of_type(\"type\", JsonType::String)),\n\n };\n\n\n\n if let Some(content_value) = event.get_mut(\"content\") {\n\n let content = match content_value {\n\n CanonicalJsonValue::Object(map) => map,\n\n _ => return Err(JsonError::not_of_type(\"content\", JsonType::Object)),\n", "file_path": "crates/ruma-signatures/src/functions.rs", "rank": 96, "score": 161895.5834129342 }, { "content": "/// Serialize the given value as a list of just that value.\n\npub fn serialize<T, S>(value: &T, serializer: S) -> Result<S::Ok, S::Error>\n\nwhere\n\n T: Serialize,\n\n S: Serializer,\n\n{\n\n [value].serialize(serializer)\n\n}\n\n\n", "file_path": "crates/ruma-serde/src/single_element_seq.rs", "rank": 97, "score": 161160.3395391292 }, { "content": "/// Serializes a value into a `application/x-www-form-urlencoded` `String` buffer.\n\n///\n\n/// ```\n\n/// let meal = &[\n\n/// (\"bread\", \"baguette\"),\n\n/// (\"cheese\", \"comté\"),\n\n/// (\"meat\", \"ham\"),\n\n/// (\"fat\", \"butter\"),\n\n/// ];\n\n///\n\n/// assert_eq!(\n\n/// ruma_serde::urlencoded::to_string(meal),\n\n/// Ok(\"bread=baguette&cheese=comt%C3%A9&meat=ham&fat=butter\".to_owned()));\n\n/// ```\n\npub fn to_string<T: ser::Serialize>(input: T) -> Result<String, Error> {\n\n let mut urlencoder = UrlEncodedSerializer::new(\"\".to_owned());\n\n input.serialize(Serializer::new(&mut urlencoder))?;\n\n Ok(urlencoder.finish())\n\n}\n\n\n\n/// A serializer for the `application/x-www-form-urlencoded` format.\n\n///\n\n/// * Supported top-level inputs are structs, maps and sequences of pairs, with or without a given\n\n/// length.\n\n///\n\n/// * Supported keys and values are integers, bytes (if convertible to strings), unit structs and\n\n/// unit variants.\n\n///\n\n/// * Newtype structs defer to their inner values.\n\npub struct Serializer<'input, 'output, Target: UrlEncodedTarget> {\n\n urlencoder: &'output mut UrlEncodedSerializer<'input, Target>,\n\n}\n\n\n\nimpl<'input, 'output, Target: UrlEncodedTarget> Serializer<'input, 'output, Target> {\n", "file_path": "crates/ruma-serde/src/urlencoded/ser.rs", "rank": 98, "score": 161039.13307799894 }, { "content": "/// Verifies that the signed event contains all the required valid signatures.\n\n///\n\n/// Some room versions may require signatures from multiple homeservers, so this function takes a\n\n/// map from servers to sets of public keys. Signatures are verified for each required homeserver.\n\n/// All known public keys for a homeserver should be provided. The first one found on the given\n\n/// event will be used.\n\n///\n\n/// If the `Ok` variant is returned by this function, it will contain a `Verified` value which\n\n/// distinguishes an event with valid signatures and a matching content hash with an event with\n\n/// only valid signatures. See the documentation for `Verified` for details.\n\n///\n\n/// # Parameters\n\n///\n\n/// * public_key_map: A map from entity identifiers to a map from key identifiers to public keys.\n\n/// Generally, entity identifiers are server names—the host/IP/port of a homeserver (e.g.\n\n/// \"example.com\") for which a signature must be verified. Key identifiers for each server (e.g.\n\n/// \"ed25519:1\") then map to their respective public keys.\n\n/// * object: The JSON object of the event that was signed.\n\n/// * version: Room version of the given event\n\n///\n\n/// # Examples\n\n///\n\n/// ```rust\n\n/// # use std::collections::BTreeMap;\n\n/// # use ruma_identifiers::RoomVersionId;\n\n/// # use ruma_signatures::verify_event;\n\n/// # use ruma_signatures::Verified;\n\n/// #\n\n/// const PUBLIC_KEY: &str = \"XGX0JRS2Af3be3knz2fBiRbApjm2Dh61gXDJA8kcJNI\";\n\n///\n\n/// // Deserialize an event from JSON.\n\n/// let object = serde_json::from_str(\n\n/// r#\"{\n\n/// \"auth_events\": [],\n\n/// \"content\": {},\n\n/// \"depth\": 3,\n\n/// \"hashes\": {\n\n/// \"sha256\": \"5jM4wQpv6lnBo7CLIghJuHdW+s2CMBJPUOGOC89ncos\"\n\n/// },\n\n/// \"origin\": \"domain\",\n\n/// \"origin_server_ts\": 1000000,\n\n/// \"prev_events\": [],\n\n/// \"room_id\": \"!x:domain\",\n\n/// \"sender\": \"@a:domain\",\n\n/// \"signatures\": {\n\n/// \"domain\": {\n\n/// \"ed25519:1\": \"KxwGjPSDEtvnFgU00fwFz+l6d2pJM6XBIaMEn81SXPTRl16AqLAYqfIReFGZlHi5KLjAWbOoMszkwsQma+lYAg\"\n\n/// }\n\n/// },\n\n/// \"type\": \"X\",\n\n/// \"unsigned\": {\n\n/// \"age_ts\": 1000000\n\n/// }\n\n/// }\"#\n\n/// ).unwrap();\n\n///\n\n/// // Create the `PublicKeyMap` that will inform `verify_json` which signatures to verify.\n\n/// let mut public_key_set = BTreeMap::new();\n\n/// public_key_set.insert(\"ed25519:1\".into(), PUBLIC_KEY.to_owned());\n\n/// let mut public_key_map = BTreeMap::new();\n\n/// public_key_map.insert(\"domain\".into(), public_key_set);\n\n///\n\n/// // Verify at least one signature for each entity in `public_key_map`.\n\n/// let verification_result = verify_event(&public_key_map, &object, &RoomVersionId::Version6);\n\n/// assert!(verification_result.is_ok());\n\n/// assert!(matches!(verification_result.unwrap(), Verified::All));\n\n/// ```\n\npub fn verify_event(\n\n public_key_map: &PublicKeyMap,\n\n object: &CanonicalJsonObject,\n\n version: &RoomVersionId,\n\n) -> Result<Verified, Error> {\n\n let redacted = redact(object, version)?;\n\n\n\n let hash = match object.get(\"hashes\") {\n\n Some(hashes_value) => match hashes_value {\n\n CanonicalJsonValue::Object(hashes) => match hashes.get(\"sha256\") {\n\n Some(hash_value) => match hash_value {\n\n CanonicalJsonValue::String(hash) => hash,\n\n _ => return Err(JsonError::not_of_type(\"sha256 hash\", JsonType::String)),\n\n },\n\n None => return Err(JsonError::not_of_type(\"hashes\", JsonType::Object)),\n\n },\n\n _ => return Err(JsonError::field_missing_from_object(\"sha256\")),\n\n },\n\n None => return Err(JsonError::field_missing_from_object(\"hashes\")),\n\n };\n", "file_path": "crates/ruma-signatures/src/functions.rs", "rank": 99, "score": 159752.35229745082 } ]
Rust
meteora-server/src/raft/server.rs
meteora-kvs/meteora
3dc67f72364ba17540970dca43559f12d1a6d929
use std::collections::HashMap; use std::sync::mpsc; use std::sync::mpsc::Sender; use std::time::Duration; use futures::Future; use grpcio::{RpcContext, UnarySink}; use log::*; use raft::eraftpb::{ConfChange, Message}; use meteora_proto::proto::common::{NodeAddress, Null, State}; use meteora_proto::proto::raft::{AddressState, ChangeReply, StatusReply}; use meteora_proto::proto::raft_grpc::RaftService; use crate::raft::config; #[derive(Clone)] pub struct RaftServer { pub sender: Sender<config::Msg>, seq: u64, node_id: u64, } impl RaftServer { pub fn new(sender: Sender<config::Msg>, node_id: u64) -> RaftServer { RaftServer { sender, seq: 0, node_id, } } } impl RaftService for RaftServer { fn status(&mut self, ctx: RpcContext, _req: Null, sink: UnarySink<StatusReply>) { let (s1, r1) = mpsc::channel(); let sender = self.sender.clone(); let node_id = self.node_id; sender .send(config::Msg::Read { cb: Box::new( move |leader_id: i32, addresses: HashMap<u64, NodeAddress>| { let mut reply = StatusReply::new(); reply.set_state(State::OK); if leader_id >= 0 { reply.set_leader_id(leader_id as u64); } else { reply.set_leader_id(node_id); } reply.set_address_map(addresses); s1.send(reply).expect("callback channel closed"); }, ), }) .unwrap(); let reply = match r1.recv_timeout(Duration::from_secs(2)) { Ok(r) => r, Err(e) => { error!("error: {:?}", e); let mut r = StatusReply::new(); r.set_state(State::IO_ERROR); r } }; let f = sink .success(reply.clone()) .map_err(move |err| error!("failed to reply: {:?}", err)); ctx.spawn(f); } fn change_config(&mut self, ctx: RpcContext, req: ConfChange, sink: UnarySink<ChangeReply>) { let (s1, r1) = mpsc::channel(); let sender = self.sender.clone(); let seq = self.seq; let node_id = self.node_id; self.seq += 1; sender .send(config::Msg::ConfigChange { seq, change: req, cb: Box::new( move |leader_id: i32, addresses: HashMap<u64, NodeAddress>| { let mut reply = ChangeReply::new(); if leader_id >= 0 { reply.set_state(State::WRONG_LEADER); reply.set_leader_id(leader_id as u64); } else { reply.set_state(State::OK); reply.set_leader_id(node_id); } reply.set_address_map(addresses); s1.send(reply).expect("callback channel closed"); }, ), }) .unwrap(); let reply = match r1.recv_timeout(Duration::from_secs(2)) { Ok(r) => r, Err(e) => { error!("error: {:?}", e); let mut r = ChangeReply::new(); r.set_state(State::IO_ERROR); r } }; let f = sink .success(reply.clone()) .map_err(move |err| error!("failed to reply: {:?}", err)); ctx.spawn(f); } fn send_msg(&mut self, _ctx: RpcContext, req: Message, _sink: ::grpcio::UnarySink<Null>) { let sender = self.sender.clone(); sender.send(config::Msg::Raft(req)).unwrap(); } fn send_address(&mut self, _ctx: RpcContext, req: AddressState, _sink: UnarySink<Null>) { let sender = self.sender.clone(); sender.send(config::Msg::Address(req)).unwrap(); } }
use std::collections::HashMap; use std::sync::mpsc; use std::sync::mpsc::Sender; use std::time::Duration; use futures::Future; use grpcio::{RpcContext, UnarySink}; use log::*; use raft::eraftpb::{ConfChange, Message}; use meteora_proto::proto::common::{NodeAddress, Null, State}; use meteora_proto::proto::raft::{AddressState, ChangeReply, StatusReply}; use meteora_proto::proto::raft_grpc::RaftService; use crate::raft::config; #[derive(Clone)] pub struct RaftServer { pub sender: Sender<config::Msg>, seq: u64, node_id: u64, } impl RaftServer { pub fn new(sender: Sender<config::Msg>, node_id: u64) -> RaftServer { RaftServer { sender, seq: 0, node_id, } } } impl RaftService for RaftServer { fn status(&mut self, ctx: RpcContext, _req: Null, sink: UnarySink<StatusReply>) { let (s1, r1) = mpsc::channel(); let sender = self.sender.clone(); let node_id = self.node_id; sender .send(config::Msg::Read { cb: Box::new( move |leader_id: i32, addresses: HashMap<u64, NodeAddress>| { let mut reply = StatusReply::new(); reply.set_state(State::OK); if leader_id >= 0 { reply.set_leader_id(leader_id as u64); } else { reply.set_leader_id(node_id); } reply.set_address_map(addresses); s1.send(reply).expect("callback channel closed"); }, ), }) .unwrap(); let reply = match r1.recv_timeout(Duration::from_secs(2)) { Ok(r) => r, Err(e) => { error!("error: {:?}", e); let mut r = StatusReply::new(); r.set_state(State::IO_ERROR); r } }; let f = sink .success(reply.clone()) .map_err(move |err| error!("failed to reply: {:?}", err)); ctx.spawn(f); } fn change_config(&mut self, ctx: RpcContext, req: ConfChange, sink: UnarySink<ChangeReply>) { let (s1, r1) = m
self.seq += 1; sender .send(config::Msg::ConfigChange { seq, change: req, cb: Box::new( move |leader_id: i32, addresses: HashMap<u64, NodeAddress>| { let mut reply = ChangeReply::new(); if leader_id >= 0 { reply.set_state(State::WRONG_LEADER); reply.set_leader_id(leader_id as u64); } else { reply.set_state(State::OK); reply.set_leader_id(node_id); } reply.set_address_map(addresses); s1.send(reply).expect("callback channel closed"); }, ), }) .unwrap(); let reply = match r1.recv_timeout(Duration::from_secs(2)) { Ok(r) => r, Err(e) => { error!("error: {:?}", e); let mut r = ChangeReply::new(); r.set_state(State::IO_ERROR); r } }; let f = sink .success(reply.clone()) .map_err(move |err| error!("failed to reply: {:?}", err)); ctx.spawn(f); } fn send_msg(&mut self, _ctx: RpcContext, req: Message, _sink: ::grpcio::UnarySink<Null>) { let sender = self.sender.clone(); sender.send(config::Msg::Raft(req)).unwrap(); } fn send_address(&mut self, _ctx: RpcContext, req: AddressState, _sink: UnarySink<Null>) { let sender = self.sender.clone(); sender.send(config::Msg::Address(req)).unwrap(); } }
psc::channel(); let sender = self.sender.clone(); let seq = self.seq; let node_id = self.node_id;
random
[ { "content": "type ProposeCallback = Box<dyn Fn(i32, HashMap<u64, NodeAddress>) + Send>;\n\n\n\npub enum Msg {\n\n Propose {\n\n seq: u64,\n\n op: Op,\n\n cb: ProposeCallback,\n\n },\n\n ConfigChange {\n\n seq: u64,\n\n change: ConfChange,\n\n cb: ProposeCallback,\n\n },\n\n Read {\n\n cb: ProposeCallback,\n\n },\n\n Address(AddressState),\n\n Raft(Message),\n\n}\n\n\n", "file_path": "meteora-server/src/raft/config.rs", "rank": 0, "score": 151511.89062086405 }, { "content": "pub fn set_logger() {\n\n match env::var(\"RUST_LOG\") {\n\n Ok(val) => {\n\n let log_level: &str = &val;\n\n match log_level {\n\n \"error\" => { /* noop */ }\n\n \"warn\" => { /* noop */ }\n\n \"info\" => { /* noop */ }\n\n \"debug\" => { /* noop */ }\n\n _ => env::set_var(\"RUST_LOG\", \"info\"),\n\n }\n\n }\n\n Err(_e) => env::set_var(\"RUST_LOG\", \"info\"),\n\n };\n\n env_logger::Builder::from_default_env()\n\n .format(|buf, record| {\n\n let ts = buf.timestamp();\n\n writeln!(\n\n buf,\n\n \"[{} {} {} {}:{}] {}\",\n", "file_path": "meteora/src/log.rs", "rank": 1, "score": 120623.50936334628 }, { "content": "pub fn set_http_logger() {\n\n match env::var(\"RUST_LOG\") {\n\n Ok(val) => {\n\n let log_level: &str = &val;\n\n match log_level {\n\n \"error\" => { /* noop */ }\n\n \"warn\" => { /* noop */ }\n\n \"info\" => { /* noop */ }\n\n \"debug\" => { /* noop */ }\n\n _ => env::set_var(\"RUST_LOG\", \"info\"),\n\n }\n\n }\n\n Err(_e) => env::set_var(\"RUST_LOG\", \"info\"),\n\n };\n\n env_logger::Builder::from_default_env()\n\n .format(|buf, record| {\n\n let ts = buf.timestamp();\n\n writeln!(buf, \"[{} {}] {}\", ts, record.level(), record.args(),)\n\n })\n\n .init();\n\n}\n", "file_path": "meteora/src/log.rs", "rank": 2, "score": 117636.37342371112 }, { "content": "pub fn create_raft_client(address: String) -> RaftServiceClient {\n\n let env = Arc::new(EnvBuilder::new().build());\n\n let ch = ChannelBuilder::new(env).connect(&address);\n\n let client = RaftServiceClient::new(ch);\n\n client\n\n}\n\n\n\npub struct RaftClient {\n\n leader_id: u64, // leader's index in server_ids\n\n clients: HashMap<u64, Arc<RaftServiceClient>>,\n\n addresses: HashMap<u64, String>,\n\n}\n\n\n\nimpl RaftClient {\n\n pub fn new(address: &str) -> RaftClient {\n\n let raft_client = create_raft_client(address.to_string());\n\n\n\n let req = Null::new();\n\n let reply = raft_client.status(&req).unwrap();\n\n let leader_id = reply.leader_id;\n", "file_path": "meteora-client/src/raft/client.rs", "rank": 3, "score": 117107.14405253009 }, { "content": "pub fn create_kv_client(address: String) -> KvServiceClient {\n\n let env = Arc::new(EnvBuilder::new().build());\n\n let ch = ChannelBuilder::new(env).connect(&address);\n\n let client = KvServiceClient::new(ch);\n\n client\n\n}\n\n\n\npub struct KVClient {\n\n leader_id: u64, // leader's node id\n\n clients: HashMap<u64, Arc<KvServiceClient>>,\n\n addresses: HashMap<u64, String>,\n\n next_index: usize,\n\n node_id: u64, // node id\n\n}\n\n\n\nimpl KVClient {\n\n pub fn new(raft_address: &str) -> KVClient {\n\n let raft_client = create_raft_client(raft_address.to_string());\n\n\n\n let req = Null::new();\n", "file_path": "meteora-client/src/kv/client.rs", "rank": 4, "score": 117107.14405253009 }, { "content": "pub fn sigterm_channel() -> Result<Receiver<()>, ctrlc::Error> {\n\n let (sender, receiver) = bounded(100);\n\n ctrlc::set_handler(move || {\n\n let _ = sender.send(());\n\n })\n\n .unwrap();\n\n\n\n Ok(receiver)\n\n}\n", "file_path": "meteora/src/signal.rs", "rank": 5, "score": 105735.21260082383 }, { "content": "pub fn run_start_cli(matches: &ArgMatches) -> Result<(), std::io::Error> {\n\n set_logger();\n\n\n\n let id = matches.value_of(\"ID\").unwrap().parse::<u64>().unwrap();\n\n let address = matches.value_of(\"ADDRESS\").unwrap();\n\n let raft_port = matches\n\n .value_of(\"RAFT_PORT\")\n\n .unwrap()\n\n .parse::<u16>()\n\n .unwrap();\n\n let kv_port = matches.value_of(\"KV_PORT\").unwrap().parse::<u16>().unwrap();\n\n let mut peer_address = \"\";\n\n let data_directory = matches.value_of(\"DATA_DIRECTORY\").unwrap();\n\n if let Some(_peer_address) = matches.value_of(\"PEER_RAFT_ADDRESS\") {\n\n peer_address = _peer_address;\n\n }\n\n\n\n let raft_address = format!(\"{}:{}\", address, raft_port);\n\n let kv_address = format!(\"{}:{}\", address, kv_port);\n\n\n", "file_path": "meteora/src/cli/start.rs", "rank": 6, "score": 103116.82417915468 }, { "content": "pub fn run_leave_cli(matches: &ArgMatches) -> Result<(), std::io::Error> {\n\n set_logger();\n\n\n\n let address = matches.value_of(\"ADDRESS\").unwrap();\n\n let id = matches.value_of(\"ID\").unwrap().parse::<u64>().unwrap();\n\n\n\n let mut raft_client = RaftClient::new(address);\n\n\n\n match raft_client.leave(id) {\n\n Ok(v) => {\n\n println!(\"{}\", serde_json::to_string(&v).unwrap());\n\n Ok(())\n\n }\n\n Err(e) => {\n\n println!(\"{}\", e);\n\n Err(e)\n\n }\n\n }\n\n}\n", "file_path": "meteora/src/cli/leave.rs", "rank": 7, "score": 103116.82417915468 }, { "content": "pub fn run_delete_cli(matches: &ArgMatches) -> Result<(), std::io::Error> {\n\n set_logger();\n\n\n\n let address = matches.value_of(\"ADDRESS\").unwrap();\n\n let key = matches.value_of(\"KEY\").unwrap();\n\n\n\n let mut kv_client = KVClient::new(address);\n\n\n\n kv_client.delete(key.as_bytes().to_vec())\n\n}\n", "file_path": "meteora/src/cli/delete.rs", "rank": 8, "score": 103116.82417915468 }, { "content": "pub fn run_put_cli(matches: &ArgMatches) -> Result<(), std::io::Error> {\n\n set_logger();\n\n\n\n let address = matches.value_of(\"ADDRESS\").unwrap();\n\n let key = matches.value_of(\"KEY\").unwrap();\n\n let value = matches.value_of(\"VALUE\").unwrap();\n\n\n\n let mut kv_client = KVClient::new(address);\n\n\n\n kv_client.put(key.as_bytes().to_vec(), value.as_bytes().to_vec())\n\n}\n", "file_path": "meteora/src/cli/put.rs", "rank": 9, "score": 103116.82417915468 }, { "content": "pub fn run_get_cli(matches: &ArgMatches) -> Result<(), std::io::Error> {\n\n set_logger();\n\n\n\n let address = matches.value_of(\"ADDRESS\").unwrap();\n\n let key = matches.value_of(\"KEY\").unwrap();\n\n\n\n let mut kv_client = KVClient::new(address);\n\n\n\n match kv_client.get(key.as_bytes().to_vec()) {\n\n Ok(v) => {\n\n println!(\"{:?}\", String::from_utf8(v).unwrap());\n\n Ok(())\n\n }\n\n Err(e) => {\n\n println!(\"{}\", e);\n\n Err(e)\n\n }\n\n }\n\n}\n", "file_path": "meteora/src/cli/get.rs", "rank": 10, "score": 103116.82417915468 }, { "content": "pub fn run_status_cli(matches: &ArgMatches) -> Result<(), std::io::Error> {\n\n set_logger();\n\n\n\n let address = matches.value_of(\"ADDRESS\").unwrap();\n\n\n\n let mut raft_client = RaftClient::new(address);\n\n\n\n match raft_client.status() {\n\n Ok(v) => {\n\n println!(\"{}\", serde_json::to_string(&v).unwrap());\n\n Ok(())\n\n }\n\n Err(e) => {\n\n println!(\"{}\", e);\n\n Err(e)\n\n }\n\n }\n\n}\n", "file_path": "meteora/src/cli/status.rs", "rank": 11, "score": 103116.82417915468 }, { "content": "pub fn init_and_run(\n\n storage: MemStorage,\n\n receiver: Receiver<Msg>,\n\n apply_sender: Sender<Op>,\n\n node_id: u64,\n\n node_address: NodeAddress,\n\n addresses: HashMap<u64, NodeAddress>,\n\n) {\n\n let mut peers = vec![];\n\n let mut addresses = addresses;\n\n let mut rpc_clients = HashMap::new();\n\n for (id, address) in &addresses {\n\n peers.push(id.clone());\n\n insert_client(id.clone(), address.raft_address.as_str(), &mut rpc_clients);\n\n }\n\n if peers.is_empty() {\n\n addresses.insert(node_id, node_address);\n\n peers.push(node_id);\n\n }\n\n debug!(\"{:?}\", peers);\n", "file_path": "meteora-server/src/raft/config.rs", "rank": 12, "score": 84627.80968942551 }, { "content": "pub fn file_descriptor_proto() -> &'static ::protobuf::descriptor::FileDescriptorProto {\n\n file_descriptor_proto_lazy.get(|| {\n\n parse_descriptor_proto()\n\n })\n\n}\n", "file_path": "meteora-proto/src/proto/common.rs", "rank": 13, "score": 70171.54700310098 }, { "content": "pub fn file_descriptor_proto() -> &'static ::protobuf::descriptor::FileDescriptorProto {\n\n file_descriptor_proto_lazy.get(|| {\n\n parse_descriptor_proto()\n\n })\n\n}\n", "file_path": "meteora-proto/src/proto/raft.rs", "rank": 14, "score": 70171.54700310098 }, { "content": "pub fn file_descriptor_proto() -> &'static ::protobuf::descriptor::FileDescriptorProto {\n\n file_descriptor_proto_lazy.get(|| {\n\n parse_descriptor_proto()\n\n })\n\n}\n", "file_path": "meteora-proto/src/proto/kv.rs", "rank": 15, "score": 70171.54700310098 }, { "content": "pub fn create_raft_service<S: RaftService + Send + Clone + 'static>(s: S) -> ::grpcio::Service {\n\n let mut builder = ::grpcio::ServiceBuilder::new();\n\n let mut instance = s.clone();\n\n builder = builder.add_unary_handler(&METHOD_RAFT_SERVICE_STATUS, move |ctx, req, resp| {\n\n instance.status(ctx, req, resp)\n\n });\n\n let mut instance = s.clone();\n\n builder = builder.add_unary_handler(&METHOD_RAFT_SERVICE_CHANGE_CONFIG, move |ctx, req, resp| {\n\n instance.change_config(ctx, req, resp)\n\n });\n\n let mut instance = s.clone();\n\n builder = builder.add_unary_handler(&METHOD_RAFT_SERVICE_SEND_MSG, move |ctx, req, resp| {\n\n instance.send_msg(ctx, req, resp)\n\n });\n\n let mut instance = s;\n\n builder = builder.add_unary_handler(&METHOD_RAFT_SERVICE_SEND_ADDRESS, move |ctx, req, resp| {\n\n instance.send_address(ctx, req, resp)\n\n });\n\n builder.build()\n\n}\n", "file_path": "meteora-proto/src/proto/raft_grpc.rs", "rank": 16, "score": 62188.51075512708 }, { "content": "pub fn create_kv_service<S: KvService + Send + Clone + 'static>(s: S) -> ::grpcio::Service {\n\n let mut builder = ::grpcio::ServiceBuilder::new();\n\n let mut instance = s.clone();\n\n builder = builder.add_unary_handler(&METHOD_KV_SERVICE_GET, move |ctx, req, resp| {\n\n instance.get(ctx, req, resp)\n\n });\n\n let mut instance = s.clone();\n\n builder = builder.add_unary_handler(&METHOD_KV_SERVICE_PUT, move |ctx, req, resp| {\n\n instance.put(ctx, req, resp)\n\n });\n\n let mut instance = s;\n\n builder = builder.add_unary_handler(&METHOD_KV_SERVICE_DELETE, move |ctx, req, resp| {\n\n instance.delete(ctx, req, resp)\n\n });\n\n builder.build()\n\n}\n", "file_path": "meteora-proto/src/proto/kv_grpc.rs", "rank": 17, "score": 62188.51075512708 }, { "content": "pub trait KvService {\n\n fn get(&mut self, ctx: ::grpcio::RpcContext, req: super::kv::GetReq, sink: ::grpcio::UnarySink<super::kv::GetReply>);\n\n fn put(&mut self, ctx: ::grpcio::RpcContext, req: super::kv::PutReq, sink: ::grpcio::UnarySink<super::kv::PutReply>);\n\n fn delete(&mut self, ctx: ::grpcio::RpcContext, req: super::kv::DeleteReq, sink: ::grpcio::UnarySink<super::kv::DeleteReply>);\n\n}\n\n\n", "file_path": "meteora-proto/src/proto/kv_grpc.rs", "rank": 18, "score": 44829.732418518164 }, { "content": "pub trait RaftService {\n\n fn status(&mut self, ctx: ::grpcio::RpcContext, req: super::common::Null, sink: ::grpcio::UnarySink<super::raft::StatusReply>);\n\n fn change_config(&mut self, ctx: ::grpcio::RpcContext, req: super::eraftpb::ConfChange, sink: ::grpcio::UnarySink<super::raft::ChangeReply>);\n\n fn send_msg(&mut self, ctx: ::grpcio::RpcContext, req: super::eraftpb::Message, sink: ::grpcio::UnarySink<super::common::Null>);\n\n fn send_address(&mut self, ctx: ::grpcio::RpcContext, req: super::raft::AddressState, sink: ::grpcio::UnarySink<super::common::Null>);\n\n}\n\n\n", "file_path": "meteora-proto/src/proto/raft_grpc.rs", "rank": 19, "score": 44829.732418518164 }, { "content": "fn on_ready(\n\n r: &mut RawNode<MemStorage>,\n\n callbacks: &mut HashMap<u64, ProposeCallback>,\n\n addresses: &mut HashMap<u64, NodeAddress>,\n\n clients: &mut HashMap<u64, Arc<RaftServiceClient>>,\n\n apply_sender: Sender<Op>,\n\n) {\n\n if !r.has_ready() {\n\n return;\n\n }\n\n\n\n // The Raft is ready, we can do something now.\n\n let mut ready = r.ready();\n\n\n\n let is_leader = r.raft.leader_id == r.raft.id;\n\n if is_leader {\n\n // If the peer is leader, the leader can send messages to other followers ASAP.\n\n let msgs = ready.messages.drain(..);\n\n for msg in msgs {\n\n let client = match clients.get(&msg.get_to()) {\n", "file_path": "meteora-server/src/raft/config.rs", "rank": 20, "score": 41299.52387602614 }, { "content": "fn insert_client(\n\n node_id: u64,\n\n node_address: &str,\n\n clients: &mut HashMap<u64, Arc<RaftServiceClient>>,\n\n) {\n\n let env = Arc::new(EnvBuilder::new().build());\n\n let ch = ChannelBuilder::new(env).connect(node_address);\n\n let client = RaftServiceClient::new(ch);\n\n clients.insert(node_id.clone(), Arc::new(client));\n\n}\n", "file_path": "meteora-server/src/raft/config.rs", "rank": 21, "score": 40310.310047026585 }, { "content": "fn main() -> Result<(), std::io::Error> {\n\n let mut proc = Command::new(\"./protoc_rust.sh\")\n\n .stdout(Stdio::piped())\n\n .spawn()\n\n .expect(\"failed to run\");\n\n let ret = proc.wait().unwrap();\n\n\n\n if ret.success() {\n\n Ok(())\n\n } else {\n\n Err(Error::new(\n\n ErrorKind::Other,\n\n format!(\"failed to run: {}\", ret.code().unwrap()),\n\n ))\n\n }\n\n}\n", "file_path": "meteora-proto/build.rs", "rank": 22, "score": 37766.17764295465 }, { "content": "fn main() -> Result<(), std::io::Error> {\n\n let app = App::new(crate_name!())\n\n .setting(AppSettings::DeriveDisplayOrder)\n\n .setting(AppSettings::SubcommandRequiredElseHelp)\n\n .version(crate_version!())\n\n .author(crate_authors!())\n\n .about(\"Key-value store.\")\n\n .help_message(\"Prints help information.\")\n\n .version_message(\"Prints version information.\")\n\n .version_short(\"v\")\n\n .subcommand(\n\n SubCommand::with_name(\"start\")\n\n .name(\"start\")\n\n .setting(AppSettings::DeriveDisplayOrder)\n\n .version(crate_version!())\n\n .author(crate_authors!())\n\n .about(\"Start key-value store.\")\n\n .help_message(\"Prints help information.\")\n\n .version_message(\"Prints version information.\")\n\n .version_short(\"v\")\n", "file_path": "meteora/src/main.rs", "rank": 23, "score": 37766.17764295465 }, { "content": "use std::env;\n\nuse std::io::Write;\n\n\n\nuse env_logger;\n\n\n", "file_path": "meteora/src/log.rs", "rank": 24, "score": 35595.63528928984 }, { "content": " ts,\n\n record.level(),\n\n record.target(),\n\n record.file().unwrap_or(\"unknown\"),\n\n record.line().unwrap_or(0),\n\n record.args(),\n\n )\n\n })\n\n .init();\n\n}\n\n\n", "file_path": "meteora/src/log.rs", "rank": 25, "score": 35595.187144920805 }, { "content": "fn parse_descriptor_proto() -> ::protobuf::descriptor::FileDescriptorProto {\n\n ::protobuf::Message::parse_from_bytes(file_descriptor_proto_data).unwrap()\n\n}\n\n\n", "file_path": "meteora-proto/src/proto/common.rs", "rank": 26, "score": 34203.510886856486 }, { "content": "fn parse_descriptor_proto() -> ::protobuf::descriptor::FileDescriptorProto {\n\n ::protobuf::Message::parse_from_bytes(file_descriptor_proto_data).unwrap()\n\n}\n\n\n", "file_path": "meteora-proto/src/proto/raft.rs", "rank": 27, "score": 34203.510886856486 }, { "content": "fn parse_descriptor_proto() -> ::protobuf::descriptor::FileDescriptorProto {\n\n ::protobuf::Message::parse_from_bytes(file_descriptor_proto_data).unwrap()\n\n}\n\n\n", "file_path": "meteora-proto/src/proto/kv.rs", "rank": 28, "score": 34203.510886856486 }, { "content": "fn apply_daemon(receiver: Receiver<Op>, db: Arc<DB>) {\n\n loop {\n\n let op = match receiver.recv() {\n\n Ok(o) => o,\n\n _ => {\n\n debug!(\"exit the apply daemon\");\n\n return;\n\n }\n\n };\n\n match op {\n\n Op::Put { key, val } => {\n\n db.put(key.as_slice(), val.as_slice()).unwrap();\n\n }\n\n Op::Delete { key } => {\n\n db.delete(key.as_slice()).unwrap();\n\n }\n\n }\n\n }\n\n}\n", "file_path": "meteora-server/src/kv/server.rs", "rank": 29, "score": 33232.97887687961 }, { "content": "\n\n fn put(&mut self, ctx: RpcContext, req: PutReq, sink: UnarySink<PutReply>) {\n\n let (s1, r1) = mpsc::channel();\n\n let sender = self.sender.clone();\n\n let op = Op::Put {\n\n key: req.get_key().to_vec(),\n\n val: req.get_value().to_vec(),\n\n };\n\n let seq = self.seq;\n\n let node_id = self.node_id;\n\n\n\n self.seq += 1;\n\n\n\n sender\n\n .send(config::Msg::Propose {\n\n seq,\n\n op,\n\n cb: Box::new(\n\n move |leader_id: i32, addresses: HashMap<u64, NodeAddress>| {\n\n let mut reply = PutReply::new();\n", "file_path": "meteora-server/src/kv/server.rs", "rank": 31, "score": 40.164220320428434 }, { "content": " r.set_state(State::IO_ERROR);\n\n r\n\n }\n\n };\n\n\n\n let f = sink\n\n .success(reply.clone())\n\n .map_err(move |err| error!(\"failed to reply: {:?}\", err));\n\n ctx.spawn(f);\n\n }\n\n\n\n fn delete(&mut self, ctx: RpcContext, req: DeleteReq, sink: UnarySink<DeleteReply>) {\n\n let (s1, r1) = mpsc::channel();\n\n let sender = self.sender.clone();\n\n let op = Op::Delete {\n\n key: req.get_key().to_vec(),\n\n };\n\n let seq = self.seq;\n\n let node_id = self.node_id;\n\n\n", "file_path": "meteora-server/src/kv/server.rs", "rank": 32, "score": 39.09348490180212 }, { "content": " apply_daemon(apply_r, db);\n\n });\n\n\n\n return (kv_server, raft_server);\n\n }\n\n}\n\n\n\nimpl KvService for KVServer {\n\n fn get(&mut self, ctx: RpcContext, req: GetReq, sink: UnarySink<GetReply>) {\n\n let (s1, r1) = mpsc::channel();\n\n let db = Arc::clone(&self.db);\n\n let sender = self.sender.clone();\n\n let node_id = self.node_id;\n\n\n\n self.seq += 1;\n\n\n\n sender\n\n .send(config::Msg::Read {\n\n cb: Box::new(\n\n move |leader_id: i32, addresses: HashMap<u64, NodeAddress>| {\n", "file_path": "meteora-server/src/kv/server.rs", "rank": 33, "score": 38.715154260392495 }, { "content": " s1.send(reply).expect(\"callback channel closed\");\n\n },\n\n ),\n\n })\n\n .unwrap();\n\n\n\n let reply = match r1.recv_timeout(Duration::from_secs(2)) {\n\n Ok(r) => r,\n\n Err(_e) => {\n\n let mut r = GetReply::new();\n\n r.set_state(State::IO_ERROR);\n\n r\n\n }\n\n };\n\n\n\n let f = sink\n\n .success(reply.clone())\n\n .map_err(move |err| error!(\"failed to reply: {:?}\", err));\n\n ctx.spawn(f);\n\n }\n", "file_path": "meteora-server/src/kv/server.rs", "rank": 34, "score": 37.70648912434596 }, { "content": " self.seq += 1;\n\n\n\n sender\n\n .send(config::Msg::Propose {\n\n seq,\n\n op,\n\n cb: Box::new(\n\n move |leader_id: i32, addresses: HashMap<u64, NodeAddress>| {\n\n let mut reply = DeleteReply::new();\n\n if leader_id >= 0 {\n\n // follower\n\n reply.set_state(State::WRONG_LEADER);\n\n reply.set_leader_id(leader_id as u64);\n\n } else {\n\n // leader\n\n reply.set_state(State::OK);\n\n reply.set_leader_id(node_id);\n\n }\n\n reply.set_address_map(addresses);\n\n s1.send(reply).expect(\"callback channel closed\");\n", "file_path": "meteora-server/src/kv/server.rs", "rank": 38, "score": 34.10034437786496 }, { "content": " if leader_id >= 0 {\n\n // follower\n\n reply.set_state(State::WRONG_LEADER);\n\n reply.set_leader_id(leader_id as u64);\n\n } else {\n\n // leader\n\n reply.set_state(State::OK);\n\n reply.set_leader_id(node_id);\n\n }\n\n reply.set_address_map(addresses);\n\n s1.send(reply).expect(\"callback channel closed\");\n\n },\n\n ),\n\n })\n\n .unwrap();\n\n\n\n let reply = match r1.recv_timeout(Duration::from_secs(2)) {\n\n Ok(r) => r,\n\n Err(_e) => {\n\n let mut r = PutReply::new();\n", "file_path": "meteora-server/src/kv/server.rs", "rank": 40, "score": 31.593694691185803 }, { "content": " },\n\n ),\n\n })\n\n .unwrap();\n\n\n\n let reply = match r1.recv_timeout(Duration::from_secs(2)) {\n\n Ok(r) => r,\n\n Err(_e) => {\n\n let mut r = DeleteReply::new();\n\n r.set_state(State::IO_ERROR);\n\n r\n\n }\n\n };\n\n\n\n let f = sink\n\n .success(reply.clone())\n\n .map_err(move |err| error!(\"failed to reply: {:?}\", err));\n\n ctx.spawn(f);\n\n }\n\n}\n\n\n", "file_path": "meteora-server/src/kv/server.rs", "rank": 41, "score": 31.2581812621418 }, { "content": "impl ::protobuf::reflect::ProtobufValue for DeleteReq {\n\n fn as_ref(&self) -> ::protobuf::reflect::ReflectValueRef {\n\n ::protobuf::reflect::ReflectValueRef::Message(self)\n\n }\n\n}\n\n\n\n#[derive(PartialEq,Clone,Default)]\n\npub struct DeleteReply {\n\n // message fields\n\n pub state: super::common::State,\n\n pub address_map: ::std::collections::HashMap<u64, super::common::NodeAddress>,\n\n pub leader_id: u64,\n\n // special fields\n\n pub unknown_fields: ::protobuf::UnknownFields,\n\n pub cached_size: ::protobuf::CachedSize,\n\n}\n\n\n\nimpl<'a> ::std::default::Default for &'a DeleteReply {\n\n fn default() -> &'a DeleteReply {\n\n <DeleteReply as ::protobuf::Message>::default_instance()\n", "file_path": "meteora-proto/src/proto/kv.rs", "rank": 44, "score": 23.262731484338524 }, { "content": "\n\nimpl ::protobuf::reflect::ProtobufValue for PutReq {\n\n fn as_ref(&self) -> ::protobuf::reflect::ReflectValueRef {\n\n ::protobuf::reflect::ReflectValueRef::Message(self)\n\n }\n\n}\n\n\n\n#[derive(PartialEq,Clone,Default)]\n\npub struct PutReply {\n\n // message fields\n\n pub state: super::common::State,\n\n pub address_map: ::std::collections::HashMap<u64, super::common::NodeAddress>,\n\n pub leader_id: u64,\n\n // special fields\n\n pub unknown_fields: ::protobuf::UnknownFields,\n\n pub cached_size: ::protobuf::CachedSize,\n\n}\n\n\n\nimpl<'a> ::std::default::Default for &'a PutReply {\n\n fn default() -> &'a PutReply {\n", "file_path": "meteora-proto/src/proto/kv.rs", "rank": 45, "score": 23.062013139063883 }, { "content": "pub struct ChangeReply {\n\n // message fields\n\n pub state: super::common::State,\n\n pub address_map: ::std::collections::HashMap<u64, super::common::NodeAddress>,\n\n pub leader_id: u64,\n\n // special fields\n\n pub unknown_fields: ::protobuf::UnknownFields,\n\n pub cached_size: ::protobuf::CachedSize,\n\n}\n\n\n\nimpl<'a> ::std::default::Default for &'a ChangeReply {\n\n fn default() -> &'a ChangeReply {\n\n <ChangeReply as ::protobuf::Message>::default_instance()\n\n }\n\n}\n\n\n\nimpl ChangeReply {\n\n pub fn new() -> ChangeReply {\n\n ::std::default::Default::default()\n\n }\n", "file_path": "meteora-proto/src/proto/raft.rs", "rank": 46, "score": 22.65423348917575 }, { "content": " self.state = super::common::State::UNKNOWN;\n\n }\n\n\n\n // Param is passed by value, moved\n\n pub fn set_state(&mut self, v: super::common::State) {\n\n self.state = v;\n\n }\n\n\n\n // repeated .meteora.kv.GetReply.AddressMapEntry address_map = 3;\n\n\n\n\n\n pub fn get_address_map(&self) -> &::std::collections::HashMap<u64, super::common::NodeAddress> {\n\n &self.address_map\n\n }\n\n pub fn clear_address_map(&mut self) {\n\n self.address_map.clear();\n\n }\n\n\n\n // Param is passed by value, moved\n\n pub fn set_address_map(&mut self, v: ::std::collections::HashMap<u64, super::common::NodeAddress>) {\n", "file_path": "meteora-proto/src/proto/kv.rs", "rank": 47, "score": 22.64096765874745 }, { "content": " <PutReply as ::protobuf::Message>::default_instance()\n\n }\n\n}\n\n\n\nimpl PutReply {\n\n pub fn new() -> PutReply {\n\n ::std::default::Default::default()\n\n }\n\n\n\n // .meteora.common.State state = 1;\n\n\n\n\n\n pub fn get_state(&self) -> super::common::State {\n\n self.state\n\n }\n\n pub fn clear_state(&mut self) {\n\n self.state = super::common::State::UNKNOWN;\n\n }\n\n\n\n // Param is passed by value, moved\n", "file_path": "meteora-proto/src/proto/kv.rs", "rank": 48, "score": 21.904116063765432 }, { "content": " pub fn set_state(&mut self, v: super::common::State) {\n\n self.state = v;\n\n }\n\n\n\n // repeated .meteora.kv.PutReply.AddressMapEntry address_map = 2;\n\n\n\n\n\n pub fn get_address_map(&self) -> &::std::collections::HashMap<u64, super::common::NodeAddress> {\n\n &self.address_map\n\n }\n\n pub fn clear_address_map(&mut self) {\n\n self.address_map.clear();\n\n }\n\n\n\n // Param is passed by value, moved\n\n pub fn set_address_map(&mut self, v: ::std::collections::HashMap<u64, super::common::NodeAddress>) {\n\n self.address_map = v;\n\n }\n\n\n\n // Mutable pointer to the field.\n", "file_path": "meteora-proto/src/proto/kv.rs", "rank": 49, "score": 21.617431964482442 }, { "content": "\n\n // .meteora.common.State state = 1;\n\n\n\n\n\n pub fn get_state(&self) -> super::common::State {\n\n self.state\n\n }\n\n pub fn clear_state(&mut self) {\n\n self.state = super::common::State::UNKNOWN;\n\n }\n\n\n\n // Param is passed by value, moved\n\n pub fn set_state(&mut self, v: super::common::State) {\n\n self.state = v;\n\n }\n\n\n\n // repeated .meteora.raft.ChangeReply.AddressMapEntry address_map = 2;\n\n\n\n\n\n pub fn get_address_map(&self) -> &::std::collections::HashMap<u64, super::common::NodeAddress> {\n", "file_path": "meteora-proto/src/proto/raft.rs", "rank": 50, "score": 21.56009435454498 }, { "content": "impl AddressState {\n\n pub fn new() -> AddressState {\n\n ::std::default::Default::default()\n\n }\n\n\n\n // repeated .meteora.raft.AddressState.AddressMapEntry address_map = 1;\n\n\n\n\n\n pub fn get_address_map(&self) -> &::std::collections::HashMap<u64, super::common::NodeAddress> {\n\n &self.address_map\n\n }\n\n pub fn clear_address_map(&mut self) {\n\n self.address_map.clear();\n\n }\n\n\n\n // Param is passed by value, moved\n\n pub fn set_address_map(&mut self, v: ::std::collections::HashMap<u64, super::common::NodeAddress>) {\n\n self.address_map = v;\n\n }\n\n\n", "file_path": "meteora-proto/src/proto/raft.rs", "rank": 51, "score": 21.357526502150176 }, { "content": " // Get\n\n let mut reply = GetReply::new();\n\n let (state, value) = match db.get(req.get_key()) {\n\n Ok(Some(v)) => (State::OK, v),\n\n Ok(None) => (State::NOT_FOUND, Vec::new()),\n\n Err(e) => {\n\n error!(\"failed to get value: {:?}\", e);\n\n (State::IO_ERROR, Vec::new())\n\n }\n\n };\n\n reply.set_state(state);\n\n if leader_id >= 0 {\n\n // follower\n\n reply.set_leader_id(leader_id as u64);\n\n } else {\n\n // leader\n\n reply.set_leader_id(node_id);\n\n }\n\n reply.set_value(value);\n\n reply.set_address_map(addresses);\n", "file_path": "meteora-server/src/kv/server.rs", "rank": 52, "score": 21.348654882486905 }, { "content": " ::protobuf::reflect::ReflectValueRef::Message(self)\n\n }\n\n}\n\n\n\n#[derive(PartialEq,Clone,Default)]\n\npub struct GetReply {\n\n // message fields\n\n pub value: ::std::vec::Vec<u8>,\n\n pub state: super::common::State,\n\n pub address_map: ::std::collections::HashMap<u64, super::common::NodeAddress>,\n\n pub leader_id: u64,\n\n // special fields\n\n pub unknown_fields: ::protobuf::UnknownFields,\n\n pub cached_size: ::protobuf::CachedSize,\n\n}\n\n\n\nimpl<'a> ::std::default::Default for &'a GetReply {\n\n fn default() -> &'a GetReply {\n\n <GetReply as ::protobuf::Message>::default_instance()\n\n }\n", "file_path": "meteora-proto/src/proto/kv.rs", "rank": 53, "score": 21.280623878258545 }, { "content": " pub fn send_msg_async_opt(&self, req: &super::eraftpb::Message, opt: ::grpcio::CallOption) -> ::grpcio::Result<::grpcio::ClientUnaryReceiver<super::common::Null>> {\n\n self.client.unary_call_async(&METHOD_RAFT_SERVICE_SEND_MSG, req, opt)\n\n }\n\n\n\n pub fn send_msg_async(&self, req: &super::eraftpb::Message) -> ::grpcio::Result<::grpcio::ClientUnaryReceiver<super::common::Null>> {\n\n self.send_msg_async_opt(req, ::grpcio::CallOption::default())\n\n }\n\n\n\n pub fn send_address_opt(&self, req: &super::raft::AddressState, opt: ::grpcio::CallOption) -> ::grpcio::Result<super::common::Null> {\n\n self.client.unary_call(&METHOD_RAFT_SERVICE_SEND_ADDRESS, req, opt)\n\n }\n\n\n\n pub fn send_address(&self, req: &super::raft::AddressState) -> ::grpcio::Result<super::common::Null> {\n\n self.send_address_opt(req, ::grpcio::CallOption::default())\n\n }\n\n\n\n pub fn send_address_async_opt(&self, req: &super::raft::AddressState, opt: ::grpcio::CallOption) -> ::grpcio::Result<::grpcio::ClientUnaryReceiver<super::common::Null>> {\n\n self.client.unary_call_async(&METHOD_RAFT_SERVICE_SEND_ADDRESS, req, opt)\n\n }\n\n\n\n pub fn send_address_async(&self, req: &super::raft::AddressState) -> ::grpcio::Result<::grpcio::ClientUnaryReceiver<super::common::Null>> {\n\n self.send_address_async_opt(req, ::grpcio::CallOption::default())\n\n }\n\n pub fn spawn<F>(&self, f: F) where F: ::futures::Future<Item = (), Error = ()> + Send + 'static {\n\n self.client.spawn(f)\n\n }\n\n}\n\n\n", "file_path": "meteora-proto/src/proto/raft_grpc.rs", "rank": 54, "score": 21.105421276649 }, { "content": "\n\n // uint64 leader_id = 3;\n\n\n\n\n\n pub fn get_leader_id(&self) -> u64 {\n\n self.leader_id\n\n }\n\n pub fn clear_leader_id(&mut self) {\n\n self.leader_id = 0;\n\n }\n\n\n\n // Param is passed by value, moved\n\n pub fn set_leader_id(&mut self, v: u64) {\n\n self.leader_id = v;\n\n }\n\n}\n\n\n\nimpl ::protobuf::Message for ChangeReply {\n\n fn is_initialized(&self) -> bool {\n\n true\n", "file_path": "meteora-proto/src/proto/raft.rs", "rank": 55, "score": 20.980122995401082 }, { "content": "\n\n/// Generated files are compatible only with the same version\n\n/// of protobuf runtime.\n\n// const _PROTOBUF_VERSION_CHECK: () = ::protobuf::VERSION_2_22_1;\n\n\n\n#[derive(PartialEq,Clone,Default)]\n\npub struct StatusReply {\n\n // message fields\n\n pub state: super::common::State,\n\n pub address_map: ::std::collections::HashMap<u64, super::common::NodeAddress>,\n\n pub leader_id: u64,\n\n // special fields\n\n pub unknown_fields: ::protobuf::UnknownFields,\n\n pub cached_size: ::protobuf::CachedSize,\n\n}\n\n\n\nimpl<'a> ::std::default::Default for &'a StatusReply {\n\n fn default() -> &'a StatusReply {\n\n <StatusReply as ::protobuf::Message>::default_instance()\n\n }\n", "file_path": "meteora-proto/src/proto/raft.rs", "rank": 56, "score": 20.742172316906327 }, { "content": " // Mutable pointer to the field.\n\n pub fn mut_address_map(&mut self) -> &mut ::std::collections::HashMap<u64, super::common::NodeAddress> {\n\n &mut self.address_map\n\n }\n\n\n\n // Take field\n\n pub fn take_address_map(&mut self) -> ::std::collections::HashMap<u64, super::common::NodeAddress> {\n\n ::std::mem::replace(&mut self.address_map, ::std::collections::HashMap::new())\n\n }\n\n}\n\n\n\nimpl ::protobuf::Message for AddressState {\n\n fn is_initialized(&self) -> bool {\n\n true\n\n }\n\n\n\n fn merge_from(&mut self, is: &mut ::protobuf::CodedInputStream<'_>) -> ::protobuf::ProtobufResult<()> {\n\n while !is.eof()? {\n\n let (field_number, wire_type) = is.read_tag_unpack()?;\n\n match field_number {\n", "file_path": "meteora-proto/src/proto/raft.rs", "rank": 57, "score": 20.739778521458557 }, { "content": " pub fn set_leader_id(&mut self, v: u64) {\n\n self.leader_id = v;\n\n }\n\n}\n\n\n\nimpl ::protobuf::Message for PutReply {\n\n fn is_initialized(&self) -> bool {\n\n true\n\n }\n\n\n\n fn merge_from(&mut self, is: &mut ::protobuf::CodedInputStream<'_>) -> ::protobuf::ProtobufResult<()> {\n\n while !is.eof()? {\n\n let (field_number, wire_type) = is.read_tag_unpack()?;\n\n match field_number {\n\n 1 => {\n\n ::protobuf::rt::read_proto3_enum_with_unknown_fields_into(wire_type, is, &mut self.state, 1, &mut self.unknown_fields)?\n\n },\n\n 2 => {\n\n ::protobuf::rt::read_map_into::<::protobuf::types::ProtobufTypeUint64, ::protobuf::types::ProtobufTypeMessage<super::common::NodeAddress>>(wire_type, is, &mut self.address_map)?;\n\n },\n", "file_path": "meteora-proto/src/proto/kv.rs", "rank": 58, "score": 20.714266867377198 }, { "content": " self.state = v;\n\n }\n\n\n\n // repeated .meteora.kv.DeleteReply.AddressMapEntry address_map = 2;\n\n\n\n\n\n pub fn get_address_map(&self) -> &::std::collections::HashMap<u64, super::common::NodeAddress> {\n\n &self.address_map\n\n }\n\n pub fn clear_address_map(&mut self) {\n\n self.address_map.clear();\n\n }\n\n\n\n // Param is passed by value, moved\n\n pub fn set_address_map(&mut self, v: ::std::collections::HashMap<u64, super::common::NodeAddress>) {\n\n self.address_map = v;\n\n }\n\n\n\n // Mutable pointer to the field.\n\n pub fn mut_address_map(&mut self) -> &mut ::std::collections::HashMap<u64, super::common::NodeAddress> {\n", "file_path": "meteora-proto/src/proto/kv.rs", "rank": 59, "score": 20.645410882125745 }, { "content": " }\n\n}\n\n\n\nimpl DeleteReply {\n\n pub fn new() -> DeleteReply {\n\n ::std::default::Default::default()\n\n }\n\n\n\n // .meteora.common.State state = 1;\n\n\n\n\n\n pub fn get_state(&self) -> super::common::State {\n\n self.state\n\n }\n\n pub fn clear_state(&mut self) {\n\n self.state = super::common::State::UNKNOWN;\n\n }\n\n\n\n // Param is passed by value, moved\n\n pub fn set_state(&mut self, v: super::common::State) {\n", "file_path": "meteora-proto/src/proto/kv.rs", "rank": 60, "score": 20.111171833431218 }, { "content": "}\n\n\n\nimpl StatusReply {\n\n pub fn new() -> StatusReply {\n\n ::std::default::Default::default()\n\n }\n\n\n\n // .meteora.common.State state = 1;\n\n\n\n\n\n pub fn get_state(&self) -> super::common::State {\n\n self.state\n\n }\n\n pub fn clear_state(&mut self) {\n\n self.state = super::common::State::UNKNOWN;\n\n }\n\n\n\n // Param is passed by value, moved\n\n pub fn set_state(&mut self, v: super::common::State) {\n\n self.state = v;\n", "file_path": "meteora-proto/src/proto/raft.rs", "rank": 61, "score": 20.045163553534632 }, { "content": "use std::collections::HashMap;\n\nuse std::sync::mpsc::{self, Receiver, Sender};\n\nuse std::sync::Arc;\n\nuse std::thread;\n\nuse std::time::Duration;\n\n\n\nuse futures::Future;\n\nuse grpcio::{RpcContext, UnarySink};\n\nuse log::*;\n\nuse raft::storage::MemStorage;\n\nuse rocksdb::DB;\n\nuse serde::{Deserialize, Serialize};\n\n\n\nuse meteora_proto::proto::common::{NodeAddress, State};\n\nuse meteora_proto::proto::kv::{DeleteReply, DeleteReq, GetReply, GetReq, PutReply, PutReq};\n\nuse meteora_proto::proto::kv_grpc::KvService;\n\n\n\nuse crate::raft::config;\n\nuse crate::raft::server::RaftServer;\n\n\n", "file_path": "meteora-server/src/kv/server.rs", "rank": 62, "score": 19.773975138170933 }, { "content": " self.leader_id = 0;\n\n }\n\n\n\n // Param is passed by value, moved\n\n pub fn set_leader_id(&mut self, v: u64) {\n\n self.leader_id = v;\n\n }\n\n}\n\n\n\nimpl ::protobuf::Message for GetReply {\n\n fn is_initialized(&self) -> bool {\n\n true\n\n }\n\n\n\n fn merge_from(&mut self, is: &mut ::protobuf::CodedInputStream<'_>) -> ::protobuf::ProtobufResult<()> {\n\n while !is.eof()? {\n\n let (field_number, wire_type) = is.read_tag_unpack()?;\n\n match field_number {\n\n 1 => {\n\n ::protobuf::rt::read_singular_proto3_bytes_into(wire_type, is, &mut self.value)?;\n", "file_path": "meteora-proto/src/proto/kv.rs", "rank": 63, "score": 19.37718842587313 }, { "content": " fn as_ref(&self) -> ::protobuf::reflect::ReflectValueRef {\n\n ::protobuf::reflect::ReflectValueRef::Message(self)\n\n }\n\n}\n\n\n\n#[derive(PartialEq,Clone,Default)]\n\npub struct AddressState {\n\n // message fields\n\n pub address_map: ::std::collections::HashMap<u64, super::common::NodeAddress>,\n\n // special fields\n\n pub unknown_fields: ::protobuf::UnknownFields,\n\n pub cached_size: ::protobuf::CachedSize,\n\n}\n\n\n\nimpl<'a> ::std::default::Default for &'a AddressState {\n\n fn default() -> &'a AddressState {\n\n <AddressState as ::protobuf::Message>::default_instance()\n\n }\n\n}\n\n\n", "file_path": "meteora-proto/src/proto/raft.rs", "rank": 64, "score": 18.922914098063686 }, { "content": " }\n\n\n\n // repeated .meteora.raft.StatusReply.AddressMapEntry address_map = 2;\n\n\n\n\n\n pub fn get_address_map(&self) -> &::std::collections::HashMap<u64, super::common::NodeAddress> {\n\n &self.address_map\n\n }\n\n pub fn clear_address_map(&mut self) {\n\n self.address_map.clear();\n\n }\n\n\n\n // Param is passed by value, moved\n\n pub fn set_address_map(&mut self, v: ::std::collections::HashMap<u64, super::common::NodeAddress>) {\n\n self.address_map = v;\n\n }\n\n\n\n // Mutable pointer to the field.\n\n pub fn mut_address_map(&mut self) -> &mut ::std::collections::HashMap<u64, super::common::NodeAddress> {\n\n &mut self.address_map\n", "file_path": "meteora-proto/src/proto/raft.rs", "rank": 65, "score": 18.809155859117446 }, { "content": "\n\nconst METHOD_RAFT_SERVICE_SEND_ADDRESS: ::grpcio::Method<super::raft::AddressState, super::common::Null> = ::grpcio::Method {\n\n ty: ::grpcio::MethodType::Unary,\n\n name: \"/meteora.raft.RaftService/SendAddress\",\n\n req_mar: ::grpcio::Marshaller { ser: ::grpcio::pb_ser, de: ::grpcio::pb_de },\n\n resp_mar: ::grpcio::Marshaller { ser: ::grpcio::pb_ser, de: ::grpcio::pb_de },\n\n};\n\n\n\n#[derive(Clone)]\n\npub struct RaftServiceClient {\n\n client: ::grpcio::Client,\n\n}\n\n\n\nimpl RaftServiceClient {\n\n pub fn new(channel: ::grpcio::Channel) -> Self {\n\n RaftServiceClient {\n\n client: ::grpcio::Client::new(channel),\n\n }\n\n }\n\n\n", "file_path": "meteora-proto/src/proto/raft_grpc.rs", "rank": 66, "score": 18.447795430621976 }, { "content": " cnt_retry += 1;\n\n warn!(\"retry with a new leader: id={}\", self.leader_id);\n\n continue;\n\n }\n\n _ => {\n\n return Err(Error::new(\n\n ErrorKind::Other,\n\n format!(\n\n \"failed to leave node from the cluster: id={}\",\n\n req.get_node_id()\n\n ),\n\n ));\n\n }\n\n };\n\n }\n\n }\n\n\n\n pub fn status(&mut self) -> Result<HashMap<u64, NodeAddress>, std::io::Error> {\n\n let req = Null::new();\n\n\n", "file_path": "meteora-client/src/raft/client.rs", "rank": 67, "score": 18.336272390100614 }, { "content": "#[derive(Clone)]\n\npub struct KVServer {\n\n db: Arc<DB>,\n\n sender: Sender<config::Msg>,\n\n seq: u64,\n\n node_id: u64,\n\n}\n\n\n\n#[derive(Serialize, Deserialize, Clone)]\n\npub enum Op {\n\n Put { key: Vec<u8>, val: Vec<u8> },\n\n Delete { key: Vec<u8> },\n\n}\n\n\n\nimpl KVServer {\n\n pub fn new(\n\n db_path: String,\n\n raft_storage: MemStorage,\n\n node_id: u64,\n\n node_address: NodeAddress,\n", "file_path": "meteora-server/src/kv/server.rs", "rank": 68, "score": 18.111714837048922 }, { "content": " self.node_id = keys.get(self.next_index).unwrap().clone();\n\n\n\n match reply.get_state() {\n\n State::OK => {\n\n return Ok(reply.get_value().to_vec());\n\n }\n\n State::NOT_FOUND => {\n\n return Err(Error::new(\n\n ErrorKind::NotFound,\n\n format!(\"not found: key={:?}\", req.get_key()),\n\n ));\n\n }\n\n _ => {\n\n cnt_retry += 1;\n\n warn!(\"failed to get value: key={:?}\", req.get_key());\n\n }\n\n }\n\n }\n\n }\n\n\n", "file_path": "meteora-client/src/kv/client.rs", "rank": 69, "score": 17.89850102337096 }, { "content": "\n\n#[derive(Clone)]\n\npub struct KvServiceClient {\n\n client: ::grpcio::Client,\n\n}\n\n\n\nimpl KvServiceClient {\n\n pub fn new(channel: ::grpcio::Channel) -> Self {\n\n KvServiceClient {\n\n client: ::grpcio::Client::new(channel),\n\n }\n\n }\n\n\n\n pub fn get_opt(&self, req: &super::kv::GetReq, opt: ::grpcio::CallOption) -> ::grpcio::Result<super::kv::GetReply> {\n\n self.client.unary_call(&METHOD_KV_SERVICE_GET, req, opt)\n\n }\n\n\n\n pub fn get(&self, req: &super::kv::GetReq) -> ::grpcio::Result<super::kv::GetReply> {\n\n self.get_opt(req, ::grpcio::CallOption::default())\n\n }\n", "file_path": "meteora-proto/src/proto/kv_grpc.rs", "rank": 70, "score": 17.84845519490493 }, { "content": "use std::collections::HashMap;\n\nuse std::sync::mpsc::{Receiver, RecvTimeoutError, Sender};\n\nuse std::sync::Arc;\n\nuse std::thread;\n\nuse std::time::{Duration, Instant};\n\n\n\nuse bincode::{deserialize, serialize};\n\nuse grpcio::{ChannelBuilder, EnvBuilder};\n\nuse log::*;\n\nuse protobuf::Message as PMessage;\n\nuse raft::prelude::*;\n\nuse raft::storage::MemStorage;\n\n\n\nuse meteora_proto::proto::common::NodeAddress;\n\nuse meteora_proto::proto::raft::AddressState;\n\nuse meteora_proto::proto::raft_grpc::RaftServiceClient;\n\n\n\nuse crate::kv::server::Op;\n\n\n", "file_path": "meteora-server/src/raft/config.rs", "rank": 71, "score": 17.565525745745276 }, { "content": " addresses: HashMap<u64, NodeAddress>,\n\n ) -> (KVServer, RaftServer) {\n\n let db = DB::open_default(&db_path).unwrap();\n\n\n\n let (rs, rr) = mpsc::channel();\n\n let (apply_s, apply_r) = mpsc::channel();\n\n thread::spawn(move || {\n\n config::init_and_run(raft_storage, rr, apply_s, node_id, node_address, addresses);\n\n });\n\n\n\n let kv_server = KVServer {\n\n db: Arc::new(db),\n\n sender: rs.clone(),\n\n seq: 0,\n\n node_id,\n\n };\n\n let raft_server = RaftServer::new(rs, node_id);\n\n\n\n let db = kv_server.db.clone();\n\n thread::spawn(move || {\n", "file_path": "meteora-server/src/kv/server.rs", "rank": 72, "score": 17.462002495559 }, { "content": " self.leader_id = v;\n\n }\n\n}\n\n\n\nimpl ::protobuf::Message for DeleteReply {\n\n fn is_initialized(&self) -> bool {\n\n true\n\n }\n\n\n\n fn merge_from(&mut self, is: &mut ::protobuf::CodedInputStream<'_>) -> ::protobuf::ProtobufResult<()> {\n\n while !is.eof()? {\n\n let (field_number, wire_type) = is.read_tag_unpack()?;\n\n match field_number {\n\n 1 => {\n\n ::protobuf::rt::read_proto3_enum_with_unknown_fields_into(wire_type, is, &mut self.state, 1, &mut self.unknown_fields)?\n\n },\n\n 2 => {\n\n ::protobuf::rt::read_map_into::<::protobuf::types::ProtobufTypeUint64, ::protobuf::types::ProtobufTypeMessage<super::common::NodeAddress>>(wire_type, is, &mut self.address_map)?;\n\n },\n\n 3 => {\n", "file_path": "meteora-proto/src/proto/kv.rs", "rank": 73, "score": 17.22833907408001 }, { "content": "use std::collections::HashMap;\n\nuse std::io::{Error, ErrorKind};\n\nuse std::sync::Arc;\n\n\n\nuse grpcio::{ChannelBuilder, EnvBuilder};\n\nuse log::*;\n\n\n\nuse meteora_proto::proto::common::{Null, State};\n\nuse meteora_proto::proto::kv::{DeleteReq, GetReq, PutReq};\n\nuse meteora_proto::proto::kv_grpc::KvServiceClient;\n\n\n\nuse crate::raft::client::create_raft_client;\n\n\n", "file_path": "meteora-client/src/kv/client.rs", "rank": 74, "score": 17.1979703282013 }, { "content": " ),\n\n ));\n\n }\n\n };\n\n }\n\n }\n\n\n\n pub fn leave(&mut self, id: u64) -> Result<HashMap<u64, NodeAddress>, std::io::Error> {\n\n let mut req = ConfChange::new();\n\n req.set_node_id(id);\n\n req.set_change_type(ConfChangeType::RemoveNode);\n\n req.set_context(vec![]);\n\n\n\n let max_retry = 10;\n\n let mut cnt_retry = 0;\n\n\n\n loop {\n\n if max_retry < cnt_retry {\n\n return Err(Error::new(\n\n ErrorKind::Other,\n", "file_path": "meteora-client/src/raft/client.rs", "rank": 75, "score": 17.19494501370961 }, { "content": " cb: callback,\n\n }) => {\n\n debug!(\"receive config change message\");\n\n let leader_id = r.raft.leader_id;\n\n if r.raft.leader_id != r.raft.id {\n\n // not leader, callback to notify client\n\n debug!(\"not a leader\");\n\n callback(leader_id as i32, addresses.clone());\n\n continue;\n\n } else {\n\n callbacks.insert(seq, callback);\n\n debug!(\"propose config change\");\n\n r.propose_conf_change(serialize(&seq).unwrap(), change)\n\n .unwrap();\n\n }\n\n }\n\n Ok(Msg::Read { cb: callback }) => {\n\n let leader_id = r.raft.leader_id;\n\n callback(leader_id as i32, addresses.clone());\n\n continue;\n", "file_path": "meteora-server/src/raft/config.rs", "rank": 76, "score": 17.1679844102014 }, { "content": " pub fn mut_address_map(&mut self) -> &mut ::std::collections::HashMap<u64, super::common::NodeAddress> {\n\n &mut self.address_map\n\n }\n\n\n\n // Take field\n\n pub fn take_address_map(&mut self) -> ::std::collections::HashMap<u64, super::common::NodeAddress> {\n\n ::std::mem::replace(&mut self.address_map, ::std::collections::HashMap::new())\n\n }\n\n\n\n // uint64 leader_id = 3;\n\n\n\n\n\n pub fn get_leader_id(&self) -> u64 {\n\n self.leader_id\n\n }\n\n pub fn clear_leader_id(&mut self) {\n\n self.leader_id = 0;\n\n }\n\n\n\n // Param is passed by value, moved\n", "file_path": "meteora-proto/src/proto/kv.rs", "rank": 77, "score": 17.03216331384165 }, { "content": " &mut self.address_map\n\n }\n\n\n\n // Take field\n\n pub fn take_address_map(&mut self) -> ::std::collections::HashMap<u64, super::common::NodeAddress> {\n\n ::std::mem::replace(&mut self.address_map, ::std::collections::HashMap::new())\n\n }\n\n\n\n // uint64 leader_id = 3;\n\n\n\n\n\n pub fn get_leader_id(&self) -> u64 {\n\n self.leader_id\n\n }\n\n pub fn clear_leader_id(&mut self) {\n\n self.leader_id = 0;\n\n }\n\n\n\n // Param is passed by value, moved\n\n pub fn set_leader_id(&mut self, v: u64) {\n", "file_path": "meteora-proto/src/proto/kv.rs", "rank": 78, "score": 17.02772654388457 }, { "content": " debug!(\"node is in use: id={}, address={}\", id, address);\n\n } else {\n\n debug!(\"node is not in use: id={}, address={}\", id, address);\n\n self.addresses.remove(id);\n\n self.clients.remove(id);\n\n }\n\n }\n\n\n\n debug!(\"addresses={:?}\", self.addresses);\n\n\n\n match reply.get_state() {\n\n State::OK => {\n\n return Ok(reply.get_address_map().clone());\n\n }\n\n State::WRONG_LEADER => {\n\n warn!(\n\n \"upddate leader id: current={}, new={}\",\n\n self.leader_id,\n\n reply.get_leader_id()\n\n );\n", "file_path": "meteora-client/src/raft/client.rs", "rank": 79, "score": 16.981896450880587 }, { "content": " &self.address_map\n\n }\n\n pub fn clear_address_map(&mut self) {\n\n self.address_map.clear();\n\n }\n\n\n\n // Param is passed by value, moved\n\n pub fn set_address_map(&mut self, v: ::std::collections::HashMap<u64, super::common::NodeAddress>) {\n\n self.address_map = v;\n\n }\n\n\n\n // Mutable pointer to the field.\n\n pub fn mut_address_map(&mut self) -> &mut ::std::collections::HashMap<u64, super::common::NodeAddress> {\n\n &mut self.address_map\n\n }\n\n\n\n // Take field\n\n pub fn take_address_map(&mut self) -> ::std::collections::HashMap<u64, super::common::NodeAddress> {\n\n ::std::mem::replace(&mut self.address_map, ::std::collections::HashMap::new())\n\n }\n", "file_path": "meteora-proto/src/proto/raft.rs", "rank": 80, "score": 16.90677292231195 }, { "content": " }\n\n}\n\n\n\nimpl ::protobuf::Message for StatusReply {\n\n fn is_initialized(&self) -> bool {\n\n true\n\n }\n\n\n\n fn merge_from(&mut self, is: &mut ::protobuf::CodedInputStream<'_>) -> ::protobuf::ProtobufResult<()> {\n\n while !is.eof()? {\n\n let (field_number, wire_type) = is.read_tag_unpack()?;\n\n match field_number {\n\n 1 => {\n\n ::protobuf::rt::read_proto3_enum_with_unknown_fields_into(wire_type, is, &mut self.state, 1, &mut self.unknown_fields)?\n\n },\n\n 2 => {\n\n ::protobuf::rt::read_map_into::<::protobuf::types::ProtobufTypeUint64, ::protobuf::types::ProtobufTypeMessage<super::common::NodeAddress>>(wire_type, is, &mut self.address_map)?;\n\n },\n\n 3 => {\n\n if wire_type != ::protobuf::wire_format::WireTypeVarint {\n", "file_path": "meteora-proto/src/proto/raft.rs", "rank": 81, "score": 16.64046134379654 }, { "content": " seq,\n\n op,\n\n cb: callback,\n\n }) => {\n\n debug!(\"receive propose message\");\n\n let leader_id = r.raft.leader_id;\n\n if r.raft.leader_id != r.raft.id {\n\n // not leader, callback to notify client\n\n debug!(\"not a leader\");\n\n callback(leader_id as i32, addresses.clone());\n\n continue;\n\n }\n\n let serialized_op = serialize(&op).unwrap();\n\n callbacks.insert(seq, callback);\n\n debug!(\"propose\");\n\n r.propose(serialize(&seq).unwrap(), serialized_op).unwrap();\n\n }\n\n Ok(Msg::ConfigChange {\n\n seq,\n\n change,\n", "file_path": "meteora-server/src/raft/config.rs", "rank": 82, "score": 16.62730730324671 }, { "content": " }\n\n\n\n // Take field\n\n pub fn take_address_map(&mut self) -> ::std::collections::HashMap<u64, super::common::NodeAddress> {\n\n ::std::mem::replace(&mut self.address_map, ::std::collections::HashMap::new())\n\n }\n\n\n\n // uint64 leader_id = 3;\n\n\n\n\n\n pub fn get_leader_id(&self) -> u64 {\n\n self.leader_id\n\n }\n\n pub fn clear_leader_id(&mut self) {\n\n self.leader_id = 0;\n\n }\n\n\n\n // Param is passed by value, moved\n\n pub fn set_leader_id(&mut self, v: u64) {\n\n self.leader_id = v;\n", "file_path": "meteora-proto/src/proto/raft.rs", "rank": 83, "score": 16.624410197034734 }, { "content": " } else {\n\n debug!(\"node is not in use: id={}, address={}\", id, address);\n\n self.addresses.remove(id);\n\n self.clients.remove(id);\n\n }\n\n }\n\n\n\n debug!(\"addresses={:?}\", self.addresses);\n\n\n\n match reply.get_state() {\n\n State::OK => {\n\n return Ok(reply.get_address_map().clone());\n\n }\n\n State::WRONG_LEADER => {\n\n warn!(\n\n \"upddate leader id: current={}, new={}\",\n\n self.leader_id,\n\n reply.get_leader_id()\n\n );\n\n self.leader_id = reply.get_leader_id();\n", "file_path": "meteora-client/src/raft/client.rs", "rank": 84, "score": 16.245836966245815 }, { "content": "\n\n fn new() -> ChangeReply {\n\n ChangeReply::new()\n\n }\n\n\n\n fn descriptor_static() -> &'static ::protobuf::reflect::MessageDescriptor {\n\n static descriptor: ::protobuf::rt::LazyV2<::protobuf::reflect::MessageDescriptor> = ::protobuf::rt::LazyV2::INIT;\n\n descriptor.get(|| {\n\n let mut fields = ::std::vec::Vec::new();\n\n fields.push(::protobuf::reflect::accessor::make_simple_field_accessor::<_, ::protobuf::types::ProtobufTypeEnum<super::common::State>>(\n\n \"state\",\n\n |m: &ChangeReply| { &m.state },\n\n |m: &mut ChangeReply| { &mut m.state },\n\n ));\n\n fields.push(::protobuf::reflect::accessor::make_map_accessor::<_, ::protobuf::types::ProtobufTypeUint64, ::protobuf::types::ProtobufTypeMessage<super::common::NodeAddress>>(\n\n \"address_map\",\n\n |m: &ChangeReply| { &m.address_map },\n\n |m: &mut ChangeReply| { &mut m.address_map },\n\n ));\n\n fields.push(::protobuf::reflect::accessor::make_simple_field_accessor::<_, ::protobuf::types::ProtobufTypeUint64>(\n", "file_path": "meteora-proto/src/proto/raft.rs", "rank": 85, "score": 16.16650786928031 }, { "content": "}\n\n\n\nimpl PutReq {\n\n pub fn new() -> PutReq {\n\n ::std::default::Default::default()\n\n }\n\n\n\n // bytes key = 1;\n\n\n\n\n\n pub fn get_key(&self) -> &[u8] {\n\n &self.key\n\n }\n\n pub fn clear_key(&mut self) {\n\n self.key.clear();\n\n }\n\n\n\n // Param is passed by value, moved\n\n pub fn set_key(&mut self, v: ::std::vec::Vec<u8>) {\n\n self.key = v;\n", "file_path": "meteora-proto/src/proto/kv.rs", "rank": 86, "score": 16.11619826020511 }, { "content": "}\n\n\n\nimpl DeleteReq {\n\n pub fn new() -> DeleteReq {\n\n ::std::default::Default::default()\n\n }\n\n\n\n // bytes key = 1;\n\n\n\n\n\n pub fn get_key(&self) -> &[u8] {\n\n &self.key\n\n }\n\n pub fn clear_key(&mut self) {\n\n self.key.clear();\n\n }\n\n\n\n // Param is passed by value, moved\n\n pub fn set_key(&mut self, v: ::std::vec::Vec<u8>) {\n\n self.key = v;\n", "file_path": "meteora-proto/src/proto/kv.rs", "rank": 87, "score": 16.11619826020511 }, { "content": "impl GetReq {\n\n pub fn new() -> GetReq {\n\n ::std::default::Default::default()\n\n }\n\n\n\n // bytes key = 1;\n\n\n\n\n\n pub fn get_key(&self) -> &[u8] {\n\n &self.key\n\n }\n\n pub fn clear_key(&mut self) {\n\n self.key.clear();\n\n }\n\n\n\n // Param is passed by value, moved\n\n pub fn set_key(&mut self, v: ::std::vec::Vec<u8>) {\n\n self.key = v;\n\n }\n\n\n", "file_path": "meteora-proto/src/proto/kv.rs", "rank": 88, "score": 16.11619826020511 }, { "content": " .apply_snapshot(ready.snapshot.clone())\n\n .unwrap();\n\n }\n\n\n\n if !ready.entries.is_empty() {\n\n // Append entries to the Raft log\n\n r.mut_store().wl().append(&ready.entries).unwrap();\n\n }\n\n\n\n if let Some(ref hs) = ready.hs {\n\n // Raft HardState changed, and we need to persist it.\n\n r.mut_store().wl().set_hardstate(hs.clone());\n\n }\n\n\n\n if !is_leader {\n\n // If not leader, the follower needs to reply the messages to\n\n // the leader after appending Raft entries.\n\n let msgs = ready.messages.drain(..);\n\n for msg in msgs {\n\n // Send messages to other peers.\n", "file_path": "meteora-server/src/raft/config.rs", "rank": 89, "score": 16.109509322363962 }, { "content": "use std::collections::HashMap;\n\nuse std::io::{Error, ErrorKind};\n\nuse std::sync::Arc;\n\n\n\nuse bincode::serialize;\n\nuse grpcio::{ChannelBuilder, EnvBuilder};\n\nuse log::*;\n\nuse raft::eraftpb::{ConfChange, ConfChangeType};\n\n\n\nuse meteora_proto::proto::common::{NodeAddress, Null, State};\n\nuse meteora_proto::proto::raft_grpc::RaftServiceClient;\n\n\n", "file_path": "meteora-client/src/raft/client.rs", "rank": 90, "score": 16.10219385242948 }, { "content": " Arc::new(create_kv_client(address.kv_address.clone())),\n\n );\n\n }\n\n }\n\n\n\n // remove unused ids\n\n for (id, address) in &self.addresses.clone() {\n\n if reply.get_address_map().contains_key(&id) {\n\n debug!(\"node is in use: id={}, address={}\", id, address);\n\n } else {\n\n debug!(\"node is not in use: id={}, address={}\", id, address);\n\n self.addresses.remove(id);\n\n self.clients.remove(id);\n\n }\n\n }\n\n\n\n debug!(\"addresses={:?}\", self.addresses);\n\n\n\n match reply.get_state() {\n\n State::OK => {\n", "file_path": "meteora-client/src/kv/client.rs", "rank": 91, "score": 16.07981305159666 }, { "content": " fn into_any(self: ::std::boxed::Box<Self>) -> ::std::boxed::Box<dyn (::std::any::Any)> {\n\n self\n\n }\n\n\n\n fn descriptor(&self) -> &'static ::protobuf::reflect::MessageDescriptor {\n\n Self::descriptor_static()\n\n }\n\n\n\n fn new() -> DeleteReply {\n\n DeleteReply::new()\n\n }\n\n\n\n fn descriptor_static() -> &'static ::protobuf::reflect::MessageDescriptor {\n\n static descriptor: ::protobuf::rt::LazyV2<::protobuf::reflect::MessageDescriptor> = ::protobuf::rt::LazyV2::INIT;\n\n descriptor.get(|| {\n\n let mut fields = ::std::vec::Vec::new();\n\n fields.push(::protobuf::reflect::accessor::make_simple_field_accessor::<_, ::protobuf::types::ProtobufTypeEnum<super::common::State>>(\n\n \"state\",\n\n |m: &DeleteReply| { &m.state },\n\n |m: &mut DeleteReply| { &mut m.state },\n", "file_path": "meteora-proto/src/proto/kv.rs", "rank": 92, "score": 16.078797820855364 }, { "content": "use std::fmt;\n\n\n\nuse serde::de::{self, Deserialize, Deserializer, MapAccess, SeqAccess, Visitor};\n\nuse serde::ser::{Serialize, SerializeStruct, Serializer};\n\n\n\nuse crate::proto::common::NodeAddress;\n\n\n\nconst NODE_ADDRESS_FIELDS: &'static [&'static str] = &[\"kv_address\", \"raft_address\"];\n\n\n\nimpl Serialize for NodeAddress {\n\n fn serialize<S>(&self, serializer: S) -> Result<<S as Serializer>::Ok, <S as Serializer>::Error>\n\n where\n\n S: Serializer,\n\n {\n\n let mut node_address =\n\n serializer.serialize_struct(\"NodeAddress\", NODE_ADDRESS_FIELDS.len())?;\n\n node_address.serialize_field(\"kv_address\", &self.kv_address)?;\n\n node_address.serialize_field(\"raft_address\", &self.raft_address)?;\n\n node_address.end()\n\n }\n", "file_path": "meteora-proto/src/proto/common_ext.rs", "rank": 93, "score": 16.064046356100377 }, { "content": "}\n\n\n\nimpl GetReply {\n\n pub fn new() -> GetReply {\n\n ::std::default::Default::default()\n\n }\n\n\n\n // bytes value = 1;\n\n\n\n\n\n pub fn get_value(&self) -> &[u8] {\n\n &self.value\n\n }\n\n pub fn clear_value(&mut self) {\n\n self.value.clear();\n\n }\n\n\n\n // Param is passed by value, moved\n\n pub fn set_value(&mut self, v: ::std::vec::Vec<u8>) {\n\n self.value = v;\n", "file_path": "meteora-proto/src/proto/kv.rs", "rank": 94, "score": 16.022050041513644 }, { "content": " ));\n\n }\n\n };\n\n\n\n let reply = match client.change_config(&req) {\n\n Ok(r) => r,\n\n _ => {\n\n return Err(Error::new(\n\n ErrorKind::Other,\n\n format!(\n\n \"failed to join node to the cluster: id={}\",\n\n req.get_node_id()\n\n ),\n\n ));\n\n }\n\n };\n\n\n\n // update address list and clients\n\n // add new ids\n\n for (id, address) in reply.get_address_map() {\n", "file_path": "meteora-client/src/raft/client.rs", "rank": 95, "score": 15.983842547239455 }, { "content": " self as &dyn (::std::any::Any)\n\n }\n\n fn as_any_mut(&mut self) -> &mut dyn (::std::any::Any) {\n\n self as &mut dyn (::std::any::Any)\n\n }\n\n fn into_any(self: ::std::boxed::Box<Self>) -> ::std::boxed::Box<dyn (::std::any::Any)> {\n\n self\n\n }\n\n\n\n fn descriptor(&self) -> &'static ::protobuf::reflect::MessageDescriptor {\n\n Self::descriptor_static()\n\n }\n\n\n\n fn new() -> AddressState {\n\n AddressState::new()\n\n }\n\n\n\n fn descriptor_static() -> &'static ::protobuf::reflect::MessageDescriptor {\n\n static descriptor: ::protobuf::rt::LazyV2<::protobuf::reflect::MessageDescriptor> = ::protobuf::rt::LazyV2::INIT;\n\n descriptor.get(|| {\n", "file_path": "meteora-proto/src/proto/raft.rs", "rank": 96, "score": 15.964502117121096 }, { "content": "\n\nimpl ::protobuf::reflect::ProtobufValue for PutReply {\n\n fn as_ref(&self) -> ::protobuf::reflect::ReflectValueRef {\n\n ::protobuf::reflect::ReflectValueRef::Message(self)\n\n }\n\n}\n\n\n\n#[derive(PartialEq,Clone,Default)]\n\npub struct DeleteReq {\n\n // message fields\n\n pub key: ::std::vec::Vec<u8>,\n\n // special fields\n\n pub unknown_fields: ::protobuf::UnknownFields,\n\n pub cached_size: ::protobuf::CachedSize,\n\n}\n\n\n\nimpl<'a> ::std::default::Default for &'a DeleteReq {\n\n fn default() -> &'a DeleteReq {\n\n <DeleteReq as ::protobuf::Message>::default_instance()\n\n }\n", "file_path": "meteora-proto/src/proto/kv.rs", "rank": 97, "score": 15.948526586968653 }, { "content": "}\n\n\n\n#[derive(Clone,PartialEq,Eq,Debug,Hash)]\n\npub enum State {\n\n UNKNOWN = 0,\n\n OK = 1,\n\n WRONG_LEADER = 2,\n\n NOT_FOUND = 3,\n\n IO_ERROR = 4,\n\n}\n\n\n\nimpl ::protobuf::ProtobufEnum for State {\n\n fn value(&self) -> i32 {\n\n *self as i32\n\n }\n\n\n\n fn from_i32(value: i32) -> ::std::option::Option<State> {\n\n match value {\n\n 0 => ::std::option::Option::Some(State::UNKNOWN),\n\n 1 => ::std::option::Option::Some(State::OK),\n", "file_path": "meteora-proto/src/proto/common.rs", "rank": 98, "score": 15.876401973272229 }, { "content": " instance.get(StatusReply::new)\n\n }\n\n}\n\n\n\nimpl ::protobuf::Clear for StatusReply {\n\n fn clear(&mut self) {\n\n self.state = super::common::State::UNKNOWN;\n\n self.address_map.clear();\n\n self.leader_id = 0;\n\n self.unknown_fields.clear();\n\n }\n\n}\n\n\n\nimpl ::std::fmt::Debug for StatusReply {\n\n fn fmt(&self, f: &mut ::std::fmt::Formatter<'_>) -> ::std::fmt::Result {\n\n ::protobuf::text_format::fmt(self, f)\n\n }\n\n}\n\n\n\nimpl ::protobuf::reflect::ProtobufValue for StatusReply {\n", "file_path": "meteora-proto/src/proto/raft.rs", "rank": 99, "score": 15.781425253041999 } ]
Rust
crates/irust/src/irust/script/mod.rs
i10416/IRust
6faff9bb1fc52597cdd4698e1179932885da375c
use crossterm::event::Event; use irust_api::{Command, GlobalVariables}; use self::script4::ScriptManager4; use super::options::Options; pub mod script4; pub trait Script { fn input_prompt(&mut self, _global_variables: &GlobalVariables) -> Option<String>; fn get_output_prompt(&mut self, _global_variables: &GlobalVariables) -> Option<String>; fn before_compiling(&mut self, _global_variables: &GlobalVariables) -> Option<()>; fn input_event_hook( &mut self, _global_variables: &GlobalVariables, _event: Event, ) -> Option<Command>; fn after_compiling(&mut self, _global_variables: &GlobalVariables) -> Option<()>; fn output_event_hook( &mut self, _input: &str, _global_variables: &GlobalVariables, ) -> Option<Command>; fn list(&self) -> Option<String>; fn activate(&mut self, _script: &str) -> Result<Option<Command>, &'static str>; fn deactivate(&mut self, _script: &str) -> Result<Option<Command>, &'static str>; fn trigger_set_title_hook(&mut self) -> Option<String>; fn trigger_set_msg_hook(&mut self) -> Option<String>; fn startup_cmds(&mut self) -> Vec<Result<Option<Command>, rscript::Error>>; fn shutdown_cmds(&mut self) -> Vec<Result<Option<Command>, rscript::Error>>; } impl super::IRust { pub fn update_input_prompt(&mut self) { if let Some(ref mut script_mg) = self.script_mg { if let Some(prompt) = script_mg.input_prompt(&self.global_variables) { self.printer.set_prompt(prompt); } } } pub fn get_output_prompt(&mut self) -> String { if let Some(ref mut script_mg) = self.script_mg { if let Some(prompt) = script_mg.get_output_prompt(&self.global_variables) { return prompt; } } self.options.output_prompt.clone() } pub fn before_compiling_hook(&mut self) { if let Some(ref mut script_mg) = self.script_mg { script_mg.before_compiling(&self.global_variables); } } pub fn input_event_hook(&mut self, event: Event) -> Option<Command> { if let Some(ref mut script_mg) = self.script_mg { return script_mg.input_event_hook(&self.global_variables, event); } None } pub fn after_compiling_hook(&mut self) { if let Some(ref mut script_mg) = self.script_mg { script_mg.after_compiling(&self.global_variables); } } pub fn output_event_hook(&mut self, input: &str) -> Option<Command> { if let Some(ref mut script_mg) = self.script_mg { return script_mg.output_event_hook(input, &self.global_variables); } None } pub fn trigger_set_title_hook(&mut self) -> Option<String> { if let Some(ref mut script_mg) = self.script_mg { return script_mg.trigger_set_title_hook(); } None } pub fn trigger_set_msg_hook(&mut self) -> Option<String> { if let Some(ref mut script_mg) = self.script_mg { return script_mg.trigger_set_msg_hook(); } None } pub fn scripts_list(&self) -> Option<String> { if let Some(ref script_mg) = self.script_mg { return script_mg.list(); } None } pub fn activate_script(&mut self, script: &str) -> Result<Option<Command>, &'static str> { if let Some(ref mut script_mg) = self.script_mg { return script_mg.activate(script); } Ok(None) } pub fn deactivate_script(&mut self, script: &str) -> Result<Option<Command>, &'static str> { if let Some(ref mut script_mg) = self.script_mg { return script_mg.deactivate(script); } Ok(None) } pub fn choose_script_mg(options: &Options) -> Option<Box<dyn Script>> { if options.activate_scripting { ScriptManager4::new().map(|script_mg| Box::new(script_mg) as Box<dyn Script>) } else { None } } pub fn update_script_state(&mut self) { self.global_variables.prompt_position = self.printer.cursor.starting_pos(); self.global_variables.cursor_position = self.printer.cursor.current_pos(); self.global_variables.is_racer_suggestion_active = self .racer .as_ref() .and_then(|r| r.active_suggestion.as_ref()) .is_some(); } pub fn run_scripts_startup_cmds(&mut self) -> super::Result<()> { if let Some(ref mut script_mg) = self.script_mg { for cmd in script_mg.startup_cmds() { if let Some(cmd) = cmd? { self.execute(cmd)?; } } } Ok(()) } pub fn run_scripts_shutdown_cmds(&mut self) -> super::Result<()> { if let Some(ref mut script_mg) = self.script_mg { for cmd in script_mg.shutdown_cmds() { if let Some(cmd) = cmd? { self.execute(cmd)?; } } } Ok(()) } }
use crossterm::event::Event; use irust_api::{Command, GlobalVariables}; use self::script4::ScriptManager4; use super::options::Options; pub mod script4; pub trait Script { fn input_prompt(&mut self, _global_variables: &GlobalVariables) -> Option<String>; fn get_output_prompt(&mut self, _global_variables: &GlobalVariables) -> Option<String>; fn before_compiling(&mut self, _global_variables: &GlobalVariables) -> Option<()>; fn input_event_hook( &mut self, _global_variables: &GlobalVariables, _event: Event, ) -> Option<Command>; fn after_compiling(&mut self, _global_variables: &GlobalVariables) -> Option<()>; fn output_event_hook( &mut self, _input: &str, _global_variables: &GlobalVariables, ) -> Option<Command>; fn list(&self) -> Option<String>; fn activate(&mut self, _script: &str) -> Result<Option<Command>, &'static str>; fn deactivate(&mut self, _script: &str) -> Result<Option<Command>, &'static str>; fn trigger_set_title_hook(&mut self) -> Option<String>; fn trigger_set_msg_hook(&mut self) -> Option<String>; fn startup_cmds(&mut self) -> Vec<Result<Option<Command>, rscript::Error>>; fn shutdown_cmds(&mut self) -> Vec<Result<Option<Command>, rscript::Error>>; } impl super::IRust { pub fn update_input_prompt(&mut self) { if let Some(ref mut script_mg) = self.script_mg { if let Some(prompt) = script_mg.input_prompt(&self.global_variables) { self.printer.set_prompt(prompt); } } } pub fn get_output_prompt(&mut self) -> String { if let Some(ref mut script_mg) = self.script_mg { if let Some(prompt) = script_mg.get_output_prompt(&self.global_variables) { return prompt; } } self.options.output_prompt.clone() } pub fn before_compiling_hook(&mut self) { if let Some(ref mut script_mg) = self.script_mg { script_mg.before_compiling(&self.global_variables); } } pub fn input_event_hook(&mut self, event: Event) -> Option<Command> { if let Some(ref mut script_mg) = self.script_mg { return script_mg.input_event_hook(&self.global_variables, event); } None } pub fn after_compiling_hook(&mut self) { if let Some(ref mut script_mg) = self.script_mg { script_mg.after_compiling(&self.global_variables); } } pub fn output_event_hook(&mut self, input: &str) -> Option<Command> { if let Some(ref mut script_mg) = self.script_mg { return script_mg.output_event_hook(input, &self.global_variables); } None } pub fn trigger_set_title_hook(&mut self) -> Option<String> { if let Some(ref mut script_mg) = self.script_mg { return script_mg.trigger_set_title_hook(); } None } pub fn trigger_set_msg_hook(&mut self) -> Option<String> { if let Some(ref mut script_mg) = self.script_mg { return script_mg.trigger_set_msg_hook(); } None } pub fn scripts_list(&self) -> Option<String> { if let Some(ref script_mg) = self.script_mg { return script_mg.list(); } None } pub fn activate_script(&mut self, script: &str) -> Result<Option<Comman
pub fn deactivate_script(&mut self, script: &str) -> Result<Option<Command>, &'static str> { if let Some(ref mut script_mg) = self.script_mg { return script_mg.deactivate(script); } Ok(None) } pub fn choose_script_mg(options: &Options) -> Option<Box<dyn Script>> { if options.activate_scripting { ScriptManager4::new().map(|script_mg| Box::new(script_mg) as Box<dyn Script>) } else { None } } pub fn update_script_state(&mut self) { self.global_variables.prompt_position = self.printer.cursor.starting_pos(); self.global_variables.cursor_position = self.printer.cursor.current_pos(); self.global_variables.is_racer_suggestion_active = self .racer .as_ref() .and_then(|r| r.active_suggestion.as_ref()) .is_some(); } pub fn run_scripts_startup_cmds(&mut self) -> super::Result<()> { if let Some(ref mut script_mg) = self.script_mg { for cmd in script_mg.startup_cmds() { if let Some(cmd) = cmd? { self.execute(cmd)?; } } } Ok(()) } pub fn run_scripts_shutdown_cmds(&mut self) -> super::Result<()> { if let Some(ref mut script_mg) = self.script_mg { for cmd in script_mg.shutdown_cmds() { if let Some(cmd) = cmd? { self.execute(cmd)?; } } } Ok(()) } }
d>, &'static str> { if let Some(ref mut script_mg) = self.script_mg { return script_mg.activate(script); } Ok(None) }
function_block-function_prefixed
[ { "content": "fn _remove_main(script: &str) -> String {\n\n const MAIN_FN: &str = \"fn main() {\";\n\n\n\n let mut script = remove_comments(script);\n\n\n\n let main_start = match script.find(MAIN_FN) {\n\n Some(idx) if _balanced_quotes(&script[..idx]) => idx,\n\n _ => return script,\n\n };\n\n\n\n let open_tag = main_start + MAIN_FN.len();\n\n\n\n let mut close_tag = None;\n\n\n\n // look for closing tag\n\n let mut tag_score = 1;\n\n for (idx, character) in script[open_tag + 1..].chars().enumerate() {\n\n if character == '{' {\n\n tag_score += 1;\n\n }\n", "file_path": "crates/irust/src/utils.rs", "rank": 1, "score": 204465.28938551102 }, { "content": "pub fn handle_args(args: &[String], options: &mut Options) -> ArgsResult {\n\n match args[0].as_str() {\n\n \"-h\" | \"--help\" => {\n\n println!(\n\n \"IRust: Cross Platform Rust REPL\n\n version: {}\\n\n\n config file is in {}\\n\n\n irust {{path_to_rust_file}} will start IRust with the file loaded in the repl\n\n --help => shows this message\n\n --reset-config => reset IRust configuration to default\",\n\n VERSION,\n\n Options::config_path()\n\n .map(|p| p.to_string_lossy().to_string())\n\n .unwrap_or_else(|| \"??\".into())\n\n );\n\n ArgsResult::Exit\n\n }\n\n\n\n \"-v\" | \"--version\" => {\n\n println!(\"{}\", VERSION);\n", "file_path": "crates/irust/src/args.rs", "rank": 2, "score": 204393.04970419552 }, { "content": "pub fn find_workpace_root(metadata: String) -> Option<String> {\n\n let start = metadata.find(\"workspace_root\")? + 17;\n\n let end = metadata[start..].find('\"')?;\n\n Some(metadata[start..start + end].to_string())\n\n}\n\n\n", "file_path": "crates/irust/src/utils.rs", "rank": 3, "score": 200089.79815473902 }, { "content": "pub fn warn_about_opt_deps(options: &mut Options) {\n\n let opt_deps: [Dep; 5] = [\n\n Dep::new(\"racer\", \"racer\", \"auto_completion\", &|| {\n\n let mut exit_status = vec![];\n\n let mut run_cmd = |cmd: &[&str]| -> io::Result<()> {\n\n println!(\"{}\", format!(\"Running: {:?}\", cmd).magenta());\n\n exit_status.push(process::Command::new(cmd[0]).args(&cmd[1..]).status()?);\n\n Ok(())\n\n };\n\n\n\n if !dep_installed(\"rustup\") {\n\n println!(\n\n \"{}\",\n\n \"rustup is not installed.\\nrustup is required to install and configure racer\"\n\n .red()\n\n );\n\n return Err(io::Error::new(\n\n io::ErrorKind::Other,\n\n \"rustup is not installed\",\n\n ));\n", "file_path": "crates/irust/src/dependencies.rs", "rank": 4, "score": 181382.41200102895 }, { "content": "pub fn theme_color_to_term_color(color: &str) -> Option<Color> {\n\n if color.starts_with('#') {\n\n if color.len() != 7 {\n\n return None;\n\n }\n\n // Hex color name\n\n let parse = || -> Option<Color> {\n\n let color = &color[1..];\n\n let r = u8::from_str_radix(&color[0..2], 16).ok()?;\n\n let g = u8::from_str_radix(&color[2..4], 16).ok()?;\n\n let b = u8::from_str_radix(&color[4..], 16).ok()?;\n\n Some(Color::Rgb { r, g, b })\n\n };\n\n parse()\n\n } else {\n\n // we only support lowercase for performance\n\n // because this is a hot path\n\n match color {\n\n \"black\" => Some(Color::Black),\n\n \"dark_grey\" => Some(Color::DarkGrey),\n", "file_path": "crates/irust/src/irust/highlight/theme.rs", "rank": 5, "score": 172954.6832558472 }, { "content": "pub fn cargo_fmt(c: &str) -> std::io::Result<String> {\n\n let fmt_path = IRUST_DIR.join(\"fmt_file\");\n\n // Ignore file doesn't exist error\n\n let _ = fs::remove_file(&fmt_path);\n\n\n\n let mut fmt_file = fs::OpenOptions::new()\n\n .create(true)\n\n .read(true)\n\n .write(true)\n\n .open(&fmt_path)?;\n\n\n\n write!(fmt_file, \"{}\", c)?;\n\n\n\n cargo_fmt_file(&fmt_path);\n\n\n\n let mut fmt_c = String::new();\n\n fmt_file.seek(std::io::SeekFrom::Start(0))?;\n\n fmt_file.read_to_string(&mut fmt_c)?;\n\n\n\n Ok(fmt_c)\n\n}\n\n\n", "file_path": "crates/irust_repl/src/cargo_cmds.rs", "rank": 6, "score": 166642.09585857822 }, { "content": "pub fn cargo_asm(fnn: &str, toolchain: ToolChain) -> Result<String> {\n\n let mut cmd = Command::new(\"cargo\");\n\n Ok(stdout_and_stderr(\n\n cargo_common(&mut cmd, \"asm\", toolchain)\n\n .arg(\"--lib\")\n\n .arg(format!(\"irust_host_repl::{}\", fnn))\n\n .arg(\"--rust\")\n\n .output()?,\n\n ))\n\n}\n", "file_path": "crates/irust_repl/src/cargo_cmds.rs", "rank": 7, "score": 161180.92889308895 }, { "content": "pub fn format_err<'a>(original_output: &'a str, show_warnings: bool) -> String {\n\n const BEFORE_2021_END_TAG: &str = \": aborting due to \";\n\n // Relies on --color=always\n\n const ERROR_TAG: &str = \"\\u{1b}[0m\\u{1b}[1m\\u{1b}[38;5;9merror\";\n\n const WARNING_TAG: &str = \"\\u{1b}[0m\\u{1b}[1m\\u{1b}[33mwarning\";\n\n\n\n let go_to_start = |output: &'a str| -> Vec<&'a str> {\n\n if show_warnings {\n\n output\n\n .lines()\n\n .skip_while(|line| !line.contains(\"irust_host_repl v0.1.0\"))\n\n .skip(1)\n\n .collect()\n\n } else {\n\n output\n\n .lines()\n\n .skip_while(|line| !line.starts_with(ERROR_TAG))\n\n .collect()\n\n }\n\n };\n", "file_path": "crates/irust/src/irust/format.rs", "rank": 8, "score": 160309.3082924637 }, { "content": "pub fn format_check_output(output: String, show_warnings: bool) -> Option<PrintQueue> {\n\n if check_is_err(&output) {\n\n Some(format_err_printqueue(&output, show_warnings))\n\n } else {\n\n None\n\n }\n\n}\n", "file_path": "crates/irust/src/irust/format.rs", "rank": 9, "score": 158975.35779195148 }, { "content": "pub fn split_args(s: String) -> Vec<String> {\n\n let mut args = vec![];\n\n let mut tmp = String::new();\n\n let mut quote = false;\n\n\n\n for c in s.chars() {\n\n match c {\n\n ' ' => {\n\n if !quote && !tmp.is_empty() {\n\n args.push(tmp.drain(..).collect());\n\n } else {\n\n tmp.push(' ');\n\n }\n\n }\n\n '\"' => {\n\n quote = !quote;\n\n }\n\n _ => tmp.push(c),\n\n }\n\n }\n\n if !tmp.is_empty() {\n\n args.push(tmp);\n\n }\n\n args\n\n}\n\n\n", "file_path": "crates/irust/src/utils.rs", "rank": 10, "score": 158162.25711640692 }, { "content": "fn remove_comments(s: &str) -> String {\n\n s.lines()\n\n .filter(|l| !l.trim_start().starts_with(\"//\"))\n\n .map(|l| {\n\n let mut quote = false;\n\n let mut d_quote = false;\n\n\n\n let mut l = l.chars().peekable();\n\n let mut purged_line = String::new();\n\n\n\n loop {\n\n match (l.next(), l.peek()) {\n\n (Some('/'), Some('/')) => {\n\n if !quote && !d_quote {\n\n break;\n\n }\n\n }\n\n (Some('\\''), _) => {\n\n quote = !quote;\n\n purged_line.push('\\'');\n", "file_path": "crates/irust/src/utils.rs", "rank": 11, "score": 155285.9279306409 }, { "content": "fn eval(deps: Option<&str>, code: &str) {\n\n let mut repl = Repl::default();\n\n if let Some(deps) = deps {\n\n let deps: Vec<String> = split_args(deps.to_string());\n\n repl.add_dep(&deps).unwrap().wait().unwrap();\n\n }\n\n let result = repl\n\n .eval_with_configuration(EvalConfig {\n\n input: code,\n\n interactive_function: None,\n\n color: true,\n\n evaluator: &*DEFAULT_EVALUATOR,\n\n })\n\n .unwrap();\n\n println!(\"{}\", result.output);\n\n}\n\n\n", "file_path": "crates/irust_repl/examples/re/main.rs", "rank": 12, "score": 154898.1975725483 }, { "content": "pub fn cargo_add_prelude(path: PathBuf, name: &'static str) -> io::Result<()> {\n\n let mut f = std::fs::OpenOptions::new()\n\n .append(true)\n\n .open(&*CARGO_TOML_FILE)?;\n\n\n\n let path = if !cfg!(windows) {\n\n path.display().to_string()\n\n } else {\n\n path.display().to_string().replace('\\\\', \"\\\\\\\\\")\n\n };\n\n\n\n writeln!(\n\n f,\n\n \"\n\n[dependencies]\n\n{} = {{ path = \\\"{}\\\" }}\n\n\",\n\n name, path\n\n )\n\n}\n\n\n", "file_path": "crates/irust_repl/src/cargo_cmds.rs", "rank": 13, "score": 153371.7290976651 }, { "content": "fn read_from_net_and_stdin(server: &mut mpsc::Receiver<String>) -> Vec<std::io::Result<Event>> {\n\n loop {\n\n if let Ok(e) = server.try_recv() {\n\n return e\n\n .chars()\n\n .map(|c| {\n\n Ok(Event::Key(KeyEvent {\n\n code: KeyCode::Char(c),\n\n modifiers: KeyModifiers::NONE,\n\n }))\n\n })\n\n .chain(std::iter::once(Ok(Event::Key(KeyEvent {\n\n code: KeyCode::Enter,\n\n modifiers: KeyModifiers::NONE,\n\n }))))\n\n .collect();\n\n }\n\n if let Ok(true) = crossterm::event::poll(Duration::from_millis(100)) {\n\n return vec![crossterm::event::read()];\n\n }\n", "file_path": "crates/irust/src/irust.rs", "rank": 14, "score": 150829.3530395261 }, { "content": "fn eval(buffer: String) -> Option<PrintQueue> {\n\n let mut buffer = buffer.split_whitespace();\n\n let cmd = buffer.next()?;\n\n let args: Vec<&str> = buffer.collect();\n\n\n\n match (|| -> Result<PrinterItem> {\n\n let output = std::process::Command::new(cmd).args(args).output()?;\n\n if output.status.success() {\n\n Ok(PrinterItem::String(\n\n String::from_utf8(output.stdout)?,\n\n Color::Blue,\n\n ))\n\n } else {\n\n Ok(PrinterItem::String(\n\n String::from_utf8(output.stderr)?,\n\n Color::Red,\n\n ))\n\n }\n\n })() {\n\n Ok(result) => Some(result.into()),\n\n Err(e) => Some(PrinterItem::String(e.to_string(), Color::Red).into()),\n\n }\n\n}\n", "file_path": "crates/printer/examples/shell.rs", "rank": 15, "score": 145302.83571516915 }, { "content": "pub fn stdout_and_stderr(out: Output) -> String {\n\n let out = if !out.stdout.is_empty() {\n\n out.stdout\n\n } else {\n\n out.stderr\n\n };\n\n\n\n String::from_utf8(out).unwrap_or_default()\n\n}\n\n\n", "file_path": "crates/irust_repl/src/utils.rs", "rank": 16, "score": 143755.2309992419 }, { "content": "pub fn cargo_new_lib_simple(path: &Path, name: &'static str) -> std::result::Result<(), io::Error> {\n\n let lib_path = path.join(name);\n\n let _ = std::fs::create_dir_all(lib_path.join(\"src\"));\n\n let create_if_not_exist = |path: PathBuf, contents| -> std::io::Result<()> {\n\n if !path.exists() {\n\n std::fs::write(path, contents)?;\n\n }\n\n Ok(())\n\n };\n\n let cargo_toml = format!(\n\n \"\\\n\n[package]\n\nname = \\\"{}\\\"\n\nversion = \\\"0.1.0\\\"\n\nedition = \\\"2021\\\"\",\n\n name\n\n );\n\n create_if_not_exist(lib_path.join(\"src/lib.rs\"), \"\")?;\n\n create_if_not_exist(lib_path.join(\"Cargo.toml\"), &cargo_toml)?;\n\n\n\n Ok(())\n\n}\n\n\n", "file_path": "crates/irust_repl/src/cargo_cmds.rs", "rank": 17, "score": 138258.03039356356 }, { "content": "pub fn cargo_rm_sync(dep: &str) -> Result<()> {\n\n // Ignore error if dependency doesn't exist\n\n Command::new(\"cargo-rm\")\n\n .current_dir(&*IRUST_DIR)\n\n .arg(\"rm\")\n\n .arg(dep)\n\n .stdout(std::process::Stdio::null())\n\n .stderr(std::process::Stdio::piped())\n\n .spawn()?\n\n .wait()?;\n\n Ok(())\n\n}\n\n\n", "file_path": "crates/irust_repl/src/cargo_cmds.rs", "rank": 18, "score": 136503.93208721792 }, { "content": "pub fn cargo_add_sync(dep: &[String]) -> Result<()> {\n\n let process = Command::new(\"cargo-add\")\n\n .current_dir(&*IRUST_DIR)\n\n .arg(\"add\")\n\n .args(dep)\n\n .stdout(std::process::Stdio::null())\n\n .stderr(std::process::Stdio::piped())\n\n .spawn()?\n\n .wait()?;\n\n if process.success() {\n\n Ok(())\n\n } else {\n\n Err(format!(\"Failed to add dependency: {:?}\", &dep).into())\n\n }\n\n}\n\n\n", "file_path": "crates/irust_repl/src/cargo_cmds.rs", "rank": 19, "score": 136312.78959484852 }, { "content": "pub fn stdout_and_stderr(out: std::process::Output) -> String {\n\n let out = if !out.stdout.is_empty() {\n\n out.stdout\n\n } else {\n\n out.stderr\n\n };\n\n\n\n String::from_utf8_lossy(&out).to_string()\n\n}\n\n\n", "file_path": "crates/irust/src/utils.rs", "rank": 20, "score": 133886.70692701056 }, { "content": "#[bench]\n\nfn bench_print_input(b: &mut Bencher) {\n\n let buffer = r#\"\\\n\n fn default() -> Self {\n\n crossterm::terminal::enable_raw_mode().expect(\"failed to enable raw_mode\");\n\n let raw = Rc::new(RefCell::new(std::io::stdout()));\n\n Self {\n\n printer: Default::default(),\n\n writer: writer::Writer::new(raw.clone()),\n\n cursor: cursor::Cursor::new(raw),\n\n }\n\n \"#\n\n .into();\n\n\n\n let mut printer = Printer::new(std::io::sink(), \"\".to_string());\n\n b.iter(|| printer.print_input(&default_process_fn, &buffer));\n\n}\n", "file_path": "crates/printer/benches/printer.rs", "rank": 21, "score": 131962.88855260386 }, { "content": "pub fn cargo_expand(toolchain: ToolChain) -> Result<String> {\n\n let mut cmd = Command::new(\"cargo\");\n\n let output = cargo_common(&mut cmd, \"expand\", toolchain)\n\n // For cargo expand, color needs to be specified here\n\n .args(&[\"--color\", \"always\"])\n\n .output()?;\n\n if !output.status.success() {\n\n return Err(stdout_and_stderr(output).trim().into());\n\n }\n\n Ok(stdout_and_stderr(output).trim().to_owned())\n\n}\n\n\n", "file_path": "crates/irust_repl/src/cargo_cmds.rs", "rank": 22, "score": 130221.02328386795 }, { "content": "fn incomplete_input(buffer: &str) -> bool {\n\n StringTools::unmatched_brackets(buffer)\n\n || buffer\n\n .trim_end()\n\n .ends_with(|c| c == ':' || c == '.' || c == '=')\n\n}\n\n\n", "file_path": "crates/irust/src/irust/engine.rs", "rank": 23, "score": 128663.03104419293 }, { "content": "pub fn ctrlc_cancel(process: &mut std::process::Child) -> Result<()> {\n\n use crossterm::event::{Event, KeyCode, KeyEvent};\n\n // Running a command as Command::new().output takes at minimum 1ms\n\n // So Polling should take a similar order of magnitude\n\n if let Ok(event) = crossterm::event::poll(std::time::Duration::from_millis(1)) {\n\n if event {\n\n if let Ok(event) = crossterm::event::read() {\n\n match event {\n\n Event::Key(KeyEvent {\n\n code: KeyCode::Char('c'),\n\n modifiers: crossterm::event::KeyModifiers::CONTROL,\n\n }) => {\n\n process.kill()?;\n\n return Err(\"Cancelled!\".into());\n\n }\n\n Event::Key(KeyEvent {\n\n code: KeyCode::Char(a),\n\n ..\n\n }) => {\n\n use std::io::Write;\n", "file_path": "crates/irust/src/utils.rs", "rank": 24, "score": 126678.08674442551 }, { "content": "fn input_is_cmd_or_shell(buffer: &str) -> bool {\n\n buffer.starts_with(':') || buffer.starts_with(\"::\")\n\n}\n", "file_path": "crates/irust/src/irust/engine.rs", "rank": 25, "score": 126024.78346099681 }, { "content": "pub fn format_err_printqueue(output: &str, show_warnings: bool) -> PrintQueue {\n\n PrinterItem::String(format_err(output, show_warnings), Color::Red).into()\n\n}\n\n\n", "file_path": "crates/irust/src/irust/format.rs", "rank": 26, "score": 122940.9852807161 }, { "content": "fn main() {\n\n let _ = Prompt::execute(&mut Prompt::run);\n\n}\n", "file_path": "script_examples/irust_prompt/src/main.rs", "rank": 27, "score": 121743.3282743899 }, { "content": "// helper\n\nfn move_to_and_modify_start(printer: &mut Printer<impl Write>, x: usize, y: usize) {\n\n printer.cursor.pos.starting_pos.0 = x;\n\n printer.cursor.pos.starting_pos.1 = y;\n\n printer.cursor.goto_start();\n\n}\n", "file_path": "crates/printer/src/printer/tests.rs", "rank": 28, "score": 118801.4751731626 }, { "content": "pub fn cargo_add(dep: &[String]) -> io::Result<std::process::Child> {\n\n Command::new(\"cargo-add\")\n\n .current_dir(&*IRUST_DIR)\n\n .arg(\"add\")\n\n .args(dep)\n\n .stdout(std::process::Stdio::null())\n\n .stderr(std::process::Stdio::piped())\n\n .spawn()\n\n}\n\n\n", "file_path": "crates/irust_repl/src/cargo_cmds.rs", "rank": 29, "score": 117232.49804259319 }, { "content": "#[derive(Serialize, Deserialize, Debug)]\n\nstruct ScriptState(HashMap<String, bool>);\n\n*/\n\n\n\nimpl Script for ScriptManager4 {\n\n fn input_prompt(&mut self, global_variables: &GlobalVariables) -> Option<String> {\n\n self.sm\n\n .trigger(irust_api::SetInputPrompt(global_variables.clone()))\n\n .next()?\n\n .ok()\n\n }\n\n fn get_output_prompt(&mut self, global_variables: &GlobalVariables) -> Option<String> {\n\n self.sm\n\n .trigger(irust_api::SetOutputPrompt(global_variables.clone()))\n\n .next()?\n\n .ok()\n\n }\n\n fn before_compiling(&mut self, global_variables: &GlobalVariables) -> Option<()> {\n\n self.sm\n\n .trigger(irust_api::BeforeCompiling(global_variables.clone()))\n\n .collect::<Result<_, _>>()\n", "file_path": "crates/irust/src/irust/script/script4.rs", "rank": 30, "score": 115858.08325846864 }, { "content": "pub trait ProcessUtils {\n\n fn interactive_output(self, function: Option<fn(&mut Child) -> Result<()>>) -> Result<Output>;\n\n}\n\n\n\nimpl ProcessUtils for Child {\n\n fn interactive_output(\n\n mut self,\n\n function: Option<fn(&mut Child) -> Result<()>>,\n\n ) -> Result<Output> {\n\n let mut stdout = self.stdout.take().expect(\"stdout is piped\");\n\n let mut stderr = self.stderr.take().expect(\"stderr is piped\");\n\n\n\n let (tx_out, rx) = mpsc::channel();\n\n let tx_err = tx_out.clone();\n\n enum OutType {\n\n Stdout(Vec<u8>),\n\n Stderr(Vec<u8>),\n\n }\n\n\n\n std::thread::spawn(move || {\n", "file_path": "crates/irust_repl/src/utils.rs", "rank": 31, "score": 114210.16711750359 }, { "content": "fn split_args(s: String) -> Vec<String> {\n\n let mut args = vec![];\n\n let mut tmp = String::new();\n\n let mut quote = false;\n\n\n\n for c in s.chars() {\n\n match c {\n\n ' ' => {\n\n if !quote && !tmp.is_empty() {\n\n args.push(tmp.drain(..).collect());\n\n } else {\n\n tmp.push(' ');\n\n }\n\n }\n\n '\"' => {\n\n quote = !quote;\n\n }\n\n _ => tmp.push(c),\n\n }\n\n }\n\n if !tmp.is_empty() {\n\n args.push(tmp);\n\n }\n\n args\n\n}\n", "file_path": "crates/irust_repl/examples/re/main.rs", "rank": 32, "score": 111916.12721378123 }, { "content": "pub fn cargo_bench(toolchain: ToolChain) -> std::result::Result<String, io::Error> {\n\n let mut cmd = Command::new(\"cargo\");\n\n Ok(stdout_and_stderr(\n\n cargo_common(&mut cmd, \"bench\", toolchain)\n\n .args(&[\"--color\", \"always\"])\n\n .output()?,\n\n ))\n\n}\n\n\n", "file_path": "crates/irust_repl/src/cargo_cmds.rs", "rank": 33, "score": 111236.50078319844 }, { "content": "pub fn format_eval_output(\n\n status: std::process::ExitStatus,\n\n output: String,\n\n prompt: String,\n\n show_warnings: bool,\n\n) -> Option<PrintQueue> {\n\n if !status.success() {\n\n return Some(format_err_printqueue(&output, show_warnings));\n\n }\n\n if output.trim() == \"()\" {\n\n return None;\n\n }\n\n\n\n let mut eval_output = PrintQueue::default();\n\n eval_output.push(PrinterItem::String(prompt, Color::Red));\n\n eval_output.push(PrinterItem::String(output, Color::White));\n\n eval_output.add_new_line(1);\n\n Some(eval_output)\n\n}\n\n\n", "file_path": "crates/irust/src/irust/format.rs", "rank": 34, "score": 106642.56857668489 }, { "content": "pub fn cargo_run(\n\n color: bool,\n\n release: bool,\n\n toolchain: ToolChain,\n\n interactive_function: Option<fn(&mut process::Child) -> Result<()>>,\n\n) -> Result<(ExitStatus, String)> {\n\n let (status, output) = cargo_build_output(color, release, toolchain)?;\n\n\n\n if !status.success() {\n\n Ok((status, output))\n\n } else {\n\n // Run the exexcutable directly instead of cargo run\n\n // This allows to run it without modifying the current working directory\n\n // example: std::process::Commmand::new(\"pwd\") will output the expected path instead of `/tmp/irust_host_repl`\n\n if !release {\n\n Ok((\n\n status,\n\n stdout_and_stderr(\n\n std::process::Command::new(&*EXE_PATH)\n\n .stdin(Stdio::piped())\n", "file_path": "crates/irust_repl/src/cargo_cmds.rs", "rank": 35, "score": 106642.56857668489 }, { "content": "pub fn cargo_build_output(\n\n color: bool,\n\n release: bool,\n\n toolchain: ToolChain,\n\n) -> std::result::Result<(ExitStatus, String), io::Error> {\n\n let color = if color { \"always\" } else { \"never\" };\n\n let mut cmd = Command::new(\"cargo\");\n\n\n\n let output = if !release {\n\n cargo_common(&mut cmd, \"build\", toolchain)\n\n .args(&[\"--color\", color])\n\n .output()?\n\n } else {\n\n cargo_common(&mut cmd, \"build\", toolchain)\n\n .arg(\"--release\")\n\n .args(&[\"--color\", color])\n\n .output()?\n\n };\n\n let status = output.status;\n\n\n\n Ok((status, stdout_and_stderr(output)))\n\n}\n\n\n", "file_path": "crates/irust_repl/src/cargo_cmds.rs", "rank": 36, "score": 104790.51624119637 }, { "content": "pub fn cargo_check_output(\n\n toolchain: ToolChain,\n\n) -> std::result::Result<(ExitStatus, String), io::Error> {\n\n let mut cmd = Command::new(\"cargo\");\n\n let output = cargo_common(&mut cmd, \"check\", toolchain)\n\n .args(&[\"--color\", \"always\"])\n\n .output()?;\n\n\n\n let status = output.status;\n\n Ok((status, stdout_and_stderr(output)))\n\n}\n\n\n", "file_path": "crates/irust_repl/src/cargo_cmds.rs", "rank": 37, "score": 104790.51624119637 }, { "content": "struct Prompt;\n\n\n\nimpl Scripter for Prompt {\n\n fn script_type() -> ScriptType {\n\n ScriptType::OneShot\n\n }\n\n\n\n fn name() -> &'static str {\n\n \"prompt\"\n\n }\n\n\n\n fn hooks() -> &'static [&'static str] {\n\n &[\n\n irust_api::SetInputPrompt::NAME,\n\n irust_api::SetOutputPrompt::NAME,\n\n irust_api::Shutdown::NAME,\n\n ]\n\n }\n\n fn version_requirement() -> VersionReq {\n\n VersionReq::parse(\">=1.50.0\").expect(\"correct version requirement\")\n\n }\n\n}\n\n\n", "file_path": "script_examples/irust_prompt/src/main.rs", "rank": 38, "score": 104649.05706759947 }, { "content": "pub fn check_required_deps() -> bool {\n\n const REQUIRED_DEPS: &[&str] = &[\"cargo\"];\n\n for dep in REQUIRED_DEPS {\n\n if !dep_installed(dep) {\n\n eprintln!(\n\n \"{0} is not insalled!\\n{0} is required for IRust to work.\",\n\n dep\n\n );\n\n return false;\n\n }\n\n }\n\n true\n\n}\n\n\n", "file_path": "crates/irust/src/dependencies.rs", "rank": 39, "score": 102516.45184157387 }, { "content": "fn _balanced_quotes(s: &str) -> bool {\n\n s.match_indices(|p| p == '\"' || p == '\\'').count() % 2 == 0\n\n}\n\n\n", "file_path": "crates/irust/src/utils.rs", "rank": 40, "score": 102293.00718564607 }, { "content": "fn dep_installed(d: &str) -> bool {\n\n if let Err(e) = std::process::Command::new(d)\n\n .arg(\"-h\")\n\n .stdout(std::process::Stdio::null())\n\n .stderr(std::process::Stdio::null())\n\n .spawn()\n\n {\n\n if e.kind() == std::io::ErrorKind::NotFound {\n\n return false;\n\n }\n\n }\n\n true\n\n}\n", "file_path": "crates/irust/src/dependencies.rs", "rank": 41, "score": 102293.00718564607 }, { "content": "pub fn default_process_fn(buffer: &Buffer) -> PrintQueue {\n\n let mut queue = PrintQueue::default();\n\n for c in buffer.iter() {\n\n if c == &'\\n' {\n\n queue.push(PrinterItem::NewLine);\n\n } else {\n\n queue.push(PrinterItem::Char(*c, Color::White));\n\n }\n\n }\n\n queue\n\n}\n", "file_path": "crates/printer/src/printer.rs", "rank": 42, "score": 101146.96520677222 }, { "content": "#[test]\n\npub fn calculate_bounds_correctly2() -> Result<()> {\n\n let mut p = Printer::new(std::io::sink(), \"\".to_owned());\n\n let width = p.cursor.bound.width;\n\n let height = p.cursor.bound.height;\n\n let queue = default_process_fn(&\"A\\tz\\nBC\\n\".into());\n\n // 2\n\n move_to_and_modify_start(&mut p, 0, height - 5);\n\n p.recalculate_bounds(queue)?;\n\n\n\n let expected_bound = {\n\n let mut v = vec![width - 1; height];\n\n v[height - 5] = 7;\n\n v[height - 4] = 6;\n\n v[height - 3] = 4;\n\n v\n\n };\n\n assert_eq!(expected_bound, p.cursor.bound.bound);\n\n\n\n Ok(())\n\n}\n\n\n", "file_path": "crates/printer/src/printer/tests.rs", "rank": 43, "score": 100664.39950608535 }, { "content": "fn check_is_err(s: &str) -> bool {\n\n !s.contains(\"dev [unoptimized + debuginfo]\")\n\n}\n\n\n", "file_path": "crates/irust/src/irust/format.rs", "rank": 44, "score": 100313.6570740182 }, { "content": "pub fn theme() -> Result<Theme> {\n\n let theme_file = dirs::config_dir()\n\n .ok_or(\"Error accessing config_dir\")?\n\n .join(\"irust\")\n\n .join(\"theme\");\n\n\n\n let data = std::fs::read_to_string(theme_file)?;\n\n\n\n Ok(toml::from_str(&data)?)\n\n}\n\n\n\n#[derive(Deserialize, Serialize, Debug)]\n\npub struct Theme {\n\n pub keyword: String,\n\n pub keyword2: String,\n\n pub function: String,\n\n pub r#type: String,\n\n pub symbol: String,\n\n pub r#macro: String,\n\n pub literal: String,\n", "file_path": "crates/irust/src/irust/highlight/theme.rs", "rank": 45, "score": 97224.40585589492 }, { "content": "pub fn patch_name(path: &Path) -> Result<()> {\n\n let toml = std::fs::read_to_string(path)?;\n\n let mut patched: String = String::new();\n\n for line in toml.lines() {\n\n if line.starts_with(\"name =\") {\n\n patched.push_str(\"name = \\\"irust_host_repl\\\"\");\n\n patched.push('\\n');\n\n } else {\n\n patched.push_str(line);\n\n patched.push('\\n');\n\n }\n\n }\n\n std::fs::write(path, patched)?;\n\n Ok(())\n\n}\n\n\n", "file_path": "crates/irust/src/utils.rs", "rank": 46, "score": 94312.53145017967 }, { "content": "pub fn cargo_fmt_file(file: &Path) {\n\n // Cargo fmt is optional\n\n let _ = try_cargo_fmt_file(file);\n\n}\n\n\n", "file_path": "crates/irust_repl/src/cargo_cmds.rs", "rank": 47, "score": 93837.6746323798 }, { "content": "fn main() {\n\n let mut ipython = IPython::default();\n\n let _ = IPython::execute(&mut |hook_name| IPython::run(&mut ipython, hook_name));\n\n}\n\n\n\nimpl IPython {\n\n fn run(&mut self, hook_name: &str) {\n\n match hook_name {\n\n irust_api::OutputEvent::NAME => {\n\n let hook: irust_api::OutputEvent = Self::read();\n\n let output = self.handle_output_event(hook);\n\n Self::write::<irust_api::OutputEvent>(&output);\n\n }\n\n irust_api::SetTitle::NAME => {\n\n let _hook: irust_api::SetTitle = Self::read();\n\n Self::write::<irust_api::SetTitle>(&Some(\"IPython\".to_string()));\n\n }\n\n irust_api::SetWelcomeMsg::NAME => {\n\n let _hook: irust_api::SetWelcomeMsg = Self::read();\n\n Self::write::<irust_api::SetWelcomeMsg>(&Some(\"IPython\".to_string()));\n", "file_path": "script_examples/ipython/src/main.rs", "rank": 48, "score": 90750.28965735646 }, { "content": "fn main() {\n\n let mut fun = Fun::new();\n\n let _ = Fun::execute(&mut |hook_name| Fun::run(&mut fun, hook_name));\n\n}\n\n\n\nimpl Fun {\n\n fn run(&mut self, hook_name: &str) {\n\n match hook_name {\n\n OutputEvent::NAME => {\n\n let hook: OutputEvent = Self::read();\n\n let output = match self.handle_output_event(hook) {\n\n Ok(out) => out,\n\n Err(e) => Some(Command::PrintOutput(\n\n e.to_string() + \"\\n\",\n\n color::Color::Red,\n\n )),\n\n };\n\n Self::write::<OutputEvent>(&output);\n\n }\n\n Shutdown::NAME => {\n", "file_path": "script_examples/fun/src/main.rs", "rank": 49, "score": 90750.28965735646 }, { "content": "pub fn read_until_bytes<R: std::io::BufRead + ?Sized>(\n\n r: &mut R,\n\n delim: &[u8],\n\n buffer: &mut Vec<u8>,\n\n) -> std::io::Result<usize> {\n\n let mut nn = 0;\n\n let mut b = [0; 512];\n\n loop {\n\n let n = r.read(&mut b)?;\n\n buffer.extend(&b[..n]);\n\n nn += n;\n\n if n == 0 || buffer.ends_with(delim) {\n\n break Ok(nn);\n\n }\n\n }\n\n}\n\n\n", "file_path": "crates/irust/src/utils.rs", "rank": 50, "score": 84712.37813195988 }, { "content": "pub fn copy_dir(src_path: &Path, out_path: &Path) -> Result<()> {\n\n if src_path.is_file() {\n\n panic!(\"Incorrect usage\")\n\n }\n\n let convert_path =\n\n |path: &Path| -> Result<PathBuf> { Ok(out_path.join(path.strip_prefix(src_path)?)) };\n\n let dcb = |dp: PathBuf| Ok(std::fs::create_dir(convert_path(&dp)?)?);\n\n let fcb = |fp: PathBuf| Ok(std::fs::copy(fp.clone(), convert_path(&fp)?)?);\n\n visit_dirs(src_path, &dcb, &fcb)\n\n}\n\n\n", "file_path": "crates/irust/src/utils.rs", "rank": 51, "score": 84712.37813195988 }, { "content": "pub fn highlight(buffer: &Buffer, theme: &Theme) -> PrintQueue {\n\n let mut print_queue = PrintQueue::default();\n\n\n\n let buffer = buffer.to_string();\n\n let rc_buf = std::rc::Rc::new(buffer.clone());\n\n\n\n let mut token_range = 0..0;\n\n let tokens: Vec<_> = rustc_lexer::tokenize(&buffer).collect();\n\n let mut paren_idx = 0_isize;\n\n\n\n macro_rules! push_to_printer {\n\n ($color: expr) => {{\n\n let color = theme::theme_color_to_term_color($color).unwrap_or(Color::White);\n\n print_queue.push(PrinterItem::RcString(\n\n rc_buf.clone(),\n\n token_range.clone(),\n\n color,\n\n ));\n\n }};\n\n }\n", "file_path": "crates/irust/src/irust/highlight.rs", "rank": 52, "score": 84712.37813195988 }, { "content": "fn start_server(adress: SocketAddrV4) -> Result<mpsc::Receiver<String>> {\n\n let server = TcpListener::bind(adress)?;\n\n let (tx, rx) = mpsc::channel();\n\n std::thread::spawn(move || {\n\n let mut buf = String::new();\n\n loop {\n\n (|| {\n\n let mut c = server.accept().ok()?.0;\n\n c.read_to_string(&mut buf).ok()?;\n\n tx.send(buf.clone()).ok()?;\n\n buf.clear();\n\n Some(())\n\n })();\n\n }\n\n });\n\n Ok(rx)\n\n}\n", "file_path": "crates/irust/src/irust.rs", "rank": 53, "score": 84080.09579122222 }, { "content": "#[test]\n\nfn scroll_because_input_needs_scroll() -> Result<()> {\n\n let mut p = Printer::new(std::io::sink(), \"\".to_owned());\n\n let b = \"\\n\\n\\n\".into();\n\n\n\n p.cursor.pos.starting_pos.0 = 0;\n\n p.cursor.pos.starting_pos.1 = p.cursor.bound.height - 1;\n\n p.cursor.goto_start();\n\n\n\n let original_pos = p.cursor.pos;\n\n p.scroll_if_needed_for_input(&b);\n\n\n\n assert_eq!(original_pos.starting_pos.1 - 3, p.cursor.pos.starting_pos.1);\n\n Ok(())\n\n}\n\n\n", "file_path": "crates/printer/src/printer/tests.rs", "rank": 54, "score": 80942.95749008507 }, { "content": "#[test]\n\nfn dont_scroll_because_input_doesent_need_scroll() -> Result<()> {\n\n let mut p = Printer::new(std::io::sink(), \"\".to_owned());\n\n let b = \"\\n\\n\\n\".into();\n\n\n\n p.cursor.pos.starting_pos.0 = 0;\n\n p.cursor.pos.starting_pos.1 = 0;\n\n p.cursor.goto_start();\n\n\n\n let original_pos = p.cursor.pos;\n\n p.scroll_if_needed_for_input(&b);\n\n\n\n assert_eq!(original_pos.starting_pos.1, p.cursor.pos.starting_pos.1);\n\n Ok(())\n\n}\n\n\n", "file_path": "crates/printer/src/printer/tests.rs", "rank": 55, "score": 77536.17405884987 }, { "content": "pub fn cargo_new(edition: Edition) -> std::result::Result<(), io::Error> {\n\n // Ignore directory exists error\n\n let _ = std::fs::create_dir_all(&*IRUST_SRC_DIR);\n\n clean_cargo_toml(edition)?;\n\n clean_files()?;\n\n\n\n Ok(())\n\n}\n\n\n", "file_path": "crates/irust_repl/src/cargo_cmds.rs", "rank": 56, "score": 76966.78886017628 }, { "content": "fn end(_hook: irust_api::AfterCompiling) {\n\n unsafe {\n\n ANIMATION_FLAG.store(false, std::sync::atomic::Ordering::Relaxed);\n\n }\n\n}\n", "file_path": "script_examples/irust_animation/src/lib.rs", "rank": 57, "score": 74986.27670808532 }, { "content": "fn start(hook: irust_api::BeforeCompiling) {\n\n thread::spawn(move || {\n\n unsafe {\n\n ANIMATION_FLAG.store(true, std::sync::atomic::Ordering::Relaxed);\n\n }\n\n use crossterm::execute;\n\n use std::io::stdout;\n\n let globals = hook.0;\n\n let mut tick = 0;\n\n const STATUS: &[&str] = &[\"-\", \"/\", \"-\", \"\\\\\"];\n\n\n\n while unsafe { ANIMATION_FLAG.load(std::sync::atomic::Ordering::Relaxed) } {\n\n let msg = format!(\"In [{}]: \", STATUS[tick % STATUS.len()]);\n\n execute!(\n\n stdout(),\n\n SavePosition,\n\n Hide,\n\n MoveTo(\n\n globals.prompt_position.0 as u16,\n\n globals.prompt_position.1 as u16\n", "file_path": "script_examples/irust_animation/src/lib.rs", "rank": 58, "score": 74986.27670808532 }, { "content": "pub fn cargo_check(toolchain: ToolChain) -> std::result::Result<std::process::Child, io::Error> {\n\n let mut cmd = Command::new(\"cargo\");\n\n cargo_common(&mut cmd, \"check\", toolchain)\n\n .stdout(std::process::Stdio::null())\n\n .stderr(std::process::Stdio::null())\n\n .spawn()\n\n}\n\n\n", "file_path": "crates/irust_repl/src/cargo_cmds.rs", "rank": 59, "score": 68287.34219848442 }, { "content": "pub fn cargo_build(toolchain: ToolChain) -> std::result::Result<std::process::Child, io::Error> {\n\n let mut cmd = Command::new(\"cargo\");\n\n cargo_common(&mut cmd, \"build\", toolchain)\n\n .stdout(std::process::Stdio::null())\n\n .stderr(std::process::Stdio::null())\n\n .spawn()\n\n}\n\n\n", "file_path": "crates/irust_repl/src/cargo_cmds.rs", "rank": 60, "score": 68287.34219848442 }, { "content": " let irust_api::SetInputPrompt(global) = Self::read();\n\n let output = Self::prompt(global, PType::In);\n\n Self::write::<irust_api::SetInputPrompt>(&output);\n\n }\n\n irust_api::SetOutputPrompt::NAME => {\n\n let irust_api::SetOutputPrompt(global) = Self::read();\n\n let output = Self::prompt(global, PType::Out);\n\n Self::write::<irust_api::SetOutputPrompt>(&output);\n\n }\n\n irust_api::Shutdown::NAME => {\n\n let _hook: irust_api::Shutdown = Self::read();\n\n let output = Self::clean_up();\n\n Self::write::<irust_api::Shutdown>(&output);\n\n }\n\n _ => unreachable!(),\n\n }\n\n }\n\n fn clean_up() -> Option<irust_api::Command> {\n\n Some(irust_api::Command::ResetPrompt)\n\n }\n\n}\n\n\n", "file_path": "script_examples/irust_prompt/src/main.rs", "rank": 61, "score": 67987.68919208442 }, { "content": "use irust_api::GlobalVariables;\n\nuse rscript::{scripting::Scripter, Hook, ScriptType, VersionReq};\n\n\n", "file_path": "script_examples/irust_prompt/src/main.rs", "rank": 62, "score": 67981.54431040325 }, { "content": "use std::collections::HashMap;\n\n\n\nuse crossterm::event::Event;\n\nuse irust_api::{Command, GlobalVariables};\n\n\n\nuse super::Script;\n\n\n\npub struct ScriptManager4 {\n\n sm: rscript::ScriptManager,\n\n startup_cmds: Vec<Result<Option<Command>, rscript::Error>>,\n\n}\n\n\n\nmacro_rules! mtry {\n\n ($e: expr) => {\n\n (|| -> Result<_, Box<dyn std::error::Error>> { Ok($e) })()\n\n };\n\n}\n\nimpl ScriptManager4 {\n\n pub fn new() -> Option<Self> {\n\n let mut sm = rscript::ScriptManager::default();\n", "file_path": "crates/irust/src/irust/script/script4.rs", "rank": 70, "score": 67929.02272392584 }, { "content": " fn deactivate(&mut self, script_name: &str) -> Result<Option<Command>, &'static str> {\n\n if let Some(script) = self\n\n .sm\n\n .scripts_mut()\n\n .iter_mut()\n\n .find(|script| script.metadata().name == script_name)\n\n {\n\n script.deactivate();\n\n // We send a shutdown message in case the script is listening for one\n\n if let Ok(maybe_command) = script.trigger(&irust_api::Shutdown()) {\n\n Ok(maybe_command)\n\n } else {\n\n Ok(None)\n\n }\n\n } else {\n\n Err(\"Script not found\")\n\n }\n\n }\n\n\n\n fn startup_cmds(&mut self) -> Vec<Result<Option<Command>, rscript::Error>> {\n", "file_path": "crates/irust/src/irust/script/script4.rs", "rank": 71, "score": 67923.30887799358 }, { "content": "\n\n fn activate(&mut self, script_name: &str) -> Result<Option<Command>, &'static str> {\n\n if let Some(script) = self\n\n .sm\n\n .scripts_mut()\n\n .iter_mut()\n\n .find(|script| script.metadata().name == script_name)\n\n {\n\n script.activate();\n\n // We send a startup message in case the script is listening for one\n\n if let Ok(maybe_command) = script.trigger(&irust_api::Startup()) {\n\n Ok(maybe_command)\n\n } else {\n\n Ok(None)\n\n }\n\n } else {\n\n Err(\"Script not found\")\n\n }\n\n }\n\n\n", "file_path": "crates/irust/src/irust/script/script4.rs", "rank": 72, "score": 67922.96389088451 }, { "content": " input: &str,\n\n global_variables: &GlobalVariables,\n\n ) -> Option<Command> {\n\n self.sm\n\n .trigger(irust_api::OutputEvent(\n\n global_variables.clone(),\n\n input.to_string(),\n\n ))\n\n .next()?\n\n .ok()?\n\n }\n\n fn trigger_set_title_hook(&mut self) -> Option<String> {\n\n self.sm.trigger(irust_api::SetTitle()).next()?.ok()?\n\n }\n\n\n\n fn trigger_set_msg_hook(&mut self) -> Option<String> {\n\n self.sm.trigger(irust_api::SetWelcomeMsg()).next()?.ok()?\n\n }\n\n\n\n fn list(&self) -> Option<String> {\n", "file_path": "crates/irust/src/irust/script/script4.rs", "rank": 73, "score": 67922.55375904658 }, { "content": " .ok()\n\n }\n\n fn after_compiling(&mut self, global_variables: &GlobalVariables) -> Option<()> {\n\n self.sm\n\n .trigger(irust_api::AfterCompiling(global_variables.clone()))\n\n .collect::<Result<_, _>>()\n\n .ok()\n\n }\n\n fn input_event_hook(\n\n &mut self,\n\n global_variables: &GlobalVariables,\n\n event: Event,\n\n ) -> Option<Command> {\n\n self.sm\n\n .trigger(irust_api::InputEvent(global_variables.clone(), event))\n\n .next()?\n\n .ok()?\n\n }\n\n fn output_event_hook(\n\n &mut self,\n", "file_path": "crates/irust/src/irust/script/script4.rs", "rank": 74, "score": 67917.94126277388 }, { "content": " }\n\n })\n\n }\n\n\n\n Some(ScriptManager4 { sm, startup_cmds })\n\n }\n\n}\n\nimpl Drop for ScriptManager4 {\n\n fn drop(&mut self) {\n\n let mut script_state = HashMap::new();\n\n for script in self.sm.scripts() {\n\n script_state.insert(script.metadata().name.clone(), script.is_active());\n\n }\n\n // Ignore errors on drop\n\n let _ = mtry!({\n\n let script_conf_path = dirs::config_dir()\n\n .ok_or(\"could not find config directory\")?\n\n .join(\"irust\")\n\n .join(\"script4.conf\");\n\n std::fs::write(script_conf_path, toml::to_string(&script_state)?)\n\n });\n\n }\n\n}\n\n\n\n/* NOTE: Toml: serilizing tuple struct is not working?\n\n#[derive(Serialize, Deserialize, Debug)]\n", "file_path": "crates/irust/src/irust/script/script4.rs", "rank": 75, "score": 67917.15468831419 }, { "content": "\n\n let mut startup_cmds = vec![];\n\n if let Ok(script_state) =\n\n mtry!(toml::from_str(&std::fs::read_to_string(script_conf_path)?)?)\n\n {\n\n // type inference\n\n let script_state: HashMap<String, bool> = script_state;\n\n\n\n sm.scripts_mut().iter_mut().for_each(|script| {\n\n let script_name = &script.metadata().name;\n\n if let Some(state) = script_state.get(script_name) {\n\n if *state {\n\n script.activate();\n\n // Trigger startup hook, in case the script needs to be aware of it\n\n if script.is_listening_for::<irust_api::Startup>() {\n\n startup_cmds.push(script.trigger(&irust_api::Startup()));\n\n }\n\n } else {\n\n script.deactivate();\n\n }\n", "file_path": "crates/irust/src/irust/script/script4.rs", "rank": 76, "score": 67916.19814624044 }, { "content": " self.startup_cmds.drain(..).collect()\n\n }\n\n\n\n fn shutdown_cmds(&mut self) -> Vec<Result<Option<Command>, rscript::Error>> {\n\n self.sm\n\n .scripts_mut()\n\n .iter_mut()\n\n .filter(|script| script.is_listening_for::<irust_api::Shutdown>())\n\n .map(|script| script.trigger(&irust_api::Shutdown()))\n\n .collect()\n\n }\n\n}\n", "file_path": "crates/irust/src/irust/script/script4.rs", "rank": 77, "score": 67913.7790997455 }, { "content": " let mut scripts: Vec<String> = self\n\n .sm\n\n .scripts()\n\n .iter()\n\n .map(|script| {\n\n let meta = script.metadata();\n\n format!(\n\n \"{}\\t{:?}\\t{:?}\\t{}\",\n\n &meta.name,\n\n &meta.script_type,\n\n &meta.hooks,\n\n script.is_active()\n\n )\n\n })\n\n .collect();\n\n //header\n\n scripts.insert(0, \"Name\\tScriptType\\tHooks\\tState\".into());\n\n\n\n Some(scripts.join(\"\\n\"))\n\n }\n", "file_path": "crates/irust/src/irust/script/script4.rs", "rank": 78, "score": 67912.79223029135 }, { "content": " let script_path = dirs::config_dir()?.join(\"irust\").join(\"script4\");\n\n sm.add_scripts_by_path(\n\n &script_path,\n\n rscript::Version::parse(crate::args::VERSION).expect(\"correct version\"),\n\n )\n\n .ok()?;\n\n unsafe {\n\n sm.add_dynamic_scripts_by_path(\n\n script_path,\n\n rscript::Version::parse(crate::args::VERSION).expect(\"correct version\"),\n\n )\n\n .ok()?;\n\n }\n\n\n\n // read conf if available\n\n let script_conf_path = dirs::config_dir()?.join(\"irust\").join(\"script4.conf\");\n\n\n\n // ignore any error that happens while trying to read conf\n\n // If an error happens, a new configuration will be written anyway when ScriptManager is\n\n // dropped\n", "file_path": "crates/irust/src/irust/script/script4.rs", "rank": 79, "score": 67909.69626142233 }, { "content": "enum PType {\n\n In,\n\n Out,\n\n}\n\nimpl std::fmt::Display for PType {\n\n fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {\n\n match self {\n\n PType::In => write!(f, \"In\"),\n\n PType::Out => write!(f, \"Out\"),\n\n }\n\n }\n\n}\n\n\n\nimpl Prompt {\n\n fn prompt(global: GlobalVariables, ptype: PType) -> String {\n\n format!(\"{} [{}]: \", ptype, global.operation_number)\n\n }\n\n fn run(hook_name: &str) {\n\n match hook_name {\n\n irust_api::SetInputPrompt::NAME => {\n", "file_path": "script_examples/irust_prompt/src/main.rs", "rank": 80, "score": 63588.87867763017 }, { "content": "fn main() {\n\n let mut options = Options::new().unwrap_or_default();\n\n\n\n // Handle args\n\n let args: Vec<String> = std::env::args().skip(1).collect();\n\n let args_result = if args.is_empty() {\n\n ArgsResult::Proceed\n\n } else {\n\n handle_args(&args, &mut options)\n\n };\n\n\n\n // Exit if there is nothing more todo\n\n if matches!(args_result, ArgsResult::Exit) {\n\n exit(0)\n\n }\n\n\n\n // If no argument are provided, check stdin for some oneshot usage\n\n if args.is_empty() {\n\n let mut stdin = std::io::stdin();\n\n if !stdin.is_tty() {\n", "file_path": "crates/irust/src/main.rs", "rank": 81, "score": 58347.13434091245 }, { "content": "#[test]\n\nfn repl() {\n\n let mut repl = Repl::default();\n\n repl.insert(\"let a = 4;\");\n\n repl.insert(\"let b = 6;\");\n\n assert_eq!(repl.eval(\"a+b\").unwrap().output, \"10\");\n\n\n\n repl.insert(r#\"let c = \"hello\";\"#);\n\n assert_eq!(repl.eval(\"c.chars().count() < a+b\").unwrap().output, \"true\");\n\n\n\n repl.set_executor(Executor::AsyncStd).unwrap();\n\n repl.insert(\"async fn d() -> usize {4}\");\n\n assert_eq!(repl.eval(\"d().await\").unwrap().output, \"4\");\n\n}\n", "file_path": "crates/irust_repl/tests/repl.rs", "rank": 82, "score": 57151.616606831885 }, { "content": "fn visit_dirs(\n\n dir: &Path,\n\n dcb: &dyn Fn(PathBuf) -> Result<()>,\n\n fcb: &dyn Fn(PathBuf) -> Result<u64>,\n\n) -> Result<()> {\n\n if dir.is_dir() {\n\n dcb(dir.to_path_buf())?;\n\n for entry in fs::read_dir(dir)? {\n\n let entry = entry?;\n\n let path = entry.path();\n\n if path.is_dir() {\n\n visit_dirs(&path, dcb, fcb)?;\n\n } else {\n\n fcb(entry.path())?;\n\n }\n\n }\n\n }\n\n Ok(())\n\n}\n", "file_path": "crates/irust/src/utils.rs", "rank": 83, "score": 57151.616606831885 }, { "content": "#[test]\n\nfn split_args_test() {\n\n let cmd = r#\":add crate --no-default --features \"a b c\"\"#.to_string();\n\n assert_eq!(\n\n vec![\":add\", \"crate\", \"--no-default\", \"--features\", \"a b c\",]\n\n .into_iter()\n\n .map(ToOwned::to_owned)\n\n .collect::<Vec<String>>(),\n\n split_args(cmd)\n\n );\n\n}\n\n\n", "file_path": "crates/irust/src/utils.rs", "rank": 84, "score": 56035.76455011107 }, { "content": "fn main() {\n\n let args: Vec<String> = std::env::args().skip(1).collect();\n\n\n\n match args.len() {\n\n 0 => panic!(\"No code provided\"), // error\n\n 1 => {\n\n // code\n\n eval(None, &args[0]);\n\n }\n\n 2 => {\n\n // deps + code\n\n eval(Some(&args[0]), &args[1]);\n\n }\n\n _ => panic!(\"Extra arguments provided\"), // extra arguments\n\n }\n\n}\n\n\n", "file_path": "crates/irust_repl/examples/re/main.rs", "rank": 85, "score": 56035.76455011107 }, { "content": "#[test]\n\nfn writenew_line_with_scroll() {\n\n let mut p = Printer::new(std::io::sink(), \"\".to_owned());\n\n let b = \"Hello world\".into();\n\n\n\n p.cursor.pos.starting_pos.0 = 0;\n\n p.cursor.pos.starting_pos.1 = p.cursor.bound.height - 1;\n\n p.cursor.goto_start();\n\n\n\n assert_eq!(p.cursor.pos.current_pos, p.cursor.pos.starting_pos);\n\n\n\n let origin_pos = p.cursor.pos;\n\n p.write_newline(&b);\n\n\n\n assert_eq!(origin_pos.starting_pos.1, p.cursor.pos.starting_pos.1);\n\n assert_eq!(origin_pos.current_pos.1, p.cursor.pos.current_pos.1);\n\n}\n\n\n", "file_path": "crates/printer/src/printer/tests.rs", "rank": 86, "score": 54991.87191275835 }, { "content": "#[test]\n\nfn writenew_line_no_scroll() {\n\n let mut p = Printer::new(std::io::sink(), \"\".to_owned());\n\n\n\n let b = \"Hello world\".into();\n\n\n\n p.cursor.pos.starting_pos.0 = 0;\n\n p.cursor.pos.starting_pos.1 = 0;\n\n p.cursor.goto_start();\n\n assert_eq!(p.cursor.pos.current_pos, p.cursor.pos.starting_pos);\n\n\n\n let origin_pos = p.cursor.pos;\n\n p.write_newline(&b);\n\n\n\n assert_eq!(origin_pos.starting_pos.1 + 1, p.cursor.pos.starting_pos.1);\n\n assert_eq!(origin_pos.current_pos.1 + 1, p.cursor.pos.current_pos.1);\n\n}\n\n\n", "file_path": "crates/printer/src/printer/tests.rs", "rank": 87, "score": 54991.87191275835 }, { "content": "fn main() -> Result<()> {\n\n let mut printer = Printer::new(std::io::stdout(), \"In: \".into());\n\n printer.print_prompt_if_set()?;\n\n std::io::Write::flush(&mut printer.writer.raw)?;\n\n\n\n let mut buffer = Buffer::new();\n\n\n\n loop {\n\n let inp = crossterm::event::read()?;\n\n match inp {\n\n crossterm::event::Event::Key(key) => match key {\n\n KeyEvent {\n\n code: KeyCode::Char(c),\n\n modifiers: KeyModifiers::NONE,\n\n } => {\n\n buffer.insert(c);\n\n printer.print_input(&default_process_fn, &buffer)?;\n\n printer.cursor.move_right_unbounded();\n\n }\n\n KeyEvent {\n", "file_path": "crates/printer/examples/shell.rs", "rank": 88, "score": 54791.95361254075 }, { "content": "#[test]\n\nfn scroll_up() -> Result<()> {\n\n let mut p = Printer::new(std::io::sink(), \"\".to_owned());\n\n\n\n let origin_pos = p.cursor.pos;\n\n p.scroll_up(3);\n\n\n\n assert_eq!(\n\n origin_pos.starting_pos.1.saturating_sub(3),\n\n p.cursor.pos.starting_pos.1\n\n );\n\n assert_eq!(\n\n origin_pos.current_pos.1.saturating_sub(3),\n\n p.cursor.pos.current_pos.1\n\n );\n\n\n\n Ok(())\n\n}\n\n\n", "file_path": "crates/printer/src/printer/tests.rs", "rank": 89, "score": 53676.10155581993 }, { "content": "fn peek_first_non_white_sapce(\n\n tokens: &[rustc_lexer::Token],\n\n) -> Option<(usize, rustc_lexer::TokenKind)> {\n\n for (idx, token) in tokens.iter().enumerate() {\n\n if token.kind != rustc_lexer::TokenKind::Whitespace {\n\n return Some((idx, token.kind));\n\n }\n\n }\n\n None\n\n}\n\n\n", "file_path": "crates/irust/src/irust/highlight.rs", "rank": 90, "score": 53093.80843207172 }, { "content": "// The difference in env flags makes cargo recompiles again!!!\n\n// => make sure all build env flags are the same\n\n// Or even better dont use any\n\nfn cargo_common<'a>(\n\n cargo: &'a mut process::Command,\n\n cmd: &str,\n\n toolchain: ToolChain,\n\n) -> &'a mut Command {\n\n match toolchain {\n\n ToolChain::Default => cargo,\n\n _ => cargo.arg(toolchain.as_arg()),\n\n }\n\n .arg(cmd)\n\n .env(\"CARGO_TARGET_DIR\", &*IRUST_TARGET_DIR)\n\n .current_dir(&*IRUST_DIR)\n\n}\n\n\n", "file_path": "crates/irust_repl/src/cargo_cmds.rs", "rank": 91, "score": 52635.96218188436 }, { "content": "#[test]\n\nfn calculate_bounds_correctly() -> Result<()> {\n\n let mut p = Printer::new(std::io::sink(), \"\".to_owned());\n\n let width = p.cursor.bound.width;\n\n let height = p.cursor.bound.height;\n\n let queue = default_process_fn(&\"alloc\\nprint\".into());\n\n\n\n // 1\n\n move_to_and_modify_start(&mut p, 0, 0);\n\n p.recalculate_bounds(queue.clone())?;\n\n\n\n let expected_bound = {\n\n let mut v = vec![width - 1; height];\n\n v[0] = 9;\n\n v[1] = 9;\n\n v\n\n };\n\n assert_eq!(expected_bound, p.cursor.bound.bound);\n\n Ok(())\n\n}\n\n\n", "file_path": "crates/printer/src/printer/tests.rs", "rank": 92, "score": 51653.53232243018 }, { "content": "#[test]\n\nfn write_from_terminal_start_cursor_pos_correct() -> Result<()> {\n\n let mut p = Printer::new(std::io::sink(), \"\".to_owned());\n\n\n\n let origin_pos = p.cursor.pos;\n\n p.write_from_terminal_start(\"hello\", Color::Red)?;\n\n assert_eq!(p.cursor.pos.current_pos.0, 5);\n\n assert_eq!(p.cursor.pos.current_pos.1, origin_pos.current_pos.1);\n\n\n\n Ok(())\n\n}\n\n\n", "file_path": "crates/printer/src/printer/tests.rs", "rank": 93, "score": 49052.92066401531 }, { "content": "fn clean_files() -> io::Result<()> {\n\n const MAIN_SRC: &str = \"fn main() {\\n\\n}\";\n\n let mut main = fs::File::create(&*MAIN_FILE)?;\n\n write!(main, \"{}\", MAIN_SRC)?;\n\n std::fs::copy(&*MAIN_FILE, &*MAIN_FILE_EXTERN)?;\n\n let _ = std::fs::remove_file(&*LIB_FILE);\n\n Ok(())\n\n}\n", "file_path": "crates/irust_repl/src/cargo_cmds.rs", "rank": 94, "score": 48802.44851074671 }, { "content": "fn is_function(tokens: &[rustc_lexer::Token]) -> bool {\n\n let (idx, kind) = match peek_first_non_white_sapce(tokens) {\n\n Some((i, k)) => (i, k),\n\n None => return false,\n\n };\n\n use rustc_lexer::TokenKind::*;\n\n match kind {\n\n OpenParen => true,\n\n Lt => true,\n\n Colon => is_function(&tokens[idx + 1..]),\n\n _ => false,\n\n }\n\n}\n\n\n\n// Splitting keywords for a nicer coloring\n\n// red blue green blue red white\n\n// exp: pub fn hello() let mut var\n\nconst KEYWORDS: &[&str] = &[\n\n \"async\", \"await\", \"while\", \"use\", \"super\", \"self\", \"Self\", \"for\", \"impl\", \"trait\", \"type\",\n\n \"pub\", \"in\", \"const\", \"static\", \"match\", \"use\", \"mut\", \"continue\", \"loop\", \"break\", \"if\",\n\n \"else\", \"macro\",\n\n];\n\nconst KEYWORDS2: &[&str] = &[\"unsafe\", \"move\", \"fn\", \"let\", \"struct\", \"enum\", \"dyn\"];\n\n\n\nconst TYPES: &[&str] = &[\n\n \"bool\", \"char\", \"usize\", \"isize\", \"u8\", \"i8\", \"u32\", \"i32\", \"u64\", \"i64\", \"u128\", \"i128\",\n\n \"str\", \"String\",\n\n];\n", "file_path": "crates/irust/src/irust/highlight.rs", "rank": 95, "score": 44963.409668629174 }, { "content": "fn clean_cargo_toml(edition: Edition) -> io::Result<()> {\n\n // edition needs to be specified or racer will not be able to autocomplete dependencies\n\n // bug maybe?\n\n let cargo_toml = format!(\n\n \"\\\n\n[package]\n\nname = \\\"irust_host_repl\\\"\n\nversion = \\\"0.1.0\\\"\n\nedition = \\\"{}\\\"\",\n\n edition\n\n );\n\n let mut cargo_toml_file = fs::File::create(&*CARGO_TOML_FILE)?;\n\n write!(cargo_toml_file, \"{}\", cargo_toml)?;\n\n Ok(())\n\n}\n\n\n", "file_path": "crates/irust_repl/src/cargo_cmds.rs", "rank": 96, "score": 43376.924095254726 }, { "content": "fn try_cargo_fmt_file(file: &Path) -> io::Result<()> {\n\n std::process::Command::new(\"rustfmt\")\n\n .stdout(std::process::Stdio::null())\n\n .stderr(std::process::Stdio::null())\n\n // ensure that main is always spread on two lines\n\n // this is needed for inserting the input correctly in the repl\n\n // fn main() {\n\n // }\n\n .arg(\"--config\")\n\n .arg(\"empty_item_single_line=false\")\n\n .arg(file)\n\n .spawn()?\n\n .wait()?;\n\n Ok(())\n\n}\n\n\n", "file_path": "crates/irust_repl/src/cargo_cmds.rs", "rank": 97, "score": 42647.975058261996 }, { "content": "use irust_api::event::{Event, KeyCode, KeyEvent, KeyModifiers};\n\nuse irust_api::Command;\n\nuse rscript::Hook;\n\n\n\nuse super::{Mode, State, Vim};\n\n\n\nimpl Vim {\n\n pub const fn new() -> Self {\n\n Self {\n\n state: State::Empty,\n\n mode: Mode::Insert,\n\n }\n\n }\n\n pub fn start_up(&mut self, _: irust_api::Startup) -> <irust_api::Startup as Hook>::Output {\n\n self.state = State::Empty;\n\n self.mode = Mode::Insert;\n\n Some(Command::SetThinCursor)\n\n }\n\n pub fn clean_up(&mut self, _: irust_api::Shutdown) -> <irust_api::Shutdown as Hook>::Output {\n\n self.state = State::Empty;\n", "file_path": "script_examples/irust_vim_dylib/src/script.rs", "rank": 98, "score": 42241.25877008072 }, { "content": " self.mode = Mode::Normal;\n\n Some(Command::SetWideCursor)\n\n }\n\n pub fn handle_input_event(\n\n &mut self,\n\n input_event: irust_api::InputEvent,\n\n ) -> <irust_api::InputEvent as Hook>::Output {\n\n let irust_api::InputEvent(global, event) = input_event;\n\n macro_rules! reset_state {\n\n () => {{\n\n self.state = State::Empty;\n\n }};\n\n }\n\n\n\n let cmd = (|| match event {\n\n Event::Key(key) => match key {\n\n KeyEvent {\n\n code: KeyCode::Char(c),\n\n modifiers,\n\n } => {\n", "file_path": "script_examples/irust_vim_dylib/src/script.rs", "rank": 99, "score": 42235.37969679614 } ]
Rust
src/stage_spec.rs
Isaac-Lozano/sa2_piece_gen
fd99d4cdd8b1f2e5d08072a962b8e686d8462153
use std::fs::File; use std::io::{Read, Seek, SeekFrom}; use std::path::Path; use serde_derive::{Serialize, Deserialize}; #[cfg(windows)] use process_reader::ProcessHandle; use byteorder::{ReadBytesExt, BE}; use crate::vector::Vector; use crate::rng::Rng; use crate::Platform; #[derive(Clone, Copy, Debug, Serialize, Deserialize)] pub struct Emerald { pub id: u16, pub position: Vector, } impl Default for Emerald { fn default() -> Emerald { Emerald { id: 0xFF00, position: Vector::default(), } } } #[derive(Clone, Debug, Serialize, Deserialize)] pub struct StageSpec { pub slot1_pieces: Vec<Emerald>, pub slot2_pieces: Vec<Emerald>, pub slot3_pieces: Vec<Emerald>, pub enemy_pieces: Vec<Emerald>, pub pre_calls: u32, } impl StageSpec { #[cfg(windows)] pub fn from_process<P>(process_name: &str) -> StageSpec where P: Platform, { let p_handle = ProcessHandle::from_name_filter(|s| s.to_lowercase() == process_name).unwrap().unwrap(); let em_addr = p_handle.read_u32(0x01AF014C).unwrap() as u64; let num_p1 = p_handle.read_u8(em_addr + 6).unwrap(); let num_p2 = p_handle.read_u8(em_addr + 7).unwrap(); let num_p3 = p_handle.read_u8(em_addr + 8).unwrap(); let num_en = p_handle.read_u8(em_addr + 9).unwrap(); let read_list = |addr, num| { let mut pieces = Vec::new(); let mut addr = p_handle.read_u32(addr).unwrap() as u64; for _ in 0..num { let major_id = p_handle.read_u8(addr).unwrap(); let minor_id = p_handle.read_u8(addr + 1).unwrap(); let x = p_handle.read_f32(addr + 4).unwrap(); let y = p_handle.read_f32(addr + 8).unwrap(); let z = p_handle.read_f32(addr + 12).unwrap(); pieces.push(Emerald { id: (major_id as u16) << 8 | minor_id as u16, position: Vector { x: x, y: y, z: z, } }); addr += 16; } pieces }; let p1_list = read_list(em_addr + 0x5C, num_p1); let p2_list = read_list(em_addr + 0x60, num_p2); let p3_list = read_list(em_addr + 0x64, num_p3); let en_list = read_list(em_addr + 0x68, num_en); let rng_state = p_handle.read_u32(0x05CE05BC).unwrap(); let mut r = Rng::new(0xDEAD0CAB); let mut calls = 0; while r.get_state() != rng_state { calls += 1; r.gen_val::<P::Consts>(); } StageSpec { slot1_pieces: p1_list, slot2_pieces: p2_list, slot3_pieces: p3_list, enemy_pieces: en_list, pre_calls: calls, } } pub fn from_path<P, A>(filename: A) -> StageSpec where P: Platform, A: AsRef<Path>, { let mut file = File::open(filename).unwrap(); file.seek(SeekFrom::Start(0x00C5D5A6)).unwrap(); let num_p1 = file.read_u8().unwrap(); let num_p2 = file.read_u8().unwrap(); let num_p3 = file.read_u8().unwrap(); let num_en = file.read_u8().unwrap(); file.seek(SeekFrom::Start(0x00C5D5FC)).unwrap(); let p1_addr = file.read_u32::<BE>().unwrap() ^ 0x80000000; let p2_addr = file.read_u32::<BE>().unwrap() ^ 0x80000000; let p3_addr = file.read_u32::<BE>().unwrap() ^ 0x80000000; let en_addr = file.read_u32::<BE>().unwrap() ^ 0x80000000; file.seek(SeekFrom::Start(0x003AD6A0)).unwrap(); let rng_state = file.read_u32::<BE>().unwrap(); let mut read_list = |addr, num| { let mut pieces = Vec::new(); file.seek(SeekFrom::Start(addr)).unwrap(); for _ in 0..num { let id = file.read_u16::<BE>().unwrap(); let _padding = file.read_u16::<BE>().unwrap(); let x = file.read_f32::<BE>().unwrap(); let y = file.read_f32::<BE>().unwrap(); let z = file.read_f32::<BE>().unwrap(); pieces.push(Emerald { id: id, position: Vector { x: x, y: y, z: z, } }); } pieces }; let p1_list = read_list(p1_addr as u64, num_p1); let p2_list = read_list(p2_addr as u64, num_p2); let p3_list = read_list(p3_addr as u64, num_p3); let en_list = read_list(en_addr as u64, num_en); let mut r = Rng::new(0xDEAD0CAB); let mut calls = 0; while r.get_state() != rng_state { calls += 1; r.gen_val::<P::Consts>(); } StageSpec { slot1_pieces: p1_list, slot2_pieces: p2_list, slot3_pieces: p3_list, enemy_pieces: en_list, pre_calls: calls, } } }
use std::fs::File; use std::io::{Read, Seek, SeekFrom}; use std::path::Path; use serde_derive::{Serialize, Deserialize}; #[cfg(windows)] use process_reader::ProcessHandle; use byteorder::{ReadBytesExt, BE}; use crate::vector::Vector; use crate::rng::Rng; use crate::Platform; #[derive(Clone, Copy, Debug, Serialize, Deserialize)] pub struct Emerald { pub id: u16, pub position: Vector, } impl Default for Emerald { fn default() -> Emerald { Emerald { id: 0xFF00, position: Vector::default(), } } } #[derive(Clone, Debug, Serialize, Deserialize)] pub struct StageSpec { pub slot1_pieces: Vec<Emerald>, pub slot2_pieces: Vec<Emerald>, pub slot3_pieces: Vec<Emerald>, pub enemy_pieces: Vec<Emerald>, pub pre_calls: u32, } impl StageSpec { #[cfg(windows)] pub fn from_process<P>(process_name: &str) -> StageSpec where P: Platform, { let p_handle = ProcessHandle::from_name_filter(|s| s.to_lowercase() == process_name).unwrap().unwrap(); let em_addr = p_handle.read_u32(0x01AF014C).unwrap() as u64; let num_p1 = p_handle.read_u8(em_addr + 6).unwrap(); let num_p2 = p_handle.read_u8(em_addr + 7).unwrap(); let num_p3 = p_handle.read_u8(em_addr + 8).unwrap(); let num_en = p_handle.read_u8(em_addr + 9).unwrap(); let read_list = |addr, num| { let mut pieces = Vec::new(); let mut addr = p_handle.read_u32(addr).unwrap() as u64; for _ in 0..num { let major_id = p_handle.read_u8(addr).unwrap(); let minor_id = p_handle.read_u8(addr + 1).unwrap(); let x = p_handle.read_f32(addr + 4).unwrap(); let y = p_handle.read_f32(addr + 8).unwrap(); let z = p_handle.read_f32(addr + 12).unwrap(); pieces.push(Emerald { id: (major_id as u16) << 8 | minor_id as u16, position: Vector { x: x, y: y, z: z, } }); addr += 16; } pieces }; let p1_list = read_list(em_addr + 0x5C, num_p1); let p2_list = read_list(em_addr + 0x60, num_p2); let p3_list = read_list(em_addr + 0x64, num_p3); let en_list = read_list(em_addr + 0x68, num_en); let rng_state = p_handle.read_u32(0x05CE05BC).unwrap(); let mut r = Rng::new(0xDEAD0CAB); let mut calls = 0; while r.get_state() != rng_state { calls += 1; r.gen_val::<P::Consts>(); } StageSpec { slot1_pieces: p1_list, slot2_pieces: p2_list, slot3_pieces: p3_list, enemy_pieces: en_list, pre_calls: calls, } } pub fn from_path<P, A>(filename: A) -> StageSpec where P: Platform, A: AsRef<Path>, { let mut file = File::open(filename).unwrap(); file.seek(SeekFrom::Start(0x00C5D5A6)).unwrap(); let num_p1 = file.read_u8().unwrap(); let num_p2 = file.read_u8().unwrap(); let num_p3 = file.read_u8().unwrap(); let num_en = file.read_u8().unwrap(); file.seek(SeekFrom::Start(0x00C5D5FC)).unwrap(); let p1_addr = file.read_u32::<BE>().unwrap() ^ 0x80000000; let p2_addr = file.read_u32::<BE>().unwrap() ^ 0x80000000; let p3_addr = file.read_u32::<BE>().unwr
let mut pieces = Vec::new(); file.seek(SeekFrom::Start(addr)).unwrap(); for _ in 0..num { let id = file.read_u16::<BE>().unwrap(); let _padding = file.read_u16::<BE>().unwrap(); let x = file.read_f32::<BE>().unwrap(); let y = file.read_f32::<BE>().unwrap(); let z = file.read_f32::<BE>().unwrap(); pieces.push(Emerald { id: id, position: Vector { x: x, y: y, z: z, } }); } pieces }; let p1_list = read_list(p1_addr as u64, num_p1); let p2_list = read_list(p2_addr as u64, num_p2); let p3_list = read_list(p3_addr as u64, num_p3); let en_list = read_list(en_addr as u64, num_en); let mut r = Rng::new(0xDEAD0CAB); let mut calls = 0; while r.get_state() != rng_state { calls += 1; r.gen_val::<P::Consts>(); } StageSpec { slot1_pieces: p1_list, slot2_pieces: p2_list, slot3_pieces: p3_list, enemy_pieces: en_list, pre_calls: calls, } } }
ap() ^ 0x80000000; let en_addr = file.read_u32::<BE>().unwrap() ^ 0x80000000; file.seek(SeekFrom::Start(0x003AD6A0)).unwrap(); let rng_state = file.read_u32::<BE>().unwrap(); let mut read_list = |addr, num| {
random
[ { "content": "pub trait Platform {\n\n type SquareRoot: vector::Sqrt;\n\n type Consts: rng::RngConsts;\n\n}\n\n\n\npub struct Gc;\n\n\n\nimpl Platform for Gc {\n\n type SquareRoot = vector::GcFp;\n\n type Consts = rng::GcRng;\n\n}\n\n\n\npub struct Pc;\n\n\n\nimpl Platform for Pc {\n\n type SquareRoot = vector::PcFp;\n\n type Consts = rng::PcRng;\n\n}\n", "file_path": "src/lib.rs", "rank": 0, "score": 50792.11146527272 }, { "content": "#[derive(Clone, Copy, Debug)]\n\nstruct BaseAndDec {\n\n base: u32,\n\n dec: u32,\n\n}\n\n\n\nconst FRSQRTE_EXPECTED: [BaseAndDec; 32] = [\n\n BaseAndDec{base: 0x3ffa000, dec: 0x7a4}, BaseAndDec{base: 0x3c29000, dec: 0x700},\n\n BaseAndDec{base: 0x38aa000, dec: 0x670}, BaseAndDec{base: 0x3572000, dec: 0x5f2},\n\n BaseAndDec{base: 0x3279000, dec: 0x584}, BaseAndDec{base: 0x2fb7000, dec: 0x524},\n\n BaseAndDec{base: 0x2d26000, dec: 0x4cc}, BaseAndDec{base: 0x2ac0000, dec: 0x47e},\n\n BaseAndDec{base: 0x2881000, dec: 0x43a}, BaseAndDec{base: 0x2665000, dec: 0x3fa},\n\n BaseAndDec{base: 0x2468000, dec: 0x3c2}, BaseAndDec{base: 0x2287000, dec: 0x38e},\n\n BaseAndDec{base: 0x20c1000, dec: 0x35e}, BaseAndDec{base: 0x1f12000, dec: 0x332},\n\n BaseAndDec{base: 0x1d79000, dec: 0x30a}, BaseAndDec{base: 0x1bf4000, dec: 0x2e6},\n\n BaseAndDec{base: 0x1a7e800, dec: 0x568}, BaseAndDec{base: 0x17cb800, dec: 0x4f3},\n\n BaseAndDec{base: 0x1552800, dec: 0x48d}, BaseAndDec{base: 0x130c000, dec: 0x435},\n\n BaseAndDec{base: 0x10f2000, dec: 0x3e7}, BaseAndDec{base: 0x0eff000, dec: 0x3a2},\n\n BaseAndDec{base: 0x0d2e000, dec: 0x365}, BaseAndDec{base: 0x0b7c000, dec: 0x32e},\n\n BaseAndDec{base: 0x09e5000, dec: 0x2fc}, BaseAndDec{base: 0x0867000, dec: 0x2d0},\n\n BaseAndDec{base: 0x06ff000, dec: 0x2a8}, BaseAndDec{base: 0x05ab800, dec: 0x283},\n", "file_path": "src/vector.rs", "rank": 1, "score": 44358.99399834648 }, { "content": "pub trait Sqrt {\n\n fn sqrt(val: f32) -> f32;\n\n}\n\n\n\npub struct GcFp;\n\n\n\nimpl GcFp {\n\n fn frsqrte(val: f64) -> f64 {\n\n let integral: u64 = unsafe {\n\n mem::transmute(val)\n\n };\n\n let sign = integral & (1 << 63);\n\n let exponent = integral & (0x7FF << 52);\n\n let mantissa = integral & ((1 << 52) - 1);\n\n\n\n if exponent == 0 && mantissa == 0 {\n\n if sign == 0 {\n\n return f64::INFINITY;\n\n }\n\n else {\n", "file_path": "src/vector.rs", "rank": 2, "score": 41937.52787910599 }, { "content": "struct F32Cmp(f32);\n\n\n\nimpl PartialEq<F32Cmp> for F32Cmp {\n\n fn eq(&self, other: &Self) -> bool {\n\n self.0.eq(&other.0)\n\n }\n\n}\n\n\n\nimpl Eq for F32Cmp {}\n\n\n\nimpl PartialOrd<F32Cmp> for F32Cmp {\n\n fn partial_cmp(&self, other: &Self) -> Option<Ordering> {\n\n self.0.partial_cmp(&other.0)\n\n }\n\n}\n\n\n\nimpl Ord for F32Cmp {\n\n fn cmp(&self, other: &Self) -> Ordering {\n\n self.partial_cmp(other).unwrap_or(Ordering::Equal)\n\n }\n", "file_path": "src/emerald_manager.rs", "rank": 3, "score": 37878.90680896952 }, { "content": "pub trait RngConsts {\n\n const MULT_COEFFICIENT: u32;\n\n const ADD_COEFFICIENT: u32;\n\n}\n\n\n\npub struct PcRng;\n\n\n\nimpl RngConsts for PcRng {\n\n const MULT_COEFFICIENT: u32 = 0x000343FD;\n\n const ADD_COEFFICIENT: u32 = 0x00269EC3;\n\n}\n\n\n\npub struct GcRng;\n\n\n\nimpl RngConsts for GcRng {\n\n const MULT_COEFFICIENT: u32 = 0x41C64E6D;\n\n const ADD_COEFFICIENT: u32 = 0x00003039;\n\n}\n\n\n\n#[derive(Clone, Copy, Debug)]\n", "file_path": "src/rng.rs", "rank": 4, "score": 24056.907065553183 }, { "content": " }\n\n}\n\n\n\npub struct PcFp;\n\n\n\nimpl Sqrt for PcFp {\n\n fn sqrt(val: f32) -> f32 {\n\n val.sqrt()\n\n }\n\n}\n\n\n\n#[derive(Clone, Copy, Debug, Serialize, Deserialize)]\n\npub struct Vector {\n\n pub x: f32,\n\n pub y: f32,\n\n pub z: f32,\n\n}\n\n\n\nimpl Vector {\n\n pub fn new(x: f32, y: f32, z: f32) -> Vector {\n", "file_path": "src/vector.rs", "rank": 5, "score": 19339.29372962786 }, { "content": "use std::ops::Sub;\n\nuse std::mem;\n\nuse std::f64;\n\nuse std::f32;\n\n\n\nuse serde_derive::{Serialize, Deserialize};\n\n\n\n#[derive(Clone, Copy, Debug)]\n", "file_path": "src/vector.rs", "rank": 6, "score": 19336.142133087837 }, { "content": "\n\n pub fn distance<F>(self, other: Vector) -> f32\n\n where F: Sqrt,\n\n {\n\n let diff = self - other;\n\n let dist_squ = diff.x * diff.x + diff.y * diff.y + diff.z * diff.z;\n\n if dist_squ < 0.025 {\n\n 0.0\n\n }\n\n else {\n\n F::sqrt(dist_squ)\n\n }\n\n }\n\n}\n\n\n\nimpl Default for Vector {\n\n fn default() -> Self {\n\n Vector {\n\n x: 0.0,\n\n y: 0.0,\n", "file_path": "src/vector.rs", "rank": 7, "score": 19332.95332191817 }, { "content": "// return -0.0;\n\n// }\n\n// }\n\n//\n\n// let reciprocal_exponent = (0x7FD << 52) - exponent;\n\n//\n\n// let i = mantissa >> 37;\n\n// let entry = FRES_EXPECTED[(i >> 10) as usize];\n\n// let mut reciprocal = sign | reciprocal_exponent;\n\n// reciprocal |= ((entry.base - (entry.dec * (i as u32 % 1024) + 1)) as u64 / 2) << 29;\n\n//\n\n// unsafe {\n\n// mem::transmute(reciprocal)\n\n// }\n\n// }\n\n}\n\n\n\nimpl Sqrt for GcFp {\n\n fn sqrt(val: f32) -> f32 {\n\n Self::fres(Self::frsqrte(val as f64)) as f32\n", "file_path": "src/vector.rs", "rank": 8, "score": 19330.991171557456 }, { "content": " Vector {\n\n x: x,\n\n y: y,\n\n z: z,\n\n }\n\n }\n\n\n\n pub fn cross(self, other: Vector) -> Vector {\n\n Vector {\n\n x: self.y * other.z - self.z * other.y,\n\n y: self.z * other.x - self.x * other.z,\n\n z: self.x * other.y - self.y * other.x,\n\n }\n\n }\n\n\n\n pub fn magnitude<F>(self) -> f32\n\n where F: Sqrt,\n\n {\n\n F::sqrt(self.x * self.x + self.y * self.y + self.z * self.z)\n\n }\n", "file_path": "src/vector.rs", "rank": 9, "score": 19330.628455239883 }, { "content": " z: 0.0,\n\n }\n\n }\n\n}\n\n\n\nimpl Sub<Vector> for Vector {\n\n type Output = Vector;\n\n\n\n fn sub(self, other: Self) -> Self::Output {\n\n Vector {\n\n x: self.x - other.x,\n\n y: self.y - other.y,\n\n z: self.z - other.z,\n\n }\n\n }\n\n}\n", "file_path": "src/vector.rs", "rank": 10, "score": 19330.394455496873 }, { "content": " let sqrt_exponent = ((0x3FF << 52) - ((exponent - (0x3FF << 52)) / 2)) & (0x7FF << 52);\n\n let mut sqrt = sign | sqrt_exponent;\n\n\n\n let i = mantissa >> 37;\n\n let index = (i >> 11) + if exponent & (1 << 52) != 0 { 16 } else { 0 };\n\n let entry = FRSQRTE_EXPECTED[index as usize];\n\n sqrt |= ((entry.base - entry.dec * (i as u32 % 2048)) as u64) << 26;\n\n\n\n unsafe {\n\n mem::transmute(sqrt)\n\n }\n\n }\n\n\n\n fn fres(val: f64) -> f64 {\n\n 1.0 / val\n\n }\n\n\n\n// fn fres(val: f64) -> f64 {\n\n// let integral: u64 = unsafe {\n\n// mem::transmute(val)\n", "file_path": "src/vector.rs", "rank": 11, "score": 19329.789570078763 }, { "content": " return f64::NEG_INFINITY;\n\n }\n\n }\n\n\n\n if exponent == (0x7FF << 52) {\n\n if mantissa == 0 {\n\n if sign == 0 {\n\n return 0.0;\n\n }\n\n else {\n\n return f64::NAN;\n\n }\n\n }\n\n return 0.0 + val;\n\n }\n\n\n\n if sign != 0 {\n\n return f64::NAN;\n\n }\n\n\n", "file_path": "src/vector.rs", "rank": 12, "score": 19325.072627254413 }, { "content": "// };\n\n// let sign = integral & (1 << 63);\n\n// let exponent = integral & (0x7FF << 52);\n\n// let mantissa = integral & ((1 << 52) - 1);\n\n//\n\n// if exponent == 0 && mantissa == 0 {\n\n// if sign == 0 {\n\n// return f64::INFINITY;\n\n// }\n\n// else {\n\n// return f64::NEG_INFINITY;\n\n// }\n\n// }\n\n//\n\n// if exponent == (0x7FF << 52) {\n\n// if mantissa == 0 {\n\n// if sign == 0 {\n\n// return 0.0;\n\n// }\n\n// else {\n", "file_path": "src/vector.rs", "rank": 13, "score": 19325.072627254413 }, { "content": " BaseAndDec{base: 0x046a000, dec: 0x261}, BaseAndDec{base: 0x0339800, dec: 0x243},\n\n BaseAndDec{base: 0x0218800, dec: 0x226}, BaseAndDec{base: 0x0105800, dec: 0x20b},\n\n];\n\n\n\nconst FRES_EXPECTED: [BaseAndDec; 32] = [\n\n BaseAndDec{base: 0x7ff800, dec: 0x3e1}, BaseAndDec{base: 0x783800, dec: 0x3a7},\n\n BaseAndDec{base: 0x70ea00, dec: 0x371}, BaseAndDec{base: 0x6a0800, dec: 0x340},\n\n BaseAndDec{base: 0x638800, dec: 0x313}, BaseAndDec{base: 0x5d6200, dec: 0x2ea},\n\n BaseAndDec{base: 0x579000, dec: 0x2c4}, BaseAndDec{base: 0x520800, dec: 0x2a0},\n\n BaseAndDec{base: 0x4cc800, dec: 0x27f}, BaseAndDec{base: 0x47ca00, dec: 0x261},\n\n BaseAndDec{base: 0x430800, dec: 0x245}, BaseAndDec{base: 0x3e8000, dec: 0x22a},\n\n BaseAndDec{base: 0x3a2c00, dec: 0x212}, BaseAndDec{base: 0x360800, dec: 0x1fb},\n\n BaseAndDec{base: 0x321400, dec: 0x1e5}, BaseAndDec{base: 0x2e4a00, dec: 0x1d1},\n\n BaseAndDec{base: 0x2aa800, dec: 0x1be}, BaseAndDec{base: 0x272c00, dec: 0x1ac},\n\n BaseAndDec{base: 0x23d600, dec: 0x19b}, BaseAndDec{base: 0x209e00, dec: 0x18b},\n\n BaseAndDec{base: 0x1d8800, dec: 0x17c}, BaseAndDec{base: 0x1a9000, dec: 0x16e},\n\n BaseAndDec{base: 0x17ae00, dec: 0x15b}, BaseAndDec{base: 0x14f800, dec: 0x15b},\n\n BaseAndDec{base: 0x124400, dec: 0x143}, BaseAndDec{base: 0x0fbe00, dec: 0x143},\n\n BaseAndDec{base: 0x0d3800, dec: 0x12d}, BaseAndDec{base: 0x0ade00, dec: 0x12d},\n\n BaseAndDec{base: 0x088400, dec: 0x11a}, BaseAndDec{base: 0x065000, dec: 0x11a},\n\n BaseAndDec{base: 0x041c00, dec: 0x108}, BaseAndDec{base: 0x020c00, dec: 0x106},\n\n];\n\n\n", "file_path": "src/vector.rs", "rank": 14, "score": 19325.072627254413 }, { "content": "// return -0.0;\n\n// }\n\n// }\n\n// return 0.0 + val;\n\n// }\n\n//\n\n// if exponent < 895 << 52 {\n\n// if sign == 0 {\n\n// return f64::MAX;\n\n// }\n\n// else {\n\n// return f64::MIN;\n\n// }\n\n// }\n\n//\n\n// if exponent >= 1149 << 52 {\n\n// if sign == 0 {\n\n// return 0.0;\n\n// }\n\n// else {\n", "file_path": "src/vector.rs", "rank": 15, "score": 19325.072627254413 }, { "content": "\n\n let read_list = |addr, num| {\n\n let mut pieces = Vec::new();\n\n let mut addr = p_handle.read_u32(addr).unwrap() as u64;\n\n\n\n for _ in 0..num {\n\n let major_id = p_handle.read_u8(addr).unwrap();\n\n let minor_id = p_handle.read_u8(addr + 1).unwrap();\n\n let x = p_handle.read_f32(addr + 4).unwrap();\n\n let y = p_handle.read_f32(addr + 8).unwrap();\n\n let z = p_handle.read_f32(addr + 12).unwrap();\n\n pieces.push(Emerald {\n\n id: (major_id as u16) << 8 | minor_id as u16,\n\n position: Vector {\n\n x: x,\n\n y: y,\n\n z: z,\n\n }\n\n });\n\n addr += 16;\n", "file_path": "src/emerald_manager.rs", "rank": 16, "score": 17700.364515413694 }, { "content": "}\n\n\n\n#[derive(Clone, Debug)]\n\npub struct EmeraldManager {\n\n pub slot1_pieces: Vec<Emerald>,\n\n pub slot2_pieces: Vec<Emerald>,\n\n pub slot3_pieces: Vec<Emerald>,\n\n pub enemy_pieces: Vec<Emerald>,\n\n pub p1: Emerald,\n\n pub p2: Emerald,\n\n pub p3: Emerald,\n\n pub r: Rng,\n\n}\n\n\n\nimpl EmeraldManager {\n\n pub fn from_set_file<P, R>(read: R) -> io::Result<EmeraldManager>\n\n where P: Platform,\n\n R: Read,\n\n {\n\n let set_file = SetFile::from_read::<Pc, _>(read)?;\n", "file_path": "src/emerald_manager.rs", "rank": 17, "score": 17699.443421162454 }, { "content": " if object.rotation.y != 0x00FF {\n\n enemy_pieces.push(Emerald {\n\n id: 0x0A00 | object.rotation.y,\n\n position: Vector {\n\n x: object.position.x,\n\n y: object.position.y,\n\n z: object.position.z,\n\n }\n\n })\n\n }\n\n }\n\n }\n\n\n\n let mut r = Rng::new(0xDEAD0CAB);\n\n for _ in 0..NUM_RNG_CALLS {\n\n r.gen_val::<P::Consts>();\n\n }\n\n\n\n Ok(EmeraldManager {\n\n slot1_pieces: slot1_pieces,\n", "file_path": "src/emerald_manager.rs", "rank": 18, "score": 17698.223976466845 }, { "content": " slot2_pieces: slot2_pieces,\n\n slot3_pieces: slot3_pieces,\n\n enemy_pieces: enemy_pieces,\n\n p1: Emerald::default(),\n\n p2: Emerald::default(),\n\n p3: Emerald::default(),\n\n r: r,\n\n })\n\n }\n\n\n\n #[cfg(windows)]\n\n pub fn from_process<P>(process_name: &str) -> EmeraldManager\n\n where P: Platform,\n\n {\n\n let p_handle = ProcessHandle::from_name_filter(|s| s.to_lowercase() == process_name).unwrap().unwrap();\n\n let em_addr = p_handle.read_u32(0x01AF014C).unwrap() as u64;\n\n let num_p1 = p_handle.read_u8(em_addr + 6).unwrap();\n\n let num_p2 = p_handle.read_u8(em_addr + 7).unwrap();\n\n let num_p3 = p_handle.read_u8(em_addr + 8).unwrap();\n\n let num_en = p_handle.read_u8(em_addr + 9).unwrap();\n", "file_path": "src/emerald_manager.rs", "rank": 19, "score": 17697.090170772422 }, { "content": "\n\n let mut slot1_pieces = Vec::new();\n\n let mut slot2_pieces = Vec::new();\n\n let mut slot3_pieces = Vec::new();\n\n let mut enemy_pieces = Vec::new();\n\n\n\n for object in set_file.0 {\n\n if object.object.0 == 0x0F {\n\n match object.rotation.x & 0xFF00 {\n\n 0x0100 | 0x0300 => slot1_pieces.push(Emerald {\n\n id: object.rotation.x,\n\n position: Vector {\n\n x: object.position.x,\n\n y: object.position.y,\n\n z: object.position.z,\n\n }\n\n }),\n\n 0x0000 | 0x0200 | 0x0500 => slot2_pieces.push(Emerald {\n\n id: object.rotation.x,\n\n position: Vector {\n", "file_path": "src/emerald_manager.rs", "rank": 20, "score": 17696.199419482346 }, { "content": " p1: Emerald::default(),\n\n p2: Emerald::default(),\n\n p3: Emerald::default(),\n\n r: r,\n\n }\n\n }\n\n\n\n pub fn from_set_file_path<P, A>(path: A) -> io::Result<EmeraldManager>\n\n where P: Platform,\n\n A: AsRef<Path>,\n\n {\n\n let file = File::open(path)?;\n\n Self::from_set_file::<P, _>(file)\n\n }\n\n\n\n pub fn from_spec<P>(spec: StageSpec) -> EmeraldManager\n\n where P: Platform,\n\n {\n\n let mut r = Rng::new(0xDEAD0CAB);\n\n for _ in 0..spec.pre_calls {\n", "file_path": "src/emerald_manager.rs", "rank": 21, "score": 17695.72591224432 }, { "content": "use std::cmp::Ordering;\n\nuse std::io::{self, Read};\n\nuse std::fs::File;\n\nuse std::path::Path;\n\n\n\nuse sa2_set::{SetFile, Pc};\n\n#[cfg(windows)]\n\nuse process_reader::ProcessHandle;\n\n\n\nuse crate::rng::Rng;\n\nuse crate::vector::Vector;\n\nuse crate::stage_spec::{Emerald, StageSpec};\n\nuse crate::Platform;\n\n\n\nconst NUM_RNG_CALLS: u32 = 138;\n\n\n", "file_path": "src/emerald_manager.rs", "rank": 22, "score": 17695.295939727486 }, { "content": " }\n\n\n\n pub fn gen_pieces_full<P>(&mut self, frame: u32)\n\n where P: Platform,\n\n {\n\n for _ in 0..(frame % 1024) {\n\n self.r.gen_val::<P::Consts>();\n\n }\n\n }\n\n}\n", "file_path": "src/emerald_manager.rs", "rank": 23, "score": 17694.477767303226 }, { "content": " r.gen_val::<P::Consts>();\n\n }\n\n\n\n EmeraldManager {\n\n slot1_pieces: spec.slot1_pieces,\n\n slot2_pieces: spec.slot2_pieces,\n\n slot3_pieces: spec.slot3_pieces,\n\n enemy_pieces: spec.enemy_pieces,\n\n p1: Emerald::default(),\n\n p2: Emerald::default(),\n\n p3: Emerald::default(),\n\n r: r,\n\n }\n\n }\n\n\n\n pub fn gen_pieces<P>(&mut self)\n\n where P: Platform,\n\n {\n\n let num_p1 = self.slot1_pieces.len() + self.enemy_pieces.len();\n\n// println!(\"num_p1: {} + {} = {}\", self.slot1_pieces.len(), self.enemy_pieces.len(), num_p1);\n", "file_path": "src/emerald_manager.rs", "rank": 24, "score": 17694.465573979684 }, { "content": "// }\n\n\n\n potential_p3.sort_by_key(|p| F32Cmp((p.position - self.p2.position).cross(p.position - self.p1.position).magnitude::<P::SquareRoot>()));\n\n\n\n let mut r_copy = self.r;\n\n let num_p3 = self.slot3_pieces.len();\n\n let mut p3_index = (num_p3 as f32 - (((self.r.gen_val::<P::Consts>() as f32 / 32768.0) * num_p3 as f32) / 2.0)) as usize;\n\n\n\n// if frame == 233 {\n\n// for (idx, p) in potential_p3.iter().enumerate() {\n\n// println!(\"sort[{:02X}]: {:04X} ({})\", idx, p.id, (p.position - self.p2.position).cross(p.position - self.p1.position).magnitude());\n\n// }\n\n// let val = r_copy.gen_val();\n\n// println!(\"{} {} {} {}\", val, num_p3, (val as f32 / 32768.0), num_p3 as f32 - ((val as f32 / 32768.0) * num_p3 as f32) / 2.0);\n\n// println!(\"p3_index: {}\", p3_index);\n\n// }\n\n if p3_index >= num_p3 {\n\n p3_index -= 1;\n\n }\n\n self.p3 = *potential_p3[p3_index];\n", "file_path": "src/emerald_manager.rs", "rank": 25, "score": 17694.395097976445 }, { "content": "\n\n// for (idx, p) in potential_p2.iter().enumerate() {\n\n// println!(\"sort[{:02X}]: {:04X} ({})\", idx, p.id, p.position.distance(self.p1.position));\n\n// }\n\n\n\n let num_p2 = self.slot2_pieces.len() + self.enemy_pieces.len();\n\n// println!(\"num_p2: {}\", num_p2);\n\n\n\n let mut p2_index = (num_p2 as f32 - (((self.r.gen_val::<P::Consts>() as f32 / 32768.0) * num_p2 as f32) / 2.0)) as usize;\n\n if p2_index >= num_p2 {\n\n p2_index -= 1;\n\n }\n\n// println!(\"index: {}\", p2_index);\n\n self.p2 = *potential_p2[p2_index];\n\n\n\n // Generate piece 3\n\n let mut potential_p3: Vec<_> = self.slot3_pieces.iter().collect();\n\n\n\n// for (idx, p) in potential_p3.iter().enumerate() {\n\n// println!(\"pre[{:02X}]: {:04X}\", idx, p.id);\n", "file_path": "src/emerald_manager.rs", "rank": 26, "score": 17694.110609843752 }, { "content": " }\n\n\n\n pieces\n\n };\n\n\n\n let p1_list = read_list(em_addr + 0x5C, num_p1);\n\n let p2_list = read_list(em_addr + 0x60, num_p2);\n\n let p3_list = read_list(em_addr + 0x64, num_p3);\n\n let en_list = read_list(em_addr + 0x68, num_en);\n\n\n\n let mut r = Rng::new(0xDEAD0CAB);\n\n for _ in 0..NUM_RNG_CALLS {\n\n r.gen_val::<P::Consts>();\n\n }\n\n\n\n EmeraldManager {\n\n slot1_pieces: p1_list,\n\n slot2_pieces: p2_list,\n\n slot3_pieces: p3_list,\n\n enemy_pieces: en_list,\n", "file_path": "src/emerald_manager.rs", "rank": 27, "score": 17693.176441018226 }, { "content": "\n\n let p1_index = ((self.r.gen_val::<P::Consts>() as f32 / 32768.0) * num_p1 as f32) as usize;\n\n// println!(\"index: {}\", p1_index);\n\n\n\n self.p1 = if p1_index < self.slot1_pieces.len() {\n\n self.slot1_pieces[p1_index]\n\n }\n\n else {\n\n self.enemy_pieces.swap_remove(p1_index - self.slot1_pieces.len())\n\n };\n\n\n\n // Generate piece 2\n\n let mut potential_p2: Vec<_> = self.slot2_pieces.iter().chain(self.enemy_pieces.iter()).collect();\n\n\n\n// for (idx, p) in potential_p2.iter().enumerate() {\n\n// println!(\"pre[{:02X}]: {:04X}\", idx, p.id);\n\n// }\n\n\n\n potential_p2.sort_by_key(|p| F32Cmp(p.position.distance::<P::SquareRoot>(self.p1.position)));\n\n// println!();\n", "file_path": "src/emerald_manager.rs", "rank": 28, "score": 17692.243199469878 }, { "content": " x: object.position.x,\n\n y: object.position.y,\n\n z: object.position.z,\n\n }\n\n }),\n\n 0x0400 | 0x0700 | 0x0800 => slot3_pieces.push(Emerald {\n\n id: object.rotation.x,\n\n position: Vector {\n\n x: object.position.x,\n\n y: object.position.y,\n\n z: object.position.z,\n\n }\n\n }),\n\n _ => {}\n\n }\n\n }\n\n if object.object.0 == 0x0038 ||\n\n object.object.0 == 0x003E ||\n\n object.object.0 == 0x003B\n\n {\n", "file_path": "src/emerald_manager.rs", "rank": 29, "score": 17691.973891414556 }, { "content": "pub struct Rng {\n\n state: Wrapping<u32>,\n\n}\n\n\n\nimpl Rng {\n\n pub fn new(seed: u32) -> Rng {\n\n Rng {\n\n state: Wrapping(seed)\n\n }\n\n }\n\n\n\n pub fn gen_val<R>(&mut self) -> u32\n\n where R: RngConsts,\n\n {\n\n // GC values are:\n\n // Mult: 0x41c64e6d\n\n // Add: 0x00003039\n\n// self.state = self.state * Wrapping(0x000343FD) + Wrapping(0x00269EC3);\n\n self.state = self.state * Wrapping(R::MULT_COEFFICIENT) + Wrapping(R::ADD_COEFFICIENT);\n\n (self.state.0 >> 0x10) & 0x7FFF\n\n }\n\n\n\n pub fn get_state(&self) -> u32 {\n\n self.state.0\n\n }\n\n}\n", "file_path": "src/rng.rs", "rank": 38, "score": 9.817439453219915 }, { "content": "// 8\n\n// 8\n\n// 16\n\n// 16\n\n// 8\n\n// 8\n\n// 8\n\n// 3\n\n// 41\n\nimpl HintLookup {\n\n pub fn from_path<P>(path: P) -> HintLookup\n\n where P: AsRef<Path>,\n\n {\n\n let file = File::open(path).unwrap();\n\n let mut decoder = Decoder::new(file);\n\n let data = decoder.decode_to_vec().unwrap();\n\n let table = Sa2TextTable::from_seek(Cursor::new(data), Language::English).unwrap();\n\n let hints = table.texts\n\n .chunks(3)\n\n .map(|chunk| \n", "file_path": "src/hint_lookup.rs", "rank": 39, "score": 9.403817800172174 }, { "content": " HintLookup {\n\n b_normal: b_normal,\n\n c_normal: c_normal,\n\n b_hidden: b_hidden,\n\n c_hidden: c_hidden,\n\n a_undergnd: a_undergnd,\n\n b_undergnd: b_undergnd,\n\n a_2p_undgnd: a_2p_undgnd,\n\n a_pathmove: a_pathmove,\n\n a_1p_tech: a_1p_tech,\n\n q_final: q_final,\n\n q_inenemy: q_inenemy,\n\n }\n\n }\n\n\n\n pub fn lookup_piece(&self, id: u16) -> &Hint {\n\n let major_id = id >> 8;\n\n let minor_id = id & 0x00FF;\n\n match major_id {\n\n 0x00 => &self.b_normal[minor_id as usize],\n", "file_path": "src/hint_lookup.rs", "rank": 40, "score": 6.985054688816731 }, { "content": "pub mod rng;\n\npub mod emerald_manager;\n\npub mod vector;\n\npub mod stage_spec;\n\npub mod hint_lookup;\n\n\n", "file_path": "src/lib.rs", "rank": 41, "score": 6.867437640862885 }, { "content": "use std::num::Wrapping;\n\n\n", "file_path": "src/rng.rs", "rank": 42, "score": 5.1182209146258115 }, { "content": "use std::io::Cursor;\n\nuse std::fs::File;\n\nuse std::path::Path;\n\n\n\nuse sa2_text::{Sa2TextTable, Sa2Text, TextElement, Language};\n\nuse prs_util::decoder::Decoder;\n\n\n", "file_path": "src/hint_lookup.rs", "rank": 43, "score": 4.870102566975946 }, { "content": " pub h3: String,\n\n}\n\n\n\n#[derive(Clone, Debug)]\n\npub struct HintLookup {\n\n b_normal: Vec<Hint>,\n\n c_normal: Vec<Hint>,\n\n b_hidden: Vec<Hint>,\n\n c_hidden: Vec<Hint>,\n\n a_undergnd: Vec<Hint>,\n\n b_undergnd: Vec<Hint>,\n\n a_2p_undgnd: Vec<Hint>,\n\n a_pathmove: Vec<Hint>,\n\n a_1p_tech: Vec<Hint>,\n\n q_final: Vec<Hint>,\n\n q_inenemy: Vec<Hint>,\n\n}\n\n\n\n// 8\n\n// 24\n", "file_path": "src/hint_lookup.rs", "rank": 44, "score": 3.5165111702688927 }, { "content": " 0x01 => &self.c_normal[minor_id as usize],\n\n 0x02 => &self.b_hidden[minor_id as usize],\n\n 0x03 => &self.c_hidden[minor_id as usize],\n\n 0x04 => &self.a_undergnd[minor_id as usize],\n\n 0x05 => &self.b_undergnd[minor_id as usize],\n\n 0x06 => &self.a_2p_undgnd[minor_id as usize],\n\n 0x07 => &self.a_pathmove[minor_id as usize],\n\n 0x08 => &self.a_1p_tech[minor_id as usize],\n\n 0x09 => &self.q_final[minor_id as usize],\n\n 0x0A => &self.q_inenemy[minor_id as usize],\n\n _ => panic!(\"Bad major id\"),\n\n }\n\n }\n\n}\n", "file_path": "src/hint_lookup.rs", "rank": 45, "score": 3.015528721469474 } ]
Rust
examples/circle_packing.rs
mitchmindtree/nannou_egui
d79939e01e6e170ad1933fc528d2bd36bb03fbe4
use nannou::{color::rgb_u32, rand::thread_rng}; use nannou::{prelude::*, rand::prelude::SliceRandom}; use nannou_egui::{self, egui, EguiBackend}; const WIDTH: f32 = 640.0; const HEIGHT: f32 = 360.0; pub fn main() { nannou::app(model) .update(update) .size(WIDTH as u32, HEIGHT as u32) .run(); } struct Circle { x: f32, y: f32, radius: f32, color: Hsv, } struct Settings { min_radius: f32, max_radius: f32, circle_count: usize, } struct Model { circles: Vec<Circle>, settings: Settings, egui_backend: EguiBackend, } impl Model { pub fn new(egui_backend: EguiBackend) -> Model { Model { circles: Vec::new(), egui_backend, settings: Settings { min_radius: 10.0, max_radius: 100.0, circle_count: 10, }, } } pub fn generate_circles(&mut self) { let colors = [ color_from_hex_rgb(0x264653), color_from_hex_rgb(0x2a9d8f), color_from_hex_rgb(0xe9c46a), color_from_hex_rgb(0xf4a261), color_from_hex_rgb(0xe76f51), ]; let mut circles = Vec::new(); let mut rng = thread_rng(); let mut loops = 0; loop { let x = random_range(-WIDTH / 2.0, WIDTH / 2.0); let y = random_range(-HEIGHT / 2.0, HEIGHT / 2.0); let radius = random_range(self.settings.min_radius, self.settings.max_radius); let color = *colors.choose(&mut rng).unwrap(); let mut circle = Circle { x, y, radius, color, }; loops += 1; if loops > 20000 { break; } if intersects(&circle, &circles) { continue; } let mut prev_radius = circle.radius; while !intersects(&circle, &circles) { prev_radius = circle.radius; circle.radius += 10.0; if circle.radius >= self.settings.max_radius { break; } } circle.radius = prev_radius; circles.push(circle); if circles.len() >= self.settings.circle_count { break; } } self.circles = circles; } } fn intersects(circle: &Circle, circles: &Vec<Circle>) -> bool { for other in circles.iter() { let dist: f32 = ((other.x - circle.x).pow(2) as f32 + (other.y - circle.y).pow(2) as f32).sqrt(); if dist < circle.radius + other.radius { return true; } } false } fn model(app: &App) -> Model { let window_id = app .new_window() .view(view) .msaa_samples(1) .raw_event(raw_window_event) .build() .unwrap(); let window = app.window(window_id).unwrap(); Model::new(EguiBackend::new(&window)) } fn update(_app: &App, model: &mut Model, _update: Update) { let ctx = model.egui_backend.begin_frame(); egui::Window::new("Workshop window") .default_pos(egui::pos2(0.0, 0.0)) .show(&ctx, |ui| { ui.add( egui::Slider::new(&mut model.settings.min_radius, 0.0..=20.0).text("min radius"), ); ui.add( egui::Slider::new(&mut model.settings.max_radius, 0.0..=200.0).text("max radius"), ); ui.add( egui::Slider::new(&mut model.settings.circle_count, 0..=2000).text("circle count"), ); if ui.button("Generate").clicked() { model.generate_circles(); } }); model.egui_backend.end_frame(); } fn raw_window_event(_app: &App, model: &mut Model, event: &nannou::winit::event::WindowEvent) { model.egui_backend.handle_event(event); } fn view(app: &App, model: &Model, frame: Frame) { let draw = app.draw(); draw.background().color(BLACK); for circle in model.circles.iter() { draw.ellipse() .x_y(circle.x, circle.y) .radius(circle.radius) .color(circle.color); } draw.to_frame(app, &frame).unwrap(); model.egui_backend.draw_ui_to_frame(&frame); } pub fn color_from_hex_rgb(color: u32) -> Hsv { let color = rgb_u32(color); rgba( color.red as f32 / 255.0, color.green as f32 / 255.0, color.blue as f32 / 255.0, 1.0, ) .into() }
use nannou::{color::rgb_u32, rand::thread_rng}; use nannou::{prelude::*, rand::prelude::SliceRandom}; use nannou_egui::{self, egui, EguiBackend}; const WIDTH: f32 = 640.0; const HEIGHT: f32 = 360.0; pub fn main() { nannou::app(model) .update(update) .size(WIDTH as u32, HEIGHT as u32) .run(); } struct Circle { x: f32, y: f32, radius: f32, color: Hsv, } struct Settings { min_radius: f32, max_radius: f32, circle_count: usize, } struct Model { circles: Vec<Circle>, settings: Settings, egui_backend: EguiBackend, } impl Model { pub fn new(egui_backend: EguiBackend) -> Model { Model { circles: Vec::new(), egui_backend, settings: Settings { min_radius: 10.0, max_radius: 100.0, circle_count: 10, }, } } pub fn generate_circles(&mut self) { let colors = [ color_from_hex_rgb(0x264653), color_from_hex_rgb(0x2a9d8f), color_from_hex_rgb(0xe9c46a), color_from_hex_rgb(0xf4a261), color_from_hex_rgb(0xe76f51), ]; let mut circles = Vec::new(); let mut rng = thread_rng(); let mut loops = 0; loop { let x = random_range(-WIDTH / 2.0, WIDTH / 2.0); let y = random_range(-HEIGHT / 2.0, HEIGHT / 2.0); let radius = random_range(self.settings.min_radius, self.settings.max_radius); let color = *colors.choose(&mut rng).unwrap(); let mut circle = Circle { x, y, radius, color, }; loops += 1; if loops > 20000 { break; } if intersects(&circle, &circles) { continue; } let mut prev_radius = circle.radius; while !intersects(&circle, &circles) { prev_radius = circle.radius; circle.radius += 10.0; if circle.radius >= self.settings.max_radius { break; } } circle.radius = prev_radius; circles.push(circle); if circles.len() >= self.settings.circle_count { break; } } self.circles = circles; } } fn intersects(circle: &Circle, circles: &Vec<Circle>) -> bool { for other in circles.iter() { let dist: f32 = ((other.x - circle.x).pow(2) as f32 + (other.y - circle.y).pow(2) as f32).sqrt(); if dist < circle.radius + other.radius { return true; } } false } fn model(app: &App) -> Model { let window_id = app .new_window() .view(view) .msaa_samples(1) .raw_event(raw_window_event) .build() .unwrap(); let window = app.window(window_id).unwrap(); Model::new(EguiBackend::new(&window)) } fn update(_app: &App, model: &mut Model, _update: Update) { let ctx = model.egui_backend.begin_frame(); egui::Window::new("Workshop window") .default_pos(egui::pos2(0.0, 0.0)) .show(&ctx, |ui| { ui.add( egui::Slider::new(&mut model.settings.min_radius, 0.0..=20.0).text("min radius"), ); ui.add( egui::Slider::new(&mut model.settings.max_radius, 0.0..=200.0).text("max radius"), ); ui.add( egui::Slider::new(&mut model.settings.circle_count, 0..=2000).text("circle count"), ); if ui.button("Generate").clicked() { model.generate_circles(); } }); model.egui_backend.end_frame(); } fn raw_window_event(_app: &App, model: &mut Model, event: &nannou::winit::event::WindowEvent) { model.egui_backend.handle_event(event); } fn view(app: &App, model: &Model, frame: Frame) { let draw = app.draw(); draw.background().color(BLACK); for circle in model.circles.iter() { draw.ellipse() .x_y(circle.x, circle.y) .radius(circle.radius) .color(circle.color); } draw.to_frame(app, &frame).unwrap(); model.egui_backend.draw_ui_to_frame(&frame); } pub fn color_from_hex_rgb(color: u32) -> Hsv { let color = rgb_u32(color);
.into() }
rgba( color.red as f32 / 255.0, color.green as f32 / 255.0, color.blue as f32 / 255.0, 1.0, )
call_expression
[ { "content": "pub fn edit_color(ui: &mut egui::Ui, color: &mut nannou::color::Hsv) {\n\n let mut egui_hsv = egui::color::Hsva::new(\n\n color.hue.to_positive_radians() as f32 / (std::f32::consts::PI * 2.0),\n\n color.saturation,\n\n color.value,\n\n 1.0,\n\n );\n\n\n\n if color_picker::color_edit_button_hsva(ui, &mut egui_hsv, color_picker::Alpha::Opaque)\n\n .changed()\n\n {\n\n *color = nannou::color::hsv(egui_hsv.h, egui_hsv.s, egui_hsv.v);\n\n }\n\n}\n", "file_path": "src/lib.rs", "rank": 0, "score": 193904.23999091773 }, { "content": "fn raw_window_event(_app: &App, model: &mut Model, event: &nannou::winit::event::WindowEvent) {\n\n model.egui_backend.handle_event(event);\n\n}\n\n\n", "file_path": "examples/tune_color.rs", "rank": 1, "score": 162107.5402461057 }, { "content": "fn update(_app: &App, model: &mut Model, update: Update) {\n\n model\n\n .egui_backend\n\n .update_time(update.since_start.as_secs_f64());\n\n let ctx = model.egui_backend.begin_frame();\n\n egui::Window::new(\"EGUI window\")\n\n .default_size(egui::vec2(0.0, 200.0))\n\n .default_pos(egui::pos2(0.0, 0.0))\n\n .show(&ctx, |ui| {\n\n ui.separator();\n\n ui.label(\"Tune parameters with ease\");\n\n ui.add(egui::Slider::new(&mut model.radius, 10.0..=100.0).text(\"Radius\"));\n\n nannou_egui::edit_color(ui, &mut model.color);\n\n });\n\n model.egui_backend.end_frame();\n\n}\n\n\n", "file_path": "examples/tune_color.rs", "rank": 4, "score": 147351.58410671176 }, { "content": "// Draw the state of your `Model` into the given `Frame` here.\n\nfn view(app: &App, model: &Model, frame: Frame) {\n\n let draw = app.draw();\n\n\n\n frame.clear(BLACK);\n\n\n\n draw.ellipse()\n\n .x_y(100.0, 100.0)\n\n .radius(model.radius)\n\n .color(model.color);\n\n\n\n draw.to_frame(app, &frame).unwrap();\n\n\n\n // Do this as the last operation on your frame.\n\n model.egui_backend.draw_ui_to_frame(&frame);\n\n}\n", "file_path": "examples/tune_color.rs", "rank": 6, "score": 145256.65690967854 }, { "content": "fn model(app: &App) -> Model {\n\n // Create a new window! Store the ID so we can refer to it later.\n\n let window_id = app\n\n .new_window()\n\n .title(\"Nannou + Egui\")\n\n .msaa_samples(1)\n\n .raw_event(raw_window_event) // This is where we forward all raw events for egui to process them\n\n .view(view) // The function that will be called for presenting graphics to a frame.\n\n .build()\n\n .unwrap();\n\n\n\n let window = app.window(window_id).unwrap();\n\n\n\n Model {\n\n egui_backend: nannou_egui::EguiBackend::new(&window),\n\n radius: 40.0,\n\n color: hsv(10.0, 0.5, 1.0),\n\n }\n\n}\n\n\n", "file_path": "examples/tune_color.rs", "rank": 8, "score": 118616.46632227232 }, { "content": "pub fn main() {\n\n nannou::app(model)\n\n .update(update)\n\n .size(WIDTH as u32, HEIGHT as u32)\n\n .run();\n\n}\n\n\n", "file_path": "examples/tune_color.rs", "rank": 10, "score": 116707.30497921712 }, { "content": "struct Model {\n\n egui_backend: nannou_egui::EguiBackend,\n\n radius: f32,\n\n color: Hsv,\n\n}\n\n\n", "file_path": "examples/tune_color.rs", "rank": 12, "score": 89777.63949002835 }, { "content": "#[inline]\n\nfn winit_to_egui_modifiers(modifiers: winit::event::ModifiersState) -> egui::Modifiers {\n\n egui::Modifiers {\n\n alt: modifiers.alt(),\n\n ctrl: modifiers.ctrl(),\n\n shift: modifiers.shift(),\n\n #[cfg(target_os = \"macos\")]\n\n mac_cmd: modifiers.logo(),\n\n #[cfg(target_os = \"macos\")]\n\n command: modifiers.logo(),\n\n #[cfg(not(target_os = \"macos\"))]\n\n mac_cmd: false,\n\n #[cfg(not(target_os = \"macos\"))]\n\n command: modifiers.ctrl(),\n\n }\n\n}\n\n\n", "file_path": "src/lib.rs", "rank": 14, "score": 79583.27992849119 }, { "content": "#[inline]\n\nfn winit_to_egui_key_code(key: VirtualKeyCode) -> Option<egui::Key> {\n\n use egui::Key;\n\n\n\n Some(match key {\n\n VirtualKeyCode::Escape => Key::Escape,\n\n VirtualKeyCode::Insert => Key::Insert,\n\n VirtualKeyCode::Home => Key::Home,\n\n VirtualKeyCode::Delete => Key::Delete,\n\n VirtualKeyCode::End => Key::End,\n\n VirtualKeyCode::PageDown => Key::PageDown,\n\n VirtualKeyCode::PageUp => Key::PageUp,\n\n VirtualKeyCode::Left => Key::ArrowLeft,\n\n VirtualKeyCode::Up => Key::ArrowUp,\n\n VirtualKeyCode::Right => Key::ArrowRight,\n\n VirtualKeyCode::Down => Key::ArrowDown,\n\n VirtualKeyCode::Back => Key::Backspace,\n\n VirtualKeyCode::Return => Key::Enter,\n\n VirtualKeyCode::Tab => Key::Tab,\n\n VirtualKeyCode::Space => Key::Space,\n\n\n", "file_path": "src/lib.rs", "rank": 18, "score": 53336.734503791486 }, { "content": "use egui::color_picker::Alpha;\n\nuse nannou::prelude::*;\n\nuse nannou_egui::{self, color_picker, egui};\n\n\n\nconst WIDTH: f32 = 640.0;\n\nconst HEIGHT: f32 = 360.0;\n\n\n", "file_path": "examples/tune_color.rs", "rank": 19, "score": 19055.702480260014 }, { "content": "# nannou_egui\n\n[![Latest version](https://img.shields.io/crates/v/nannou_egui.svg)](https://crates.io/crates/nannou_egui)\n\n\n\n\n\nThis is my [egui] integration for nannou. The purpose of this is to allow you to tune values for your generative art creations without requiring a compilation cycle.\n\n\n\nThere are a bunch of rough edges as this is really early in dev (and I am not familiar with webgpu).\n\nMost notably, right now you need to have MSAA = 1 in your window settings and scaling doesn't work at the moment. \n\nFor inspiration on how to expose UI widgets, please check the [egui] repo as it has a lot of examples. You have sliders, color pickers, checkboxes, dropdownlists and many more widgets available.\n\n\n\nFor information on how to integrate it to your nannou creations, there's an [example] in this repo.\n\n\n\nTo run the circle packing example: `cargo run --example circle_packing`: \n\n\n\n![](https://github.com/AlexEne/nannou_egui/blob/main/media/circle_packing.gif)\n\n\n\n\n\nTo run the color tune example: `cargo run --example tune_color`:\n\n\n\n![](https://github.com/AlexEne/nannou_egui/blob/main/media/tune_egui.gif)\n\n\n\n## Todo\n\n- [ ] Fixing the current MSAA issue and \n\n- [ ] Easier integration for storing tunable parameters to disk.\n\n- [ ] Shortcuts for hiding the UI\n\n\n\n[egui]: https://github.com/emilk/egui\n\n[example]: https://github.com/AlexEne/nannou_egui/tree/main/nannou_egui_example\n", "file_path": "README.md", "rank": 24, "score": 13046.59304395684 }, { "content": " height: u32,\n\n scale_factor: f64,\n\n context: egui::CtxRef,\n\n paint_jobs: Vec<ClippedMesh>,\n\n}\n\n\n\nimpl EguiBackend {\n\n pub fn new(window: &nannou::window::Window) -> EguiBackend {\n\n let scale_factor = window.scale_factor() as f64;\n\n let width = window.inner_size_pixels().0;\n\n let height = window.inner_size_pixels().1;\n\n\n\n let raw_input = egui::RawInput {\n\n pixels_per_point: Some(scale_factor as f32),\n\n screen_rect: Some(egui::Rect::from_min_size(\n\n Default::default(),\n\n egui::vec2(width as f32, height as f32) / scale_factor as f32,\n\n )),\n\n ..Default::default()\n\n };\n", "file_path": "src/lib.rs", "rank": 25, "score": 11.031294351205624 }, { "content": "use std::{borrow::BorrowMut, cell::RefCell};\n\n\n\npub use egui;\n\npub use egui::color_picker;\n\npub use egui_wgpu_backend;\n\n\n\nuse egui::{pos2, ClippedMesh, CtxRef};\n\nuse egui_wgpu_backend::ScreenDescriptor;\n\nuse winit::event::VirtualKeyCode;\n\nuse winit::event::WindowEvent::*;\n\n\n\nconst OUTPUT_FORMAT: egui_wgpu_backend::wgpu::TextureFormat =\n\n egui_wgpu_backend::wgpu::TextureFormat::Rgba16Float;\n\n\n\npub struct EguiBackend {\n\n render_pass: RefCell<egui_wgpu_backend::RenderPass>,\n\n raw_input: egui::RawInput,\n\n modifier_state: winit::event::ModifiersState,\n\n pointer_pos: egui::Pos2,\n\n width: u32,\n", "file_path": "src/lib.rs", "rank": 26, "score": 10.961425519418837 }, { "content": " pub fn update_time(&mut self, elapsed_seconds: f64) {\n\n self.raw_input.time = Some(elapsed_seconds);\n\n }\n\n\n\n pub fn draw_ui_to_frame(&self, frame: &nannou::Frame) {\n\n let device_queue_pair = frame.device_queue_pair();\n\n let device = device_queue_pair.device();\n\n let queue = device_queue_pair.queue();\n\n let mut render_pass = self.render_pass.borrow_mut();\n\n let paint_jobs = &self.paint_jobs;\n\n let mut encoder = frame.command_encoder();\n\n\n\n let screen_descriptor = ScreenDescriptor {\n\n physical_width: self.width,\n\n physical_height: self.height,\n\n scale_factor: self.scale_factor as f32,\n\n };\n\n render_pass.update_texture(device, queue, &self.context.texture());\n\n render_pass.update_user_textures(&device, &queue);\n\n render_pass.update_buffers(device, queue, &paint_jobs, &screen_descriptor);\n", "file_path": "src/lib.rs", "rank": 27, "score": 10.098221596127601 }, { "content": "\n\n pub fn handle_event(&mut self, event: &winit::event::WindowEvent) {\n\n let mut raw_input = &mut self.raw_input;\n\n match event {\n\n Resized(physical_size) => {\n\n self.width = physical_size.width;\n\n self.height = physical_size.height;\n\n raw_input.screen_rect = Some(egui::Rect::from_min_size(\n\n Default::default(),\n\n egui::vec2(physical_size.width as f32, physical_size.height as f32)\n\n / self.scale_factor as f32,\n\n ));\n\n }\n\n ScaleFactorChanged {\n\n scale_factor,\n\n new_inner_size,\n\n } => {\n\n self.scale_factor = *scale_factor;\n\n raw_input.pixels_per_point = Some(*scale_factor as f32);\n\n raw_input.screen_rect = Some(egui::Rect::from_min_size(\n", "file_path": "src/lib.rs", "rank": 28, "score": 10.031518683783688 }, { "content": " ReceivedCharacter(ch) => {\n\n if ch.is_alphanumeric() && !self.modifier_state.ctrl() && !self.modifier_state.logo()\n\n {\n\n raw_input.events.push(egui::Event::Text(ch.to_string()));\n\n }\n\n }\n\n _ => {}\n\n }\n\n }\n\n\n\n pub fn begin_frame(&mut self) -> CtxRef {\n\n self.context.begin_frame(self.raw_input.borrow_mut().take());\n\n self.context.clone()\n\n }\n\n\n\n pub fn end_frame(&mut self) {\n\n let (_, paint_cmds) = self.context.end_frame();\n\n self.paint_jobs = self.context.tessellate(paint_cmds);\n\n }\n\n\n", "file_path": "src/lib.rs", "rank": 29, "score": 8.312324656424327 }, { "content": "\n\n let context = egui::CtxRef::default();\n\n context.set_fonts(egui::FontDefinitions::default());\n\n context.set_style(egui::Style::default());\n\n\n\n EguiBackend {\n\n render_pass: RefCell::new(egui_wgpu_backend::RenderPass::new(\n\n window.swap_chain_device(),\n\n OUTPUT_FORMAT,\n\n )),\n\n context,\n\n modifier_state: winit::event::ModifiersState::empty(),\n\n width,\n\n height,\n\n scale_factor,\n\n raw_input,\n\n pointer_pos: Default::default(),\n\n paint_jobs: Vec::new(),\n\n }\n\n }\n", "file_path": "src/lib.rs", "rank": 30, "score": 7.231889582878901 }, { "content": " Default::default(),\n\n egui::vec2(new_inner_size.width as f32, new_inner_size.height as f32)\n\n / self.scale_factor as f32,\n\n ));\n\n }\n\n MouseInput { state, button, .. } => {\n\n if let winit::event::MouseButton::Other(..) = button {\n\n } else {\n\n raw_input.events.push(egui::Event::PointerButton {\n\n pos: self.pointer_pos,\n\n button: match button {\n\n winit::event::MouseButton::Left => egui::PointerButton::Primary,\n\n winit::event::MouseButton::Right => egui::PointerButton::Secondary,\n\n winit::event::MouseButton::Middle => egui::PointerButton::Middle,\n\n winit::event::MouseButton::Other(_) => unreachable!(),\n\n },\n\n pressed: *state == winit::event::ElementState::Pressed,\n\n modifiers: Default::default(),\n\n });\n\n }\n", "file_path": "src/lib.rs", "rank": 31, "score": 6.096590141490321 }, { "content": " }\n\n MouseWheel { delta, .. } => {\n\n match delta {\n\n winit::event::MouseScrollDelta::LineDelta(x, y) => {\n\n let line_height = 24.0;\n\n raw_input.scroll_delta = egui::vec2(*x, *y) * line_height;\n\n }\n\n winit::event::MouseScrollDelta::PixelDelta(delta) => {\n\n // Actually point delta\n\n raw_input.scroll_delta = egui::vec2(delta.x as f32, delta.y as f32);\n\n }\n\n }\n\n }\n\n CursorMoved { position, .. } => {\n\n self.pointer_pos = pos2(\n\n position.x as f32 / self.scale_factor as f32,\n\n position.y as f32 / self.scale_factor as f32,\n\n );\n\n raw_input\n\n .events\n", "file_path": "src/lib.rs", "rank": 32, "score": 5.764378749428255 }, { "content": "\n\n // Record all render passes.\n\n render_pass.execute(\n\n &mut encoder,\n\n frame.texture_view(),\n\n &paint_jobs,\n\n &screen_descriptor,\n\n None,\n\n );\n\n }\n\n}\n\n\n\n/// Translates winit to egui keycodes.\n\n#[inline]\n", "file_path": "src/lib.rs", "rank": 33, "score": 3.9818209436296153 }, { "content": " .push(egui::Event::PointerMoved(self.pointer_pos));\n\n }\n\n CursorLeft { .. } => {\n\n raw_input.events.push(egui::Event::PointerGone);\n\n }\n\n ModifiersChanged(input) => self.modifier_state = *input,\n\n KeyboardInput { input, .. } => {\n\n if let Some(virtual_keycode) = input.virtual_keycode {\n\n if let Some(key) = winit_to_egui_key_code(virtual_keycode) {\n\n // TODO figure out why if I enable this the characters get ignored\n\n\n\n raw_input.events.push(egui::Event::Key {\n\n key,\n\n pressed: input.state == winit::event::ElementState::Pressed,\n\n // modifiers: winit_to_egui_modifiers(self.modifier_state),\n\n modifiers: winit_to_egui_modifiers(self.modifier_state),\n\n });\n\n }\n\n }\n\n }\n", "file_path": "src/lib.rs", "rank": 34, "score": 3.4410477293129893 }, { "content": " VirtualKeyCode::A => Key::A,\n\n VirtualKeyCode::K => Key::K,\n\n VirtualKeyCode::U => Key::U,\n\n VirtualKeyCode::W => Key::W,\n\n VirtualKeyCode::Z => Key::Z,\n\n\n\n _ => {\n\n return None;\n\n }\n\n })\n\n}\n\n\n\n/// Translates winit to egui modifier keys.\n", "file_path": "src/lib.rs", "rank": 35, "score": 0.928440050311629 } ]
Rust
src/devices/tools/banjo/src/fidl.rs
opensource-assist/fuschia
66646c55b3d0b36aae90a4b6706b87f1a6261935
use { lazy_static::lazy_static, regex::Regex, serde::{Deserialize, Deserializer}, serde_derive::{Deserialize, Serialize}, std::collections::BTreeMap, }; lazy_static! { pub static ref IDENTIFIER_RE: Regex = Regex::new(r#"^[A-Za-z]([_A-Za-z0-9]*[A-Za-z0-9])?$"#).unwrap(); pub static ref COMPOUND_IDENTIFIER_RE: Regex = Regex::new(r#"([_A-Za-z][_A-Za-z0-9]*-)*[_A-Za-z][_A-Za-z0-9]*/[_A-Za-z][_A-Za-z0-9]*"#) .unwrap(); pub static ref LIBRARY_IDENTIFIER_RE: Regex = Regex::new(r#"^[a-z][a-z0-9]*(\.[a-z][a-z0-9]*)*$"#).unwrap(); pub static ref VERSION_RE: Regex = Regex::new(r#"^[0-9]+\.[0-9]+\.[0-9]+$"#).unwrap(); } #[derive(Clone, Debug, PartialEq, Eq, Default, Serialize, Deserialize)] #[serde(transparent)] pub struct Ordinal(#[serde(deserialize_with = "validate_ordinal")] pub u32); fn validate_ordinal<'de, D>(deserializer: D) -> Result<u32, D::Error> where D: Deserializer<'de>, { let ordinal = u32::deserialize(deserializer)?; if ordinal == 0 { return Err(serde::de::Error::custom("Ordinal must not be equal to 0")); } Ok(ordinal) } #[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)] #[repr(transparent)] pub struct Count(pub u32); #[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)] #[serde(transparent)] pub struct Identifier(#[serde(deserialize_with = "validate_identifier")] pub String); fn validate_identifier<'de, D>(deserializer: D) -> Result<String, D::Error> where D: Deserializer<'de>, { let id = String::deserialize(deserializer)?; if !IDENTIFIER_RE.is_match(&id) { return Err(serde::de::Error::custom(format!("Invalid identifier: {}", id))); } Ok(id) } #[derive(Clone, Debug, PartialEq, Eq, PartialOrd, Ord, Serialize, Deserialize)] #[serde(transparent)] pub struct CompoundIdentifier( #[serde(deserialize_with = "validate_compound_identifier")] pub String, ); fn validate_compound_identifier<'de, D>(deserializer: D) -> Result<String, D::Error> where D: Deserializer<'de>, { let id = String::deserialize(deserializer)?; if !COMPOUND_IDENTIFIER_RE.is_match(&id) { return Err(serde::de::Error::custom(format!("Invalid compound identifier: {}", id))); } Ok(id) } #[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)] #[serde(transparent)] pub struct LibraryIdentifier(#[serde(deserialize_with = "validate_library_identifier")] pub String); fn validate_library_identifier<'de, D>(deserializer: D) -> Result<String, D::Error> where D: Deserializer<'de>, { let id = String::deserialize(deserializer)?; if !LIBRARY_IDENTIFIER_RE.is_match(&id) { return Err(serde::de::Error::custom(format!("Invalid library identifier: {}", id))); } Ok(id) } #[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)] #[serde(transparent)] pub struct Version(#[serde(deserialize_with = "validate_version")] pub String); fn validate_version<'de, D>(deserializer: D) -> Result<String, D::Error> where D: Deserializer<'de>, { let version = String::deserialize(deserializer)?; if !VERSION_RE.is_match(&version) { return Err(serde::de::Error::custom(format!("Invalid version: {}", version))); } Ok(version) } #[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)] #[serde(rename_all = "lowercase")] pub enum Declaration { Const, Enum, Interface, Struct, Table, Union, XUnion, } #[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)] #[serde(transparent)] pub struct DeclarationsMap(pub BTreeMap<CompoundIdentifier, Declaration>); #[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)] pub struct Library { pub name: LibraryIdentifier, pub declarations: DeclarationsMap, } #[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)] pub struct Location { pub filename: String, pub line: u32, pub column: u32, } #[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)] #[serde(rename_all = "lowercase")] pub enum HandleSubtype { Handle, Process, Thread, Vmo, Channel, Event, Port, Interrupt, Debuglog, Socket, Resource, Eventpair, Job, Vmar, Fifo, Guest, Timer, Bti, Profile, } #[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)] #[serde(rename_all = "lowercase")] pub enum IntegerType { Int8, Int16, Int32, Int64, Uint8, Uint16, Uint32, Uint64, } #[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)] #[serde(rename_all = "lowercase")] pub enum PrimitiveSubtype { Bool, Float32, Float64, Int8, Int16, Int32, Int64, Uint8, Uint16, Uint32, Uint64, } #[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)] #[serde(tag = "kind", rename_all = "lowercase")] pub enum Type { Array { element_type: Box<Type>, element_count: Count, }, Vector { element_type: Box<Type>, maybe_element_count: Option<Count>, nullable: bool, }, #[serde(rename = "string")] Str { maybe_element_count: Option<Count>, nullable: bool, }, Handle { subtype: HandleSubtype, nullable: bool, }, Request { subtype: CompoundIdentifier, nullable: bool, }, Primitive { subtype: PrimitiveSubtype, }, Identifier { identifier: CompoundIdentifier, nullable: bool, }, } #[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)] #[serde(tag = "kind", rename_all = "lowercase")] pub enum Literal { #[serde(rename = "string")] Str { value: String, }, Numeric { value: String, }, True, False, #[serde(rename = "default")] _Default, } #[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)] #[serde(tag = "kind", rename_all = "lowercase")] pub enum Constant { Identifier { identifier: CompoundIdentifier }, Literal { literal: Literal }, } #[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)] pub struct Const { pub name: CompoundIdentifier, pub location: Option<Location>, #[serde(rename = "type")] pub _type: Type, pub value: Constant, } #[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)] pub struct EnumMember { pub name: Identifier, pub location: Option<Location>, pub maybe_attributes: Option<Vec<Attribute>>, pub value: Constant, } #[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)] pub struct Enum { pub maybe_attributes: Option<Vec<Attribute>>, pub name: CompoundIdentifier, pub location: Option<Location>, #[serde(rename = "type")] pub _type: IntegerType, pub members: Vec<EnumMember>, } #[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)] pub struct Attribute { pub name: String, pub value: String, } #[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)] pub struct MethodParameter { #[serde(rename = "type")] pub _type: Type, pub name: Identifier, pub location: Option<Location>, pub size: Count, pub max_out_of_line: Count, pub alignment: Count, pub offset: Count, } #[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)] pub struct Method { pub maybe_attributes: Option<Vec<Attribute>>, pub ordinal: Ordinal, pub generated_ordinal: Ordinal, pub name: Identifier, pub location: Option<Location>, pub has_request: bool, pub maybe_request: Option<Vec<MethodParameter>>, pub maybe_request_size: Option<Count>, pub maybe_request_alignment: Option<Count>, pub has_response: bool, pub maybe_response: Option<Vec<MethodParameter>>, pub maybe_response_size: Option<Count>, pub maybe_response_alignment: Option<Count>, } #[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)] pub struct Interface { pub maybe_attributes: Option<Vec<Attribute>>, pub name: CompoundIdentifier, pub location: Option<Location>, pub methods: Vec<Method>, } #[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)] pub struct StructMember { #[serde(rename = "type")] pub _type: Type, pub name: Identifier, pub location: Option<Location>, pub size: Count, pub max_out_of_line: Count, pub alignment: Count, pub offset: Count, pub maybe_attributes: Option<Vec<Attribute>>, pub maybe_default_value: Option<Constant>, } #[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)] pub struct Struct { pub max_handles: Option<Count>, pub maybe_attributes: Option<Vec<Attribute>>, pub name: CompoundIdentifier, pub location: Option<Location>, pub anonymous: Option<bool>, pub members: Vec<StructMember>, pub size: Count, pub max_out_of_line: Count, } #[derive(Clone, Debug, PartialEq, Eq, Default, Serialize, Deserialize)] pub struct TableMember { pub ordinal: Ordinal, pub reserved: bool, #[serde(rename = "type")] pub _type: Option<Type>, pub name: Option<Identifier>, pub location: Option<Location>, pub size: Option<Count>, pub max_out_of_line: Option<Count>, pub alignment: Option<Count>, pub offset: Option<Count>, pub maybe_default_value: Option<Constant>, } #[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)] pub struct Table { pub max_handles: Option<Count>, pub maybe_attributes: Option<Vec<Attribute>>, pub name: CompoundIdentifier, pub location: Option<Location>, pub members: Vec<TableMember>, pub size: Count, pub max_out_of_line: Count, } #[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)] pub struct UnionMember { #[serde(rename = "type")] pub _type: Type, pub name: Identifier, pub location: Option<Location>, pub size: Count, pub max_out_of_line: Count, pub alignment: Count, pub offset: Count, pub maybe_attributes: Option<Vec<Attribute>>, } #[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)] pub struct Union { pub max_handles: Option<Count>, pub maybe_attributes: Option<Vec<Attribute>>, pub name: CompoundIdentifier, pub location: Option<Location>, pub members: Vec<UnionMember>, pub size: Count, pub max_out_of_line: Count, pub alignment: Count, } #[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)] pub struct XUnionMember { pub ordinal: Ordinal, #[serde(rename = "type")] pub _type: Type, pub name: Identifier, pub location: Option<Location>, pub size: Count, pub max_out_of_line: Count, pub alignment: Count, pub offset: Count, pub maybe_attributes: Option<Vec<Attribute>>, } #[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)] pub struct XUnion { pub max_handles: Option<Count>, pub maybe_attributes: Option<Vec<Attribute>>, pub name: CompoundIdentifier, pub location: Option<Location>, pub members: Vec<XUnionMember>, pub size: Count, pub max_out_of_line: Count, pub alignment: Count, } #[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)] pub struct Ir { pub version: Version, pub name: LibraryIdentifier, pub library_dependencies: Vec<Library>, pub const_declarations: Vec<Const>, pub enum_declarations: Vec<Enum>, pub interface_declarations: Vec<Interface>, pub struct_declarations: Vec<Struct>, pub table_declarations: Vec<Table>, pub union_declarations: Vec<Union>, pub xunion_declarations: Vec<XUnion>, pub declaration_order: Vec<CompoundIdentifier>, pub declarations: DeclarationsMap, }
use { lazy_static::lazy_static, regex::Regex, serde::{Deserialize, Deserializer}, serde_derive::{Deserialize, Serialize}, std::collections::BTreeMap, }; lazy_static! { pub static ref IDENTIFIER_RE: Regex = Regex::new(r#"^[A-Za-z]([_A-Za-z0-9]*[A-Za-z0-9])?$"#).unwrap(); pub static ref COMPOUND_IDENTIFIER_RE: Regex = Regex::new(r#"([_A-Za-z][_A-Za-z0-9]*-)*[_A-Za-z][_A-Za-z0-9]*/[_A-Za-z][_A-Za-z0-9]*"#) .unwrap(); pub static ref LIBRARY_IDENTIFIER_RE: Regex = Regex::new(r#"^[a-z][a-z0-9]*(\.[a-z][a-z0-9]*)*$"#).unwrap(); pub static ref VERSION_RE: Regex = Regex::new(r#"^[0-9]+\.[0-9]+\.[0-9]+$"#).unwrap(); } #[derive(Clone, Debug, PartialEq, Eq, Default, Serialize, Deserialize)] #[serde(transparent)] pub struct Ordinal(#[serde(deserialize_with = "validate_ordinal")] pub u32); fn validate_ordinal<'de, D>(deserializer: D) -> Result<u32, D::Error> where D: Deserializer<'de>, { let ordinal = u32::deserialize(deserializer)?; if ordinal == 0 { return Err(serde::de::Error::custom("Ordinal must not be equal to 0")); } Ok(ordinal) } #[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)] #[repr(transparent)] pub struct Count(pub u32); #[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)] #[serde(transparent)] pub struct Identifier(#[serde(deserialize_with = "validate_identifier")] pub String); fn validate_identifier<'de, D>(deserializer: D) -> Result<String, D::Error> where D: Deserializer<'de>, { let id = String::deserialize(deserializer)?; if !IDENTIFIER_RE.is_match(&id) { return Err(serde::de::Error::custom(format!("Invalid identifier: {}", id))); } Ok(id) } #[derive(Clone, Debug, PartialEq, Eq, PartialOrd, Ord, Serialize, Deserialize)] #[serde(transparent)] pub struct CompoundIdentifier( #[serde(deserialize_with = "validate_compound_identifier")] pub String, ); fn validate_compound_identifier<'de, D>(deserializer: D) -> Result<String, D::Error> where D: Deserializer<'de>, { let id = String::deserialize(deserializer)?; if !COMPOUND_IDENTIFIER_RE.is_match(&id) { return Err(serde::de::Error::custom(format!("Invalid compound identifier: {}", id))); } Ok(id) } #[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)] #[serde(transparent)] pub struct LibraryIdentifier(#[serde(deserialize_with = "validate_library_identifier")] pub String);
#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)] #[serde(transparent)] pub struct Version(#[serde(deserialize_with = "validate_version")] pub String); fn validate_version<'de, D>(deserializer: D) -> Result<String, D::Error> where D: Deserializer<'de>, { let version = String::deserialize(deserializer)?; if !VERSION_RE.is_match(&version) { return Err(serde::de::Error::custom(format!("Invalid version: {}", version))); } Ok(version) } #[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)] #[serde(rename_all = "lowercase")] pub enum Declaration { Const, Enum, Interface, Struct, Table, Union, XUnion, } #[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)] #[serde(transparent)] pub struct DeclarationsMap(pub BTreeMap<CompoundIdentifier, Declaration>); #[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)] pub struct Library { pub name: LibraryIdentifier, pub declarations: DeclarationsMap, } #[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)] pub struct Location { pub filename: String, pub line: u32, pub column: u32, } #[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)] #[serde(rename_all = "lowercase")] pub enum HandleSubtype { Handle, Process, Thread, Vmo, Channel, Event, Port, Interrupt, Debuglog, Socket, Resource, Eventpair, Job, Vmar, Fifo, Guest, Timer, Bti, Profile, } #[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)] #[serde(rename_all = "lowercase")] pub enum IntegerType { Int8, Int16, Int32, Int64, Uint8, Uint16, Uint32, Uint64, } #[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)] #[serde(rename_all = "lowercase")] pub enum PrimitiveSubtype { Bool, Float32, Float64, Int8, Int16, Int32, Int64, Uint8, Uint16, Uint32, Uint64, } #[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)] #[serde(tag = "kind", rename_all = "lowercase")] pub enum Type { Array { element_type: Box<Type>, element_count: Count, }, Vector { element_type: Box<Type>, maybe_element_count: Option<Count>, nullable: bool, }, #[serde(rename = "string")] Str { maybe_element_count: Option<Count>, nullable: bool, }, Handle { subtype: HandleSubtype, nullable: bool, }, Request { subtype: CompoundIdentifier, nullable: bool, }, Primitive { subtype: PrimitiveSubtype, }, Identifier { identifier: CompoundIdentifier, nullable: bool, }, } #[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)] #[serde(tag = "kind", rename_all = "lowercase")] pub enum Literal { #[serde(rename = "string")] Str { value: String, }, Numeric { value: String, }, True, False, #[serde(rename = "default")] _Default, } #[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)] #[serde(tag = "kind", rename_all = "lowercase")] pub enum Constant { Identifier { identifier: CompoundIdentifier }, Literal { literal: Literal }, } #[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)] pub struct Const { pub name: CompoundIdentifier, pub location: Option<Location>, #[serde(rename = "type")] pub _type: Type, pub value: Constant, } #[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)] pub struct EnumMember { pub name: Identifier, pub location: Option<Location>, pub maybe_attributes: Option<Vec<Attribute>>, pub value: Constant, } #[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)] pub struct Enum { pub maybe_attributes: Option<Vec<Attribute>>, pub name: CompoundIdentifier, pub location: Option<Location>, #[serde(rename = "type")] pub _type: IntegerType, pub members: Vec<EnumMember>, } #[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)] pub struct Attribute { pub name: String, pub value: String, } #[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)] pub struct MethodParameter { #[serde(rename = "type")] pub _type: Type, pub name: Identifier, pub location: Option<Location>, pub size: Count, pub max_out_of_line: Count, pub alignment: Count, pub offset: Count, } #[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)] pub struct Method { pub maybe_attributes: Option<Vec<Attribute>>, pub ordinal: Ordinal, pub generated_ordinal: Ordinal, pub name: Identifier, pub location: Option<Location>, pub has_request: bool, pub maybe_request: Option<Vec<MethodParameter>>, pub maybe_request_size: Option<Count>, pub maybe_request_alignment: Option<Count>, pub has_response: bool, pub maybe_response: Option<Vec<MethodParameter>>, pub maybe_response_size: Option<Count>, pub maybe_response_alignment: Option<Count>, } #[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)] pub struct Interface { pub maybe_attributes: Option<Vec<Attribute>>, pub name: CompoundIdentifier, pub location: Option<Location>, pub methods: Vec<Method>, } #[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)] pub struct StructMember { #[serde(rename = "type")] pub _type: Type, pub name: Identifier, pub location: Option<Location>, pub size: Count, pub max_out_of_line: Count, pub alignment: Count, pub offset: Count, pub maybe_attributes: Option<Vec<Attribute>>, pub maybe_default_value: Option<Constant>, } #[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)] pub struct Struct { pub max_handles: Option<Count>, pub maybe_attributes: Option<Vec<Attribute>>, pub name: CompoundIdentifier, pub location: Option<Location>, pub anonymous: Option<bool>, pub members: Vec<StructMember>, pub size: Count, pub max_out_of_line: Count, } #[derive(Clone, Debug, PartialEq, Eq, Default, Serialize, Deserialize)] pub struct TableMember { pub ordinal: Ordinal, pub reserved: bool, #[serde(rename = "type")] pub _type: Option<Type>, pub name: Option<Identifier>, pub location: Option<Location>, pub size: Option<Count>, pub max_out_of_line: Option<Count>, pub alignment: Option<Count>, pub offset: Option<Count>, pub maybe_default_value: Option<Constant>, } #[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)] pub struct Table { pub max_handles: Option<Count>, pub maybe_attributes: Option<Vec<Attribute>>, pub name: CompoundIdentifier, pub location: Option<Location>, pub members: Vec<TableMember>, pub size: Count, pub max_out_of_line: Count, } #[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)] pub struct UnionMember { #[serde(rename = "type")] pub _type: Type, pub name: Identifier, pub location: Option<Location>, pub size: Count, pub max_out_of_line: Count, pub alignment: Count, pub offset: Count, pub maybe_attributes: Option<Vec<Attribute>>, } #[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)] pub struct Union { pub max_handles: Option<Count>, pub maybe_attributes: Option<Vec<Attribute>>, pub name: CompoundIdentifier, pub location: Option<Location>, pub members: Vec<UnionMember>, pub size: Count, pub max_out_of_line: Count, pub alignment: Count, } #[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)] pub struct XUnionMember { pub ordinal: Ordinal, #[serde(rename = "type")] pub _type: Type, pub name: Identifier, pub location: Option<Location>, pub size: Count, pub max_out_of_line: Count, pub alignment: Count, pub offset: Count, pub maybe_attributes: Option<Vec<Attribute>>, } #[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)] pub struct XUnion { pub max_handles: Option<Count>, pub maybe_attributes: Option<Vec<Attribute>>, pub name: CompoundIdentifier, pub location: Option<Location>, pub members: Vec<XUnionMember>, pub size: Count, pub max_out_of_line: Count, pub alignment: Count, } #[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)] pub struct Ir { pub version: Version, pub name: LibraryIdentifier, pub library_dependencies: Vec<Library>, pub const_declarations: Vec<Const>, pub enum_declarations: Vec<Enum>, pub interface_declarations: Vec<Interface>, pub struct_declarations: Vec<Struct>, pub table_declarations: Vec<Table>, pub union_declarations: Vec<Union>, pub xunion_declarations: Vec<XUnion>, pub declaration_order: Vec<CompoundIdentifier>, pub declarations: DeclarationsMap, }
fn validate_library_identifier<'de, D>(deserializer: D) -> Result<String, D::Error> where D: Deserializer<'de>, { let id = String::deserialize(deserializer)?; if !LIBRARY_IDENTIFIER_RE.is_match(&id) { return Err(serde::de::Error::custom(format!("Invalid library identifier: {}", id))); } Ok(id) }
function_block-full_function
[]
Rust
src/main.rs
svenstaro/ggj2017
9d2cc2d01e33621096ac6aba20aa2889e4960856
pub mod utils; pub mod block; extern crate nalgebra as na; extern crate ncollide; extern crate nphysics2d; extern crate ggez; extern crate rand; use ggez::conf; use ggez::game::{Game, GameState}; use ggez::{GameResult, Context}; use ggez::graphics; use ggez::timer; use std::time::Duration; use rand::Rand; use std::collections::HashMap; use na::Vector2; use ncollide::shape::{Plane, Cuboid}; use nphysics2d::world::World; use nphysics2d::object::RigidBody; use ggez::event::*; use block::Block; use utils::draw_rectangle; struct MainState { text: graphics::Text, physics_world: World<f32>, blocks: Vec<Block>, player: Block, key_pressed: HashMap<Keycode, bool>, } impl GameState for MainState { fn load(ctx: &mut Context) -> GameResult<MainState> { let font = graphics::Font::new(ctx, "DejaVuSerif.ttf", 48).unwrap(); let text = graphics::Text::new(ctx, "Hello world!", &font).unwrap(); let mut world = World::new(); let explane = Block::new(RigidBody::new_dynamic(Cuboid::new(Vector2::new(100.0, 100.0)), 1.0, 0.3, 0.6), &mut world); let mut s = MainState { text: text, physics_world: world, blocks: Vec::new(), player: explane, key_pressed: HashMap::new(), }; s.physics_world.set_gravity(Vector2::new(0.0, 9.81)); let static_block = Block::new(RigidBody::new_dynamic(Cuboid::new(Vector2::new(2000.0, 10.0)), 1.0, 0.3, 0.6), &mut s.physics_world); static_block.body.borrow_mut().append_translation(&Vector2::new(0.0, 400.0)); s.blocks.push(static_block); s.player.body.borrow_mut().append_translation(&Vector2::new(400.0, 100.0)); Ok(s) } fn update(&mut self, _ctx: &mut Context, dt: Duration) -> GameResult<()> { self.physics_world.step(timer::duration_to_f64(dt) as f32); for (key, _) in self.key_pressed.iter() { match key { &Keycode::Right => { println!("right"); self.player.body.borrow_mut().apply_central_impulse(Vector2::new(2000.0, 0.0)); } &Keycode::Left => { println!("left"); self.player.body.borrow_mut().apply_central_impulse(Vector2::new(-2000.0, 0.0)); } &Keycode::Up => { println!("up"); self.player.body.borrow_mut().apply_central_impulse(Vector2::new(0.0, -2000.0)); } _ => (), } } Ok(()) } fn draw(&mut self, ctx: &mut Context) -> GameResult<()> { let mut rng = rand::thread_rng(); ctx.renderer.clear(); graphics::draw(ctx, &mut self.text, None, None)?; for block in &self.blocks { graphics::set_color(ctx, graphics::Color::rand(&mut rng)); draw_rectangle(ctx, block); } graphics::set_color(ctx, graphics::Color::RGB(0, 255, 0)); draw_rectangle(ctx, &self.player); graphics::set_color(ctx, graphics::Color::RGB(0, 0, 0)); ctx.renderer.present(); timer::sleep_until_next_frame(ctx, 60); Ok(()) } fn key_down_event(&mut self, _keycode: Keycode, _keymod: Mod, _repeat: bool) { if !_repeat { self.key_pressed.insert(_keycode, true); } } fn key_up_event(&mut self, _keycode: Keycode, _keymod: Mod, _repeat: bool) { if !_repeat { self.key_pressed.remove(&_keycode); } } } pub fn main() { let mut c = conf::Conf::new(); c.window_title = "ExPlane".to_string(); c.window_width = 1280; c.window_height = 720; let mut game: Game<MainState> = Game::new("helloworld", c).unwrap(); if let Err(e) = game.run() { println!("Error encountered: {}", e); } else { println!("Game exited cleanly."); } }
pub mod utils; pub mod block; extern crate nalgebra as na; extern crate ncollide; extern crate nphysics2d; extern crate ggez; extern crate rand; use ggez::conf; use ggez::game::{Game, GameState}; use ggez::{GameResult, Context}; use ggez::graphics; use ggez::timer; use std::time::Duration; use rand::Rand; use std::collections::HashMap; use na::Vector2; use ncollide::shape::{Plane, Cuboid}; use nphysics2d::world::World; use nphysics2d::object::RigidBody; use ggez::event::*; use block::Block; use utils::draw_rectangle; struct MainState { text: graphics::Text, physics_world: World<f32>, blocks: Vec<Block>, player: Block, key_pressed: HashMap<Keycode, bool>, } impl GameState for MainState { fn load(ctx: &mut Context) -> GameResult<MainState> { let font = graphics::Font::new(ctx, "DejaVuSerif.ttf", 48).unwrap(); let text = graphics::Text::new(ctx, "Hello world!", &font).unwrap(); let mut world = World::new(); let explane = Block::new(RigidBody::new_dynamic(Cuboid::new(Vector2::new(100.0, 100.0)), 1.0, 0.3, 0.6), &mut world); let mut s = MainState { text: text, physics_world: world, blocks: Vec::new(), player: explane, key_pressed: HashMap::new(), }; s.physics_world.set_gravity(Vector2::new(0.0, 9.81)); let static_block = Block::new(RigidBody::new_dynamic(Cuboid::new(Vector2::new(2000.0, 10.0)), 1.0, 0.3, 0.6), &mut s.physics_world); static_block.body.borrow_mut().append_translation(&Vector2::new(0.0, 400.0)); s.blocks.push(static_block); s.player.body.borrow_mut().append_translation(&Vector2::new(400.0, 100.0)); Ok(s) } fn update(&mut self, _ctx: &mut Context, dt: Duration) -> GameResult<()> { self.physics_world.step(timer::duration_to_f64(dt) as f32); for (key, _) in self.key_pressed.iter() { match key { &Keycode::Right => { println!("right"); self.player.body.borrow_mut().apply_central_impulse(Vector2::new(2000.0, 0.0)); } &Keycode::Left => { println!("left"); self.player.body.borrow_mut().apply_central_impulse(Vector2::new(-2000.0, 0.0)); } &Keycode::Up => { println!("up"); self.player.body.borrow_mut().apply_central_impulse(Vector2::new(0.0, -2000.0)); } _ => (), } } Ok(()) } fn draw(&mut self, ctx: &mut Context) -> GameResult<()> { let mut rng = rand::thread_rng(); ctx.renderer.clear(); graphics::draw(ctx, &mut self.text, None, None)?; for block in &self.blocks { graphics::set_color(ctx, graphics::Color::rand(&mut rng)); draw_rectangle(ctx, block); } graphics::set_color(ctx, graphics::Color::RGB(0, 255, 0)); draw_rectangle(
fn key_down_event(&mut self, _keycode: Keycode, _keymod: Mod, _repeat: bool) { if !_repeat { self.key_pressed.insert(_keycode, true); } } fn key_up_event(&mut self, _keycode: Keycode, _keymod: Mod, _repeat: bool) { if !_repeat { self.key_pressed.remove(&_keycode); } } } pub fn main() { let mut c = conf::Conf::new(); c.window_title = "ExPlane".to_string(); c.window_width = 1280; c.window_height = 720; let mut game: Game<MainState> = Game::new("helloworld", c).unwrap(); if let Err(e) = game.run() { println!("Error encountered: {}", e); } else { println!("Game exited cleanly."); } }
ctx, &self.player); graphics::set_color(ctx, graphics::Color::RGB(0, 0, 0)); ctx.renderer.present(); timer::sleep_until_next_frame(ctx, 60); Ok(()) }
function_block-function_prefixed
[ { "content": "pub fn draw_rectangle(ctx: &mut Context, block: &Block) {\n\n let body = block.body.borrow();\n\n\n\n if body.shape().is_shape::<Cuboid<Vector2<f32>>>() {\n\n let shape: &Cuboid<Vector2<f32>> = body.shape().as_shape().unwrap();\n\n let extents = shape.half_extents();\n\n let destrect = graphics::Rect::new(\n\n body.position().translation.x as i32,\n\n body.position().translation.y as i32,\n\n extents.x as u32,\n\n extents.y as u32,\n\n );\n\n let _ = graphics::rectangle(ctx, graphics::DrawMode::Fill, destrect);\n\n }\n\n}\n", "file_path": "src/utils.rs", "rank": 0, "score": 91943.50441618855 }, { "content": "use ggez::graphics;\n\nuse ggez::Context;\n\n\n\nuse na::Vector2;\n\nuse ncollide::shape::Cuboid;\n\n\n\nuse block::Block;\n\n\n\n\n", "file_path": "src/utils.rs", "rank": 3, "score": 13525.04128448961 }, { "content": "use nphysics2d::object::{RigidBody, RigidBodyHandle};\n\nuse nphysics2d::world::World;\n\n\n\npub struct Block {\n\n pub body: RigidBodyHandle<f32>,\n\n}\n\n\n\nimpl Block {\n\n pub fn new(body: RigidBody<f32>, physics_world: &mut World<f32>) -> Block {\n\n let rb_handle = physics_world.add_rigid_body(body);\n\n let b = Block { body: rb_handle };\n\n b\n\n }\n\n}\n", "file_path": "src/block.rs", "rank": 4, "score": 13524.889192603645 }, { "content": "# ggj2017\n\nGlobalGameJam 2017 game\n", "file_path": "README.md", "rank": 5, "score": 7751.442067000835 } ]
Rust
src/drv.rs
kaivol/smartoris-i2c
ce0526e04c95712b9b9c64ca5d6e6598ce65f530
use crate::{ diverged::{DmaChDiverged, I2CDiverged}, I2CMaster, }; use drone_cortexm::{fib, reg::prelude::*, thr::prelude::*}; use drone_stm32_map::periph::{ dma::ch::{traits::*, DmaChMap, DmaChPeriph}, i2c::{traits::*, I2CMap, I2CPeriph}, }; use futures::prelude::*; pub struct I2CSetup< I2C: I2CMap, I2CEv: IntToken, I2CEr: IntToken, DmaTx: DmaChMap, DmaTxInt: IntToken, DmaRx: DmaChMap, DmaRxInt: IntToken, > { pub i2c: I2CPeriph<I2C>, pub i2c_ev: I2CEv, pub i2c_er: I2CEr, pub i2c_freq: u32, pub i2c_presc: u32, pub i2c_trise: u32, pub i2c_mode: I2CMode, pub dma_tx: DmaChPeriph<DmaTx>, pub dma_tx_int: DmaTxInt, pub dma_tx_ch: u32, pub dma_tx_pl: u32, pub dma_rx: DmaChPeriph<DmaRx>, pub dma_rx_int: DmaRxInt, pub dma_rx_ch: u32, pub dma_rx_pl: u32, } #[derive(Clone, Copy)] pub enum I2CMode { Sm1, Fm2, Fm169, } pub struct I2CDrv< I2C: I2CMap, I2CEv: IntToken, I2CEr: IntToken, DmaTx: DmaChMap, DmaTxInt: IntToken, DmaRx: DmaChMap, DmaRxInt: IntToken, > { i2c: I2CDiverged<I2C>, i2c_ev: I2CEv, i2c_er: I2CEr, dma_tx: DmaChDiverged<DmaTx>, dma_tx_int: DmaTxInt, dma_rx: DmaChDiverged<DmaRx>, dma_rx_int: DmaRxInt, } impl< I2C: I2CMap, I2CEv: IntToken, I2CEr: IntToken, DmaTx: DmaChMap, DmaTxInt: IntToken, DmaRx: DmaChMap, DmaRxInt: IntToken, > I2CDrv<I2C, I2CEv, I2CEr, DmaTx, DmaTxInt, DmaRx, DmaRxInt> { #[must_use] pub fn init(setup: I2CSetup<I2C, I2CEv, I2CEr, DmaTx, DmaTxInt, DmaRx, DmaRxInt>) -> Self { let I2CSetup { i2c, i2c_ev, i2c_er, i2c_freq, i2c_presc, i2c_trise, i2c_mode, dma_tx, dma_tx_int, dma_tx_ch, dma_tx_pl, dma_rx, dma_rx_int, dma_rx_ch, dma_rx_pl, } = setup; let mut drv = Self { i2c: i2c.into(), i2c_ev, i2c_er, dma_tx: dma_tx.into(), dma_tx_int, dma_rx: dma_rx.into(), dma_rx_int, }; drv.init_i2c(i2c_freq, i2c_presc, i2c_trise, i2c_mode); drv.init_dma_tx(dma_tx_ch, dma_tx_pl); drv.init_dma_rx(dma_rx_ch, dma_rx_pl); drv } #[inline] pub fn master( &mut self, ) -> I2CMaster<'_, I2C, I2CEv, I2CEr, DmaTx, DmaTxInt, DmaRx, DmaRxInt> { while self.i2c.i2c_cr1.stop().read_bit() {} I2CMaster::new(self/*, buf*/) } pub(crate) unsafe fn write(&mut self, addr: u8, buf_tx: &[u8]) -> impl Future<Output = ()> { self.dma_tx(buf_tx); self.start(addr << 1, false) } pub(crate) unsafe fn read(&mut self, addr: u8, buf_rx: &mut [u8]) -> impl Future<Output = ()> { let dma_rx = self.dma_rx(buf_rx); self.start(addr << 1 | 1, buf_rx.len() > 1).then(|()| dma_rx) } pub(crate) fn stop(&mut self) { self.i2c.i2c_cr1.stop().set_bit(); } unsafe fn dma_tx(&mut self, buf_tx: &[u8]) { self.dma_tx.dma_cm0ar.store_reg(|r, v| { r.m0a().write(v, buf_tx.as_ptr() as u32); }); self.dma_tx.dma_cndtr.store_reg(|r, v| { r.ndt().write(v, buf_tx.len() as u32); }); self.dma_tx.dma_ifcr_ctcif.set_bit(); self.dma_tx.dma_ccr.modify_reg(|r, v| r.en().set(v)); } unsafe fn dma_rx(&mut self, buf_rx: &mut [u8]) -> impl Future<Output = ()> { let dma_ifcr_ctcif = self.dma_rx.dma_ifcr_ctcif; let dma_isr_dmeif = self.dma_rx.dma_isr_dmeif; let dma_isr_feif = self.dma_rx.dma_isr_feif; let dma_isr_tcif = self.dma_rx.dma_isr_tcif; let dma_isr_teif = self.dma_rx.dma_isr_teif; let future = self.dma_rx_int.add_future(fib::new_fn(move || { let val = dma_isr_tcif.load_val(); handle_dma_err::<DmaRx>(&val, dma_isr_dmeif, dma_isr_feif, dma_isr_teif); if dma_isr_tcif.read(&val) { dma_ifcr_ctcif.set_bit(); fib::Complete(()) } else { fib::Yielded(()) } })); self.dma_rx.dma_cm0ar.store_reg(|r, v| { r.m0a().write(v, buf_rx.as_mut_ptr() as u32); }); self.dma_rx.dma_cndtr.store_reg(|r, v| { r.ndt().write(v, buf_rx.len() as u32); }); self.dma_rx.dma_ccr.modify_reg(|r, v| r.en().set(v)); future } fn start(&mut self, addr: u8, ack: bool) -> impl Future<Output = ()> { let i2c_cr1 = self.i2c.i2c_cr1; let i2c_cr2 = self.i2c.i2c_cr2; let i2c_sr1 = self.i2c.i2c_sr1; let i2c_sr2 = self.i2c.i2c_sr2; let i2c_dr = self.i2c.i2c_dr; let set_start = move || { i2c_cr1.modify_reg(|r, v| { if ack { r.ack().set(v); } else { r.ack().clear(v); } r.start().set(v); }); }; let repeated = self.i2c.i2c_sr2.msl().read_bit(); let future = self.i2c_ev.add_future(fib::new_fn(move || { let sr1_val = i2c_sr1.load_val(); if i2c_sr1.sb().read(&sr1_val) { i2c_dr.store_reg(|r, v| r.dr().write(v, u32::from(addr))); fib::Yielded(()) } else if i2c_sr1.addr().read(&sr1_val) { let sr2_val = i2c_sr2.load_val(); if i2c_sr2.tra().read(&sr2_val) { fib::Yielded(()) } else { fib::Complete(()) } } else if i2c_sr1.btf().read(&sr1_val) { if repeated { set_start(); fib::Yielded(()) } else { i2c_cr2.itevten().clear_bit(); fib::Complete(()) } } else { fib::Yielded(()) } })); self.i2c.i2c_cr2.itevten().set_bit(); if !repeated { set_start(); } future } fn init_i2c(&mut self, i2c_freq: u32, i2c_presc: u32, i2c_trise: u32, i2c_mode: I2CMode) { self.i2c.rcc_busenr_i2cen.set_bit(); self.i2c.i2c_cr2.store_reg(|r, v| { r.last().set(v); r.dmaen().set(v); r.iterren().set(v); r.freq().write(v, i2c_freq); }); self.i2c.i2c_ccr.store_reg(|r, v| { match i2c_mode { I2CMode::Sm1 => { r.f_s().clear(v); } I2CMode::Fm2 => { r.f_s().set(v); r.duty().clear(v); } I2CMode::Fm169 => { r.f_s().set(v); r.duty().set(v); } } r.ccr().write(v, i2c_presc); }); self.i2c.i2c_trise.store_reg(|r, v| { r.trise().write(v, i2c_trise); }); self.i2c.i2c_cr1.store_reg(|r, v| r.pe().set(v)); let i2c_sr1 = self.i2c.i2c_sr1; self.i2c_er.add_fn(move || { let val = i2c_sr1.load_val(); handle_i2c_err::<I2C>(&val, i2c_sr1); fib::Yielded::<(), !>(()) }); } fn init_dma_tx(&mut self, channel: u32, priority: u32) { let address = self.i2c.i2c_dr.as_mut_ptr(); self.dma_tx.dma_cpar.store_reg(|r, v| { r.pa().write(v, address as u32); }); self.dma_tx.dma_ccr.store_reg(|r, v| { r.chsel().write(v, channel); r.pl().write(v, priority); r.msize().write(v, 0b00); r.psize().write(v, 0b00); r.minc().set(v); r.pinc().clear(v); r.dir().write(v, 0b01); r.tcie().clear(v); r.teie().set(v); }); let dma_isr_dmeif = self.dma_tx.dma_isr_dmeif; let dma_isr_feif = self.dma_tx.dma_isr_feif; let dma_isr_teif = self.dma_tx.dma_isr_teif; self.dma_tx_int.add_fn(move || { let val = dma_isr_teif.load_val(); handle_dma_err::<DmaTx>(&val, dma_isr_dmeif, dma_isr_feif, dma_isr_teif); fib::Yielded::<(), !>(()) }); } fn init_dma_rx(&mut self, channel: u32, priority: u32) { let address = self.i2c.i2c_dr.as_ptr(); self.dma_rx.dma_cpar.store_reg(|r, v| { r.pa().write(v, address as u32); }); self.dma_rx.dma_ccr.store_reg(|r, v| { r.chsel().write(v, channel); r.pl().write(v, priority); r.msize().write(v, 0b00); r.psize().write(v, 0b00); r.minc().set(v); r.pinc().clear(v); r.dir().write(v, 0b00); r.tcie().set(v); r.teie().set(v); }); } } fn handle_dma_err<T: DmaChMap>( val: &T::DmaIsrVal, dma_isr_dmeif: T::CDmaIsrDmeif, dma_isr_feif: T::CDmaIsrFeif, dma_isr_teif: T::CDmaIsrTeif, ) { if dma_isr_teif.read(&val) { panic!("Transfer error"); } if dma_isr_dmeif.read(&val) { panic!("Direct mode error"); } if dma_isr_feif.read(&val) { panic!("FIFO error"); } } fn handle_i2c_err<T: I2CMap>(val: &T::I2CSr1Val, i2c_sr1: T::CI2CSr1) { if i2c_sr1.berr().read(&val) { panic!("Misplaced Start or Stop condition"); } if i2c_sr1.arlo().read(&val) { panic!("Arbitration Lost detected"); } if i2c_sr1.af().read(&val) { panic!("Acknowledge failure"); } if i2c_sr1.ovr().read(&val) { panic!("Overrun or underrun"); } if i2c_sr1.timeout().read(&val) { panic!("SCL remained LOW for 25 ms"); } }
use crate::{ diverged::{DmaChDiverged, I2CDiverged}, I2CMaster, }; use drone_cortexm::{fib, reg::prelude::*, thr::prelude::*}; use drone_stm32_map::periph::{ dma::ch::{traits::*, DmaChMap, DmaChPeriph}, i2c::{traits::*, I2CMap, I2CPeriph}, }; use futures::prelude::*; pub struct I2CSetup< I2C: I2CMap, I2CEv: IntToken, I2CEr: IntToken, DmaTx: DmaChMap, DmaTxInt: IntToken, DmaRx: DmaChMap, DmaRxInt: IntToken, > { pub i2c: I2CPeriph<I2C>, pub i2c_ev: I2CEv, pub i2c_er: I2CEr, pub i2c_freq: u32, pub i2c_presc: u32, pub i2c_trise: u32, pub i2c_mode: I2CMode, pub dma_tx: DmaChPeriph<DmaTx>, pub dma_tx_int: DmaTxInt, pub dma_tx_ch: u32, pub dma_tx_pl: u32, pub dma_rx: DmaChPeriph<DmaRx>, pub dma_rx_int: DmaRxInt, pub dma_rx_ch: u32, pub dma_rx_pl: u32, } #[derive(Clone, Copy)] pub enum I2CMode { Sm1, Fm2, Fm169, } pub struct I2CDrv< I2C: I2CMap, I2CEv: IntToken, I2CEr: IntToken, DmaTx: DmaChMap, DmaTxInt: IntToken, DmaRx: DmaChMap, DmaRxInt: IntToken, > { i2c: I2CDiverged<I2C>, i2c_ev: I2CEv, i2c_er: I2CEr, dma_tx: DmaChDiverged<DmaTx>, dma_tx_int: DmaTxInt, dma_rx: DmaChDiverged<DmaRx>, dma_rx_int: DmaRxInt, } impl< I2C: I2CMap, I2CEv: IntToken, I2CEr: IntToken, DmaTx: DmaChMap, DmaTxInt: IntToken, DmaRx: DmaChMap, DmaRxInt: IntToken, > I2CDrv<I2C, I2CEv, I2CEr, DmaTx, DmaTxInt, DmaRx, DmaRxInt> { #[must_use] pub fn init(setup: I2CSetup<I2C, I2CEv, I2CEr, DmaTx, DmaTxInt, DmaRx, DmaRxInt>) -> Self { let I2CSetup { i2c, i2c_ev, i2c_er, i2c_freq, i2c_presc, i2c_trise, i2c_mode, dma_tx, dma_tx_int, dma_tx_ch, dma_tx_pl, dma_rx, dma_rx_int, dma_rx_ch, dma_rx_pl, } = setup; let mut drv = Self { i2c: i2c.into(), i2c_ev, i2c_er, dma_tx: dma_tx.into(), dma_tx_int, dma_rx: dma_rx.into(), dma_rx_int, }; drv.init_i2c(i2c_freq, i2c_presc, i2c_trise, i2c_mode); drv.init_dma_tx(dma_tx_ch, dma_tx_pl); drv.init_dma_rx(dma_rx_ch, dma_rx_pl); drv } #[inline] pub fn master( &mut self, ) -> I2CMaster<'_, I2C, I2CEv, I2CEr, DmaTx, DmaTxInt, DmaRx, DmaRxInt> { while self.i2c.i2c_cr1.stop().read_bit() {} I2CMaster::new(self/*, buf*/) } pub(crate) unsafe fn write(&mut self, addr: u8, buf_tx: &[u8]) -> impl Future<Output = ()> { self.dma_tx(buf_tx); self.start(addr << 1, false) } pub(crate) unsafe fn read(&mut self, addr: u8, buf_rx: &mut [u8]) -> impl Future<Output = ()> { let dma_rx = self.dma_rx(buf_rx); self.start(addr << 1 | 1, buf_rx.len() > 1).then(|()| dma_rx) } pub(crate) fn stop(&mut self) { self.i2c.i2c_cr1.stop().set_bit(); } unsafe fn dma_tx(&mut self, buf_tx: &[u8]) { self.dma_tx.dma_cm0ar.store_reg(|r, v| { r.m0a().write(v, buf_tx.as_ptr() as u32); }); self.dma_tx.dma_cndtr.store_reg(|r, v| { r.ndt().write(v, buf_tx.len() as u32); }); self.dma_tx.dma_ifcr_ctcif.set_bit(); self.dma_tx.dma_ccr.modify_reg(|r, v| r.en().set(v)); } unsafe fn dma_rx(&mut self, buf_rx: &mut [u8]) -> impl Future<Output = ()> { let dma_ifcr_ctcif = self.dma_rx.dma_ifcr_ctcif; let dma_isr_dmeif = self.dma_rx.dma_isr_dmeif; let dma_isr_feif = self.dma_rx.dma_isr_feif; let dma_isr_tcif = self.dma_rx.dma_isr_tcif; let dma_isr_teif = self.dma_rx.dma_isr_teif; let future = self.dma_rx_int.add_future(fib::new_fn(move || { let val = dma_isr_tcif.load_val(); handle_dma_err::<DmaRx>(&val, dma_isr_dmeif, dma_isr_feif, dma_isr_teif); if dma_isr_tcif.read(&val) { dma_ifcr_ctcif.set_bit(); fib::Complete(()) } else { fib::Yielded(()) } })); self.dma_rx.dma_cm0ar.store_reg(|r, v| {
} })); self.i2c.i2c_cr2.itevten().set_bit(); if !repeated { set_start(); } future } fn init_i2c(&mut self, i2c_freq: u32, i2c_presc: u32, i2c_trise: u32, i2c_mode: I2CMode) { self.i2c.rcc_busenr_i2cen.set_bit(); self.i2c.i2c_cr2.store_reg(|r, v| { r.last().set(v); r.dmaen().set(v); r.iterren().set(v); r.freq().write(v, i2c_freq); }); self.i2c.i2c_ccr.store_reg(|r, v| { match i2c_mode { I2CMode::Sm1 => { r.f_s().clear(v); } I2CMode::Fm2 => { r.f_s().set(v); r.duty().clear(v); } I2CMode::Fm169 => { r.f_s().set(v); r.duty().set(v); } } r.ccr().write(v, i2c_presc); }); self.i2c.i2c_trise.store_reg(|r, v| { r.trise().write(v, i2c_trise); }); self.i2c.i2c_cr1.store_reg(|r, v| r.pe().set(v)); let i2c_sr1 = self.i2c.i2c_sr1; self.i2c_er.add_fn(move || { let val = i2c_sr1.load_val(); handle_i2c_err::<I2C>(&val, i2c_sr1); fib::Yielded::<(), !>(()) }); } fn init_dma_tx(&mut self, channel: u32, priority: u32) { let address = self.i2c.i2c_dr.as_mut_ptr(); self.dma_tx.dma_cpar.store_reg(|r, v| { r.pa().write(v, address as u32); }); self.dma_tx.dma_ccr.store_reg(|r, v| { r.chsel().write(v, channel); r.pl().write(v, priority); r.msize().write(v, 0b00); r.psize().write(v, 0b00); r.minc().set(v); r.pinc().clear(v); r.dir().write(v, 0b01); r.tcie().clear(v); r.teie().set(v); }); let dma_isr_dmeif = self.dma_tx.dma_isr_dmeif; let dma_isr_feif = self.dma_tx.dma_isr_feif; let dma_isr_teif = self.dma_tx.dma_isr_teif; self.dma_tx_int.add_fn(move || { let val = dma_isr_teif.load_val(); handle_dma_err::<DmaTx>(&val, dma_isr_dmeif, dma_isr_feif, dma_isr_teif); fib::Yielded::<(), !>(()) }); } fn init_dma_rx(&mut self, channel: u32, priority: u32) { let address = self.i2c.i2c_dr.as_ptr(); self.dma_rx.dma_cpar.store_reg(|r, v| { r.pa().write(v, address as u32); }); self.dma_rx.dma_ccr.store_reg(|r, v| { r.chsel().write(v, channel); r.pl().write(v, priority); r.msize().write(v, 0b00); r.psize().write(v, 0b00); r.minc().set(v); r.pinc().clear(v); r.dir().write(v, 0b00); r.tcie().set(v); r.teie().set(v); }); } } fn handle_dma_err<T: DmaChMap>( val: &T::DmaIsrVal, dma_isr_dmeif: T::CDmaIsrDmeif, dma_isr_feif: T::CDmaIsrFeif, dma_isr_teif: T::CDmaIsrTeif, ) { if dma_isr_teif.read(&val) { panic!("Transfer error"); } if dma_isr_dmeif.read(&val) { panic!("Direct mode error"); } if dma_isr_feif.read(&val) { panic!("FIFO error"); } } fn handle_i2c_err<T: I2CMap>(val: &T::I2CSr1Val, i2c_sr1: T::CI2CSr1) { if i2c_sr1.berr().read(&val) { panic!("Misplaced Start or Stop condition"); } if i2c_sr1.arlo().read(&val) { panic!("Arbitration Lost detected"); } if i2c_sr1.af().read(&val) { panic!("Acknowledge failure"); } if i2c_sr1.ovr().read(&val) { panic!("Overrun or underrun"); } if i2c_sr1.timeout().read(&val) { panic!("SCL remained LOW for 25 ms"); } }
r.m0a().write(v, buf_rx.as_mut_ptr() as u32); }); self.dma_rx.dma_cndtr.store_reg(|r, v| { r.ndt().write(v, buf_rx.len() as u32); }); self.dma_rx.dma_ccr.modify_reg(|r, v| r.en().set(v)); future } fn start(&mut self, addr: u8, ack: bool) -> impl Future<Output = ()> { let i2c_cr1 = self.i2c.i2c_cr1; let i2c_cr2 = self.i2c.i2c_cr2; let i2c_sr1 = self.i2c.i2c_sr1; let i2c_sr2 = self.i2c.i2c_sr2; let i2c_dr = self.i2c.i2c_dr; let set_start = move || { i2c_cr1.modify_reg(|r, v| { if ack { r.ack().set(v); } else { r.ack().clear(v); } r.start().set(v); }); }; let repeated = self.i2c.i2c_sr2.msl().read_bit(); let future = self.i2c_ev.add_future(fib::new_fn(move || { let sr1_val = i2c_sr1.load_val(); if i2c_sr1.sb().read(&sr1_val) { i2c_dr.store_reg(|r, v| r.dr().write(v, u32::from(addr))); fib::Yielded(()) } else if i2c_sr1.addr().read(&sr1_val) { let sr2_val = i2c_sr2.load_val(); if i2c_sr2.tra().read(&sr2_val) { fib::Yielded(()) } else { fib::Complete(()) } } else if i2c_sr1.btf().read(&sr1_val) { if repeated { set_start(); fib::Yielded(()) } else { i2c_cr2.itevten().clear_bit(); fib::Complete(()) } } else { fib::Yielded(())
random
[ { "content": " unsafe { self.drv.read(addr, buffer).await };\n\n self\n\n }\n\n\n\n /// Returns a reference to the session buffer.\n\n // #[must_use]\n\n // pub fn buf(&self) -> &[u8] {\n\n // &self.buf\n\n // }\n\n\n\n /// Returns a mutable reference to the session buffer.\n\n // #[must_use]\n\n // pub fn buf_mut(&mut self) -> &mut Box<[u8]> {\n\n // &mut self.buf\n\n // }\n\n\n\n /// Sends a Stop signal and returns the session buffer.\n\n pub fn stop(self) {\n\n // let Self { drv, buf } = self;\n\n self.drv.stop();\n\n // ManuallyDrop::into_inner(buf)\n\n }\n\n}\n", "file_path": "src/master.rs", "rank": 2, "score": 20104.926864106696 }, { "content": " drv: &'a mut I2CDrv<I2C, I2CEv, I2CEr, DmaTx, DmaTxInt, DmaRx, DmaRxInt>,\n\n // buf: ManuallyDrop<Box<[u8]>>,\n\n}\n\n\n\nimpl<\n\n 'a,\n\n I2C: I2CMap,\n\n I2CEv: IntToken,\n\n I2CEr: IntToken,\n\n DmaTx: DmaChMap,\n\n DmaTxInt: IntToken,\n\n DmaRx: DmaChMap,\n\n DmaRxInt: IntToken,\n\n> I2CMaster<'a, I2C, I2CEv, I2CEr, DmaTx, DmaTxInt, DmaRx, DmaRxInt>\n\n{\n\n pub(crate) fn new(\n\n drv: &'a mut I2CDrv<I2C, I2CEv, I2CEr, DmaTx, DmaTxInt, DmaRx, DmaRxInt>,\n\n // buf: Box<[u8]>,\n\n ) -> Self {\n\n Self { drv/*, buf: ManuallyDrop::new(buf)*/ }\n", "file_path": "src/master.rs", "rank": 3, "score": 20098.180591717104 }, { "content": " }\n\n\n\n /// Sends the Start signal for the address `addr`, and writes the data from\n\n /// the session buffer slice of the range `index` to the slave.\n\n pub async fn write(\n\n self,\n\n addr: u8,\n\n buffer: &[u8],\n\n ) -> I2CMaster<'a, I2C, I2CEv, I2CEr, DmaTx, DmaTxInt, DmaRx, DmaRxInt> {\n\n unsafe { self.drv.write(addr, buffer).await };\n\n self\n\n }\n\n\n\n /// Sends the Start signal for the address `addr`, and reads the data from\n\n /// the slave into the session buffer slice of the range `index`.\n\n pub async fn read(\n\n self,\n\n addr: u8,\n\n buffer: &mut [u8],\n\n ) -> I2CMaster<'a, I2C, I2CEv, I2CEr, DmaTx, DmaTxInt, DmaRx, DmaRxInt> {\n", "file_path": "src/master.rs", "rank": 4, "score": 20096.86106745068 }, { "content": "use crate::I2CDrv;\n\nuse drone_cortexm::thr::prelude::*;\n\nuse drone_stm32_map::periph::{dma::ch::DmaChMap, i2c::I2CMap};\n\n\n\n/// I²C master session.\n\n///\n\n/// The session object takes ownership of the provided buffer, which is returned\n\n/// by [`I2CMaster::stop`] method. If the `stop` method is not called, the\n\n/// buffer will be leaked.\n\n#[must_use]\n\npub struct I2CMaster<\n\n 'a,\n\n I2C: I2CMap,\n\n I2CEv: IntToken,\n\n I2CEr: IntToken,\n\n DmaTx: DmaChMap,\n\n DmaTxInt: IntToken,\n\n DmaRx: DmaChMap,\n\n DmaRxInt: IntToken,\n\n> {\n", "file_path": "src/master.rs", "rank": 5, "score": 20093.60095683179 }, { "content": "use drone_cortexm::reg::prelude::*;\n\nuse drone_stm32_map::periph::i2c::{I2CMap, I2CPeriph};\n\n\n\n#[allow(dead_code)]\n\npub(crate) struct I2CDiverged<T: I2CMap> {\n\n pub(crate) rcc_busenr_i2cen: T::SRccBusenrI2Cen,\n\n pub(crate) rcc_busrstr_i2crst: T::SRccBusrstrI2Crst,\n\n pub(crate) rcc_bussmenr_i2csmen: T::SRccBussmenrI2Csmen,\n\n pub(crate) i2c_cr1: T::CI2CCr1,\n\n pub(crate) i2c_cr2: T::CI2CCr2,\n\n pub(crate) i2c_oar1: T::UI2COar1,\n\n pub(crate) i2c_oar2: T::UI2COar2,\n\n pub(crate) i2c_dr: T::CI2CDr,\n\n pub(crate) i2c_sr1: T::CI2CSr1,\n\n pub(crate) i2c_sr2: T::CI2CSr2,\n\n pub(crate) i2c_ccr: T::UI2CCcr,\n\n pub(crate) i2c_trise: T::UI2CTrise,\n\n pub(crate) i2c_fltr: T::UI2CFltr,\n\n}\n\n\n", "file_path": "src/diverged/i2c.rs", "rank": 6, "score": 18294.83949142926 }, { "content": "impl<T: I2CMap> From<I2CPeriph<T>> for I2CDiverged<T> {\n\n fn from(periph: I2CPeriph<T>) -> Self {\n\n let I2CPeriph {\n\n rcc_busenr_i2cen,\n\n rcc_busrstr_i2crst,\n\n rcc_bussmenr_i2csmen,\n\n i2c_cr1,\n\n i2c_cr2,\n\n i2c_oar1,\n\n i2c_oar2,\n\n i2c_dr,\n\n i2c_sr1,\n\n i2c_sr2,\n\n i2c_ccr,\n\n i2c_trise,\n\n i2c_fltr,\n\n } = periph;\n\n Self {\n\n rcc_busenr_i2cen,\n\n rcc_busrstr_i2crst,\n", "file_path": "src/diverged/i2c.rs", "rank": 7, "score": 18291.503648440885 }, { "content": " rcc_bussmenr_i2csmen,\n\n i2c_cr1: i2c_cr1.into_copy(),\n\n i2c_cr2: i2c_cr2.into_copy(),\n\n i2c_oar1: i2c_oar1.into_unsync(),\n\n i2c_oar2: i2c_oar2.into_unsync(),\n\n i2c_dr: i2c_dr.into_copy(),\n\n i2c_sr1: i2c_sr1.into_copy(),\n\n i2c_sr2: i2c_sr2.into_copy(),\n\n i2c_ccr: i2c_ccr.into_unsync(),\n\n i2c_trise: i2c_trise.into_unsync(),\n\n i2c_fltr: i2c_fltr.into_unsync(),\n\n }\n\n }\n\n}\n", "file_path": "src/diverged/i2c.rs", "rank": 8, "score": 18290.790481361164 }, { "content": "[![crates.io](https://img.shields.io/crates/v/smartoris-i2c.svg)](https://crates.io/crates/smartoris-i2c)\n\n![maintenance](https://img.shields.io/badge/maintenance-actively--developed-brightgreen.svg)\n\n\n\n# smartoris-i2c\n\n\n\nI²C [Drone OS] driver for STM32F4 micro-controllers.\n\n\n\n## Limitations\n\n\n\n* Transmission and reception works only through DMA channels with\n\ninterrupts. Polling and interrupt only methods are not supported.\n\n\n\n* Errors from peripherals are handled via panicking.\n\n\n\n* Only the master role is implemented.\n\n\n\n## Usage\n\n\n\nAdd the crate to your `Cargo.toml` dependencies:\n\n\n\n```toml\n\n[dependencies]\n\nsmartoris-i2c = { version = \"0.1.0\" }\n\n```\n\n\n\nAdd or extend `std` feature as follows:\n\n\n\n```toml\n\n[features]\n\nstd = [\"smartoris-i2c/std\"]\n\n```\n\n\n\nExample of initializing the driver for I2C1, DMA1 CH5/CH6, and B6/B7 pins:\n\n\n\n```rust\n\nmod thr {\n\n pub use drone_cortexm::thr::init;\n\n pub use drone_stm32_map::thr::*;\n\n\n\n use drone_cortexm::thr;\n\n\n\n thr::nvic! {\n\n thread => pub Thr {};\n\n local => pub ThrLocal {};\n\n vtable => pub Vtable;\n\n index => pub Thrs;\n\n init => pub ThrsInit;\n\n\n\n threads => {\n\n interrupts => {\n\n /// DMA1 Stream5 global interrupt.\n\n 16: pub dma1_ch5;\n\n /// DMA1 Stream6 global interrupt.\n\n 17: pub dma1_ch6;\n\n /// I²C1 event interrupt.\n\n 31: pub i2c1_ev;\n\n /// I²C1 error interrupt.\n\n 32: pub i2c1_er;\n\n };\n\n };\n\n }\n\n}\n\n\n\nuse crate::thr::ThrsInit;\n\nuse drone_cortexm::{reg::prelude::*, thr::prelude::*};\n\nuse drone_stm32_map::periph::{\n\n dma::{periph_dma1, periph_dma1_ch5, periph_dma1_ch6},\n\n gpio::periph_gpio_b,\n\n i2c::periph_i2c1,\n\n};\n\nuse smartoris_i2c::{I2CDrv, I2CMode, I2CSetup};\n\n\n\nfn handler(reg: Regs, thr_init: ThrsInit) {\n\n let thr = thr::init(thr_init);\n\n\n\n // Enable interrupts.\n\n thr.dma1_ch5.enable_int();\n\n thr.dma1_ch6.enable_int();\n\n thr.i2c1_ev.enable_int();\n", "file_path": "README.md", "rank": 28, "score": 10640.912915489575 }, { "content": " thr.i2c1_er.enable_int();\n\n\n\n // Configure GPIO pins.\n\n let gpio_b = periph_gpio_b!(reg);\n\n gpio_b.rcc_busenr_gpioen.set_bit(); // IO port clock enable\n\n gpio_b.gpio_otyper.store(|r| {\n\n r.set_ot6() // output open-drain\n\n .set_ot7() // output open-drain\n\n });\n\n gpio_b.gpio_ospeedr.store(|r| {\n\n r.write_ospeedr6(0b11) // very high speed\n\n .write_ospeedr7(0b11) // very high speed\n\n });\n\n gpio_b.gpio_pupdr.store(|r| {\n\n r.write_pupdr6(0b00) // no pull-up, pull-down\n\n .write_pupdr7(0b00) // no pull-up, pull-down\n\n });\n\n gpio_b.gpio_afrl.store(|r| {\n\n r.write_afrl6(0b0100) // I2C1/I2C2/I2C3\n\n .write_afrl7(0b0100) // I2C1/I2C2/I2C3\n\n });\n\n gpio_b.gpio_moder.store(|r| {\n\n r.write_moder6(0b10) // alternate function\n\n .write_moder7(0b10) // alternate function\n\n });\n\n gpio_b.rcc_busenr_gpioen.clear_bit(); // IO port clock disable\n\n\n\n periph_dma1!(reg).rcc_busenr_dmaen.set_bit(); // DMA clock enable\n\n\n\n // Set up the driver.\n\n let i2c1 = I2CDrv::init(I2CSetup {\n\n i2c: periph_i2c1!(reg),\n\n i2c_ev: thr.i2c1_ev,\n\n i2c_er: thr.i2c1_er,\n\n i2c_freq: 42, // APB1 clock = 42 MHz\n\n i2c_presc: 35, // SCL clock = 400 kHz\n\n i2c_trise: 13, // 285.7 ns\n\n i2c_mode: I2CMode::Fm2, // Fm mode t_low/t_high = 2\n\n dma_tx: periph_dma1_ch6!(reg),\n\n dma_tx_int: thr.dma1_ch6,\n\n dma_tx_ch: 1, // I2C1_TX\n\n dma_tx_pl: 0b11, // very high\n\n dma_rx: periph_dma1_ch5!(reg),\n\n dma_rx_int: thr.dma1_ch5,\n\n dma_rx_ch: 1, // I2C1_RX\n\n dma_rx_pl: 0b11, // very high\n\n });\n\n}\n\n```\n\n\n\nExample of usage:\n\n\n\n```rust\n\nlet buf = vec![0x92, 0, 0, 0].into_boxed_slice();\n\nlet buf = i2c1\n\n .master(buf) // create a master session backed by the given buffer\n\n .write(0x39, ..1) // write the first byte from the buffer to address `0x39`\n\n .await\n\n .read(0x39, ..) // read 4 bytes into the buffer from address `0x39`\n\n .await\n\n .stop(); // release the bus and get the buffer back\n\nprintln!(\"{:?}\", buf);\n\n```\n\n\n", "file_path": "README.md", "rank": 29, "score": 10637.115602698756 }, { "content": "## References\n\n\n\n* [I²C-bus Specification, Version 6.0, 4th of April\n\n2014](https://www.nxp.com/docs/en/user-guide/UM10204.pdf)\n\n\n\n[Drone OS]: https://www.drone-os.com/\n\n\n\n## License\n\n\n\nLicensed under either of\n\n\n\n * Apache License, Version 2.0\n\n ([LICENSE-APACHE](LICENSE-APACHE) or http://www.apache.org/licenses/LICENSE-2.0)\n\n * MIT license\n\n ([LICENSE-MIT](LICENSE-MIT) or http://opensource.org/licenses/MIT)\n\n\n\nat your option.\n\n\n\n## Contribution\n\n\n\nUnless you explicitly state otherwise, any contribution intentionally submitted\n\nfor inclusion in the work by you, as defined in the Apache-2.0 license, shall be\n\ndual licensed as above, without any additional terms or conditions.\n", "file_path": "README.md", "rank": 30, "score": 10628.507863221625 }, { "content": " clippy::similar_names,\n\n clippy::wildcard_imports\n\n)]\n\n#![cfg_attr(not(feature = \"std\"), no_std)]\n\n\n\nmod diverged;\n\nmod drv;\n\nmod master;\n\n\n\npub use self::{\n\n drv::{I2CDrv, I2CMode, I2CSetup},\n\n master::I2CMaster,\n\n};\n\n\n\n#[prelude_import]\n\n#[allow(unused_imports)]\n\nuse drone_core::prelude::*;\n", "file_path": "src/lib.rs", "rank": 31, "score": 11.334468290496693 }, { "content": "//! 31: pub i2c1_ev;\n\n//! /// I²C1 error interrupt.\n\n//! 32: pub i2c1_er;\n\n//! };\n\n//! };\n\n//! }\n\n//! }\n\n//!\n\n//! use crate::thr::ThrsInit;\n\n//! use drone_cortexm::{reg::prelude::*, thr::prelude::*};\n\n//! use drone_stm32_map::periph::{\n\n//! dma::{periph_dma1, periph_dma1_ch5, periph_dma1_ch6},\n\n//! gpio::periph_gpio_b,\n\n//! i2c::periph_i2c1,\n\n//! };\n\n//! use smartoris_i2c::{I2CDrv, I2CMode, I2CSetup};\n\n//!\n\n//! fn handler(reg: Regs, thr_init: ThrsInit) {\n\n//! let thr = thr::init(thr_init);\n\n//!\n", "file_path": "src/lib.rs", "rank": 32, "score": 11.053961180171267 }, { "content": "//! # };\n\n//! # }\n\n//! # }\n\n//! # async fn handler() {\n\n//! # let mut i2c1: smartoris_i2c::I2CDrv<\n\n//! # I2C1,\n\n//! # thr::I2C1Ev,\n\n//! # thr::I2C1Er,\n\n//! # Dma1Ch6,\n\n//! # thr::Dma1Ch6,\n\n//! # Dma1Ch5,\n\n//! # thr::Dma1Ch5,\n\n//! # > = unsafe { core::mem::MaybeUninit::uninit().assume_init() };\n\n//! let buf = vec![0x92, 0, 0, 0].into_boxed_slice();\n\n//! let buf = i2c1\n\n//! .master(buf) // create a master session backed by the given buffer\n\n//! .write(0x39, ..1) // write the first byte from the buffer to address `0x39`\n\n//! .await\n\n//! .read(0x39, ..) // read 4 bytes into the buffer from address `0x39`\n\n//! .await\n", "file_path": "src/lib.rs", "rank": 33, "score": 10.42652288765056 }, { "content": "mod dma_ch;\n\nmod i2c;\n\n\n\npub(crate) use self::{dma_ch::DmaChDiverged, i2c::I2CDiverged};\n", "file_path": "src/diverged/mod.rs", "rank": 34, "score": 8.919028824029759 }, { "content": "//! # #![feature(const_fn_fn_ptr_basics)]\n\n//! # use drone_stm32_map::periph::{\n\n//! # dma::ch::{Dma1Ch5, Dma1Ch6},\n\n//! # i2c::I2C1,\n\n//! # };\n\n//! # mod thr {\n\n//! # use drone_stm32_map::thr::*;\n\n//! # drone_cortexm::thr::nvic! {\n\n//! # thread => pub Thr {};\n\n//! # local => pub ThrLocal {};\n\n//! # vtable => pub Vtable;\n\n//! # index => pub Thrs;\n\n//! # init => pub ThrsInit;\n\n//! # threads => {\n\n//! # interrupts => {\n\n//! # 16: pub dma1_ch5;\n\n//! # 17: pub dma1_ch6;\n\n//! # 31: pub i2c1_ev;\n\n//! # 32: pub i2c1_er;\n\n//! # };\n", "file_path": "src/lib.rs", "rank": 35, "score": 8.622061214603988 }, { "content": "use drone_cortexm::reg::prelude::*;\n\nuse drone_stm32_map::periph::dma::ch::{DmaChMap, DmaChPeriph};\n\n\n\n#[allow(dead_code)]\n\npub(crate) struct DmaChDiverged<T: DmaChMap> {\n\n pub(crate) dma_ccr: T::UDmaCcr,\n\n pub(crate) dma_cfcr: T::UDmaCfcr,\n\n pub(crate) dma_cm0ar: T::UDmaCm0Ar,\n\n pub(crate) dma_cm1ar: T::UDmaCm1Ar,\n\n pub(crate) dma_cndtr: T::UDmaCndtr,\n\n pub(crate) dma_cpar: T::UDmaCpar,\n\n pub(crate) dma_ifcr_cdmeif: T::CDmaIfcrCdmeif,\n\n pub(crate) dma_ifcr_cfeif: T::CDmaIfcrCfeif,\n\n pub(crate) dma_ifcr_chtif: T::CDmaIfcrChtif,\n\n pub(crate) dma_ifcr_ctcif: T::CDmaIfcrCtcif,\n\n pub(crate) dma_ifcr_cteif: T::CDmaIfcrCteif,\n\n pub(crate) dma_isr_dmeif: T::CDmaIsrDmeif,\n\n pub(crate) dma_isr_feif: T::CDmaIsrFeif,\n\n pub(crate) dma_isr_htif: T::CDmaIsrHtif,\n\n pub(crate) dma_isr_tcif: T::CDmaIsrTcif,\n", "file_path": "src/diverged/dma_ch.rs", "rank": 36, "score": 7.240327564920995 }, { "content": " pub(crate) dma_isr_teif: T::CDmaIsrTeif,\n\n}\n\n\n\nimpl<T: DmaChMap> From<DmaChPeriph<T>> for DmaChDiverged<T> {\n\n fn from(periph: DmaChPeriph<T>) -> Self {\n\n let DmaChPeriph {\n\n dma_ccr,\n\n dma_cfcr,\n\n dma_cm0ar,\n\n dma_cm1ar,\n\n dma_cndtr,\n\n dma_cpar,\n\n dma_ifcr_cdmeif,\n\n dma_ifcr_cfeif,\n\n dma_ifcr_chtif,\n\n dma_ifcr_ctcif,\n\n dma_ifcr_cteif,\n\n dma_isr_dmeif,\n\n dma_isr_feif,\n\n dma_isr_htif,\n", "file_path": "src/diverged/dma_ch.rs", "rank": 37, "score": 6.063353911204889 }, { "content": "//! Add or extend `std` feature as follows:\n\n//!\n\n//! ```toml\n\n//! [features]\n\n//! std = [\"smartoris-i2c/std\"]\n\n//! ```\n\n//!\n\n//! Example of initializing the driver for I2C1, DMA1 CH5/CH6, and B6/B7 pins:\n\n//!\n\n//! ```no_run\n\n//! # #![feature(const_fn_fn_ptr_basics)]\n\n//! # use drone_stm32_map::stm32_reg_tokens;\n\n//! # use drone_core::token::Token;\n\n//! # stm32_reg_tokens! {\n\n//! # index => Regs;\n\n//! # exclude => {\n\n//! # scb_ccr,\n\n//! # mpu_type, mpu_ctrl, mpu_rnr, mpu_rbar, mpu_rasr,\n\n//! # }\n\n//! # }\n", "file_path": "src/lib.rs", "rank": 38, "score": 5.852962074139445 }, { "content": "//! mod thr {\n\n//! pub use drone_cortexm::thr::init;\n\n//! pub use drone_stm32_map::thr::*;\n\n//!\n\n//! use drone_cortexm::thr;\n\n//!\n\n//! thr::nvic! {\n\n//! thread => pub Thr {};\n\n//! local => pub ThrLocal {};\n\n//! vtable => pub Vtable;\n\n//! index => pub Thrs;\n\n//! init => pub ThrsInit;\n\n//!\n\n//! threads => {\n\n//! interrupts => {\n\n//! /// DMA1 Stream5 global interrupt.\n\n//! 16: pub dma1_ch5;\n\n//! /// DMA1 Stream6 global interrupt.\n\n//! 17: pub dma1_ch6;\n\n//! /// I²C1 event interrupt.\n", "file_path": "src/lib.rs", "rank": 39, "score": 5.440938881268925 }, { "content": "//! I²C [Drone OS] driver for STM32F4 micro-controllers.\n\n//!\n\n//! # Limitations\n\n//!\n\n//! * Transmission and reception works only through DMA channels with\n\n//! interrupts. Polling and interrupt only methods are not supported.\n\n//!\n\n//! * Errors from peripherals are handled via panicking.\n\n//!\n\n//! * Only the master role is implemented.\n\n//!\n\n//! # Usage\n\n//!\n\n//! Add the crate to your `Cargo.toml` dependencies:\n\n//!\n\n//! ```toml\n\n//! [dependencies]\n\n//! smartoris-i2c = { version = \"0.1.0\" }\n\n//! ```\n\n//!\n", "file_path": "src/lib.rs", "rank": 40, "score": 5.3772868274006225 }, { "content": "//! i2c_trise: 13, // 285.7 ns\n\n//! i2c_mode: I2CMode::Fm2, // Fm mode t_low/t_high = 2\n\n//! dma_tx: periph_dma1_ch6!(reg),\n\n//! dma_tx_int: thr.dma1_ch6,\n\n//! dma_tx_ch: 1, // I2C1_TX\n\n//! dma_tx_pl: 0b11, // very high\n\n//! dma_rx: periph_dma1_ch5!(reg),\n\n//! dma_rx_int: thr.dma1_ch5,\n\n//! dma_rx_ch: 1, // I2C1_RX\n\n//! dma_rx_pl: 0b11, // very high\n\n//! });\n\n//! }\n\n//! # fn main() {\n\n//! # unsafe { handler(Regs::take(), ThrsInit::take()) };\n\n//! # }\n\n//! ```\n\n//!\n\n//! Example of usage:\n\n//!\n\n//! ```no_run\n", "file_path": "src/lib.rs", "rank": 41, "score": 4.85516866656158 }, { "content": "//! });\n\n//! gpio_b.gpio_afrl.store(|r| {\n\n//! r.write_afrl6(0b0100) // I2C1/I2C2/I2C3\n\n//! .write_afrl7(0b0100) // I2C1/I2C2/I2C3\n\n//! });\n\n//! gpio_b.gpio_moder.store(|r| {\n\n//! r.write_moder6(0b10) // alternate function\n\n//! .write_moder7(0b10) // alternate function\n\n//! });\n\n//! gpio_b.rcc_busenr_gpioen.clear_bit(); // IO port clock disable\n\n//!\n\n//! periph_dma1!(reg).rcc_busenr_dmaen.set_bit(); // DMA clock enable\n\n//!\n\n//! // Set up the driver.\n\n//! let i2c1 = I2CDrv::init(I2CSetup {\n\n//! i2c: periph_i2c1!(reg),\n\n//! i2c_ev: thr.i2c1_ev,\n\n//! i2c_er: thr.i2c1_er,\n\n//! i2c_freq: 42, // APB1 clock = 42 MHz\n\n//! i2c_presc: 35, // SCL clock = 400 kHz\n", "file_path": "src/lib.rs", "rank": 42, "score": 4.770078617360672 }, { "content": " dma_isr_tcif,\n\n dma_isr_teif,\n\n } = periph;\n\n Self {\n\n dma_ccr: dma_ccr.into_unsync(),\n\n dma_cfcr: dma_cfcr.into_unsync(),\n\n dma_cm0ar: dma_cm0ar.into_unsync(),\n\n dma_cm1ar: dma_cm1ar.into_unsync(),\n\n dma_cndtr: dma_cndtr.into_unsync(),\n\n dma_cpar: dma_cpar.into_unsync(),\n\n dma_ifcr_cdmeif: dma_ifcr_cdmeif.into_copy(),\n\n dma_ifcr_cfeif: dma_ifcr_cfeif.into_copy(),\n\n dma_ifcr_chtif: dma_ifcr_chtif.into_copy(),\n\n dma_ifcr_ctcif: dma_ifcr_ctcif.into_copy(),\n\n dma_ifcr_cteif: dma_ifcr_cteif.into_copy(),\n\n dma_isr_dmeif: dma_isr_dmeif.into_copy(),\n\n dma_isr_feif: dma_isr_feif.into_copy(),\n\n dma_isr_htif: dma_isr_htif.into_copy(),\n\n dma_isr_tcif: dma_isr_tcif.into_copy(),\n\n dma_isr_teif: dma_isr_teif.into_copy(),\n\n }\n\n }\n\n}\n", "file_path": "src/diverged/dma_ch.rs", "rank": 43, "score": 4.425904516730214 }, { "content": "//! .stop(); // release the bus and get the buffer back\n\n//! println!(\"{:?}\", buf);\n\n//! # }\n\n//! # fn main() {}\n\n//! ```\n\n//!\n\n//! # References\n\n//!\n\n//! * [I²C-bus Specification, Version 6.0, 4th of April\n\n//! 2014](https://www.nxp.com/docs/en/user-guide/UM10204.pdf)\n\n//!\n\n//! [Drone OS]: https://www.drone-os.com/\n\n\n\n#![feature(never_type)]\n\n#![feature(prelude_import)]\n\n#![warn(missing_docs)]\n\n#![warn(clippy::pedantic)]\n\n#![allow(\n\n clippy::cast_possible_truncation,\n\n clippy::module_name_repetitions,\n", "file_path": "src/lib.rs", "rank": 44, "score": 1.7245516431053955 } ]
Rust
examples/echo.rs
sdroege/memfd-rs
923792d71da3cd225eaeeb7517164279aec38817
extern crate nix; extern crate getopts; extern crate memfd; use std::io; use std::os::unix::io::{RawFd, AsRawFd}; use std::path::{Path, PathBuf}; use nix::sys::socket::*; use nix::unistd::*; use nix::sys::uio::*; use getopts::Options; use std::env; use memfd::*; #[derive(Debug)] pub struct UnixDatagram { fd: RawFd, } impl UnixDatagram { pub fn new() -> io::Result<UnixDatagram> { let fd = match socket(AddressFamily::Unix, SockType::Datagram, SOCK_CLOEXEC, 0) { Ok(fd) => fd, Err(nix::Error::Sys(errno)) => { return Err(io::Error::from_raw_os_error(errno as i32)); } Err(_) => unreachable!(), }; Ok(UnixDatagram { fd: fd }) } pub fn bind<P: AsRef<Path>>(path: P) -> io::Result<UnixDatagram> { let datagram = try!(UnixDatagram::new()); let _ = unlink(path.as_ref()); let addr = match UnixAddr::new(path.as_ref()) { Ok(addr) => addr, Err(nix::Error::Sys(errno)) => { return Err(io::Error::from_raw_os_error(errno as i32)); } Err(_) => unreachable!(), }; match bind(datagram.fd, &SockAddr::Unix(addr)) { Ok(()) => (), Err(nix::Error::Sys(errno)) => { return Err(io::Error::from_raw_os_error(errno as i32)); } Err(_) => unreachable!(), }; Ok(datagram) } pub fn send<P: AsRef<Path>>(&self, path: P, data: &[u8], memfd: Option<&SealedMemFd>) -> io::Result<()> { let iov = [IoVec::from_slice(data)]; let addr = match UnixAddr::new(path.as_ref()) { Ok(addr) => addr, Err(nix::Error::Sys(errno)) => { return Err(io::Error::from_raw_os_error(errno as i32)); } Err(_) => unreachable!(), }; let res = match memfd { Some(fd) => { sendmsg(self.fd, &iov, &[ControlMessage::ScmRights(&[fd.as_raw_fd()])], MSG_CMSG_CLOEXEC, Some(&SockAddr::Unix(addr))) } None => { sendmsg(self.fd, &iov, &[], MsgFlags::empty(), Some(&SockAddr::Unix(addr))) } }; match res { Ok(_) => Ok(()), Err(nix::Error::Sys(errno)) => Err(io::Error::from_raw_os_error(errno as i32)), Err(_) => unreachable!(), } } pub fn recv(&self, data: &mut [u8], memfd: &mut Option<SealedMemFd>) -> io::Result<(usize, Option<PathBuf>)> { let iov = [IoVec::from_mut_slice(data)]; let mut cmsgs: CmsgSpace<[RawFd; 1]> = CmsgSpace::new(); let msg = match recvmsg(self.fd, &iov, Some(&mut cmsgs), MSG_CMSG_CLOEXEC) { Ok(msg) => msg, Err(nix::Error::Sys(errno)) => { return Err(io::Error::from_raw_os_error(errno as i32)); } Err(_) => unreachable!(), }; let path = msg.address .map(|a| { match a { SockAddr::Unix(u) => u.path().map(|p| p.to_path_buf()), _ => None, } }) .and_then(|p| p); *memfd = None; for cmsg in msg.cmsgs() { match cmsg { ControlMessage::ScmRights(fds) if fds.len() == 1 => { *memfd = Some(try!(SealedMemFd::new(fds[0]))); break; } _ => (), }; } Ok((msg.bytes, path)) } } impl Drop for UnixDatagram { fn drop(&mut self) { if self.fd != -1 { let _ = close(self.fd); } } } fn run_server<P: AsRef<Path>>(path: P) { let dg = UnixDatagram::bind(path).unwrap(); loop { let mut data = [0; 1024]; let mut memfd = None; let res = dg.recv(&mut data, &mut memfd).unwrap(); let memfd = memfd.unwrap(); println!("Received {} bytes from {:?}", res.0, res.1); println!("Data: {:?}", &data[0..res.0]); println!("MemFd size: {}", memfd.get_size().unwrap()); println!(""); } } fn run_client<P: AsRef<Path>>(path: P) { let dg = UnixDatagram::new().unwrap(); let path_ref = path.as_ref(); loop { let data = [0, 1, 2, 3, 4, 5, 6, 7]; let mut mfd = MemFd::new("echo").unwrap(); let _ = mfd.set_size(1024 * 1024).unwrap(); { let s = mfd.as_mut_slice().unwrap(); for i in 0..s.len() { s[i] = i as u8; } } let smfd = mfd.seal().unwrap(); let res = dg.send(path_ref, &data, Some(&smfd)); println!("Sent: {:?}", res); res.unwrap(); } } fn print_usage(program: &str, opts: &Options) { let brief = format!("Usage: {} FILE [options]", program); print!("{}", opts.usage(&brief)); } fn main() { let args: Vec<String> = env::args().collect(); let program = args[0].clone(); let mut opts = Options::new(); opts.optflag("h", "help", "Help"); opts.optflag("c", "client", "Run in client mode"); opts.optflag("s", "server", "Run in server mode"); opts.reqopt("p", "path", "Path to connect to", "PATH"); let matches = match opts.parse(&args[1..]) { Ok(m) => m, Err(f) => panic!(f.to_string()), }; if matches.opt_present("h") { print_usage(&program, &opts); return; } if matches.opt_present("c") && matches.opt_present("s") { print_usage(&program, &opts); return; } let path = match matches.opt_str("p") { Some(path) => path, None => { print_usage(&program, &opts); return; } }; if matches.opt_present("c") { run_client(&path); } else if matches.opt_present("s") { run_server(&path); } else { print_usage(&program, &opts); return; } }
extern crate nix; extern crate getopts; extern crate memfd; use std::io; use std::os::unix::io::{RawFd, AsRawFd}; use std::path::{Path, PathBuf}; use nix::sys::socket::*; use nix::unistd::*; use nix::sys::uio::*; use getopts::Options; use std::env; use memfd::*; #[derive(Debug)] pub struct UnixDatagram { fd: RawFd, } impl UnixDatagram { pub fn new() -> io::Result<UnixDatagram> { let fd = match socket(AddressFamily::Unix, SockType::Datagram, SOCK_CLOEXEC, 0) { Ok(fd) => fd, Err(nix::Error::Sys(errno)) => { return Err(io::Error::from_raw_os_error(errno as i32)); } Err(_) => unreachable!(), }; Ok(UnixDatagram { fd: fd }) } pub fn bind<P: AsRef<Path>>(path: P) -> io::Result<UnixDatagram> { let datagram = try!(UnixDatagram::new()); let _ = unlink(path.as_ref()); let addr = match UnixAddr::new(path.as_ref()) { Ok(addr) => addr, Err(nix::Error::Sys(errno)) => { return Err(io::Error::from_raw_os_error(errno as i32)); } Err(_) => unreachable!(), }; match bind(datagram.fd, &SockAddr::Unix(addr)) { Ok(()) => (), Err(nix::Error::Sys(errno)) => { return Err(io::Error::from_raw_os_error(errno as i32)); } Err(_) => unreachable!(), }; Ok(datagram) } pub fn send<P: AsRef<Path>>(&self, path: P, data: &[u8], memfd: Option<&SealedMemFd>) -> io::Result<()> { let iov = [IoVec::from_slice(data)]; let addr = match UnixAddr::new(path.as_ref()) { Ok(addr) => addr, Err(nix::Error::Sys(errno)) => { return Err(io::Error::from_raw_os_error(errno as i32)); } Err(_) => unreachable!(), }; let res = match memfd { Some(fd) => {
} None => { sendmsg(self.fd, &iov, &[], MsgFlags::empty(), Some(&SockAddr::Unix(addr))) } }; match res { Ok(_) => Ok(()), Err(nix::Error::Sys(errno)) => Err(io::Error::from_raw_os_error(errno as i32)), Err(_) => unreachable!(), } } pub fn recv(&self, data: &mut [u8], memfd: &mut Option<SealedMemFd>) -> io::Result<(usize, Option<PathBuf>)> { let iov = [IoVec::from_mut_slice(data)]; let mut cmsgs: CmsgSpace<[RawFd; 1]> = CmsgSpace::new(); let msg = match recvmsg(self.fd, &iov, Some(&mut cmsgs), MSG_CMSG_CLOEXEC) { Ok(msg) => msg, Err(nix::Error::Sys(errno)) => { return Err(io::Error::from_raw_os_error(errno as i32)); } Err(_) => unreachable!(), }; let path = msg.address .map(|a| { match a { SockAddr::Unix(u) => u.path().map(|p| p.to_path_buf()), _ => None, } }) .and_then(|p| p); *memfd = None; for cmsg in msg.cmsgs() { match cmsg { ControlMessage::ScmRights(fds) if fds.len() == 1 => { *memfd = Some(try!(SealedMemFd::new(fds[0]))); break; } _ => (), }; } Ok((msg.bytes, path)) } } impl Drop for UnixDatagram { fn drop(&mut self) { if self.fd != -1 { let _ = close(self.fd); } } } fn run_server<P: AsRef<Path>>(path: P) { let dg = UnixDatagram::bind(path).unwrap(); loop { let mut data = [0; 1024]; let mut memfd = None; let res = dg.recv(&mut data, &mut memfd).unwrap(); let memfd = memfd.unwrap(); println!("Received {} bytes from {:?}", res.0, res.1); println!("Data: {:?}", &data[0..res.0]); println!("MemFd size: {}", memfd.get_size().unwrap()); println!(""); } } fn run_client<P: AsRef<Path>>(path: P) { let dg = UnixDatagram::new().unwrap(); let path_ref = path.as_ref(); loop { let data = [0, 1, 2, 3, 4, 5, 6, 7]; let mut mfd = MemFd::new("echo").unwrap(); let _ = mfd.set_size(1024 * 1024).unwrap(); { let s = mfd.as_mut_slice().unwrap(); for i in 0..s.len() { s[i] = i as u8; } } let smfd = mfd.seal().unwrap(); let res = dg.send(path_ref, &data, Some(&smfd)); println!("Sent: {:?}", res); res.unwrap(); } } fn print_usage(program: &str, opts: &Options) { let brief = format!("Usage: {} FILE [options]", program); print!("{}", opts.usage(&brief)); } fn main() { let args: Vec<String> = env::args().collect(); let program = args[0].clone(); let mut opts = Options::new(); opts.optflag("h", "help", "Help"); opts.optflag("c", "client", "Run in client mode"); opts.optflag("s", "server", "Run in server mode"); opts.reqopt("p", "path", "Path to connect to", "PATH"); let matches = match opts.parse(&args[1..]) { Ok(m) => m, Err(f) => panic!(f.to_string()), }; if matches.opt_present("h") { print_usage(&program, &opts); return; } if matches.opt_present("c") && matches.opt_present("s") { print_usage(&program, &opts); return; } let path = match matches.opt_str("p") { Some(path) => path, None => { print_usage(&program, &opts); return; } }; if matches.opt_present("c") { run_client(&path); } else if matches.opt_present("s") { run_server(&path); } else { print_usage(&program, &opts); return; } }
sendmsg(self.fd, &iov, &[ControlMessage::ScmRights(&[fd.as_raw_fd()])], MSG_CMSG_CLOEXEC, Some(&SockAddr::Unix(addr)))
call_expression
[ { "content": " pub fn as_slice<'a>(&'a self) -> Result<&'a [u8], io::Error> {\n\n let size = try!(self.get_size());\n\n if size == 0 {\n\n return Ok(&[]);\n\n }\n\n\n\n match self.map {\n\n SealedMap::ReadOnly(p, s) => Ok(unsafe { slice::from_raw_parts(p as *const u8, s) }),\n\n SealedMap::Unmapped => unreachable!(),\n\n }\n\n }\n\n\n\n // Not implementing Clone trait because this can fail\n\n pub fn clone(&self) -> Result<SealedMemFd, io::Error> {\n\n let new_fd = match dup(self.fd) {\n\n Ok(fd) => fd,\n\n Err(nix::Error::Sys(errno)) => return Err(io::Error::from_raw_os_error(errno as i32)),\n\n Err(_) => unreachable!(),\n\n };\n\n\n", "file_path": "src/lib.rs", "rank": 10, "score": 10.655604675027295 }, { "content": "extern crate nix;\n\nextern crate libc;\n\n\n\nuse libc::{off_t, c_void, size_t};\n\nuse nix::sys::stat::*;\n\nuse nix::fcntl::*;\n\nuse nix::sys::memfd::*;\n\nuse nix::unistd::*;\n\nuse nix::sys::mman::*;\n\nuse std::ptr;\n\nuse std::slice;\n\nuse std::io;\n\nuse std::ffi::CString;\n\nuse std::os::unix::io::{RawFd, IntoRawFd, AsRawFd};\n\n\n\n#[cfg(test)]\n\nmod tests {\n\n use super::*;\n\n use std::os::unix::io::{IntoRawFd, AsRawFd};\n\n\n", "file_path": "src/lib.rs", "rank": 12, "score": 10.095349671539697 }, { "content": " Err(_) => -1,\n\n }\n\n }\n\n}\n\n\n\nimpl SealedMemFd {\n\n pub fn new(fd: RawFd) -> Result<SealedMemFd, io::Error> {\n\n let mut memfd = SealedMemFd {\n\n fd: fd,\n\n map: SealedMap::Unmapped,\n\n };\n\n\n\n try!(memfd.ensure_seals());\n\n try!(memfd.update_map());\n\n\n\n Ok(memfd)\n\n }\n\n\n\n fn ensure_seals(&self) -> Result<(), io::Error> {\n\n match fcntl(self.fd, FcntlArg::F_GET_SEALS) {\n", "file_path": "src/lib.rs", "rank": 13, "score": 8.722455442617063 }, { "content": " self.fd,\n\n 0) {\n\n Ok(p) => p,\n\n Err(nix::Error::Sys(errno)) => return Err(io::Error::from_raw_os_error(errno as i32)),\n\n Err(_) => unreachable!(),\n\n };\n\n\n\n self.map = SealedMap::ReadOnly(p, size);\n\n\n\n Ok(())\n\n }\n\n\n\n pub fn get_size(&self) -> Result<usize, io::Error> {\n\n match fstat(self.fd) {\n\n Ok(stat) => Ok(stat.st_size as usize),\n\n Err(nix::Error::Sys(errno)) => Err(io::Error::from_raw_os_error(errno as i32)),\n\n Err(_) => unreachable!(),\n\n }\n\n }\n\n\n", "file_path": "src/lib.rs", "rank": 14, "score": 8.644871530318657 }, { "content": " }\n\n Err(_) => unreachable!(),\n\n };\n\n\n\n let memfd = MemFd {\n\n fd: fd,\n\n map: Map::Unmapped,\n\n };\n\n\n\n try!(memfd.ensure_seals());\n\n\n\n Ok(memfd)\n\n }\n\n\n\n pub unsafe fn new_from_fd(fd: RawFd) -> Result<MemFd, io::Error> {\n\n let mut memfd = MemFd {\n\n fd: fd,\n\n map: Map::Unmapped,\n\n };\n\n\n", "file_path": "src/lib.rs", "rank": 15, "score": 8.593102948877059 }, { "content": " try!(memfd.ensure_seals());\n\n try!(memfd.update_map());\n\n\n\n Ok(memfd)\n\n }\n\n\n\n fn ensure_seals(&self) -> Result<(), io::Error> {\n\n match fcntl(self.fd, FcntlArg::F_GET_SEALS) {\n\n Ok(seals) if SealFlag::from_bits_truncate(seals).is_empty() => Ok(()),\n\n Ok(seals) => {\n\n Err(io::Error::new(io::ErrorKind::PermissionDenied,\n\n format!(\"memfd is sealed: {:?}\",\n\n SealFlag::from_bits_truncate(seals))))\n\n }\n\n Err(nix::Error::Sys(errno)) => Err(io::Error::from_raw_os_error(errno as i32)),\n\n Err(_) => unreachable!(),\n\n }\n\n }\n\n\n\n pub fn set_size(&mut self, size: usize) -> Result<(), io::Error> {\n", "file_path": "src/lib.rs", "rank": 16, "score": 8.426267806093753 }, { "content": " PROT_READ | PROT_WRITE,\n\n MAP_SHARED,\n\n self.fd,\n\n 0) {\n\n Ok(p) => p,\n\n Err(nix::Error::Sys(errno)) => return Err(io::Error::from_raw_os_error(errno as i32)),\n\n Err(_) => unreachable!(),\n\n };\n\n\n\n self.map = Map::ReadWrite(p, size);\n\n\n\n Ok(())\n\n }\n\n\n\n pub fn get_size(&self) -> Result<usize, io::Error> {\n\n match fstat(self.fd) {\n\n Ok(stat) => Ok(stat.st_size as usize),\n\n Err(nix::Error::Sys(errno)) => Err(io::Error::from_raw_os_error(errno as i32)),\n\n Err(_) => unreachable!(),\n\n }\n", "file_path": "src/lib.rs", "rank": 17, "score": 8.239072056145456 }, { "content": " Map::Unmapped => Err(io::Error::new(io::ErrorKind::PermissionDenied, \"unmapped\")),\n\n Map::ReadWrite(p, s) => Ok(unsafe { slice::from_raw_parts_mut(p as *mut u8, s) }),\n\n }\n\n }\n\n\n\n pub fn seal(mut self) -> Result<SealedMemFd, io::Error> {\n\n let fd = self.fd;\n\n try!(self.unmap());\n\n self.fd = -1;\n\n\n\n match fcntl(fd,\n\n FcntlArg::F_ADD_SEALS(F_SEAL_GROW | F_SEAL_SEAL | F_SEAL_SHRINK |\n\n F_SEAL_WRITE)) {\n\n Ok(_) => (),\n\n Err(nix::Error::Sys(errno)) => return Err(io::Error::from_raw_os_error(errno as i32)),\n\n Err(_) => unreachable!(),\n\n };\n\n\n\n SealedMemFd::new(fd)\n\n }\n", "file_path": "src/lib.rs", "rank": 18, "score": 8.094489098494423 }, { "content": " try!(self.ensure_seals());\n\n\n\n match ftruncate(self.fd, size as off_t) {\n\n Ok(_) => (),\n\n Err(nix::Error::Sys(errno)) => return Err(io::Error::from_raw_os_error(errno as i32)),\n\n Err(_) => unreachable!(),\n\n };\n\n\n\n try!(self.update_map());\n\n\n\n Ok(())\n\n }\n\n\n\n fn unmap(&mut self) -> Result<(), io::Error> {\n\n match self.map {\n\n Map::ReadWrite(p, size) => {\n\n match munmap(p, size) {\n\n Ok(_) => {\n\n self.map = Map::Unmapped;\n\n Ok(())\n", "file_path": "src/lib.rs", "rank": 19, "score": 7.3155489989525435 }, { "content": " }\n\n\n\n pub fn as_slice<'a>(&'a self) -> Result<&'a [u8], io::Error> {\n\n let size = try!(self.get_size());\n\n if size == 0 {\n\n return Ok(&[]);\n\n }\n\n\n\n match self.map {\n\n Map::Unmapped => Err(io::Error::new(io::ErrorKind::PermissionDenied, \"unmapped\")),\n\n Map::ReadWrite(p, s) => Ok(unsafe { slice::from_raw_parts(p as *const u8, s) }),\n\n }\n\n }\n\n\n\n pub fn as_mut_slice<'a>(&'a mut self) -> Result<&'a mut [u8], io::Error> {\n\n let size = try!(self.get_size());\n\n if size == 0 {\n\n return Ok(&mut []);\n\n }\n\n match self.map {\n", "file_path": "src/lib.rs", "rank": 20, "score": 7.089973283569592 }, { "content": "\n\n // Not implementing AsRawFd trait because this is unsafe\n\n pub unsafe fn as_raw_fd(&self) -> RawFd {\n\n self.fd\n\n }\n\n}\n\n\n\nimpl Drop for MemFd {\n\n fn drop(&mut self) {\n\n let _ = self.unmap();\n\n if self.fd != -1 {\n\n let _ = close(self.fd);\n\n }\n\n }\n\n}\n\n\n\nimpl IntoRawFd for MemFd {\n\n fn into_raw_fd(self) -> RawFd {\n\n match self.seal() {\n\n Ok(sealed) => sealed.into_raw_fd(),\n", "file_path": "src/lib.rs", "rank": 21, "score": 6.955193096156471 }, { "content": " Ok(seals) if SealFlag::from_bits_truncate(seals) ==\n\n F_SEAL_GROW | F_SEAL_SEAL | F_SEAL_SHRINK | F_SEAL_WRITE => Ok(()),\n\n Ok(seals) => {\n\n Err(io::Error::new(io::ErrorKind::PermissionDenied,\n\n format!(\"memfd is not sealed: {:?}\",\n\n SealFlag::from_bits_truncate(seals))))\n\n }\n\n Err(nix::Error::Sys(errno)) => Err(io::Error::from_raw_os_error(errno as i32)),\n\n Err(_) => unreachable!(),\n\n }\n\n }\n\n\n\n fn unmap(&mut self) -> Result<(), io::Error> {\n\n match self.map {\n\n SealedMap::ReadOnly(p, size) => {\n\n match munmap(p, size) {\n\n Ok(_) => {\n\n self.map = SealedMap::Unmapped;\n\n Ok(())\n\n }\n", "file_path": "src/lib.rs", "rank": 22, "score": 6.528300521561538 }, { "content": " SealedMemFd::new(new_fd)\n\n }\n\n}\n\n\n\nimpl Drop for SealedMemFd {\n\n fn drop(&mut self) {\n\n let _ = self.unmap();\n\n if self.fd != -1 {\n\n let _ = close(self.fd);\n\n }\n\n }\n\n}\n\n\n\nimpl AsRawFd for SealedMemFd {\n\n fn as_raw_fd(&self) -> RawFd {\n\n self.fd\n\n }\n\n}\n\n\n\nimpl IntoRawFd for SealedMemFd {\n\n fn into_raw_fd(mut self) -> RawFd {\n\n let fd = self.fd;\n\n self.fd = -1;\n\n // unmap happens on drop\n\n\n\n fd\n\n }\n\n}\n", "file_path": "src/lib.rs", "rank": 23, "score": 5.395867951015242 }, { "content": " }\n\n Err(nix::Error::Sys(errno)) => {\n\n self.map = Map::Unmapped;\n\n Err(io::Error::from_raw_os_error(errno as i32))\n\n }\n\n Err(_) => unreachable!(),\n\n }\n\n }\n\n Map::Unmapped => Ok(()),\n\n }\n\n }\n\n\n\n fn update_map(&mut self) -> Result<(), io::Error> {\n\n try!(self.unmap());\n\n try!(self.ensure_seals());\n\n\n\n let size = try!(self.get_size());\n\n\n\n let p = match mmap(ptr::null_mut(),\n\n size as size_t,\n", "file_path": "src/lib.rs", "rank": 24, "score": 5.204643007647361 }, { "content": " Err(nix::Error::Sys(errno)) => {\n\n self.map = SealedMap::Unmapped;\n\n Err(io::Error::from_raw_os_error(errno as i32))\n\n }\n\n Err(_) => unreachable!(),\n\n }\n\n }\n\n SealedMap::Unmapped => Ok(()),\n\n }\n\n }\n\n\n\n fn update_map(&mut self) -> Result<(), io::Error> {\n\n try!(self.unmap());\n\n\n\n let size = try!(self.get_size());\n\n\n\n let p = match mmap(ptr::null_mut(),\n\n size as size_t,\n\n PROT_READ,\n\n MAP_PRIVATE,\n", "file_path": "src/lib.rs", "rank": 25, "score": 4.949656669941748 }, { "content": "\n\n {\n\n let s = smfd.as_slice().unwrap();\n\n assert_eq!(s.len(), 1024);\n\n assert_eq!(s[0], 12u8);\n\n }\n\n }\n\n\n\n #[test]\n\n fn test_into_raw_fd() {\n\n let mut mfd = MemFd::new(\"test\").unwrap();\n\n mfd.set_size(1024).unwrap();\n\n\n\n {\n\n let s = mfd.as_mut_slice().unwrap();\n\n assert_eq!(s.len(), 1024);\n\n s[0] = 12u8;\n\n }\n\n\n\n let fd = mfd.into_raw_fd();\n", "file_path": "src/lib.rs", "rank": 27, "score": 4.420740494055533 }, { "content": " assert!(fd != -1);\n\n\n\n let smfd = SealedMemFd::new(fd).unwrap();\n\n assert_eq!(smfd.as_raw_fd(), fd);\n\n\n\n assert_eq!(smfd.get_size().unwrap(), 1024);\n\n\n\n {\n\n let s = smfd.as_slice().unwrap();\n\n assert_eq!(s.len(), 1024);\n\n assert_eq!(s[0], 12u8);\n\n }\n\n\n\n assert_eq!(smfd.into_raw_fd(), fd);\n\n let _ = SealedMemFd::new(fd).unwrap();\n\n }\n\n\n\n #[test]\n\n fn test_clone() {\n\n let clone = {\n", "file_path": "src/lib.rs", "rank": 28, "score": 4.277328500916709 }, { "content": " let mut mfd = MemFd::new(\"test\").unwrap();\n\n mfd.set_size(1024).unwrap();\n\n\n\n {\n\n let s = mfd.as_mut_slice().unwrap();\n\n assert_eq!(s.len(), 1024);\n\n s[0] = 12u8;\n\n }\n\n\n\n let smfd = mfd.seal().unwrap();\n\n\n\n {\n\n let s = smfd.as_slice().unwrap();\n\n assert_eq!(s.len(), 1024);\n\n assert_eq!(s[0], 12u8);\n\n }\n\n\n\n smfd.clone().unwrap()\n\n };\n\n\n\n {\n\n let s = clone.as_slice().unwrap();\n\n assert_eq!(s.len(), 1024);\n\n assert_eq!(s[0], 12u8);\n\n }\n\n }\n\n}\n\n\n\n#[derive(Debug)]\n", "file_path": "src/lib.rs", "rank": 29, "score": 3.6274200374848844 }, { "content": " let mut mfd = MemFd::new(\"test\").unwrap();\n\n mfd.set_size(1024).unwrap();\n\n\n\n let s = mfd.as_mut_slice().unwrap();\n\n assert_eq!(s.len(), 1024);\n\n }\n\n\n\n #[test]\n\n fn test_seal() {\n\n let mut mfd = MemFd::new(\"test\").unwrap();\n\n mfd.set_size(1024).unwrap();\n\n\n\n {\n\n let s = mfd.as_mut_slice().unwrap();\n\n assert_eq!(s.len(), 1024);\n\n s[0] = 12u8;\n\n }\n\n\n\n let smfd = mfd.seal().unwrap();\n\n assert_eq!(smfd.get_size().unwrap(), 1024);\n", "file_path": "src/lib.rs", "rank": 30, "score": 3.4549474652910854 }, { "content": " #[test]\n\n fn test_new() {\n\n MemFd::new(\"test\").unwrap();\n\n }\n\n\n\n #[test]\n\n fn test_set_get_size() {\n\n let mut mfd = MemFd::new(\"test\").unwrap();\n\n assert_eq!(mfd.get_size().unwrap(), 0);\n\n mfd.set_size(1024).unwrap();\n\n assert_eq!(mfd.get_size().unwrap(), 1024);\n\n }\n\n\n\n #[test]\n\n fn test_shrink() {\n\n let mut mfd = MemFd::new(\"test\").unwrap();\n\n mfd.set_size(1024).unwrap();\n\n mfd.set_size(512).unwrap();\n\n assert_eq!(mfd.get_size().unwrap(), 512);\n\n }\n", "file_path": "src/lib.rs", "rank": 31, "score": 2.886143174250661 }, { "content": "\n\n #[test]\n\n fn test_grow() {\n\n let mut mfd = MemFd::new(\"test\").unwrap();\n\n mfd.set_size(1024).unwrap();\n\n mfd.set_size(2048).unwrap();\n\n assert_eq!(mfd.get_size().unwrap(), 2048);\n\n }\n\n\n\n #[test]\n\n fn test_as_slice() {\n\n let mut mfd = MemFd::new(\"test\").unwrap();\n\n mfd.set_size(1024).unwrap();\n\n\n\n let s = mfd.as_slice().unwrap();\n\n assert_eq!(s.len(), 1024);\n\n }\n\n\n\n #[test]\n\n fn test_as_mut_slice() {\n", "file_path": "src/lib.rs", "rank": 32, "score": 2.446145671318151 } ]
Rust
src/router/messaging.rs
verkehrsministerium/autobahnkreuz-rs
03d194257709ad9ef1226141b052bf9c0f2408d6
use crate::router::{ConnectionHandler, ConnectionState}; use ws::{CloseCode, Handler, Message as WSMessage, Request, Response, Result as WSResult}; use crate::messages::{ErrorDetails, ErrorType, Message, Reason}; use rmp_serde::Deserializer as RMPDeserializer; use serde_json; use serde::Deserialize; use std::collections::HashMap; use std::io::Cursor; use crate::{Error, ErrorKind, WampResult, ID}; impl ConnectionHandler { pub fn send_message(&self, message: Message) { self.router.send_message(self.info_id, message) } fn handle_message(&mut self, message: Message) -> WampResult<()> { log::debug!("Received message {:?}", message); match message { Message::Hello(realm, details) => { self.handle_hello(realm, details)?; }, Message::Subscribe(request_id, options, topic) => { self.handle_subscribe(request_id, options, topic); } Message::Publish(request_id, options, topic, args, kwargs) => { self.handle_publish(request_id, options, topic, args, kwargs); } Message::Unsubscribe(request_id, topic_id) => { self.handle_unsubscribe(request_id, topic_id); } Message::Goodbye(details, reason) => { self.handle_goodbye(details, reason)?; }, Message::Register(_request_id, _options, _procedure) => { unimplemented!(); } Message::Unregister(_request_id, _procedure_id) => { unimplemented!(); } Message::Call(_request_id, _options, _procedure, _args, _kwargs) => { unimplemented!(); } Message::Yield(_invocation_id, _options, _args, _kwargs) => { unimplemented!(); } Message::Error(_e_type, _request_id, _details, _reason, _args, _kwargs) => { unimplemented!(); } t => Err(Error::new(ErrorKind::InvalidMessageType(t)))?, } Ok(()) } fn parse_message(&self, msg: WSMessage) -> WampResult<Message> { match msg { WSMessage::Text(payload) => match serde_json::from_str(&payload) { Ok(message) => Ok(message), Err(e) => Err(Error::new(ErrorKind::JSONError(e))), }, WSMessage::Binary(payload) => { let mut de = RMPDeserializer::new(Cursor::new(payload)); match Deserialize::deserialize(&mut de) { Ok(message) => Ok(message), Err(e) => Err(Error::new(ErrorKind::MsgPackError(e))), } } } } fn send_error(&self, err_type: ErrorType, request_id: ID, reason: Reason) { self.send_message(Message::Error(err_type, request_id, HashMap::new(), reason, None, None)); } fn send_abort(&self, reason: Reason) { self.send_message(Message::Abort(ErrorDetails::new(), reason)); } fn on_message_error(&self, error: Error) -> WSResult<()> { use std::error::Error as StdError; match error.get_kind() { ErrorKind::WSError(e) => Err(e)?, ErrorKind::URLError(_) => unimplemented!(), ErrorKind::HandshakeError(r) => { log::error!("Handshake error: {}", r); self.send_abort(r); self.terminate_connection()?; } ErrorKind::UnexpectedMessage(msg) => { log::error!("Unexpected Message: {}", msg); self.terminate_connection()?; } ErrorKind::ThreadError(_) => unimplemented!(), ErrorKind::ConnectionLost => unimplemented!(), ErrorKind::Closing(_) => { unimplemented!{} } ErrorKind::JSONError(e) => { log::error!("Could not parse JSON: {}", e); self.terminate_connection()?; } ErrorKind::MsgPackError(e) => { log::error!("Could not parse MsgPack: {}", e.description()); self.terminate_connection()?; } ErrorKind::MalformedData => unimplemented!(), ErrorKind::InvalidMessageType(msg) => { log::error!("Router unable to handle message {:?}", msg); self.terminate_connection()?; } ErrorKind::InvalidState(s) => { log::error!("Invalid State: {}", s); self.terminate_connection()?; } ErrorKind::Timeout => { log::error!("Connection timeout"); self.terminate_connection()?; } ErrorKind::ErrorReason(err_type, id, reason) => self.send_error(err_type, id, reason), } Ok(()) } } impl Handler for ConnectionHandler { fn on_request(&mut self, request: &Request) -> WSResult<Response> { log::info!("New request"); let mut response = match Response::from_request(request) { Ok(response) => response, Err(e) => { log::error!("Could not create response: {}", e); return Err(e); } }; self.process_protocol(request, &mut response)?; log::debug!("Sending response"); Ok(response) } fn on_message(&mut self, msg: WSMessage) -> WSResult<()> { log::debug!("Receveied message: {:?}", msg); let message = match self.parse_message(msg) { Err(e) => return self.on_message_error(e), Ok(m) => m, }; match self.handle_message(message) { Err(e) => self.on_message_error(e), _ => Ok(()), } } fn on_close(&mut self, code: CloseCode, reason: &str) { log::debug!("connection closed with {:?}: {}", code, reason); if let Ok(conn) = self.router.connection(self.info_id) { let state = conn.lock().unwrap().state.clone(); if state != ConnectionState::Disconnected { log::trace!("Client disconnected. Closing connection"); self.terminate_connection().ok(); } } } }
use crate::router::{ConnectionHandler, ConnectionState}; use ws::{CloseCode, Handler, Message as WSMessage, Request, Response, Result as WSResult}; use crate::messages::{ErrorDetails, ErrorType, Message, Reason}; use rmp_serde::Deserializer as RMPDeserializer; use serde_json; use serde::Deserialize; use std::collections::HashMap; use std::io::Cursor; use crate::{Error, ErrorKind, WampResult, ID}; impl ConnectionHandler { pub fn send_message(&self, message: Message) { self.router.send_message(self.info_id, message) } fn handle_message(&mut self, message: Message) -> WampResult<()> { log::debug!("Received message {:?}", message); match message { Message::Hello(realm, details) => { self.handle_hello(realm, details)?; }, Message::Subscribe(request_id, options, topic) => { self.handle_subscribe(request_id, options, topic); } Message::Publish(request_id, options, topic, args, kwargs) => { self.handle_publish(request_id, options, topic, args, kwargs); } Message::Unsubscribe(request_id, topic_id) => { self.handle_unsubscribe(request_id, topic_id); } Message::Goodbye(details, reason) => { self.handle_goodbye(details, reason)?; }, Message::Register(_request_id, _options, _procedure) => { unimplemented!(); } Message::Unregister(_request_id, _procedure_id) => { unimplemented!(); } Message::Call(_request_id, _options, _procedure, _args, _kwargs) => { unimplemented!(); } Message::Yield(_invocation_id, _options, _args, _kwargs) => { unimplemented!(); } Message::Error(_e_type, _request_id, _details, _reason, _args, _kwargs) => { unimplemented!(); } t => Err(Error::new(ErrorKind::InvalidMessageType(t)))?, } Ok(()) } fn parse_message(&self, msg: WSMessage) -> WampResult<Message> { match msg { WSMessage::Text(payload) => match serde_json::from_str(&payload) { Ok(message) => Ok(message), Err(e) => Err(Error::new(ErrorKind::JSONError(e))), }, WSMessage::Binary(payload) => { let mut de = RMPDeserializer::new(Cursor::new(payload)); match Deserialize::deserialize(&mut de) { Ok(message) => Ok(message), Err(e) => Err(Error::new(ErrorKind::MsgPackError(e))), } } } } fn send_error(&self, err_type: ErrorType, request_id: ID, reason: Reason) { self.send_message(Message::Error(err_type, request_id, HashMap::new(), reason, None, None)); } fn send_abort(&self, reason: Reason) { self.send_message(Message::Abort(ErrorDetails::new(), reason)); } fn on_message_error(&self, error: Error) -> WSResult<()> { use std::error::Error as StdError; match error.get_kind() { ErrorKind::WSError(e) => Err(e)?, ErrorKind::URLError(_) => unimplemented!(), ErrorKind::HandshakeError(r) => { log::error!("Handshake error: {}", r); self.send_abort(r); self.terminate_connection()?; } ErrorKind::UnexpectedMessage(msg) => { log::error!("Unexpected Message: {}", msg); self.terminate_connection()?; } ErrorKind::ThreadError(_) => unimplemented!(), ErrorKind::ConnectionLost => unimplemented!(), ErrorKind::Closing(_) => { unimplemented!{} } ErrorKind::JSONError(e) => { log::error!("Could not parse JSON: {}", e); self.terminate_connection()?; } ErrorKind::MsgPackError(e) => { log::error!("Could not parse MsgPack: {}", e.description()); self.terminate_connection()?; } ErrorKind::MalformedData => unimplemented!(), ErrorKind::InvalidMessageType(msg) => { log::error!("Router unable to handle message {:?}", msg); self.terminate_connection()?; } ErrorKind::InvalidState(s) => { log::error!("Invalid State: {}", s); self.terminate_connection()?; } ErrorKind::Timeout => { log::error!("Connection timeout"); self.terminate_connection()?; } ErrorKind::ErrorReason(err_type, id, reason) => self.send_error(err_type, id, reason), } Ok(()) } } impl Handler for ConnectionHandler { fn on_request(&mut self, request: &Request) -> WSResult<Response> { log::info!("New request"); let mut response = match Response::from_request(request) { Ok(response) => response, Err(e) => { log::error!("Could not create response: {}", e); return Err(e); } }; self.process_protocol(request, &mut response)?; log::debug!("Sending response"); Ok(response) } fn on_message(&mut self, msg: WSMessage) -> WSResult<()> { log::debug!("Receveied message: {:?}", msg);
match self.handle_message(message) { Err(e) => self.on_message_error(e), _ => Ok(()), } } fn on_close(&mut self, code: CloseCode, reason: &str) { log::debug!("connection closed with {:?}: {}", code, reason); if let Ok(conn) = self.router.connection(self.info_id) { let state = conn.lock().unwrap().state.clone(); if state != ConnectionState::Disconnected { log::trace!("Client disconnected. Closing connection"); self.terminate_connection().ok(); } } } }
let message = match self.parse_message(msg) { Err(e) => return self.on_message_error(e), Ok(m) => m, };
assignment_statement
[ { "content": "pub fn send_message_msgpack(sender: &Sender, message: &Message) -> WSResult<()> {\n\n // Send the message\n\n let mut buf: Vec<u8> = Vec::new();\n\n message\n\n .serialize(&mut Serializer::with(&mut buf, StructMapWriter))\n\n .unwrap();\n\n sender.send(WSMessage::Binary(buf))\n\n}\n", "file_path": "src/router/machine.rs", "rank": 0, "score": 129030.9092260878 }, { "content": "pub fn send_message_json(sender: &Sender, message: &Message) -> WSResult<()> {\n\n // Send the message\n\n let text = serde_json::to_string(message).unwrap();\n\n log::info!(\"sending {}\", text);\n\n sender.send(WSMessage::Text(text))\n\n}\n\n\n", "file_path": "src/router/machine.rs", "rank": 1, "score": 129030.9092260878 }, { "content": "pub trait ArgList {\n\n fn get_int(&self, index: usize) -> CallResult<Option<i64>>;\n\n fn get_string(&self, index: usize) -> CallResult<Option<&str>>;\n\n fn verify_len(&self, expected_len: usize) -> CallResult<()>;\n\n}\n\n\n", "file_path": "src/messages/types/value.rs", "rank": 2, "score": 83194.5213677649 }, { "content": "pub trait ArgDict {\n\n fn get_int(&self, key: &str) -> CallResult<Option<i64>>;\n\n fn get_string<'a>(&'a self, key: &str) -> CallResult<Option<&'a str>>;\n\n}\n\n\n\nimpl ArgList for List {\n\n fn get_int(&self, index: usize) -> CallResult<Option<i64>> {\n\n let value = self.get(index);\n\n match value {\n\n Some(value) => {\n\n if let Value::Integer(value) = *value {\n\n Ok(Some(value))\n\n } else {\n\n Err(CallError::new(\n\n Reason::InvalidArgument,\n\n Some(vec![Value::String(format!(\n\n \"Expected integer, got {}\",\n\n value.summarize()\n\n ))]),\n\n None,\n", "file_path": "src/messages/types/value.rs", "rank": 3, "score": 83194.5213677649 }, { "content": "struct ReasonVisitor;\n\n\n\nimpl Reason {\n\n #[inline]\n\n fn get_string(&self) -> &str {\n\n match *self {\n\n Reason::InvalidURI => \"wamp.error.invalid_uri\",\n\n Reason::NoSuchProcedure => \"wamp.error.no_such_procedure\",\n\n Reason::ProcedureAlreadyExists => \"wamp.error.procedure_already_exists\",\n\n Reason::NoSuchRegistration => \"wamp.error.no_such_registration\",\n\n Reason::NoSuchSubscription => \"wamp.error.no_such_subscription\",\n\n Reason::InvalidArgument => \"wamp.error.invalid_argument\",\n\n Reason::SystemShutdown => \"wamp.error.system_shutdown\",\n\n Reason::CloseRealm => \"wamp.error.close_realm\",\n\n Reason::GoodbyeAndOut => \"wamp.error.goodbye_and_out\",\n\n Reason::NotAuthorized => \"wamp.error.not_authorized\",\n\n Reason::AuthorizationFailed => \"wamp.error.authorization_failed\",\n\n Reason::NoSuchRealm => \"wamp.error.no_such_realm\",\n\n Reason::NoSuchRole => \"wamp.error.no_such_role\",\n\n Reason::Cancelled => \"wamp.error.cancelled\",\n", "file_path": "src/messages/types/error.rs", "rank": 4, "score": 72846.57445770508 }, { "content": "fn random_id() -> u64 {\n\n let mut rng = thread_rng();\n\n // TODO make this a constant\n\n let between = Uniform::new(0, 1u64.rotate_left(56) - 1);\n\n between.sample(&mut rng)\n\n}\n\n\n\nimpl Default for Router {\n\n fn default() -> Self {\n\n Self::new()\n\n }\n\n}\n\n\n\nimpl Router {\n\n #[inline]\n\n pub fn new() -> Router {\n\n let node_id_msg = \"Please specify a NODE_ID >= 0 via an environment variable!\";\n\n let re = Regex::new(r\"\\d+\").unwrap();\n\n let node_id_str = env::var(\"NODE_ID\").expect(node_id_msg);\n\n let mut node_id = re.find(node_id_str.as_str())\n", "file_path": "src/router/mod.rs", "rank": 5, "score": 64848.58539195882 }, { "content": "fn is_not(b: &bool) -> bool {\n\n !*b\n\n}\n\n\n\n/**************************\n\n Structs\n\n**************************/\n\n\n\n/// The policies that can be used for matching a uri pattern.\n\n#[derive(PartialEq, Debug, Clone, Copy)]\n\npub enum MatchingPolicy {\n\n /// The given pattern matches any URI that has it as a prefix\n\n Prefix,\n\n /// The given pattern contains at least one 'wildcard' segment which can match any segment at the same location\n\n Wildcard,\n\n /// The given pattern only matches URIs that are identical.\n\n Strict,\n\n}\n\n\n\n/// The policies that dictate how invocations are distributed amongst shared registrations\n", "file_path": "src/messages/types/mod.rs", "rank": 6, "score": 57866.41320368758 }, { "content": "struct ErrorTypeVisitor;\n", "file_path": "src/messages/types/error.rs", "rank": 7, "score": 54016.224552988875 }, { "content": " }\n\n}\n\n\n\nimpl ErrorDetails {\n\n pub fn new() -> ErrorDetails {\n\n ErrorDetails { message: None }\n\n }\n\n\n\n pub fn new_with_message(message: &str) -> ErrorDetails {\n\n ErrorDetails {\n\n message: Some(message.to_string()),\n\n }\n\n }\n\n}\n\n\n\nimpl SubscribeOptions {\n\n pub fn new() -> SubscribeOptions {\n\n SubscribeOptions {\n\n pattern_match: MatchingPolicy::Strict,\n\n }\n", "file_path": "src/messages/types/options.rs", "rank": 8, "score": 52292.46429459766 }, { "content": " trustlevel: None,\n\n topic: None,\n\n }\n\n }\n\n\n\n pub fn new_with_topic(topic: URI) -> EventDetails {\n\n EventDetails {\n\n publisher: None,\n\n trustlevel: None,\n\n topic: Some(topic),\n\n }\n\n }\n\n}\n\n\n\nimpl InvocationDetails {\n\n pub fn new() -> InvocationDetails {\n\n InvocationDetails { procedure: None }\n\n }\n\n}\n\n\n\nimpl ResultDetails {\n\n pub fn new() -> ResultDetails {\n\n ResultDetails {}\n\n }\n\n}\n", "file_path": "src/messages/types/options.rs", "rank": 9, "score": 52287.78258896537 }, { "content": " }\n\n }\n\n}\n\n\n\nimpl CallOptions {\n\n pub fn new() -> CallOptions {\n\n CallOptions {}\n\n }\n\n}\n\n\n\nimpl YieldOptions {\n\n pub fn new() -> YieldOptions {\n\n YieldOptions {}\n\n }\n\n}\n\n\n\nimpl EventDetails {\n\n pub fn new() -> EventDetails {\n\n EventDetails {\n\n publisher: None,\n", "file_path": "src/messages/types/options.rs", "rank": 10, "score": 52283.50035684211 }, { "content": "use super::{is_not, ClientRoles, InvocationPolicy, MatchingPolicy, RouterRoles, URI};\n\nuse serde::{Serialize, Deserialize};\n\n\n\n#[derive(Serialize, Deserialize, PartialEq, Clone, Debug, Default)]\n\npub struct HelloDetails {\n\n #[serde(default, skip_serializing_if = \"Option::is_none\")]\n\n agent: Option<String>,\n\n roles: ClientRoles,\n\n}\n\n\n\n#[derive(Serialize, Deserialize, PartialEq, Clone, Debug, Default)]\n\npub struct WelcomeDetails {\n\n #[serde(default, skip_serializing_if = \"Option::is_none\")]\n\n agent: Option<String>,\n\n roles: RouterRoles,\n\n}\n\n\n\n#[derive(Serialize, Deserialize, PartialEq, Clone, Debug, Default)]\n\npub struct ErrorDetails {\n\n #[serde(default, skip_serializing_if = \"Option::is_none\")]\n", "file_path": "src/messages/types/options.rs", "rank": 11, "score": 52282.8122903021 }, { "content": "}\n\n\n\n#[derive(Serialize, Deserialize, PartialEq, Clone, Debug, Default)]\n\npub struct InvocationDetails {\n\n #[serde(default, skip_serializing_if = \"Option::is_none\")]\n\n pub procedure: Option<URI>,\n\n}\n\n\n\n#[derive(PartialEq, Clone, Debug, Default, Serialize, Deserialize)]\n\npub struct ResultDetails {}\n\n\n\nimpl HelloDetails {\n\n pub fn new(roles: ClientRoles) -> HelloDetails {\n\n HelloDetails {\n\n roles: roles,\n\n agent: None,\n\n }\n\n }\n\n\n\n pub fn new_with_agent(roles: ClientRoles, agent: &str) -> HelloDetails {\n", "file_path": "src/messages/types/options.rs", "rank": 12, "score": 52281.95245660706 }, { "content": " }\n\n}\n\n\n\nimpl PublishOptions {\n\n pub fn new(acknowledge: bool) -> PublishOptions {\n\n PublishOptions {\n\n acknowledge: acknowledge,\n\n }\n\n }\n\n\n\n pub fn should_acknowledge(&self) -> bool {\n\n self.acknowledge\n\n }\n\n}\n\n\n\nimpl RegisterOptions {\n\n pub fn new() -> RegisterOptions {\n\n RegisterOptions {\n\n pattern_match: MatchingPolicy::Strict,\n\n invocation_policy: InvocationPolicy::Single,\n", "file_path": "src/messages/types/options.rs", "rank": 13, "score": 52279.463652925886 }, { "content": " #[serde(default, rename = \"invoke\", skip_serializing_if = \"InvocationPolicy::is_single\")]\n\n pub invocation_policy: InvocationPolicy,\n\n}\n\n\n\n#[derive(PartialEq, Clone, Debug, Default, Serialize, Deserialize)]\n\npub struct CallOptions {}\n\n\n\n#[derive(PartialEq, Clone, Debug, Default, Serialize, Deserialize)]\n\npub struct YieldOptions {}\n\n\n\n#[derive(Serialize, Clone, Deserialize, PartialEq, Debug, Default)]\n\npub struct EventDetails {\n\n #[serde(default, skip_serializing_if = \"Option::is_none\")]\n\n publisher: Option<String>,\n\n\n\n #[serde(default, skip_serializing_if = \"Option::is_none\")]\n\n trustlevel: Option<u64>,\n\n\n\n #[serde(default, skip_serializing_if = \"Option::is_none\")]\n\n pub topic: Option<URI>,\n", "file_path": "src/messages/types/options.rs", "rank": 14, "score": 52279.03557817834 }, { "content": " message: Option<String>,\n\n}\n\n\n\n#[derive(Serialize, Deserialize, PartialEq, Clone, Debug, Default)]\n\npub struct SubscribeOptions {\n\n #[serde(default, rename = \"match\", skip_serializing_if = \"MatchingPolicy::is_strict\")]\n\n pub pattern_match: MatchingPolicy,\n\n}\n\n\n\n#[derive(Serialize, Deserialize, PartialEq, Clone, Debug, Default)]\n\npub struct PublishOptions {\n\n #[serde(default, skip_serializing_if = \"is_not\")]\n\n acknowledge: bool,\n\n}\n\n\n\n#[derive(Serialize, Deserialize, PartialEq, Clone, Debug, Default)]\n\npub struct RegisterOptions {\n\n #[serde(default, rename = \"match\", skip_serializing_if = \"MatchingPolicy::is_strict\")]\n\n pub pattern_match: MatchingPolicy,\n\n\n", "file_path": "src/messages/types/options.rs", "rank": 15, "score": 52277.826206140475 }, { "content": " HelloDetails {\n\n roles: roles,\n\n agent: Some(agent.to_string()),\n\n }\n\n }\n\n}\n\n\n\nimpl WelcomeDetails {\n\n pub fn new(roles: RouterRoles) -> WelcomeDetails {\n\n WelcomeDetails {\n\n roles: roles,\n\n agent: None,\n\n }\n\n }\n\n\n\n pub fn new_with_agent(roles: RouterRoles, agent: &str) -> WelcomeDetails {\n\n WelcomeDetails {\n\n roles: roles,\n\n agent: Some(agent.to_string()),\n\n }\n", "file_path": "src/messages/types/options.rs", "rank": 16, "score": 52277.07635613482 }, { "content": " Publish,\n\n Register,\n\n Unregister,\n\n Invocation,\n\n Call,\n\n}\n\n\n\nimpl CallError {\n\n #[inline]\n\n pub fn new(reason: Reason, args: Option<List>, kwargs: Option<Dict>) -> CallError {\n\n CallError {\n\n reason: reason,\n\n args: args,\n\n kwargs: kwargs,\n\n }\n\n }\n\n\n\n pub fn into_tuple(self) -> (Reason, Option<List>, Option<Dict>) {\n\n (self.reason, self.args, self.kwargs)\n\n }\n", "file_path": "src/messages/types/error.rs", "rank": 17, "score": 52076.104105291844 }, { "content": " D: serde::Deserializer<'de>,\n\n {\n\n deserializer.deserialize_u64(ErrorTypeVisitor)\n\n }\n\n}\n\n\n\nimpl<'de> serde::de::Visitor<'de> for ErrorTypeVisitor {\n\n type Value = ErrorType;\n\n\n\n fn expecting(&self, formatter: &mut fmt::Formatter) -> fmt::Result {\n\n formatter.write_str(\"Integer representing an error type\")\n\n }\n\n\n\n #[inline]\n\n fn visit_u64<E>(self, value: u64) -> Result<ErrorType, E>\n\n where\n\n E: serde::de::Error,\n\n {\n\n match value {\n\n 32 => Ok(ErrorType::Subscribe),\n", "file_path": "src/messages/types/error.rs", "rank": 18, "score": 52072.657410849395 }, { "content": "\n\n fn expecting(&self, formatter: &mut fmt::Formatter) -> fmt::Result {\n\n formatter.write_str(\"error reason uri\")\n\n }\n\n\n\n #[inline]\n\n fn visit_str<E>(self, value: &str) -> Result<Reason, E>\n\n where\n\n E: serde::de::Error,\n\n {\n\n match value {\n\n \"wamp.error.invalid_uri\" => Ok(Reason::InvalidURI),\n\n \"wamp.error.no_such_procedure\" => Ok(Reason::NoSuchProcedure),\n\n \"wamp.error.procedure_already_exists\" => Ok(Reason::ProcedureAlreadyExists),\n\n \"wamp.error.no_such_registration\" => Ok(Reason::NoSuchRegistration),\n\n \"wamp.error.no_such_subscription\" => Ok(Reason::NoSuchSubscription),\n\n \"wamp.error.invalid_argument\" => Ok(Reason::InvalidArgument),\n\n \"wamp.error.system_shutdown\" => Ok(Reason::SystemShutdown),\n\n \"wamp.error.close_realm\" => Ok(Reason::CloseRealm),\n\n \"wamp.error.goodbye_and_out\" => Ok(Reason::GoodbyeAndOut),\n", "file_path": "src/messages/types/error.rs", "rank": 19, "score": 52072.26591694839 }, { "content": "\n\n #[inline]\n\n pub fn get_reason(&self) -> &Reason {\n\n &self.reason\n\n }\n\n\n\n #[inline]\n\n pub fn get_args(&self) -> &Option<List> {\n\n &self.args\n\n }\n\n\n\n #[inline]\n\n pub fn get_kwargs(&self) -> &Option<Dict> {\n\n &self.kwargs\n\n }\n\n}\n\n\n", "file_path": "src/messages/types/error.rs", "rank": 20, "score": 52070.787097484215 }, { "content": "impl serde::Serialize for Reason {\n\n fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>\n\n where\n\n S: serde::Serializer,\n\n {\n\n serializer.serialize_str(self.get_string())\n\n }\n\n}\n\n\n\nimpl<'de> serde::Deserialize<'de> for Reason {\n\n fn deserialize<D>(deserializer: D) -> Result<Reason, D::Error>\n\n where\n\n D: serde::Deserializer<'de>,\n\n {\n\n deserializer.deserialize_str(ReasonVisitor)\n\n }\n\n}\n\n\n\nimpl<'de> serde::de::Visitor<'de> for ReasonVisitor {\n\n type Value = Reason;\n", "file_path": "src/messages/types/error.rs", "rank": 21, "score": 52070.031173303425 }, { "content": " Cancelled,\n\n OptionNotAllowed,\n\n NoEligibleCallee,\n\n OptionDisallowedDiscloseMe,\n\n NetworkFailure,\n\n NormalClose,\n\n CustomReason(URI),\n\n}\n\n\n\n#[derive(Debug)]\n\npub struct CallError {\n\n reason: Reason,\n\n args: Option<List>,\n\n kwargs: Option<Dict>,\n\n}\n\n\n\n#[derive(Hash, Eq, PartialEq, Clone, Debug)]\n\npub enum ErrorType {\n\n Subscribe,\n\n Unsubscribe,\n", "file_path": "src/messages/types/error.rs", "rank": 22, "score": 52069.47743251957 }, { "content": " \"wamp.error.not_authorized\" => Ok(Reason::NotAuthorized),\n\n \"wamp.error.authorization_failed\" => Ok(Reason::AuthorizationFailed),\n\n \"wamp.error.no_such_realm\" => Ok(Reason::NoSuchRealm),\n\n \"wamp.error.no_such_role\" => Ok(Reason::NoSuchRole),\n\n \"wamp.error.cancelled\" => Ok(Reason::Cancelled),\n\n \"wamp.error.option_not_allowed\" => Ok(Reason::OptionNotAllowed),\n\n \"wamp.error.no_eligible_callee\" => Ok(Reason::NoEligibleCallee),\n\n \"wamp.error.option-disallowed.disclose_me\" => Ok(Reason::OptionDisallowedDiscloseMe),\n\n \"wamp.error.network_failure\" => Ok(Reason::NetworkFailure),\n\n \"wamp.close.normal\" => Ok(Reason::NormalClose),\n\n x => Ok(Reason::CustomReason(URI::new(x))),\n\n }\n\n }\n\n}\n\n\n\n/*-------------------------\n\n ErrorType\n\n-------------------------*/\n\n\n\nimpl serde::Serialize for ErrorType {\n", "file_path": "src/messages/types/error.rs", "rank": 23, "score": 52068.484121200585 }, { "content": " Reason::OptionNotAllowed => \"wamp.error.option_not_allowed\",\n\n Reason::NoEligibleCallee => \"wamp.error.no_eligible_callee\",\n\n Reason::OptionDisallowedDiscloseMe => \"wamp.error.option-disallowed.disclose_me\",\n\n Reason::NetworkFailure => \"wamp.error.network_failure\",\n\n Reason::NormalClose => \"wamp.close.normal\",\n\n Reason::CustomReason(ref reason) => &reason.uri,\n\n }\n\n }\n\n}\n\n\n\nimpl fmt::Display for Reason {\n\n fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {\n\n write!(f, \"{}\", self.get_string())\n\n }\n\n}\n\n\n\n/*-------------------------\n\n Reason\n\n-------------------------*/\n\n\n", "file_path": "src/messages/types/error.rs", "rank": 24, "score": 52068.38551068396 }, { "content": " 34 => Ok(ErrorType::Unsubscribe),\n\n 16 => Ok(ErrorType::Publish),\n\n 64 => Ok(ErrorType::Register),\n\n 66 => Ok(ErrorType::Unregister),\n\n 68 => Ok(ErrorType::Invocation),\n\n 48 => Ok(ErrorType::Call),\n\n x => Err(serde::de::Error::custom(format!(\n\n \"Invalid message error type: {}\",\n\n x\n\n ))),\n\n }\n\n }\n\n}\n", "file_path": "src/messages/types/error.rs", "rank": 25, "score": 52067.18807694678 }, { "content": " fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>\n\n where\n\n S: serde::Serializer,\n\n {\n\n let ser_int = match *self {\n\n ErrorType::Subscribe => 32,\n\n ErrorType::Unsubscribe => 34,\n\n ErrorType::Publish => 16,\n\n ErrorType::Register => 64,\n\n ErrorType::Unregister => 66,\n\n ErrorType::Invocation => 68,\n\n ErrorType::Call => 48,\n\n };\n\n serializer.serialize_u64(ser_int)\n\n }\n\n}\n\n\n\nimpl<'de> serde::Deserialize<'de> for ErrorType {\n\n fn deserialize<D>(deserializer: D) -> Result<ErrorType, D::Error>\n\n where\n", "file_path": "src/messages/types/error.rs", "rank": 26, "score": 52066.619657448486 }, { "content": "use super::{Dict, List};\n\nuse serde;\n\nuse std::fmt;\n\nuse crate::URI;\n\n\n\n#[derive(Hash, Eq, PartialEq, Clone, Debug)]\n\npub enum Reason {\n\n InvalidURI,\n\n NoSuchProcedure,\n\n ProcedureAlreadyExists,\n\n NoSuchRegistration,\n\n NoSuchSubscription,\n\n InvalidArgument,\n\n SystemShutdown,\n\n CloseRealm,\n\n GoodbyeAndOut,\n\n NotAuthorized,\n\n AuthorizationFailed,\n\n NoSuchRealm,\n\n NoSuchRole,\n", "file_path": "src/messages/types/error.rs", "rank": 27, "score": 52060.183973117695 }, { "content": "struct MatchingPolicyVisitor;\n", "file_path": "src/messages/types/mod.rs", "rank": 28, "score": 45407.26139469999 }, { "content": "/// Represents data that a pattern trie will hold\n\npub trait PatternData {\n\n fn get_id(&self) -> ID;\n\n}\n\n\n", "file_path": "src/router/pubsub/patterns.rs", "rank": 29, "score": 37811.90471185717 }, { "content": " ThreadError(SendError<messages::Message>),\n\n ConnectionLost,\n\n Closing(String),\n\n JSONError(JSONError),\n\n MsgPackError(MsgPackError),\n\n MalformedData,\n\n InvalidMessageType(Message),\n\n InvalidState(&'static str),\n\n Timeout,\n\n ErrorReason(ErrorType, ID, Reason),\n\n}\n\nimpl Error {\n\n pub fn new(kind: ErrorKind) -> Error {\n\n Error { kind: kind }\n\n }\n\n\n\n fn get_description(&self) -> String {\n\n format!(\"WAMP Error: {}\", self.kind.description())\n\n }\n\n\n", "file_path": "src/error.rs", "rank": 30, "score": 31190.65461120625 }, { "content": "use super::{ErrorType, Message, ID};\n\nuse crate::messages::{self, Reason};\n\nuse rmp_serde::decode::Error as MsgPackError;\n\nuse serde_json::Error as JSONError;\n\nuse std::fmt;\n\nuse std::sync::mpsc::SendError;\n\nuse url::ParseError;\n\nuse ws::Error as WSError;\n\n\n\n#[derive(Debug)]\n\npub struct Error {\n\n pub kind: ErrorKind,\n\n}\n\n\n\n#[derive(Debug)]\n\npub enum ErrorKind {\n\n WSError(WSError),\n\n URLError(ParseError),\n\n HandshakeError(Reason),\n\n UnexpectedMessage(&'static str), // Used when a peer receives another message before Welcome or Hello\n", "file_path": "src/error.rs", "rank": 31, "score": 31187.692182920495 }, { "content": " #[inline]\n\n pub fn get_kind(self) -> ErrorKind {\n\n self.kind\n\n }\n\n}\n\n\n\nimpl fmt::Display for Error {\n\n fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {\n\n write!(f, \"{}\", self.get_description())\n\n }\n\n}\n\n\n\nimpl ErrorKind {\n\n pub fn description(&self) -> String {\n\n match *self {\n\n ErrorKind::WSError(ref e) => e.to_string(),\n\n ErrorKind::URLError(ref e) => e.to_string(),\n\n ErrorKind::HandshakeError(ref r) => r.to_string(),\n\n ErrorKind::ThreadError(ref e) => e.to_string(),\n\n ErrorKind::JSONError(ref e) => e.to_string(),\n", "file_path": "src/error.rs", "rank": 32, "score": 31182.412767392136 }, { "content": " ErrorKind::MsgPackError(ref e) => e.to_string(),\n\n ErrorKind::ErrorReason(_, _, ref s) => s.to_string(),\n\n ErrorKind::Closing(ref s) => s.clone(),\n\n ErrorKind::UnexpectedMessage(s) | ErrorKind::InvalidState(s) => s.to_string(),\n\n ErrorKind::ConnectionLost => \"Connection Lost\".to_string(),\n\n ErrorKind::MalformedData => \"Malformed Data\".to_string(),\n\n ErrorKind::Timeout => \"Connection timed out\".to_string(),\n\n ErrorKind::InvalidMessageType(ref t) => format!(\"Invalid Message Type: {:?}\", t),\n\n }\n\n }\n\n}\n", "file_path": "src/error.rs", "rank": 33, "score": 31180.419886866846 }, { "content": "struct MessageVisitor;\n\n\n\nimpl MessageVisitor {\n\n fn visit_hello<'de, V>(&self, mut visitor: V) -> Result<Message, V::Error>\n\n where\n\n V: serde::de::SeqAccess<'de>,\n\n {\n\n let uri = try_or!(\n\n visitor.next_element(),\n\n \"Hello message ended before realm uri\"\n\n );\n\n let details = try_or!(\n\n visitor.next_element(),\n\n \"Hello message ended before details dict\"\n\n );\n\n Ok(Message::Hello(uri, details))\n\n }\n\n\n\n fn visit_welcome<'de, V>(&self, mut visitor: V) -> Result<Message, V::Error>\n\n where\n", "file_path": "src/messages/mod.rs", "rank": 34, "score": 30502.705246473273 }, { "content": "struct ConnectionHandler {\n\n info_id: u64,\n\n router: RouterInfo,\n\n subscribed_topics: Vec<(ID, ID)>,\n\n subscriptions: Arc<Mutex<SubscriptionPatternNode<u64>>>,\n\n}\n\n\n\n#[derive(Debug)]\n\npub struct ConnectionInfo {\n\n state: ConnectionState,\n\n protocol: String,\n\n id: u64,\n\n}\n\n\n\n#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]\n\npub enum ConnectionState {\n\n Initializing,\n\n Connected,\n\n ShuttingDown,\n\n Disconnected,\n\n}\n\n\n\nunsafe impl Sync for Router {}\n\n\n\nstatic WAMP_JSON: &'static str = \"wamp.2.json\";\n\nstatic WAMP_MSGPACK: &'static str = \"wamp.2.msgpack\";\n\n\n", "file_path": "src/router/mod.rs", "rank": 35, "score": 26957.05110364681 }, { "content": " fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>\n\n where\n\n S: serde::Serializer,\n\n {\n\n match *self {\n\n Message::Hello(ref realm, ref details) => (1, &realm, details).serialize(serializer),\n\n Message::Welcome(ref session, ref details) => {\n\n (2, session, details).serialize(serializer)\n\n }\n\n Message::Abort(ref details, ref reason) => (3, details, reason).serialize(serializer),\n\n Message::Goodbye(ref details, ref reason) => (6, details, reason).serialize(serializer),\n\n Message::Error(ref ty, id, ref details, ref reason, ref args, ref kwargs) => {\n\n serialize_with_args!(args, kwargs, serializer, 8, ty, id, details, reason)\n\n }\n\n Message::Subscribe(request_id, ref options, ref topic) => {\n\n (32, request_id, options, topic).serialize(serializer)\n\n }\n\n Message::Subscribed(request_id, subscription_id) => {\n\n (33, request_id, subscription_id).serialize(serializer)\n\n }\n", "file_path": "src/messages/mod.rs", "rank": 41, "score": 25472.964935055323 }, { "content": " visitor.next_element(),\n\n \"Error message ended before reason uri\"\n\n );\n\n let args = visitor.next_element()?;\n\n let kwargs = visitor.next_element()?;\n\n Ok(Message::Error(\n\n message_type,\n\n id,\n\n details,\n\n reason,\n\n args,\n\n kwargs,\n\n ))\n\n }\n\n\n\n fn visit_subscribe<'de, V>(&self, mut visitor: V) -> Result<Message, V::Error>\n\n where\n\n V: serde::de::SeqAccess<'de>,\n\n {\n\n let request = try_or!(\n", "file_path": "src/messages/mod.rs", "rank": 42, "score": 25472.537508521647 }, { "content": " Ok(Message::Yield(id, options, args, kwargs))\n\n }\n\n\n\n fn visit_result<'de, V>(&self, mut visitor: V) -> Result<Message, V::Error>\n\n where\n\n V: serde::de::SeqAccess<'de>,\n\n {\n\n let id = try_or!(\n\n visitor.next_element(),\n\n \"Result message ended before session id\"\n\n );\n\n let details = try_or!(\n\n visitor.next_element(),\n\n \"Result message ended before details dict\"\n\n );\n\n let args = visitor.next_element()?;\n\n let kwargs = visitor.next_element()?;\n\n Ok(Message::Result(id, details, args, kwargs))\n\n }\n\n}\n", "file_path": "src/messages/mod.rs", "rank": 43, "score": 25472.48245579225 }, { "content": "use std::fmt;\n\n\n\npub use crate::messages::types::*;\n\nuse serde;\n\nuse crate::ID;\n\nmod types;\n\n\n\nmacro_rules! try_or {\n\n ($e:expr, $msg:expr) => {\n\n match ($e)? {\n\n Some(val) => val,\n\n None => return Err(serde::de::Error::custom($msg)),\n\n }\n\n };\n\n}\n\n\n\n#[derive(Debug, Clone, PartialEq)]\n\npub enum Message {\n\n Hello(URI, HelloDetails),\n\n Welcome(ID, WelcomeDetails),\n", "file_path": "src/messages/mod.rs", "rank": 45, "score": 25470.082807731687 }, { "content": " visitor.next_element(),\n\n \"Publish message ended before session id\"\n\n );\n\n let details = try_or!(\n\n visitor.next_element(),\n\n \"Publish message ended before details dict\"\n\n );\n\n let topic = try_or!(\n\n visitor.next_element(),\n\n \"Publish message ended before topic uri\"\n\n );\n\n let args = visitor.next_element()?;\n\n let kwargs = visitor.next_element()?;\n\n Ok(Message::Publish(id, details, topic, args, kwargs))\n\n }\n\n\n\n fn visit_published<'de, V>(&self, mut visitor: V) -> Result<Message, V::Error>\n\n where\n\n V: serde::de::SeqAccess<'de>,\n\n {\n", "file_path": "src/messages/mod.rs", "rank": 46, "score": 25469.135945681683 }, { "content": " V: serde::de::SeqAccess<'de>,\n\n {\n\n let id = try_or!(\n\n visitor.next_element(),\n\n \"Call message ended before session id\"\n\n );\n\n let options = try_or!(\n\n visitor.next_element(),\n\n \"Call message ended before options dict\"\n\n );\n\n let topic = try_or!(\n\n visitor.next_element(),\n\n \"Call message ended before procedure uri\"\n\n );\n\n let args = visitor.next_element()?;\n\n let kwargs = visitor.next_element()?;\n\n Ok(Message::Call(id, options, topic, args, kwargs))\n\n }\n\n\n\n fn visit_invocation<'de, V>(&self, mut visitor: V) -> Result<Message, V::Error>\n", "file_path": "src/messages/mod.rs", "rank": 47, "score": 25468.912808170404 }, { "content": " Message::Result(id, ref details, ref args, ref kwargs) => {\n\n serialize_with_args!(args, kwargs, serializer, 50, id, details)\n\n }\n\n }\n\n }\n\n}\n\n\n\nimpl<'de> serde::Deserialize<'de> for Message {\n\n fn deserialize<D>(deserializer: D) -> Result<Message, D::Error>\n\n where\n\n D: serde::Deserializer<'de>,\n\n {\n\n log::debug!(\"deserializing message\");\n\n deserializer.deserialize_any(MessageVisitor)\n\n }\n\n}\n\n\n", "file_path": "src/messages/mod.rs", "rank": 48, "score": 25467.954501993096 }, { "content": " }\n\n Message::Register(request_id, ref options, ref procedure) => {\n\n (64, request_id, options, procedure).serialize(serializer)\n\n }\n\n Message::Registered(request_id, registration_id) => {\n\n (65, request_id, registration_id).serialize(serializer)\n\n }\n\n Message::Unregister(request_id, registration_id) => {\n\n (66, request_id, registration_id).serialize(serializer)\n\n }\n\n Message::Unregistered(request_id) => (67, request_id).serialize(serializer),\n\n Message::Call(id, ref options, ref topic, ref args, ref kwargs) => {\n\n serialize_with_args!(args, kwargs, serializer, 48, id, options, topic)\n\n }\n\n Message::Invocation(id, registration_id, ref details, ref args, ref kwargs) => {\n\n serialize_with_args!(args, kwargs, serializer, 68, id, registration_id, details)\n\n }\n\n Message::Yield(id, ref options, ref args, ref kwargs) => {\n\n serialize_with_args!(args, kwargs, serializer, 70, id, options)\n\n }\n", "file_path": "src/messages/mod.rs", "rank": 49, "score": 25467.604338757417 }, { "content": " details,\n\n args,\n\n kwargs,\n\n ))\n\n }\n\n\n\n fn visit_yield<'de, V>(&self, mut visitor: V) -> Result<Message, V::Error>\n\n where\n\n V: serde::de::SeqAccess<'de>,\n\n {\n\n let id = try_or!(\n\n visitor.next_element(),\n\n \"Yield message ended before session id\"\n\n );\n\n let options = try_or!(\n\n visitor.next_element(),\n\n \"Yield message ended before options dict\"\n\n );\n\n let args = visitor.next_element()?;\n\n let kwargs = visitor.next_element()?;\n", "file_path": "src/messages/mod.rs", "rank": 50, "score": 25467.392586075282 }, { "content": " visitor.next_element(),\n\n \"Event message ended before publication id\"\n\n );\n\n let details = try_or!(\n\n visitor.next_element(),\n\n \"Event message ended before details dict\"\n\n );\n\n let args = visitor.next_element()?;\n\n let kwargs = visitor.next_element()?;\n\n Ok(Message::Event(\n\n subscription_id,\n\n publication_id,\n\n details,\n\n args,\n\n kwargs,\n\n ))\n\n }\n\n\n\n fn visit_register<'de, V>(&self, mut visitor: V) -> Result<Message, V::Error>\n\n where\n", "file_path": "src/messages/mod.rs", "rank": 51, "score": 25467.187390419436 }, { "content": " visitor.next_element(),\n\n \"Subscribe message ended before request id\"\n\n );\n\n let options = try_or!(\n\n visitor.next_element(),\n\n \"Subscribe message ended before options dict\"\n\n );\n\n let topic = try_or!(\n\n visitor.next_element(),\n\n \"Subscribe message ended before topic uri\"\n\n );\n\n Ok(Message::Subscribe(request, options, topic))\n\n }\n\n\n\n fn visit_subscribed<'de, V>(&self, mut visitor: V) -> Result<Message, V::Error>\n\n where\n\n V: serde::de::SeqAccess<'de>,\n\n {\n\n let request = try_or!(\n\n visitor.next_element(),\n", "file_path": "src/messages/mod.rs", "rank": 52, "score": 25467.079685430916 }, { "content": " Ok(Message::Goodbye(details, reason))\n\n }\n\n\n\n fn visit_error<'de, V>(&self, mut visitor: V) -> Result<Message, V::Error>\n\n where\n\n V: serde::de::SeqAccess<'de>,\n\n {\n\n let message_type = try_or!(\n\n visitor.next_element(),\n\n \"Error message ended before message type\"\n\n );\n\n let id = try_or!(\n\n visitor.next_element(),\n\n \"Error message ended before session id\"\n\n );\n\n let details = try_or!(\n\n visitor.next_element(),\n\n \"Error message ended before details dict\"\n\n );\n\n let reason = try_or!(\n", "file_path": "src/messages/mod.rs", "rank": 53, "score": 25466.57734997334 }, { "content": " );\n\n Ok(Message::Unsubscribe(request, subscription))\n\n }\n\n\n\n fn visit_unsubscribed<'de, V>(&self, mut visitor: V) -> Result<Message, V::Error>\n\n where\n\n V: serde::de::SeqAccess<'de>,\n\n {\n\n let request = try_or!(\n\n visitor.next_element(),\n\n \"Unsubscribed message ended before request id\"\n\n );\n\n Ok(Message::Unsubscribed(request))\n\n }\n\n\n\n fn visit_publish<'de, V>(&self, mut visitor: V) -> Result<Message, V::Error>\n\n where\n\n V: serde::de::SeqAccess<'de>,\n\n {\n\n let id = try_or!(\n", "file_path": "src/messages/mod.rs", "rank": 54, "score": 25465.653471732436 }, { "content": " let registration_id = try_or!(\n\n visitor.next_element(),\n\n \"Registered message ended before registration id\"\n\n );\n\n Ok(Message::Unregister(request, registration_id))\n\n }\n\n\n\n fn visit_unregistered<'de, V>(&self, mut visitor: V) -> Result<Message, V::Error>\n\n where\n\n V: serde::de::SeqAccess<'de>,\n\n {\n\n let request = try_or!(\n\n visitor.next_element(),\n\n \"Registered message ended before request id\"\n\n );\n\n Ok(Message::Unregistered(request))\n\n }\n\n\n\n fn visit_call<'de, V>(&self, mut visitor: V) -> Result<Message, V::Error>\n\n where\n", "file_path": "src/messages/mod.rs", "rank": 55, "score": 25465.641722583543 }, { "content": " Message::Unsubscribe(request_id, subscription_id) => {\n\n (34, request_id, subscription_id).serialize(serializer)\n\n }\n\n Message::Unsubscribed(request_id) => (35, request_id).serialize(serializer),\n\n Message::Publish(id, ref details, ref topic, ref args, ref kwargs) => {\n\n serialize_with_args!(args, kwargs, serializer, 16, id, details, topic)\n\n }\n\n Message::Published(request_id, publication_id) => {\n\n (17, request_id, publication_id).serialize(serializer)\n\n }\n\n Message::Event(subscription_id, publication_id, ref details, ref args, ref kwargs) => {\n\n serialize_with_args!(\n\n args,\n\n kwargs,\n\n serializer,\n\n 36,\n\n subscription_id,\n\n publication_id,\n\n details\n\n )\n", "file_path": "src/messages/mod.rs", "rank": 56, "score": 25465.514931643876 }, { "content": " V: serde::de::SeqAccess<'de>,\n\n {\n\n let request = try_or!(\n\n visitor.next_element(),\n\n \"Register message ended before request id\"\n\n );\n\n let options = try_or!(\n\n visitor.next_element(),\n\n \"Register message ended before request options\"\n\n );\n\n let procedure = try_or!(\n\n visitor.next_element(),\n\n \"Register message ended before procedure\"\n\n );\n\n Ok(Message::Register(request, options, procedure))\n\n }\n\n\n\n fn visit_registered<'de, V>(&self, mut visitor: V) -> Result<Message, V::Error>\n\n where\n\n V: serde::de::SeqAccess<'de>,\n", "file_path": "src/messages/mod.rs", "rank": 58, "score": 25464.38608519397 }, { "content": " );\n\n let reason = try_or!(\n\n visitor.next_element(),\n\n \"Abort message ended before reason uri\"\n\n );\n\n Ok(Message::Abort(details, reason))\n\n }\n\n\n\n fn visit_goodbye<'de, V>(&self, mut visitor: V) -> Result<Message, V::Error>\n\n where\n\n V: serde::de::SeqAccess<'de>,\n\n {\n\n let details = try_or!(\n\n visitor.next_element(),\n\n \"Goodbye message ended before details dict\"\n\n );\n\n let reason = try_or!(\n\n visitor.next_element(),\n\n \"Goodbye message ended before reason uri\"\n\n );\n", "file_path": "src/messages/mod.rs", "rank": 59, "score": 25463.178847940246 }, { "content": " {\n\n let request = try_or!(\n\n visitor.next_element(),\n\n \"Registered message ended before request id\"\n\n );\n\n let registration_id = try_or!(\n\n visitor.next_element(),\n\n \"Registered message ended before registration id\"\n\n );\n\n Ok(Message::Registered(request, registration_id))\n\n }\n\n\n\n fn visit_unregister<'de, V>(&self, mut visitor: V) -> Result<Message, V::Error>\n\n where\n\n V: serde::de::SeqAccess<'de>,\n\n {\n\n let request = try_or!(\n\n visitor.next_element(),\n\n \"Registered message ended before request id\"\n\n );\n", "file_path": "src/messages/mod.rs", "rank": 60, "score": 25463.130658983147 }, { "content": "\n\n#[cfg(test)]\n\nmod test {\n\n use super::types::{CallOptions, ClientRoles, ErrorDetails, ErrorType, EventDetails,\n\n HelloDetails, InvocationDetails, PublishOptions, Reason, RegisterOptions,\n\n ResultDetails, RouterRoles, SubscribeOptions, Value, WelcomeDetails,\n\n YieldOptions, URI};\n\n use super::Message;\n\n use rmp_serde::Deserializer as RMPDeserializer;\n\n use rmp_serde::Serializer;\n\n use serde::{Deserialize, Serialize};\n\n use serde_json;\n\n use std::collections::HashMap;\n\n use crate::utils::StructMapWriter;\n\n\n\n macro_rules! two_way_test {\n\n ($message:expr, $s:expr) => {{\n\n let message = $message;\n\n assert_eq!(serde_json::to_string(&message).unwrap(), $s);\n\n assert_eq!(serde_json::from_str::<Message>($s).unwrap(), message);\n", "file_path": "src/messages/mod.rs", "rank": 61, "score": 25463.00682870434 }, { "content": " \"Subscribed message ended before request id\"\n\n );\n\n let subscription = try_or!(\n\n visitor.next_element(),\n\n \"Subscribed message ended before subscription id\"\n\n );\n\n Ok(Message::Subscribed(request, subscription))\n\n }\n\n\n\n fn visit_unsubscribe<'de, V>(&self, mut visitor: V) -> Result<Message, V::Error>\n\n where\n\n V: serde::de::SeqAccess<'de>,\n\n {\n\n let request = try_or!(\n\n visitor.next_element(),\n\n \"Unsubscribe message ended before request id\"\n\n );\n\n let subscription = try_or!(\n\n visitor.next_element(),\n\n \"Unsubscribe message ended before subscription id\"\n", "file_path": "src/messages/mod.rs", "rank": 63, "score": 25462.4708223205 }, { "content": " let request = try_or!(\n\n visitor.next_element(),\n\n \"Published message ended before request id\"\n\n );\n\n let publication = try_or!(\n\n visitor.next_element(),\n\n \"Published message ended before publication id\"\n\n );\n\n Ok(Message::Published(request, publication))\n\n }\n\n\n\n fn visit_event<'de, V>(&self, mut visitor: V) -> Result<Message, V::Error>\n\n where\n\n V: serde::de::SeqAccess<'de>,\n\n {\n\n let subscription_id = try_or!(\n\n visitor.next_element(),\n\n \"Event message ended before session subscription id\"\n\n );\n\n let publication_id = try_or!(\n", "file_path": "src/messages/mod.rs", "rank": 64, "score": 25462.33398487613 }, { "content": " V: serde::de::SeqAccess<'de>,\n\n {\n\n let session = try_or!(\n\n visitor.next_element(),\n\n \"Welcome message ended before session id\"\n\n );\n\n let details = try_or!(\n\n visitor.next_element(),\n\n \"Welcome message ended before details dict\"\n\n );\n\n Ok(Message::Welcome(session, details))\n\n }\n\n\n\n fn visit_abort<'de, V>(&self, mut visitor: V) -> Result<Message, V::Error>\n\n where\n\n V: serde::de::SeqAccess<'de>,\n\n {\n\n let details = try_or!(\n\n visitor.next_element(),\n\n \"Abort message ended before details dict\"\n", "file_path": "src/messages/mod.rs", "rank": 65, "score": 25461.443953990194 }, { "content": " \"[70,6131533,{},[\\\"a value\\\"]]\"\n\n );\n\n let mut kwargs = HashMap::new();\n\n kwargs.insert(\n\n \"key1\".to_string(),\n\n Value::List(vec![Value::UnsignedInteger(5)]),\n\n );\n\n two_way_test!(\n\n Message::Yield(6131533, YieldOptions::new(), Some(Vec::new()), Some(kwargs)),\n\n \"[70,6131533,{},[],{\\\"key1\\\":[5]}]\"\n\n )\n\n }\n\n\n\n #[test]\n\n fn serialize_result() {\n\n two_way_test!(\n\n Message::Result(7814135, ResultDetails::new(), None, None),\n\n \"[50,7814135,{}]\"\n\n );\n\n\n", "file_path": "src/messages/mod.rs", "rank": 66, "score": 25460.656467699002 }, { "content": " Abort(ErrorDetails, Reason),\n\n Goodbye(ErrorDetails, Reason),\n\n Error(ErrorType, ID, Dict, Reason, Option<List>, Option<Dict>),\n\n Subscribe(ID, SubscribeOptions, URI),\n\n Subscribed(ID, ID),\n\n Unsubscribe(ID, ID),\n\n Unsubscribed(ID),\n\n Publish(ID, PublishOptions, URI, Option<List>, Option<Dict>),\n\n Published(ID, ID),\n\n Event(ID, ID, EventDetails, Option<List>, Option<Dict>),\n\n Register(ID, RegisterOptions, URI),\n\n Registered(ID, ID),\n\n Unregister(ID, ID),\n\n Unregistered(ID),\n\n Call(ID, CallOptions, URI, Option<List>, Option<Dict>),\n\n Invocation(ID, ID, InvocationDetails, Option<List>, Option<Dict>),\n\n Yield(ID, YieldOptions, Option<List>, Option<Dict>),\n\n Result(ID, ResultDetails, Option<List>, Option<Dict>),\n\n}\n\n\n", "file_path": "src/messages/mod.rs", "rank": 67, "score": 25460.590799926205 }, { "content": " where\n\n V: serde::de::SeqAccess<'de>,\n\n {\n\n let id = try_or!(\n\n visitor.next_element(),\n\n \"Invocation message ended before session id\"\n\n );\n\n let registration_id = try_or!(\n\n visitor.next_element(),\n\n \"Invocation message ended before registration id\"\n\n );\n\n let details = try_or!(\n\n visitor.next_element(),\n\n \"Invocation message ended before details dict\"\n\n );\n\n let args = visitor.next_element()?;\n\n let kwargs = visitor.next_element()?;\n\n Ok(Message::Invocation(\n\n id,\n\n registration_id,\n", "file_path": "src/messages/mod.rs", "rank": 68, "score": 25460.47387461731 }, { "content": " two_way_test!(\n\n Message::Result(\n\n 764346,\n\n ResultDetails::new(),\n\n Some(vec![Value::String(\"a value\".to_string())]),\n\n None\n\n ),\n\n \"[50,764346,{},[\\\"a value\\\"]]\"\n\n );\n\n let mut kwargs = HashMap::new();\n\n kwargs.insert(\"key1\".to_string(), Value::List(vec![Value::Float(8.6)]));\n\n two_way_test!(\n\n Message::Result(764346, ResultDetails::new(), Some(Vec::new()), Some(kwargs)),\n\n \"[50,764346,{},[],{\\\"key1\\\":[8.6]}]\"\n\n )\n\n }\n\n\n\n}\n", "file_path": "src/messages/mod.rs", "rank": 69, "score": 25458.80567488768 }, { "content": "\n\nimpl<'de> serde::de::Visitor<'de> for MessageVisitor {\n\n type Value = Message;\n\n\n\n fn expecting(&self, formatter: &mut fmt::Formatter) -> fmt::Result {\n\n formatter.write_str(\"a message\")\n\n }\n\n\n\n fn visit_seq<V>(self, mut visitor: V) -> Result<Message, V::Error>\n\n where\n\n V: serde::de::SeqAccess<'de>,\n\n {\n\n log::debug!(\"visiting seq\");\n\n let message_type: u64 = try_or!(visitor.next_element(), \"No message type found\");\n\n log::debug!(\"visiting {}\", message_type);\n\n match message_type {\n\n 1 => self.visit_hello(visitor),\n\n 2 => self.visit_welcome(visitor),\n\n 3 => self.visit_abort(visitor),\n\n 6 => self.visit_goodbye(visitor),\n", "file_path": "src/messages/mod.rs", "rank": 70, "score": 25458.451013209404 }, { "content": " Message::Event(\n\n 764346,\n\n 3895494,\n\n EventDetails::new(),\n\n Some(vec![Value::String(\"a value\".to_string())]),\n\n None\n\n ),\n\n \"[36,764346,3895494,{},[\\\"a value\\\"]]\"\n\n );\n\n let mut kwargs = HashMap::new();\n\n kwargs.insert(\"key1\".to_string(), Value::List(vec![Value::Integer(-5)]));\n\n two_way_test!(\n\n Message::Event(\n\n 65675,\n\n 587495,\n\n EventDetails::new(),\n\n Some(Vec::new()),\n\n Some(kwargs)\n\n ),\n\n \"[36,65675,587495,{},[],{\\\"key1\\\":[-5]}]\"\n", "file_path": "src/messages/mod.rs", "rank": 71, "score": 25455.62312438974 }, { "content": " two_way_test!(\n\n Message::Abort(\n\n ErrorDetails::new_with_message(\"The realm does not exist\"),\n\n Reason::NoSuchRealm\n\n ),\n\n \"[3,{\\\"message\\\":\\\"The realm does not exist\\\"},\\\"wamp.error.no_such_realm\\\"]\"\n\n );\n\n }\n\n\n\n #[test]\n\n fn serialize_goodbye() {\n\n two_way_test!(\n\n Message::Goodbye(ErrorDetails::new(), Reason::GoodbyeAndOut),\n\n \"[6,{},\\\"wamp.error.goodbye_and_out\\\"]\"\n\n );\n\n two_way_test!(\n\n Message::Goodbye(\n\n ErrorDetails::new_with_message(\"The host is shutting down now\"),\n\n Reason::SystemShutdown\n\n ),\n", "file_path": "src/messages/mod.rs", "rank": 72, "score": 25455.351328504024 }, { "content": " Message::Invocation(\n\n 764346,\n\n 9823526,\n\n InvocationDetails::new(),\n\n Some(vec![Value::String(\"a value\".to_string())]),\n\n None\n\n ),\n\n \"[68,764346,9823526,{},[\\\"a value\\\"]]\"\n\n );\n\n let mut kwargs = HashMap::new();\n\n kwargs.insert(\n\n \"key1\".to_string(),\n\n Value::List(vec![Value::UnsignedInteger(5)]),\n\n );\n\n two_way_test!(\n\n Message::Invocation(\n\n 764346,\n\n 9823526,\n\n InvocationDetails::new(),\n\n Some(Vec::new()),\n", "file_path": "src/messages/mod.rs", "rank": 73, "score": 25455.278039415985 }, { "content": " two_way_test!(\n\n Message::Call(\n\n 764346,\n\n CallOptions::new(),\n\n URI::new(\"com.myapp.compute\"),\n\n Some(Vec::new()),\n\n Some(kwargs)\n\n ),\n\n \"[48,764346,{},\\\"com.myapp.compute\\\",[],{\\\"key1\\\":[5]}]\"\n\n )\n\n }\n\n\n\n #[test]\n\n fn serialize_invocation() {\n\n // two_way_test!(\n\n // Message::Invocation(7814135, 9823526, InvocationDetails::new(), None, None),\n\n // \"[68,7814135,9823526,{}]\"\n\n // );\n\n\n\n two_way_test!(\n", "file_path": "src/messages/mod.rs", "rank": 74, "score": 25454.608972819937 }, { "content": " \"[6,{\\\"message\\\":\\\"The host is shutting down now\\\"},\\\"wamp.error.system_shutdown\\\"]\"\n\n );\n\n }\n\n\n\n #[test]\n\n fn serialize_error() {\n\n two_way_test!(\n\n Message::Error(\n\n ErrorType::Subscribe,\n\n 713845233,\n\n HashMap::new(),\n\n Reason::NotAuthorized,\n\n None,\n\n None\n\n ),\n\n \"[8,32,713845233,{},\\\"wamp.error.not_authorized\\\"]\"\n\n );\n\n\n\n two_way_test!(\n\n Message::Error(\n", "file_path": "src/messages/mod.rs", "rank": 75, "score": 25454.396845111267 }, { "content": " Some(kwargs)\n\n ),\n\n \"[68,764346,9823526,{},[],{\\\"key1\\\":[5]}]\"\n\n )\n\n }\n\n\n\n #[test]\n\n fn serialize_yield() {\n\n two_way_test!(\n\n Message::Yield(6131533, YieldOptions::new(), None, None),\n\n \"[70,6131533,{}]\"\n\n );\n\n\n\n two_way_test!(\n\n Message::Yield(\n\n 6131533,\n\n YieldOptions::new(),\n\n Some(vec![Value::String(\"a value\".to_string())]),\n\n None\n\n ),\n", "file_path": "src/messages/mod.rs", "rank": 76, "score": 25454.396656762092 }, { "content": "macro_rules! serialize_with_args {\n\n ($args:expr, $kwargs:expr, $serializer:expr, $($item: expr),*) => (\n\n if let Some(ref kwargs) = *$kwargs {\n\n if let Some(ref args) = *$args {\n\n ( $($item,)* args, kwargs).serialize($serializer)\n\n } else {\n\n ( $($item,)* Vec::<u8>::new(), kwargs).serialize($serializer)\n\n }\n\n } else {\n\n if let Some(ref args) = *$args {\n\n ( $($item,)* args).serialize($serializer)\n\n } else {\n\n ( $($item,)*).serialize($serializer)\n\n }\n\n\n\n }\n\n );\n\n}\n\n\n\nimpl serde::Serialize for Message {\n", "file_path": "src/messages/mod.rs", "rank": 77, "score": 25454.104098769658 }, { "content": " None\n\n ),\n\n \"[48,7814135,{},\\\"com.myapp.ping\\\"]\"\n\n );\n\n\n\n two_way_test!(\n\n Message::Call(\n\n 764346,\n\n CallOptions::new(),\n\n URI::new(\"com.myapp.echo\"),\n\n Some(vec![Value::String(\"a value\".to_string())]),\n\n None\n\n ),\n\n \"[48,764346,{},\\\"com.myapp.echo\\\",[\\\"a value\\\"]]\"\n\n );\n\n let mut kwargs = HashMap::new();\n\n kwargs.insert(\n\n \"key1\".to_string(),\n\n Value::List(vec![Value::UnsignedInteger(5)]),\n\n );\n", "file_path": "src/messages/mod.rs", "rank": 78, "score": 25453.88485624917 }, { "content": " \"[16,453453,{},\\\"ca.dal.test.topic1\\\"]\"\n\n );\n\n\n\n two_way_test!(\n\n Message::Publish(\n\n 23934583,\n\n PublishOptions::new(true),\n\n URI::new(\"ca.dal.test.topic2\"),\n\n Some(vec![Value::String(\"a value\".to_string())]),\n\n None\n\n ),\n\n \"[16,23934583,{\\\"acknowledge\\\":true},\\\"ca.dal.test.topic2\\\",[\\\"a value\\\"]]\"\n\n );\n\n let mut kwargs = HashMap::new();\n\n kwargs.insert(\"key1\".to_string(), Value::List(vec![Value::Integer(-5)]));\n\n two_way_test!(\n\n Message::Publish(\n\n 3243542,\n\n PublishOptions::new(true),\n\n URI::new(\"ca.dal.test.topic3\"),\n", "file_path": "src/messages/mod.rs", "rank": 79, "score": 25452.87131198477 }, { "content": " ErrorType::Unsubscribe,\n\n 3746383,\n\n HashMap::new(),\n\n Reason::InvalidURI,\n\n Some(Vec::new()),\n\n None\n\n ),\n\n \"[8,34,3746383,{},\\\"wamp.error.invalid_uri\\\",[]]\"\n\n );\n\n\n\n two_way_test!(\n\n Message::Error(\n\n ErrorType::Register,\n\n 8534533,\n\n HashMap::new(),\n\n Reason::InvalidArgument,\n\n Some(Vec::new()),\n\n Some(HashMap::new())\n\n ),\n\n \"[8,64,8534533,{},\\\"wamp.error.invalid_argument\\\",[],{}]\"\n", "file_path": "src/messages/mod.rs", "rank": 80, "score": 25452.673816450853 }, { "content": " Some(Vec::new()),\n\n Some(kwargs)\n\n ),\n\n \"[16,3243542,{\\\"acknowledge\\\":true},\\\"ca.dal.test.topic3\\\",[],{\\\"key1\\\":[-5]}]\"\n\n )\n\n }\n\n\n\n #[test]\n\n fn serialize_published() {\n\n two_way_test!(Message::Published(23443, 564564), \"[17,23443,564564]\")\n\n }\n\n\n\n #[test]\n\n fn serialize_event() {\n\n two_way_test!(\n\n Message::Event(4353453, 298173, EventDetails::new(), None, None),\n\n \"[36,4353453,298173,{}]\"\n\n );\n\n\n\n two_way_test!(\n", "file_path": "src/messages/mod.rs", "rank": 81, "score": 25452.57167791966 }, { "content": " let mut buf: Vec<u8> = Vec::new();\n\n message\n\n .serialize(&mut Serializer::with(&mut buf, StructMapWriter))\n\n .unwrap();\n\n let mut de = RMPDeserializer::new(&buf[..]);\n\n let new_message: Message = Deserialize::deserialize(&mut de).unwrap();\n\n assert_eq!(new_message, message);\n\n }};\n\n }\n\n\n\n #[test]\n\n fn serialize_hello() {\n\n two_way_test!(\n\n Message::Hello(URI::new(\"ca.dal.wamp.test\"), HelloDetails::new(ClientRoles::new_basic())),\n\n \"[1,\\\"ca.dal.wamp.test\\\",{\\\"roles\\\":{\\\"publisher\\\":{\\\"features\\\":{}},\\\"subscriber\\\":{\\\"features\\\":{}},\\\"caller\\\":{\\\"features\\\":{}},\\\"callee\\\":{\\\"features\\\":{}}}}]\"\n\n );\n\n two_way_test!(\n\n Message::Hello(URI::new(\"ca.dal.wamp.test\"), HelloDetails::new_with_agent(ClientRoles::new(), \"dal_wamp\")),\n\n \"[1,\\\"ca.dal.wamp.test\\\",{\\\"agent\\\":\\\"dal_wamp\\\",\\\"roles\\\":{\\\"publisher\\\":{\\\"features\\\":{}},\\\"subscriber\\\":{\\\"features\\\":{\\\"pattern_based_subscription\\\":true}},\\\"caller\\\":{\\\"features\\\":{}},\\\"callee\\\":{\\\"features\\\":{}}}}]\"\n\n )\n", "file_path": "src/messages/mod.rs", "rank": 82, "score": 25451.95867033918 }, { "content": " }\n\n\n\n #[test]\n\n fn serialize_welcome() {\n\n two_way_test!(\n\n Message::Welcome(493782, WelcomeDetails::new(RouterRoles::new_basic())),\n\n \"[2,493782,{\\\"roles\\\":{\\\"dealer\\\":{},\\\"broker\\\":{}}}]\"\n\n );\n\n two_way_test!(\n\n Message::Welcome(493782, WelcomeDetails::new_with_agent(RouterRoles::new(), \"dal_wamp\")),\n\n \"[2,493782,{\\\"agent\\\":\\\"dal_wamp\\\",\\\"roles\\\":{\\\"dealer\\\":{\\\"features\\\":{\\\"pattern_based_registration\\\":true}},\\\"broker\\\":{\\\"features\\\":{\\\"pattern_based_subscription\\\":true}}}}]\"\n\n );\n\n }\n\n\n\n #[test]\n\n fn serialize_abort() {\n\n two_way_test!(\n\n Message::Abort(ErrorDetails::new(), Reason::NoSuchRealm),\n\n \"[3,{},\\\"wamp.error.no_such_realm\\\"]\"\n\n );\n", "file_path": "src/messages/mod.rs", "rank": 83, "score": 25451.69004479458 }, { "content": " 8 => self.visit_error(visitor),\n\n 32 => self.visit_subscribe(visitor),\n\n 33 => self.visit_subscribed(visitor),\n\n 34 => self.visit_unsubscribe(visitor),\n\n 35 => self.visit_unsubscribed(visitor),\n\n 16 => self.visit_publish(visitor),\n\n 17 => self.visit_published(visitor),\n\n 36 => self.visit_event(visitor),\n\n 64 => self.visit_register(visitor),\n\n 65 => self.visit_registered(visitor),\n\n 66 => self.visit_unregister(visitor),\n\n 67 => self.visit_unregistered(visitor),\n\n 48 => self.visit_call(visitor),\n\n 68 => self.visit_invocation(visitor),\n\n 70 => self.visit_yield(visitor),\n\n 50 => self.visit_result(visitor),\n\n _ => Err(serde::de::Error::custom(\"Unknown message type\")),\n\n }\n\n }\n\n}\n", "file_path": "src/messages/mod.rs", "rank": 84, "score": 25451.445900029255 }, { "content": " #[test]\n\n fn serialize_unsubscribe() {\n\n two_way_test!(Message::Unsubscribe(754, 8763), \"[34,754,8763]\")\n\n }\n\n\n\n #[test]\n\n fn serialize_unsubscribed() {\n\n two_way_test!(Message::Unsubscribed(675343), \"[35,675343]\")\n\n }\n\n\n\n #[test]\n\n fn serialize_publish() {\n\n two_way_test!(\n\n Message::Publish(\n\n 453453,\n\n PublishOptions::new(false),\n\n URI::new(\"ca.dal.test.topic1\"),\n\n None,\n\n None\n\n ),\n", "file_path": "src/messages/mod.rs", "rank": 85, "score": 25450.503090247894 }, { "content": " fn serialize_unregister() {\n\n two_way_test!(\n\n Message::Unregister(788923562, 2103333224),\n\n \"[66,788923562,2103333224]\"\n\n );\n\n }\n\n\n\n #[test]\n\n fn serialize_unregistered() {\n\n two_way_test!(Message::Unregistered(788923562), \"[67,788923562]\");\n\n }\n\n\n\n #[test]\n\n fn serialize_call() {\n\n two_way_test!(\n\n Message::Call(\n\n 7814135,\n\n CallOptions::new(),\n\n URI::new(\"com.myapp.ping\"),\n\n None,\n", "file_path": "src/messages/mod.rs", "rank": 86, "score": 25449.945189585127 }, { "content": " )\n\n }\n\n\n\n #[test]\n\n fn serialize_register() {\n\n two_way_test!(\n\n Message::Register(25349185, RegisterOptions::new(), URI::new(\"ca.test.proc\")),\n\n \"[64,25349185,{},\\\"ca.test.proc\\\"]\"\n\n );\n\n }\n\n\n\n #[test]\n\n fn serialize_registered() {\n\n two_way_test!(\n\n Message::Registered(25349185, 2103333224),\n\n \"[65,25349185,2103333224]\"\n\n );\n\n }\n\n\n\n #[test]\n", "file_path": "src/messages/mod.rs", "rank": 87, "score": 25447.387116549864 }, { "content": " );\n\n }\n\n\n\n #[test]\n\n fn serialize_subscribe() {\n\n two_way_test!(\n\n Message::Subscribe(\n\n 58944,\n\n SubscribeOptions::new(),\n\n URI::new(\"ca.dal.test.the_sub\")\n\n ),\n\n \"[32,58944,{},\\\"ca.dal.test.the_sub\\\"]\"\n\n )\n\n }\n\n\n\n #[test]\n\n fn serialize_subscribed() {\n\n two_way_test!(Message::Subscribed(47853, 48975938), \"[33,47853,48975938]\")\n\n }\n\n\n", "file_path": "src/messages/mod.rs", "rank": 88, "score": 25447.32927240132 }, { "content": " fn expecting(&self, formatter: &mut fmt::Formatter) -> fmt::Result {\n\n formatter.write_str(\"matching policy for registration\")\n\n }\n\n\n\n #[inline]\n\n fn visit_str<E>(self, value: &str) -> Result<MatchingPolicy, E>\n\n where\n\n E: serde::de::Error,\n\n {\n\n match value {\n\n \"prefix\" => Ok(MatchingPolicy::Prefix),\n\n \"wildcard\" => Ok(MatchingPolicy::Wildcard),\n\n \"\" => Ok(MatchingPolicy::Strict),\n\n x => Err(serde::de::Error::custom(format!(\n\n \"Invalid matching policy: {}\",\n\n x\n\n ))),\n\n }\n\n }\n\n}\n", "file_path": "src/messages/types/mod.rs", "rank": 89, "score": 24143.3623357882 }, { "content": " ))\n\n }\n\n }\n\n}\n\n\n\nimpl ArgDict for Dict {\n\n fn get_int(&self, key: &str) -> CallResult<Option<i64>> {\n\n let value = self.get(key);\n\n match value {\n\n Some(value) => {\n\n if let Value::Integer(value) = *value {\n\n Ok(Some(value))\n\n } else {\n\n Err(CallError::new(\n\n Reason::InvalidArgument,\n\n Some(vec![Value::String(format!(\n\n \"Expected integer, got {}\",\n\n value.summarize()\n\n ))]),\n\n None,\n", "file_path": "src/messages/types/value.rs", "rank": 90, "score": 24142.16893048852 }, { "content": " }\n\n Value::Boolean(b) => b.to_string(),\n\n }\n\n }\n\n}\n\n\n\n// XXX Right now there is no way to tell the difference between a URI and a string, or an ID and an Integer\n\nimpl<'de> serde::de::Visitor<'de> for ValueVisitor {\n\n type Value = Value;\n\n\n\n fn expecting(&self, formatter: &mut fmt::Formatter) -> fmt::Result {\n\n formatter.write_str(\"JSON value\")\n\n }\n\n\n\n #[inline]\n\n fn visit_str<E>(self, value: &str) -> Result<Value, E>\n\n where\n\n E: serde::de::Error,\n\n {\n\n Ok(Value::String(value.to_string()))\n", "file_path": "src/messages/types/value.rs", "rank": 91, "score": 24141.64838884397 }, { "content": " ))\n\n }\n\n }\n\n None => Ok(None),\n\n }\n\n }\n\n fn get_string<'a>(&'a self, key: &str) -> CallResult<Option<&'a str>> {\n\n let value = self.get(key);\n\n match value {\n\n Some(value) => {\n\n if let Value::String(ref value) = *value {\n\n Ok(Some(value))\n\n } else {\n\n Err(CallError::new(\n\n Reason::InvalidArgument,\n\n Some(vec![Value::String(format!(\n\n \"Expected string, got {}\",\n\n value.summarize()\n\n ))]),\n\n None,\n", "file_path": "src/messages/types/value.rs", "rank": 92, "score": 24140.041759145854 }, { "content": " ))\n\n }\n\n }\n\n None => Ok(None),\n\n }\n\n }\n\n\n\n fn get_string(&self, index: usize) -> CallResult<Option<&str>> {\n\n let value = self.get(index);\n\n match value {\n\n Some(value) => {\n\n if let Value::String(ref value) = *value {\n\n Ok(Some(value))\n\n } else {\n\n Err(CallError::new(\n\n Reason::InvalidArgument,\n\n Some(vec![Value::String(format!(\n\n \"Expected string, got {}\",\n\n value.summarize()\n\n ))]),\n", "file_path": "src/messages/types/value.rs", "rank": 93, "score": 24139.75643658678 }, { "content": " D: serde::Deserializer<'de>,\n\n {\n\n deserializer.deserialize_str(InvocationPolicyVisitor)\n\n }\n\n}\n\n\n\nimpl<'de> serde::de::Visitor<'de> for InvocationPolicyVisitor {\n\n type Value = InvocationPolicy;\n\n\n\n fn expecting(&self, formatter: &mut fmt::Formatter) -> fmt::Result {\n\n formatter.write_str(\"invocation policy for a procedure\")\n\n }\n\n\n\n #[inline]\n\n fn visit_str<E>(self, value: &str) -> Result<InvocationPolicy, E>\n\n where\n\n E: serde::de::Error,\n\n {\n\n match value {\n\n \"single\" => Ok(InvocationPolicy::Single),\n", "file_path": "src/messages/types/mod.rs", "rank": 94, "score": 24139.620704050838 }, { "content": " E: serde::de::Error,\n\n {\n\n Ok(Value::Float(value))\n\n }\n\n\n\n #[inline]\n\n fn visit_bool<E>(self, value: bool) -> Result<Value, E>\n\n where\n\n E: serde::de::Error,\n\n {\n\n Ok(Value::Boolean(value))\n\n }\n\n\n\n #[inline]\n\n fn visit_map<Visitor>(self, mut visitor: Visitor) -> Result<Value, Visitor::Error>\n\n where\n\n Visitor: serde::de::MapAccess<'de>,\n\n {\n\n let mut values = HashMap::new();\n\n if let Some(size) = visitor.size_hint() {\n", "file_path": "src/messages/types/value.rs", "rank": 95, "score": 24139.552147378192 }, { "content": " ))\n\n }\n\n }\n\n None => Ok(None),\n\n }\n\n }\n\n}\n\n\n\nimpl Value {\n\n pub fn summarize(&self) -> String {\n\n match *self {\n\n Value::Dict(ref d) => {\n\n let mut result = String::new();\n\n result.push('{');\n\n result.push_str(&d.iter()\n\n .take(50)\n\n .map(|(key, value)| format!(\"{}:{}\", key, value.summarize()))\n\n .join(\",\"));\n\n result.push('}');\n\n result\n", "file_path": "src/messages/types/value.rs", "rank": 96, "score": 24139.486797441226 }, { "content": "mod error;\n\nmod options;\n\nmod roles;\n\nmod value;\n\n\n\nuse serde;\n\nuse std::fmt;\n\n\n\npub use crate::messages::types::error::*;\n\npub use crate::messages::types::options::*;\n\npub use crate::messages::types::roles::*;\n\npub use crate::messages::types::value::*;\n\n\n", "file_path": "src/messages/types/mod.rs", "rank": 97, "score": 24139.141531067256 }, { "content": " }\n\n\n\n #[inline]\n\n fn visit_i64<E>(self, value: i64) -> Result<Value, E>\n\n where\n\n E: serde::de::Error,\n\n {\n\n Ok(Value::Integer(value))\n\n }\n\n\n\n #[inline]\n\n fn visit_u64<E>(self, value: u64) -> Result<Value, E>\n\n where\n\n E: serde::de::Error,\n\n {\n\n Ok(Value::UnsignedInteger(value))\n\n }\n\n\n\n fn visit_f64<E>(self, value: f64) -> Result<Value, E>\n\n where\n", "file_path": "src/messages/types/value.rs", "rank": 98, "score": 24137.439545374225 }, { "content": " type Value = URI;\n\n\n\n fn expecting(&self, formatter: &mut fmt::Formatter) -> fmt::Result {\n\n formatter.write_str(\"URI\")\n\n }\n\n #[inline]\n\n fn visit_str<E>(self, value: &str) -> Result<URI, E>\n\n where\n\n E: serde::de::Error,\n\n {\n\n Ok(URI {\n\n uri: value.to_string(),\n\n })\n\n }\n\n}\n", "file_path": "src/messages/types/value.rs", "rank": 99, "score": 24137.356775777425 } ]
Rust
rust/strprintf/src/traits.rs
Spacewalker2/newsboat
8efc234e7d3ca6df3d0797c131eb917fe4ab18cf
use std::ffi::CString; pub trait Printfable { type Holder: CReprHolder; fn to_c_repr_holder(self: Self) -> Option<<Self as Printfable>::Holder>; } impl Printfable for i32 { type Holder = i32; fn to_c_repr_holder(self: Self) -> Option<<Self as Printfable>::Holder> { Some(self) } } impl Printfable for u32 { type Holder = u32; fn to_c_repr_holder(self: Self) -> Option<<Self as Printfable>::Holder> { Some(self) } } impl Printfable for i64 { type Holder = i64; fn to_c_repr_holder(self: Self) -> Option<<Self as Printfable>::Holder> { Some(self) } } impl Printfable for u64 { type Holder = u64; fn to_c_repr_holder(self: Self) -> Option<<Self as Printfable>::Holder> { Some(self) } } impl Printfable for f32 { type Holder = f64; fn to_c_repr_holder(self: Self) -> Option<<Self as Printfable>::Holder> { Some(self as f64) } } impl Printfable for f64 { type Holder = f64; fn to_c_repr_holder(self: Self) -> Option<<Self as Printfable>::Holder> { Some(self) } } impl<'a> Printfable for &'a str { type Holder = CString; fn to_c_repr_holder(self: Self) -> Option<<Self as Printfable>::Holder> { CString::new(self).ok() } } impl<'a> Printfable for &'a String { type Holder = CString; fn to_c_repr_holder(self: Self) -> Option<<Self as Printfable>::Holder> { CString::new(self.as_str()).ok() } } impl Printfable for String { type Holder = CString; fn to_c_repr_holder(self: Self) -> Option<<Self as Printfable>::Holder> { CString::new(self).ok() } } impl<T> Printfable for *const T { type Holder = *const libc::c_void; fn to_c_repr_holder(self: Self) -> Option<<Self as Printfable>::Holder> { Some(self as *const libc::c_void) } } pub trait CReprHolder { type Output; fn to_c_repr(self: &Self) -> <Self as CReprHolder>::Output; } impl CReprHolder for i32 { type Output = i32; fn to_c_repr(self: &Self) -> <Self as CReprHolder>::Output { *self } } impl CReprHolder for u32 { type Output = u32; fn to_c_repr(self: &Self) -> <Self as CReprHolder>::Output { *self } } impl CReprHolder for i64 { type Output = i64; fn to_c_repr(self: &Self) -> <Self as CReprHolder>::Output { *self } } impl CReprHolder for u64 { type Output = u64; fn to_c_repr(self: &Self) -> <Self as CReprHolder>::Output { *self } } impl CReprHolder for f64 { type Output = f64; fn to_c_repr(self: &Self) -> <Self as CReprHolder>::Output { *self } } impl CReprHolder for CString { type Output = *const libc::c_char; fn to_c_repr(self: &Self) -> <Self as CReprHolder>::Output { self.as_ptr() } } impl CReprHolder for *const libc::c_void { type Output = *const libc::c_void; fn to_c_repr(self: &Self) -> <Self as CReprHolder>::Output { *self } }
use std::ffi::CString; pub trait Printfable { type Holder: CReprHolder; fn to_c_repr_holder(self: Self) -> Option<<Self as Printfable>::Holder>; } impl Printfable for i32 { type Holder = i32; fn to_c_repr_holder(self: Self) -> Option<<Self as Printfable>::Holder> { Some(self) } } impl Printfable for u32 { type Holder = u32; fn to_c_repr_holder(self: Self) -> Option<<Self as Printfable>::Holder> { Some(self) } } impl Printfable for i64 { type Holder = i64; fn to_c_repr_holder(self: Self) -> Option<<Self as Printfable>::Holder> { Some(self) } } impl Printfable for u64 { type Holder = u64; fn to_c_repr_holder(self: Self) -> Option<<Self as Printfable>::Holder> { Some(self) } } impl Printfable for f32 { type Holder = f64; fn to_c_repr_holder(self: Self) -> Option<<Self as Printfable>::Holder> { Some(self as f64) } } impl Printfable for f64 { type Holder = f64; fn to_c_repr_holder(self: Self) -> Option<<Self as Printfable>::Holder> { Some(self) } } impl<'a> Printfable for &'a str { type Holder = CString; fn to_c_repr_holder(self: Self) -> Option<<Self as Printfable>::Holder> { CString::new(self).ok() } } impl<'a> Printfable for &'a String { type Holder = CString; fn to_c_repr_holder(self: Self) -> Option<<Self as Printfable>::Holder> { CString::new(self.as_str()).ok() } } impl Printfable for String { type Holder = CString; fn to_c_repr_holder(self: Self) -> Option<<Self as Printfable>::Holder> { CString::new(self).ok() } } impl<T> Printfable for *const T { type Holder = *const libc::c_void; fn to_c_repr_holder(self: Self) -> Option<<Self as Printfable>::Holder> { Some(self as *const libc::c_void) } } pub trait CReprHolder { type Output; fn to_c_repr(self: &Self) -> <Self
<Self as CReprHolder>::Output { *self } } impl CReprHolder for CString { type Output = *const libc::c_char; fn to_c_repr(self: &Self) -> <Self as CReprHolder>::Output { self.as_ptr() } } impl CReprHolder for *const libc::c_void { type Output = *const libc::c_void; fn to_c_repr(self: &Self) -> <Self as CReprHolder>::Output { *self } }
as CReprHolder>::Output; } impl CReprHolder for i32 { type Output = i32; fn to_c_repr(self: &Self) -> <Self as CReprHolder>::Output { *self } } impl CReprHolder for u32 { type Output = u32; fn to_c_repr(self: &Self) -> <Self as CReprHolder>::Output { *self } } impl CReprHolder for i64 { type Output = i64; fn to_c_repr(self: &Self) -> <Self as CReprHolder>::Output { *self } } impl CReprHolder for u64 { type Output = u64; fn to_c_repr(self: &Self) -> <Self as CReprHolder>::Output { *self } } impl CReprHolder for f64 { type Output = f64; fn to_c_repr(self: &Self) ->
random
[ { "content": "pub fn to_u(rs_str: String, default_value: u32) -> u32 {\n\n let mut result = rs_str.parse::<u32>();\n\n\n\n if result.is_err() {\n\n result = Ok(default_value);\n\n }\n\n\n\n result.unwrap()\n\n}\n\n\n", "file_path": "rust/libnewsboat/src/utils.rs", "rank": 0, "score": 271303.02830339293 }, { "content": "/// Runs given command in a shell, and returns the output (from stdout; stderr is printed to the\n\n/// screen).\n\npub fn get_command_output(cmd: &str) -> String {\n\n let cmd = Command::new(\"sh\")\n\n .arg(\"-c\")\n\n .arg(cmd)\n\n // Inherit stdin so that the program can ask something of the user (see\n\n // https://github.com/newsboat/newsboat/issues/455 for an example).\n\n .stdin(Stdio::inherit())\n\n .output();\n\n // from_utf8_lossy will convert any bad bytes to U+FFFD\n\n cmd.map(|cmd| String::from_utf8_lossy(&cmd.stdout).into_owned())\n\n .unwrap_or_else(|_| String::from(\"\"))\n\n}\n\n\n", "file_path": "rust/libnewsboat/src/utils.rs", "rank": 1, "score": 265895.278050332 }, { "content": "/// Quote a string for use with stfl by replacing all occurences of \"<\" with \"<>\"\n\n/// ```\n\n/// use libnewsboat::utils::quote_for_stfl;\n\n/// assert_eq!(&quote_for_stfl(\"<\"), \"<>\");\n\n/// assert_eq!(&quote_for_stfl(\"<<><><><\"), \"<><>><>><>><>\");\n\n/// assert_eq!(&quote_for_stfl(\"test\"), \"test\");\n\n/// ```\n\npub fn quote_for_stfl(string: &str) -> String {\n\n string.replace(\"<\", \"<>\")\n\n}\n\n\n", "file_path": "rust/libnewsboat/src/utils.rs", "rank": 2, "score": 263908.3829967899 }, { "content": "pub fn replace_all(input: String, from: &str, to: &str) -> String {\n\n input.replace(from, to)\n\n}\n\n\n", "file_path": "rust/libnewsboat/src/utils.rs", "rank": 3, "score": 257782.62199561612 }, { "content": "/// Calculate the number of padding tabs when formatting columns\n\n///\n\n/// The number of tabs will be adjusted by the width of the given string. Usually, a column will\n\n/// consist of 4 tabs, 8 characters each. Each column will consist of at least one tab.\n\n///\n\n/// ```\n\n/// use libnewsboat::utils::gentabs;\n\n///\n\n/// fn genstring(len: usize) -> String {\n\n/// return std::iter::repeat(\"a\").take(len).collect::<String>();\n\n/// }\n\n///\n\n/// assert_eq!(gentabs(\"\"), 4);\n\n/// assert_eq!(gentabs(\"a\"), 4);\n\n/// assert_eq!(gentabs(\"aa\"), 4);\n\n/// assert_eq!(gentabs(\"aaa\"), 4);\n\n/// assert_eq!(gentabs(\"aaaa\"), 4);\n\n/// assert_eq!(gentabs(\"aaaaa\"), 4);\n\n/// assert_eq!(gentabs(\"aaaaaa\"), 4);\n\n/// assert_eq!(gentabs(\"aaaaaaa\"), 4);\n\n/// assert_eq!(gentabs(\"aaaaaaaa\"), 3);\n\n/// assert_eq!(gentabs(&genstring(8)), 3);\n\n/// assert_eq!(gentabs(&genstring(9)), 3);\n\n/// assert_eq!(gentabs(&genstring(15)), 3);\n\n/// assert_eq!(gentabs(&genstring(16)), 2);\n\n/// assert_eq!(gentabs(&genstring(20)), 2);\n\n/// assert_eq!(gentabs(&genstring(24)), 1);\n\n/// assert_eq!(gentabs(&genstring(32)), 1);\n\n/// assert_eq!(gentabs(&genstring(100)), 1);\n\n/// ```\n\npub fn gentabs(string: &str) -> usize {\n\n let tabcount = strwidth(string) / 8;\n\n if tabcount >= 4 {\n\n 1\n\n } else {\n\n 4 - tabcount\n\n }\n\n}\n\n\n", "file_path": "rust/libnewsboat/src/utils.rs", "rank": 4, "score": 243561.20697124556 }, { "content": "pub fn trim(rs_str: String) -> String {\n\n rs_str.trim().to_string()\n\n}\n\n\n", "file_path": "rust/libnewsboat/src/utils.rs", "rank": 5, "score": 239035.46936598173 }, { "content": "/// Get basename from a URL if available else return an empty string\n\n/// ```\n\n/// use libnewsboat::utils::get_basename;\n\n/// assert_eq!(get_basename(\"https://example.com/\"), \"\");\n\n/// assert_eq!(get_basename(\"https://example.org/?param=value#fragment\"), \"\");\n\n/// assert_eq!(get_basename(\"https://example.org/path/to/?param=value#fragment\"), \"\");\n\n/// assert_eq!(get_basename(\"https://example.org/file.mp3\"), \"file.mp3\");\n\n/// assert_eq!(get_basename(\"https://example.org/path/to/file.mp3?param=value#fragment\"), \"file.mp3\");\n\n/// ```\n\npub fn get_basename(input: &str) -> String {\n\n match Url::parse(input) {\n\n Ok(url) => match url.path_segments() {\n\n Some(segments) => segments.last().unwrap().to_string(),\n\n None => String::from(\"\"),\n\n },\n\n Err(_) => String::from(\"\"),\n\n }\n\n}\n\n\n", "file_path": "rust/libnewsboat/src/utils.rs", "rank": 6, "score": 237802.8379353618 }, { "content": "/// Censor URLs by replacing username and password with '*'\n\n/// ```\n\n/// use libnewsboat::utils::censor_url;\n\n/// assert_eq!(&censor_url(\"\"), \"\");\n\n/// assert_eq!(&censor_url(\"foobar\"), \"foobar\");\n\n/// assert_eq!(&censor_url(\"foobar://xyz/\"), \"foobar://xyz/\");\n\n/// assert_eq!(&censor_url(\"http://newsbeuter.org/\"),\n\n/// \"http://newsbeuter.org/\");\n\n/// assert_eq!(&censor_url(\"https://newsbeuter.org/\"),\n\n/// \"https://newsbeuter.org/\");\n\n///\n\n/// assert_eq!(&censor_url(\"http://@newsbeuter.org/\"),\n\n/// \"http://newsbeuter.org/\");\n\n/// assert_eq!(&censor_url(\"https://@newsbeuter.org/\"),\n\n/// \"https://newsbeuter.org/\");\n\n///\n\n/// assert_eq!(&censor_url(\"http://foo:[email protected]/\"),\n\n/// \"http://*:*@newsbeuter.org/\");\n\n/// assert_eq!(&censor_url(\"https://foo:[email protected]/\"),\n\n/// \"https://*:*@newsbeuter.org/\");\n\n///\n\n/// assert_eq!(&censor_url(\"http://[email protected]/\"),\n\n/// \"http://*:*@newsbeuter.org/\");\n\n/// assert_eq!(&censor_url(\"https://[email protected]/\"),\n\n/// \"https://*:*@newsbeuter.org/\");\n\n///\n\n/// assert_eq!(&censor_url(\"xxx://[email protected]/\"),\n\n/// \"xxx://*:*@newsbeuter.org/\");\n\n///\n\n/// assert_eq!(&censor_url(\"http://foobar\"), \"http://foobar/\");\n\n/// assert_eq!(&censor_url(\"https://foobar\"), \"https://foobar/\");\n\n///\n\n/// assert_eq!(&censor_url(\"http://aschas@host\"), \"http://*:*@host/\");\n\n/// assert_eq!(&censor_url(\"https://aschas@host\"), \"https://*:*@host/\");\n\n///\n\n/// assert_eq!(&censor_url(\"query:name:age between 1:10\"),\n\n/// \"query:name:age between 1:10\");\n\n/// ```\n\npub fn censor_url(url: &str) -> String {\n\n if !url.is_empty() && !is_special_url(url) {\n\n Url::parse(url)\n\n .map(|mut url| {\n\n if url.username() != \"\" || url.password().is_some() {\n\n // can not panic. If either username or password is present we can change both.\n\n url.set_username(\"*\").unwrap();\n\n url.set_password(Some(\"*\")).unwrap();\n\n }\n\n url\n\n })\n\n .as_ref()\n\n .map(Url::as_str)\n\n .unwrap_or(url)\n\n .to_owned()\n\n } else {\n\n url.into()\n\n }\n\n}\n\n\n", "file_path": "rust/libnewsboat/src/utils.rs", "rank": 7, "score": 237798.2738288879 }, { "content": "/// Returns a longest substring fits to the given width.\n\n/// Returns an empty string if `str` is an empty string or `max_width` is zero.\n\n///\n\n/// Each chararacter width is calculated with UnicodeWidthChar::width. If UnicodeWidthChar::width()\n\n/// returns None, the character width is treated as 0.\n\n/// ```\n\n/// use libnewsboat::utils::substr_with_width;\n\n/// assert_eq!(substr_with_width(\"a\", 1), \"a\");\n\n/// assert_eq!(substr_with_width(\"a\", 2), \"a\");\n\n/// assert_eq!(substr_with_width(\"ab\", 1), \"a\");\n\n/// assert_eq!(substr_with_width(\"abc\", 1), \"a\");\n\n/// assert_eq!(substr_with_width(\"A\\u{3042}B\\u{3044}C\\u{3046}\", 5), \"A\\u{3042}B\")\n\n///```\n\npub fn substr_with_width(string: &str, max_width: usize) -> String {\n\n let mut result = String::new();\n\n let mut width = 0;\n\n for c in string.chars() {\n\n // Control chars count as width 0\n\n let w = UnicodeWidthChar::width(c).unwrap_or(0);\n\n if width + w > max_width {\n\n break;\n\n }\n\n width += w;\n\n result.push(c);\n\n }\n\n result\n\n}\n\n\n", "file_path": "rust/libnewsboat/src/utils.rs", "rank": 8, "score": 234193.7409231674 }, { "content": "/// Combine a base URL and a link to a new absolute URL.\n\n/// If the base URL is malformed or joining with the link fails, link will be returned.\n\n/// # Examples\n\n/// ```\n\n/// use libnewsboat::utils::absolute_url;\n\n/// assert_eq!(absolute_url(\"http://foobar/hello/crook/\", \"bar.html\"),\n\n/// \"http://foobar/hello/crook/bar.html\".to_owned());\n\n/// assert_eq!(absolute_url(\"https://foobar/foo/\", \"/bar.html\"),\n\n/// \"https://foobar/bar.html\".to_owned());\n\n/// assert_eq!(absolute_url(\"https://foobar/foo/\", \"http://quux/bar.html\"),\n\n/// \"http://quux/bar.html\".to_owned());\n\n/// assert_eq!(absolute_url(\"http://foobar\", \"bla.html\"),\n\n/// \"http://foobar/bla.html\".to_owned());\n\n/// assert_eq!(absolute_url(\"http://test:test@foobar:33\", \"bla2.html\"),\n\n/// \"http://test:test@foobar:33/bla2.html\".to_owned());\n\n/// assert_eq!(absolute_url(\"foo\", \"bar\"), \"bar\".to_owned());\n\n/// ```\n\npub fn absolute_url(base_url: &str, link: &str) -> String {\n\n Url::parse(base_url)\n\n .and_then(|url| url.join(link))\n\n .as_ref()\n\n .map(Url::as_str)\n\n .unwrap_or(link)\n\n .to_owned()\n\n}\n\n\n\n/// Path to the home directory, if known. Doesn't work on Windows.\n", "file_path": "rust/libnewsboat/src/utils.rs", "rank": 9, "score": 234130.52860359062 }, { "content": "pub fn run_program(cmd_with_args: &[&str], input: &str) -> String {\n\n if cmd_with_args.is_empty() {\n\n return String::new();\n\n }\n\n\n\n Command::new(cmd_with_args[0])\n\n .args(&cmd_with_args[1..])\n\n .stdin(Stdio::piped())\n\n .stdout(Stdio::piped())\n\n .stderr(Stdio::null())\n\n .spawn()\n\n .map_err(|error| {\n\n log!(\n\n Level::Debug,\n\n \"utils::run_program: spawning a child for \\\"{:?}\\\" \\\n\n with input \\\"{}\\\" failed: {}\",\n\n cmd_with_args,\n\n input,\n\n error\n\n );\n", "file_path": "rust/libnewsboat/src/utils.rs", "rank": 10, "score": 234127.95133683307 }, { "content": "pub fn make_title(rs_str: String) -> String {\n\n /* Sometimes it is possible to construct the title from the URL\n\n * This attempts to do just that. eg:\n\n * http://domain.com/story/yy/mm/dd/title-with-dashes?a=b\n\n */\n\n // Strip out trailing slashes\n\n let mut result = rs_str.trim_end_matches('/');\n\n\n\n // get to the final part of the URI's path and\n\n // extract just the juicy part 'title-with-dashes?a=b'\n\n let v: Vec<&str> = result.rsplitn(2, '/').collect();\n\n result = v[0];\n\n\n\n // find where query part of URI starts\n\n // throw away the query part 'title-with-dashes'\n\n let v: Vec<&str> = result.splitn(2, '?').collect();\n\n result = v[0];\n\n\n\n // Throw away common webpage suffixes: .html, .php, .aspx, .htm\n\n result = result\n", "file_path": "rust/libnewsboat/src/utils.rs", "rank": 11, "score": 233682.10306764132 }, { "content": "pub fn trim_end(rs_str: String) -> String {\n\n let x: &[_] = &['\\n', '\\r'];\n\n rs_str.trim_end_matches(x).to_string()\n\n}\n\n\n", "file_path": "rust/libnewsboat/src/utils.rs", "rank": 12, "score": 233682.1030676413 }, { "content": "/// Returns a longest substring fits to the given width.\n\n/// Returns an empty string if `str` is an empty string or `max_width` is zero.\n\n///\n\n/// Each chararacter width is calculated with UnicodeWidthChar::width. If UnicodeWidthChar::width()\n\n/// returns None, the character width is treated as 0. A STFL tag (e.g. `<b>`, `<foobar>`, `</>`)\n\n/// width is treated as 0, but escaped less-than (`<>`) width is treated as 1.\n\n/// ```\n\n/// use libnewsboat::utils::substr_with_width_stfl;\n\n/// assert_eq!(substr_with_width_stfl(\"a\", 1), \"a\");\n\n/// assert_eq!(substr_with_width_stfl(\"a\", 2), \"a\");\n\n/// assert_eq!(substr_with_width_stfl(\"ab\", 1), \"a\");\n\n/// assert_eq!(substr_with_width_stfl(\"abc\", 1), \"a\");\n\n/// assert_eq!(substr_with_width_stfl(\"A\\u{3042}B\\u{3044}C\\u{3046}\", 5), \"A\\u{3042}B\")\n\n///```\n\npub fn substr_with_width_stfl(string: &str, max_width: usize) -> String {\n\n let mut result = String::new();\n\n let mut in_bracket = false;\n\n let mut tagbuf = Vec::<char>::new();\n\n let mut width = 0;\n\n for c in string.chars() {\n\n if in_bracket {\n\n tagbuf.push(c);\n\n if c == '>' {\n\n in_bracket = false;\n\n if tagbuf == ['<', '>'] {\n\n if width + 1 > max_width {\n\n break;\n\n }\n\n result += \"<>\"; // escaped less-than\n\n tagbuf.clear();\n\n width += 1;\n\n } else {\n\n result += &tagbuf.iter().collect::<String>();\n\n tagbuf.clear();\n", "file_path": "rust/libnewsboat/src/utils.rs", "rank": 13, "score": 229835.61610380252 }, { "content": "/// Convert numerical prefix of the string to i32.\n\n///\n\n/// Return 0 if there is no numeric prefix. On underflow, return `std::i32::MIN`. On overflow,\n\n/// return `std::i32::MAX`.\n\nfn string_to_num(input: &str) -> i32 {\n\n let search_start = if input.starts_with('-') { 1 } else { 0 };\n\n\n\n let numerics_end = input[search_start..]\n\n .find(|c: char| !c.is_numeric())\n\n .unwrap_or_else(|| input.len())\n\n + search_start; // Adding the starting offset to get an index inside the original input\n\n\n\n if numerics_end - search_start == 0 {\n\n // No numeric prefix\n\n return 0;\n\n }\n\n\n\n if let Ok(number) = input[..numerics_end].parse::<i32>() {\n\n number\n\n } else if search_start == 1 {\n\n // Number starts with minus and couldn't be parsed => underflow\n\n std::i32::MIN\n\n } else {\n\n // Number doesn't start with minus and couldn't be parsed => overflow\n\n std::i32::MAX\n\n }\n\n}\n\n\n", "file_path": "rust/libnewsboat/src/matcher.rs", "rank": 14, "score": 225842.43923553248 }, { "content": "pub fn unescape_url(rs_str: String) -> Option<String> {\n\n let decoded = percent_decode(rs_str.as_bytes()).decode_utf8();\n\n decoded.ok().map(|s| s.replace(\"\\0\", \"\"))\n\n}\n\n\n", "file_path": "rust/libnewsboat/src/utils.rs", "rank": 15, "score": 222744.39032305122 }, { "content": "/// Extract filter and url from line separated by ':'.\n\npub fn extract_filter(line: &str) -> (&str, &str) {\n\n debug_assert!(line.starts_with(\"filter:\"));\n\n // line must start with \"filter:\"\n\n let line = line.get(\"filter:\".len()..).unwrap();\n\n let (filter, url) = line.split_at(line.find(':').unwrap_or(0));\n\n let url = url.get(1..).unwrap_or(\"\");\n\n log!(\n\n Level::Debug,\n\n \"utils::extract_filter: {} -> filter: {} url: {}\",\n\n line,\n\n filter,\n\n url\n\n );\n\n (filter, url)\n\n}\n\n\n\n#[cfg(test)]\n\nmod tests {\n\n use super::*;\n\n\n", "file_path": "rust/libnewsboat/src/utils.rs", "rank": 16, "score": 209060.24689444626 }, { "content": "pub fn quote(input: String) -> String {\n\n let mut input = input.replace(\"\\\"\", \"\\\\\\\"\");\n\n input.insert(0, '\"');\n\n input.push('\"');\n\n input\n\n}\n\n\n", "file_path": "rust/libnewsboat/src/utils.rs", "rank": 17, "score": 208660.87610623747 }, { "content": "/// Returns `true` if given MIME type is considered to be a podcast by Newsboat.\n\npub fn is_valid_podcast_type(mimetype: &str) -> bool {\n\n PODCAST_MIME_TO_LINKTYPE\n\n .iter()\n\n .any(|(matcher, _)| matcher(mimetype))\n\n}\n\n\n", "file_path": "rust/libnewsboat/src/utils.rs", "rank": 18, "score": 207488.75113096906 }, { "content": "pub fn quote_if_necessary(input: String) -> String {\n\n match input.find(' ') {\n\n Some(_) => quote(input),\n\n None => input,\n\n }\n\n}\n\n\n", "file_path": "rust/libnewsboat/src/utils.rs", "rank": 20, "score": 204336.2799714332 }, { "content": "pub fn consolidate_whitespace(input: String) -> String {\n\n let found = input.find(|c: char| !c.is_whitespace());\n\n let mut result = String::new();\n\n\n\n if let Some(found) = found {\n\n let (leading, rest) = input.split_at(found);\n\n let lastchar = input.chars().rev().next().unwrap();\n\n\n\n result.push_str(leading);\n\n\n\n let iter = rest.split_whitespace();\n\n for elem in iter {\n\n result.push_str(elem);\n\n result.push(' ');\n\n }\n\n result.pop();\n\n if lastchar.is_whitespace() {\n\n result.push(' ');\n\n }\n\n }\n\n\n\n result\n\n}\n\n\n", "file_path": "rust/libnewsboat/src/utils.rs", "rank": 21, "score": 204336.2799714332 }, { "content": "/// Returns the part of the string before first # character (or the whole input string if there are\n\n/// no # character in it). Pound characters inside double quotes and backticks are ignored.\n\npub fn strip_comments(line: &str) -> &str {\n\n let mut prev_was_backslash = false;\n\n let mut inside_quotes = false;\n\n let mut inside_backticks = false;\n\n\n\n let mut first_pound_chr_idx = line.len();\n\n\n\n for (idx, chr) in line.char_indices() {\n\n match chr {\n\n '\\\\' => {\n\n prev_was_backslash = true;\n\n continue;\n\n }\n\n '\"' => {\n\n // If the quote is escaped or we're inside backticks, do nothing\n\n if !prev_was_backslash && !inside_backticks {\n\n inside_quotes = !inside_quotes;\n\n }\n\n }\n\n '`' => {\n", "file_path": "rust/libnewsboat/src/utils.rs", "rank": 22, "score": 204162.78822814586 }, { "content": "/// The tag and Git commit ID the program was built from, or a pre-defined value from config.h if\n\n/// there is no Git directory.\n\npub fn program_version() -> String {\n\n // NEWSBOAT_VERSION is set by this crate's build script, \"build.rs\"\n\n env!(\"NEWSBOAT_VERSION\").to_string()\n\n}\n\n\n", "file_path": "rust/libnewsboat/src/utils.rs", "rank": 23, "score": 202400.090205156 }, { "content": "pub fn get_random_value(max: u32) -> u32 {\n\n rand::random::<u32>() % max\n\n}\n\n\n", "file_path": "rust/libnewsboat/src/utils.rs", "rank": 24, "score": 200554.9559886866 }, { "content": "/// Converts podcast's MIME type into an HtmlRenderer's \"link type\"\n\n///\n\n/// Returns None if given MIME type is not a podcast type. See `is_valid_podcast_type()`.\n\npub fn podcast_mime_to_link_type(mime_type: &str) -> Option<htmlrenderer::LinkType> {\n\n PODCAST_MIME_TO_LINKTYPE\n\n .iter()\n\n .find_map(|(matcher, link_type)| {\n\n if matcher(mime_type) {\n\n Some(*link_type)\n\n } else {\n\n None\n\n }\n\n })\n\n}\n\n\n", "file_path": "rust/libnewsboat/src/utils.rs", "rank": 25, "score": 198262.71798502482 }, { "content": "/// Newsboat's major version number.\n\npub fn newsboat_major_version() -> u32 {\n\n // This will panic if the version couldn't be parsed, which is virtually impossible as Cargo\n\n // won't even start compilation if it couldn't parse the version.\n\n env!(\"CARGO_PKG_VERSION_MAJOR\").parse::<u32>().unwrap()\n\n}\n\n\n", "file_path": "rust/libnewsboat/src/utils.rs", "rank": 26, "score": 197907.43476083313 }, { "content": "pub fn get_default_browser() -> String {\n\n use std::env;\n\n env::var(\"BROWSER\").unwrap_or_else(|_| \"lynx\".to_string())\n\n}\n\n\n", "file_path": "rust/libnewsboat/src/utils.rs", "rank": 27, "score": 197710.83597063372 }, { "content": "// This function assumes that the user is not interested in command's output (not even errors on\n\n// stderr!), so it redirects everything to /dev/null.\n\npub fn run_command(cmd: &str, param: &str) {\n\n let child = Command::new(cmd)\n\n .arg(param)\n\n // Prevent the command from blocking Newsboat by asking for input\n\n .stdin(Stdio::null())\n\n // Prevent the command from botching the screen by printing onto it.\n\n .stdout(Stdio::null())\n\n .stderr(Stdio::null())\n\n .spawn();\n\n if let Err(error) = child {\n\n log!(\n\n Level::Debug,\n\n \"utils::run_command: spawning a child for \\\"{}\\\" failed: {}\",\n\n cmd,\n\n error\n\n );\n\n }\n\n\n\n // We deliberately *don't* wait for the child to finish.\n\n}\n\n\n", "file_path": "rust/libnewsboat/src/utils.rs", "rank": 29, "score": 194196.66713999613 }, { "content": "#[doc(hidden)]\n\npub fn fmt_arg<T>(format: &str, arg: T) -> Option<String>\n\nwhere\n\n T: Printfable,\n\n{\n\n // Returns None if `format` contains a null byte\n\n CString::new(format).ok().and_then(|local_format_cstring| {\n\n // Returns None if a holder couldn't be obtained - e.g. the value is a String that\n\n // contains a null byte\n\n arg.to_c_repr_holder().and_then(|arg_c_repr_holder| {\n\n match fmt_arg_with_buffer_size(&local_format_cstring, &arg_c_repr_holder, 1024) {\n\n Ok(formatted) => Some(formatted),\n\n Err(buf_size) => {\n\n fmt_arg_with_buffer_size(&local_format_cstring, &arg_c_repr_holder, buf_size)\n\n .ok()\n\n }\n\n }\n\n })\n\n })\n\n}\n\n\n", "file_path": "rust/strprintf/src/lib.rs", "rank": 30, "score": 193633.39707430627 }, { "content": "pub fn strwidth(rs_str: &str) -> usize {\n\n UnicodeWidthStr::width(rs_str)\n\n}\n\n\n", "file_path": "rust/libnewsboat/src/utils.rs", "rank": 31, "score": 192927.26606233625 }, { "content": "/// Returns the width of `rs_str` when displayed on screen.\n\n///\n\n/// STFL tags (e.g. `<b>`, `<foobar>`, `</>`) are counted as having 0 width.\n\n/// Escaped less-than sign (`<` escaped as `<>`) is counted as having a width of 1 character.\n\n/// ```\n\n/// use libnewsboat::utils::strwidth_stfl;\n\n/// assert_eq!(strwidth_stfl(\"a\"), 1);\n\n/// assert_eq!(strwidth_stfl(\"abc<tag>def\"), 6);\n\n/// assert_eq!(strwidth_stfl(\"less-than: <>\"), 12);\n\n/// assert_eq!(strwidth_stfl(\"ABCDEF\"), 12);\n\n///```\n\npub fn strwidth_stfl(rs_str: &str) -> usize {\n\n let mut s = &rs_str[..];\n\n let mut width = 0;\n\n loop {\n\n if let Some(pos) = s.find('<') {\n\n width += strwidth(&s[..pos]);\n\n s = &s[pos..];\n\n if let Some(endpos) = s.find('>') {\n\n if endpos == 1 {\n\n // Found \"<>\" which stfl uses to encode a literal '<'\n\n width += strwidth(\"<\");\n\n }\n\n s = &s[endpos + 1..];\n\n } else {\n\n // '<' without closing '>' so ignore rest of string\n\n break;\n\n }\n\n } else {\n\n width += strwidth(s);\n\n break;\n\n }\n\n }\n\n\n\n width\n\n}\n\n\n", "file_path": "rust/libnewsboat/src/utils.rs", "rank": 32, "score": 188910.93535158603 }, { "content": "pub fn strnaturalcmp(a: &str, b: &str) -> std::cmp::Ordering {\n\n natord::compare(a, b)\n\n}\n\n\n", "file_path": "rust/libnewsboat/src/utils.rs", "rank": 33, "score": 180533.11926055222 }, { "content": "/// An array of \"MIME matchers\" and their associated LinkTypes\n\n///\n\n/// This is used for two tasks:\n\n///\n\n/// 1. checking if a MIME type is a podcast type (`utils::is_valid_podcast_type`). That involves\n\n/// running all matching functions on given input and checking if any of them returned `true`;\n\n///\n\n/// 2. figuring out the `LinkType` for a particular enclosure, given its MIME type\n\n/// (`utils::podcast_mime_to_link_type`).\n\ntype MimeMatcher = (fn(&str) -> bool, htmlrenderer::LinkType);\n\nconst PODCAST_MIME_TO_LINKTYPE: [MimeMatcher; 2] = [\n\n (\n\n |mime| {\n\n // RFC 5334, section 10.1 says \"historically, some implementations expect .ogg files to be\n\n // solely Vorbis-encoded audio\", so let's assume it's audio, not video.\n\n // https://tools.ietf.org/html/rfc5334#section-10.1\n\n mime.starts_with(\"audio/\") || mime == \"application/ogg\"\n\n },\n\n htmlrenderer::LinkType::Audio,\n\n ),\n\n (\n\n |mime| mime.starts_with(\"video/\"),\n\n htmlrenderer::LinkType::Video,\n\n ),\n\n];\n\n\n", "file_path": "rust/libnewsboat/src/utils.rs", "rank": 34, "score": 179643.21793384958 }, { "content": "/// Check if the given URL is a http(s) URL\n\n/// # Example\n\n/// ```\n\n/// use libnewsboat::utils::is_http_url;\n\n/// assert!(is_http_url(\"http://example.com\"));\n\n/// ```\n\npub fn is_http_url(url: &str) -> bool {\n\n url.starts_with(\"https://\") || url.starts_with(\"http://\")\n\n}\n\n\n", "file_path": "rust/libnewsboat/src/utils.rs", "rank": 35, "score": 178116.4273795731 }, { "content": "pub fn is_query_url(url: &str) -> bool {\n\n url.starts_with(\"query:\")\n\n}\n\n\n", "file_path": "rust/libnewsboat/src/utils.rs", "rank": 36, "score": 178111.22171106195 }, { "content": "pub fn is_valid_attribute(attribute: &str) -> bool {\n\n const VALID_ATTRIBUTES: [&str; 9] = [\n\n \"standout\",\n\n \"underline\",\n\n \"reverse\",\n\n \"blink\",\n\n \"dim\",\n\n \"bold\",\n\n \"protect\",\n\n \"invis\",\n\n \"default\",\n\n ];\n\n VALID_ATTRIBUTES.contains(&attribute)\n\n}\n\n\n", "file_path": "rust/libnewsboat/src/utils.rs", "rank": 37, "score": 178111.22171106195 }, { "content": "pub fn is_valid_color(color: &str) -> bool {\n\n const COLORS: [&str; 9] = [\n\n \"black\", \"red\", \"green\", \"yellow\", \"blue\", \"magenta\", \"cyan\", \"white\", \"default\",\n\n ];\n\n\n\n if COLORS.contains(&color) {\n\n true\n\n } else if color.starts_with(\"color0\") {\n\n color == \"color0\"\n\n } else if color.starts_with(\"color\") {\n\n let num_part = &color[5..];\n\n num_part.parse::<u8>().is_ok()\n\n } else {\n\n false\n\n }\n\n}\n\n\n", "file_path": "rust/libnewsboat/src/utils.rs", "rank": 38, "score": 178111.22171106195 }, { "content": "pub fn is_exec_url(url: &str) -> bool {\n\n url.starts_with(\"exec:\")\n\n}\n\n\n", "file_path": "rust/libnewsboat/src/utils.rs", "rank": 39, "score": 178111.22171106195 }, { "content": "pub fn is_special_url(url: &str) -> bool {\n\n is_query_url(url) || is_filter_url(url) || is_exec_url(url)\n\n}\n\n\n", "file_path": "rust/libnewsboat/src/utils.rs", "rank": 40, "score": 178111.22171106195 }, { "content": "pub fn is_filter_url(url: &str) -> bool {\n\n url.starts_with(\"filter:\")\n\n}\n\n\n", "file_path": "rust/libnewsboat/src/utils.rs", "rank": 41, "score": 178111.22171106195 }, { "content": "/// Run the given command interactively with inherited stdin and stdout/stderr. Return the lowest\n\n/// 8 bits of its exit code, or `None` if the command failed to start.\n\n/// ```\n\n/// use libnewsboat::utils::run_interactively;\n\n///\n\n/// let result = run_interactively(\"echo true\", \"test\");\n\n/// assert_eq!(result, Some(0));\n\n///\n\n/// let result = run_interactively(\"exit 1\", \"test\");\n\n/// assert_eq!(result, Some(1));\n\n///\n\n/// // Unfortunately, there is no easy way to provoke this function to return `None`, nor to test\n\n/// // that it returns just the lowest 8 bits.\n\n/// ```\n\npub fn run_interactively(command: &str, caller: &str) -> Option<u8> {\n\n log!(Level::Debug, &format!(\"{}: running `{}'\", caller, command));\n\n Command::new(\"sh\")\n\n .arg(\"-c\")\n\n .arg(command)\n\n .status()\n\n .map_err(|err| {\n\n log!(\n\n Level::Warn,\n\n &format!(\"{}: Couldn't create child process: {}\", caller, err)\n\n )\n\n })\n\n .ok()\n\n .and_then(|exit_status| exit_status.code())\n\n .map(|exit_code| exit_code as u8)\n\n}\n\n\n", "file_path": "rust/libnewsboat/src/utils.rs", "rank": 42, "score": 177259.5995309825 }, { "content": "/// Remove all soft-hyphens as they can behave unpredictably (see\n\n/// https://github.com/akrennmair/newsbeuter/issues/259#issuecomment-259609490) and inadvertently\n\n/// render as hyphens\n\npub fn remove_soft_hyphens(text: &mut String) {\n\n text.retain(|c| c != '\\u{00AD}')\n\n}\n\n\n", "file_path": "rust/libnewsboat/src/utils.rs", "rank": 43, "score": 174249.8030475891 }, { "content": "pub fn get_auth_method(method: &str) -> c_ulong {\n\n match method {\n\n \"basic\" => curl_sys::CURLAUTH_BASIC,\n\n \"digest\" => curl_sys::CURLAUTH_DIGEST,\n\n \"digest_ie\" => curl_sys::CURLAUTH_DIGEST_IE,\n\n \"gssnegotiate\" => curl_sys::CURLAUTH_GSSNEGOTIATE,\n\n \"ntlm\" => curl_sys::CURLAUTH_NTLM,\n\n \"anysafe\" => curl_sys::CURLAUTH_ANYSAFE,\n\n \"any\" | \"\" => curl_sys::CURLAUTH_ANY,\n\n _ => {\n\n log!(\n\n Level::UserError,\n\n \"utils::get_auth_method: you configured an invalid proxy authentication method: {}\",\n\n method\n\n );\n\n curl_sys::CURLAUTH_ANY\n\n }\n\n }\n\n}\n\n\n", "file_path": "rust/libnewsboat/src/utils.rs", "rank": 44, "score": 174125.96743194858 }, { "content": "pub fn parse(input: &str) -> Vec<Specifier> {\n\n match parser(input) {\n\n Ok((_leftovers, ast)) => sanitize(ast),\n\n Err(_) => vec![Specifier::Text(\"\")],\n\n }\n\n}\n\n\n\n#[cfg(test)]\n\nmod tests {\n\n use super::*;\n\n\n\n #[test]\n\n fn t_parses_formats_without_specifiers() {\n\n let input = \"Hello, world!\";\n\n let (leftovers, result) = parser(input).unwrap();\n\n assert_eq!(leftovers, \"\");\n\n assert_eq!(result, vec![Specifier::Text(\"Hello, world!\")]);\n\n }\n\n\n\n #[test]\n", "file_path": "rust/libnewsboat/src/fmtstrformatter/parser.rs", "rank": 45, "score": 168334.01730523712 }, { "content": "/// Parse a string `expr` as a filter expression.\n\npub fn parse(expr: &str) -> Result<Expression, Error> {\n\n match parser::<VerboseError<&str>>(expr) {\n\n Ok((leftovers, expression)) => {\n\n if leftovers.is_empty() {\n\n Ok(expression)\n\n } else {\n\n Err(Error::TrailingCharacters(&leftovers))\n\n }\n\n }\n\n Err(error) => {\n\n let handler = |e: VerboseError<&str>| -> Error {\n\n match e.errors.first() {\n\n None => Error::AtPos(0),\n\n Some((s, _kind)) => Error::AtPos(expr.offset(s)),\n\n }\n\n };\n\n\n\n match error {\n\n nom::Err::Incomplete(_) => {\n\n panic!(\"Got nom::Err::Incomplete despite wrapping the parser into `complete()`\")\n", "file_path": "rust/libnewsboat/src/filterparser.rs", "rank": 46, "score": 163387.85613341338 }, { "content": "pub fn file_contents(path: &path::Path) -> String {\n\n fs::File::open(path)\n\n .and_then(|mut f| {\n\n let mut buf = String::new();\n\n let _ = f.read_to_string(&mut buf);\n\n Ok(buf)\n\n })\n\n // If failed to open/read file, return an empty string\n\n .unwrap_or_else(|_| String::new())\n\n}\n\n\n", "file_path": "rust/libnewsboat/tests/configpaths_helpers/mod.rs", "rank": 47, "score": 161328.39585555077 }, { "content": "fn quoted_string<'a, E: ParseError<&'a str>>(input: &'a str) -> IResult<&'a str, Value, E> {\n\n let empty_string = value(String::new(), tag(\"\\\"\\\"\"));\n\n let nonempty_string = |input| {\n\n let (leftovers, chr) = delimited(\n\n tag(\"\\\"\"),\n\n escaped(is_not(\"\\\\\\\"\"), '\\\\', take(1usize)),\n\n tag(\"\\\"\"),\n\n )(input)?;\n\n Ok((leftovers, String::from(chr)))\n\n };\n\n\n\n map(alt((nonempty_string, empty_string)), Value)(input)\n\n}\n\n\n", "file_path": "rust/libnewsboat/src/filterparser.rs", "rank": 48, "score": 150386.61865497587 }, { "content": "/// An entity that can be matched against a filter expression using `Matcher`.\n\npub trait Matchable {\n\n /// Returns the value of the attribute named `attr`, or `None` if there is no such attribute.\n\n fn attribute_value(&self, attr: &str) -> Option<String>;\n\n}\n", "file_path": "rust/libnewsboat/src/matchable.rs", "rank": 49, "score": 149567.082397186 }, { "content": "/// Creates a file at given `filepath` and writes `content` into it.\n\n///\n\n/// Returns `true` if successful, `false` otherwise.\n\npub fn create_file(path: &path::Path, content: &str) -> bool {\n\n fs::File::create(path)\n\n .and_then(|mut f| f.write_all(content.as_bytes()))\n\n .is_ok()\n\n}\n\n\n", "file_path": "rust/libnewsboat/tests/configpaths_helpers/mod.rs", "rank": 50, "score": 145806.44150516717 }, { "content": "/// Sets up a panic hook with a user-friendly message.\n\n///\n\n/// See module description for details.\n\npub fn setup() {\n\n if ::std::env::var(\"RUST_BACKTRACE\").is_err() {\n\n panic::set_hook(Box::new(move |panic_info: &PanicInfo| {\n\n print_panic_msg(panic_info).expect(\"An error occurred while preparing a crash report\");\n\n }));\n\n }\n\n}\n\n\n", "file_path": "rust/libnewsboat/src/human_panic.rs", "rank": 51, "score": 144757.2417529516 }, { "content": "fn spacing(input: &str) -> IResult<&str, Specifier> {\n\n let (input, _) = tag(\"%>\")(input)?;\n\n let (input, c) = take(1usize)(input)?;\n\n\n\n // unwrap() won't panic because we use take!(1) in parser above\n\n let chr = c.chars().next().unwrap();\n\n\n\n Ok((input, Specifier::Spacing(chr)))\n\n}\n\n\n", "file_path": "rust/libnewsboat/src/fmtstrformatter/parser.rs", "rank": 52, "score": 137954.14901965766 }, { "content": "fn conditional(input: &str) -> IResult<&str, Specifier> {\n\n // Prepared partial parsers\n\n let start_tag = tag(\"%?\");\n\n let condition = take(1usize);\n\n let then_tag = tag(\"?\");\n\n let then_branch = conditional_branch;\n\n let else_tag = tag(\"&\");\n\n let end_tag = tag(\"?\");\n\n\n\n let some_else_branch = |input| {\n\n let (input, _) = else_tag(input)?;\n\n let (input, els) = conditional_branch(input)?;\n\n let (input, _) = end_tag(input)?;\n\n Ok((input, Some(els)))\n\n };\n\n let none_else_branch = |input| {\n\n let (input, _) = end_tag(input)?;\n\n Ok((input, None))\n\n };\n\n let else_branch = alt((some_else_branch, none_else_branch));\n", "file_path": "rust/libnewsboat/src/fmtstrformatter/parser.rs", "rank": 53, "score": 137954.14901965766 }, { "content": "/// Recursively create directories if missing and set permissions accordingly.\n\npub fn mkdir_parents<R: AsRef<Path>>(p: &R, mode: u32) -> io::Result<()> {\n\n DirBuilder::new()\n\n .mode(mode)\n\n .recursive(true) // directories created with same security and permissions\n\n .create(p.as_ref())\n\n}\n\n\n", "file_path": "rust/libnewsboat/src/utils.rs", "rank": 54, "score": 136049.42519378493 }, { "content": "fn padded_format(input: &str) -> IResult<&str, Specifier> {\n\n let (input, _) = tag(\"%\")(input)?;\n\n let (input, width) =\n\n take_while(|chr: char| chr.is_ascii() && (chr.is_numeric() || chr == '-'))(input)?;\n\n let (input, format) = take(1usize)(input)?;\n\n\n\n // unwrap() won't fail because parser uses take!(1) to get exactly one character\n\n let format = format.chars().next().unwrap();\n\n\n\n let width = width.parse::<isize>().unwrap_or(0);\n\n let padding = match width.cmp(&0isize) {\n\n Ordering::Equal => Padding::None,\n\n Ordering::Greater => Padding::Left(width.abs() as usize),\n\n Ordering::Less => Padding::Right(width.abs() as usize),\n\n };\n\n\n\n Ok((input, Specifier::Format(format, padding)))\n\n}\n\n\n", "file_path": "rust/libnewsboat/src/fmtstrformatter/parser.rs", "rank": 55, "score": 135430.33194751944 }, { "content": "/// Skips one or more space characters.\n\n///\n\n/// This is different from `nom::character::complete::space1` in that this function only skips\n\n/// spaces (ASCII 0x20), whereas Nom's function also skips tabs.\n\nfn space1<'a, E: ParseError<&'a str>>(input: &'a str) -> IResult<&'a str, &'a str, E> {\n\n take_while1(|c| c == ' ')(input)\n\n}\n\n\n", "file_path": "rust/libnewsboat/src/filterparser.rs", "rank": 56, "score": 133187.49466281058 }, { "content": "/// Skips zero or more space characters.\n\n///\n\n/// This is different from `nom::character::complete::space0` in that this function only skips\n\n/// spaces (ASCII 0x20), whereas Nom's function also skips tabs.\n\nfn space0<'a, E: ParseError<&'a str>>(input: &'a str) -> IResult<&'a str, &'a str, E> {\n\n take_while(|c| c == ' ')(input)\n\n}\n\n\n", "file_path": "rust/libnewsboat/src/filterparser.rs", "rank": 57, "score": 133187.49466281058 }, { "content": "fn number<'a, E: ParseError<&'a str>>(input: &'a str) -> IResult<&'a str, &'a str, E> {\n\n recognize(tuple((opt(tag(\"-\")), take_while1(|c| is_digit(c as u8)))))(input)\n\n}\n\n\n", "file_path": "rust/libnewsboat/src/filterparser.rs", "rank": 58, "score": 133187.49466281058 }, { "content": "fn escaped_percent_sign(input: &str) -> IResult<&str, Specifier> {\n\n tag(\"%%\")(input).map(|result| (result.0, Specifier::Text(&result.1[0..1])))\n\n}\n\n\n", "file_path": "rust/libnewsboat/src/fmtstrformatter/parser.rs", "rank": 59, "score": 133061.78616959765 }, { "content": "fn text_inside_conditional(input: &str) -> IResult<&str, Specifier> {\n\n let (input, text) = take_till1(|chr: char| chr == '%' || chr == '&' || chr == '?')(input)?;\n\n\n\n Ok((input, Specifier::Text(text)))\n\n}\n\n\n", "file_path": "rust/libnewsboat/src/fmtstrformatter/parser.rs", "rank": 60, "score": 133061.78616959765 }, { "content": "fn text_outside_conditional(input: &str) -> IResult<&str, Specifier> {\n\n let (input, text) = take_till1(|chr: char| chr == '%')(input)?;\n\n\n\n Ok((input, Specifier::Text(text)))\n\n}\n\n\n", "file_path": "rust/libnewsboat/src/fmtstrformatter/parser.rs", "rank": 61, "score": 133061.78616959765 }, { "content": "fn parser(input: &str) -> IResult<&str, Vec<Specifier>> {\n\n let alternatives = (\n\n conditional,\n\n escaped_percent_sign,\n\n spacing,\n\n padded_format,\n\n text_outside_conditional,\n\n );\n\n many0(alt(alternatives))(input)\n\n}\n\n\n", "file_path": "rust/libnewsboat/src/fmtstrformatter/parser.rs", "rank": 62, "score": 131935.34739130532 }, { "content": "/// Peeks to see if input is either:\n\n/// - zero or more spaces followed by opening paren\n\n/// - one or more spaces\n\n///\n\n/// This is meant to be applied after matching \"and\" or \"or\" in the input. These logical operators\n\n/// require a space after them iff they're followed by something other than parenthesized\n\n/// expression. For example, these are all valid expressions:\n\n/// - \"x=1and y=0\"\n\n/// - \"x=1and(y=0)\"\n\n///\n\n/// While this one is invalid:\n\n/// - \"x=1andy=0\": no space between operator `and` and attribute name `y`\n\nfn space_after_logop<'a, E: ParseError<&'a str>>(input: &'a str) -> IResult<&'a str, &'a str, E> {\n\n let opt_space_and_paren = recognize(tuple((space0, tag(\"(\"))));\n\n let parser = alt((opt_space_and_paren, space1));\n\n peek(parser)(input)\n\n}\n\n\n", "file_path": "rust/libnewsboat/src/filterparser.rs", "rank": 63, "score": 131317.5967183477 }, { "content": "fn conditional_branch(input: &str) -> IResult<&str, Vec<Specifier>> {\n\n let alternatives = (\n\n escaped_percent_sign,\n\n spacing,\n\n padded_format,\n\n text_inside_conditional,\n\n );\n\n many0(alt(alternatives))(input)\n\n}\n\n\n", "file_path": "rust/libnewsboat/src/fmtstrformatter/parser.rs", "rank": 64, "score": 129566.8016133835 }, { "content": "#[doc(hidden)]\n\npub fn fmt_arg_with_buffer_size<T>(\n\n format_cstring: &CStr,\n\n arg_c_repr_holder: &T,\n\n buf_size: usize,\n\n) -> Result<String, usize>\n\nwhere\n\n T: CReprHolder,\n\n{\n\n let mut buffer = Vec::<u8>::with_capacity(buf_size);\n\n let buffer_ptr = buffer.as_mut_ptr();\n\n unsafe {\n\n // We're passing the buffer to C, so let's make Rust forget about it for a while.\n\n mem::forget(buffer);\n\n\n\n let bytes_written = libc::snprintf(\n\n buffer_ptr as *mut libc::c_char,\n\n buf_size as libc::size_t,\n\n format_cstring.as_ptr() as *const libc::c_char,\n\n arg_c_repr_holder.to_c_repr(),\n\n ) as usize;\n", "file_path": "rust/strprintf/src/lib.rs", "rank": 65, "score": 128604.04448706389 }, { "content": "/// Returns a global logger instance.\n\n///\n\n/// This logger exists for the duration of the program. It's better to set the loglevel and\n\n/// logfiles as early as possible, so no messages are lost.\n\npub fn get_instance() -> &'static Logger {\n\n GLOBAL_LOGGER.get_or_init(Logger::new)\n\n}\n\n\n\n/// Convenience macro for logging.\n\n///\n\n/// Most of the time, you should just use this. For example:\n\n/// ```no_run\n\n/// use libnewsboat::{log, logger::{self, Level}};\n\n///\n\n/// fn super_cool_function(value: u32) {\n\n/// log!(Level::Debug, \"super_cool_function(): value = {}\", value);\n\n/// }\n\n/// ```\n\n#[macro_export]\n\nmacro_rules! log {\n\n ( $level:expr, $message:expr ) => {\n\n logger::get_instance().log($level, $message);\n\n };\n\n ( $level:expr, $format:expr, $( $arg:expr ),+ ) => {\n", "file_path": "rust/libnewsboat/src/logger.rs", "rank": 66, "score": 125987.37445085742 }, { "content": "fn parens<'a, E: ParseError<&'a str>>(input: &'a str) -> IResult<&'a str, Expression, E> {\n\n let (input, _) = tag(\"(\")(input)?;\n\n let (input, _) = space0(input)?;\n\n let (input, result) = alt((expression, parens, comparison))(input)?;\n\n let (input, _) = space0(input)?;\n\n let (leftovers, _) = tag(\")\")(input)?;\n\n\n\n Ok((leftovers, result))\n\n}\n\n\n", "file_path": "rust/libnewsboat/src/filterparser.rs", "rank": 67, "score": 124327.37626359059 }, { "content": "fn expression<'a, E: ParseError<&'a str>>(input: &'a str) -> IResult<&'a str, Expression, E> {\n\n // `Expression`s enum variants can't be used as return values without filling in their\n\n // arguments, so we have to create another enum, which variants we can return and `match` on.\n\n // This is better than matching on bare strings returned by `tag`, as it enables us to write an\n\n // exhaustive `match` that the compiler can validate is exhaustive: we won't be able to add\n\n // a `tag` to the parser and forget to handle it.\n\n #[derive(Clone)]\n\n enum Op {\n\n And,\n\n Or,\n\n };\n\n\n\n let (input, left) = alt((parens, comparison))(input)?;\n\n let (input, _) = space0(input)?;\n\n let (input, op) = terminated(\n\n alt((value(Op::And, tag(\"and\")), value(Op::Or, tag(\"or\")))),\n\n space_after_logop,\n\n )(input)?;\n\n let (input, _) = space0(input)?;\n\n let (leftovers, right) = alt((expression, parens, comparison))(input)?;\n\n\n\n let op = match op {\n\n Op::And => Expression::And(Box::new(left), Box::new(right)),\n\n Op::Or => Expression::Or(Box::new(left), Box::new(right)),\n\n };\n\n\n\n Ok((leftovers, op))\n\n}\n\n\n", "file_path": "rust/libnewsboat/src/filterparser.rs", "rank": 68, "score": 124327.37626359059 }, { "content": "fn range<'a, E: ParseError<&'a str>>(input: &'a str) -> IResult<&'a str, Value, E> {\n\n separated_pair(number, tag(\":\"), number)(input)\n\n .map(|(leftovers, (a, b))| (leftovers, Value(format!(\"{}:{}\", a, b))))\n\n}\n\n\n", "file_path": "rust/libnewsboat/src/filterparser.rs", "rank": 69, "score": 124327.37626359059 }, { "content": "fn parser<'a, E: ParseError<&'a str>>(input: &'a str) -> IResult<&'a str, Expression, E> {\n\n let parsers = alt((expression, parens, comparison));\n\n // Ignore leading and trailing whitespace\n\n let parsers = delimited(space0, parsers, space0);\n\n // Try to parse input. If parser says it needs more data, make that an error, since `input` is\n\n // all we got.\n\n complete(parsers)(input)\n\n}\n\n\n", "file_path": "rust/libnewsboat/src/filterparser.rs", "rank": 70, "score": 124327.37626359059 }, { "content": "fn operators<'a, E: ParseError<&'a str>>(input: &'a str) -> IResult<&'a str, Operator, E> {\n\n alt((\n\n value(Operator::RegexMatches, tag(\"=~\")),\n\n value(Operator::Equals, alt((tag(\"==\"), tag(\"=\")))),\n\n value(Operator::NotRegexMatches, tag(\"!~\")),\n\n value(Operator::NotEquals, tag(\"!=\")),\n\n value(Operator::LessThanOrEquals, tag(\"<=\")),\n\n value(Operator::GreaterThanOrEquals, tag(\">=\")),\n\n value(Operator::LessThan, tag(\"<\")),\n\n value(Operator::GreaterThan, tag(\">\")),\n\n value(Operator::Between, tag(\"between\")),\n\n value(Operator::Contains, tag(\"#\")),\n\n value(Operator::NotContains, tag(\"!#\")),\n\n ))(input)\n\n}\n\n\n", "file_path": "rust/libnewsboat/src/filterparser.rs", "rank": 71, "score": 124327.37626359059 }, { "content": "fn comparison<'a, E: ParseError<&'a str>>(input: &'a str) -> IResult<&'a str, Expression, E> {\n\n let attribute_name =\n\n take_while1(|c| is_alphanumeric(c as u8) || c == '_' || c == '-' || c == '.');\n\n\n\n let (input, attr) = attribute_name(input)?;\n\n let attribute = attr.to_string();\n\n let (input, _) = space0(input)?;\n\n let (input, op) = operators(input)?;\n\n let (input, _) = space0(input)?;\n\n let (leftovers, value) =\n\n alt((quoted_string, range, map(number, |n| Value(n.to_string()))))(input)?;\n\n\n\n Ok((\n\n leftovers,\n\n Expression::Comparison {\n\n attribute,\n\n op,\n\n value,\n\n },\n\n ))\n\n}\n\n\n", "file_path": "rust/libnewsboat/src/filterparser.rs", "rank": 72, "score": 124327.37626359059 }, { "content": "#[cfg(not(target_os = \"windows\"))]\n\npub fn home_dir() -> Option<PathBuf> {\n\n // This function got deprecated because it examines HOME environment variable even on Windows,\n\n // which is wrong. But Newsboat doesn't support Windows, so we're fine using that.\n\n //\n\n // Cf. https://github.com/rust-lang/rust/issues/28940\n\n #[allow(deprecated)]\n\n std::env::home_dir()\n\n}\n\n\n", "file_path": "rust/libnewsboat/src/utils.rs", "rank": 73, "score": 123110.92684384242 }, { "content": " class StringType = std::string, class BooleanType = bool,\n", "file_path": "3rd-party/json.hpp", "rank": 74, "score": 119305.04282580531 }, { "content": "struct is_constructible_string_type_impl : std::false_type {};\n\n\n\ntemplate <typename BasicJsonType, typename ConstructibleStringType>\n", "file_path": "3rd-party/json.hpp", "rank": 75, "score": 118907.07431140589 }, { "content": "struct is_compatible_string_type_impl : std::false_type {};\n\n\n\ntemplate <typename BasicJsonType, typename CompatibleStringType>\n", "file_path": "3rd-party/json.hpp", "rank": 76, "score": 118907.07431140589 }, { "content": "struct is_constructible_string_type_impl <\n\n BasicJsonType, ConstructibleStringType,\n\n enable_if_t<is_detected_exact<typename BasicJsonType::string_t::value_type,\n\n value_type_t, ConstructibleStringType>::value >>\n\n{\n\n static constexpr auto value =\n\n std::is_constructible<ConstructibleStringType,\n\n typename BasicJsonType::string_t>::value;\n\n};\n\n\n\ntemplate <typename BasicJsonType, typename ConstructibleStringType>\n", "file_path": "3rd-party/json.hpp", "rank": 77, "score": 118223.86994305263 }, { "content": "struct is_compatible_string_type_impl <\n\n BasicJsonType, CompatibleStringType,\n\n enable_if_t<is_detected_exact<typename BasicJsonType::string_t::value_type,\n\n value_type_t, CompatibleStringType>::value >>\n\n{\n\n static constexpr auto value =\n\n std::is_constructible<typename BasicJsonType::string_t, CompatibleStringType>::value;\n\n};\n\n\n\ntemplate <typename BasicJsonType, typename ConstructibleStringType>\n", "file_path": "3rd-party/json.hpp", "rank": 78, "score": 118223.86994305263 }, { "content": "fn get_location(panic_info: &PanicInfo) -> String {\n\n match panic_info.location() {\n\n Some(location) => format!(\"Crash location: {}:{}\", location.file(), location.line()),\n\n None => String::from(\"Crash location unknown\"),\n\n }\n\n}\n", "file_path": "rust/libnewsboat/src/human_panic.rs", "rank": 79, "score": 118190.882817834 }, { "content": "fn get_error_message(panic_info: &PanicInfo) -> String {\n\n let payload = panic_info.payload().downcast_ref::<&str>();\n\n if let Some(payload) = payload {\n\n format!(\"Message: {}\", &payload)\n\n } else {\n\n String::from(\"No error message\")\n\n }\n\n}\n\n\n", "file_path": "rust/libnewsboat/src/human_panic.rs", "rank": 80, "score": 115905.91237695242 }, { "content": "#[cfg(feature = \"nightly\")]\n\nfn get_crash_cause(panic_info: &PanicInfo) -> String {\n\n match panic_info.message() {\n\n Some(m) => format!(\"Crash cause: {}\", m),\n\n None => \"Crash cause unknown\".into(),\n\n };\n\n}\n\n\n", "file_path": "rust/libnewsboat/src/human_panic.rs", "rank": 81, "score": 115905.91237695242 }, { "content": "#[cfg(not(feature = \"nightly\"))]\n\nfn get_crash_cause(_panic_info: &PanicInfo) -> String {\n\n String::from(\"Couldn't determine the crash cause.\")\n\n}\n\n\n", "file_path": "rust/libnewsboat/src/human_panic.rs", "rank": 82, "score": 115905.91237695242 }, { "content": "#[test]\n\nfn t_getcwd_returns_non_empty_string() {\n\n let result = utils::getcwd();\n\n assert!(result.is_ok());\n\n assert_ne!(result.unwrap(), Path::new(\"\"));\n\n}\n", "file_path": "rust/libnewsboat/tests/getcwd_returns_non-empty_string.rs", "rank": 83, "score": 113495.85283293691 }, { "content": "/// Replaces tilde (`~`) at the beginning of the path with the path to user's home directory.\n\npub fn resolve_tilde(path: PathBuf) -> PathBuf {\n\n if let (Some(home), Ok(suffix)) = (home_dir(), path.strip_prefix(\"~\")) {\n\n return home.join(suffix);\n\n }\n\n\n\n // Either the `path` doesn't start with tilde, or we couldn't figure out the path to the\n\n // home directory -- either way, it's no big deal. Let's return the original string.\n\n path\n\n}\n\n\n", "file_path": "rust/libnewsboat/src/utils.rs", "rank": 84, "score": 113433.53926429746 }, { "content": "/// Get the current working directory.\n\npub fn getcwd() -> Result<PathBuf, io::Error> {\n\n use std::env;\n\n env::current_dir()\n\n}\n\n\n", "file_path": "rust/libnewsboat/src/utils.rs", "rank": 85, "score": 112045.73680363073 }, { "content": "pub fn assert_create_dirs_returns_false(tmp: &TempDir) {\n\n let readonly = libc::S_IRUSR | libc::S_IXUSR;\n\n let _home_chmod = Chmod::new(&tmp.path(), readonly);\n\n\n\n let paths = ConfigPaths::new();\n\n assert!(paths.initialized());\n\n assert!(!paths.create_dirs());\n\n}\n", "file_path": "rust/libnewsboat/tests/configpaths_helpers/mod.rs", "rank": 86, "score": 111595.02702426478 }, { "content": "class output_string_adapter : public output_adapter_protocol<CharType>\n\n{\n\n public:\n\n explicit output_string_adapter(StringType& s) noexcept\n\n : str(s)\n\n {}\n\n\n\n void write_character(CharType c) override\n\n {\n\n str.push_back(c);\n\n }\n\n\n\n JSON_HEDLEY_NON_NULL(2)\n\n void write_characters(const CharType* s, std::size_t length) override\n\n {\n\n str.append(s, length);\n\n }\n\n\n\n private:\n\n StringType& str;\n\n};\n\n\n\ntemplate<typename CharType, typename StringType = std::basic_string<CharType>>\n", "file_path": "3rd-party/json.hpp", "rank": 87, "score": 111165.41985647664 }, { "content": "pub fn assert_dotdir_not_migrated(dotdir: &path::Path) {\n\n let mut paths = ConfigPaths::new();\n\n assert!(paths.initialized());\n\n\n\n // Shouldn't migrate anything, so should return false.\n\n assert!(!paths.try_migrate_from_newsbeuter());\n\n\n\n assert!(!is_readable(&dotdir.join(\"config\")));\n\n assert!(!is_readable(&dotdir.join(\"urls\")));\n\n\n\n assert!(!is_readable(&dotdir.join(\"cache.db\")));\n\n assert!(!is_readable(&dotdir.join(\"queue\")));\n\n assert!(!is_readable(&dotdir.join(\"history.search\")));\n\n assert!(!is_readable(&dotdir.join(\"history.cmdline\")));\n\n}\n\n\n", "file_path": "rust/libnewsboat/tests/configpaths_helpers/mod.rs", "rank": 88, "score": 111148.49860728513 }, { "content": "/// Returns positions of the first two percent signs in the string, or None if there are less than\n\n/// two percent signs.\n\nfn find_percent_signs(input: &str) -> Option<(usize, usize)> {\n\n input.find('%').and_then(|first| {\n\n input[first + 1..]\n\n .find('%')\n\n .map(|second| (first, first + 1 + second))\n\n })\n\n}\n\n\n\nimpl<'a> Iterator for SpecifiersIterator<'a> {\n\n type Item = &'a str;\n\n\n\n fn next(&mut self) -> Option<Self::Item> {\n\n let mut pair;\n\n let mut current_offset = 0usize;\n\n loop {\n\n pair = find_percent_signs(&self.current_string[current_offset..])\n\n .map(|(first, second)| (first + current_offset, second + current_offset));\n\n match pair {\n\n Some((first, second)) if second - first == 1 => {\n\n // Found an escaped percent sign; continue the search after it\n", "file_path": "rust/strprintf/src/specifiers_iterator.rs", "rank": 89, "score": 107356.92467873977 }, { "content": "pub fn mock_newsboat_dotdir(tmp: &TempDir) -> FileSentries {\n\n let sentries = FileSentries::new();\n\n\n\n let dotdir_path = tmp.path().join(\".newsboat\");\n\n mock_dotdir(&dotdir_path, &sentries);\n\n\n\n sentries\n\n}\n\n\n", "file_path": "rust/libnewsboat/tests/configpaths_helpers/mod.rs", "rank": 90, "score": 107033.81925109113 }, { "content": "#[no_mangle]\n\npub fn matcher_error_to_ffi(error: MatcherError) -> MatcherErrorFfi {\n\n abort_on_panic(|| {\n\n match error {\n\n MatcherError::AttributeUnavailable { attr } => {\n\n // NUL bytes in filter expressions are disallowed by the parser, so attribute name is\n\n // safe and unwrap() here won't ever be triggered.\n\n let info = CString::new(attr).unwrap().into_raw();\n\n MatcherErrorFfi {\n\n err_type: ATTRIB_UNAVAIL,\n\n info,\n\n info2: ptr::null_mut(),\n\n }\n\n }\n\n\n\n MatcherError::InvalidRegex { regex, errmsg } => {\n\n // NUL bytes in filter expressions are disallowed by the parser, so regex here is safe\n\n // and unwrap() won't be triggered.\n\n let info = CString::new(regex).unwrap().into_raw();\n\n // Error message comes from regerror, which is a C function. Since it returns\n\n // a C string, it's obvious that errmsg won't contain NUL bytes. Thus, unwrap() here\n", "file_path": "rust/libnewsboat-ffi/src/matchererror.rs", "rank": 91, "score": 107033.81925109113 }, { "content": "pub fn mock_newsbeuter_dotdir(tmp: &TempDir) -> FileSentries {\n\n let sentries = FileSentries::new();\n\n\n\n let dotdir_path = tmp.path().join(\".newsbeuter\");\n\n mock_dotdir(&dotdir_path, &sentries);\n\n\n\n sentries\n\n}\n\n\n", "file_path": "rust/libnewsboat/tests/configpaths_helpers/mod.rs", "rank": 92, "score": 107033.81925109113 }, { "content": "pub fn mock_newsboat_xdg_dirs(tmp: &TempDir) -> FileSentries {\n\n let config_dir_path = tmp.path().join(\".config\").join(\"newsboat\");\n\n let data_dir_path = tmp.path().join(\".local\").join(\"share\").join(\"newsboat\");\n\n mock_xdg_dirs(&config_dir_path, &data_dir_path)\n\n}\n\n\n", "file_path": "rust/libnewsboat/tests/configpaths_helpers/mod.rs", "rank": 93, "score": 105174.89972071245 }, { "content": "pub fn mock_newsbeuter_xdg_dirs(tmp: &TempDir) -> FileSentries {\n\n let config_dir_path = tmp.path().join(\".config\").join(\"newsbeuter\");\n\n let data_dir_path = tmp.path().join(\".local\").join(\"share\").join(\"newsbeuter\");\n\n mock_xdg_dirs(&config_dir_path, &data_dir_path)\n\n}\n\n\n", "file_path": "rust/libnewsboat/tests/configpaths_helpers/mod.rs", "rank": 94, "score": 105174.89972071245 }, { "content": "pub fn resolve_relative(reference: &Path, path: &Path) -> PathBuf {\n\n if path.is_relative() {\n\n // Will only ever panic if reference is `/`, which shouldn't be the case as reference is\n\n // always a file path\n\n return reference.parent().unwrap().join(path);\n\n }\n\n path.to_path_buf()\n\n}\n\n\n", "file_path": "rust/libnewsboat/src/utils.rs", "rank": 95, "score": 104010.80664432206 }, { "content": "struct StringMaker<std::pair<newsboat::LineType, std::string>> {\n\n\tstatic std::string convert(\n\n\t\tstd::pair<newsboat::LineType, std::string> const& value)\n\n\t{\n\n\t\tstd::ostringstream o;\n\n\t\to << \"(\";\n\n\t\to << toString(value.first);\n\n\t\to << \", \\\"\";\n\n\t\to << value.second;\n\n\t\to << \"\\\")\";\n\n\t\treturn o.str();\n\n\t}\n\n};\n\n} // namespace Catch\n\n\n\nTEST_CASE(\n\n\t\"Links are rendered as underlined text with reference number in \"\n\n\t\"square brackets\",\n\n\t\"[HtmlRenderer]\")\n\n{\n", "file_path": "test/htmlrenderer.cpp", "rank": 96, "score": 102863.20877561954 }, { "content": "fn evaluate_expression(expr: &Expression, item: &impl Matchable) -> Result<bool, MatcherError> {\n\n match expr {\n\n Comparison {\n\n attribute,\n\n op,\n\n value,\n\n } => match item.attribute_value(&attribute) {\n\n None => Err(MatcherError::AttributeUnavailable {\n\n attr: attribute.clone(),\n\n }),\n\n\n\n Some(ref attr) => op.apply(attr, &value),\n\n },\n\n And(left, right) => evaluate_expression(left, item).and_then(|result| {\n\n if result {\n\n evaluate_expression(right, item)\n\n } else {\n\n Ok(false)\n\n }\n\n }),\n", "file_path": "rust/libnewsboat/src/matcher.rs", "rank": 97, "score": 94827.7817828386 }, { "content": "fn mkdir<R: AsRef<Path>>(path: R, mode: u32) -> io::Result<()> {\n\n DirBuilder::new().mode(mode).create(path.as_ref())\n\n}\n\n\n", "file_path": "rust/libnewsboat/src/configpaths.rs", "rank": 98, "score": 94616.289873793 }, { "content": "pub fn assert_xdg_not_migrated(config_dir: &path::Path, data_dir: &path::Path) {\n\n let mut paths = ConfigPaths::new();\n\n assert!(paths.initialized());\n\n\n\n // Shouldn't migrate anything, so should return false.\n\n assert!(!paths.try_migrate_from_newsbeuter());\n\n\n\n assert!(!is_readable(&config_dir.join(\"config\")));\n\n assert!(!is_readable(&config_dir.join(\"urls\")));\n\n\n\n assert!(!is_readable(&data_dir.join(\"cache.db\")));\n\n assert!(!is_readable(&data_dir.join(\"queue\")));\n\n assert!(!is_readable(&data_dir.join(\"history.search\")));\n\n assert!(!is_readable(&data_dir.join(\"history.cmdline\")));\n\n}\n\n\n\n/// Sets new permissions on a given path, and restores them back when the\n\n/// object is destroyed.\n\npub struct Chmod<'a> {\n\n path: &'a path::Path,\n", "file_path": "rust/libnewsboat/tests/configpaths_helpers/mod.rs", "rank": 99, "score": 91811.3832983107 } ]
Rust
src/bf.rs
ruslashev/bfga
673f382e2b70a86a5b661f0ffb494579e39afb61
#[derive(Clone)] pub enum BfErr { SyntaxError, InstrLimitExceeded, LogicError, } pub type BfResult = Result<(String, u64), BfErr>; impl std::fmt::Display for BfErr { fn fmt(&self, f: &mut std::fmt::Formatter) -> std::fmt::Result { match self { BfErr::SyntaxError => write!(f, "syntax error"), BfErr::InstrLimitExceeded => write!(f, "instruction limit exceeded"), BfErr::LogicError => write!(f, "logic error"), } } } const TAPE_SIZE: usize = 1_000; fn check_bf_syntax(src: &Vec<char>) -> bool { let mut balance = 0; for instr in src { balance += match instr { '[' => 1, ']' => -1, _ => 0 }; if balance < 0 { return false } } balance == 0 } fn find_matching_brackets(src: &Vec<char>) -> Vec<usize> { let mut matching_brackets = vec![0; src.len()]; let mut count = 0; let mut idx_per_count = vec![0; src.len()]; for (idx, &instr) in src.iter().enumerate() { if instr == '[' { idx_per_count[count] = idx; count += 1; } else if instr == ']' { count -= 1; matching_brackets[idx_per_count[count]] = idx; matching_brackets[idx] = idx_per_count[count]; } } matching_brackets } pub fn interpret_brainfuck(src: &Vec<char>, max_intructions: u64) -> BfResult { let mut instr_ptr: usize = 0; let mut tape_ptr: usize = 0; let mut tape: [u8; TAPE_SIZE] = [0; TAPE_SIZE]; let mut num_instructions = 0; let mut output = String::from(""); if check_bf_syntax(src) == false { return Err(BfErr::SyntaxError) } let matching_brackets = find_matching_brackets(src); loop { if instr_ptr >= src.len() { break } if max_intructions != 0 { num_instructions += 1; if num_instructions > max_intructions { return Err(BfErr::InstrLimitExceeded) } } let instr: char = src[instr_ptr]; instr_ptr = match instr { '+' => { tape[tape_ptr] = tape[tape_ptr].wrapping_add(1); instr_ptr + 1 } '-' => { tape[tape_ptr] = tape[tape_ptr].wrapping_sub(1); instr_ptr + 1 } '>' => { if tape_ptr < TAPE_SIZE - 1 { tape_ptr += 1 } else { return Err(BfErr::LogicError); } instr_ptr + 1 } '<' => { if tape_ptr > 0 { tape_ptr -= 1 } else { return Err(BfErr::LogicError); } instr_ptr + 1 } '[' => { if tape[tape_ptr] == 0 { matching_brackets[instr_ptr] } else { instr_ptr + 1 } } ']' => { if tape[tape_ptr] != 0 { matching_brackets[instr_ptr] } else { instr_ptr + 1 } } '.' => { output.push(tape[tape_ptr] as char); instr_ptr + 1 } _ => instr_ptr + 1, } } Ok((output, num_instructions)) } #[test] fn hello_world_test() { let src = "++++++++[>++++[>++>+++>+++>+<<<<-]>+>+>->>+[<]<-]>>.> ---.+++++++..+++.>>.<-.<.+++.------.--------.>>+.>++."; match interpret_brainfuck(&src.chars().collect(), 10_000) { Ok((output, _)) => assert_eq!(output, "Hello World!\n"), Err(_) => panic!("oopsie") } } #[test] fn matching_brackets_test() { let src = ".[..[]..[].]."; let expected = vec![0, 11, 0, 0, 5, 4, 0, 0, 9, 8, 0, 1, 0]; assert_eq!(expected, find_matching_brackets(&src.chars().collect())); }
#[derive(Clone)] pub enum BfErr { SyntaxError, InstrLimitExceeded, LogicError, } pub type BfResult = Result<(String, u64), BfErr>; impl std::fmt::Display for BfErr {
} const TAPE_SIZE: usize = 1_000; fn check_bf_syntax(src: &Vec<char>) -> bool { let mut balance = 0; for instr in src { balance += match instr { '[' => 1, ']' => -1, _ => 0 }; if balance < 0 { return false } } balance == 0 } fn find_matching_brackets(src: &Vec<char>) -> Vec<usize> { let mut matching_brackets = vec![0; src.len()]; let mut count = 0; let mut idx_per_count = vec![0; src.len()]; for (idx, &instr) in src.iter().enumerate() { if instr == '[' { idx_per_count[count] = idx; count += 1; } else if instr == ']' { count -= 1; matching_brackets[idx_per_count[count]] = idx; matching_brackets[idx] = idx_per_count[count]; } } matching_brackets } pub fn interpret_brainfuck(src: &Vec<char>, max_intructions: u64) -> BfResult { let mut instr_ptr: usize = 0; let mut tape_ptr: usize = 0; let mut tape: [u8; TAPE_SIZE] = [0; TAPE_SIZE]; let mut num_instructions = 0; let mut output = String::from(""); if check_bf_syntax(src) == false { return Err(BfErr::SyntaxError) } let matching_brackets = find_matching_brackets(src); loop { if instr_ptr >= src.len() { break } if max_intructions != 0 { num_instructions += 1; if num_instructions > max_intructions { return Err(BfErr::InstrLimitExceeded) } } let instr: char = src[instr_ptr]; instr_ptr = match instr { '+' => { tape[tape_ptr] = tape[tape_ptr].wrapping_add(1); instr_ptr + 1 } '-' => { tape[tape_ptr] = tape[tape_ptr].wrapping_sub(1); instr_ptr + 1 } '>' => { if tape_ptr < TAPE_SIZE - 1 { tape_ptr += 1 } else { return Err(BfErr::LogicError); } instr_ptr + 1 } '<' => { if tape_ptr > 0 { tape_ptr -= 1 } else { return Err(BfErr::LogicError); } instr_ptr + 1 } '[' => { if tape[tape_ptr] == 0 { matching_brackets[instr_ptr] } else { instr_ptr + 1 } } ']' => { if tape[tape_ptr] != 0 { matching_brackets[instr_ptr] } else { instr_ptr + 1 } } '.' => { output.push(tape[tape_ptr] as char); instr_ptr + 1 } _ => instr_ptr + 1, } } Ok((output, num_instructions)) } #[test] fn hello_world_test() { let src = "++++++++[>++++[>++>+++>+++>+<<<<-]>+>+>->>+[<]<-]>>.> ---.+++++++..+++.>>.<-.<.+++.------.--------.>>+.>++."; match interpret_brainfuck(&src.chars().collect(), 10_000) { Ok((output, _)) => assert_eq!(output, "Hello World!\n"), Err(_) => panic!("oopsie") } } #[test] fn matching_brackets_test() { let src = ".[..[]..[].]."; let expected = vec![0, 11, 0, 0, 5, 4, 0, 0, 9, 8, 0, 1, 0]; assert_eq!(expected, find_matching_brackets(&src.chars().collect())); }
fn fmt(&self, f: &mut std::fmt::Formatter) -> std::fmt::Result { match self { BfErr::SyntaxError => write!(f, "syntax error"), BfErr::InstrLimitExceeded => write!(f, "instruction limit exceeded"), BfErr::LogicError => write!(f, "logic error"), } }
function_block-full_function
[ { "content": "fn fitness(chromosome: &Chromosome, bf_result: &bf::BfResult) -> u64 {\n\n let fitness = match bf_result {\n\n Ok((output, num_instructions)) => {\n\n let diff = string_difference(&output, TARGET);\n\n let length_term =\n\n if diff == 0 {\n\n program_length(chromosome) + num_instructions\n\n } else {\n\n FIXED_PROGRAM_LENGTH_FITNESS_COST\n\n };\n\n\n\n diff + length_term\n\n },\n\n Err(_) => BAD_PROGRAM_PENALTY\n\n };\n\n\n\n fitness\n\n}\n\n\n", "file_path": "src/main.rs", "rank": 1, "score": 37085.651700057584 }, { "content": "type Gene = char;\n\n\n", "file_path": "src/main.rs", "rank": 2, "score": 35953.944958564636 }, { "content": "#[test]\n\npub fn rand_test() {\n\n let attempts = 10;\n\n\n\n for seed in 1..attempts {\n\n let mut rng = Wyhash64RNG::new_fixed(seed);\n\n let iterations = 10000000;\n\n let mut sum = 0;\n\n let max = 1000;\n\n let err = 1.;\n\n\n\n for _ in 1..iterations {\n\n sum += 1 + rng.gen() % max;\n\n }\n\n\n\n let avg = (sum as f64) / (iterations as f64);\n\n let mexp = (max as f64) / 2.;\n\n\n\n assert!((avg - mexp).abs() < err);\n\n }\n\n}\n\n\n", "file_path": "src/rand.rs", "rank": 3, "score": 35439.31760428769 }, { "content": "#[test]\n\npub fn rand_test_range() {\n\n let attempts = 10;\n\n\n\n for seed in 1..attempts {\n\n let mut rng = Wyhash64RNG::new_fixed(seed);\n\n let iterations = 10000000;\n\n let mut sum = 0;\n\n let min = 500;\n\n let max = 1500;\n\n let err = 1.;\n\n\n\n for _ in 1..iterations {\n\n sum += rng.gen_in_range(min, max)\n\n }\n\n\n\n let avg = (sum as f64) / (iterations as f64);\n\n let mexp = ((max as f64) + (min as f64)) / 2.;\n\n\n\n assert!((avg - mexp).abs() < err);\n\n }\n\n}\n\n\n", "file_path": "src/rand.rs", "rank": 4, "score": 34611.51309230694 }, { "content": "fn time_seed() -> u64 {\n\n let now = time::SystemTime::now();\n\n let full = now.duration_since(time::UNIX_EPOCH).unwrap();\n\n\n\n u64::from(full.subsec_nanos())\n\n}\n\n\n", "file_path": "src/rand.rs", "rank": 5, "score": 34232.60915373852 }, { "content": "type Population = Vec<Individual>;\n\n\n\nimpl Individual {\n\n fn new(chromosome: Chromosome) -> Individual {\n\n let bf_result = bf::interpret_brainfuck(&chromosome, INSTR_LIMIT);\n\n let fitness = fitness(&chromosome, &bf_result);\n\n\n\n Individual { chromosome, bf_result, fitness }\n\n }\n\n}\n\n\n\nimpl std::fmt::Display for Individual {\n\n fn fmt(&self, f: &mut std::fmt::Formatter) -> std::fmt::Result {\n\n match &self.bf_result {\n\n Ok((output, _)) => write!(f, \"output: \\\"{}\\\"\", output),\n\n Err(err) => write!(f, \"{}\", err),\n\n }\n\n }\n\n}\n\n\n", "file_path": "src/main.rs", "rank": 6, "score": 33535.292145796455 }, { "content": "type Chromosome = Vec<Gene>;\n\n\n", "file_path": "src/main.rs", "rank": 7, "score": 33535.292145796455 }, { "content": "type Rng = rand::Wyhash64RNG;\n\n\n", "file_path": "src/main.rs", "rank": 8, "score": 32714.965697885717 }, { "content": "fn program_length(chromosome: &Chromosome) -> u64 {\n\n chromosome.iter().fold(0, |sum, &x| sum + if x == ' ' { 0 } else { 1 })\n\n}\n\n\n", "file_path": "src/main.rs", "rank": 9, "score": 29985.55488638456 }, { "content": "fn string_difference(x: &str, y: &str) -> u64 {\n\n let mut difference: u64 = 0;\n\n\n\n if x == y {\n\n return 0\n\n }\n\n\n\n if x.len() == y.len() {\n\n for i in 0..x.len() {\n\n difference += (x.as_bytes()[i] as i16 - y.as_bytes()[i] as i16).abs() as u64\n\n }\n\n return difference\n\n }\n\n\n\n let (smaller, larger): (&str, &str) = if x.len() < y.len() { (x, y) } else { (y, x) };\n\n\n\n for i in 0..smaller.len() {\n\n difference += (smaller.as_bytes()[i] as i16 - larger.as_bytes()[i] as i16).abs() as u64\n\n }\n\n\n\n for i in smaller.len()..larger.len() {\n\n difference += larger.as_bytes()[i] as u64\n\n }\n\n\n\n difference\n\n}\n\n\n", "file_path": "src/main.rs", "rank": 10, "score": 28018.596399885326 }, { "content": "fn tournament_select(rng: &mut Rng, population: &Population, k: u64) -> usize {\n\n let mut best = rng.gen_in_size(population.len());\n\n\n\n for _ in 0..k - 1 {\n\n let candidate = rng.gen_in_size(population.len());\n\n\n\n if population[candidate].fitness < population[best].fitness {\n\n best = candidate;\n\n }\n\n }\n\n\n\n best\n\n}\n\n\n", "file_path": "src/main.rs", "rank": 11, "score": 23532.04520668021 }, { "content": "use std::time;\n\n\n\npub struct Wyhash64RNG {\n\n state: u64,\n\n}\n\n\n\nimpl Wyhash64RNG {\n\n pub fn new() -> Wyhash64RNG {\n\n Self::new_fixed(time_seed())\n\n }\n\n\n\n pub fn new_fixed(seed: u64) -> Wyhash64RNG {\n\n Wyhash64RNG { state: seed }\n\n }\n\n\n\n pub fn gen(&mut self) -> u64 {\n\n self.state = self.state.wrapping_add(0x60bee2bee120fc15);\n\n let mut tmp: u128 = (self.state as u128).wrapping_mul(0xa3b195354a39b70d);\n\n let m1: u64 = ((tmp >> 64) ^ tmp) as u64;\n\n tmp = (m1 as u128).wrapping_mul(0x1b03738712fad5c9);\n", "file_path": "src/rand.rs", "rank": 12, "score": 3.209484319826711 }, { "content": " ((tmp >> 64) ^ tmp) as u64\n\n }\n\n\n\n pub fn gen_in_range(&mut self, min: u64, max: u64) -> u64 {\n\n min + Self::gen(self) % (max - min + 1)\n\n }\n\n\n\n pub fn gen_in_size(&mut self, max: usize) -> usize {\n\n Self::gen_in_range(self, 0, (max - 1) as u64) as usize\n\n }\n\n\n\n pub fn gen_percent(&mut self) -> u64 {\n\n Self::gen_in_range(self, 0, 100)\n\n }\n\n}\n\n\n", "file_path": "src/rand.rs", "rank": 13, "score": 3.086739902654919 }, { "content": "use ctrlc;\n\nuse std::sync::{atomic, Arc};\n\nmod bf;\n\nmod rand;\n\n\n\nconst INITIAL_POPULATION_SIZE: u64 = 2000;\n\nconst MUTATION_PROB_PERC: u64 = 10;\n\nconst ELITISM_RATIO: f64 = 5. / 100.;\n\nconst INITIAL_PROGRAM_LENGTH: usize = 100;\n\nconst INSTR_LIMIT: u64 = 100_000;\n\nconst BAD_PROGRAM_PENALTY: u64 = 100000;\n\nconst FIXED_PROGRAM_LENGTH_FITNESS_COST: u64 = 10000;\n\nconst TOURNAMENT_SIZE: u64 = 2;\n\nconst REMOVE_MUT_PROB: u64 = 20;\n\nconst INSERT_MUT_PROB: u64 = 10;\n\nconst MODIFY_MUT_PROB: u64 = 70;\n\n\n\nstatic TARGET: &str = \"hello\";\n\nstatic VALID_GENES: &str = \"+++++++-------<<>>.[]\";\n\n\n", "file_path": "src/main.rs", "rank": 15, "score": 1.7037654454676523 } ]
Rust
meta/src/local.rs
kaiuri/rust-rosetta
67862e06956f955cdf34743a7e5c7c93e4077b64
use std::collections::HashSet; use std::fs; use std::path::{Path, PathBuf}; use anyhow::{anyhow, Context, Error}; use reqwest::Url; use toml::Value; use walkdir::WalkDir; use crate::remote; use crate::TASK_URL_RE; #[derive(Debug, Clone)] pub struct LocalTask { pub package_name: String, pub manifest_path: PathBuf, pub source: HashSet<PathBuf>, pub url: Url, pub title: String, } fn is_dylib_or_proc_macro(target: &cargo_metadata::Target) -> bool { target.kind.contains(&String::from("dylib")) || target.kind.contains(&String::from("proc-macro")) } pub fn parse_tasks<P>(manifest_path: P) -> Result<Vec<LocalTask>, Error> where P: AsRef<Path>, { let metadata = cargo_metadata::metadata(Some(manifest_path.as_ref())).unwrap(); let packages = &metadata.packages; let mut tasks = vec![]; for member in &metadata.workspace_members { if member.name() == "rust-rosetta" || member.name() == "meta" { continue; } let package = packages.iter().find(|p| p.name == member.name()).unwrap(); if package.targets.iter().any(is_dylib_or_proc_macro) { continue; } let manifest_path = Path::new(&package.manifest_path); let rosetta_url = parse_rosetta_url(manifest_path).context(format!( "could not parse rosetta code URL from {}", manifest_path.display() ))?; let title = { let caps = TASK_URL_RE.captures(rosetta_url.as_str()).ok_or_else(|| { anyhow!( "task URL does not match rosetta code regex: {}", rosetta_url ) })?; remote::decode_title(&caps[1]) }; tasks.push(LocalTask { package_name: member.name().to_owned(), manifest_path: manifest_path.to_owned(), source: find_sources(manifest_path.parent().unwrap())?, url: rosetta_url, title, }); } Ok(tasks) } fn parse_rosetta_url<P>(manifest_path: P) -> Result<Url, Error> where P: AsRef<Path>, { let manifest: Value = fs::read_to_string(manifest_path)?.parse()?; let url = manifest .get("package") .and_then(|p| p.get("metadata")) .and_then(|m| m.get("rosettacode")) .and_then(|m| m.get("url")) .and_then(|u| u.as_str()) .ok_or_else(|| anyhow!("unexpected metadata format"))?; Ok(Url::parse(url)?) } fn find_sources<P>(directory: P) -> Result<HashSet<PathBuf>, Error> where P: AsRef<Path>, { let mut sources = HashSet::new(); for entry in WalkDir::new(directory) { let entry = entry?; if let Some("rs") = entry.path().extension().and_then(|s| s.to_str()) { sources.insert(entry.path().to_owned()); } } Ok(sources) }
use std::collections::HashSet; use std::fs; use std::path::{Path, PathBuf}; use anyhow::{anyhow, Context, Error}; use reqwest::Url; use toml::Value; use walkdir::WalkDir; use crate::remote; use crate::TASK_URL_RE; #[derive(Debug, Clone)] pub struct LocalTask { pub package_name: String, pub manifest_path: PathBuf, pub source: HashSet<PathBuf>, pub url: Url, pub title: String, } fn is_dylib_or_proc_macro(target: &cargo_metadata::Target) -> bool { target.kind.contains(&String::from("dylib")) || target.kind.contains(&String::from("proc-macro")) } pub fn parse_tasks<P>(manifest_path: P) -> Result<Vec<LocalTask>, Error> where P: AsRef<Path>, { let metadata = cargo_metadata::metadata(Some(manifest_path.as_ref())).unwrap(); let packages = &metadata.packages; let mut tasks = vec![]; for member in &metadata.workspace_members { if member.name() == "rust-rosetta" || member.name() == "meta" { continue; } let package = packages.iter().find(|p| p.name == member.name()).unwrap(); if package.targets.iter().any(is_dylib_or_proc_macro) { continue; } let manifest_path = Path::new(&package.manifest_path); let rosetta_url = parse_rosetta_url(manifest_path).context(format!( "could not parse rosetta code URL from {}", manifest_path.display() ))?; let title = { let caps = TASK_URL_RE.captures(rosetta_url.as_str()).ok_or_else(|| { anyhow!( "task URL does not match rosetta code regex: {}", rosetta_url ) })?; remote::decode_title(&caps[1]) }; tasks.push(LocalTask { package_name: member.name().to_owned(), manifest_path: manifest_path.to_owned(), source: find_sources(manifest_path.parent().unwrap())?, url: rosetta_url, title, }); } Ok(tasks) }
fn find_sources<P>(directory: P) -> Result<HashSet<PathBuf>, Error> where P: AsRef<Path>, { let mut sources = HashSet::new(); for entry in WalkDir::new(directory) { let entry = entry?; if let Some("rs") = entry.path().extension().and_then(|s| s.to_str()) { sources.insert(entry.path().to_owned()); } } Ok(sources) }
fn parse_rosetta_url<P>(manifest_path: P) -> Result<Url, Error> where P: AsRef<Path>, { let manifest: Value = fs::read_to_string(manifest_path)?.parse()?; let url = manifest .get("package") .and_then(|p| p.get("metadata")) .and_then(|m| m.get("rosettacode")) .and_then(|m| m.get("url")) .and_then(|u| u.as_str()) .ok_or_else(|| anyhow!("unexpected metadata format"))?; Ok(Url::parse(url)?) }
function_block-full_function
[]
Rust
src/bin/tui/status.rs
ssneep/grin
b7e29fee55e60c1ec6fa8678b252231855b34816
use cursive::Cursive; use cursive::view::View; use cursive::views::{BoxView, LinearLayout, TextView}; use cursive::direction::Orientation; use cursive::traits::*; use tui::constants::*; use tui::types::*; use servers::ServerStats; pub struct TUIStatusView; impl TUIStatusListener for TUIStatusView { fn create() -> Box<View> { let basic_status_view = BoxView::with_full_screen( LinearLayout::new(Orientation::Vertical) .child( LinearLayout::new(Orientation::Horizontal) .child(TextView::new("Current Status: ")) .child(TextView::new("Starting").with_id("basic_current_status")), ) .child( LinearLayout::new(Orientation::Horizontal) .child(TextView::new("Connected Peers: ")) .child(TextView::new("0").with_id("connected_peers")), ) .child( LinearLayout::new(Orientation::Horizontal) .child(TextView::new("Chain Height: ")) .child(TextView::new(" ").with_id("chain_height")), ) .child( LinearLayout::new(Orientation::Horizontal) .child(TextView::new("Total Difficulty: ")) .child(TextView::new(" ").with_id("basic_total_difficulty")), ) .child( LinearLayout::new(Orientation::Horizontal) .child(TextView::new("------------------------")), ) .child( LinearLayout::new(Orientation::Horizontal) .child(TextView::new(" ").with_id("basic_mining_config_status")), ) .child( LinearLayout::new(Orientation::Horizontal) .child(TextView::new(" ").with_id("basic_mining_status")), ) .child( LinearLayout::new(Orientation::Horizontal) .child(TextView::new(" ").with_id("basic_network_info")), ), ); Box::new(basic_status_view.with_id(VIEW_BASIC_STATUS)) } fn update(c: &mut Cursive, stats: &ServerStats) { let basic_status = { if stats.is_syncing { if stats.awaiting_peers { "Waiting for peers".to_string() } else { format!("Syncing - Latest header: {}", stats.header_head.height).to_string() } } else { "Running".to_string() } }; let basic_mining_config_status = { if stats.mining_stats.is_enabled { "Configured as mining node" } else { "Configured as validating node only (not mining)" } }; let (basic_mining_status, basic_network_info) = { if stats.mining_stats.is_enabled { if stats.is_syncing { ( "Mining Status: Paused while syncing".to_string(), " ".to_string(), ) } else if stats.mining_stats.combined_gps == 0.0 { ( "Mining Status: Starting miner and awaiting first solution...".to_string(), " ".to_string(), ) } else { ( format!( "Mining Status: Mining at height {} at {:.*} GPS", stats.mining_stats.block_height, 4, stats.mining_stats.combined_gps ), format!( "Cuckoo {} - Network Difficulty {}", stats.mining_stats.cuckoo_size, stats.mining_stats.network_difficulty.to_string() ), ) } } else { (" ".to_string(), " ".to_string()) } }; c.call_on_id("basic_current_status", |t: &mut TextView| { t.set_content(basic_status); }); c.call_on_id("connected_peers", |t: &mut TextView| { t.set_content(stats.peer_count.to_string()); }); c.call_on_id("chain_height", |t: &mut TextView| { t.set_content(stats.head.height.to_string()); }); c.call_on_id("basic_total_difficulty", |t: &mut TextView| { t.set_content(stats.head.total_difficulty.to_string()); }); c.call_on_id("basic_mining_config_status", |t: &mut TextView| { t.set_content(basic_mining_config_status); }); c.call_on_id("basic_mining_status", |t: &mut TextView| { t.set_content(basic_mining_status); }); c.call_on_id("basic_network_info", |t: &mut TextView| { t.set_content(basic_network_info); }); } }
use cursive::Cursive; use cursive::view::View; use cursive::views::{BoxView, LinearLayout, TextView}; use cursive::direction::Orientation; use cursive::traits::*; use tui::constants::*; use tui::types::*; use servers::ServerStats; pub struct TUIStatusView; impl TUIStatusListener for TUIStatusView { fn create() -> Box<View> { let basic_status_view = BoxView::with_full_screen( LinearLayout::new(Orientation::Vertical) .child( LinearLayout::new(Orientation::Horizontal) .child(TextView::new("Current Status: ")) .child(TextView::new("Starting").with_id("basic_current_status")), ) .child( LinearLayout::new(Orientation::Horizontal) .child(TextView::new("Connected Peers: ")) .child(TextView::new("0").with_id("connected_peers")), ) .child( LinearLayout::new(Orientation::Horizontal) .child(TextView::new("Chain Height: ")) .child(TextView::new(" ").with_id("chain_height")), ) .child( LinearLayout::new(Orientation::Horizontal) .child(TextView::new("Total Difficulty: ")) .child(TextView::new(" ").with_id("basic_total_difficulty")), ) .child( LinearLayout::new(Orientation::Horizontal) .child(TextView::new("------------------------")), ) .child( LinearLayout::new(Orientation::Horizontal) .child(TextView::new(" ").with_id("basic_mining_config_status")), ) .child( LinearLayout::new(Orientation::Horizontal) .child(TextView::new(" ").with_id("basic_mining_status")), ) .child( LinearLayout::new(Orientation::Horizontal) .
fn update(c: &mut Cursive, stats: &ServerStats) { let basic_status = { if stats.is_syncing { if stats.awaiting_peers { "Waiting for peers".to_string() } else { format!("Syncing - Latest header: {}", stats.header_head.height).to_string() } } else { "Running".to_string() } }; let basic_mining_config_status = { if stats.mining_stats.is_enabled { "Configured as mining node" } else { "Configured as validating node only (not mining)" } }; let (basic_mining_status, basic_network_info) = { if stats.mining_stats.is_enabled { if stats.is_syncing { ( "Mining Status: Paused while syncing".to_string(), " ".to_string(), ) } else if stats.mining_stats.combined_gps == 0.0 { ( "Mining Status: Starting miner and awaiting first solution...".to_string(), " ".to_string(), ) } else { ( format!( "Mining Status: Mining at height {} at {:.*} GPS", stats.mining_stats.block_height, 4, stats.mining_stats.combined_gps ), format!( "Cuckoo {} - Network Difficulty {}", stats.mining_stats.cuckoo_size, stats.mining_stats.network_difficulty.to_string() ), ) } } else { (" ".to_string(), " ".to_string()) } }; c.call_on_id("basic_current_status", |t: &mut TextView| { t.set_content(basic_status); }); c.call_on_id("connected_peers", |t: &mut TextView| { t.set_content(stats.peer_count.to_string()); }); c.call_on_id("chain_height", |t: &mut TextView| { t.set_content(stats.head.height.to_string()); }); c.call_on_id("basic_total_difficulty", |t: &mut TextView| { t.set_content(stats.head.total_difficulty.to_string()); }); c.call_on_id("basic_mining_config_status", |t: &mut TextView| { t.set_content(basic_mining_config_status); }); c.call_on_id("basic_mining_status", |t: &mut TextView| { t.set_content(basic_mining_status); }); c.call_on_id("basic_network_info", |t: &mut TextView| { t.set_content(basic_network_info); }); } }
child(TextView::new(" ").with_id("basic_network_info")), ), ); Box::new(basic_status_view.with_id(VIEW_BASIC_STATUS)) }
function_block-function_prefix_line
[ { "content": "pub fn unban_peer(\n\n\tbase_addr: &String,\n\n\tapi_server_port: u16,\n\n\tpeer_addr: &String,\n\n) -> Result<(), Error> {\n\n\tlet url = format!(\n\n\t\t\"http://{}:{}/v1/peers/{}/unban\",\n\n\t\tbase_addr, api_server_port, peer_addr\n\n\t);\n\n\tapi::client::post(url.as_str(), &\"\").map_err(|e| Error::API(e))\n\n}\n\n\n", "file_path": "servers/tests/api.rs", "rank": 0, "score": 188833.14148930582 }, { "content": "pub fn get_all_peers(\n\n\tbase_addr: &String,\n\n\tapi_server_port: u16,\n\n) -> Result<Vec<p2p::PeerData>, Error> {\n\n\tlet url = format!(\"http://{}:{}/v1/peers/all\", base_addr, api_server_port);\n\n\tapi::client::get::<Vec<p2p::PeerData>>(url.as_str()).map_err(|e| Error::API(e))\n\n}\n\n\n\n/// Error type wrapping underlying module errors.\n\n#[derive(Debug)]\n\npub enum Error {\n\n\t/// Error originating from HTTP API calls.\n\n\tAPI(api::Error),\n\n}\n", "file_path": "servers/tests/api.rs", "rank": 1, "score": 188833.14148930582 }, { "content": "pub fn get_peer(\n\n\tbase_addr: &String,\n\n\tapi_server_port: u16,\n\n\tpeer_addr: &String,\n\n) -> Result<p2p::PeerData, Error> {\n\n\tlet url = format!(\n\n\t\t\"http://{}:{}/v1/peers/{}\",\n\n\t\tbase_addr, api_server_port, peer_addr\n\n\t);\n\n\tapi::client::get::<p2p::PeerData>(url.as_str()).map_err(|e| Error::API(e))\n\n}\n\n\n", "file_path": "servers/tests/api.rs", "rank": 2, "score": 188833.14148930582 }, { "content": "pub fn get_connected_peers(\n\n\tbase_addr: &String,\n\n\tapi_server_port: u16,\n\n) -> Result<Vec<p2p::PeerInfo>, Error> {\n\n\tlet url = format!(\n\n\t\t\"http://{}:{}/v1/peers/connected\",\n\n\t\tbase_addr, api_server_port\n\n\t);\n\n\tapi::client::get::<Vec<p2p::PeerInfo>>(url.as_str()).map_err(|e| Error::API(e))\n\n}\n\n\n", "file_path": "servers/tests/api.rs", "rank": 3, "score": 184991.71610397624 }, { "content": "/// Initial mining difficulty\n\npub fn initial_block_difficulty() -> u64 {\n\n\tlet param_ref = CHAIN_TYPE.read().unwrap();\n\n\tmatch *param_ref {\n\n\t\tChainTypes::AutomatedTesting => TESTING_INITIAL_DIFFICULTY,\n\n\t\tChainTypes::UserTesting => TESTING_INITIAL_DIFFICULTY,\n\n\t\tChainTypes::Testnet1 => TESTING_INITIAL_DIFFICULTY,\n\n\t\tChainTypes::Testnet2 => TESTNET2_INITIAL_DIFFICULTY,\n\n\t\tChainTypes::Mainnet => INITIAL_DIFFICULTY,\n\n\t}\n\n}\n\n\n", "file_path": "core/src/global.rs", "rank": 4, "score": 176530.87486153183 }, { "content": "/// Check whether the block version is valid at a given height, implements\n\n/// 6 months interval scheduled hard forks for the first 2 years.\n\npub fn valid_header_version(height: u64, version: u16) -> bool {\n\n\t// uncomment below as we go from hard fork to hard fork\n\n\tif height <= HARD_FORK_INTERVAL && version == 1 {\n\n\t\ttrue\n\n\t/* } else if height <= 2 * HARD_FORK_INTERVAL && version == 2 {\n\n\t\ttrue */\n\n\t/* } else if height <= 3 * HARD_FORK_INTERVAL && version == 3 {\n\n\t\ttrue */\n\n\t/* } else if height <= 4 * HARD_FORK_INTERVAL && version == 4 {\n\n\t\ttrue */\n\n\t/* } else if height > 4 * HARD_FORK_INTERVAL && version > 4 {\n\n\t\ttrue */\n\n\t} else {\n\n\t\tfalse\n\n\t}\n\n}\n\n\n\n/// Time window in blocks to calculate block time median\n\npub const MEDIAN_TIME_WINDOW: u64 = 11;\n\n\n", "file_path": "core/src/consensus.rs", "rank": 5, "score": 172918.04146216487 }, { "content": "/// Sets the lock_height on the transaction being built.\n\npub fn with_lock_height(lock_height: u64) -> Box<Append> {\n\n\tBox::new(\n\n\t\tmove |_build, (tx, kern, sum)| -> (Transaction, TxKernel, BlindSum) {\n\n\t\t\t(tx, kern.with_lock_height(lock_height), sum)\n\n\t\t},\n\n\t)\n\n}\n\n\n", "file_path": "core/src/core/build.rs", "rank": 6, "score": 165440.3820878845 }, { "content": "/// The height of a node in a full binary tree from its postorder traversal\n\n/// index. This function is the base on which all others, as well as the MMR,\n\n/// are built.\n\n///\n\n/// We first start by noticing that the insertion order of a node in a MMR [1]\n\n/// is identical to the height of a node in a binary tree traversed in\n\n/// postorder. Specifically, we want to be able to generate the following\n\n/// sequence:\n\n///\n\n/// // [0, 0, 1, 0, 0, 1, 2, 0, 0, 1, 0, 0, 1, 2, 3, 0, 0, 1, ...]\n\n///\n\n/// Which turns out to start as the heights in the (left, right, top)\n\n/// -postorder- traversal of the following tree:\n\n///\n\n/// // 3\n\n/// // / \\\n\n/// // / \\\n\n/// // / \\\n\n/// // 2 2\n\n/// // / \\ / \\\n\n/// // / \\ / \\\n\n/// // 1 1 1 1\n\n/// // / \\ / \\ / \\ / \\\n\n/// // 0 0 0 0 0 0 0 0\n\n///\n\n/// If we extend this tree up to a height of 4, we can continue the sequence,\n\n/// and for an infinitely high tree, we get the infinite sequence of heights\n\n/// in the MMR.\n\n///\n\n/// So to generate the MMR height sequence, we want a function that, given an\n\n/// index in that sequence, gets us the height in the tree. This allows us to\n\n/// build the sequence not only to infinite, but also at any index, without the\n\n/// need to materialize the beginning of the sequence.\n\n///\n\n/// To see how to get the height of a node at any position in the postorder\n\n/// traversal sequence of heights, we start by rewriting the previous tree with\n\n/// each the position of every node written in binary:\n\n///\n\n///\n\n/// // 1111\n\n/// // / \\\n\n/// // / \\\n\n/// // / \\\n\n/// // / \\\n\n/// // 111 1110\n\n/// // / \\ / \\\n\n/// // / \\ / \\\n\n/// // 11 110 1010 1101\n\n/// // / \\ / \\ / \\ / \\\n\n/// // 1 10 100 101 1000 1001 1011 1100\n\n///\n\n/// The height of a node is the number of 1 digits on the leftmost branch of\n\n/// the tree, minus 1. For example, 1111 has 4 ones, so its height is `4-1=3`.\n\n///\n\n/// To get the height of any node (say 1101), we need to travel left in the\n\n/// tree, get the leftmost node and count the ones. To travel left, we just\n\n/// need to subtract the position by it's most significant bit, mins one. For\n\n/// example to get from 1101 to 110 we subtract it by (1000-1) (`13-(8-1)=5`).\n\n/// Then to to get 110 to 11, we subtract it by (100-1) ('6-(4-1)=3`).\n\n///\n\n/// By applying this operation recursively, until we get a number that, in\n\n/// binary, is all ones, and then counting the ones, we can get the height of\n\n/// any node, from its postorder traversal position. Which is the order in which\n\n/// nodes are added in a MMR.\n\n///\n\n/// [1] https://github.com/opentimestamps/opentimestamps-server/blob/master/doc/merkle-mountain-range.md\n\npub fn bintree_postorder_height(num: u64) -> u64 {\n\n\tlet mut h = num;\n\n\twhile !all_ones(h) {\n\n\t\th = bintree_jump_left(h);\n\n\t}\n\n\tmost_significant_pos(h) - 1\n\n}\n\n\n", "file_path": "core/src/core/pmmr.rs", "rank": 7, "score": 158889.97312686878 }, { "content": "/// Computes the proof-of-work difficulty that the next block should comply\n\n/// with. Takes an iterator over past blocks, from latest (highest height) to\n\n/// oldest (lowest height). The iterator produces pairs of timestamp and\n\n/// difficulty for each block.\n\n///\n\n/// The difficulty calculation is based on both Digishield and GravityWave\n\n/// family of difficulty computation, coming to something very close to Zcash.\n\n/// The refence difficulty is an average of the difficulty over a window of\n\n/// DIFFICULTY_ADJUST_WINDOW blocks. The corresponding timespan is calculated\n\n/// by using the difference between the median timestamps at the beginning\n\n/// and the end of the window.\n\npub fn next_difficulty<T>(cursor: T) -> Result<Difficulty, TargetError>\n\nwhere\n\n\tT: IntoIterator<Item = Result<(u64, Difficulty), TargetError>>,\n\n{\n\n\t// Create vector of difficulty data running from earliest\n\n\t// to latest, and pad with simulated pre-genesis data to allow earlier\n\n\t// adjustment if there isn't enough window data\n\n\t// length will be DIFFICULTY_ADJUST_WINDOW+MEDIAN_TIME_WINDOW\n\n\tlet diff_data = global::difficulty_data_to_vector(cursor);\n\n\n\n\t// Obtain the median window for the earlier time period\n\n\t// the first MEDIAN_TIME_WINDOW elements\n\n\tlet mut window_earliest: Vec<u64> = diff_data\n\n\t\t.iter()\n\n\t\t.take(MEDIAN_TIME_WINDOW as usize)\n\n\t\t.map(|n| n.clone().unwrap().0)\n\n\t\t.collect();\n\n\t// pick median\n\n\twindow_earliest.sort();\n\n\tlet earliest_ts = window_earliest[MEDIAN_TIME_INDEX as usize];\n", "file_path": "core/src/consensus.rs", "rank": 8, "score": 157634.2725322815 }, { "content": "pub fn _get_chain_height(config: &WalletConfig) -> Result<u64, Error> {\n\n\tlet url = format!(\"{}/v1/chain\", config.check_node_api_http_addr);\n\n\n\n\tmatch api::client::get::<api::Tip>(url.as_str()) {\n\n\t\tOk(tip) => Ok(tip.height),\n\n\t\tErr(e) => {\n\n\t\t\t// if we got anything other than 200 back from server, bye\n\n\t\t\terror!(\n\n\t\t\t\tLOGGER,\n\n\t\t\t\t\"get_chain_height: Restore failed... unable to contact API {}. Error: {}\",\n\n\t\t\t\tconfig.check_node_api_http_addr,\n\n\t\t\t\te\n\n\t\t\t);\n\n\t\t\tErr(e.context(ErrorKind::Node).into())\n\n\t\t}\n\n\t}\n\n}\n\n\n", "file_path": "wallet/src/restore.rs", "rank": 9, "score": 147326.59251466498 }, { "content": "pub fn difficulty_data_to_vector<T>(cursor: T) -> Vec<Result<(u64, Difficulty), TargetError>>\n\nwhere\n\n\tT: IntoIterator<Item = Result<(u64, Difficulty), TargetError>>,\n\n{\n\n\t// Convert iterator to vector, so we can append to it if necessary\n\n\tlet needed_block_count = (MEDIAN_TIME_WINDOW + DIFFICULTY_ADJUST_WINDOW) as usize;\n\n\tlet mut last_n: Vec<Result<(u64, Difficulty), TargetError>> =\n\n\t\tcursor.into_iter().take(needed_block_count).collect();\n\n\n\n\t// Sort blocks from earliest to latest (to keep conceptually easier)\n\n\tlast_n.reverse();\n\n\t// Only needed just after blockchain launch... basically ensures there's\n\n\t// always enough data by simulating perfectly timed pre-genesis\n\n\t// blocks at the genesis difficulty as needed.\n\n\tlet block_count_difference = needed_block_count - last_n.len();\n\n\tif block_count_difference > 0 {\n\n\t\t// Collect any real data we have\n\n\t\tlet mut live_intervals: Vec<(u64, Difficulty)> = last_n\n\n\t\t\t.iter()\n\n\t\t\t.map(|b| (b.clone().unwrap().0, b.clone().unwrap().1))\n", "file_path": "core/src/global.rs", "rank": 10, "score": 146215.99595098384 }, { "content": "/// Build a coinbase output and the corresponding kernel\n\npub fn receive_coinbase(\n\n\tconfig: &WalletConfig,\n\n\tkeychain: &Keychain,\n\n\tblock_fees: &BlockFees,\n\n) -> Result<(Output, TxKernel, BlockFees), Error> {\n\n\tlet root_key_id = keychain.root_key_id();\n\n\n\n\tlet height = block_fees.height;\n\n\tlet lock_height = height + global::coinbase_maturity();\n\n\n\n\t// Now acquire the wallet lock and write the new output.\n\n\tlet (key_id, derivation) = WalletData::with_wallet(&config.data_file_dir, |wallet_data| {\n\n\t\tlet key_id = block_fees.key_id();\n\n\t\tlet (key_id, derivation) = match key_id {\n\n\t\t\tSome(key_id) => retrieve_existing_key(&wallet_data, key_id),\n\n\t\t\tNone => next_available_key(&wallet_data, keychain),\n\n\t\t};\n\n\n\n\t\t// track the new output and return the stuff needed for reward\n\n\t\twallet_data.add_output(OutputData {\n", "file_path": "wallet/src/receiver.rs", "rank": 11, "score": 145326.65963022484 }, { "content": "/// Builds a complete transaction.\n\npub fn transaction(\n\n\telems: Vec<Box<Append>>,\n\n\tkeychain: &keychain::Keychain,\n\n) -> Result<Transaction, keychain::Error> {\n\n\tlet (mut tx, blind_sum) = partial_transaction(elems, keychain)?;\n\n\tassert_eq!(tx.kernels.len(), 1);\n\n\n\n\tlet mut kern = tx.kernels.remove(0);\n\n\tlet msg = secp::Message::from_slice(&kernel_sig_msg(kern.fee, kern.lock_height))?;\n\n\n\n\tlet skey = blind_sum.secret_key(&keychain.secp())?;\n\n\tkern.excess = keychain.secp().commit(0, skey)?;\n\n\tkern.excess_sig = Keychain::aggsig_sign_with_blinding(&keychain.secp(), &msg, &blind_sum)?;\n\n\n\n\ttx.kernels.push(kern);\n\n\n\n\tOk(tx)\n\n}\n\n\n", "file_path": "core/src/core/build.rs", "rank": 12, "score": 145326.65963022484 }, { "content": "pub fn outputs_batch(\n\n\tconfig: &WalletConfig,\n\n\tstart_height: u64,\n\n\tmax: u64,\n\n) -> Result<api::OutputListing, Error> {\n\n\tlet query_param = format!(\"start_index={}&max={}\", start_height, max);\n\n\n\n\tlet url = format!(\n\n\t\t\"{}/v1/txhashset/outputs?{}\",\n\n\t\tconfig.check_node_api_http_addr, query_param,\n\n\t);\n\n\n\n\tmatch api::client::get::<api::OutputListing>(url.as_str()) {\n\n\t\tOk(o) => Ok(o),\n\n\t\tErr(e) => {\n\n\t\t\t// if we got anything other than 200 back from server, bye\n\n\t\t\terror!(\n\n\t\t\t\tLOGGER,\n\n\t\t\t\t\"outputs_batch: Restore failed... unable to contact API {}. Error: {}\",\n\n\t\t\t\tconfig.check_node_api_http_addr,\n\n\t\t\t\te\n\n\t\t\t);\n\n\t\t\tErr(e.context(ErrorKind::Node))?\n\n\t\t}\n\n\t}\n\n}\n\n\n", "file_path": "wallet/src/restore.rs", "rank": 13, "score": 145326.65963022484 }, { "content": "/// The default implementation of read_exact is useless with async TcpStream as\n\n/// it will return as soon as something has been read, regardless of\n\n/// whether the buffer has been filled (and then errors). This implementation\n\n/// will block until it has read exactly `len` bytes and returns them as a\n\n/// `vec<u8>`. Except for a timeout, this implementation will never return a\n\n/// partially filled buffer.\n\n///\n\n/// The timeout in milliseconds aborts the read when it's met. Note that the\n\n/// time is not guaranteed to be exact. To support cases where we want to poll\n\n/// instead of blocking, a `block_on_empty` boolean, when false, ensures\n\n/// `read_exact` returns early with a `io::ErrorKind::WouldBlock` if nothing\n\n/// has been read from the socket.\n\npub fn read_exact(\n\n\tconn: &mut TcpStream,\n\n\tmut buf: &mut [u8],\n\n\ttimeout: u32,\n\n\tblock_on_empty: bool,\n\n) -> io::Result<()> {\n\n\tlet sleep_time = time::Duration::from_millis(1);\n\n\tlet mut count = 0;\n\n\n\n\tlet mut read = 0;\n\n\tloop {\n\n\t\tmatch conn.read(buf) {\n\n\t\t\tOk(0) => break,\n\n\t\t\tOk(n) => {\n\n\t\t\t\tlet tmp = buf;\n\n\t\t\t\tbuf = &mut tmp[n..];\n\n\t\t\t\tread += n;\n\n\t\t\t}\n\n\t\t\tErr(ref e) if e.kind() == io::ErrorKind::Interrupted => {}\n\n\t\t\tErr(ref e) if e.kind() == io::ErrorKind::WouldBlock => {\n", "file_path": "p2p/src/msg.rs", "rank": 14, "score": 145326.65963022484 }, { "content": "/// Construct msg bytes from tx fee and lock_height\n\npub fn kernel_sig_msg(fee: u64, lock_height: u64) -> [u8; 32] {\n\n\tlet mut bytes = [0; 32];\n\n\tBigEndian::write_u64(&mut bytes[16..24], fee);\n\n\tBigEndian::write_u64(&mut bytes[24..], lock_height);\n\n\tbytes\n\n}\n", "file_path": "util/src/lib.rs", "rank": 15, "score": 144916.2364160155 }, { "content": "/// Process the block header.\n\n/// This is only ever used during sync and uses a context based on sync_head.\n\npub fn sync_block_header(\n\n\tbh: &BlockHeader,\n\n\tmut sync_ctx: BlockContext,\n\n\tmut header_ctx: BlockContext,\n\n) -> Result<Option<Tip>, Error> {\n\n\tdebug!(\n\n\t\tLOGGER,\n\n\t\t\"pipe: sync_block_header: {} at {}\",\n\n\t\tbh.hash(),\n\n\t\tbh.height\n\n\t);\n\n\n\n\tvalidate_header(&bh, &mut sync_ctx)?;\n\n\tadd_block_header(bh, &mut sync_ctx)?;\n\n\n\n\t// TODO - confirm this is needed during sync process (I don't see how it is)\n\n\t// we do not touch the txhashset when syncing headers\n\n\t// just taking the shared lock\n\n\tlet _ = header_ctx.txhashset.write().unwrap();\n\n\n\n\t// now update the header_head (if new header with most work) and the sync_head\n\n\t// (always)\n\n\tupdate_header_head(bh, &mut header_ctx)?;\n\n\tupdate_sync_head(bh, &mut sync_ctx)\n\n}\n\n\n", "file_path": "chain/src/pipe.rs", "rank": 16, "score": 142780.5354950336 }, { "content": "/// Mines a genesis block, using the config specified miner if specified.\n\n/// Otherwise, uses the internal miner\n\npub fn mine_genesis_block(\n\n\tminer_config: Option<types::MinerConfig>,\n\n) -> Result<core::core::Block, Error> {\n\n\tlet mut gen = genesis::genesis_testnet2();\n\n\tif global::is_user_testing_mode() || global::is_automated_testing_mode() {\n\n\t\tgen = genesis::genesis_dev();\n\n\t\tgen.header.timestamp = time::now();\n\n\t}\n\n\n\n\t// total_difficulty on the genesis header *is* the difficulty of that block\n\n\tlet genesis_difficulty = gen.header.total_difficulty.clone();\n\n\n\n\tlet sz = global::sizeshift() as u32;\n\n\tlet proof_size = global::proofsize();\n\n\n\n\tlet mut miner: Box<MiningWorker> = match miner_config {\n\n\t\tSome(c) => if c.enable_mining {\n\n\t\t\tlet mut p = plugin::PluginMiner::new(consensus::EASINESS, sz, proof_size);\n\n\t\t\tp.init(c.clone());\n\n\t\t\tBox::new(p)\n\n\t\t} else {\n\n\t\t\tBox::new(cuckoo::Miner::new(consensus::EASINESS, sz, proof_size))\n\n\t\t},\n\n\t\tNone => Box::new(cuckoo::Miner::new(consensus::EASINESS, sz, proof_size)),\n\n\t};\n\n\tpow_size(&mut *miner, &mut gen.header, genesis_difficulty, sz as u32).unwrap();\n\n\tOk(gen)\n\n}\n\n\n", "file_path": "pow/src/lib.rs", "rank": 17, "score": 142780.5131012764 }, { "content": "/// Builds a new transaction by combining all the combinators provided in a\n\n/// Vector. Transactions can either be built \"from scratch\" with a list of\n\n/// inputs or outputs or from a pre-existing transaction that gets added to.\n\n///\n\n/// Example:\n\n/// let (tx1, sum) = build::transaction(vec![input_rand(4), output_rand(1),\n\n/// with_fee(1)], keychain).unwrap();\n\n/// let (tx2, _) = build::transaction(vec![initial_tx(tx1), with_excess(sum),\n\n/// output_rand(2)], keychain).unwrap();\n\n///\n\npub fn partial_transaction(\n\n\telems: Vec<Box<Append>>,\n\n\tkeychain: &keychain::Keychain,\n\n) -> Result<(Transaction, BlindingFactor), keychain::Error> {\n\n\tlet mut ctx = Context { keychain };\n\n\tlet (mut tx, kern, sum) = elems.iter().fold(\n\n\t\t(Transaction::empty(), TxKernel::empty(), BlindSum::new()),\n\n\t\t|acc, elem| elem(&mut ctx, acc),\n\n\t);\n\n\tlet blind_sum = ctx.keychain.blind_sum(&sum)?;\n\n\n\n\t// we only support building a tx with a single kernel via build::transaction()\n\n\tassert!(tx.kernels.is_empty());\n\n\ttx.kernels.push(kern);\n\n\n\n\tOk((tx, blind_sum))\n\n}\n\n\n", "file_path": "core/src/core/build.rs", "rank": 18, "score": 142779.98124036784 }, { "content": "/// Adds a coinbase input spending a coinbase output.\n\n/// We will use the block hash to verify coinbase maturity.\n\npub fn coinbase_input(\n\n\tvalue: u64,\n\n\tblock_hash: Hash,\n\n\tmerkle_proof: MerkleProof,\n\n\tkey_id: Identifier,\n\n) -> Box<Append> {\n\n\tdebug!(\n\n\t\tLOGGER,\n\n\t\t\"Building input (spending coinbase): {}, {}\", value, key_id\n\n\t);\n\n\tbuild_input(\n\n\t\tvalue,\n\n\t\tOutputFeatures::COINBASE_OUTPUT,\n\n\t\tSome(block_hash),\n\n\t\tSome(merkle_proof),\n\n\t\tkey_id,\n\n\t)\n\n}\n\n\n", "file_path": "core/src/core/build.rs", "rank": 19, "score": 142779.61197276157 }, { "content": "/// Initializes the logger for unit and integration tests\n\npub fn init_test_logger() {\n\n\tlet mut was_init_ref = WAS_INIT.lock().unwrap();\n\n\tif *was_init_ref.deref() {\n\n\t\treturn;\n\n\t}\n\n\tlet mut config_ref = LOGGING_CONFIG.lock().unwrap();\n\n\t*config_ref = LoggingConfig::default();\n\n\t*was_init_ref = true;\n\n\tsend_panic_to_log();\n\n}\n\n\n", "file_path": "util/src/logger.rs", "rank": 20, "score": 142774.51093186255 }, { "content": "/// Utility function to handle forks. From the forked block, jump backward\n\n/// to find to fork root. Rewind the txhashset to the root and apply all the\n\n/// forked blocks prior to the one being processed to set the txhashset in\n\n/// the expected state.\n\npub fn rewind_and_apply_fork(\n\n\tb: &Block,\n\n\tstore: Arc<ChainStore>,\n\n\text: &mut txhashset::Extension,\n\n) -> Result<(), Error> {\n\n\t// extending a fork, first identify the block where forking occurred\n\n\t// keeping the hashes of blocks along the fork\n\n\tlet mut current = b.header.previous;\n\n\tlet mut hashes = vec![];\n\n\tloop {\n\n\t\tlet curr_header = store.get_block_header(&current)?;\n\n\n\n\t\tif let Ok(_) = store.is_on_current_chain(&curr_header) {\n\n\t\t\tbreak;\n\n\t\t} else {\n\n\t\t\thashes.insert(0, (curr_header.height, curr_header.hash()));\n\n\t\t\tcurrent = curr_header.previous;\n\n\t\t}\n\n\t}\n\n\n", "file_path": "chain/src/pipe.rs", "rank": 21, "score": 142774.51093186255 }, { "content": "/// Issue a new transaction to the provided sender by spending some of our\n\n/// wallet\n\n/// Outputs. The destination can be \"stdout\" (for command line) (currently disabled) or a URL to the\n\n/// recipients wallet receiver (to be implemented).\n\npub fn issue_send_tx(\n\n\tconfig: &WalletConfig,\n\n\tkeychain: &Keychain,\n\n\tamount: u64,\n\n\tminimum_confirmations: u64,\n\n\tdest: String,\n\n\tmax_outputs: usize,\n\n\tselection_strategy_is_use_all: bool,\n\n\tfluff: bool,\n\n) -> Result<(), Error> {\n\n\tchecker::refresh_outputs(config, keychain)?;\n\n\n\n\tlet chain_tip = checker::get_tip_from_node(config)?;\n\n\tlet current_height = chain_tip.height;\n\n\n\n\t// proof of concept - set lock_height on the tx\n\n\tlet lock_height = chain_tip.height;\n\n\n\n\tlet (tx, blind, coins, change_key, amount_with_fee) = build_send_tx(\n\n\t\tconfig,\n", "file_path": "wallet/src/sender.rs", "rank": 22, "score": 142774.51093186255 }, { "content": "pub fn connect_and_monitor(\n\n\tp2p_server: Arc<p2p::Server>,\n\n\tcapabilities: p2p::Capabilities,\n\n\tseed_list: Box<Fn() -> Vec<SocketAddr> + Send>,\n\n\tstop: Arc<AtomicBool>,\n\n) {\n\n\tlet _ = thread::Builder::new()\n\n\t\t.name(\"seed\".to_string())\n\n\t\t.spawn(move || {\n\n\t\t\tlet peers = p2p_server.peers.clone();\n\n\n\n\t\t\t// open a channel with a listener that connects every peer address sent below\n\n\t\t\t// max peer count\n\n\t\t\tlet (tx, rx) = mpsc::channel();\n\n\n\n\t\t\t// check seeds first\n\n\t\t\tconnect_to_seeds(peers.clone(), tx.clone(), seed_list);\n\n\n\n\t\t\tlet mut prev = time::now_utc() - time::Duration::seconds(60);\n\n\t\t\tloop {\n", "file_path": "servers/src/grin/seed.rs", "rank": 23, "score": 142774.51093186255 }, { "content": "/// Save pmmr index location for a given block\n\npub fn save_pmmr_metadata(\n\n\tt: &Tip,\n\n\ttxhashset: &txhashset::TxHashSet,\n\n\tstore: Arc<ChainStore>,\n\n) -> Result<(), Error> {\n\n\t// Save pmmr file metadata for this block\n\n\tlet block_file_md = txhashset.last_file_metadata();\n\n\tstore\n\n\t\t.save_block_pmmr_file_metadata(&t.last_block_h, &block_file_md)\n\n\t\t.map_err(|e| Error::StoreErr(e, \"saving pmmr file metadata\".to_owned()))?;\n\n\tOk(())\n\n}\n\n\n", "file_path": "chain/src/pipe.rs", "rank": 24, "score": 142774.51093186255 }, { "content": "/// Builds a complete transaction, splitting the key and\n\n/// setting the excess, excess_sig and tx offset as necessary.\n\npub fn transaction_with_offset(\n\n\telems: Vec<Box<Append>>,\n\n\tkeychain: &keychain::Keychain,\n\n) -> Result<Transaction, keychain::Error> {\n\n\tlet mut ctx = Context { keychain };\n\n\tlet (mut tx, mut kern, sum) = elems.iter().fold(\n\n\t\t(Transaction::empty(), TxKernel::empty(), BlindSum::new()),\n\n\t\t|acc, elem| elem(&mut ctx, acc),\n\n\t);\n\n\tlet blind_sum = ctx.keychain.blind_sum(&sum)?;\n\n\n\n\tlet split = blind_sum.split(&keychain.secp())?;\n\n\tlet k1 = split.blind_1;\n\n\tlet k2 = split.blind_2;\n\n\n\n\tlet msg = secp::Message::from_slice(&kernel_sig_msg(kern.fee, kern.lock_height))?;\n\n\n\n\t// generate kernel excess and excess_sig using the split key k1\n\n\tlet skey = k1.secret_key(&keychain.secp())?;\n\n\tkern.excess = ctx.keychain.secp().commit(0, skey)?;\n", "file_path": "core/src/core/build.rs", "rank": 25, "score": 142774.51093186255 }, { "content": "/// Starts the syncing loop, just spawns two threads that loop forever\n\npub fn run_sync(\n\n\tcurrently_syncing: Arc<AtomicBool>,\n\n\tawaiting_peers: Arc<AtomicBool>,\n\n\tpeers: Arc<p2p::Peers>,\n\n\tchain: Arc<chain::Chain>,\n\n\tskip_sync_wait: bool,\n\n\tarchive_mode: bool,\n\n\tstop: Arc<AtomicBool>,\n\n) {\n\n\tlet chain = chain.clone();\n\n\tlet _ = thread::Builder::new()\n\n\t\t.name(\"sync\".to_string())\n\n\t\t.spawn(move || {\n\n\t\t\tlet mut si = SyncInfo::new();\n\n\n\n\t\t\t// initial sleep to give us time to peer with some nodes\n\n\t\t\tif !skip_sync_wait {\n\n\t\t\t\tawaiting_peers.store(true, Ordering::Relaxed);\n\n\t\t\t\tlet mut n = 0;\n\n\t\t\t\twhile peers.more_work_peers().len() < 4 && n < 30 {\n", "file_path": "servers/src/grin/sync.rs", "rank": 26, "score": 142774.51093186255 }, { "content": "/// Reads a partial transaction into the amount, sum of blinding\n\n/// factors and the transaction itself.\n\npub fn read_partial_tx(\n\n\tkeychain: &keychain::Keychain,\n\n\tpartial_tx: &PartialTx,\n\n) -> Result<\n\n\t(\n\n\t\tu64,\n\n\t\tPublicKey,\n\n\t\tPublicKey,\n\n\t\tBlindingFactor,\n\n\t\tOption<Signature>,\n\n\t\tTransaction,\n\n\t),\n\n\tError,\n\n> {\n\n\tlet blind_bin = util::from_hex(partial_tx.public_blind_excess.clone())\n\n\t\t.context(ErrorKind::GenericError(\"Could not decode HEX\"))?;\n\n\tlet blinding = PublicKey::from_slice(keychain.secp(), &blind_bin[..])\n\n\t\t.context(ErrorKind::GenericError(\"Could not construct public key\"))?;\n\n\n\n\tlet nonce_bin = util::from_hex(partial_tx.public_nonce.clone())\n", "file_path": "wallet/src/types.rs", "rank": 27, "score": 142774.51093186255 }, { "content": "pub fn issue_burn_tx(\n\n\tconfig: &WalletConfig,\n\n\tkeychain: &Keychain,\n\n\tamount: u64,\n\n\tminimum_confirmations: u64,\n\n\tmax_outputs: usize,\n\n) -> Result<(), Error> {\n\n\tlet keychain = &Keychain::burn_enabled(keychain, &Identifier::zero());\n\n\n\n\tlet chain_tip = checker::get_tip_from_node(config)?;\n\n\tlet current_height = chain_tip.height;\n\n\n\n\tlet _ = checker::refresh_outputs(config, keychain);\n\n\n\n\tlet key_id = keychain.root_key_id();\n\n\n\n\t// select some spendable coins from the wallet\n\n\tlet coins = WalletData::read_wallet(&config.data_file_dir, |wallet_data| {\n\n\t\tOk(wallet_data.select_coins(\n\n\t\t\tkey_id.clone(),\n", "file_path": "wallet/src/sender.rs", "rank": 28, "score": 142774.51093186255 }, { "content": "/// Builds a PartialTx\n\n/// aggsig_tx_context should contain the private key/nonce pair\n\n/// the resulting partial tx will contain the corresponding public keys\n\npub fn build_partial_tx(\n\n\ttransaction_id: &Uuid,\n\n\tkeychain: &keychain::Keychain,\n\n\treceive_amount: u64,\n\n\tkernel_offset: BlindingFactor,\n\n\tpart_sig: Option<secp::Signature>,\n\n\ttx: Transaction,\n\n) -> PartialTx {\n\n\tlet (pub_excess, pub_nonce) = keychain.aggsig_get_public_keys(transaction_id);\n\n\tlet mut pub_excess = pub_excess.serialize_vec(keychain.secp(), true).clone();\n\n\tlet len = pub_excess.clone().len();\n\n\tlet pub_excess: Vec<_> = pub_excess.drain(0..len).collect();\n\n\n\n\tlet mut pub_nonce = pub_nonce.serialize_vec(keychain.secp(), true);\n\n\tlet len = pub_nonce.clone().len();\n\n\tlet pub_nonce: Vec<_> = pub_nonce.drain(0..len).collect();\n\n\n\n\tPartialTx {\n\n\t\tphase: PartialTxPhase::SenderInitiation,\n\n\t\tid: transaction_id.clone(),\n", "file_path": "wallet/src/types.rs", "rank": 29, "score": 142774.51093186255 }, { "content": "pub fn ban_peer(base_addr: &String, api_server_port: u16, peer_addr: &String) -> Result<(), Error> {\n\n\tlet url = format!(\n\n\t\t\"http://{}:{}/v1/peers/{}/ban\",\n\n\t\tbase_addr, api_server_port, peer_addr\n\n\t);\n\n\tapi::client::post(url.as_str(), &\"\").map_err(|e| Error::API(e))\n\n}\n\n\n", "file_path": "servers/tests/api.rs", "rank": 30, "score": 141582.91559999736 }, { "content": "// Ensure a block suitable for mining is built and returned\n\n// If a wallet listener URL is not provided the reward will be \"burnt\"\n\n// Warning: This call does not return until/unless a new block can be built\n\npub fn get_block(\n\n\tchain: &Arc<chain::Chain>,\n\n\ttx_pool: &Arc<RwLock<pool::TransactionPool<PoolToChainAdapter>>>,\n\n\tkey_id: Option<Identifier>,\n\n\tmax_tx: u32,\n\n\twallet_listener_url: Option<String>,\n\n) -> (core::Block, BlockFees) {\n\n\t// get the latest chain state and build a block on top of it\n\n\tlet mut result = build_block(\n\n\t\tchain,\n\n\t\ttx_pool,\n\n\t\tkey_id.clone(),\n\n\t\tmax_tx,\n\n\t\twallet_listener_url.clone(),\n\n\t);\n\n\twhile let Err(e) = result {\n\n\t\tmatch e {\n\n\t\t\tself::Error::Chain(chain::Error::DuplicateCommitment(_)) => {\n\n\t\t\t\tdebug!(\n\n\t\t\t\t\tLOGGER,\n", "file_path": "servers/src/mining/mine_block.rs", "rank": 31, "score": 140369.27015180644 }, { "content": "/// The proofsize\n\npub fn proofsize() -> usize {\n\n\tlet param_ref = CHAIN_TYPE.read().unwrap();\n\n\tmatch *param_ref {\n\n\t\tChainTypes::AutomatedTesting => AUTOMATED_TESTING_PROOF_SIZE,\n\n\t\tChainTypes::UserTesting => USER_TESTING_PROOF_SIZE,\n\n\t\tChainTypes::Testnet1 => PROOFSIZE,\n\n\t\tChainTypes::Testnet2 => PROOFSIZE,\n\n\t\tChainTypes::Mainnet => PROOFSIZE,\n\n\t}\n\n}\n\n\n", "file_path": "core/src/global.rs", "rank": 32, "score": 140269.01007870783 }, { "content": "/// The sizeshift\n\npub fn sizeshift() -> u8 {\n\n\tlet param_ref = CHAIN_TYPE.read().unwrap();\n\n\tmatch *param_ref {\n\n\t\tChainTypes::AutomatedTesting => AUTOMATED_TESTING_SIZESHIFT,\n\n\t\tChainTypes::UserTesting => USER_TESTING_SIZESHIFT,\n\n\t\tChainTypes::Testnet1 => USER_TESTING_SIZESHIFT,\n\n\t\tChainTypes::Testnet2 => DEFAULT_SIZESHIFT,\n\n\t\tChainTypes::Mainnet => DEFAULT_SIZESHIFT,\n\n\t}\n\n}\n\n\n", "file_path": "core/src/global.rs", "rank": 33, "score": 140269.01007870783 }, { "content": "/// Coinbase maturity\n\npub fn coinbase_maturity() -> u64 {\n\n\tlet param_ref = CHAIN_TYPE.read().unwrap();\n\n\tmatch *param_ref {\n\n\t\tChainTypes::AutomatedTesting => AUTOMATED_TESTING_COINBASE_MATURITY,\n\n\t\tChainTypes::UserTesting => USER_TESTING_COINBASE_MATURITY,\n\n\t\tChainTypes::Testnet1 => COINBASE_MATURITY,\n\n\t\tChainTypes::Testnet2 => COINBASE_MATURITY,\n\n\t\tChainTypes::Mainnet => COINBASE_MATURITY,\n\n\t}\n\n}\n\n\n", "file_path": "core/src/global.rs", "rank": 34, "score": 137716.86138034554 }, { "content": "/// Are we in production mode (a live public network)?\n\npub fn is_production_mode() -> bool {\n\n\tlet param_ref = CHAIN_TYPE.read().unwrap();\n\n\tChainTypes::Testnet1 == *param_ref || ChainTypes::Testnet2 == *param_ref\n\n\t\t|| ChainTypes::Mainnet == *param_ref\n\n}\n\n\n", "file_path": "core/src/global.rs", "rank": 35, "score": 137716.86138034554 }, { "content": "/// Horizon at which we can cut-through and do full local pruning\n\npub fn cut_through_horizon() -> u32 {\n\n\tlet param_ref = CHAIN_TYPE.read().unwrap();\n\n\tmatch *param_ref {\n\n\t\tChainTypes::AutomatedTesting => TESTING_CUT_THROUGH_HORIZON,\n\n\t\tChainTypes::UserTesting => TESTING_CUT_THROUGH_HORIZON,\n\n\t\tChainTypes::Testnet1 => CUT_THROUGH_HORIZON,\n\n\t\tChainTypes::Testnet2 => CUT_THROUGH_HORIZON,\n\n\t\tChainTypes::Mainnet => CUT_THROUGH_HORIZON,\n\n\t}\n\n}\n\n\n", "file_path": "core/src/global.rs", "rank": 36, "score": 137716.86138034554 }, { "content": "// current height back to 0 decreasing in powers of 2\n\nfn get_locator_heights(height: u64) -> Vec<u64> {\n\n\tlet mut current = height.clone();\n\n\tlet mut heights = vec![];\n\n\twhile current > 0 {\n\n\t\theights.push(current);\n\n\t\tif heights.len() >= (p2p::MAX_LOCATORS as usize) - 1 {\n\n\t\t\tbreak;\n\n\t\t}\n\n\t\tlet next = 2u64.pow(heights.len() as u32);\n\n\t\tcurrent = if current > next { current - next } else { 0 }\n\n\t}\n\n\theights.push(0);\n\n\theights\n\n}\n\n\n", "file_path": "servers/src/grin/sync.rs", "rank": 37, "score": 135522.15656099608 }, { "content": "/// Helper function to get a nonce known to create a valid POW on\n\n/// the genesis block, to prevent it taking ages. Should be fine for now\n\n/// as the genesis block POW solution turns out to be the same for every new\n\n/// block chain at the moment\n\npub fn get_genesis_nonce() -> u64 {\n\n\tlet param_ref = CHAIN_TYPE.read().unwrap();\n\n\tmatch *param_ref {\n\n\t\t// won't make a difference\n\n\t\tChainTypes::AutomatedTesting => 0,\n\n\t\t// Magic nonce for current genesis block at cuckoo16\n\n\t\tChainTypes::UserTesting => 27944,\n\n\t\t// Magic nonce for genesis block for testnet2 (cuckoo30)\n\n\t\t_ => panic!(\"Pre-set\"),\n\n\t}\n\n}\n\n\n\n/// Converts an iterator of block difficulty data to more a more mangeable vector and pads\n\n/// if needed (which will) only be needed for the first few blocks after genesis\n\n\n", "file_path": "core/src/global.rs", "rank": 38, "score": 135316.47877658278 }, { "content": "/// Start all server HTTP handlers. Register all of them with Iron\n\n/// and runs the corresponding HTTP server.\n\n///\n\n/// Hyper currently has a bug that prevents clean shutdown. In order\n\n/// to avoid having references kept forever by handlers, we only pass\n\n/// weak references. Note that this likely means a crash if the handlers are\n\n/// used after a server shutdown (which should normally never happen,\n\n/// except during tests).\n\npub fn start_rest_apis<T>(\n\n\taddr: String,\n\n\tchain: Weak<chain::Chain>,\n\n\ttx_pool: Weak<RwLock<pool::TransactionPool<T>>>,\n\n\tpeers: Weak<p2p::Peers>,\n\n) where\n\n\tT: pool::BlockChain + Send + Sync + 'static,\n\n{\n\n\tlet _ = thread::Builder::new()\n\n\t\t.name(\"apis\".to_string())\n\n\t\t.spawn(move || {\n\n\t\t\t// build handlers and register them under the appropriate endpoint\n\n\t\t\tlet output_handler = OutputHandler {\n\n\t\t\t\tchain: chain.clone(),\n\n\t\t\t};\n\n\t\t\tlet block_handler = BlockHandler {\n\n\t\t\t\tchain: chain.clone(),\n\n\t\t\t};\n\n\t\t\tlet chain_tip_handler = ChainHandler {\n\n\t\t\t\tchain: chain.clone(),\n", "file_path": "api/src/handlers.rs", "rank": 39, "score": 135316.02583122405 }, { "content": "/// Are we in user testing mode?\n\npub fn is_user_testing_mode() -> bool {\n\n\tlet param_ref = CHAIN_TYPE.read().unwrap();\n\n\tChainTypes::UserTesting == *param_ref\n\n}\n\n\n", "file_path": "core/src/global.rs", "rank": 40, "score": 135311.62060028943 }, { "content": "/// Are we in automated testing mode?\n\npub fn is_automated_testing_mode() -> bool {\n\n\tlet param_ref = CHAIN_TYPE.read().unwrap();\n\n\tChainTypes::AutomatedTesting == *param_ref\n\n}\n\n\n", "file_path": "core/src/global.rs", "rank": 41, "score": 135311.62060028943 }, { "content": "/// Call the wallet API to create a coinbase output for the given block_fees.\n\n/// Will retry based on default \"retry forever with backoff\" behavior.\n\npub fn create_coinbase(url: &str, block_fees: &BlockFees) -> Result<CbData, Error> {\n\n\tlet mut has_error = false;\n\n\n\n\tretry_backoff_forever(|| {\n\n\t\tlet res = single_create_coinbase(&url, &block_fees);\n\n\t\tif let Err(_) = res {\n\n\t\t\thas_error = true;\n\n\t\t\terror!(\n\n\t\t\t\tLOGGER,\n\n\t\t\t\t\"Failed to get coinbase from {}. Run grin wallet listen\", url\n\n\t\t\t);\n\n\t\t}\n\n\t\tif has_error {\n\n\t\t\terror!(LOGGER, \"Successfully received coinbase from {}\", url);\n\n\t\t}\n\n\t\tres\n\n\t})\n\n}\n\n\n", "file_path": "wallet/src/client.rs", "rank": 42, "score": 135282.6746018561 }, { "content": "/// A process to monitor transactions in the stempool.\n\n/// With Dandelion, transaction can be broadcasted in stem or fluff phase.\n\n/// When sent in stem phase, the transaction is relayed to only node: the dandelion relay. In\n\n/// order to maintain reliability a timer is started for each transaction sent in stem phase.\n\n/// This function will monitor the stempool and test if the timer is expired for each transaction.\n\n/// In that case the transaction will be sent in fluff phase (to multiple peers) instead of\n\n/// sending only to the peer relay.\n\npub fn monitor_transactions<T>(\n\n\tconfig: PoolConfig,\n\n\ttx_pool: Arc<RwLock<TransactionPool<T>>>,\n\n\tstop: Arc<AtomicBool>,\n\n) where\n\n\tT: BlockChain + Send + Sync + 'static,\n\n{\n\n\tdebug!(LOGGER, \"Started Dandelion transaction monitor\");\n\n\tlet _ = thread::Builder::new()\n\n\t\t.name(\"dandelion\".to_string())\n\n\t\t.spawn(move || {\n\n\t\t\tloop {\n\n\t\t\t\tlet tx_pool = tx_pool.clone();\n\n\t\t\t\tlet stem_transactions = tx_pool.read().unwrap().stem_transactions.clone();\n\n\t\t\t\tlet time_stem_transactions = tx_pool.read().unwrap().time_stem_transactions.clone();\n\n\n\n\t\t\t\tfor tx_hash in stem_transactions.keys() {\n\n\t\t\t\t\tlet time_transaction = time_stem_transactions.get(tx_hash).unwrap();\n\n\t\t\t\t\tlet interval = now_utc().to_timespec().sec - time_transaction;\n\n\n", "file_path": "servers/src/grin/dandelion_monitor.rs", "rank": 43, "score": 133046.3449083977 }, { "content": "/// Extract the list of seeds from a pre-defined text file available through\n\n/// http. Easy method until we have a set of DNS names we can rely on.\n\npub fn web_seeds() -> Box<Fn() -> Vec<SocketAddr> + Send> {\n\n\tBox::new(|| {\n\n\t\tlet client = hyper::Client::new();\n\n\t\tdebug!(LOGGER, \"Retrieving seed nodes from {}\", &SEEDS_URL);\n\n\n\n\t\t// http get, filtering out non 200 results\n\n\t\tlet mut res = client\n\n\t\t\t.get(SEEDS_URL)\n\n\t\t\t.send()\n\n\t\t\t.expect(\"Failed to resolve seeds.\");\n\n\t\tif res.status != hyper::Ok {\n\n\t\t\tpanic!(\"Failed to resolve seeds, got status {}.\", res.status);\n\n\t\t}\n\n\t\tlet mut buf = vec![];\n\n\t\tres.read_to_end(&mut buf)\n\n\t\t\t.expect(\"Could not read seed list.\");\n\n\n\n\t\tlet text = str::from_utf8(&buf[..]).expect(\"Corrupted seed list.\");\n\n\t\tlet addrs = text.split_whitespace()\n\n\t\t\t.map(|s| s.parse().unwrap())\n\n\t\t\t.collect::<Vec<_>>();\n\n\t\tdebug!(LOGGER, \"Retrieved seed addresses: {:?}\", addrs);\n\n\t\taddrs\n\n\t})\n\n}\n\n\n", "file_path": "servers/src/grin/seed.rs", "rank": 44, "score": 132335.7121118348 }, { "content": "pub fn dns_seeds() -> Box<Fn() -> Vec<SocketAddr> + Send> {\n\n\tBox::new(|| {\n\n\t\tlet mut addresses: Vec<SocketAddr> = vec![];\n\n\t\tfor dns_seed in DNS_SEEDS {\n\n\t\t\tlet temp_addresses = addresses.clone();\n\n\t\t\tdebug!(LOGGER, \"Retrieving seed nodes from dns {}\", dns_seed);\n\n\t\t\tmatch (dns_seed.to_owned(), 0).to_socket_addrs() {\n\n\t\t\t\tOk(addrs) => addresses.append(\n\n\t\t\t\t\t&mut (addrs\n\n\t\t\t\t\t\t.map(|mut addr| {\n\n\t\t\t\t\t\t\taddr.set_port(13414);\n\n\t\t\t\t\t\t\taddr\n\n\t\t\t\t\t\t})\n\n\t\t\t\t\t\t.filter(|addr| !temp_addresses.contains(addr))\n\n\t\t\t\t\t\t.collect()),\n\n\t\t\t\t),\n\n\t\t\t\tErr(e) => debug!(\n\n\t\t\t\t\tLOGGER,\n\n\t\t\t\t\t\"Failed to resolve seed {:?} got error {:?}\", dns_seed, e\n\n\t\t\t\t),\n\n\t\t\t}\n\n\t\t}\n\n\t\taddresses\n\n\t})\n\n}\n\n\n", "file_path": "servers/src/grin/seed.rs", "rank": 45, "score": 132335.7121118348 }, { "content": "/// Placeholder for mainnet genesis block, will definitely change before\n\n/// release so no use trying to pre-mine it.\n\npub fn genesis_main() -> core::Block {\n\n\tcore::Block {\n\n\t\theader: core::BlockHeader {\n\n\t\t\theight: 0,\n\n\t\t\tprevious: core::hash::Hash([0xff; 32]),\n\n\t\t\ttimestamp: time::Tm {\n\n\t\t\t\ttm_year: 2018 - 1900,\n\n\t\t\t\ttm_mon: 7,\n\n\t\t\t\ttm_mday: 14,\n\n\t\t\t\t..time::empty_tm()\n\n\t\t\t},\n\n\t\t\ttotal_difficulty: Difficulty::from_num(global::initial_block_difficulty()),\n\n\t\t\tnonce: global::get_genesis_nonce(),\n\n\t\t\tpow: core::Proof::zero(consensus::PROOFSIZE),\n\n\t\t\t..Default::default()\n\n\t\t},\n\n\t\tinputs: vec![],\n\n\t\toutputs: vec![],\n\n\t\tkernels: vec![],\n\n\t}\n\n}\n", "file_path": "core/src/genesis.rs", "rank": 46, "score": 131055.21023153045 }, { "content": "/// Genesis block definition for development networks. The proof of work size\n\n/// is small enough to mine it on the fly, so it does not contain its own\n\n/// proof of work solution. Can also be easily mutated for different tests.\n\npub fn genesis_dev() -> core::Block {\n\n\tcore::Block {\n\n\t\theader: core::BlockHeader {\n\n\t\t\theight: 0,\n\n\t\t\tprevious: core::hash::Hash([0xff; 32]),\n\n\t\t\ttimestamp: time::Tm {\n\n\t\t\t\ttm_year: 1997 - 1900,\n\n\t\t\t\ttm_mon: 7,\n\n\t\t\t\ttm_mday: 4,\n\n\t\t\t\t..time::empty_tm()\n\n\t\t\t},\n\n\t\t\tnonce: global::get_genesis_nonce(),\n\n\t\t\t..Default::default()\n\n\t\t},\n\n\t\tinputs: vec![],\n\n\t\toutputs: vec![],\n\n\t\tkernels: vec![],\n\n\t}\n\n}\n\n\n", "file_path": "core/src/genesis.rs", "rank": 47, "score": 131050.07675716616 }, { "content": "/// First testnet genesis block, still subject to change (especially the date,\n\n/// will hopefully come before Christmas).\n\npub fn genesis_testnet1() -> core::Block {\n\n\tcore::Block {\n\n\t\theader: core::BlockHeader {\n\n\t\t\theight: 0,\n\n\t\t\tprevious: core::hash::Hash([0xff; 32]),\n\n\t\t\ttimestamp: time::Tm {\n\n\t\t\t\ttm_year: 2017 - 1900,\n\n\t\t\t\ttm_mon: 10,\n\n\t\t\t\ttm_mday: 16,\n\n\t\t\t\ttm_hour: 20,\n\n\t\t\t\t..time::empty_tm()\n\n\t\t\t},\n\n\t\t\tnonce: 28205,\n\n\t\t\tpow: core::Proof::new(vec![\n\n\t\t\t\t0x21e, 0x7a2, 0xeae, 0x144e, 0x1b1c, 0x1fbd, 0x203a, 0x214b, 0x293b, 0x2b74,\n\n\t\t\t\t0x2bfa, 0x2c26, 0x32bb, 0x346a, 0x34c7, 0x37c5, 0x4164, 0x42cc, 0x4cc3, 0x55af,\n\n\t\t\t\t0x5a70, 0x5b14, 0x5e1c, 0x5f76, 0x6061, 0x60f9, 0x61d7, 0x6318, 0x63a1, 0x63fb,\n\n\t\t\t\t0x649b, 0x64e5, 0x65a1, 0x6b69, 0x70f8, 0x71c7, 0x71cd, 0x7492, 0x7b11, 0x7db8,\n\n\t\t\t\t0x7f29, 0x7ff8,\n\n\t\t\t]),\n\n\t\t\t..Default::default()\n\n\t\t},\n\n\t\tinputs: vec![],\n\n\t\toutputs: vec![],\n\n\t\tkernels: vec![],\n\n\t}\n\n}\n\n\n", "file_path": "core/src/genesis.rs", "rank": 48, "score": 131050.07675716616 }, { "content": "/// Second testnet genesis block (cuckoo30). TBD and don't start getting excited\n\n/// just because you see this reference here... this is for testing mining\n\n/// at cuckoo 30\n\npub fn genesis_testnet2() -> core::Block {\n\n\tcore::Block {\n\n\t\theader: core::BlockHeader {\n\n\t\t\theight: 0,\n\n\t\t\tprevious: core::hash::Hash([0xff; 32]),\n\n\t\t\ttimestamp: time::Tm {\n\n\t\t\t\ttm_year: 2018 - 1900,\n\n\t\t\t\ttm_mon: 2,\n\n\t\t\t\ttm_mday: 26,\n\n\t\t\t\ttm_hour: 16,\n\n\t\t\t\t..time::empty_tm()\n\n\t\t\t},\n\n\t\t\ttotal_difficulty: Difficulty::from_num(global::initial_block_difficulty()),\n\n\t\t\tnonce: 1060,\n\n\t\t\tpow: core::Proof::new(vec![\n\n\t\t\t\t0x1940730, 0x333b9d0, 0x4739d6f, 0x4c6cfb1, 0x6e3d6c3, 0x74408a3, 0x7ba2bd2,\n\n\t\t\t\t0x83e2024, 0x8ca22b5, 0x9d39ab8, 0xb6646dd, 0xc6698b6, 0xc6f78fe, 0xc99b662,\n\n\t\t\t\t0xcf2ae8c, 0xcf41eed, 0xdd073e6, 0xded6af8, 0xf08d1a5, 0x1156a144, 0x11d1160a,\n\n\t\t\t\t0x131bb0a5, 0x137ad703, 0x13b0831f, 0x1421683f, 0x147e3c1f, 0x1496fda0, 0x150ba22b,\n\n\t\t\t\t0x15cc5bc6, 0x16edf697, 0x17ced40c, 0x17d84f9e, 0x18a515c1, 0x19320d9c, 0x19da4f6d,\n\n\t\t\t\t0x1b50bcb1, 0x1b8bc72f, 0x1c7b6964, 0x1d07b3a9, 0x1d189d4d, 0x1d1f9a15, 0x1dafcd41,\n\n\t\t\t]),\n\n\t\t\t..Default::default()\n\n\t\t},\n\n\t\tinputs: vec![],\n\n\t\toutputs: vec![],\n\n\t\tkernels: vec![],\n\n\t}\n\n}\n\n\n", "file_path": "core/src/genesis.rs", "rank": 49, "score": 131050.07675716616 }, { "content": "/// A no-op function for doing nothing with some pruned data.\n\npub fn prune_noop(_pruned_data: &[u8]) {}\n\n\n\n/// Wrapper for a file that can be read at any position (random read) but for\n\n/// which writes are append only. Reads are backed by a memory map (mmap(2)),\n\n/// relying on the operating system for fast access and caching. The memory\n\n/// map is reallocated to expand it when new writes are flushed.\n\n///\n\n/// Despite being append-only, the file can still be pruned and truncated. The\n\n/// former simply happens by rewriting it, ignoring some of the data. The\n\n/// latter by truncating the underlying file and re-creating the mmap.\n\npub struct AppendOnlyFile {\n\n\tpath: String,\n\n\tfile: File,\n\n\tmmap: Option<memmap::Mmap>,\n\n\tbuffer_start: usize,\n\n\tbuffer: Vec<u8>,\n\n\tbuffer_start_bak: usize,\n\n}\n\n\n\nimpl AppendOnlyFile {\n", "file_path": "store/src/types.rs", "rank": 50, "score": 128779.41419099618 }, { "content": "#[test]\n\nfn peer_handshake() {\n\n\tutil::init_test_logger();\n\n\n\n\tlet p2p_conf = p2p::P2PConfig {\n\n\t\thost: \"0.0.0.0\".parse().unwrap(),\n\n\t\tport: open_port(),\n\n\t\tpeers_allow: None,\n\n\t\tpeers_deny: None,\n\n\t\t..p2p::P2PConfig::default()\n\n\t};\n\n\tlet net_adapter = Arc::new(p2p::DummyAdapter {});\n\n\tlet server = Arc::new(\n\n\t\tp2p::Server::new(\n\n\t\t\t\".grin\".to_owned(),\n\n\t\t\tp2p::Capabilities::UNKNOWN,\n\n\t\t\tp2p_conf.clone(),\n\n\t\t\tnet_adapter.clone(),\n\n\t\t\tHash::from_vec(vec![]),\n\n\t\t\tArc::new(AtomicBool::new(false)),\n\n\t\t\tfalse,\n", "file_path": "p2p/tests/peer_handshake.rs", "rank": 51, "score": 128616.5847763963 }, { "content": "/// Actual block reward for a given total fee amount\n\npub fn reward(fee: u64) -> u64 {\n\n\tREWARD + fee\n\n}\n\n\n\n/// Number of blocks before a coinbase matures and can be spent\n\npub const COINBASE_MATURITY: u64 = 1_000;\n\n\n\n/// Block interval, in seconds, the network will tune its next_target for. Note\n\n/// that we may reduce this value in the future as we get more data on mining\n\n/// with Cuckoo Cycle, networks improve and block propagation is optimized\n\n/// (adjusting the reward accordingly).\n\npub const BLOCK_TIME_SEC: u64 = 60;\n\n\n\n/// Cuckoo-cycle proof size (cycle length)\n\npub const PROOFSIZE: usize = 42;\n\n\n\n/// Default Cuckoo Cycle size shift used for mining and validating.\n\npub const DEFAULT_SIZESHIFT: u8 = 30;\n\n\n\n/// Default Cuckoo Cycle easiness, high enough to have good likeliness to find\n", "file_path": "core/src/consensus.rs", "rank": 52, "score": 127410.38490078748 }, { "content": "/// Set the mining mode\n\npub fn set_mining_mode(mode: ChainTypes) {\n\n\tlet mut param_ref = CHAIN_TYPE.write().unwrap();\n\n\t*param_ref = mode;\n\n}\n\n\n", "file_path": "core/src/global.rs", "rank": 53, "score": 126632.34233007915 }, { "content": "#[derive(Clone)]\n\nstruct TrackingAdapter {\n\n\tadapter: Arc<NetAdapter>,\n\n\tknown: Arc<RwLock<Vec<Hash>>>,\n\n}\n\n\n\nimpl TrackingAdapter {\n\n\tfn new(adapter: Arc<NetAdapter>) -> TrackingAdapter {\n\n\t\tTrackingAdapter {\n\n\t\t\tadapter: adapter,\n\n\t\t\tknown: Arc::new(RwLock::new(vec![])),\n\n\t\t}\n\n\t}\n\n\n\n\tfn has(&self, hash: Hash) -> bool {\n\n\t\tlet known = self.known.read().unwrap();\n\n\t\t// may become too slow, an ordered set (by timestamp for eviction) may\n\n\t\t// end up being a better choice\n\n\t\tknown.contains(&hash)\n\n\t}\n\n\n", "file_path": "p2p/src/peer.rs", "rank": 54, "score": 126493.1620966912 }, { "content": "/// Is this position a leaf in the MMR?\n\n/// We know the positions of all leaves based on the postorder height of an MMR of any size\n\n/// (somewhat unintuitively but this is how the PMMR is \"append only\").\n\npub fn is_leaf(pos: u64) -> bool {\n\n\tbintree_postorder_height(pos) == 0\n\n}\n\n\n", "file_path": "core/src/core/pmmr.rs", "rank": 55, "score": 125144.814398152 }, { "content": "/// Just removes all results from previous runs\n\npub fn clean_all_output(test_name_dir: &str) {\n\n\tlet target_dir = format!(\"target/tmp/{}\", test_name_dir);\n\n\tlet result = fs::remove_dir_all(target_dir);\n\n\tif let Err(e) = result {\n\n\t\tprintln!(\"{}\", e);\n\n\t}\n\n}\n\n\n\n/// Errors that can be returned by LocalServerContainer\n\n#[derive(Debug)]\n\n#[allow(dead_code)]\n\npub enum Error {\n\n\tInternal(String),\n\n\tArgument(String),\n\n\tNotFound,\n\n}\n\n\n\n/// All-in-one server configuration struct, for convenience\n\n///\n\n#[derive(Clone)]\n", "file_path": "servers/tests/framework/mod.rs", "rank": 56, "score": 124599.0380631586 }, { "content": "/// Runs a proof of work computation over the provided block using the provided\n\n/// Mining Worker, until the required difficulty target is reached. May take a\n\n/// while for a low target...\n\npub fn pow_size<T: MiningWorker + ?Sized>(\n\n\tminer: &mut T,\n\n\tbh: &mut BlockHeader,\n\n\tdiff: Difficulty,\n\n\t_: u32,\n\n) -> Result<(), Error> {\n\n\tlet start_nonce = bh.nonce;\n\n\n\n\t// set the nonce for faster solution finding in user testing\n\n\tif bh.height == 0 && global::is_user_testing_mode() {\n\n\t\tbh.nonce = global::get_genesis_nonce();\n\n\t}\n\n\n\n\t// try to find a cuckoo cycle on that header hash\n\n\tloop {\n\n\t\t// can be trivially optimized by avoiding re-serialization every time but this\n\n\t\t// is not meant as a fast miner implementation\n\n\t\tlet pow_hash = bh.pre_pow_hash();\n\n\n\n\t\t// if we found a cycle (not guaranteed) and the proof hash is higher that the\n", "file_path": "pow/src/lib.rs", "rank": 57, "score": 123002.63538502913 }, { "content": "/// Is the node at this pos the \"left\" sibling of its parent?\n\npub fn is_left_sibling(pos: u64) -> bool {\n\n\tlet (_, sibling_pos) = family(pos);\n\n\tsibling_pos > pos\n\n}\n\n\n", "file_path": "core/src/core/pmmr.rs", "rank": 58, "score": 122992.65047370049 }, { "content": "/// Initialises the logger with the given configuration\n\npub fn init_logger(config: Option<LoggingConfig>) {\n\n\tif let Some(c) = config {\n\n\t\tlet mut config_ref = LOGGING_CONFIG.lock().unwrap();\n\n\t\t*config_ref = c.clone();\n\n\t\t// Logger configuration successfully injected into LOGGING_CONFIG...\n\n\t\tlet mut was_init_ref = WAS_INIT.lock().unwrap();\n\n\t\t*was_init_ref = true;\n\n\t\t// .. allow logging, having ensured that paths etc are immutable\n\n\t}\n\n\tsend_panic_to_log();\n\n}\n\n\n", "file_path": "util/src/logger.rs", "rank": 59, "score": 122992.65047370049 }, { "content": "// Creates a new chain with a genesis at a simulated difficulty\n\nfn create_chain_sim(diff: u64) -> Vec<Result<(u64, Difficulty), TargetError>> {\n\n\tprintln!(\n\n\t\t\"adding create: {}, {}\",\n\n\t\ttime::get_time().sec,\n\n\t\tDifficulty::from_num(diff)\n\n\t);\n\n\tvec![\n\n\t\tOk((time::get_time().sec as u64, Difficulty::from_num(diff))),\n\n\t]\n\n}\n\n\n", "file_path": "core/tests/consensus.rs", "rank": 60, "score": 122597.00618101514 }, { "content": "/// Encode the provided bytes into a hex string\n\npub fn to_hex(bytes: Vec<u8>) -> String {\n\n\tlet mut s = String::new();\n\n\tfor byte in bytes {\n\n\t\twrite!(&mut s, \"{:02x}\", byte).expect(\"Unable to write\");\n\n\t}\n\n\ts\n\n}\n\n\n", "file_path": "util/src/hex.rs", "rank": 61, "score": 121995.02545753037 }, { "content": "/// Create and return a MinerConfig\n\npub fn miner_config() -> pow::types::MinerConfig {\n\n\tlet mut plugin_config = pow::types::CuckooMinerPluginConfig::default();\n\n\tlet mut plugin_config_vec: Vec<pow::types::CuckooMinerPluginConfig> = Vec::new();\n\n\tplugin_config.type_filter = String::from(\"mean_cpu\");\n\n\tplugin_config_vec.push(plugin_config);\n\n\n\n\tpow::types::MinerConfig {\n\n\t\tenable_mining: true,\n\n\t\tburn_reward: true,\n\n\t\tminer_async_mode: Some(false),\n\n\t\tminer_plugin_dir: None,\n\n\t\tminer_plugin_config: Some(plugin_config_vec),\n\n\t\t..Default::default()\n\n\t}\n\n}\n", "file_path": "servers/tests/framework/mod.rs", "rank": 62, "score": 120964.8878215373 }, { "content": "pub fn amount_to_hr_string(amount: u64) -> String {\n\n\tlet amount = (amount as f64 / GRIN_BASE as f64) as f64;\n\n\tlet places = (GRIN_BASE as f64).log(10.0) as usize + 1;\n\n\tString::from(format!(\"{:.*}\", places, amount))\n\n}\n\n\n\n#[cfg(test)]\n\nmod test {\n\n\tuse super::*;\n\n\tuse core::target::Difficulty;\n\n\tuse core::hash::ZERO_HASH;\n\n\tuse core::build::{initial_tx, input, output, with_excess, with_fee, with_lock_height};\n\n\tuse core::block::Error::KernelLockHeight;\n\n\tuse ser;\n\n\tuse keychain;\n\n\tuse keychain::{BlindingFactor, Keychain};\n\n\n\n\t#[test]\n\n\tpub fn test_amount_to_hr() {\n\n\t\tassert!(50123456789 == amount_from_hr_string(\"50.123456789\").unwrap());\n", "file_path": "core/src/core/mod.rs", "rank": 63, "score": 120959.34620677994 }, { "content": "/// Request some block headers from a peer to advance us.\n\nfn request_headers(peer: Arc<RwLock<Peer>>, chain: Arc<chain::Chain>) -> Result<(), Error> {\n\n\tlet locator = get_locator(chain)?;\n\n\tif let Ok(peer) = peer.try_read() {\n\n\t\tdebug!(\n\n\t\t\tLOGGER,\n\n\t\t\t\"sync: request_headers: asking {} for headers, {:?}\", peer.info.addr, locator,\n\n\t\t);\n\n\t\tlet _ = peer.send_header_request(locator);\n\n\t} else {\n\n\t\t// not much we can do here, log and try again next time\n\n\t\tdebug!(\n\n\t\t\tLOGGER,\n\n\t\t\t\"sync: request_headers: failed to get read lock on peer\",\n\n\t\t);\n\n\t}\n\n\tOk(())\n\n}\n\n\n", "file_path": "servers/src/grin/sync.rs", "rank": 64, "score": 120583.63063354103 }, { "content": "/// The number of leaves nodes in a MMR of the provided size. Uses peaks to\n\n/// get the positions of all full binary trees and uses the height of these\n\npub fn n_leaves(mut sz: u64) -> u64 {\n\n\twhile bintree_postorder_height(sz + 1) > 0 {\n\n\t\tsz += 1;\n\n\t}\n\n\tpeaks(sz)\n\n\t\t.iter()\n\n\t\t.map(|n| (1 << bintree_postorder_height(*n)) as u64)\n\n\t\t.sum()\n\n}\n\n\n", "file_path": "core/src/core/pmmr.rs", "rank": 65, "score": 119858.98163614568 }, { "content": "/// Sets the fee on the transaction being built.\n\npub fn with_fee(fee: u64) -> Box<Append> {\n\n\tBox::new(\n\n\t\tmove |_build, (tx, kern, sum)| -> (Transaction, TxKernel, BlindSum) {\n\n\t\t\t(tx, kern.with_fee(fee), sum)\n\n\t\t},\n\n\t)\n\n}\n\n\n", "file_path": "core/src/core/build.rs", "rank": 66, "score": 119847.95359661334 }, { "content": "/// Calculates the positions of the parent and sibling of the node at the\n\n/// provided position.\n\npub fn family(pos: u64) -> (u64, u64) {\n\n\tlet pos_height = bintree_postorder_height(pos);\n\n\tlet next_height = bintree_postorder_height(pos + 1);\n\n\tif next_height > pos_height {\n\n\t\tlet sibling = bintree_jump_left_sibling(pos);\n\n\t\tlet parent = pos + 1;\n\n\t\t(parent, sibling)\n\n\t} else {\n\n\t\tlet sibling = bintree_jump_right_sibling(pos);\n\n\t\tlet parent = sibling + 1;\n\n\t\t(parent, sibling)\n\n\t}\n\n}\n\n\n", "file_path": "core/src/core/pmmr.rs", "rank": 67, "score": 119847.95359661334 }, { "content": "/// Gets the postorder traversal index of all peaks in a MMR given the last\n\n/// node's position. Starts with the top peak, which is always on the left\n\n/// side of the range, and navigates toward lower siblings toward the right\n\n/// of the range.\n\npub fn peaks(num: u64) -> Vec<u64> {\n\n\t// detecting an invalid mountain range, when siblings exist but no parent\n\n\t// exists\n\n\tif bintree_postorder_height(num + 1) > bintree_postorder_height(num) {\n\n\t\treturn vec![];\n\n\t}\n\n\n\n\t// our top peak is always on the leftmost side of the tree and leftmost trees\n\n\t// have for index a binary values with all 1s (i.e. 11, 111, 1111, etc.)\n\n\tlet mut top = 1;\n\n\twhile (top - 1) <= num {\n\n\t\ttop = top << 1;\n\n\t}\n\n\ttop = (top >> 1) - 1;\n\n\tif top == 0 {\n\n\t\treturn vec![1];\n\n\t}\n\n\n\n\tlet mut peaks = vec![top];\n\n\n", "file_path": "core/src/core/pmmr.rs", "rank": 68, "score": 119847.95359661334 }, { "content": "/// Convenience function when the seed list is immediately known. Mostly used\n\n/// for tests.\n\npub fn predefined_seeds(addrs_str: Vec<String>) -> Box<Fn() -> Vec<SocketAddr> + Send> {\n\n\tBox::new(move || {\n\n\t\taddrs_str\n\n\t\t\t.iter()\n\n\t\t\t.map(|s| s.parse().unwrap())\n\n\t\t\t.collect::<Vec<_>>()\n\n\t})\n\n}\n", "file_path": "servers/src/grin/seed.rs", "rank": 69, "score": 119253.99793622637 }, { "content": "/// Sets a known tx \"offset\". Used in final step of tx construction.\n\npub fn with_offset(offset: BlindingFactor) -> Box<Append> {\n\n\tBox::new(\n\n\t\tmove |_build, (tx, kern, sum)| -> (Transaction, TxKernel, BlindSum) {\n\n\t\t\t(tx.with_offset(offset), kern, sum)\n\n\t\t},\n\n\t)\n\n}\n\n\n", "file_path": "core/src/core/build.rs", "rank": 70, "score": 117819.8826271969 }, { "content": "/// Adds a known excess value on the transaction being built. Usually used in\n\n/// combination with the initial_tx function when a new transaction is built\n\n/// by adding to a pre-existing one.\n\npub fn with_excess(excess: BlindingFactor) -> Box<Append> {\n\n\tBox::new(\n\n\t\tmove |_build, (tx, kern, sum)| -> (Transaction, TxKernel, BlindSum) {\n\n\t\t\t(tx, kern, sum.add_blinding_factor(excess.clone()))\n\n\t\t},\n\n\t)\n\n}\n\n\n", "file_path": "core/src/core/build.rs", "rank": 71, "score": 117819.56406192153 }, { "content": "pub fn show_info(config: &WalletConfig, keychain: &Keychain) {\n\n\tlet wallet_info = retrieve_info(config, keychain);\n\n\tprintln!(\n\n\t\t\"\\n____ Wallet Summary Info at {} ({}) ____\\n\",\n\n\t\twallet_info.current_height, wallet_info.data_confirmed_from\n\n\t);\n\n\tlet mut table = table!(\n\n\t\t[bFG->\"Total\", FG->amount_to_hr_string(wallet_info.total)],\n\n\t\t[bFY->\"Awaiting Confirmation\", FY->amount_to_hr_string(wallet_info.amount_awaiting_confirmation)],\n\n\t\t[bFY->\"Confirmed but Still Locked\", FY->amount_to_hr_string(wallet_info.amount_confirmed_but_locked)],\n\n\t\t[bFG->\"Currently Spendable\", FG->amount_to_hr_string(wallet_info.amount_currently_spendable)],\n\n\t\t[Fw->\"---------\", Fw->\"---------\"],\n\n\t\t[Fr->\"(Locked by previous transaction)\", Fr->amount_to_hr_string(wallet_info.amount_locked)]\n\n\t);\n\n\ttable.set_format(*prettytable::format::consts::FORMAT_NO_BORDER_LINE_SEPARATOR);\n\n\ttable.printstd();\n\n\tprintln!();\n\n\n\n\tif !wallet_info.data_confirmed {\n\n\t\tprintln!(\n\n\t\t\t\"\\nWARNING: Failed to verify wallet contents with grin server. \\\n\n\t\t\t Above info is maybe not fully updated or invalid! \\\n\n\t\t\t Check that your `grin server` is OK, or see `wallet help restore`\"\n\n\t\t);\n\n\t}\n\n}\n\n\n", "file_path": "wallet/src/info.rs", "rank": 72, "score": 117814.6493296928 }, { "content": "// Block handler functions\n\nfn get_block_by_height(\n\n\tbase_addr: &String,\n\n\tapi_server_port: u16,\n\n\theight: u64,\n\n) -> Result<api::BlockPrintable, Error> {\n\n\tlet url = format!(\n\n\t\t\"http://{}:{}/v1/blocks/{}\",\n\n\t\tbase_addr, api_server_port, height\n\n\t);\n\n\tapi::client::get::<api::BlockPrintable>(url.as_str()).map_err(|e| Error::API(e))\n\n}\n\n\n", "file_path": "servers/tests/api.rs", "rank": 73, "score": 117305.38024723592 }, { "content": "fn get_outputs_by_height(\n\n\tbase_addr: &String,\n\n\tapi_server_port: u16,\n\n\tstart_height: u64,\n\n\tend_height: u64,\n\n) -> Result<Vec<api::BlockOutputs>, Error> {\n\n\tlet url = format!(\n\n\t\t\"http://{}:{}/v1/chain/outputs/byheight?start_height={}&end_height={}\",\n\n\t\tbase_addr, api_server_port, start_height, end_height\n\n\t);\n\n\tapi::client::get::<Vec<api::BlockOutputs>>(url.as_str()).map_err(|e| Error::API(e))\n\n}\n\n\n", "file_path": "servers/tests/api.rs", "rank": 74, "score": 117305.38024723592 }, { "content": "fn monitor_peers(\n\n\tpeers: Arc<p2p::Peers>,\n\n\tconfig: p2p::P2PConfig,\n\n\tcapabilities: p2p::Capabilities,\n\n\ttx: mpsc::Sender<SocketAddr>,\n\n) {\n\n\t// regularly check if we need to acquire more peers and if so, gets\n\n\t// them from db\n\n\tlet total_count = peers.all_peers().len();\n\n\tlet mut healthy_count = 0;\n\n\tlet mut banned_count = 0;\n\n\tlet mut defunct_count = 0;\n\n\tfor x in peers.all_peers() {\n\n\t\tmatch x.flags {\n\n\t\t\tp2p::State::Banned => {\n\n\t\t\t\tlet interval = now_utc().to_timespec().sec - x.last_banned;\n\n\t\t\t\t// Unban peer\n\n\t\t\t\tif interval >= config.ban_window() {\n\n\t\t\t\t\tpeers.unban_peer(&x.addr);\n\n\t\t\t\t\tdebug!(\n", "file_path": "servers/src/grin/seed.rs", "rank": 75, "score": 117096.76412851475 }, { "content": "/// Implements siphash 2-4 specialized for a 4 u64 array key and a u64 nonce\n\npub fn siphash24(v: [u64; 4], nonce: u64) -> u64 {\n\n\tlet mut v0 = v[0];\n\n\tlet mut v1 = v[1];\n\n\tlet mut v2 = v[2];\n\n\tlet mut v3 = v[3] ^ nonce;\n\n\n\n\t// macro for left rotation\n\n\tmacro_rules! rotl {\n\n ($num:ident, $shift:expr) => {\n\n $num = ($num << $shift) | ($num >> (64 - $shift));\n\n }\n\n }\n\n\n\n\t// macro for a single siphash round\n\n\tmacro_rules! round {\n\n () => {\n\n v0 = v0.wrapping_add(v1);\n\n v2 = v2.wrapping_add(v3);\n\n rotl!(v1, 13);\n\n rotl!(v3, 16);\n", "file_path": "pow/src/siphash.rs", "rank": 76, "score": 116835.05883587038 }, { "content": "/// Returns the static instance, but calls randomize on it as well\n\n/// (Recommended to avoid side channel attacks\n\npub fn static_secp_instance() -> Arc<Mutex<secp::Secp256k1>> {\n\n\tlet mut secp_inst = SECP256K1.lock().unwrap();\n\n\tsecp_inst.randomize(&mut thread_rng());\n\n\tSECP256K1.clone()\n\n}\n", "file_path": "util/src/secp_static.rs", "rank": 77, "score": 115886.30367819616 }, { "content": "/// Returns the pmmr index of the nth inserted element\n\npub fn insertion_to_pmmr_index(mut sz: u64) -> u64 {\n\n\t//1 based pmmrs\n\n\tsz = sz - 1;\n\n\t2 * sz - sz.count_ones() as u64 + 1\n\n}\n\n\n", "file_path": "core/src/core/pmmr.rs", "rank": 78, "score": 115886.30367819616 }, { "content": "fn get_block_by_height_compact(\n\n\tbase_addr: &String,\n\n\tapi_server_port: u16,\n\n\theight: u64,\n\n) -> Result<api::CompactBlockPrintable, Error> {\n\n\tlet url = format!(\n\n\t\t\"http://{}:{}/v1/blocks/{}?compact\",\n\n\t\tbase_addr, api_server_port, height\n\n\t);\n\n\tapi::client::get::<api::CompactBlockPrintable>(url.as_str()).map_err(|e| Error::API(e))\n\n}\n\n\n", "file_path": "servers/tests/api.rs", "rank": 79, "score": 114740.74131234556 }, { "content": "pub fn start_rest_apis(wallet_config: WalletConfig, keychain: Keychain) {\n\n\tinfo!(\n\n\t\tLOGGER,\n\n\t\t\"Starting the Grin wallet receiving daemon at {}...\",\n\n\t\twallet_config.api_listen_addr()\n\n\t);\n\n\n\n\tlet receive_tx_handler = WalletReceiver {\n\n\t\tconfig: wallet_config.clone(),\n\n\t\tkeychain: keychain.clone(),\n\n\t};\n\n\tlet coinbase_handler = CoinbaseHandler {\n\n\t\tconfig: wallet_config.clone(),\n\n\t\tkeychain: keychain.clone(),\n\n\t};\n\n\n\n\tlet router = router!(\n\n\t\treceive_tx: post \"/receive/transaction\" => receive_tx_handler,\n\n\t\treceive_coinbase: post \"/receive/coinbase\" => coinbase_handler,\n\n\t);\n\n\n\n\tlet mut apis = ApiServer::new(\"/v1\".to_string());\n\n\tapis.register_handler(router);\n\n\tmatch apis.start(wallet_config.api_listen_addr()) {\n\n\t\tErr(e) => error!(LOGGER, \"Failed to start Grin wallet listener: {}.\", e),\n\n\t\tOk(_) => info!(LOGGER, \"Wallet listener started\"),\n\n\t};\n\n}\n", "file_path": "wallet/src/server.rs", "rank": 80, "score": 114054.99421592889 }, { "content": "/// Sets an initial transaction to add to when building a new transaction.\n\n/// We currently only support building a tx with a single kernel with build::transaction()\n\npub fn initial_tx(mut tx: Transaction) -> Box<Append> {\n\n\tassert_eq!(tx.kernels.len(), 1);\n\n\tlet kern = tx.kernels.remove(0);\n\n\tBox::new(\n\n\t\tmove |_build, (_, _, sum)| -> (Transaction, TxKernel, BlindSum) {\n\n\t\t\t(tx.clone(), kern.clone(), sum)\n\n\t\t},\n\n\t)\n\n}\n\n\n", "file_path": "core/src/core/build.rs", "rank": 81, "score": 113142.0527344011 }, { "content": "/// Packages the txhashset data files into a zip and returns a Read to the\n\n/// resulting file\n\npub fn zip_read(root_dir: String) -> Result<File, Error> {\n\n\tlet txhashset_path = Path::new(&root_dir).join(TXHASHSET_SUBDIR);\n\n\tlet zip_path = Path::new(&root_dir).join(TXHASHSET_ZIP);\n\n\n\n\t// create the zip archive\n\n\t{\n\n\t\tzip::compress(&txhashset_path, &File::create(zip_path.clone())?)\n\n\t\t\t.map_err(|ze| Error::Other(ze.to_string()))?;\n\n\t}\n\n\n\n\t// open it again to read it back\n\n\tlet zip_file = File::open(zip_path)?;\n\n\tOk(zip_file)\n\n}\n\n\n", "file_path": "chain/src/txhashset.rs", "rank": 82, "score": 113142.0527344011 }, { "content": "#[test]\n\nfn test_store_header_height() {\n\n\tlet _ = env_logger::init();\n\n\tlet chain_dir = \".grin_idx_2\";\n\n\tclean_output_dir(chain_dir);\n\n\n\n\tlet chain_store =\n\n\t\t&chain::store::ChainKVStore::new(chain_dir.to_string()).unwrap() as &ChainStore;\n\n\n\n\tlet mut block_header = BlockHeader::default();\n\n\tblock_header.height = 1;\n\n\n\n\tchain_store.save_block_header(&block_header).unwrap();\n\n\tchain_store.save_header_height(&block_header).unwrap();\n\n\n\n\tlet stored_block_header = chain_store.get_header_by_height(1).unwrap();\n\n\tassert_eq!(block_header.hash(), stored_block_header.hash());\n\n\n\n\tchain_store.delete_header_by_height(1).unwrap();\n\n\n\n\tlet result = chain_store.get_header_by_height(1);\n\n\tassert_eq!(result.is_err(), true);\n\n}\n", "file_path": "chain/tests/store_indices.rs", "rank": 83, "score": 112323.72926431076 }, { "content": "fn open_port() -> u16 {\n\n\t// use port 0 to allow the OS to assign an open port\n\n\t// TcpListener's Drop impl will unbind the port as soon as\n\n\t// listener goes out of scope\n\n\tlet listener = TcpListener::bind(\"127.0.0.1:0\").unwrap();\n\n\tlistener.local_addr().unwrap().port()\n\n}\n\n\n\n// Starts a server and connects a client peer to it to check handshake,\n\n// followed by a ping/pong exchange to make sure the connection is live.\n", "file_path": "p2p/tests/peer_handshake.rs", "rank": 84, "score": 111664.9625127214 }, { "content": "/// Compress a source directory recursively into a zip file using the\n\n/// bzip2 format. Permissions are set to 644 by default to avoid any\n\n/// unwanted execution bits.\n\npub fn compress(src_dir: &Path, dst_file: &File) -> ZipResult<()> {\n\n\tif !Path::new(src_dir).is_dir() {\n\n\t\treturn Err(ZipError::Io(io::Error::new(\n\n\t\t\tio::ErrorKind::Other,\n\n\t\t\t\"Source must be a directory.\",\n\n\t\t)));\n\n\t}\n\n\n\n\tlet options = FileOptions::default()\n\n\t\t.compression_method(zip_rs::CompressionMethod::Bzip2)\n\n\t\t.unix_permissions(0o644);\n\n\n\n\tlet mut zip = zip_rs::ZipWriter::new(dst_file);\n\n\tlet walkdir = WalkDir::new(src_dir.to_str().unwrap());\n\n\tlet it = walkdir.into_iter();\n\n\n\n\tfor dent in it.filter_map(|e| e.ok()) {\n\n\t\tlet path = dent.path();\n\n\t\tlet name = path.strip_prefix(Path::new(src_dir))\n\n\t\t\t.unwrap()\n", "file_path": "util/src/zip.rs", "rank": 85, "score": 111315.74942588489 }, { "content": "pub fn retrieve_info(config: &WalletConfig, keychain: &Keychain) -> WalletInfo {\n\n\tlet result = checker::refresh_outputs(&config, &keychain);\n\n\n\n\tlet ret_val = WalletData::read_wallet(&config.data_file_dir, |wallet_data| {\n\n\t\tlet (current_height, from) = match checker::get_tip_from_node(config) {\n\n\t\t\tOk(tip) => (tip.height, \"from server node\"),\n\n\t\t\tErr(_) => match wallet_data.outputs.values().map(|out| out.height).max() {\n\n\t\t\t\tSome(height) => (height, \"from wallet\"),\n\n\t\t\t\tNone => (0, \"node/wallet unavailable\"),\n\n\t\t\t},\n\n\t\t};\n\n\t\tlet mut unspent_total = 0;\n\n\t\tlet mut unspent_but_locked_total = 0;\n\n\t\tlet mut unconfirmed_total = 0;\n\n\t\tlet mut locked_total = 0;\n\n\t\tfor out in wallet_data\n\n\t\t\t.outputs\n\n\t\t\t.values()\n\n\t\t\t.filter(|out| out.root_key_id == keychain.root_key_id())\n\n\t\t{\n", "file_path": "wallet/src/info.rs", "rank": 86, "score": 111310.74327213386 }, { "content": "/// Validates the proof of work of a given header, and that the proof of work\n\n/// satisfies the requirements of the header.\n\npub fn verify_size(bh: &BlockHeader, cuckoo_sz: u32) -> bool {\n\n\tCuckoo::new(&bh.pre_pow_hash()[..], cuckoo_sz)\n\n\t\t.verify(bh.pow.clone(), consensus::EASINESS as u64)\n\n}\n\n\n", "file_path": "pow/src/lib.rs", "rank": 87, "score": 111310.74327213386 }, { "content": "/// Start listening on the provided connection and wraps it. Does not hang\n\n/// the current thread, instead just returns a future and the Connection\n\n/// itself.\n\npub fn listen<H>(stream: TcpStream, handler: H) -> Tracker\n\nwhere\n\n\tH: MessageHandler,\n\n{\n\n\tlet (send_tx, send_rx) = mpsc::sync_channel(10);\n\n\tlet (close_tx, close_rx) = mpsc::channel();\n\n\tlet (error_tx, error_rx) = mpsc::channel();\n\n\n\n\tstream\n\n\t\t.set_nonblocking(true)\n\n\t\t.expect(\"Non-blocking IO not available.\");\n\n\tpoll(stream, handler, send_rx, error_tx, close_rx);\n\n\n\n\tTracker {\n\n\t\tsent_bytes: Arc::new(Mutex::new(0)),\n\n\t\treceived_bytes: Arc::new(Mutex::new(0)),\n\n\t\tsend_channel: send_tx,\n\n\t\tclose_channel: close_tx,\n\n\t\terror_channel: error_rx,\n\n\t}\n\n}\n\n\n", "file_path": "p2p/src/conn.rs", "rank": 88, "score": 110726.33705653617 }, { "content": "pub fn restore(config: &WalletConfig, keychain: &Keychain) -> Result<(), Error> {\n\n\t// Don't proceed if wallet.dat has anything in it\n\n\tlet is_empty = WalletData::read_wallet(&config.data_file_dir, |wallet_data| {\n\n\t\tOk(wallet_data.outputs.len() == 0)\n\n\t}).context(ErrorKind::WalletData(\"could not read wallet\"))?;\n\n\tif !is_empty {\n\n\t\terror!(\n\n\t\t\tLOGGER,\n\n\t\t\t\"Not restoring. Please back up and remove existing wallet.dat first.\"\n\n\t\t);\n\n\t\treturn Ok(());\n\n\t}\n\n\n\n\tinfo!(LOGGER, \"Starting restore.\");\n\n\n\n\tlet batch_size = 1000;\n\n\tlet mut start_index = 1;\n\n\t// this will start here, then lower as outputs are found, moving backwards on\n\n\t// the chain\n\n\tloop {\n", "file_path": "wallet/src/restore.rs", "rank": 89, "score": 110726.33705653617 }, { "content": "/// Aggregate a vec of transactions into a multi-kernel transaction\n\npub fn aggregate(transactions: Vec<Transaction>) -> Result<Transaction, Error> {\n\n\tlet mut inputs: Vec<Input> = vec![];\n\n\tlet mut outputs: Vec<Output> = vec![];\n\n\tlet mut kernels: Vec<TxKernel> = vec![];\n\n\n\n\t// we will sum these together at the end to give us the overall offset for the\n\n\t// transaction\n\n\tlet mut kernel_offsets = vec![];\n\n\n\n\tfor mut transaction in transactions {\n\n\t\t// we will summ these later to give a single aggregate offset\n\n\t\tkernel_offsets.push(transaction.offset);\n\n\n\n\t\tinputs.append(&mut transaction.inputs);\n\n\t\toutputs.append(&mut transaction.outputs);\n\n\t\tkernels.append(&mut transaction.kernels);\n\n\t}\n\n\n\n\t// now sum the kernel_offsets up to give us an aggregate offset for the\n\n\t// transaction\n", "file_path": "core/src/core/transaction.rs", "rank": 90, "score": 110726.33705653617 }, { "content": "fn peer_key(peer_addr: SocketAddr) -> Vec<u8> {\n\n\tto_key(\n\n\t\tPEER_PREFIX,\n\n\t\t&mut format!(\"{}:{}\", peer_addr.ip(), peer_addr.port()).into_bytes(),\n\n\t)\n\n}\n", "file_path": "p2p/src/store.rs", "rank": 91, "score": 109119.8883992836 }, { "content": "/// Helper function to easily issue a HTTP POST request with the provided JSON\n\n/// object as body on a given URL that returns a JSON object. Handles request\n\n/// building, JSON serialization and deserialization, and response code\n\n/// checking.\n\npub fn post<'a, IN>(url: &'a str, input: &IN) -> Result<(), Error>\n\nwhere\n\n\tIN: Serialize,\n\n{\n\n\tlet in_json = serde_json::to_string(input).context(ErrorKind::Internal(\n\n\t\t\"Could not serialize data to JSON\".to_owned(),\n\n\t))?;\n\n\tlet client = hyper::Client::new();\n\n\tlet _res = check_error(client.post(url).body(&mut in_json.as_bytes()).send())?;\n\n\tOk(())\n\n}\n\n\n", "file_path": "api/src/client.rs", "rank": 92, "score": 108911.89571838442 }, { "content": "/// Decompress a source file into the provided destination path.\n\npub fn decompress<R>(src_file: R, dest: &Path) -> ZipResult<()>\n\nwhere\n\n\tR: io::Read + io::Seek,\n\n{\n\n\tlet mut archive = zip_rs::ZipArchive::new(src_file)?;\n\n\n\n\tfor i in 0..archive.len() {\n\n\t\tlet mut file = archive.by_index(i)?;\n\n\t\tlet file_path = dest.join(file.name());\n\n\n\n\t\tif (&*file.name()).ends_with('/') {\n\n\t\t\tfs::create_dir_all(&file_path)?;\n\n\t\t} else {\n\n\t\t\tif let Some(p) = file_path.parent() {\n\n\t\t\t\tif !p.exists() {\n\n\t\t\t\t\tfs::create_dir_all(&p)?;\n\n\t\t\t\t}\n\n\t\t\t}\n\n\t\t\tlet mut outfile = fs::File::create(&file_path)?;\n\n\t\t\tio::copy(&mut file, &mut outfile)?;\n", "file_path": "util/src/zip.rs", "rank": 93, "score": 108895.0275942689 }, { "content": "/// Adds an output with the provided value and key identifier from the\n\n/// keychain.\n\npub fn output(value: u64, key_id: Identifier) -> Box<Append> {\n\n\tBox::new(\n\n\t\tmove |build, (tx, kern, sum)| -> (Transaction, TxKernel, BlindSum) {\n\n\t\t\tdebug!(LOGGER, \"Building an output: {}, {}\", value, key_id,);\n\n\n\n\t\t\tlet commit = build.keychain.commit(value, &key_id).unwrap();\n\n\t\t\ttrace!(LOGGER, \"Builder - Pedersen Commit is: {:?}\", commit,);\n\n\n\n\t\t\tlet msg = ProofMessageElements::new(value, &key_id);\n\n\n\n\t\t\tlet rproof = build\n\n\t\t\t\t.keychain\n\n\t\t\t\t.range_proof(value, &key_id, commit, None, msg.to_proof_message())\n\n\t\t\t\t.unwrap();\n\n\n\n\t\t\t(\n\n\t\t\t\ttx.with_output(Output {\n\n\t\t\t\t\tfeatures: OutputFeatures::DEFAULT_OUTPUT,\n\n\t\t\t\t\tcommit: commit,\n\n\t\t\t\t\tproof: rproof,\n\n\t\t\t\t}),\n\n\t\t\t\tkern,\n\n\t\t\t\tsum.add_key_id(key_id.clone()),\n\n\t\t\t)\n\n\t\t},\n\n\t)\n\n}\n\n\n", "file_path": "core/src/core/build.rs", "rank": 94, "score": 108895.0275942689 }, { "content": "pub fn refresh_outputs(config: &WalletConfig, keychain: &Keychain) -> Result<(), Error> {\n\n\trefresh_output_state(config, keychain)?;\n\n\trefresh_missing_block_hashes(config, keychain)?;\n\n\tOk(())\n\n}\n\n\n", "file_path": "wallet/src/checker.rs", "rank": 95, "score": 108895.0275942689 }, { "content": "/// Adds an input with the provided value and blinding key to the transaction\n\n/// being built.\n\npub fn input(value: u64, key_id: Identifier) -> Box<Append> {\n\n\tdebug!(\n\n\t\tLOGGER,\n\n\t\t\"Building input (spending regular output): {}, {}\", value, key_id\n\n\t);\n\n\tbuild_input(value, OutputFeatures::DEFAULT_OUTPUT, None, None, key_id)\n\n}\n\n\n", "file_path": "core/src/core/build.rs", "rank": 96, "score": 108895.0275942689 }, { "content": "/// Helper function to easily issue a HTTP GET request against a given URL that\n\n/// returns a JSON object. Handles request building, JSON deserialization and\n\n/// response code checking.\n\npub fn get<'a, T>(url: &'a str) -> Result<T, Error>\n\nwhere\n\n\tfor<'de> T: Deserialize<'de>,\n\n{\n\n\tlet client = hyper::Client::new();\n\n\tlet res = check_error(client.get(url).send())?;\n\n\tserde_json::from_reader(res).map_err(|e| {\n\n\t\te.context(ErrorKind::Internal(\n\n\t\t\t\"Server returned invalid JSON\".to_owned(),\n\n\t\t)).into()\n\n\t})\n\n}\n\n\n", "file_path": "api/src/client.rs", "rank": 97, "score": 108598.09971968402 }, { "content": "/// Build a db key from a prefix and a numeric identifier.\n\npub fn u64_to_key<'a>(prefix: u8, val: u64) -> Vec<u8> {\n\n\tlet mut u64_vec = vec![];\n\n\tu64_vec.write_u64::<BigEndian>(val).unwrap();\n\n\tu64_vec.insert(0, SEP);\n\n\tu64_vec.insert(0, prefix);\n\n\tu64_vec\n\n}\n\n\n", "file_path": "store/src/lib.rs", "rank": 98, "score": 108583.49149164913 }, { "content": "pub fn amount_from_hr_string(amount: &str) -> Result<u64, ParseFloatError> {\n\n\tlet amount = amount.parse::<f64>()?;\n\n\tOk((amount * GRIN_BASE as f64) as u64)\n\n}\n\n\n\n/// Common method for converting an amount to a human-readable string\n\n\n", "file_path": "core/src/core/mod.rs", "rank": 99, "score": 107911.33885058097 } ]
Rust
contract/src/lib.rs
Kouprin/contracts-one
8b49f210c379227596a575a141aca7adf282c856
use regex::Regex; use std::cmp::min; use std::convert::TryInto; mod audit; mod certificate; mod contract; mod primitives; mod project; mod user; mod version; pub use crate::audit::*; pub use crate::certificate::*; pub use crate::contract::*; pub use crate::primitives::*; pub use crate::project::*; pub use crate::user::*; pub use crate::version::*; use near_sdk::borsh::{self, BorshDeserialize, BorshSerialize}; use near_sdk::collections::{LookupMap, LookupSet, TreeMap, UnorderedMap, UnorderedSet}; use near_sdk::json_types::{Base58CryptoHash, ValidAccountId, WrappedTimestamp}; use near_sdk::serde::{Deserialize, Serialize}; use near_sdk::{env, near_bindgen, AccountId, Balance, CryptoHash, PanicOnDefault, Timestamp}; near_sdk::setup_alloc!(); #[near_bindgen] #[derive(BorshDeserialize, BorshSerialize, PanicOnDefault)] pub struct Main { pub projects: UnorderedMap<ProjectId, Project>, pub contracts: TreeMap<ContractHash, Contract>, } #[near_bindgen] impl Main { #[init] pub fn new() -> Self { assert!(!env::state_exists(), "Already initialized"); let mut main = Self { projects: UnorderedMap::new(b"a".to_vec()), contracts: TreeMap::new(b"b".to_vec()), }; let mut user = main.extract_user_or_create(&env::signer_account_id()); user.is_council = true; main.save_user_or_panic(&env::signer_account_id(), &user); assert!(Self::council().insert(&env::signer_account_id())); main } } impl Main { pub(crate) fn users() -> LookupMap<UserId, User> { LookupMap::new(b"c".to_vec()) } pub(crate) fn audits() -> LookupMap<AuditId, Audit> { LookupMap::new(b"d".to_vec()) } pub(crate) fn council() -> LookupSet<UserId> { LookupSet::new(b"e".to_vec()) } pub(crate) fn is_council() -> bool { Self::council().contains(&env::predecessor_account_id()) } pub(crate) fn assert_deposit(required_deposit: Balance) { assert!( env::attached_deposit() >= required_deposit, "{}: required {}, received {}", ERR_DEPOSIT_NOT_ENOUGH, required_deposit, env::attached_deposit() ) } pub(crate) fn assert_one_yocto() { assert_eq!(env::attached_deposit(), 1, "Must be 1 yocto") } pub(crate) fn assert_council() { assert!( Self::is_council(), "{}: account {}", ERR_COUNCIL, env::predecessor_account_id() ) } pub(crate) fn assert_text_len(text: &String) { assert!( text.len() < MAX_TEXT_LENGTH, "{}: length of {} is {}, max allowed length is {}", ERR_TEXT_TOO_LONG, text, text.len(), MAX_TEXT_LENGTH, ) } pub(crate) fn assert_vec_len<T>(vec: &Vec<T>) { assert!( vec.len() < MAX_VEC_LENGTH, "{}: length of vector is {}, max allowed length is {}", ERR_VEC_TOO_LONG, vec.len(), MAX_VEC_LENGTH, ) } pub(crate) fn assert_council_or_project_owner(&self, project_name: &String) { assert!( Self::is_council() || self .projects .get(&Project::get_id(project_name)) .unwrap() .owners .contains(&env::predecessor_account_id()), "{}: account {}", ERR_COUNCIL_OR_PROJECT_OWNER, env::predecessor_account_id() ) } }
use regex::Regex; use std::cmp::min; use std::convert::TryInto; mod audit; mod certificate; mod contract; mod primitives; mod project; mod user; mod version; pub use crate::audit::*; pub use crate::certificate::*; pub use crate::contract::*; pub use crate::primitives::*; pub use crate::project::*; pub use crate::user::*; pub use crate::version::*; use near_sdk::borsh::{self, BorshDeserialize, BorshSerialize}; use near_sdk::collections::{LookupMap, LookupSet, TreeMap, UnorderedMap, UnorderedSet}; use near_sdk::json_types::{Base58CryptoHash, ValidAccountId, WrappedTimestamp}; use near_sdk::serde::{Deserialize, Serialize}; use near_sdk::{env, near_bindgen, AccountId, Balance, CryptoHash, PanicOnDefault, Timestamp}; near_sdk::setup_alloc!(); #[near_bindgen] #[derive(BorshDeserialize, BorshSerialize, PanicOnDefault)] pub struct Main { pub projects: UnorderedMap<ProjectId, Project>, pub contracts: TreeMap<ContractHash, Contract>, } #[near_bindgen] impl Main { #[init]
} impl Main { pub(crate) fn users() -> LookupMap<UserId, User> { LookupMap::new(b"c".to_vec()) } pub(crate) fn audits() -> LookupMap<AuditId, Audit> { LookupMap::new(b"d".to_vec()) } pub(crate) fn council() -> LookupSet<UserId> { LookupSet::new(b"e".to_vec()) } pub(crate) fn is_council() -> bool { Self::council().contains(&env::predecessor_account_id()) } pub(crate) fn assert_deposit(required_deposit: Balance) { assert!( env::attached_deposit() >= required_deposit, "{}: required {}, received {}", ERR_DEPOSIT_NOT_ENOUGH, required_deposit, env::attached_deposit() ) } pub(crate) fn assert_one_yocto() { assert_eq!(env::attached_deposit(), 1, "Must be 1 yocto") } pub(crate) fn assert_council() { assert!( Self::is_council(), "{}: account {}", ERR_COUNCIL, env::predecessor_account_id() ) } pub(crate) fn assert_text_len(text: &String) { assert!( text.len() < MAX_TEXT_LENGTH, "{}: length of {} is {}, max allowed length is {}", ERR_TEXT_TOO_LONG, text, text.len(), MAX_TEXT_LENGTH, ) } pub(crate) fn assert_vec_len<T>(vec: &Vec<T>) { assert!( vec.len() < MAX_VEC_LENGTH, "{}: length of vector is {}, max allowed length is {}", ERR_VEC_TOO_LONG, vec.len(), MAX_VEC_LENGTH, ) } pub(crate) fn assert_council_or_project_owner(&self, project_name: &String) { assert!( Self::is_council() || self .projects .get(&Project::get_id(project_name)) .unwrap() .owners .contains(&env::predecessor_account_id()), "{}: account {}", ERR_COUNCIL_OR_PROJECT_OWNER, env::predecessor_account_id() ) } }
pub fn new() -> Self { assert!(!env::state_exists(), "Already initialized"); let mut main = Self { projects: UnorderedMap::new(b"a".to_vec()), contracts: TreeMap::new(b"b".to_vec()), }; let mut user = main.extract_user_or_create(&env::signer_account_id()); user.is_council = true; main.save_user_or_panic(&env::signer_account_id(), &user); assert!(Self::council().insert(&env::signer_account_id())); main }
function_block-full_function
[ { "content": "#[test]\n\nfn register_project_by_not_a_user() {\n\n let mut state = State::new();\n\n state.create_alice();\n\n\n\n let contract = &state.contract;\n\n let alice = state.accounts.get(ALICE).unwrap();\n\n let outcome = call!(\n\n alice,\n\n contract.register_project(\n\n DEFAULT_PROJECT_ID.to_string(),\n\n \"bla\".to_string(),\n\n DEFAULT_URL.to_string(),\n\n DEFAULT_PROJECT_OWNERS\n\n .iter()\n\n .map(|o| o.to_string().try_into().unwrap())\n\n .collect()\n\n ),\n\n deposit = REGISTER_PROJECT_DEPOSIT\n\n );\n\n outcome.assert_success();\n\n}\n\n\n", "file_path": "contract/tests/general.rs", "rank": 0, "score": 49908.57994581161 }, { "content": "struct State {\n\n pub root: UserAccount,\n\n pub contract: ContractAccount<MainContract>,\n\n pub accounts: HashMap<String, UserAccount>,\n\n}\n\n\n\nimpl State {\n\n pub fn new() -> Self {\n\n let root = init_simulator(None);\n\n\n\n let deployed_contract = deploy!(\n\n contract: MainContract,\n\n contract_id: CONTRACT_ID,\n\n bytes: &CONTRACT_WASM_BYTES,\n\n signer_account: root,\n\n deposit: to_yocto(\"1000000000\"),\n\n init_method: new()\n\n );\n\n let state = State {\n\n root,\n", "file_path": "contract/tests/general.rs", "rank": 1, "score": 42302.389897602276 }, { "content": "pub const SUBMIT_AUDIT_DEPOSIT: Balance = 100_000_000_000_000_000_000_000; // 0.1 NEAR\n\npub const MAX_TEXT_LENGTH: usize = 1000;\n\npub const MAX_VEC_LENGTH: usize = 16;\n\npub const PRICE_PER_BYTE: Balance = 10_000_000_000_000_000_000;\n\n\n\npub type AuditId = CryptoHash;\n\n// pub type ContractId = (ProjectId, Version); - unused\n\npub type ContractHash = CryptoHash;\n\npub type ProjectId = CryptoHash;\n\npub type Standard = String;\n\npub type Url = String;\n\npub type UserId = AccountId;\n\n\n\n#[derive(Deserialize, Serialize, Debug)]\n\n#[serde(crate = \"near_sdk::serde\")]\n\npub struct SafetyReport {\n\n pub safety_level: String,\n\n pub safety_issues: Vec<String>,\n\n}\n\n\n", "file_path": "contract/src/primitives.rs", "rank": 2, "score": 30897.7970536425 }, { "content": "use crate::*;\n\n\n\npub const ERR_DEPOSIT_NOT_ENOUGH: &str = \"Attached deposit is not enough\";\n\npub const ERR_COUNCIL: &str = \"Only council can do this operation\";\n\npub const ERR_COUNCIL_OR_PROJECT_OWNER: &str =\n\n \"Only project owner or council can do this operation\";\n\npub const ERR_PROJECT_NAME_INVALID: &str = \"Project name is invalid\";\n\npub const ERR_INVALID_REPORT_URL: &str = \"Report cannot be used more than once\";\n\npub const ERR_ALREADY_EXISTS: &str = \"Already exists\";\n\npub const ERR_ACCESS_DENIED: &str = \"Caller is not allowed to do this operation\";\n\npub const ERR_EMPTY_CERTIFICATE: &str = \"Nothing to certify\";\n\npub const ERR_PROJECT_CREATOR_IS_NOT_OWNER: &str =\n\n \"Project creator is not in list of project owners\";\n\npub const ERR_TEXT_TOO_LONG: &str = \"Text is too long\";\n\npub const ERR_VEC_TOO_LONG: &str = \"Vector is too long\";\n\npub const ERR_INVALID_SCORE: &str = \"The score is invalid\";\n\n\n\npub const REGISTER_PROJECT_DEPOSIT: Balance = 1_000_000_000_000_000_000_000_000; // 1 NEAR\n\npub const REGISTER_CONTRACT_DEPOSIT: Balance = 100_000_000_000_000_000_000_000; // 0.1 NEAR\n\npub const CREATE_USER_DEPOSIT: Balance = 10_000_000_000_000_000_000_000; // 0.01 NEAR\n", "file_path": "contract/src/primitives.rs", "rank": 3, "score": 30895.591181981617 }, { "content": "pub const SAFETY_LEVEL_CRITICAL: &str = \"Dangerous\";\n\npub const SAFETY_LEVEL_LOW: &str = \"Low\";\n\npub const SAFETY_LEVEL_MODERATE: &str = \"Moderate\";\n\npub const SAFETY_LEVEL_HIGH: &str = \"High\";\n\n\n\npub const SAFETY_REPORT_NO_SOURCE_CODE: &str = \"No source code uploaded. Don't trust.\";\n\npub const SAFETY_REPORT_NO_AUDITS: &str = \"The contract hasn't been audited.\";\n\npub const SAFETY_REPORT_NO_CERTIFICATES: &str = \"The contract hasn't been certified by NEAR council.\";\n\n\n\nimpl SafetyReport {\n\n pub fn new(safety_level_num: u64, safety_issues: Vec<&str>) -> Self {\n\n let safety_level = match safety_level_num {\n\n 1 => SAFETY_LEVEL_LOW,\n\n 2 => SAFETY_LEVEL_MODERATE,\n\n 3 => SAFETY_LEVEL_HIGH,\n\n _ => SAFETY_LEVEL_CRITICAL,\n\n }.to_string();\n\n Self {\n\n safety_level,\n\n safety_issues: safety_issues.iter().map(|&s| s.into()).collect(),\n\n }\n\n }\n\n}\n", "file_path": "contract/src/primitives.rs", "rank": 4, "score": 30892.064199404704 }, { "content": "use crate::*;\n\n\n\n#[derive(BorshDeserialize, BorshSerialize)]\n\npub struct Audit {\n\n pub publisher: UserId,\n\n\n\n pub auditor_url: Url,\n\n pub report_url: Url,\n\n pub summary: String,\n\n pub date: Timestamp,\n\n}\n\n\n\nimpl Audit {\n\n pub(crate) fn id(&self) -> AuditId {\n\n env::sha256(self.report_url.as_bytes()).try_into().unwrap()\n\n }\n\n}\n\n\n\n#[derive(Deserialize, Serialize, Debug)]\n\n#[serde(crate = \"near_sdk::serde\")]\n", "file_path": "contract/src/audit.rs", "rank": 5, "score": 30826.805723805937 }, { "content": "use regex::Regex;\n\nuse std::cmp::Ordering;\n\n\n\nuse crate::*;\n\n\n\n#[derive(BorshDeserialize, BorshSerialize, Clone)]\n\npub struct Version {\n\n pub major: u64,\n\n pub minor: u64,\n\n pub patch: u64,\n\n}\n\n\n\nimpl From<&Version> for String {\n\n fn from(v: &Version) -> Self {\n\n format!(\"{}.{}.{}\", v.major, v.minor, v.patch)\n\n }\n\n}\n\n\n\nimpl From<&String> for Version {\n\n fn from(s: &String) -> Self {\n", "file_path": "contract/src/version.rs", "rank": 6, "score": 30825.41945334406 }, { "content": " }\n\n }\n\n}\n\n\n\n#[near_bindgen]\n\nimpl Main {\n\n pub fn get_audit(&self, audit_id: AuditId) -> Option<AuditView> {\n\n Self::audits().get(&audit_id).map(|a| (&a).into())\n\n }\n\n\n\n #[payable]\n\n pub fn submit_audit(\n\n &mut self,\n\n contract_hash: Base58CryptoHash,\n\n auditor_url: String,\n\n report_url: String,\n\n summary: String,\n\n date: WrappedTimestamp,\n\n ) -> bool {\n\n Self::assert_deposit(SUBMIT_AUDIT_DEPOSIT);\n", "file_path": "contract/src/audit.rs", "rank": 7, "score": 30824.308336595903 }, { "content": "pub struct AuditView {\n\n pub audit_id: Base58CryptoHash,\n\n\n\n pub publisher: AccountId,\n\n\n\n pub auditor_url: String,\n\n pub report_url: String,\n\n pub summary: String,\n\n pub date: WrappedTimestamp,\n\n}\n\n\n\nimpl From<&Audit> for AuditView {\n\n fn from(a: &Audit) -> Self {\n\n Self {\n\n audit_id: a.id().into(),\n\n publisher: a.publisher.clone(),\n\n auditor_url: a.auditor_url.clone(),\n\n report_url: a.report_url.clone(),\n\n summary: a.summary.clone(),\n\n date: a.date.into(),\n", "file_path": "contract/src/audit.rs", "rank": 8, "score": 30821.754875564922 }, { "content": " Self::assert_text_len(&auditor_url);\n\n Self::assert_text_len(&report_url);\n\n Self::assert_text_len(&summary);\n\n let mut audits = Self::audits();\n\n let audit = Audit {\n\n publisher: env::predecessor_account_id(),\n\n auditor_url,\n\n report_url,\n\n summary,\n\n date: date.into(),\n\n };\n\n assert!(audits.insert(&audit.id(), &audit).is_none());\n\n\n\n let mut contract = self.contracts.get(&contract_hash.into()).unwrap();\n\n self.assert_council_or_project_owner(&contract.project_name);\n\n assert!(contract.audits.insert(&audit.id()));\n\n\n\n true\n\n }\n\n}\n", "file_path": "contract/src/audit.rs", "rank": 9, "score": 30820.610212430496 }, { "content": " Some(self.cmp(other))\n\n }\n\n}\n\n\n\nimpl PartialEq for Version {\n\n fn eq(&self, other: &Self) -> bool {\n\n (self.major, self.minor, self.patch) == (other.major, other.minor, other.patch)\n\n }\n\n}\n\n\n\nimpl Eq for Version {}\n", "file_path": "contract/src/version.rs", "rank": 10, "score": 30818.997001533062 }, { "content": " let re = Regex::new(r\"^([1-9]+[0-9]*{1,6}|0).([1-9]+[0-9]*{1,6}|0).([1-9]+[0-9]*{1,8}|0)$\")\n\n .unwrap();\n\n let captures = re.captures(&s).unwrap();\n\n assert_eq!(captures.len(), 4);\n\n Version {\n\n major: captures[1].parse::<u64>().unwrap(),\n\n minor: captures[2].parse::<u64>().unwrap(),\n\n patch: captures[3].parse::<u64>().unwrap(),\n\n }\n\n }\n\n}\n\n\n\nimpl Ord for Version {\n\n fn cmp(&self, other: &Self) -> Ordering {\n\n (self.major, self.minor, self.patch).cmp(&(other.major, other.minor, other.patch))\n\n }\n\n}\n\n\n\nimpl PartialOrd for Version {\n\n fn partial_cmp(&self, other: &Self) -> Option<Ordering> {\n", "file_path": "contract/src/version.rs", "rank": 11, "score": 30818.056159744407 }, { "content": "use crate::*;\n\n\n\n#[derive(BorshDeserialize, BorshSerialize)]\n\npub struct User {\n\n pub projects_owned: UnorderedSet<ProjectId>,\n\n\n\n pub is_council: bool,\n\n}\n\n\n\n#[derive(Deserialize, Serialize, Debug)]\n\n#[serde(crate = \"near_sdk::serde\")]\n\npub struct UserView {\n\n pub projects_owned: Vec<Base58CryptoHash>,\n\n\n\n pub is_council: bool,\n\n}\n\n\n\nimpl From<&User> for UserView {\n\n fn from(u: &User) -> Self {\n\n Self {\n", "file_path": "contract/src/user.rs", "rank": 12, "score": 30755.05274790468 }, { "content": " projects_owned: u.projects_owned.iter().map(|id| id.into()).collect(),\n\n is_council: u.is_council,\n\n }\n\n }\n\n}\n\n\n\n#[near_bindgen]\n\nimpl Main {\n\n pub fn get_user(&self, user_id: ValidAccountId) -> Option<UserView> {\n\n Self::users().get(user_id.as_ref()).map(|u| (&u).into())\n\n }\n\n\n\n #[payable]\n\n pub fn create_user(&mut self, user_id: ValidAccountId) -> bool {\n\n Self::assert_deposit(CREATE_USER_DEPOSIT);\n\n assert!(\n\n Self::users().get(user_id.as_ref()).is_none(),\n\n \"{}\",\n\n ERR_ALREADY_EXISTS\n\n );\n", "file_path": "contract/src/user.rs", "rank": 13, "score": 30751.370570701427 }, { "content": " let user = self.extract_user_or_create(user_id.as_ref());\n\n self.save_user_or_panic(user_id.as_ref(), &user);\n\n\n\n true\n\n }\n\n\n\n #[payable]\n\n pub fn register_council(&mut self, user_id: ValidAccountId) -> bool {\n\n Self::assert_council();\n\n Self::assert_one_yocto();\n\n let mut user = self.extract_user_or_create(user_id.as_ref());\n\n user.is_council = true;\n\n self.save_user_or_panic(user_id.as_ref(), &user);\n\n assert!(Self::council().insert(user_id.as_ref()));\n\n\n\n true\n\n }\n\n}\n\n\n\nimpl Main {\n", "file_path": "contract/src/user.rs", "rank": 14, "score": 30749.333748281584 }, { "content": " pub(crate) fn extract_user_or_create(&mut self, user_id: &UserId) -> User {\n\n Self::users().remove(&user_id).unwrap_or_else(|| {\n\n let mut prefix = Vec::with_capacity(33);\n\n prefix.push(b'u');\n\n prefix.extend(env::sha256(&user_id.as_bytes()));\n\n\n\n User {\n\n projects_owned: UnorderedSet::new(prefix),\n\n is_council: false,\n\n }\n\n })\n\n }\n\n\n\n pub(crate) fn save_user_or_panic(&mut self, user_id: &UserId, user: &User) {\n\n assert!(Self::users().insert(user_id, user).is_none());\n\n }\n\n}\n", "file_path": "contract/src/user.rs", "rank": 15, "score": 30748.38056299316 }, { "content": "use crate::*;\n\n\n\n#[derive(BorshDeserialize, BorshSerialize)]\n\npub struct Certificate {\n\n pub issuer: UserId,\n\n pub issue_time: Timestamp,\n\n\n\n pub is_hash_valid: Option<bool>,\n\n pub is_audit_accepted: Option<bool>,\n\n pub is_code_approved: Option<bool>,\n\n pub is_standards_confirmed: Option<bool>,\n\n\n\n pub details: String,\n\n}\n\n\n\n#[derive(Deserialize, Serialize, Debug)]\n\n#[serde(crate = \"near_sdk::serde\")]\n\npub struct CertificateView {\n\n pub issuer: AccountId,\n\n pub issue_time: WrappedTimestamp,\n", "file_path": "contract/src/certificate.rs", "rank": 16, "score": 30683.34508533761 }, { "content": "\n\n pub is_hash_valid: Option<bool>,\n\n pub is_audit_accepted: Option<bool>,\n\n pub is_code_approved: Option<bool>,\n\n pub is_standards_confirmed: Option<bool>,\n\n\n\n pub details: String,\n\n}\n\n\n\nimpl From<&Certificate> for CertificateView {\n\n fn from(c: &Certificate) -> Self {\n\n Self {\n\n issuer: c.issuer.clone(),\n\n issue_time: c.issue_time.into(),\n\n is_hash_valid: c.is_hash_valid,\n\n is_audit_accepted: c.is_audit_accepted,\n\n is_code_approved: c.is_code_approved,\n\n is_standards_confirmed: c.is_standards_confirmed,\n\n details: c.details.clone(),\n\n }\n", "file_path": "contract/src/certificate.rs", "rank": 17, "score": 30679.096632979425 }, { "content": " && is_code_approved.is_none()\n\n && is_standards_confirmed.is_none()\n\n && details.len() == 0\n\n {\n\n // Empty certificate\n\n assert!(false, \"{}\", ERR_EMPTY_CERTIFICATE);\n\n }\n\n\n\n let mut contract = self.contracts.get(&contract_hash.into()).unwrap();\n\n contract.certificates.insert(&Certificate {\n\n issuer: env::predecessor_account_id(),\n\n issue_time: env::block_timestamp(),\n\n is_hash_valid,\n\n is_audit_accepted,\n\n is_code_approved,\n\n is_standards_confirmed,\n\n details,\n\n });\n\n self.contracts.insert(&contract_hash.into(), &contract);\n\n\n\n true\n\n }\n\n}\n", "file_path": "contract/src/certificate.rs", "rank": 18, "score": 30678.91342427846 }, { "content": " }\n\n}\n\n\n\n#[near_bindgen]\n\nimpl Main {\n\n #[payable]\n\n pub fn certify_contract(\n\n &mut self,\n\n contract_hash: Base58CryptoHash,\n\n is_hash_valid: Option<bool>,\n\n is_audit_accepted: Option<bool>,\n\n is_code_approved: Option<bool>,\n\n is_standards_confirmed: Option<bool>,\n\n details: String,\n\n ) -> bool {\n\n Self::assert_one_yocto();\n\n Self::assert_council();\n\n Self::assert_text_len(&details);\n\n if is_hash_valid.is_none()\n\n && is_audit_accepted.is_none()\n", "file_path": "contract/src/certificate.rs", "rank": 19, "score": 30678.53505087504 }, { "content": " pub url: String,\n\n\n\n pub owners: Vec<AccountId>,\n\n\n\n pub contracts: Vec<ContractView>,\n\n\n\n pub last_version: Option<String>,\n\n}\n\n\n\nimpl From<(&Project, &Main)> for ProjectView {\n\n fn from(p: (&Project, &Main)) -> Self {\n\n Self {\n\n project_id: Project::get_id(&p.0.project_name).into(),\n\n project_name: p.0.project_name.clone(),\n\n description: p.0.description.clone(),\n\n url: p.0.url.clone(),\n\n owners: p.0.owners.to_vec(),\n\n contracts: p\n\n .0\n\n .contracts\n", "file_path": "contract/src/project.rs", "rank": 20, "score": 30002.16660389389 }, { "content": "use crate::*;\n\n\n\n#[derive(BorshDeserialize, BorshSerialize)]\n\npub struct Project {\n\n pub project_name: String,\n\n pub description: String,\n\n pub url: String,\n\n\n\n pub owners: UnorderedSet<AccountId>,\n\n\n\n pub contracts: TreeMap<Version, ContractHash>,\n\n}\n\n\n\n#[derive(Deserialize, Serialize, Debug)]\n\n#[serde(crate = \"near_sdk::serde\")]\n\npub struct ProjectView {\n\n pub project_id: Base58CryptoHash,\n\n\n\n pub project_name: String,\n\n pub description: String,\n", "file_path": "contract/src/project.rs", "rank": 21, "score": 30001.485768290968 }, { "content": " ERR_ALREADY_EXISTS\n\n );\n\n\n\n true\n\n }\n\n}\n\n\n\nimpl Main {\n\n pub(crate) fn view_last_contract(&self, project: &Project) -> Option<Contract> {\n\n if project.contracts.len() == 0 {\n\n return None;\n\n }\n\n self.contracts\n\n .get(&project.contracts.iter_rev().next().map(|(_, c)| c).unwrap())\n\n }\n\n\n\n pub(crate) fn extract_project_or_panic(&mut self, project_id: &ProjectId) -> Project {\n\n self.projects.remove(project_id).unwrap()\n\n }\n\n\n", "file_path": "contract/src/project.rs", "rank": 22, "score": 30000.130431034206 }, { "content": " .iter()\n\n .map(|(_, c)| (&p.1.contracts.get(&c).unwrap()).into())\n\n .collect(),\n\n last_version: p\n\n .1\n\n .view_last_contract(p.0)\n\n .map_or(None, |c| Some((&c.version).into())),\n\n }\n\n }\n\n}\n\n\n\nimpl Project {\n\n pub(crate) fn get_id(project_name: &String) -> ProjectId {\n\n env::sha256(project_name.as_bytes())\n\n .as_slice()\n\n .try_into()\n\n .unwrap()\n\n }\n\n}\n\n\n", "file_path": "contract/src/project.rs", "rank": 23, "score": 30000.044039042852 }, { "content": "#[near_bindgen]\n\nimpl Main {\n\n pub fn get_project(&self, project_name: String) -> Option<ProjectView> {\n\n self.projects\n\n .get(&Project::get_id(&project_name))\n\n .map(|p| (&p, self).into())\n\n }\n\n\n\n pub fn get_all_projects(&self, from: u64, to: u64) -> Vec<ProjectView> {\n\n let from = min(from, self.projects.len());\n\n let to = min(to, self.projects.len());\n\n let mut res = vec![];\n\n for i in from..to {\n\n // values_as_vector() should work for O(1)\n\n res.push((&self.projects.values_as_vector().get(i).unwrap(), self).into())\n\n }\n\n res\n\n }\n\n\n\n pub fn get_project_last_contract(&self, project_name: String) -> Option<ContractView> {\n", "file_path": "contract/src/project.rs", "rank": 24, "score": 29998.901912878624 }, { "content": " Self::assert_text_len(&description);\n\n Self::assert_text_len(&url);\n\n Self::assert_vec_len(&owners);\n\n\n\n let project_id = Project::get_id(&project_name);\n\n let mut is_predecessor_found = false;\n\n for user_id in owners.iter() {\n\n if user_id.as_ref() == &env::predecessor_account_id() {\n\n is_predecessor_found = true;\n\n }\n\n let mut user = self.extract_user_or_create(user_id.as_ref());\n\n user.projects_owned.insert(&project_id);\n\n self.save_user_or_panic(user_id.as_ref(), &user);\n\n }\n\n assert!(is_predecessor_found, \"{}\", ERR_PROJECT_CREATOR_IS_NOT_OWNER);\n\n\n\n let mut prefix = Vec::with_capacity(33);\n\n prefix.push(b'x');\n\n prefix.extend(&project_id);\n\n let mut owners_set = UnorderedSet::new(prefix);\n", "file_path": "contract/src/project.rs", "rank": 25, "score": 29995.098277005793 }, { "content": " self.view_last_contract(&self.projects.get(&Project::get_id(&project_name)).unwrap())\n\n .map(|c| (&c).into())\n\n }\n\n\n\n #[payable]\n\n pub fn register_project(\n\n &mut self,\n\n project_name: String,\n\n description: String,\n\n url: String,\n\n owners: Vec<ValidAccountId>,\n\n ) -> bool {\n\n Self::assert_deposit(REGISTER_PROJECT_DEPOSIT);\n\n assert!(\n\n project_name.len() > 0 && project_name.len() <= 64,\n\n \"{}\",\n\n ERR_PROJECT_NAME_INVALID\n\n );\n\n let re = Regex::new(r\"^(([A-Z|a-z|0-9]+[\\-_\\.])*[A-Z|a-z|0-9]+)$\").unwrap();\n\n assert!(re.is_match(&project_name), \"{}\", ERR_PROJECT_NAME_INVALID);\n", "file_path": "contract/src/project.rs", "rank": 26, "score": 29994.745949690583 }, { "content": " pub(crate) fn extract_project_by_name_or_panic(&mut self, project_name: &String) -> Project {\n\n self.extract_project_or_panic(&Project::get_id(project_name))\n\n }\n\n\n\n pub(crate) fn save_project_or_panic(&mut self, project_id: &ProjectId, project: &Project) {\n\n assert!(self.projects.insert(project_id, project).is_none())\n\n }\n\n\n\n pub(crate) fn save_project_by_name_or_panic(\n\n &mut self,\n\n project_name: &String,\n\n project: &Project,\n\n ) {\n\n self.save_project_or_panic(&Project::get_id(project_name), project)\n\n }\n\n}\n", "file_path": "contract/src/project.rs", "rank": 27, "score": 29994.738108699978 }, { "content": " owners_set.extend(owners.into_iter().map(|o| o.into()));\n\n\n\n let mut prefix2 = Vec::with_capacity(33);\n\n prefix2.push(b'y');\n\n prefix2.extend(&project_id);\n\n\n\n assert!(\n\n self.projects\n\n .insert(\n\n &project_id,\n\n &Project {\n\n project_name,\n\n description,\n\n url,\n\n owners: owners_set,\n\n contracts: TreeMap::new(prefix2),\n\n }\n\n )\n\n .is_none(),\n\n \"{}\",\n", "file_path": "contract/src/project.rs", "rank": 28, "score": 29993.856156327183 }, { "content": "#[test]\n\nfn init_sanity() {\n\n let mut state = State::new();\n\n state.create_alice();\n\n\n\n state.validate();\n\n}\n\n\n", "file_path": "contract/tests/general.rs", "rank": 29, "score": 28427.653490655524 }, { "content": "#[test]\n\nfn version_sanity() {\n\n let mut state = State::new();\n\n state.create_alice();\n\n\n\n state.do_register_project(DEFAULT_PROJECT_ID, DEFAULT_PROJECT_OWNERS, None);\n\n state.do_register_contract(\n\n ALICE,\n\n DEFAULT_PROJECT_ID,\n\n DEFAULT_CONTRACT_HASH,\n\n \"0.0.0\",\n\n None,\n\n );\n\n state.do_register_contract(ALICE, DEFAULT_PROJECT_ID, &\"1\".repeat(32), \"0.0.1\", None);\n\n // TODO random hashes\n\n}\n\n\n", "file_path": "contract/tests/general.rs", "rank": 30, "score": 28296.002703516195 }, { "content": "#[test]\n\nfn project_names() {\n\n let state = State::new();\n\n\n\n state.do_register_project(\"test\", DEFAULT_PROJECT_OWNERS, None);\n\n state.do_register_project(\"Test_Project.123\", DEFAULT_PROJECT_OWNERS, None);\n\n state.do_register_project(\n\n \"Test_Project.123 \",\n\n DEFAULT_PROJECT_OWNERS,\n\n Some(ERR_PROJECT_NAME_INVALID),\n\n );\n\n state.do_register_project(\"\", DEFAULT_PROJECT_OWNERS, Some(ERR_PROJECT_NAME_INVALID));\n\n state.do_register_project(\"0\", DEFAULT_PROJECT_OWNERS, None);\n\n state.do_register_project(\"a\", DEFAULT_PROJECT_OWNERS, None);\n\n state.do_register_project(\"#\", DEFAULT_PROJECT_OWNERS, Some(ERR_PROJECT_NAME_INVALID));\n\n state.do_register_project(\"_\", DEFAULT_PROJECT_OWNERS, Some(ERR_PROJECT_NAME_INVALID));\n\n state.do_register_project(&\"1\".repeat(64), DEFAULT_PROJECT_OWNERS, None);\n\n state.do_register_project(\n\n &\"1\".repeat(65),\n\n DEFAULT_PROJECT_OWNERS,\n\n Some(ERR_PROJECT_NAME_INVALID),\n\n );\n\n\n\n state.validate();\n\n}\n\n\n", "file_path": "contract/tests/general.rs", "rank": 31, "score": 27539.552334649983 }, { "content": " async _initNear () {\n\n const keyStore = new nearAPI.keyStores.BrowserLocalStorageKeyStore()\n\n const near = await nearAPI.connect(Object.assign({ deps: { keyStore } }, NearConfig))\n\n this._near.keyStore = keyStore\n\n this._near.near = near\n\n\n\n this._near.walletConnection = new nearAPI.WalletConnection(near, NearConfig.contractName)\n\n this._near.accountId = this._near.walletConnection.getAccountId()\n\n\n\n this._near.account = this._near.walletConnection.account()\n\n this._near.contract = new nearAPI.Contract(this._near.account, NearConfig.contractName, {\n\n viewMethods: [\n\n 'get_user',\n\n 'get_project',\n\n 'get_all_projects',\n\n 'get_project_last_contract',\n\n 'get_contract',\n\n 'get_contract_source_code',\n\n 'get_audit'\n\n ],\n\n changeMethods: [\n\n 'create_user',\n\n 'register_project',\n\n 'register_contract',\n\n 'register_council',\n\n 'submit_audit',\n\n 'certify_contract'\n\n ]\n\n })\n\n\n\n this._near.logOut = () => {\n\n this._near.walletConnection.signOut()\n\n this._near.accountId = null\n\n this.setState({\n\n signedIn: !!this._accountId,\n\n signedAccountId: this._accountId\n\n })\n\n }\n\n\n\n this._near.refreshAllowance = async () => {\n\n alert(\"You're out of access key allowance. Need sign in again to refresh it\")\n\n await this.logOut()\n\n await this.requestSignIn()\n\n }\n", "file_path": "frontend/src/App.js", "rank": 32, "score": 24434.92151695483 }, { "content": "const mapProject = (c) => {\n\n return c ? {\n\n id: c.project_id,\n\n name: c.project_name,\n\n url: c.url,\n\n contracts: c.contracts,\n\n description: c.description,\n\n lastVersion: c.last_version,\n\n owners: c.owners\n\n } : null\n", "file_path": "frontend/src/components/Helpers.js", "rank": 33, "score": 22868.569947817596 }, { "content": "const mapCertificateView = (c) => {\n\n return c ? {\n\n projectName: c.project_name,\n\n version: c.version,\n\n author: c.author,\n\n reportUrl: c.report_url,\n\n summary: c.summary,\n\n standardsConfirmed: c.standards_confirmed,\n\n basicValidityPassed: c.basic_validity_passed,\n\n contractApproved: c.contract_approved,\n\n score: c.score\n\n } : null\n", "file_path": "frontend/src/components/Helpers.js", "rank": 34, "score": 22620.35349415526 }, { "content": "const mapProjectView = (c) => {\n\n return c ? {\n\n id: c.project_id,\n\n name: c.project_name,\n\n description: c.description,\n\n url: c.url,\n\n owners: c.owners,\n\n contracts: c.contracts,\n\n lastVersion: c.last_version\n\n } : null\n", "file_path": "frontend/src/components/Helpers.js", "rank": 35, "score": 22118.2740303849 }, { "content": "import React from 'react'\n\n\n\nimport { ProfileLink, ProjectLink } from '../components/Links'\n\nimport { mapCertificateView } from '../components/Helpers'\n\n\n\nfunction CertificateCard (props) {\n\n const data = props.data\n\n const certificate = mapCertificateView(data)\n\n const standards = certificate.standardsConfirmed.map((data, index) => {\n\n return (\n\n <div key={index} className='badge bg-success mx-1'>\n\n {data}\n\n </div>\n\n )\n\n })\n\n return (\n\n <div className='card mb-3 bg-gray' style={{ width: '100%' }}>\n\n <div className='card-body'>\n\n <div className='d-flex flex-row'>\n\n <h5 className='card-title pe-3'>Certificated <ProjectLink projectName={certificate.projectName} /></h5>\n\n <div className='card-title gray pe-3'>version {certificate.version}</div>\n\n <div className='card-title gray pe-3'>by <ProfileLink userName={certificate.author} /></div>\n\n <div className='me-auto card-title'>{standards}</div>\n\n <big className='pe-3 card-title'><small className='gray'>score:</small> {certificate.score}</big>\n\n <big className='pe-3 card-title'><small className='gray'>basic validity:</small> {certificate.basicValidityPassed ? 'passed' : 'failed'}</big>\n\n <big className='card-title'><small className='gray'>audit verdict:</small> {certificate.contractApproved ? 'approved' : 'refused'}</big>\n\n </div>\n\n <div className='d-flex flex-row card-text'>\n\n <div className='w-75'>\n\n <div className='card-text gray'>{certificate.summary}</div>\n\n </div>\n\n <div className='ms-auto'>\n\n <a href={'//' + certificate.reportUrl} className='btn btn-secondary'>Go to report</a>\n\n </div>\n\n </div>\n\n </div>\n\n </div>\n\n )\n\n}\n\n\n\nexport { CertificateCard }\n", "file_path": "frontend/src/components/CertificateCard.js", "rank": 36, "score": 18899.83950055806 }, { "content": "import React from 'react'\n\nimport { useParams } from 'react-router'\n\nimport { Link } from 'react-router-dom'\n\nimport useSWR from 'swr'\n\nimport Moment from 'react-moment'\n\n\n\nimport { mapProject, loader } from '../components/Helpers'\n\n\n\nfunction ProjectInfoPage (props) {\n\n const { projectName } = useParams()\n\n\n\n const fetchProject = async (...args) => {\n\n return mapProject(await props._near.contract.get_project({ project_name: args[1] }))\n\n }\n\n\n\n const { data: project } = useSWR(['project', projectName], fetchProject, { errorRetryInterval: 500 })\n\n\n\n const owners = project && project.owners.map((data, index) => {\n\n return (\n\n <div key={index} className='container g-0'>\n\n <div>\n\n <Link to={`/profileProjects/${data}`}>{data}</Link>\n\n </div>\n\n </div>\n\n )\n\n })\n\n\n\n const versions = project && project.contracts.map((data, index) => {\n\n return (\n\n <div key={index} className='container g-0'>\n\n <div key={index} className='row'>\n\n <div className='col-1'>\n\n <Link to={`/contract/${data.hash}`}>{data.version}</Link>\n\n </div>\n\n <div className='col-4'>\n\n <samp className='small'><Link to={`/contract/${data.hash}`}>{data.hash}</Link></samp>\n\n </div>\n\n <div className='col-7'>\n\n Published <Moment unix fromNow>{data.published_time / 1000000000}</Moment> by <Link to={`/profileProjects/${data.publisher}`}>{data.publisher}</Link>\n\n </div>\n\n </div>\n\n </div>\n\n )\n\n })\n\n\n\n return props.connected && project ? (\n\n <div className='pb-3'>\n\n <div className='container g-0 px-5'>\n\n <div className='d-flex flex-row bd-highlight mb-3'>\n\n <div className='py-2 bd-highlight'>\n\n <h5>Project</h5>\n\n </div>\n\n <div className='p-2 bd-highlight' />\n\n <div className='p-2 bd-highlight'>\n\n <h5 className='gray'>{project.name}</h5>\n\n </div>\n\n </div>\n\n <div className='mb-3 py-2'>\n\n <h4>Description</h4>\n\n <div>{project.description}</div>\n\n </div>\n\n <hr />\n\n <div className='mb-3 py-2'>\n\n <h4>Known versions</h4>\n\n <div>{versions}</div>\n\n </div>\n\n <hr />\n\n <div className='mb-3 py-2'>\n\n <h4>Owners</h4>\n\n <div>{owners}</div>\n\n </div>\n\n </div>\n\n </div>\n\n ) : loader()\n\n}\n\n\n\nexport default ProjectInfoPage\n", "file_path": "frontend/src/pages/ProjectInfo.js", "rank": 37, "score": 18480.340252492024 }, { "content": "import React from 'react'\n\nimport { Link } from 'react-router-dom'\n\n\n\nimport { ContractLink, ProfileLink, ProjectLink } from './Links'\n\nimport { mapProjectView } from './Helpers'\n\n\n\nfunction ProjectCard (props) {\n\n const data = props.data\n\n const project = mapProjectView(data)\n\n let lastContract = null\n\n if (project.contracts) {\n\n project.contracts.forEach(element => {\n\n if (element.version === project.lastVersion) {\n\n lastContract = element\n\n }\n\n })\n\n }\n\n return (\n\n <div className='card mb-3 bg-gray' style={{ width: '100%' }}>\n\n <div className='card-body'>\n\n <div className='card-title d-flex flex-row'>\n\n <h5 className='pe-3'>Project <ProjectLink projectName={project.name} /></h5>\n\n {lastContract &&\n\n <div className='gray pe-3'><big>{project.contracts.length}</big> contract(s)</div>}\n\n {lastContract &&\n\n <div className='gray pe-3'>last version <ContractLink contractHash={lastContract.hash} version={project.lastVersion} /></div>}\n\n {lastContract &&\n\n <div className='gray'>by <ProfileLink userName={lastContract.publisher} /></div>}\n\n {/* lastContract &&\n\n <div className='ms-auto badge bg-success mt-1 mb-2'>test</div> */}\n\n </div>\n\n <div className='d-flex flex-row card-text'>\n\n <div className='flex-grow-1 d-flex flex-row'>\n\n <div className='card-text gray'>{project.description}</div>\n\n </div>\n\n {lastContract &&\n\n <div className='ms-3 align-bottom '>\n\n <Link to={'/contract/' + lastContract.hash} className='btn btn-primary'>Last deployed contract</Link>\n\n </div>}\n\n <div className='ms-3 align-bottom '>\n\n <Link to={'/projectInfo/' + project.name} className='btn btn-secondary'>Project details</Link>\n\n </div>\n\n </div>\n\n </div>\n\n </div>\n\n )\n\n}\n\n\n\nexport { ProjectCard }\n", "file_path": "frontend/src/components/ProjectCard.js", "rank": 38, "score": 18480.340252492024 }, { "content": " pub source_code_size: u64,\n\n pub commit_hash: String,\n\n\n\n pub publisher: UserId,\n\n\n\n pub standards_declared: Vec<Standard>,\n\n\n\n pub audits: Vec<AuditId>,\n\n\n\n pub certificates: Vec<CertificateView>,\n\n\n\n pub safety_report: SafetyReport,\n\n}\n\n\n\nimpl From<&Contract> for ContractView {\n\n fn from(c: &Contract) -> Self {\n\n Self {\n\n hash: c.hash.into(),\n\n project_name: c.project_name.clone(),\n\n contract_name: c.contract_name.clone(),\n", "file_path": "contract/src/contract.rs", "rank": 39, "score": 5223.470799182521 }, { "content": "use crate::*;\n\n\n\n#[derive(BorshDeserialize, BorshSerialize)]\n\npub struct Contract {\n\n pub hash: ContractHash,\n\n\n\n pub project_name: String,\n\n pub contract_name: String,\n\n\n\n pub version: Version,\n\n pub published_time: Timestamp,\n\n\n\n // Cargo.toml + Cargo.lock + src folder?\n\n // Full marketplace contract + tests took 30k, 0.3 NEAR\n\n pub source_code_archived: Option<String>,\n\n pub commit_hash: String,\n\n\n\n pub publisher: UserId,\n\n\n\n pub standards_declared: UnorderedSet<Standard>,\n", "file_path": "contract/src/contract.rs", "rank": 40, "score": 5223.1000446737535 }, { "content": " issues.push(SAFETY_REPORT_NO_CERTIFICATES);\n\n } else {\n\n // TODO implement certificates analyses\n\n }\n\n\n\n return SafetyReport::new (safety_level , issues );\n\n }\n\n}\n\n\n\n#[derive(Deserialize, Serialize, Debug)]\n\n#[serde(crate = \"near_sdk::serde\")]\n\npub struct ContractView {\n\n pub hash: Base58CryptoHash,\n\n\n\n pub project_name: String,\n\n pub contract_name: String,\n\n\n\n pub version: String,\n\n pub published_time: WrappedTimestamp,\n\n\n", "file_path": "contract/src/contract.rs", "rank": 41, "score": 5222.085681542118 }, { "content": " version: (&c.version).into(),\n\n published_time: c.published_time.into(),\n\n source_code_size: c\n\n .source_code_archived\n\n .as_ref()\n\n .map(|s| s.len() as u64)\n\n .unwrap_or(0),\n\n commit_hash: c.commit_hash.clone(),\n\n publisher: c.publisher.clone(),\n\n standards_declared: c.standards_declared.to_vec(),\n\n audits: c.audits.to_vec(),\n\n certificates: c.certificates.iter().map(|c| (&c).into()).collect(),\n\n safety_report: c.get_safety_report()\n\n }\n\n }\n\n}\n\n\n\n#[near_bindgen]\n\nimpl Main {\n\n pub fn get_contract(&self, contract_hash: Base58CryptoHash) -> Option<ContractView> {\n", "file_path": "contract/src/contract.rs", "rank": 42, "score": 5221.557064997896 }, { "content": " prefix2.extend(&ContractHash::from(contract_hash));\n\n\n\n let mut prefix3 = Vec::with_capacity(33);\n\n prefix3.push(b'm');\n\n prefix3.extend(&ContractHash::from(contract_hash));\n\n\n\n let contract = Contract {\n\n hash: contract_hash.into(),\n\n project_name: project_name.clone(),\n\n contract_name,\n\n version: version.clone(),\n\n published_time: env::block_timestamp(),\n\n source_code_archived: None,\n\n commit_hash,\n\n publisher: env::predecessor_account_id(),\n\n standards_declared: standards_declared_set,\n\n audits: UnorderedSet::new(prefix2),\n\n certificates: UnorderedSet::new(prefix3),\n\n };\n\n\n", "file_path": "contract/src/contract.rs", "rank": 43, "score": 5219.717613324139 }, { "content": "\n\n pub audits: UnorderedSet<AuditId>,\n\n\n\n pub certificates: UnorderedSet<Certificate>,\n\n}\n\n\n\nimpl Contract {\n\n pub(crate) fn get_safety_report(&self) -> SafetyReport {\n\n if self.source_code_archived.is_none() {\n\n return SafetyReport::new (0, vec![SAFETY_REPORT_NO_SOURCE_CODE]);\n\n }\n\n let mut safety_level = 3;\n\n let mut issues = vec![];\n\n if self.audits.is_empty() {\n\n safety_level = min(safety_level, 2);\n\n issues.push(SAFETY_REPORT_NO_AUDITS);\n\n }\n\n\n\n if self.certificates.is_empty() {\n\n safety_level = min(safety_level, 1);\n", "file_path": "contract/src/contract.rs", "rank": 44, "score": 5219.200952726714 }, { "content": " assert!(self\n\n .contracts\n\n .insert(&contract_hash.into(), &contract)\n\n .is_none());\n\n assert!(project\n\n .contracts\n\n .insert(&version, &contract_hash.into())\n\n .is_none());\n\n self.save_project_by_name_or_panic(&project_name, &project);\n\n\n\n true\n\n }\n\n\n\n #[payable]\n\n pub fn upload_source_code(\n\n &mut self,\n\n contract_hash: Base58CryptoHash,\n\n source_code_archived: String,\n\n ) -> bool {\n\n let mut contract = self.contracts.get(&contract_hash.into()).unwrap();\n", "file_path": "contract/src/contract.rs", "rank": 45, "score": 5217.562908943287 }, { "content": " self.contracts\n\n .get(&contract_hash.into())\n\n .map(|c| (&c).into())\n\n }\n\n\n\n pub fn get_contract_source_code(&self, contract_hash: Base58CryptoHash) -> Option<String> {\n\n self.contracts\n\n .get(&contract_hash.into())\n\n .map(|c| c.source_code_archived)\n\n .unwrap_or(None)\n\n }\n\n\n\n #[payable]\n\n pub fn register_contract(\n\n &mut self,\n\n project_name: String,\n\n contract_name: String,\n\n contract_hash: Base58CryptoHash,\n\n version: String,\n\n commit_hash: String,\n", "file_path": "contract/src/contract.rs", "rank": 46, "score": 5216.9440648505515 }, { "content": " standards_declared: Vec<Standard>,\n\n ) -> bool {\n\n Self::assert_deposit(REGISTER_CONTRACT_DEPOSIT);\n\n Self::assert_text_len(&project_name);\n\n Self::assert_text_len(&contract_name);\n\n Self::assert_text_len(&commit_hash);\n\n Self::assert_vec_len(&standards_declared);\n\n\n\n let version: Version = (&version).into(); // asserts if version is valid\n\n let mut project = self.extract_project_by_name_or_panic(&project_name);\n\n assert!(project.owners.contains(&env::predecessor_account_id()));\n\n\n\n let mut prefix = Vec::with_capacity(33);\n\n prefix.push(b'k');\n\n prefix.extend(&ContractHash::from(contract_hash));\n\n let mut standards_declared_set = UnorderedSet::new(prefix);\n\n standards_declared_set.extend(standards_declared.into_iter());\n\n\n\n let mut prefix2 = Vec::with_capacity(33);\n\n prefix2.push(b'l');\n", "file_path": "contract/src/contract.rs", "rank": 47, "score": 5215.982870236541 }, { "content": " if contract.source_code_archived.is_some() {\n\n Self::assert_council();\n\n Self::assert_one_yocto();\n\n } else {\n\n self.assert_council_or_project_owner(&contract.project_name);\n\n Self::assert_deposit(source_code_archived.len() as Balance * PRICE_PER_BYTE);\n\n }\n\n contract.source_code_archived = Some(source_code_archived);\n\n self.contracts.insert(&contract_hash.into(), &contract);\n\n\n\n true\n\n }\n\n}", "file_path": "contract/src/contract.rs", "rank": 48, "score": 5215.87094038705 }, { "content": "const mapContract = (c) => {\n\n return c ? {\n\n audits: c.audits,\n\n certificates: c.certificates,\n\n commitHash: c.commit_hash,\n\n contractName: c.contract_name,\n\n hash: c.hash,\n\n projectName: c.project_name,\n\n publishedTime: c.published_time,\n\n publisher: c.publisher,\n\n safetyLevel: c.safety_report.safety_level,\n\n safetyIssues: c.safety_report.safety_issues,\n\n sourceCodeSize: c.source_code_size,\n\n standardsDeclared: c.standards_declared,\n\n version: c.version\n\n } : null\n", "file_path": "frontend/src/components/Helpers.js", "rank": 49, "score": 4360.047682186016 }, { "content": "use std::collections::HashMap;\n\nuse std::convert::TryInto;\n\n\n\n/// Import the generated proxy contract\n\nuse contracts_one::MainContract;\n\nuse contracts_one::{\n\n ContractView, ProjectView, UserView, CREATE_USER_DEPOSIT, ERR_PROJECT_NAME_INVALID,\n\n REGISTER_CONTRACT_DEPOSIT, REGISTER_PROJECT_DEPOSIT, SUBMIT_AUDIT_DEPOSIT,\n\n};\n\n\n\nuse near_sdk::json_types::Base58CryptoHash;\n\nuse near_sdk::Timestamp;\n\nuse near_sdk_sim::{call, deploy, init_simulator, to_yocto, view, ContractAccount, UserAccount};\n\n\n\n// Load in contract bytes at runtime\n\nnear_sdk_sim::lazy_static_include::lazy_static_include_bytes! {\n\n CONTRACT_WASM_BYTES => \"res/contracts_one.wasm\",\n\n}\n\n\n\nconst CONTRACT_ID: &str = \"contracts_one\";\n", "file_path": "contract/tests/general.rs", "rank": 52, "score": 4176.162158735383 }, { "content": " let res = view!(contract.get_all_projects(0, 1000)).unwrap_json();\n\n res\n\n }\n\n\n\n pub fn get_contract(&self, contract_hash: &str) -> ContractView {\n\n let contract = &self.contract;\n\n let res = view!(contract.get_contract(contract_hash.try_into().unwrap())).unwrap_json();\n\n res\n\n }\n\n\n\n pub fn get_project(&self, project_name: &str) -> ProjectView {\n\n let contract = &self.contract;\n\n let res = view!(contract.get_project(project_name.into())).unwrap_json();\n\n res\n\n }\n\n\n\n pub fn get_user(&self, user_name: &str) -> Option<UserView> {\n\n let contract = &self.contract;\n\n let res = view!(contract.get_user(user_name.try_into().unwrap())).unwrap_json();\n\n res\n", "file_path": "contract/tests/general.rs", "rank": 54, "score": 4172.562249365185 }, { "content": " contract: deployed_contract,\n\n accounts: HashMap::default(),\n\n };\n\n // Already added in new()\n\n // state.do_create_user(&state.root.account_id(), None);\n\n state\n\n }\n\n\n\n pub fn create_alice(&mut self) {\n\n let alice = self.root.create_user(ALICE.into(), to_yocto(\"1000000000\"));\n\n self.accounts.insert(ALICE.into(), alice);\n\n }\n\n\n\n pub fn create_bob(&mut self) {\n\n let bob = self.root.create_user(BOB.into(), to_yocto(\"1000000000\"));\n\n self.accounts.insert(BOB.into(), bob);\n\n }\n\n\n\n pub fn get_all_projects(&self) -> Vec<ProjectView> {\n\n let contract = &self.contract;\n", "file_path": "contract/tests/general.rs", "rank": 55, "score": 4171.250983868109 }, { "content": " format!(\"{:?}\", outcome.status()).contains(msg),\n\n \"received {:?}\",\n\n outcome.status()\n\n );\n\n assert!(!outcome.is_ok(), \"Should panic\");\n\n } else {\n\n outcome.assert_success();\n\n }\n\n }\n\n\n\n pub fn do_register_contract(\n\n &self,\n\n account_name: &str,\n\n project: &str,\n\n hash: &str,\n\n version: &str,\n\n err: Option<&str>,\n\n ) {\n\n let contract = &self.contract;\n\n let account = self.accounts.get(account_name).unwrap();\n", "file_path": "contract/tests/general.rs", "rank": 57, "score": 4169.574253025831 }, { "content": " report_url.to_string(),\n\n summary.to_string(),\n\n date.into()\n\n ),\n\n deposit = SUBMIT_AUDIT_DEPOSIT\n\n );\n\n if let Some(msg) = err {\n\n assert!(\n\n format!(\"{:?}\", outcome.status()).contains(msg),\n\n \"received {:?}\",\n\n outcome.status()\n\n );\n\n assert!(!outcome.is_ok(), \"Should panic\");\n\n } else {\n\n outcome.assert_success();\n\n }\n\n }\n\n\n\n pub fn validate(&self) {\n\n let projects = self.get_all_projects();\n\n let a = self.get_user(ALICE);\n\n // println!(\"A = {:?}\", a);\n\n //assert_eq!(project_names.len(), 5);\n\n\n\n //assert!(false);\n\n }\n\n}\n\n\n", "file_path": "contract/tests/general.rs", "rank": 58, "score": 4169.405881614242 }, { "content": " }\n\n }\n\n\n\n fn do_submit_audit(\n\n &self,\n\n account_name: &str,\n\n contract_hash: &str,\n\n auditor_url: &str,\n\n report_url: &str,\n\n summary: &str,\n\n date: Timestamp,\n\n err: Option<&str>,\n\n ) {\n\n let contract = &self.contract;\n\n let account = self.accounts.get(account_name).unwrap();\n\n let outcome = call!(\n\n account,\n\n contract.submit_audit(\n\n contract_hash.try_into().unwrap(),\n\n auditor_url.to_string(),\n", "file_path": "contract/tests/general.rs", "rank": 59, "score": 4169.290430088373 }, { "content": " }\n\n\n\n pub fn do_register_project(&self, name: &str, owners: &[&str], err: Option<&str>) {\n\n let contract = &self.contract;\n\n\n\n let outcome = call!(\n\n self.root,\n\n contract.register_project(\n\n name.to_string(),\n\n \"bla\".to_string(),\n\n DEFAULT_URL.to_string(),\n\n owners\n\n .iter()\n\n .map(|o| o.to_string().try_into().unwrap())\n\n .collect()\n\n ),\n\n deposit = REGISTER_PROJECT_DEPOSIT\n\n );\n\n if let Some(msg) = err {\n\n assert!(\n", "file_path": "contract/tests/general.rs", "rank": 60, "score": 4168.773848871458 }, { "content": " \"5suuACmAzbTj8oyv4bQUjuJZbRinGMAKMLorDDEFzu4b\",\n\n \"0.0.0\",\n\n None,\n\n );\n\n\n\n assert_eq!(\n\n ver,\n\n &state.get_project(\"contract.one_test\").contracts[0].version\n\n );\n\n}\n", "file_path": "contract/tests/general.rs", "rank": 61, "score": 4168.646295645298 }, { "content": " let outcome = call!(\n\n account,\n\n contract.register_contract(\n\n project.to_string(),\n\n \"default contract name\".to_string(),\n\n hash.try_into().unwrap(),\n\n version.to_string(),\n\n \"default sha-1\".to_string(),\n\n DEFAULT_STANDARDS_DECLARED\n\n ),\n\n deposit = REGISTER_CONTRACT_DEPOSIT\n\n );\n\n if let Some(msg) = err {\n\n assert!(\n\n format!(\"{:?}\", outcome.status()).contains(msg),\n\n \"received {:?}\",\n\n outcome.status()\n\n );\n\n assert!(!outcome.is_ok(), \"Should panic\");\n\n } else {\n", "file_path": "contract/tests/general.rs", "rank": 62, "score": 4168.231373297432 }, { "content": " outcome.assert_success();\n\n }\n\n }\n\n\n\n fn do_create_user(&self, account_name: &str, err: Option<&str>) {\n\n let contract = &self.contract;\n\n let outcome = call!(\n\n self.root,\n\n contract.create_user(account_name.try_into().unwrap()),\n\n deposit = CREATE_USER_DEPOSIT\n\n );\n\n if let Some(msg) = err {\n\n assert!(\n\n format!(\"{:?}\", outcome.status()).contains(msg),\n\n \"received {:?}\",\n\n outcome.status()\n\n );\n\n assert!(!outcome.is_ok(), \"Should panic\");\n\n } else {\n\n outcome.assert_success();\n", "file_path": "contract/tests/general.rs", "rank": 63, "score": 4167.563244921901 }, { "content": "\n\nconst ERR_ASSERT: Option<&str> = Some(\"assertion failed\");\n\nconst ERR_UNWRAP: Option<&str> = Some(\"called `Option::unwrap()`\");\n\n\n\nconst DEFAULT_PROJECT_ID: &str = \"Test_Project_111\";\n\nconst DEFAULT_CONTRACT_HASH: &str = \"FtPgYqXzhGhcsB4rMt8ji5krAQuoDWamLgtUqYMLKnP3\";\n\nconst DEFAULT_URL: &str = \"near.org\";\n\nconst DEFAULT_VERSION: &str = \"1.2.3\";\n\nconst DEFAULT_STANDARDS_DECLARED: Vec<String> = vec![];\n\nconst ALICE: &str = \"alice\";\n\nconst BOB: &str = \"bob\";\n\n#[allow(dead_code)]\n\nconst CAROL: &str = \"carol\";\n\nconst DEFAULT_PROJECT_OWNERS: &[&'static str; 3] = &[\"root\", ALICE, BOB];\n\n\n", "file_path": "contract/tests/general.rs", "rank": 64, "score": 4166.936396168279 }, { "content": "#[test]\n\nfn reproduce_1() {\n\n let mut state = State::new();\n\n state.create_alice();\n\n state.create_bob();\n\n\n\n state.do_register_project(\"contract.one_test\", DEFAULT_PROJECT_OWNERS, None);\n\n state.do_register_contract(\n\n ALICE,\n\n \"contract.one_test\",\n\n \"5suuACmAzbTj8oyv4bQUjuJZbRinGMAKMLorDDEFzu4a\",\n\n \"1.2.3\",\n\n None,\n\n );\n\n let ver = &state.get_project(\"contract.one_test\").contracts[0].version;\n\n\n\n state.do_register_project(\"contract.two_test\", DEFAULT_PROJECT_OWNERS, None);\n\n state.do_register_project(\"contract.three_test\", DEFAULT_PROJECT_OWNERS, None);\n\n state.do_register_contract(\n\n ALICE,\n\n \"contract.three_test\",\n", "file_path": "contract/tests/general.rs", "rank": 68, "score": 3985.5245242888755 }, { "content": "import React from 'react'\n\nimport { useParams } from 'react-router'\n\nimport { Link } from 'react-router-dom'\n\nimport useSWR from 'swr'\n\nimport Moment from 'react-moment'\n\n\n\nimport { loader, mapContract, mapProject } from '../components/Helpers'\n\n\n\nfunction ContractPage (props) {\n\n const { contractHash } = useParams()\n\n\n\n const fetchProject = async (...args) => {\n\n return mapProject(await props._near.contract.get_project({ project_name: args[1] }))\n\n }\n\n\n\n const fetchContract = async (...args) => {\n\n return args[1] === '' ? mapContract(null) : mapContract(await props._near.contract.get_contract({ contract_hash: args[1] }))\n\n }\n\n\n\n const { data: contract } = useSWR(contractHash ? ['contract', contractHash] : null, fetchContract, { errorRetryInterval: 500 })\n\n const { data: project } = useSWR(contract ? ['project', contract.projectName] : null, fetchProject, { errorRetryInterval: 500 })\n\n\n\n const certificates = contract && contract.certificates.length ? contract.certificates.map((data, index) => {\n\n const approvedMsg = data.approved ? 'approved' : 'refused'\n\n return (\n\n <div key={index} className='container g-0'>\n\n <div>\n\n {approvedMsg} by <Link to={`/profileAudits/${data.author}`}>{data.author}</Link>\n\n </div>\n\n </div>\n\n )\n\n }) : <div>No certificates found</div>\n\n\n\n const standards = contract && contract.standardsDeclared.length ? contract.standardsDeclared.map((data, index) => {\n\n return (\n\n <div key={index} className='badge bg-primary me-2'>\n\n <small>{data}</small>\n\n </div>\n\n )\n\n }) : <div>No standards declared</div>\n\n\n\n const safety = contract && (contract.safetyLevel === 'High' ? 'bg-success' : (contract.safetyLevel === 'Moderate' ? 'bg-warning' : 'bg-danger'))\n\n\n\n const audits = contract && contract.audits.length ? contract.audits.map((data, index) => {\n\n return (\n\n <div key={index} className='badge bg-secondary me-2'>\n\n <small>{data}</small>\n\n </div>\n\n )\n\n }) : <div>No audits</div>\n\n\n\n const issues = contract && contract.safetyIssues.length ? contract.safetyIssues.map((data, index) => {\n\n return (\n\n <div key={index} className='container g-0'>\n\n <small>\n\n {data}\n\n </small>\n\n </div>\n\n )\n\n }) : <div>No issues found</div>\n\n\n\n return props.connected && contract && project ? (\n\n <div className='pb-3'>\n\n <div className='container g-0 px-5'>\n\n <div className='d-flex flex-row bd-highlight mb-3'>\n\n <div className='py-2 bd-highlight'>\n\n <h5>Contract</h5>\n\n </div>\n\n <div className='p-2 bd-highlight' />\n\n <div className='p-2 bd-highlight'>\n\n <h5 className='gray'>{contract.hash}</h5>\n\n </div>\n\n </div>\n\n <div className='mb-3 py-2'>\n\n <h4>Project</h4>\n\n <Link to={`/projectInfo/${contract.projectName}`}>{contract.projectName}</Link>\n\n </div>\n\n <div className='mb-3 py-2'>\n\n <h4>Description</h4>\n\n <div>{project.description}</div>\n\n </div>\n\n <hr />\n\n <div className='mb-3 py-2'>\n\n <h4>Contract details</h4>\n\n <div className='row'>\n\n <div className='col-2' style={{ minWidth: '200px' }}>\n\n Contract name:\n\n </div>\n\n <div className='col-4' style={{ minWidth: '200px' }}>\n\n {contract.contractName}\n\n </div>\n\n </div>\n\n <div className='row'>\n\n <div className='col-2' style={{ minWidth: '200px' }}>\n\n Version:\n\n </div>\n\n <div className='col-4' style={{ minWidth: '200px' }}>\n\n {contract.version}\n\n </div>\n\n </div>\n\n <div className='row'>\n\n <div className='col-2' style={{ minWidth: '200px' }}>\n\n Publisher:\n\n </div>\n\n <div className='col-4' style={{ minWidth: '200px' }}>\n\n <Link to={`/profileProjects/${contract.publisher}`}>{contract.publisher}</Link>\n\n </div>\n\n </div>\n\n <div className='row'>\n\n <div className='col-2' style={{ minWidth: '200px' }}>\n\n Published time:\n\n </div>\n\n <div className='col-4' style={{ minWidth: '200px' }}>\n\n <Moment unix fromNow>{contract.publishedTime / 1000000000}</Moment>\n\n </div>\n\n </div>\n\n <div className='row'>\n\n <div className='col-2' style={{ minWidth: '200px' }}>\n\n Hash:\n\n </div>\n\n <div className='col-4' style={{ minWidth: '200px' }}>\n\n <samp className='small'>{contract.hash}</samp>\n\n </div>\n\n </div>\n\n <div className='row'>\n\n <div className='col-2' style={{ minWidth: '200px' }}>\n\n Audits:\n\n </div>\n\n <div className='col-4' style={{ minWidth: '200px' }}>\n\n {audits}\n\n </div>\n\n </div>\n\n <div className='row'>\n\n <div className='col-2' style={{ minWidth: '200px' }}>\n\n Source code:\n\n </div>\n\n <div className='col-4' style={{ minWidth: '200px' }}>\n\n {contract.sourceCodeSize} bytes <Link to='/cli'>(download)</Link>\n\n </div>\n\n </div>\n\n <div className='row'>\n\n <div className='col-2' style={{ minWidth: '200px' }}>\n\n Safety report:\n\n </div>\n\n <div className='col-4' style={{ minWidth: '200px' }}>\n\n <div className={'badge ' + safety}>{contract.safetyLevel}</div>\n\n {issues}\n\n </div>\n\n </div>\n\n </div>\n\n <hr />\n\n <div className='mb-3 py-2'>\n\n <h4>Standards</h4>\n\n {standards}\n\n </div>\n\n <div className='mb-3 py-2'>\n\n <h4>Certificates</h4>\n\n {certificates}\n\n </div>\n\n </div>\n\n </div>\n\n ) : loader()\n\n}\n\n\n\nexport default ContractPage\n", "file_path": "frontend/src/pages/Contract.js", "rank": 69, "score": 3825.3468947051915 }, { "content": "const path = require('path')\n", "file_path": "cli/index.js", "rank": 70, "score": 3533.982071112724 }, { "content": "const bs58 = require('bs58')\n", "file_path": "cli/index.js", "rank": 71, "score": 3533.982071112724 }, { "content": "const tar = require('tar')\n", "file_path": "cli/index.js", "rank": 72, "score": 3533.982071112724 }, { "content": "const crypto = require('crypto')\n", "file_path": "cli/index.js", "rank": 73, "score": 3533.982071112724 }, { "content": "const fs = require('fs')\n", "file_path": "cli/index.js", "rank": 74, "score": 3533.982071112724 }, { "content": "const nearAPI = require('near-api-js')\n", "file_path": "cli/near.js", "rank": 75, "score": 3405.37729900054 }, { "content": "const nearCommand = program\n\n .command('near [options]')\n", "file_path": "cli/index.js", "rank": 76, "score": 3405.37729900054 }, { "content": " constructor (props) {\n\n super(props)\n\n\n\n this._near = {}\n\n\n\n this._near.lsKey = NearConfig.contractName + ':v01:'\n\n\n\n this._near.config = NearConfig\n\n\n\n this.state = {\n\n connected: false,\n\n account: null\n\n }\n\n\n\n this._initNear().then(() => {\n\n this.setState({\n\n signedIn: !!this._near.accountId,\n\n signedAccountId: this._near.accountId,\n\n connected: true\n\n })\n\n })\n", "file_path": "frontend/src/App.js", "rank": 77, "score": 3405.37729900054 }, { "content": "const NEAR = '\\u24C3\\u202F'\n", "file_path": "frontend/src/components/Helpers.js", "rank": 78, "score": 3285.803950916223 }, { "content": " async requestSignIn (e) {\n\n e && e.preventDefault()\n\n const appTitle = 'Contracts One'\n\n await this._near.walletConnection.requestSignIn(\n\n NearConfig.contractName,\n\n appTitle\n\n )\n\n return false\n", "file_path": "frontend/src/App.js", "rank": 79, "score": 3285.803950916223 }, { "content": "const realZlibConstants = require('zlib').constants\n", "file_path": "cli/index.js", "rank": 80, "score": 3285.803950916223 }, { "content": "const fromNear = (s) => parseFloat(s) / 1e24 || 0\n", "file_path": "frontend/src/components/Helpers.js", "rank": 81, "score": 3285.803950916223 }, { "content": "# TBD\n", "file_path": "README.md", "rank": 82, "score": 2881.1408259648247 }, { "content": "#!/usr/bin/env node\n\nconst { program } = require('commander')\n\nconst bs58 = require('bs58')\n\nconst crypto = require('crypto')\n\nconst fs = require('fs')\n\nconst path = require('path')\n\nconst tar = require('tar')\n\nconst realZlibConstants = require('zlib').constants\n\n\n\nconst { nearContractView } = require('./near')\n\n\n\nprogram.version(require('./package.json').version)\n\n\n\nprogram\n\n .command('pack <path-to-project> <filename>')\n\n .description('pack the contract source code to the proper bs58-encoded .tar.gz archive')\n\n .action((sourceCodePath, filename) => {\n\n tar.c(\n\n {\n\n gzip: { level: realZlibConstants.Z_BEST_COMPRESSION, strategy: realZlibConstants.Z_DEFAULT_STRATEGY },\n\n file: path.resolve(filename + '.tar.gz'),\n\n C: path.normalize(sourceCodePath),\n\n filter: function (name) {\n\n const pathResolved = path.resolve(sourceCodePath, name)\n\n const isDir = fs.lstatSync(pathResolved).isDirectory()\n\n const base = path.basename(pathResolved)\n\n const ext = path.extname(pathResolved)\n\n const process = (isDir && base !== 'target' && base !== 'res') || base === 'Cargo.lock' || base === 'Cargo.toml' || ext === '.rs'\n\n if (process) {\n\n console.log(base, 'processing...')\n\n }\n\n return process\n\n }\n\n },\n\n // TODO replace with actual files to remove './' prefixes from tar\n\n ['.']\n\n ).then(_ => {\n\n const bytes = fs.readFileSync(path.resolve(filename + '.tar.gz'))\n\n // TODO use base64 encoding\n\n console.log('bs58 encoding...')\n\n const bs58encoded = bs58.encode(bytes)\n\n fs.writeFileSync(filename, bs58encoded)\n\n fs.unlinkSync(path.resolve(filename + '.tar.gz'))\n\n console.log('done')\n\n })\n\n })\n\n\n\nprogram\n\n .command('unpack <filename>')\n\n .description('unpack the contract source code from the bs58-encoded .tar.gz archive')\n\n .action((filename) => {\n\n const bytes = fs.readFileSync(filename)\n\n console.log('bs58 decoding...')\n\n const bs58decoded = bs58.decode(bytes.toString())\n\n fs.writeFileSync(path.resolve(filename + '.tar.gz'), bs58decoded)\n\n console.log('files extracting...')\n\n tar.x(\n\n {\n\n file: path.resolve(filename + '.tar.gz')\n\n }\n\n ).then(_ => {\n\n fs.unlinkSync(path.resolve(filename + '.tar.gz'))\n\n console.log('done')\n\n })\n\n })\n\n\n\nprogram\n\n .command('hash <wasm-file>')\n\n .description('get code_hash from the compiled wasm file')\n\n .action((wasmFile) => {\n\n const bytes = fs.readFileSync(wasmFile)\n\n const hash = crypto.createHash('sha256').update(bytes).digest('hex')\n\n const bs58encoded = bs58.encode(Buffer.from(hash, 'hex'))\n\n console.log(bs58encoded)\n\n })\n\n\n\nconst nearCommand = program\n\n .command('near [options]')\n\n .description('operations with NEAR blockchain')\n\n\n\nnearCommand\n\n .command('source <code-hash> <filename>')\n\n .description('download source code of the contract by given hash as the file')\n\n .action(async (codeHash, filename) => {\n\n // TODO use env variable\n\n const env = 'testnet'\n\n const contract = await nearContractView(env)\n\n console.log(contract)\n\n const response = await contract.get_contract_source_code({ contract_hash: codeHash })\n\n fs.writeFileSync(filename, response)\n\n console.log('done')\n\n })\n\n\n\n;(async () => {\n\n await program.parseAsync(process.argv)\n\n})()\n", "file_path": "cli/index.js", "rank": 83, "score": 2795.083705421967 }, { "content": "const nearAPI = require('near-api-js')\n\n\n\nfunction getConfig (env) {\n\n switch (env) {\n\n case 'mainnet':\n\n return {\n\n networkId: 'mainnet',\n\n nodeUrl: 'https://rpc.mainnet.near.org',\n\n // TODO\n\n contractName: '',\n\n walletUrl: 'https://wallet.near.org',\n\n helperUrl: 'https://helper.mainnet.near.org'\n\n }\n\n case '':\n\n case 'testnet':\n\n return {\n\n networkId: 'testnet',\n\n nodeUrl: 'https://rpc.testnet.near.org',\n\n contractName: 'dev-1618917933127-5935675',\n\n walletUrl: 'https://wallet.testnet.near.org',\n\n helperUrl: 'https://helper.testnet.near.org',\n\n keyStore: []\n\n }\n\n }\n\n}\n\n\n\nasync function nearContractView (env) {\n\n const config = getConfig(env)\n\n const near = await nearAPI.connect(config)\n\n const account = await near.account(config.contractName)\n\n return new nearAPI.Contract(\n\n account,\n\n config.contractName, {\n\n viewMethods: ['get_contract_source_code'],\n\n changeMethods: []\n\n })\n\n}\n\n\n\nmodule.exports = {\n\n getConfig,\n\n nearContractView,\n\n nearAPI\n\n}\n", "file_path": "cli/near.js", "rank": 84, "score": 2795.083705421967 }, { "content": "import React from 'react'\n\nimport ReactDOM from 'react-dom'\n\nimport './index.css'\n\nimport App from './App'\n\n\n\nReactDOM.render(<App />, document.getElementById('root'))\n", "file_path": "frontend/src/index.js", "rank": 85, "score": 2714.018383963389 }, { "content": "import React from 'react'\n\n\n\nconst NEAR = '\\u24C3\\u202F'\n\n\n\nconst fromNear = (s) => parseFloat(s) / 1e24 || 0\n\n\n\nfunction loader () {\n\n return (\n\n // key='1' is needed by InfiniteScroll\n\n <div className='d-flex justify-content-center' key='1'>\n\n <div className='spinner-grow' role='status'>\n\n <span className='visually-hidden'>Loading...</span>\n\n </div>\n\n </div>\n\n )\n\n}\n\n\n\nconst mapProjectView = (c) => {\n\n return c ? {\n\n id: c.project_id,\n\n name: c.project_name,\n\n description: c.description,\n\n url: c.url,\n\n owners: c.owners,\n\n contracts: c.contracts,\n\n lastVersion: c.last_version\n\n } : null\n\n}\n\n\n\nconst mapCertificateView = (c) => {\n\n return c ? {\n\n projectName: c.project_name,\n\n version: c.version,\n\n author: c.author,\n\n reportUrl: c.report_url,\n\n summary: c.summary,\n\n standardsConfirmed: c.standards_confirmed,\n\n basicValidityPassed: c.basic_validity_passed,\n\n contractApproved: c.contract_approved,\n\n score: c.score\n\n } : null\n\n}\n\n\n\nconst mapContract = (c) => {\n\n return c ? {\n\n audits: c.audits,\n\n certificates: c.certificates,\n\n commitHash: c.commit_hash,\n\n contractName: c.contract_name,\n\n hash: c.hash,\n\n projectName: c.project_name,\n\n publishedTime: c.published_time,\n\n publisher: c.publisher,\n\n safetyLevel: c.safety_report.safety_level,\n\n safetyIssues: c.safety_report.safety_issues,\n\n sourceCodeSize: c.source_code_size,\n\n standardsDeclared: c.standards_declared,\n\n version: c.version\n\n } : null\n\n}\n\n\n\nconst mapProject = (c) => {\n\n return c ? {\n\n id: c.project_id,\n\n name: c.project_name,\n\n url: c.url,\n\n contracts: c.contracts,\n\n description: c.description,\n\n lastVersion: c.last_version,\n\n owners: c.owners\n\n } : null\n\n}\n\n\n\nexport { NEAR, fromNear, loader, mapContract, mapProject, mapProjectView, mapCertificateView }\n", "file_path": "frontend/src/components/Helpers.js", "rank": 86, "score": 2637.522774492448 }, { "content": "import React from 'react'\n\nimport { Link } from 'react-router-dom'\n\n\n\nfunction ContractLink (props) {\n\n const contractHash = props.contractHash\n\n const version = props.version\n\n return <Link className='navigate' to={'/contract/' + contractHash}>{version}</Link>\n\n}\n\n\n\nfunction ProjectLink (props) {\n\n const projectName = props.projectName\n\n return <Link className='navigate' to={'/projectInfo/' + projectName}>{projectName}</Link>\n\n}\n\n\n\nfunction ProfileLink (props) {\n\n const userName = props.userName\n\n return <Link className='navigate' to={'/profileStats/' + userName}>{userName}</Link>\n\n}\n\n\n\nexport { ContractLink, ProjectLink, ProfileLink }\n", "file_path": "frontend/src/components/Links.js", "rank": 87, "score": 2637.522774492448 } ]
Rust
src/editor.rs
Crosse/raster
f54e52004ef889748caf2322d5bd9e25837615ef
use std::cmp; use error::{RasterError, RasterResult}; use blend::{self, BlendMode}; use Color; use Image; use position::{Position, PositionMode}; use transform; pub fn blend( image1: &Image, image2: &Image, blend_mode: BlendMode, opacity: f32, position: PositionMode, offset_x: i32, offset_y: i32, ) -> RasterResult<Image> { let opacity = if opacity > 1.0 { 1.0 } else if opacity < 0.0 { 0.0 } else { opacity }; let positioner = Position::new(position, offset_x, offset_y); let (offset_x, offset_y) = positioner.get_x_y(image1.width, image1.height, image2.width, image2.height)?; let (w1, h1) = (image1.width, image1.height); let (w2, h2) = (image2.width, image2.height); if (offset_x >= w1) || (offset_x + w2 <= 0) || (offset_y >= h1) || (offset_y + h2 <= 0) { return Err(RasterError::BlendingImageFallsOutsideCanvas); } let mut loop_start_x = 0; let canvas_start_x = offset_x; if canvas_start_x < 0 { let diff = 0 - canvas_start_x; loop_start_x += diff; } let mut loop_end_x = w2; let canvas_end_x = offset_x + w2; if canvas_end_x > w1 { let diff = canvas_end_x - w1; loop_end_x -= diff; } let mut loop_start_y = 0; let canvas_start_y = offset_y; if canvas_start_y < 0 { let diff = 0 - canvas_start_y; loop_start_y += diff; } let mut loop_end_y = h2; let canvas_end_y = offset_y + h2; if canvas_end_y > h1 { let diff = canvas_end_y - h1; loop_end_y -= diff; } match blend_mode { BlendMode::Normal => blend::normal( image1, image2, loop_start_y, loop_end_y, loop_start_x, loop_end_x, offset_x, offset_y, opacity, ), BlendMode::Difference => blend::difference( image1, image2, loop_start_y, loop_end_y, loop_start_x, loop_end_x, offset_x, offset_y, opacity, ), BlendMode::Multiply => blend::multiply( image1, image2, loop_start_y, loop_end_y, loop_start_x, loop_end_x, offset_x, offset_y, opacity, ), BlendMode::Overlay => blend::overlay( image1, image2, loop_start_y, loop_end_y, loop_start_x, loop_end_x, offset_x, offset_y, opacity, ), BlendMode::Screen => blend::screen( image1, image2, loop_start_y, loop_end_y, loop_start_x, loop_end_x, offset_x, offset_y, opacity, ), } } pub fn crop( src: &mut Image, crop_width: i32, crop_height: i32, position: PositionMode, offset_x: i32, offset_y: i32, ) -> RasterResult<()> { let positioner = Position::new(position, offset_x, offset_y); let (offset_x, offset_y) = positioner.get_x_y(src.width, src.height, crop_width, crop_height)?; let offset_x = cmp::max(0, offset_x); let offset_y = cmp::max(0, offset_y); let height2 = { let height2 = offset_y + crop_height; cmp::min(height2, src.height) }; let width2 = { let width2 = offset_x + crop_width; cmp::min(width2, src.width) }; let mut dest = Image::blank(width2 - offset_x, height2 - offset_y); for y in 0..dest.height { for x in 0..dest.width { let pixel = src.get_pixel(offset_x + x, offset_y + y)?; dest.set_pixel(x, y, &Color::rgba(pixel.r, pixel.g, pixel.b, pixel.a))?; } } src.width = dest.width; src.height = dest.height; src.bytes = dest.bytes; Ok(()) } pub fn fill(src: &mut Image, color: Color) -> RasterResult<()> { for y in 0..src.height { for x in 0..src.width { src.set_pixel(x, y, &color)?; } } Ok(()) } #[derive(Debug)] pub enum ResizeMode { Exact, ExactWidth, ExactHeight, Fit, Fill, } pub fn resize(src: &mut Image, w: i32, h: i32, mode: ResizeMode) -> RasterResult<()> { match mode { ResizeMode::Exact => transform::resize_exact(src, w, h), ResizeMode::ExactWidth => transform::resize_exact_width(src, w), ResizeMode::ExactHeight => transform::resize_exact_height(src, h), ResizeMode::Fit => transform::resize_fit(src, w, h), ResizeMode::Fill => transform::resize_fill(src, w, h), } }
use std::cmp; use error::{RasterError, RasterResult}; use blend::{self, BlendMode}; use Color; use Image; use position::{Position, PositionMode}; use transform; pub fn blend( image1: &Image, image2: &Image, blend_mode: BlendMode, opacity: f32, position: PositionMode, offset_x: i32, offset_y: i32, ) -> RasterResult<Image> { let opacity = if opacity > 1.0 { 1.0 } else if opacity < 0.0 { 0.0 } else { opacity }; let positioner = Position::new(position, offset_x, offset_y); let (offset_x, offset_y) = positioner.get_x_y(image1.widt
offset_y, opacity, ), BlendMode::Difference => blend::difference( image1, image2, loop_start_y, loop_end_y, loop_start_x, loop_end_x, offset_x, offset_y, opacity, ), BlendMode::Multiply => blend::multiply( image1, image2, loop_start_y, loop_end_y, loop_start_x, loop_end_x, offset_x, offset_y, opacity, ), BlendMode::Overlay => blend::overlay( image1, image2, loop_start_y, loop_end_y, loop_start_x, loop_end_x, offset_x, offset_y, opacity, ), BlendMode::Screen => blend::screen( image1, image2, loop_start_y, loop_end_y, loop_start_x, loop_end_x, offset_x, offset_y, opacity, ), } } pub fn crop( src: &mut Image, crop_width: i32, crop_height: i32, position: PositionMode, offset_x: i32, offset_y: i32, ) -> RasterResult<()> { let positioner = Position::new(position, offset_x, offset_y); let (offset_x, offset_y) = positioner.get_x_y(src.width, src.height, crop_width, crop_height)?; let offset_x = cmp::max(0, offset_x); let offset_y = cmp::max(0, offset_y); let height2 = { let height2 = offset_y + crop_height; cmp::min(height2, src.height) }; let width2 = { let width2 = offset_x + crop_width; cmp::min(width2, src.width) }; let mut dest = Image::blank(width2 - offset_x, height2 - offset_y); for y in 0..dest.height { for x in 0..dest.width { let pixel = src.get_pixel(offset_x + x, offset_y + y)?; dest.set_pixel(x, y, &Color::rgba(pixel.r, pixel.g, pixel.b, pixel.a))?; } } src.width = dest.width; src.height = dest.height; src.bytes = dest.bytes; Ok(()) } pub fn fill(src: &mut Image, color: Color) -> RasterResult<()> { for y in 0..src.height { for x in 0..src.width { src.set_pixel(x, y, &color)?; } } Ok(()) } #[derive(Debug)] pub enum ResizeMode { Exact, ExactWidth, ExactHeight, Fit, Fill, } pub fn resize(src: &mut Image, w: i32, h: i32, mode: ResizeMode) -> RasterResult<()> { match mode { ResizeMode::Exact => transform::resize_exact(src, w, h), ResizeMode::ExactWidth => transform::resize_exact_width(src, w), ResizeMode::ExactHeight => transform::resize_exact_height(src, h), ResizeMode::Fit => transform::resize_fit(src, w, h), ResizeMode::Fill => transform::resize_fill(src, w, h), } }
h, image1.height, image2.width, image2.height)?; let (w1, h1) = (image1.width, image1.height); let (w2, h2) = (image2.width, image2.height); if (offset_x >= w1) || (offset_x + w2 <= 0) || (offset_y >= h1) || (offset_y + h2 <= 0) { return Err(RasterError::BlendingImageFallsOutsideCanvas); } let mut loop_start_x = 0; let canvas_start_x = offset_x; if canvas_start_x < 0 { let diff = 0 - canvas_start_x; loop_start_x += diff; } let mut loop_end_x = w2; let canvas_end_x = offset_x + w2; if canvas_end_x > w1 { let diff = canvas_end_x - w1; loop_end_x -= diff; } let mut loop_start_y = 0; let canvas_start_y = offset_y; if canvas_start_y < 0 { let diff = 0 - canvas_start_y; loop_start_y += diff; } let mut loop_end_y = h2; let canvas_end_y = offset_y + h2; if canvas_end_y > h1 { let diff = canvas_end_y - h1; loop_end_y -= diff; } match blend_mode { BlendMode::Normal => blend::normal( image1, image2, loop_start_y, loop_end_y, loop_start_x, loop_end_x, offset_x,
random
[ { "content": "/// Compare two images and returns a hamming distance. A value of 0 indicates a likely similar\n\n/// picture. A value between 1 and 10 is potentially a variation. A value greater than 10 is\n\n/// likely a different image.\n\n///\n\n/// # Examples\n\n/// ```\n\n/// use raster::compare;\n\n///\n\n/// let image1 = raster::open(\"tests/in/sample.jpg\").unwrap();\n\n/// let image2 = raster::open(\"tests/in/sample.png\").unwrap();\n\n///\n\n/// let hamming_distance = compare::similar(&image1, &image2).unwrap();\n\n/// println!(\"{}\", hamming_distance);\n\n/// ```\n\npub fn similar(image1: &Image, image2: &Image) -> RasterResult<u8> {\n\n let bin1 = diff_hash(image1)?;\n\n let bin2 = diff_hash(image2)?;\n\n let mut distance = 0;\n\n for (index, value) in bin1.iter().enumerate() {\n\n if value != &bin2[index] {\n\n distance += 1;\n\n }\n\n }\n\n Ok(distance)\n\n}\n\n\n", "file_path": "src/compare.rs", "rank": 0, "score": 188915.54223964835 }, { "content": "/// Compare if two images are equal. It will compare if the two images are of the same width and\n\n/// height. If the dimensions differ, it will return false. If the dimensions are equal, it will\n\n/// loop through each pixels. If one of the pixel don't match, it will return false. The pixels\n\n/// are compared using their RGB (Red, Green, Blue) values.\n\n///\n\n/// # Examples\n\n/// ```\n\n/// use raster::compare;\n\n///\n\n/// let image1 = raster::open(\"tests/in/sample.png\").unwrap();\n\n/// let image2 = raster::open(\"tests/in/sample.png\").unwrap();\n\n///\n\n/// let equal = compare::equal(&image1, &image2).unwrap();\n\n/// assert_eq!(true, equal);\n\n/// ```\n\npub fn equal(image1: &Image, image2: &Image) -> RasterResult<bool> {\n\n // Check if image dimensions are equal\n\n if image1.width != image2.width || image1.height != image2.height {\n\n Ok(false)\n\n } else {\n\n // Loop using image1\n\n for y in 0..image1.height {\n\n for x in 0..image1.width {\n\n // Get image1 pixel\n\n let pixel1 = image1.get_pixel(x, y)?;\n\n\n\n // Get image2 pixel\n\n let pixel2 = image2.get_pixel(x, y)?;\n\n\n\n // Compare pixel value\n\n if pixel1.r != pixel2.r || pixel1.g != pixel2.g || pixel1.b != pixel2.b {\n\n return Ok(false);\n\n }\n\n }\n\n }\n\n\n\n Ok(true)\n\n }\n\n}\n\n\n\n// Private functions\n\n\n", "file_path": "src/compare.rs", "rank": 1, "score": 188914.8916100428 }, { "content": "/// Rotate an image clockwise. Negate the degrees to do a counter-clockwise rotation. Background\n\n/// color can be any color.\n\n///\n\n/// Note: If you look closely, the quality for arbitrary angles is not very good due to the simple\n\n/// sampling algorithm. The 90, 180, and 270 angles looks fine because no pixels are lost. This\n\n/// will be fixed in the future with a better sampling algorithm.\n\n///\n\n/// # Examples\n\n///\n\n/// ### Rotate 45 degrees with a black background color:\n\n///\n\n/// ```\n\n/// use raster::{transform, Color};\n\n///\n\n/// //...\n\n///\n\n/// let mut image = raster::open(\"tests/in/sample.png\").unwrap();\n\n/// transform::rotate(&mut image, 45, Color::rgb(0,0,0)).unwrap();\n\n/// raster::save(&image, \"tests/out/test_transform_rotate_45.png\").unwrap();\n\n/// ```\n\n///\n\n/// ![](https://kosinix.github.io/raster/out/test_transform_rotate_45.png)\n\n///\n\n///\n\n/// ### Rotate 45 degrees counter-clockwise with a red background color:\n\n///\n\n/// ```\n\n/// use raster::{transform, Color};\n\n///\n\n/// //...\n\n///\n\n/// let mut image = raster::open(\"tests/in/sample.png\").unwrap();\n\n/// transform::rotate(&mut image, -45, Color::rgb(252,145,145)).unwrap();\n\n/// raster::save(&image, \"tests/out/test_transform_rotate_45cc.png\").unwrap();\n\n/// ```\n\n///\n\n/// ![](https://kosinix.github.io/raster/out/test_transform_rotate_45cc.png)\n\n///\n\npub fn rotate(src: &mut Image, degree: i32, bg: Color) -> RasterResult<()> {\n\n let w1 = src.width;\n\n let h1 = src.height;\n\n\n\n let degree = degree as f32; // convert to float\n\n\n\n // Using screen coords system, top left is always at (0,0)\n\n let mut min_x = 0;\n\n let mut max_x = 0;\n\n let mut min_y = 0;\n\n let mut max_y = 0;\n\n\n\n let top_right_1: (i32, i32) = (w1, 0);\n\n let top_right_2: (i32, i32) = _rotate(top_right_1, degree);\n\n min_x = cmp::min(min_x, top_right_2.0);\n\n max_x = cmp::max(max_x, top_right_2.0);\n\n min_y = cmp::min(min_y, top_right_2.1);\n\n max_y = cmp::max(max_y, top_right_2.1);\n\n\n\n let bottom_right_1: (i32, i32) = (w1, h1);\n", "file_path": "src/transform.rs", "rank": 2, "score": 184335.93457900098 }, { "content": "/// Resize image to exact dimensions ignoring aspect ratio.\n\n/// Useful if you want to force exact width and height.\n\npub fn resize_exact(src: &mut Image, w: i32, h: i32) -> RasterResult<()> {\n\n resample(src, w, h, InterpolationMode::Bicubic)\n\n}\n\n\n", "file_path": "src/transform.rs", "rank": 3, "score": 167995.0054874841 }, { "content": "/// Resize an image to fit within the given width and height.\n\n/// The re-sized image will not exceed the given dimension.\n\n/// Preserves the aspect ratio.\n\npub fn resize_fit(src: &mut Image, w: i32, h: i32) -> RasterResult<()> {\n\n let ratio: f64 = src.width as f64 / src.height as f64;\n\n\n\n // Try basing it on width first\n\n let mut resize_width = w;\n\n let mut resize_height = (w as f64 / ratio).round() as i32;\n\n\n\n if (resize_width > w) || (resize_height > h) {\n\n // Oops, either width or height does not fit\n\n // So base on height instead\n\n resize_height = h;\n\n resize_width = (h as f64 * ratio).round() as i32;\n\n }\n\n\n\n resample(src, resize_width, resize_height, InterpolationMode::Bicubic)\n\n}\n\n\n\n// Private functions\n\n\n", "file_path": "src/transform.rs", "rank": 4, "score": 167992.9186710404 }, { "content": "/// Resize image to fill all the space in the given dimension. Excess parts are removed.\n\npub fn resize_fill(src: &mut Image, w: i32, h: i32) -> RasterResult<()> {\n\n let width = src.width;\n\n let height = src.height;\n\n let ratio = width as f32 / height as f32;\n\n\n\n // Base optimum size on new width\n\n let mut optimum_width = w;\n\n let mut optimum_height = (w as f32 / ratio).round() as i32;\n\n\n\n if (optimum_width < w) || (optimum_height < h) {\n\n // Oops, where trying to fill and there are blank areas\n\n // So base optimum size on height instead\n\n optimum_width = (h as f32 * ratio) as i32;\n\n optimum_height = h;\n\n }\n\n\n\n resample(\n\n src,\n\n optimum_width,\n\n optimum_height,\n\n InterpolationMode::Bicubic,\n\n ).and_then(|_| crop(src, w, h, PositionMode::Center, 0, 0)) // Trim excess parts\n\n}\n\n\n", "file_path": "src/transform.rs", "rank": 5, "score": 167992.60346587165 }, { "content": "// Rotate a point clockwise to a given degree.\n\nfn _rotate(p: (i32, i32), deg: f32) -> (i32, i32) {\n\n let radians: f32 = deg.to_radians();\n\n let px: f32 = p.0 as f32;\n\n let py: f32 = p.1 as f32;\n\n let cos = radians.cos();\n\n let sin = radians.sin();\n\n let x = ((px * cos) - (py * sin)).round();\n\n let y = ((px * sin) + (py * cos)).round();\n\n (x as i32, y as i32)\n\n}\n", "file_path": "src/transform.rs", "rank": 6, "score": 163802.4229087561 }, { "content": "/// Resize image to exact height. Width is auto calculated.\n\n/// Useful for creating row of images with the same height.\n\npub fn resize_exact_height(src: &mut Image, h: i32) -> RasterResult<()> {\n\n let width = src.width;\n\n let height = src.height;\n\n let ratio = width as f32 / height as f32;\n\n\n\n let resize_height = h;\n\n let resize_width = (h as f32 * ratio) as i32;\n\n\n\n resample(src, resize_width, resize_height, InterpolationMode::Bicubic)\n\n}\n\n\n", "file_path": "src/transform.rs", "rank": 7, "score": 157810.27552617955 }, { "content": "/// Resize image to exact width. Height is auto calculated.\n\n/// Useful for creating column of images with the same width.\n\npub fn resize_exact_width(src: &mut Image, w: i32) -> RasterResult<()> {\n\n let width = src.width;\n\n let height = src.height;\n\n let ratio = width as f32 / height as f32;\n\n\n\n let resize_width = w;\n\n let resize_height = (w as f32 / ratio).round() as i32;\n\n\n\n resample(src, resize_width, resize_height, InterpolationMode::Bicubic)\n\n}\n\n\n", "file_path": "src/transform.rs", "rank": 8, "score": 157810.27552617955 }, { "content": "/// Interpolate using nearest neighbor.\n\npub fn nearest(src: &mut Image, w: i32, h: i32) -> RasterResult<()> {\n\n let x_ratio: f64 = src.width as f64 / w as f64;\n\n let y_ratio: f64 = src.height as f64 / h as f64;\n\n\n\n let mut dest = Image::blank(w, h);\n\n for y in 0..h {\n\n for x in 0..w {\n\n let px: i32 = (x as f64 * x_ratio).floor() as i32;\n\n let py: i32 = (y as f64 * y_ratio).floor() as i32;\n\n let pixel = src.get_pixel(px, py)?;\n\n\n\n dest.set_pixel(x, y, &pixel)?;\n\n }\n\n }\n\n src.width = dest.width;\n\n src.height = dest.height;\n\n src.bytes = dest.bytes;\n\n\n\n Ok(())\n\n}\n\n\n", "file_path": "src/interpolate.rs", "rank": 10, "score": 150810.28162791033 }, { "content": "/// Interpolate using linear function.\n\npub fn bilinear(src: &mut Image, w2: i32, h2: i32) -> RasterResult<()> {\n\n bilinear_width(src, w2).and_then(|_| bilinear_height(src, h2))\n\n}\n\n\n\n// Private functions\n\n\n", "file_path": "src/interpolate.rs", "rank": 12, "score": 145481.81270746025 }, { "content": "fn ch_alpha_f(base: f32, top: f32, f: BlendFunction, opacity: f32) -> f32 {\n\n match f {\n\n BlendFunction::Difference => ch_alpha(base, ch_difference(base, top), opacity),\n\n BlendFunction::Multiply => ch_alpha(base, ch_multiply(base, top), opacity),\n\n BlendFunction::Overlay => ch_alpha(base, ch_overlay(base, top), opacity),\n\n BlendFunction::Screen => ch_alpha(base, ch_screen(base, top), opacity),\n\n }\n\n}\n\n\n", "file_path": "src/blend.rs", "rank": 13, "score": 141292.35371230356 }, { "content": "/// Apply a gamma correction.\n\n///\n\n/// Gamma can be a value from 0.01 - 9.99.\n\n/// A gamma < 1.0 will darken and a gamma > 1.0 will lighten the image.\n\n///\n\n/// # Examples\n\n/// ```\n\n/// use raster::filter;\n\n///\n\n/// let mut image = raster::open(\"tests/in/sample.jpg\").unwrap();\n\n/// filter::gamma(&mut image, 2.0).unwrap();\n\n/// raster::save(&image, \"tests/out/test_filter_gamma.jpg\").unwrap();\n\n/// ```\n\n///\n\n/// ### Before\n\n/// ![](https://kosinix.github.io/raster/in/sample.jpg)\n\n///\n\n/// ### After\n\n/// ![](https://kosinix.github.io/raster/out/test_filter_gamma.jpg)\n\n///\n\n// http://stackoverflow.com/questions/14088889/changing-a-color-brightness\n\npub fn gamma(src: &mut Image, gamma: f32) -> RasterResult<()> {\n\n let w: i32 = src.width;\n\n let h: i32 = src.height;\n\n\n\n if gamma < 0.01 || gamma > 9.99 {\n\n return Err(RasterError::InvalidGamma(gamma));\n\n }\n\n\n\n for y in 0..h {\n\n for x in 0..w {\n\n let p = src.get_pixel(x, y)?;\n\n let r = (p.r as f32 / 255.0).powf(gamma) * 255.0;\n\n let g = (p.g as f32 / 255.0).powf(gamma) * 255.0;\n\n let b = (p.b as f32 / 255.0).powf(gamma) * 255.0;\n\n\n\n src.set_pixel(x, y, &Color::rgba(r as u8, g as u8, b as u8, p.a as u8))?;\n\n }\n\n }\n\n\n\n Ok(())\n\n}\n\n\n", "file_path": "src/filter.rs", "rank": 14, "score": 140698.30592607215 }, { "content": "/// Apply brightness.\n\n///\n\n/// A brightness of < 0.0 will darken the image and brightness of > 1.0 will lighten it.\n\n///\n\n/// # Examples\n\n/// ```\n\n/// use raster::filter;\n\n///\n\n/// let mut image = raster::open(\"tests/in/sample.jpg\").unwrap();\n\n/// filter::brightness(&mut image, 1.5).unwrap();\n\n/// raster::save(&image, \"tests/out/test_filter_brightness.jpg\").unwrap();\n\n/// ```\n\n///\n\n/// ### Before\n\n/// ![](https://kosinix.github.io/raster/in/sample.jpg)\n\n///\n\n/// ### After\n\n/// ![](https://kosinix.github.io/raster/out/test_filter_brightness.jpg)\n\n///\n\npub fn brightness(src: &mut Image, factor: f32) -> RasterResult<()> {\n\n let w: i32 = src.width;\n\n let h: i32 = src.height;\n\n\n\n // if gamma < 0.01 || gamma > 9.99{\n\n // return Err(format!(\"Incorrect gamma value {}. Must be in range 0.01 - 9.99.\", gamma));\n\n // }\n\n // let factor = 255.0 * factor;\n\n\n\n for y in 0..h {\n\n for x in 0..w {\n\n let p = src.get_pixel(x, y)?;\n\n let r = cmp::max(0, cmp::min(255, (p.r as f32 * factor) as i32));\n\n let g = cmp::max(0, cmp::min(255, (p.g as f32 * factor) as i32));\n\n let b = cmp::max(0, cmp::min(255, (p.b as f32 * factor) as i32));\n\n // TODO: Should alpha be included?\n\n let a = cmp::max(0, cmp::min(255, (p.a as f32 * factor) as i32));\n\n\n\n src.set_pixel(x, y, &Color::rgba(r as u8, g as u8, b as u8, a as u8))?;\n\n }\n\n }\n\n\n\n Ok(())\n\n}\n\n\n", "file_path": "src/filter.rs", "rank": 15, "score": 140697.43364843854 }, { "content": "/// Change saturation.\n\n///\n\n/// Pass a float value for sat. < 0.0 to decrease and > 0.0 to increase. Eg 0.5 for 50% increase\n\n/// in saturation.\n\n///\n\n/// Note: Saturation does not look good at the moment.\n\n///\n\n/// # Examples\n\n/// ```\n\n/// use raster::filter;\n\n///\n\n/// // Create image from file\n\n/// let mut image = raster::open(\"tests/in/sample.png\").unwrap();\n\n/// filter::saturation(&mut image, 0.5).unwrap();\n\n/// raster::save(&image, \"tests/out/test_filter_saturation.jpg\").unwrap();\n\n/// ```\n\n///\n\n/// ### Before\n\n/// ![](https://kosinix.github.io/raster/in/sample.png)\n\n///\n\n/// ### After\n\n/// ![](https://kosinix.github.io/raster/out/test_filter_saturation.jpg)\n\n///\n\npub fn saturation(src: &mut Image, sat: f32) -> RasterResult<()> {\n\n let w: i32 = src.width;\n\n let h: i32 = src.height;\n\n\n\n for y in 0..h {\n\n for x in 0..w {\n\n let p = src.get_pixel(x, y)?;\n\n let hsv = Color::to_hsv(p.r, p.g, p.b);\n\n let s = hsv.1;\n\n let factor = (100.0 - s) * sat; // use % remaining\n\n let mut new_s = s + factor;\n\n if new_s > 100.0 {\n\n new_s = 100.0;\n\n } else if new_s < 0.0 {\n\n new_s = 0.0;\n\n }\n\n let rgb = Color::to_rgb(hsv.0, new_s, hsv.2);\n\n\n\n src.set_pixel(x, y, &Color::rgb(rgb.0, rgb.1, rgb.2))?;\n\n }\n\n }\n\n\n\n Ok(())\n\n}\n\n\n", "file_path": "src/filter.rs", "rank": 16, "score": 140696.975036934 }, { "content": "/// Apply a convolution matrix.\n\n///\n\n/// The divisor is applied as the last step of convolution.\n\n///\n\n/// # Examples\n\n/// ```\n\n/// use raster::filter;\n\n///\n\n/// // Create image from file\n\n/// let mut image = raster::open(\"tests/in/sample.jpg\").unwrap();\n\n/// let matrix: [[i32; 3]; 3] = [\n\n/// [0, 0, 0],\n\n/// [0, 1, 0],\n\n/// [0, 0, 0]\n\n/// ];\n\n/// filter::convolve(&mut image, matrix, 1).unwrap();\n\n/// raster::save(&image, \"tests/out/test_filter_convolve.jpg\").unwrap();\n\n/// ```\n\npub fn convolve(src: &mut Image, matrix: [[i32; 3]; 3], divisor: i32) -> RasterResult<()> {\n\n let w: i32 = src.width;\n\n let h: i32 = src.height;\n\n let m_size = 3; // Matrix size\n\n\n\n let copy = src.clone(); // Create a copy as input of pixels\n\n\n\n for y in 0..h {\n\n for x in 0..w {\n\n let mstarty = y - 1;\n\n let mstartx = x - 1;\n\n\n\n let mut accum_red: i32 = 0;\n\n let mut accum_green: i32 = 0;\n\n let mut accum_blue: i32 = 0;\n\n let mut accum_alpha: i32 = 0;\n\n\n\n for (m_index_y, mut src_y) in (0..).zip(mstarty..mstarty + m_size) {\n\n if src_y < 0 {\n\n src_y = 0;\n", "file_path": "src/filter.rs", "rank": 17, "score": 140566.93413169688 }, { "content": "fn ch_alpha(base: f32, top: f32, opacity: f32) -> f32 {\n\n (opacity * top) + ((1.0 - opacity) * base)\n\n}\n\n\n", "file_path": "src/blend.rs", "rank": 18, "score": 140435.3127765729 }, { "content": "/// Flip an image on its x or y axis.\n\n///\n\n/// # Examples\n\n///\n\n/// ### Flip X:\n\n///\n\n/// ```\n\n/// use raster::{transform, TransformMode};\n\n///\n\n/// //...\n\n///\n\n/// let mut image = raster::open(\"tests/in/sample.png\").unwrap();\n\n/// transform::flip(&mut image, TransformMode::Horizontal).unwrap();\n\n/// raster::save(&image, \"tests/out/test_transform_flip_x.png\").unwrap();\n\n/// ```\n\n///\n\n/// ![](https://kosinix.github.io/raster/out/test_transform_flip_x.png)\n\n///\n\n/// ### Flip Y:\n\n///\n\n/// ```\n\n/// use raster::{transform, TransformMode};\n\n///\n\n/// //...\n\n///\n\n/// let mut image = raster::open(\"tests/in/sample.png\").unwrap();\n\n/// transform::flip(&mut image, TransformMode::Vertical).unwrap();\n\n/// raster::save(&image, \"tests/out/test_transform_flip_y.png\").unwrap();\n\n/// ```\n\n///\n\n/// ![](https://kosinix.github.io/raster/out/test_transform_flip_y.png)\n\n///\n\npub fn flip(src: &mut Image, mode: TransformMode) -> RasterResult<()> {\n\n let w: i32 = src.width;\n\n let h: i32 = src.height;\n\n\n\n match mode {\n\n TransformMode::Horizontal => {\n\n for x in 0..w {\n\n let src_x = x;\n\n let dest_x = w - x - 1;\n\n if dest_x <= src_x {\n\n break;\n\n }\n\n for y in 0..h {\n\n let pixel_left = src.get_pixel(src_x, y)?;\n\n let pixel_right = src.get_pixel(dest_x, y)?;\n\n\n\n src.set_pixel(dest_x, y, &pixel_left)?;\n\n src.set_pixel(src_x, y, &pixel_right)?;\n\n }\n\n }\n", "file_path": "src/transform.rs", "rank": 20, "score": 128795.11973529201 }, { "content": "fn rgb_max(r: f32, g: f32, b: f32) -> f32 {\n\n let max = if g > r { g } else { r };\n\n\n\n if b > max {\n\n b\n\n } else {\n\n max\n\n }\n\n}\n", "file_path": "src/color.rs", "rank": 21, "score": 125953.13134488388 }, { "content": "fn rgb_min(r: f32, g: f32, b: f32) -> f32 {\n\n let min = if g < r { g } else { r };\n\n\n\n if b < min {\n\n b\n\n } else {\n\n min\n\n }\n\n}\n\n\n", "file_path": "src/color.rs", "rank": 22, "score": 125953.13134488388 }, { "content": "fn ch_overlay(base: f32, top: f32) -> f32 {\n\n if base < 128.0 {\n\n 2.0 * base * top / 255.0\n\n } else {\n\n 255.0 - ((2.0 * (255.0 - base)) * (255.0 - top) / 255.0)\n\n }\n\n}\n\n\n", "file_path": "src/blend.rs", "rank": 23, "score": 121403.40552278413 }, { "content": "fn ch_screen(base: f32, top: f32) -> f32 {\n\n 255.0 - (((255.0 - base) * (255.0 - top)) / 255.0)\n\n}\n", "file_path": "src/blend.rs", "rank": 24, "score": 121403.40552278413 }, { "content": "fn ch_difference(base: f32, top: f32) -> f32 {\n\n (base - top).abs()\n\n}\n\n\n", "file_path": "src/blend.rs", "rank": 25, "score": 121403.40552278413 }, { "content": "fn ch_multiply(base: f32, top: f32) -> f32 {\n\n (base * top) / 255.0\n\n}\n\n\n", "file_path": "src/blend.rs", "rank": 26, "score": 121403.40552278413 }, { "content": "pub fn difference(\n\n image1: &Image,\n\n image2: &Image,\n\n loop_start_y: i32,\n\n loop_end_y: i32,\n\n loop_start_x: i32,\n\n loop_end_x: i32,\n\n offset_x: i32,\n\n offset_y: i32,\n\n opacity: f32,\n\n) -> RasterResult<Image> {\n\n let mut canvas = image1.clone();\n\n\n\n for y in loop_start_y..loop_end_y {\n\n for x in loop_start_x..loop_end_x {\n\n let canvas_x = x + offset_x;\n\n let canvas_y = y + offset_y;\n\n let rgba1 = image1.get_pixel(canvas_x, canvas_y)?;\n\n let a1 = rgba1.a as f32 / 255.0; // convert to 0.0 - 1.0\n\n let r1 = rgba1.r as f32 * a1;\n", "file_path": "src/blend.rs", "rank": 27, "score": 119043.74319876324 }, { "content": "pub fn screen(\n\n image1: &Image,\n\n image2: &Image,\n\n loop_start_y: i32,\n\n loop_end_y: i32,\n\n loop_start_x: i32,\n\n loop_end_x: i32,\n\n offset_x: i32,\n\n offset_y: i32,\n\n opacity: f32,\n\n) -> RasterResult<Image> {\n\n let mut canvas = image1.clone();\n\n\n\n for y in loop_start_y..loop_end_y {\n\n for x in loop_start_x..loop_end_x {\n\n let canvas_x = x + offset_x;\n\n let canvas_y = y + offset_y;\n\n let rgba1 = image1.get_pixel(canvas_x, canvas_y)?;\n\n let a1 = rgba1.a as f32 / 255.0; // convert to 0.0 - 1.0\n\n let r1 = rgba1.r as f32 * a1;\n", "file_path": "src/blend.rs", "rank": 28, "score": 119043.74319876324 }, { "content": "pub fn overlay(\n\n image1: &Image,\n\n image2: &Image,\n\n loop_start_y: i32,\n\n loop_end_y: i32,\n\n loop_start_x: i32,\n\n loop_end_x: i32,\n\n offset_x: i32,\n\n offset_y: i32,\n\n opacity: f32,\n\n) -> RasterResult<Image> {\n\n let mut canvas = image1.clone();\n\n\n\n for y in loop_start_y..loop_end_y {\n\n for x in loop_start_x..loop_end_x {\n\n let canvas_x = x + offset_x;\n\n let canvas_y = y + offset_y;\n\n let rgba1 = image1.get_pixel(canvas_x, canvas_y)?;\n\n let a1 = rgba1.a as f32 / 255.0; // convert to 0.0 - 1.0\n\n let r1 = rgba1.r as f32 * a1;\n", "file_path": "src/blend.rs", "rank": 29, "score": 119043.74319876324 }, { "content": "pub fn multiply(\n\n image1: &Image,\n\n image2: &Image,\n\n loop_start_y: i32,\n\n loop_end_y: i32,\n\n loop_start_x: i32,\n\n loop_end_x: i32,\n\n offset_x: i32,\n\n offset_y: i32,\n\n opacity: f32,\n\n) -> RasterResult<Image> {\n\n let mut canvas = image1.clone();\n\n\n\n for y in loop_start_y..loop_end_y {\n\n for x in loop_start_x..loop_end_x {\n\n let canvas_x = x + offset_x;\n\n let canvas_y = y + offset_y;\n\n let rgba1 = image1.get_pixel(canvas_x, canvas_y)?;\n\n let a1 = rgba1.a as f32 / 255.0; // convert to 0.0 - 1.0\n\n let r1 = rgba1.r as f32 * a1;\n", "file_path": "src/blend.rs", "rank": 30, "score": 119043.74319876324 }, { "content": "pub fn normal(\n\n image1: &Image,\n\n image2: &Image,\n\n loop_start_y: i32,\n\n loop_end_y: i32,\n\n loop_start_x: i32,\n\n loop_end_x: i32,\n\n offset_x: i32,\n\n offset_y: i32,\n\n opacity: f32,\n\n) -> RasterResult<Image> {\n\n let mut canvas = image1.clone();\n\n\n\n for y in loop_start_y..loop_end_y {\n\n for x in loop_start_x..loop_end_x {\n\n let canvas_x = x + offset_x;\n\n let canvas_y = y + offset_y;\n\n let color1 = image1.get_pixel(canvas_x, canvas_y)?;\n\n let a1 = color1.a as f32 / 255.0; // convert to 0.0 - 1.0\n\n let r1 = color1.r as f32 * a1;\n", "file_path": "src/blend.rs", "rank": 31, "score": 119043.74319876324 }, { "content": "/// Create an image from an image file.\n\n///\n\n/// # Errors\n\n///\n\n/// This function can return `RasterError::Io`, `RasterError::Decode`, or\n\n/// `RasterError::UnsupportedFormat` upon failure.\n\n/// See error module for more info.\n\n///\n\n/// # Examples\n\n///\n\n/// ```\n\n/// // Create an image from file\n\n/// let image = raster::open(\"tests/in/sample.png\").unwrap();\n\n/// println!(\"{:?}\", image.bytes);\n\n/// ```\n\npub fn open(image_file: &str) -> RasterResult<Image> {\n\n let path = Path::new(image_file);\n\n let ext = path.extension()\n\n .and_then(|s| s.to_str())\n\n .map_or(\"\".to_string(), |s| s.to_ascii_lowercase());\n\n\n\n // Open the file with basic error check\n\n let file = File::open(image_file)?;\n\n\n\n match &ext[..] {\n\n \"gif\" => Ok(endec::decode_gif(&file)?),\n\n \"jpg\" | \"jpeg\" => {\n\n let src = piston_image::open(image_file)?;\n\n let (w, h) = src.dimensions();\n\n let mut bytes = Vec::with_capacity((w * h) as usize * 4);\n\n for y in 0..h {\n\n for x in 0..w {\n\n let p = src.get_pixel(x, y);\n\n bytes.extend_from_slice(&p.data[0..4]);\n\n }\n", "file_path": "src/lib.rs", "rank": 32, "score": 117745.18746270871 }, { "content": "/// Save an image to an image file. The image type is detected from the file extension of the file\n\n/// name.\n\n///\n\n/// # Errors\n\n///\n\n/// This function can return `RasterError::Io`, `RasterError::Encode`, or\n\n/// `RasterError::UnsupportedFormat` upon failure.\n\n/// See error module for more info.\n\n///\n\n/// # Examples\n\n///\n\n/// ```\n\n/// // Create an image from file\n\n/// let image = raster::open(\"tests/in/sample.png\").unwrap();\n\n/// raster::save(&image, \"tests/out/test.png\").unwrap();\n\n/// ```\n\npub fn save(image: &Image, out: &str) -> RasterResult<()> {\n\n let path = Path::new(out);\n\n let ext = path.extension()\n\n .and_then(|s| s.to_str())\n\n .map_or(\"\".to_string(), |s| s.to_ascii_lowercase());\n\n\n\n match &ext[..] {\n\n \"gif\" => Ok(endec::encode_gif(&image, &path)?),\n\n \"jpg\" | \"jpeg\" => {\n\n piston_image::save_buffer(\n\n &path,\n\n &image.bytes,\n\n image.width as u32,\n\n image.height as u32,\n\n piston_image::RGBA(8),\n\n ).map_err(|_| RasterError::Encode(ImageFormat::Jpeg, \"Format\".to_string()))\n\n }\n\n \"png\" => Ok(endec::encode_png(&image, &path)?),\n\n _ => Err(RasterError::UnsupportedFormat(ext)),\n\n }\n\n}\n", "file_path": "src/lib.rs", "rank": 33, "score": 117380.60247540555 }, { "content": "// Decode GIF\n\npub fn decode_gif(image_file: &File) -> RasterResult<Image> {\n\n let mut decoder = gif::Decoder::new(image_file);\n\n\n\n // Configure the decoder such that it will expand the image to RGBA.\n\n gif::SetParameter::set(&mut decoder, gif::ColorOutput::RGBA);\n\n\n\n // Read the file header\n\n let mut reader = decoder.read_info()?;\n\n\n\n // Read frame 1.\n\n // TODO: Work on all frames\n\n if let Some(_) = reader.next_frame_info()? {\n\n let mut bytes = vec![0; reader.buffer_size()];\n\n reader.read_into_buffer(&mut bytes)?;\n\n Ok(Image {\n\n width: reader.width() as i32,\n\n height: reader.height() as i32,\n\n bytes: bytes,\n\n })\n\n } else {\n\n Err(RasterError::Decode(\n\n ImageFormat::Gif,\n\n \"Error getting frame info\".to_string(),\n\n ))\n\n }\n\n}\n\n\n", "file_path": "src/endec.rs", "rank": 34, "score": 115571.191600724 }, { "content": "// Decode PNG\n\npub fn decode_png(image_file: &File) -> RasterResult<Image> {\n\n let decoder = png::Decoder::new(image_file);\n\n let (info, mut reader) = decoder.read_info()?;\n\n let mut bytes = vec![0; info.buffer_size()];\n\n\n\n reader.next_frame(&mut bytes)?;\n\n\n\n if info.color_type == png::ColorType::RGB {\n\n // Applies only to RGB\n\n\n\n let mut insert_count = 0;\n\n let len = (info.width * info.height) as usize;\n\n for i in 0..len {\n\n // TODO: This is slow!\n\n let insert_pos = 3 * (i + 1) + insert_count;\n\n bytes.insert(insert_pos, 255);\n\n insert_count += 1;\n\n }\n\n } // TODO other ::ColorType\n\n Ok(Image {\n\n width: info.width as i32,\n\n height: info.height as i32,\n\n bytes: bytes,\n\n })\n\n}\n\n\n", "file_path": "src/endec.rs", "rank": 35, "score": 115571.191600724 }, { "content": "// Encode PNG\n\npub fn encode_png(image: &Image, path: &Path) -> RasterResult<()> {\n\n // Open the file with basic error check\n\n let file = File::create(path)?;\n\n let ref mut w = BufWriter::new(file);\n\n\n\n let mut encoder = png::Encoder::new(w, image.width as u32, image.height as u32);\n\n png::HasParameters::set(&mut encoder, png::ColorType::RGBA);\n\n png::HasParameters::set(&mut encoder, png::BitDepth::Eight);\n\n let mut writer = encoder.write_header()?;\n\n Ok(writer.write_image_data(&image.bytes)?)\n\n}\n", "file_path": "src/endec.rs", "rank": 36, "score": 112887.63185566312 }, { "content": "// Encode GIF\n\npub fn encode_gif(image: &Image, path: &Path) -> RasterResult<()> {\n\n // Open the file with basic error check\n\n let file = File::create(path)?;\n\n let writer = BufWriter::new(file);\n\n let frame = gif::Frame::from_rgba(\n\n image.width as u16,\n\n image.height as u16,\n\n &mut image.bytes.clone(),\n\n ); // TODO: Perf issue?\n\n let mut encoder = gif::Encoder::new(writer, frame.width, frame.height, &[])?;\n\n encoder.write_frame(&frame).map_err(RasterError::Io)?;\n\n Ok(())\n\n}\n\n\n", "file_path": "src/endec.rs", "rank": 37, "score": 112887.63185566312 }, { "content": "/// Turn into grayscale image.\n\n///\n\n/// # Examples\n\n/// ```\n\n/// use raster::filter;\n\n///\n\n/// let mut image = raster::open(\"tests/in/sample.jpg\").unwrap();\n\n/// filter::grayscale(&mut image).unwrap();\n\n/// raster::save(&image, \"tests/out/test_filter_grayscale.jpg\").unwrap();\n\n/// ```\n\n///\n\n/// ### Before\n\n/// ![](https://kosinix.github.io/raster/in/sample.jpg)\n\n///\n\n/// ### After\n\n/// ![](https://kosinix.github.io/raster/out/test_filter_grayscale.jpg)\n\n///\n\npub fn grayscale(src: &mut Image) -> RasterResult<()> {\n\n let w: i32 = src.width;\n\n let h: i32 = src.height;\n\n\n\n for y in 0..h {\n\n for x in 0..w {\n\n let p = src.get_pixel(x, y)?;\n\n let gray = (p.r as f32 * 0.3) + (p.g as f32 * 0.59) + (p.b as f32 * 0.11);\n\n\n\n src.set_pixel(\n\n x,\n\n y,\n\n &Color::rgba(gray as u8, gray as u8, gray as u8, gray as u8),\n\n )?;\n\n }\n\n }\n\n\n\n Ok(())\n\n}\n\n\n", "file_path": "src/filter.rs", "rank": 38, "score": 111863.0890448471 }, { "content": "/// Apply sharpen.\n\n///\n\n/// # Examples\n\n/// ```\n\n/// use raster::filter;\n\n///\n\n/// // Create image from file\n\n/// let mut image = raster::open(\"tests/in/sample.jpg\").unwrap();\n\n/// filter::sharpen(&mut image).unwrap();\n\n/// raster::save(&image, \"tests/out/test_filter_sharpen.jpg\").unwrap();\n\n/// ```\n\n/// ### Before\n\n/// ![](https://kosinix.github.io/raster/in/sample.jpg)\n\n///\n\n/// ### After\n\n/// ![](https://kosinix.github.io/raster/out/test_filter_sharpen.jpg)\n\n///\n\npub fn sharpen(src: &mut Image) -> RasterResult<()> {\n\n let matrix: [[i32; 3]; 3] = [[0, -1, 0], [-1, 5, -1], [0, -1, 0]];\n\n convolve(src, matrix, 1)\n\n}\n\n\n\n// Private functions\n\n\n", "file_path": "src/filter.rs", "rank": 39, "score": 111862.97882512765 }, { "content": "/// Apply emboss.\n\n///\n\n/// # Examples\n\n/// ```\n\n/// use raster::filter;\n\n///\n\n/// // Create image from file\n\n/// let mut image = raster::open(\"tests/in/sample.jpg\").unwrap();\n\n/// filter::emboss(&mut image).unwrap();\n\n/// raster::save(&image, \"tests/out/test_filter_emboss.jpg\").unwrap();\n\n/// ```\n\n///\n\n/// ### Before\n\n/// ![](https://kosinix.github.io/raster/in/sample.jpg)\n\n///\n\n/// ### After\n\n/// ![](https://kosinix.github.io/raster/out/test_filter_emboss.jpg)\n\n///\n\npub fn emboss(src: &mut Image) -> RasterResult<()> {\n\n let matrix: [[i32; 3]; 3] = [[-2, -1, 0], [-1, 1, 1], [0, 1, 2]];\n\n convolve(src, matrix, 1)\n\n}\n\n\n", "file_path": "src/filter.rs", "rank": 40, "score": 111862.97882512765 }, { "content": "/// Interpolate the width using linear function.\n\nfn bilinear_width(src: &mut Image, w2: i32) -> RasterResult<()> {\n\n let w1 = src.width;\n\n let h1 = src.height;\n\n\n\n let x_ratio: f64 = w1 as f64 / w2 as f64;\n\n\n\n let mut dest = Image::blank(w2, h1);\n\n\n\n let offset_x = (w2 / w1 / 2) as i32;\n\n\n\n let x_start = 0 - offset_x;\n\n let x_end = w2 - offset_x;\n\n\n\n for y in 0..h1 {\n\n for x in x_start..x_end {\n\n let src_x = {\n\n let src_x = x as f64 * x_ratio;\n\n if src_x < 0.0 {\n\n 0.0 // limit lower bound to 0\n\n } else {\n", "file_path": "src/interpolate.rs", "rank": 41, "score": 106910.11581408793 }, { "content": "/// Interpolate the height using linear function.\n\nfn bilinear_height(src: &mut Image, h2: i32) -> RasterResult<()> {\n\n let w1 = src.width;\n\n let h1 = src.height;\n\n\n\n let y_ratio: f64 = h1 as f64 / h2 as f64;\n\n\n\n let mut dest = Image::blank(w1, h2);\n\n\n\n let offset_y = (h2 / h1 / 2) as i32;\n\n\n\n let y_start = 0 - offset_y;\n\n let y_end = h2 - offset_y;\n\n\n\n for x in 0..w1 {\n\n for y in y_start..y_end {\n\n let src_y = {\n\n let src_y = y as f64 * y_ratio;\n\n if src_y < 0.0 {\n\n 0.0 // limit lower bound to 0\n\n } else {\n", "file_path": "src/interpolate.rs", "rank": 42, "score": 106910.11581408793 }, { "content": "/// Apply Sobel edge detection.\n\n///\n\n/// # Examples\n\n/// ```\n\n/// use raster::{filter, Orientation};\n\n///\n\n/// // Create image from file\n\n/// let mut image = raster::open(\"tests/in/sample.jpg\").unwrap();\n\n/// filter::sobel(&mut image, Orientation::Horizontal).unwrap();\n\n/// raster::save(&image, \"tests/out/test_filter_sobel_x.jpg\").unwrap();\n\n/// ```\n\n///\n\n/// ### Before\n\n/// ![](https://kosinix.github.io/raster/in/sample.jpg)\n\n///\n\n/// ### After\n\n/// ![](https://kosinix.github.io/raster/out/test_filter_sobel_x.jpg)\n\n///\n\npub fn sobel(src: &mut Image, mode: Orientation) -> RasterResult<()> {\n\n grayscale(src)?;\n\n let matrix = match mode {\n\n Orientation::Horizontal => [[-1, 0, 1], [-2, 0, 2], [-1, 0, 1]],\n\n Orientation::Vertical => [[-1, -2, -1], [0, 0, 0], [1, 2, 1]],\n\n Orientation::DiagonalUp => [[0, -1, -2], [1, 0, -1], [2, 1, 0]],\n\n Orientation::DiagonalDown => [[-2, -1, 0], [-1, 0, 1], [0, 1, 2]],\n\n Orientation::Both => {\n\n return sobel_both(\n\n src,\n\n [[-1, 0, 1], [-2, 0, 2], [-1, 0, 1]],\n\n [[-1, -2, -1], [0, 0, 0], [1, 2, 1]],\n\n )\n\n }\n\n Orientation::DiagonalBoth => {\n\n return sobel_both(\n\n src,\n\n [[0, -1, -2], [1, 0, -1], [2, 1, 0]],\n\n [[-2, -1, 0], [-1, 0, 1], [0, 1, 2]],\n\n )\n\n }\n\n };\n\n convolve(src, matrix, 1)\n\n}\n\n\n", "file_path": "src/filter.rs", "rank": 43, "score": 102260.95465714848 }, { "content": "/// Apply box or Gaussian blur.\n\n///\n\n/// # Examples\n\n/// ### Box Blur\n\n///\n\n/// ```\n\n/// use raster::{filter, BlurMode};\n\n///\n\n/// // Create image from file\n\n/// let mut image = raster::open(\"tests/in/sample.jpg\").unwrap();\n\n/// filter::blur(&mut image, BlurMode::Box).unwrap();\n\n/// raster::save(&image, \"tests/out/test_filter_box_blur.jpg\").unwrap();\n\n/// ```\n\n/// ### Before\n\n/// ![](https://kosinix.github.io/raster/in/sample.jpg)\n\n///\n\n/// ### After\n\n/// ![](https://kosinix.github.io/raster/out/test_filter_box_blur.jpg)\n\n///\n\n/// ### Gaussian Blur\n\n///\n\n/// ```\n\n/// use raster::{filter, BlurMode};\n\n///\n\n/// // Create image from file\n\n/// let mut image = raster::open(\"tests/in/sample.jpg\").unwrap();\n\n/// filter::blur(&mut image, BlurMode::Gaussian).unwrap();\n\n/// raster::save(&image, \"tests/out/test_filter_gaussian_blur.jpg\").unwrap();\n\n/// ```\n\n/// ### Before\n\n/// ![](https://kosinix.github.io/raster/in/sample.jpg)\n\n///\n\n/// ### After\n\n/// ![](https://kosinix.github.io/raster/out/test_filter_gaussian_blur.jpg)\n\n///\n\npub fn blur(src: &mut Image, mode: BlurMode) -> RasterResult<()> {\n\n match mode {\n\n BlurMode::Box => blur_box(src),\n\n BlurMode::Gaussian => blur_gaussian(src),\n\n }\n\n}\n\n\n", "file_path": "src/filter.rs", "rank": 44, "score": 100238.73385603413 }, { "content": "/// Resample an image into a new size using a given interpolation method.\n\npub fn resample(\n\n src: &mut Image,\n\n w: i32,\n\n h: i32,\n\n interpolation: InterpolationMode,\n\n) -> RasterResult<()> {\n\n match interpolation {\n\n InterpolationMode::Bilinear => bilinear(src, w, h),\n\n InterpolationMode::Bicubic => bilinear(src, w, h), // TODO: bicubic\n\n InterpolationMode::Nearest => nearest(src, w, h),\n\n }\n\n}\n\n\n", "file_path": "src/interpolate.rs", "rank": 46, "score": 91696.4234875862 }, { "content": "// DifferenceHash\n\n//\n\n// Algorithm:\n\n// Reduce size. The fastest way to remove high frequencies and detail is to shrink the image. In\n\n// this case, shrink it to 9x8 so that there are 72 total pixels. Reduce color. Convert the image\n\n// to a grayscale picture. This changes the hash from 72 pixels to a total of 72 colors. Compute\n\n// the difference. The algorithm works on the difference between adjacent pixels. This identifies\n\n// the relative gradient direction. In this case, the 9 pixels per row yields 8 differences\n\n// between adjacent pixels. Eight rows of eight differences becomes 64 bits. Assign bits. Each bit\n\n// is simply set based on whether the left pixel is brighter than the right pixel.\n\n//\n\n// http://www.hackerfactor.com/blog/index.php?/archives/529-Kind-of-Like-That.html\n\n//\n\n//\n\nfn diff_hash(image: &Image) -> RasterResult<Vec<u8>> {\n\n let width = 9;\n\n let height = 8;\n\n\n\n let mut image = image.clone(); // copy it since resize is desctructive\n\n editor::resize(&mut image, width, height, ResizeMode::Exact)?; // Resize to exactly 9x8\n\n\n\n // Build hash\n\n let mut hash = Vec::new();\n\n for y in 0..height {\n\n // Get the pixel value for the leftmost pixel.\n\n let pixel = image.get_pixel(0, y)?;\n\n let mut left = ((pixel.r as f32 + pixel.g as f32 + pixel.b as f32) / 3.0).floor();\n\n\n\n // Get the pixel value for each pixel starting from position 1.\n\n for x in 1..width {\n\n let pixel = image.get_pixel(x, y)?;\n\n let right = ((pixel.r as f32 + pixel.g as f32 + pixel.b as f32) / 3.0).floor();\n\n // Each hash bit is set based on whether the left pixel is brighter than the right\n\n // pixel.\n", "file_path": "src/compare.rs", "rank": 47, "score": 78932.0519855646 }, { "content": "// Box\n\nfn blur_box(src: &mut Image) -> RasterResult<()> {\n\n let matrix: [[i32; 3]; 3] = [[1, 1, 1], [1, 1, 1], [1, 1, 1]];\n\n convolve(src, matrix, 9)\n\n}\n\n\n", "file_path": "src/filter.rs", "rank": 48, "score": 74145.23345199291 }, { "content": "// Gaussian\n\nfn blur_gaussian(src: &mut Image) -> RasterResult<()> {\n\n let matrix: [[i32; 3]; 3] = [[1, 2, 1], [2, 4, 2], [1, 2, 1]];\n\n convolve(src, matrix, 16)\n\n}\n", "file_path": "src/filter.rs", "rank": 49, "score": 74145.23345199291 }, { "content": "// Convert a hex string to decimal. Eg. \"00\" -> 0. \"FF\" -> 255.\n\nfn _hex_dec(hex_string: &str) -> RasterResult<u8> {\n\n u8::from_str_radix(hex_string, 16)\n\n .map(|o| o as u8)\n\n .map_err(RasterError::HexParse)\n\n}\n\n\n", "file_path": "src/color.rs", "rank": 50, "score": 73318.09981294189 }, { "content": "#[test]\n\nfn hsb_test() {\n\n let hsv = Color::to_hsv(50, 50, 100);\n\n\n\n assert_eq!(240, hsv.0);\n\n assert_eq!(50, (hsv.1).round() as i32); // round and cast to integer because float\n\n assert_eq!(39, (hsv.2).round() as i32);\n\n}\n\n\n", "file_path": "tests/color_tests.rs", "rank": 51, "score": 67623.01508155647 }, { "content": "#[test]\n\nfn hex_test() {\n\n // Ok tests\n\n let color = Color::hex(\"#FFFFFF\"); // Opaque white\n\n assert!(color.is_ok());\n\n\n\n let color = Color::hex(\"#00FF007F\"); // Green with 50% opacity\n\n assert!(color.is_ok());\n\n\n\n // Error tests\n\n let color = Color::hex(\"\");\n\n assert!(color.is_err());\n\n\n\n let color = Color::hex(\"#\");\n\n assert!(color.is_err());\n\n\n\n let color = Color::hex(\"#FFF\");\n\n assert!(color.is_err());\n\n}\n", "file_path": "tests/color_tests.rs", "rank": 52, "score": 67623.01508155647 }, { "content": "#[test]\n\nfn conversion_accuracy_test() {\n\n let rgb1 = (127, 70, 60);\n\n let hsv = Color::to_hsv(rgb1.0, rgb1.1, rgb1.2);\n\n let rgb2 = Color::to_rgb(hsv.0, hsv.1, hsv.2);\n\n\n\n assert_eq!(rgb1.0, rgb2.0);\n\n assert_eq!(rgb1.1, rgb2.1);\n\n assert_eq!(rgb1.2, rgb2.2);\n\n}\n\n\n", "file_path": "tests/color_tests.rs", "rank": 53, "score": 65446.59872427922 }, { "content": " BottomRight,\n\n}\n\n\n\n/// Struct for computing position on an image.\n\npub struct Position {\n\n position: PositionMode,\n\n offset_x: i32,\n\n offset_y: i32,\n\n}\n\n\n\nimpl Position {\n\n pub fn new(position: PositionMode, offset_x: i32, offset_y: i32) -> Position {\n\n Position {\n\n position: position,\n\n offset_x: offset_x,\n\n offset_y: offset_y,\n\n }\n\n }\n\n\n\n /// Get X and Y position based on parameters.\n", "file_path": "src/position.rs", "rank": 54, "score": 61703.11914158935 }, { "content": " // Will this ever fail?\n\n pub fn get_x_y(\n\n &self,\n\n canvas_width: i32,\n\n canvas_height: i32,\n\n image_width: i32,\n\n image_height: i32,\n\n ) -> RasterResult<(i32, i32)> {\n\n let offset_x = self.offset_x;\n\n let offset_y = self.offset_y;\n\n\n\n Ok(match self.position {\n\n PositionMode::TopLeft => (offset_x, offset_y),\n\n PositionMode::TopCenter => {\n\n let x = ((canvas_width / 2) - (image_width / 2)) + offset_x;\n\n (x, offset_y)\n\n }\n\n PositionMode::TopRight => {\n\n let x = (canvas_width - image_width) + offset_x;\n\n (x, offset_y)\n", "file_path": "src/position.rs", "rank": 55, "score": 61701.15530258239 }, { "content": "//! A module for computing position on an image.\n\n\n\n// from rust\n\n\n\n// from external crate\n\n\n\n// from local crate\n\nuse error::RasterResult;\n\n\n\n/// Enumeration for different anchor positions.\n\n#[derive(Debug)]\n\npub enum PositionMode {\n\n TopLeft,\n\n TopCenter,\n\n TopRight,\n\n CenterLeft,\n\n Center,\n\n CenterRight,\n\n BottomLeft,\n\n BottomCenter,\n", "file_path": "src/position.rs", "rank": 56, "score": 61698.68819733466 }, { "content": " }\n\n PositionMode::CenterLeft => {\n\n let y = ((canvas_height / 2) - (image_height / 2)) + offset_x;\n\n (offset_x, y)\n\n }\n\n PositionMode::Center => {\n\n let x = ((canvas_width / 2) - (image_width / 2)) + offset_x;\n\n let y = ((canvas_height / 2) - (image_height / 2)) + offset_y;\n\n (x, y)\n\n }\n\n PositionMode::CenterRight => {\n\n let x = (canvas_width - image_width) + offset_x;\n\n let y = ((canvas_height / 2) - (image_height / 2)) + offset_y;\n\n (x, y)\n\n }\n\n PositionMode::BottomLeft => {\n\n let y = (canvas_height - image_height) + offset_y;\n\n (offset_x, y)\n\n }\n\n PositionMode::BottomCenter => {\n", "file_path": "src/position.rs", "rank": 57, "score": 61696.95046999601 }, { "content": " let x = ((canvas_width / 2) - (image_width / 2)) + offset_x;\n\n let y = (canvas_height - image_height) + offset_y;\n\n (x, y)\n\n }\n\n PositionMode::BottomRight => {\n\n let x = (canvas_width - image_width) + offset_y;\n\n let y = (canvas_height - image_height) + offset_y;\n\n (x, y)\n\n }\n\n })\n\n }\n\n}\n", "file_path": "src/position.rs", "rank": 58, "score": 61694.75353770379 }, { "content": "fn sobel_both(\n\n src: &mut Image,\n\n matrix_one: [[i32; 3]; 3],\n\n matrix_two: [[i32; 3]; 3],\n\n) -> RasterResult<()> {\n\n let mut image_x = src.clone();\n\n let mut image_y = src.clone();\n\n convolve(&mut image_x, matrix_one, 1)?;\n\n convolve(&mut image_y, matrix_two, 1)?;\n\n\n\n let w: i32 = src.width;\n\n let h: i32 = src.height;\n\n for y in 0..h {\n\n for x in 0..w {\n\n let pixel_x = image_x.get_pixel(x, y)?;\n\n let pixel_y = image_y.get_pixel(x, y)?;\n\n // Calculate the sum of the derivatives with sqrt((dImage/dx)²+(dImage/dy)²)\n\n let pixel = ((pixel_x.r as f64).powi(2) + (pixel_y.r as f64).powi(2)).sqrt();\n\n src.set_pixel(\n\n x,\n\n y,\n\n &Color::rgba(pixel as u8, pixel as u8, pixel as u8, pixel_x.a as u8),\n\n )?;\n\n }\n\n }\n\n\n\n Ok(())\n\n}\n\n\n", "file_path": "src/filter.rs", "rank": 59, "score": 44062.44666967938 }, { "content": "#[test]\n\nfn sobel_x_test() {\n\n let mut image = raster::open(\"tests/in/sample.jpg\").unwrap();\n\n filter::sobel(&mut image, Orientation::Horizontal).unwrap();\n\n raster::save(&image, \"tests/out/test_filter_sobel_x.jpg\").unwrap();\n\n}\n\n\n", "file_path": "tests/filter_tests.rs", "rank": 60, "score": 41665.11040008723 }, { "content": "#[test]\n\nfn prepare_test() {\n\n let _ = std::fs::create_dir_all(\"./tests/out\"); // Make sure test out dir is present. This might be a symptom that we need better error handling in editor::save\n\n}\n\n\n\n// TODO: test open and save\n", "file_path": "tests/integration_tests.rs", "rank": 61, "score": 41665.11040008723 }, { "content": "#[test]\n\nfn open_fail() {\n\n assert!({\n\n if let Err(_) = raster::open(\"\") {\n\n true\n\n } else {\n\n false\n\n }\n\n });\n\n}\n\n\n", "file_path": "tests/io_tests.rs", "rank": 62, "score": 41665.11040008723 }, { "content": "#[test]\n\nfn unsupported_format() {\n\n let fail = {\n\n match raster::open(\"tests/in/unsupported.txt\") {\n\n Ok(_) => false,\n\n Err(e) => match e {\n\n raster::error::RasterError::UnsupportedFormat(_) => true,\n\n _ => false,\n\n },\n\n }\n\n };\n\n assert!(fail);\n\n}\n\n\n", "file_path": "tests/io_tests.rs", "rank": 63, "score": 41665.11040008723 }, { "content": "#[test]\n\nfn sobel_test() {\n\n let mut image = raster::open(\"tests/in/sample.jpg\").unwrap();\n\n filter::sobel(&mut image, Orientation::Both).unwrap();\n\n raster::save(&image, \"tests/out/test_filter_sobel.jpg\").unwrap();\n\n}\n\n\n", "file_path": "tests/filter_tests.rs", "rank": 64, "score": 41665.11040008723 }, { "content": "#[test]\n\nfn sobel_y_test() {\n\n let mut image = raster::open(\"tests/in/sample.jpg\").unwrap();\n\n filter::sobel(&mut image, Orientation::Vertical).unwrap();\n\n raster::save(&image, \"tests/out/test_filter_sobel_y.jpg\").unwrap();\n\n}\n\n\n", "file_path": "tests/filter_tests.rs", "rank": 65, "score": 41665.11040008723 }, { "content": "#[test]\n\nfn brightness_test() {\n\n let mut image = raster::open(\"tests/in/sample.jpg\").unwrap();\n\n filter::brightness(&mut image, 1.5).unwrap();\n\n raster::save(&image, \"tests/out/test_filter_brightness.jpg\").unwrap();\n\n}\n\n\n", "file_path": "tests/filter_tests.rs", "rank": 66, "score": 41665.11040008723 }, { "content": "#[test]\n\nfn read_png_format() {\n\n let ok = {\n\n if let Ok(_) = raster::open(\"tests/in/sample.png\") {\n\n true\n\n } else {\n\n false\n\n }\n\n };\n\n assert!(ok);\n\n}\n\n\n", "file_path": "tests/io_tests.rs", "rank": 67, "score": 40623.67339819396 }, { "content": "#[test]\n\nfn read_jpg_format() {\n\n let ok = {\n\n if let Ok(_) = raster::open(\"tests/in/sample.jpg\") {\n\n true\n\n } else {\n\n false\n\n }\n\n };\n\n assert!(ok);\n\n}\n\n\n", "file_path": "tests/io_tests.rs", "rank": 68, "score": 40623.67339819396 }, { "content": "#[test]\n\nfn read_gif_format() {\n\n let ok = {\n\n if let Ok(_) = raster::open(\"tests/in/sample.gif\") {\n\n true\n\n } else {\n\n false\n\n }\n\n };\n\n assert!(ok);\n\n}\n\n\n", "file_path": "tests/io_tests.rs", "rank": 69, "score": 40623.67339819396 }, { "content": "#[test]\n\nfn sobel_d2_test() {\n\n let mut image = raster::open(\"tests/in/sample.jpg\").unwrap();\n\n filter::sobel(&mut image, Orientation::DiagonalDown).unwrap();\n\n raster::save(&image, \"tests/out/test_filter_sobel_d2.jpg\").unwrap();\n\n}\n", "file_path": "tests/filter_tests.rs", "rank": 70, "score": 40623.67339819396 }, { "content": "#[test]\n\nfn sobel_d1_test() {\n\n let mut image = raster::open(\"tests/in/sample.jpg\").unwrap();\n\n filter::sobel(&mut image, Orientation::DiagonalUp).unwrap();\n\n raster::save(&image, \"tests/out/test_filter_sobel_d1.jpg\").unwrap();\n\n}\n\n\n", "file_path": "tests/filter_tests.rs", "rank": 71, "score": 40623.67339819396 }, { "content": "#[test]\n\nfn read_gif_format_fail() {\n\n assert!({\n\n if let Err(e) = raster::open(\"tests/in/not-a-gif.gif\") {\n\n if let raster::error::RasterError::Decode(format, _) = e {\n\n assert!({\n\n if let raster::ImageFormat::Gif = format {\n\n // Should be gif\n\n true\n\n } else {\n\n false\n\n }\n\n });\n\n }\n\n true\n\n } else {\n\n false\n\n }\n\n });\n\n}\n\n\n", "file_path": "tests/io_tests.rs", "rank": 72, "score": 39669.49248136525 }, { "content": "#[test]\n\nfn read_png_format_fail() {\n\n assert!({\n\n if let Err(e) = raster::open(\"tests/in/not-a-png.png\") {\n\n if let raster::error::RasterError::Decode(format, _) = e {\n\n assert!({\n\n if let raster::ImageFormat::Png = format {\n\n // Should be png\n\n true\n\n } else {\n\n false\n\n }\n\n });\n\n }\n\n true\n\n } else {\n\n false\n\n }\n\n });\n\n}\n", "file_path": "tests/io_tests.rs", "rank": 73, "score": 39669.49248136525 }, { "content": "#[test]\n\nfn read_jpeg_format_fail() {\n\n assert!({\n\n if let Err(e) = raster::open(\"tests/in/not-a-jpeg.jpg\") {\n\n if let raster::error::RasterError::Decode(format, _) = e {\n\n assert!({\n\n if let raster::ImageFormat::Jpeg = format {\n\n // Should be jpg\n\n true\n\n } else {\n\n false\n\n }\n\n });\n\n }\n\n true\n\n } else {\n\n false\n\n }\n\n });\n\n}\n\n\n", "file_path": "tests/io_tests.rs", "rank": 74, "score": 39669.49248136525 }, { "content": "#[derive(Debug)]\n\nenum BlendFunction {\n\n Difference,\n\n Multiply,\n\n Overlay,\n\n Screen,\n\n}\n\n\n", "file_path": "src/blend.rs", "rank": 75, "score": 35337.70928552925 }, { "content": "// Simple linear function\n\nfn _lerp(a: u8, b: u8, t: f64) -> u8 {\n\n let a = a as f64;\n\n let b = b as f64;\n\n\n\n (a + (t * (b - a))) as u8\n\n}\n\n\n", "file_path": "src/interpolate.rs", "rank": 76, "score": 33177.775518662864 }, { "content": "//! A module for 2D transformation.\n\n\n\n// from rust\n\nuse std::cmp;\n\n\n\n// from external crate\n\n\n\n// from local crate\n\nuse error::RasterResult;\n\nuse Image;\n\nuse Color;\n\nuse interpolate::{resample, InterpolationMode};\n\nuse position::PositionMode;\n\nuse editor::crop;\n\n\n\n/// An enum for the various modes that can be used for transforming.\n\n#[derive(Debug)]\n\npub enum TransformMode {\n\n /// Transform on x axis.\n\n Horizontal,\n", "file_path": "src/transform.rs", "rank": 77, "score": 30512.313901871687 }, { "content": " /// Transform on y axis.\n\n Vertical,\n\n}\n\n\n\n/// Flip an image on its x or y axis.\n\n///\n\n/// # Examples\n\n///\n\n/// ### Flip X:\n\n///\n\n/// ```\n\n/// use raster::{transform, TransformMode};\n\n///\n\n/// //...\n\n///\n\n/// let mut image = raster::open(\"tests/in/sample.png\").unwrap();\n\n/// transform::flip(&mut image, TransformMode::Horizontal).unwrap();\n\n/// raster::save(&image, \"tests/out/test_transform_flip_x.png\").unwrap();\n\n/// ```\n\n///\n", "file_path": "src/transform.rs", "rank": 78, "score": 30503.56845841573 }, { "content": "/// ![](https://kosinix.github.io/raster/out/test_transform_flip_x.png)\n\n///\n\n/// ### Flip Y:\n\n///\n\n/// ```\n\n/// use raster::{transform, TransformMode};\n\n///\n\n/// //...\n\n///\n\n/// let mut image = raster::open(\"tests/in/sample.png\").unwrap();\n\n/// transform::flip(&mut image, TransformMode::Vertical).unwrap();\n\n/// raster::save(&image, \"tests/out/test_transform_flip_y.png\").unwrap();\n\n/// ```\n\n///\n\n/// ![](https://kosinix.github.io/raster/out/test_transform_flip_y.png)\n\n///\n", "file_path": "src/transform.rs", "rank": 79, "score": 30502.829283115097 }, { "content": " let bottom_right_2: (i32, i32) = _rotate(bottom_right_1, degree);\n\n min_x = cmp::min(min_x, bottom_right_2.0);\n\n max_x = cmp::max(max_x, bottom_right_2.0);\n\n min_y = cmp::min(min_y, bottom_right_2.1);\n\n max_y = cmp::max(max_y, bottom_right_2.1);\n\n\n\n let bottom_left_1: (i32, i32) = (0, h1);\n\n let bottom_left_2: (i32, i32) = _rotate(bottom_left_1, degree);\n\n min_x = cmp::min(min_x, bottom_left_2.0);\n\n max_x = cmp::max(max_x, bottom_left_2.0);\n\n min_y = cmp::min(min_y, bottom_left_2.1);\n\n max_y = cmp::max(max_y, bottom_left_2.1);\n\n\n\n let w2 = ((min_x as f32).abs() + (max_x as f32).abs()) as i32 + 1;\n\n let h2 = ((min_y as f32).abs() + (max_y as f32).abs()) as i32 + 1;\n\n let mut dest = Image::blank(w2, h2);\n\n\n\n for (dest_y, y) in (0..).zip(min_y..max_y + 1) {\n\n for (dest_x, x) in (0..).zip(min_x..max_x + 1) {\n\n let point: (i32, i32) = _rotate((x, y), -degree);\n", "file_path": "src/transform.rs", "rank": 80, "score": 30501.84478567722 }, { "content": "\n\n Ok(())\n\n }\n\n TransformMode::Vertical => {\n\n for y in 0..h {\n\n let src_y = y;\n\n let dest_y = h - y - 1;\n\n if dest_y <= src_y {\n\n break;\n\n }\n\n for x in 0..w {\n\n let pixel_top = src.get_pixel(x, src_y)?;\n\n let pixel_bottom = src.get_pixel(x, dest_y)?;\n\n\n\n src.set_pixel(x, dest_y, &pixel_top)?;\n\n src.set_pixel(x, src_y, &pixel_bottom)?;\n\n }\n\n }\n\n\n\n Ok(())\n\n }\n\n }\n\n}\n\n\n", "file_path": "src/transform.rs", "rank": 81, "score": 30496.85076610169 }, { "content": "\n\n if point.0 >= 0 && point.0 < w1 && point.1 >= 0 && point.1 < h1 {\n\n let pixel = src.get_pixel(point.0, point.1)?;\n\n dest.set_pixel(dest_x, dest_y, &pixel)?;\n\n } else {\n\n dest.set_pixel(dest_x, dest_y, &Color::rgba(bg.r, bg.g, bg.b, bg.a))?;\n\n }\n\n }\n\n }\n\n\n\n src.width = dest.width;\n\n src.height = dest.height;\n\n src.bytes = dest.bytes;\n\n\n\n Ok(())\n\n}\n\n\n", "file_path": "src/transform.rs", "rank": 82, "score": 30496.54553883824 }, { "content": "//! A module for blending 2 images.\n\n// See https://en.wikipedia.org/wiki/Alpha_compositing\n\n\n\n// from rust\n\n\n\n// from external crate\n\n\n\n// from local crate\n\nuse error::RasterResult;\n\nuse Image;\n\nuse Color;\n\n\n\n/// Enumeration for blending modes.\n\n#[derive(Debug)]\n\npub enum BlendMode {\n\n Normal,\n\n Difference,\n\n Multiply,\n\n Overlay,\n\n Screen,\n\n}\n\n\n", "file_path": "src/blend.rs", "rank": 83, "score": 30264.485758169016 }, { "content": " let g1 = rgba1.g as f32 * a1;\n\n let b1 = rgba1.b as f32 * a1;\n\n\n\n let rgba2 = image2.get_pixel(x, y)?;\n\n let a2 = rgba2.a as f32 / 255.0 * opacity; // convert to 0.0 - 1.0\n\n let r2 = rgba2.r as f32;\n\n let g2 = rgba2.g as f32;\n\n let b2 = rgba2.b as f32;\n\n\n\n let r3 = ch_alpha_f(r1, r2, BlendFunction::Screen, a2);\n\n let g3 = ch_alpha_f(g1, g2, BlendFunction::Screen, a2);\n\n let b3 = ch_alpha_f(b1, b2, BlendFunction::Screen, a2);\n\n let a3 = 255;\n\n\n\n canvas.set_pixel(\n\n canvas_x,\n\n canvas_y,\n\n &Color::rgba(r3 as u8, g3 as u8, b3 as u8, a3 as u8),\n\n )?;\n\n }\n", "file_path": "src/blend.rs", "rank": 84, "score": 30262.039084690427 }, { "content": " let g1 = rgba1.g as f32 * a1;\n\n let b1 = rgba1.b as f32 * a1;\n\n\n\n let rgba2 = image2.get_pixel(x, y)?;\n\n let a2 = rgba2.a as f32 / 255.0 * opacity; // convert to 0.0 - 1.0\n\n let r2 = rgba2.r as f32;\n\n let g2 = rgba2.g as f32;\n\n let b2 = rgba2.b as f32;\n\n\n\n let r3 = ch_alpha_f(r1, r2, BlendFunction::Overlay, a2);\n\n let g3 = ch_alpha_f(g1, g2, BlendFunction::Overlay, a2);\n\n let b3 = ch_alpha_f(b1, b2, BlendFunction::Overlay, a2);\n\n let a3 = 255;\n\n\n\n canvas.set_pixel(\n\n canvas_x,\n\n canvas_y,\n\n &Color::rgba(r3 as u8, g3 as u8, b3 as u8, a3 as u8),\n\n )?;\n\n }\n\n }\n\n\n\n Ok(canvas)\n\n}\n\n\n", "file_path": "src/blend.rs", "rank": 85, "score": 30261.908310994502 }, { "content": " let g1 = rgba1.g as f32 * a1;\n\n let b1 = rgba1.b as f32 * a1;\n\n\n\n let rgba2 = image2.get_pixel(x, y)?;\n\n let a2 = rgba2.a as f32 / 255.0 * opacity; // convert to 0.0 - 1.0\n\n let r2 = rgba2.r as f32;\n\n let g2 = rgba2.g as f32;\n\n let b2 = rgba2.b as f32;\n\n\n\n let r3 = ch_alpha_f(r1, r2, BlendFunction::Difference, a2);\n\n let g3 = ch_alpha_f(g1, g2, BlendFunction::Difference, a2);\n\n let b3 = ch_alpha_f(b1, b2, BlendFunction::Difference, a2);\n\n let a3 = 255;\n\n\n\n canvas.set_pixel(\n\n canvas_x,\n\n canvas_y,\n\n &Color::rgba(r3 as u8, g3 as u8, b3 as u8, a3 as u8),\n\n )?;\n\n }\n\n }\n\n\n\n Ok(canvas)\n\n}\n\n\n", "file_path": "src/blend.rs", "rank": 86, "score": 30261.908310994502 }, { "content": " let g1 = rgba1.g as f32 * a1;\n\n let b1 = rgba1.b as f32 * a1;\n\n\n\n let rgba2 = image2.get_pixel(x, y)?;\n\n let a2 = rgba2.a as f32 / 255.0 * opacity; // convert to 0.0 - 1.0\n\n let r2 = rgba2.r as f32;\n\n let g2 = rgba2.g as f32;\n\n let b2 = rgba2.b as f32;\n\n\n\n let r3 = ch_alpha_f(r1, r2, BlendFunction::Multiply, a2);\n\n let g3 = ch_alpha_f(g1, g2, BlendFunction::Multiply, a2);\n\n let b3 = ch_alpha_f(b1, b2, BlendFunction::Multiply, a2);\n\n let a3 = 255;\n\n\n\n canvas.set_pixel(\n\n canvas_x,\n\n canvas_y,\n\n &Color::rgba(r3 as u8, g3 as u8, b3 as u8, a3 as u8),\n\n )?;\n\n }\n\n }\n\n\n\n Ok(canvas)\n\n}\n\n\n", "file_path": "src/blend.rs", "rank": 87, "score": 30261.908310994502 }, { "content": " let g1 = color1.g as f32 * a1;\n\n let b1 = color1.b as f32 * a1;\n\n\n\n let color2 = image2.get_pixel(x, y)?;\n\n let a2 = color2.a as f32 / 255.0 * opacity; // convert to 0.0 - 1.0\n\n let r2 = color2.r as f32;\n\n let g2 = color2.g as f32;\n\n let b2 = color2.b as f32;\n\n\n\n let r3 = (a2 * r2) + ((1.0 - a2) * r1);\n\n let g3 = (a2 * g2) + ((1.0 - a2) * g1);\n\n let b3 = (a2 * b2) + ((1.0 - a2) * b1);\n\n let a3 = 255;\n\n\n\n canvas.set_pixel(\n\n canvas_x,\n\n canvas_y,\n\n &Color::rgba(r3 as u8, g3 as u8, b3 as u8, a3 as u8),\n\n )?;\n\n }\n\n }\n\n\n\n Ok(canvas)\n\n}\n\n\n", "file_path": "src/blend.rs", "rank": 88, "score": 30259.980288277537 }, { "content": " }\n\n\n\n Ok(canvas)\n\n}\n\n\n\n// PRIVATE FNs\n\n// base, top 0.0 - 255.0\n\n// opacity 0.0 - 1.0\n\n\n\n/*\n\nThis is the private BlendFunction enum, not to be confused with BlendMode, which is for public\n\nconsumption! BlendFunction differs only in lacking a Normal variant, as ch_alpha_f has no need for\n\nsuch things.\n\n*/\n", "file_path": "src/blend.rs", "rank": 89, "score": 30257.86961493237 }, { "content": "\n\n /// Convert HSV/HSB (Hue, Saturation, Brightness) to RGB.\n\n ///\n\n /// ```\n\n /// use raster::Color;\n\n ///\n\n /// let rgb1 = (127, 70, 60);\n\n /// let hsv = Color::to_hsv(rgb1.0, rgb1.1, rgb1.2); // Convert to HSV\n\n /// let rgb2 = Color::to_rgb(hsv.0, hsv.1, hsv.2); // Convert back to RGB\n\n ///\n\n /// // Check if source RGB is equal to final RGB\n\n /// assert_eq!(rgb1.0, rgb2.0);\n\n /// assert_eq!(rgb1.1, rgb2.1);\n\n /// assert_eq!(rgb1.2, rgb2.2);\n\n /// ```\n\n // Using f32 for s,v for accuracy when converting from RGB-HSV and vice-versa.\n\n pub fn to_rgb(h: u16, s: f32, v: f32) -> (u8, u8, u8) {\n\n let h = h as f32 / 60.0;\n\n let s = s as f32 / 100.0; // Convert to 0.0 - 1.0\n\n let v = v as f32 / 100.0;\n", "file_path": "src/color.rs", "rank": 90, "score": 30094.000554813407 }, { "content": "//! A module for handling colors.\n\n\n\n// from rust\n\nuse std;\n\n\n\n// from external crate\n\n\n\n// from local crate\n\nuse error::{RasterError, RasterResult};\n\n\n\n/// A struct for representing and creating color.\n\n#[derive(Debug, Clone)]\n\npub struct Color {\n\n /// Red channel 0 - 255\n\n pub r: u8,\n\n\n\n /// Green channel 0 - 255\n\n pub g: u8,\n\n\n\n /// Blue channel 0 - 255\n", "file_path": "src/color.rs", "rank": 91, "score": 30093.705482941765 }, { "content": " /// Returns a red Color.\n\n pub fn red() -> Color {\n\n Color {\n\n r: 255,\n\n g: 0,\n\n b: 0,\n\n a: 255,\n\n }\n\n }\n\n\n\n /// Create a RGB color. Alpha defaults to opaque (255).\n\n ///\n\n /// # Examples\n\n ///\n\n /// ```\n\n /// use raster::Color;\n\n ///\n\n /// let rgb = Color::rgb(0, 255, 0); // Green\n\n ///\n\n /// println!(\"{:?}\", rgb);\n", "file_path": "src/color.rs", "rank": 92, "score": 30093.064902316954 }, { "content": " /// assert!(color.is_err());\n\n ///\n\n /// let color = Color::hex(\"#\");\n\n /// assert!(color.is_err());\n\n ///\n\n /// let color = Color::hex(\"#FFF\");\n\n /// assert!(color.is_err());\n\n ///\n\n /// ```\n\n ///\n\n /// To get the value, use unwrap:\n\n ///\n\n /// ```\n\n /// use raster::Color;\n\n ///\n\n /// let color = Color::hex(\"#00FF007F\").unwrap();\n\n /// assert_eq!(255, color.g);\n\n /// ```\n\n pub fn hex(hex: &str) -> RasterResult<Color> {\n\n if hex.len() == 9 && hex.starts_with('#') {\n", "file_path": "src/color.rs", "rank": 93, "score": 30092.900446937583 }, { "content": " pub b: u8,\n\n\n\n /// Alpha channel 0 - 255\n\n pub a: u8,\n\n}\n\n\n\nimpl<'a> Color {\n\n /// Returns a black Color.\n\n pub fn black() -> Color {\n\n Color {\n\n r: 0,\n\n g: 0,\n\n b: 0,\n\n a: 255,\n\n }\n\n }\n\n\n\n /// Returns a blue Color.\n\n pub fn blue() -> Color {\n\n Color {\n", "file_path": "src/color.rs", "rank": 94, "score": 30092.478295549758 }, { "content": " /// ```\n\n // Using f32 for s,v for accuracy when converting from RGB-HSV and vice-versa.\n\n pub fn to_hsv(r: u8, g: u8, b: u8) -> (u16, f32, f32) {\n\n let r = r as f32 / 255.0;\n\n let g = g as f32 / 255.0;\n\n let b = b as f32 / 255.0;\n\n\n\n let min = rgb_min(r, g, b);\n\n let max = rgb_max(r, g, b);\n\n\n\n let chroma = max - min;\n\n\n\n let h = {\n\n let mut h = 0.0;\n\n\n\n if chroma != 0.0 {\n\n if (max - r).abs() < std::f32::EPSILON {\n\n h = 60.0 * ((g - b) / chroma);\n\n if h < 0.0 {\n\n h += 360.0;\n", "file_path": "src/color.rs", "rank": 95, "score": 30092.385765621373 }, { "content": " ///\n\n /// assert_eq!(rgb.r, 0);\n\n /// assert_eq!(rgb.g, 255);\n\n /// assert_eq!(rgb.b, 0);\n\n /// assert_eq!(rgb.a, 255);\n\n /// ```\n\n pub fn rgb(r: u8, g: u8, b: u8) -> Color {\n\n Color { r, g, b, a: 255 }\n\n }\n\n\n\n /// Create a RGBA color.\n\n ///\n\n /// # Examples\n\n ///\n\n /// ```\n\n /// use raster::Color;\n\n ///\n\n /// let rgba = Color::rgba(0, 0, 255, 255); // Blue\n\n ///\n\n /// println!(\"{:?}\", rgba);\n", "file_path": "src/color.rs", "rank": 96, "score": 30092.191844956815 }, { "content": " ///\n\n /// # Errors\n\n ///\n\n /// If the hex *string* is malformed (doesn't begin with `#` or is of invalid length) then this\n\n /// fails with `RasterError::InvalidHex`. If it passes that, but the string can't be parsed\n\n /// into actual values, then this fails with `RasterError::HexParse`.\n\n ///\n\n /// # Examples\n\n /// ```\n\n /// use raster::Color;\n\n ///\n\n /// // Ok tests\n\n /// let color = Color::hex(\"#FFFFFF\"); // Opaque white\n\n /// assert!(color.is_ok());\n\n ///\n\n /// let color = Color::hex(\"#00FF007F\"); // Green with 50% opacity\n\n /// assert!(color.is_ok());\n\n ///\n\n /// // Error tests\n\n /// let color = Color::hex(\"\");\n", "file_path": "src/color.rs", "rank": 97, "score": 30091.463535918436 }, { "content": " r: 0,\n\n g: 0,\n\n b: 255,\n\n a: 255,\n\n }\n\n }\n\n\n\n /// Returns a green Color.\n\n pub fn green() -> Color {\n\n Color {\n\n r: 0,\n\n g: 255,\n\n b: 0,\n\n a: 255,\n\n }\n\n }\n\n\n\n /// Create a color from hexadecimal value.\n\n ///\n\n /// Example of valid formats: #FFFFFF, #ffeecc, #00ff007f\n", "file_path": "src/color.rs", "rank": 98, "score": 30090.998803461596 }, { "content": " ///\n\n /// assert_eq!(rgba.r, 0);\n\n /// assert_eq!(rgba.g, 0);\n\n /// assert_eq!(rgba.b, 255);\n\n /// assert_eq!(rgba.a, 255);\n\n /// ```\n\n pub fn rgba(r: u8, g: u8, b: u8, a: u8) -> Color {\n\n Color { r, g, b, a }\n\n }\n\n\n\n /// Convert RGB to HSV/HSB (Hue, Saturation, Brightness).\n\n ///\n\n /// ```\n\n /// use raster::Color;\n\n ///\n\n /// let hsv = Color::to_hsv(50, 50, 100);\n\n ///\n\n /// assert_eq!(240, hsv.0);\n\n /// assert_eq!(50.0, (hsv.1).round()); // Saturation in float\n\n /// assert_eq!(39.0, (hsv.2).round()); // Brightness in float\n", "file_path": "src/color.rs", "rank": 99, "score": 30090.9616148228 } ]
Rust
src/draw_buffer.rs
GreatAttractor/projections
95c4217162c5841f1f90160c058b279b5423ba5e
use glium::Surface; use glium::texture::{ depth_texture2d_multisample::DepthTexture2dMultisample, depth_texture2d::DepthTexture2d, texture2d_multisample::Texture2dMultisample, texture2d::Texture2d, }; use std::cell::RefCell; use std::rc::Rc; const INITIAL_DRAW_BUF_SIZE: u32 = 256; const COLOR_FORMAT: glium::texture::UncompressedFloatFormat = glium::texture::UncompressedFloatFormat::U8U8U8U8; const DEPTH_FORMAT: glium::texture::DepthFormat = glium::texture::DepthFormat::I24; const NUM_SAMPLES: u32 = 8; #[derive(Copy, Clone, PartialEq)] pub enum Sampling { Single, Multi } enum Buffers { SingleSampling(Texture2d, DepthTexture2d), MultiSampling(Texture2dMultisample, DepthTexture2dMultisample) } impl Buffers { fn sampling(&self) -> Sampling { match self { Buffers::SingleSampling(_, _) => Sampling::Single, Buffers::MultiSampling(_, _) => Sampling::Multi } } } pub struct DrawBuffer { id: imgui::TextureId, renderer: Rc<RefCell<imgui_glium_renderer::Renderer>>, display: glium::Display, draw_bufs: Buffers, storage_buf: Rc<Texture2d>, texture_copy_single_gl_prog: Rc<glium::Program>, texture_copy_multi_gl_prog: Rc<glium::Program>, unit_quad: Rc<glium::VertexBuffer<crate::data::XyVertex>> } impl DrawBuffer { pub fn set_sampling(&mut self, sampling: Sampling) { let (id, draw_bufs, storage_buf) = DrawBuffer::create( sampling, &Some(self.id), self.width(), self.height(), COLOR_FORMAT, &self.display, &mut self.renderer.borrow_mut() ); self.id = id; self.draw_bufs = draw_bufs; self.storage_buf = storage_buf; } pub fn update_storage_buf(&self) { let mut fbo = glium::framebuffer::SimpleFrameBuffer::new(&self.display, &*self.storage_buf).unwrap(); match &self.draw_bufs { Buffers::SingleSampling(draw_buf, _) => { let uniforms = uniform! { source_texture: draw_buf.sampled() }; fbo.draw( &*self.unit_quad, &glium::index::NoIndices(glium::index::PrimitiveType::TriangleFan), &self.texture_copy_single_gl_prog, &uniforms, &Default::default() ).unwrap(); }, Buffers::MultiSampling(draw_buf, _) => { let uniforms = uniform! { source_texture: draw_buf.sampled() }; fbo.draw( &*self.unit_quad, &glium::index::NoIndices(glium::index::PrimitiveType::TriangleFan), &self.texture_copy_multi_gl_prog, &uniforms, &Default::default() ).unwrap(); }, }; } pub fn storage_buf(&self) -> &Rc<Texture2d> { &self.storage_buf } pub fn frame_buf(&self) -> glium::framebuffer::SimpleFrameBuffer { match &self.draw_bufs { Buffers::SingleSampling(draw_buf, depth_buf) => glium::framebuffer::SimpleFrameBuffer::with_depth_buffer( &self.display, draw_buf, depth_buf ).unwrap(), Buffers::MultiSampling(draw_buf, depth_buf) => glium::framebuffer::SimpleFrameBuffer::with_depth_buffer( &self.display, draw_buf, depth_buf ).unwrap() } } pub fn width(&self) -> u32 { self.storage_buf.width() } pub fn height(&self) -> u32 { self.storage_buf.height() } pub fn new( sampling: Sampling, texture_copy_single_gl_prog: &Rc<glium::Program>, texture_copy_multi_gl_prog: &Rc<glium::Program>, unit_quad: &Rc<glium::VertexBuffer<crate::data::XyVertex>>, display: &glium::Display, renderer: &Rc<RefCell<imgui_glium_renderer::Renderer>> ) -> DrawBuffer { let (id, draw_bufs, storage_buf) = DrawBuffer::create( sampling, &None, INITIAL_DRAW_BUF_SIZE, INITIAL_DRAW_BUF_SIZE, COLOR_FORMAT, display, &mut renderer.borrow_mut() ); DrawBuffer { id, display: display.clone(), renderer: Rc::clone(renderer), draw_bufs, storage_buf, unit_quad: Rc::clone(unit_quad), texture_copy_single_gl_prog: Rc::clone(texture_copy_single_gl_prog), texture_copy_multi_gl_prog: Rc::clone(texture_copy_multi_gl_prog) } } pub fn new_with_size( sampling: Sampling, texture_copy_single_gl_prog: &Rc<glium::Program>, texture_copy_multi_gl_prog: &Rc<glium::Program>, unit_quad: &Rc<glium::VertexBuffer<crate::data::XyVertex>>, display: &glium::Display, renderer: &Rc<RefCell<imgui_glium_renderer::Renderer>>, width: u32, height: u32 ) -> DrawBuffer { let (id, draw_bufs, storage_buf) = DrawBuffer::create( sampling, &None, width, height, COLOR_FORMAT, display, &mut renderer.borrow_mut() ); DrawBuffer { id, display: display.clone(), renderer: Rc::clone(renderer), draw_bufs, storage_buf, unit_quad: Rc::clone(unit_quad), texture_copy_single_gl_prog: Rc::clone(texture_copy_single_gl_prog), texture_copy_multi_gl_prog: Rc::clone(texture_copy_multi_gl_prog) } } pub fn id(&self) -> imgui::TextureId { self.id } fn create( sampling: Sampling, prev_id: &Option<imgui::TextureId>, width: u32, height: u32, format: glium::texture::UncompressedFloatFormat, display: &glium::Display, renderer: &mut imgui_glium_renderer::Renderer ) -> (imgui::TextureId, Buffers, Rc<Texture2d>) { let draw_bufs = match sampling { Sampling::Single => Buffers::SingleSampling( Texture2d::empty_with_format( display, format, glium::texture::MipmapsOption::NoMipmap, width, height ).unwrap(), DepthTexture2d::empty_with_format( display, DEPTH_FORMAT, glium::texture::MipmapsOption::NoMipmap, width, height ).unwrap() ), Sampling::Multi => Buffers::MultiSampling( Texture2dMultisample::empty_with_format( display, format, glium::texture::MipmapsOption::NoMipmap, width, height, NUM_SAMPLES ).unwrap(), DepthTexture2dMultisample::empty_with_format( display, DEPTH_FORMAT, glium::texture::MipmapsOption::NoMipmap, width, height, NUM_SAMPLES ).unwrap() ) }; let storage_buf = std::rc::Rc::new(Texture2d::empty_with_format( display, glium::texture::UncompressedFloatFormat::U8U8U8, glium::texture::MipmapsOption::NoMipmap, width, height ).unwrap()); let imgui_tex = imgui_glium_renderer::Texture { texture: storage_buf.clone(), sampler: glium::uniforms::SamplerBehavior { magnify_filter: glium::uniforms::MagnifySamplerFilter::Linear, minify_filter: glium::uniforms::MinifySamplerFilter::Linear, ..Default::default() }, }; let id = match prev_id { None => renderer.textures().insert(imgui_tex), Some(prev_id) => { renderer.textures().replace(*prev_id, imgui_tex); *prev_id } }; (id, draw_bufs, storage_buf) } pub fn update_size( &mut self, width: u32, height: u32 ) -> bool { if width != self.storage_buf.width() || height != self.storage_buf.height() { let (id, draw_bufs, storage_buf) = DrawBuffer::create( self.draw_bufs.sampling(), &Some(self.id), width, height, COLOR_FORMAT, &self.display, &mut self.renderer.borrow_mut() ); self.id = id; self.draw_bufs = draw_bufs; self.storage_buf = storage_buf; true } else { false } } }
use glium::Surface; use glium::texture::{ depth_texture2d_multisample::DepthTexture2dMultisample, depth_texture2d::DepthTexture2d, texture2d_multisample::Texture2dMultisample, texture2d::Texture2d, }; use std::cell::RefCell; use std::rc::Rc; const INITIAL_DRAW_BUF_SIZE: u32 = 256; const COLOR_FORMAT: glium::texture::UncompressedFloatFormat = glium::texture::UncompressedFloatFormat::U8U8U8U8; const DEPTH_FORMAT: glium::texture::DepthFormat = glium::texture::DepthFormat::I24; const NUM_SAMPLES: u32 = 8; #[derive(Copy, Clone, PartialEq)] pub enum Sampling { Single, Multi } enum Buffers { SingleSampling(Texture2d, DepthTexture2d), MultiSampling(Texture2dMultisample, DepthTexture2dMultisample) } impl Buffers { fn sampling(&self) -> Sampling { match self { Buffers::SingleSampling(_, _) => Sampling::Single, Buffers::MultiSampling(_, _) => Sampling::Multi } } } pub struct DrawBuffer { id: imgui::TextureId, renderer: Rc<RefCell<imgui_glium_renderer::Renderer>>, display: glium::Display, draw_bufs: Buffers, storage_buf: Rc<Texture2d>, texture_copy_single_gl_prog: Rc<glium::Program>, texture_copy_multi_gl_prog: Rc<glium::Program>, unit_quad: Rc<glium::VertexBuffer<crate::data::XyVertex>> } impl DrawBuffer { pub fn set_sampling(&mut self, sampling: Sampling) { let (id, draw_bufs, storage_buf) = DrawBuffer::create( sampling, &Some(self.id), self.width(), self.height(), COLOR_FORMAT, &self.display, &mut self.renderer.borrow_mut() ); self.id = id; self.draw_bufs = draw_bufs; self.storage_buf = storage_buf; } pub fn update_storage_buf(&self) { let mut fbo = glium::framebuffer::SimpleFrameBuffer::new(&self.display, &*self.storage_buf).unwrap(); match &self.draw_bufs { Buffers::SingleSampling(draw_buf, _) => { let uniforms = uniform! { source_texture: draw_buf.sampled() }; fbo.draw( &*self.unit_quad, &glium::index::NoIndices(glium::index::PrimitiveType::TriangleFan), &self.texture_copy_single_gl_prog, &uniforms, &Default::default() ).unwrap(); }, Buffers::MultiSampling(draw_buf, _) => { let uniforms = uniform! { source_texture: draw_buf.sampled() }; fbo.draw( &*self.unit_quad, &glium::index::NoIndices(glium::index::PrimitiveType::TriangleFan), &self.texture_copy_multi_gl_prog, &uniforms, &Default::default() ).unwrap(); }, }; } pub fn storage_buf(&self) -> &Rc<Texture2d> { &self.storage_buf } pub fn frame_buf(&self) -> glium::framebuffer::SimpleFrameBuffer { match &self.draw_bufs { Buffers::SingleSampling(draw_buf, de
height, NUM_SAMPLES ).unwrap() ) }; let storage_buf = std::rc::Rc::new(Texture2d::empty_with_format( display, glium::texture::UncompressedFloatFormat::U8U8U8, glium::texture::MipmapsOption::NoMipmap, width, height ).unwrap()); let imgui_tex = imgui_glium_renderer::Texture { texture: storage_buf.clone(), sampler: glium::uniforms::SamplerBehavior { magnify_filter: glium::uniforms::MagnifySamplerFilter::Linear, minify_filter: glium::uniforms::MinifySamplerFilter::Linear, ..Default::default() }, }; let id = match prev_id { None => renderer.textures().insert(imgui_tex), Some(prev_id) => { renderer.textures().replace(*prev_id, imgui_tex); *prev_id } }; (id, draw_bufs, storage_buf) } pub fn update_size( &mut self, width: u32, height: u32 ) -> bool { if width != self.storage_buf.width() || height != self.storage_buf.height() { let (id, draw_bufs, storage_buf) = DrawBuffer::create( self.draw_bufs.sampling(), &Some(self.id), width, height, COLOR_FORMAT, &self.display, &mut self.renderer.borrow_mut() ); self.id = id; self.draw_bufs = draw_bufs; self.storage_buf = storage_buf; true } else { false } } }
pth_buf) => glium::framebuffer::SimpleFrameBuffer::with_depth_buffer( &self.display, draw_buf, depth_buf ).unwrap(), Buffers::MultiSampling(draw_buf, depth_buf) => glium::framebuffer::SimpleFrameBuffer::with_depth_buffer( &self.display, draw_buf, depth_buf ).unwrap() } } pub fn width(&self) -> u32 { self.storage_buf.width() } pub fn height(&self) -> u32 { self.storage_buf.height() } pub fn new( sampling: Sampling, texture_copy_single_gl_prog: &Rc<glium::Program>, texture_copy_multi_gl_prog: &Rc<glium::Program>, unit_quad: &Rc<glium::VertexBuffer<crate::data::XyVertex>>, display: &glium::Display, renderer: &Rc<RefCell<imgui_glium_renderer::Renderer>> ) -> DrawBuffer { let (id, draw_bufs, storage_buf) = DrawBuffer::create( sampling, &None, INITIAL_DRAW_BUF_SIZE, INITIAL_DRAW_BUF_SIZE, COLOR_FORMAT, display, &mut renderer.borrow_mut() ); DrawBuffer { id, display: display.clone(), renderer: Rc::clone(renderer), draw_bufs, storage_buf, unit_quad: Rc::clone(unit_quad), texture_copy_single_gl_prog: Rc::clone(texture_copy_single_gl_prog), texture_copy_multi_gl_prog: Rc::clone(texture_copy_multi_gl_prog) } } pub fn new_with_size( sampling: Sampling, texture_copy_single_gl_prog: &Rc<glium::Program>, texture_copy_multi_gl_prog: &Rc<glium::Program>, unit_quad: &Rc<glium::VertexBuffer<crate::data::XyVertex>>, display: &glium::Display, renderer: &Rc<RefCell<imgui_glium_renderer::Renderer>>, width: u32, height: u32 ) -> DrawBuffer { let (id, draw_bufs, storage_buf) = DrawBuffer::create( sampling, &None, width, height, COLOR_FORMAT, display, &mut renderer.borrow_mut() ); DrawBuffer { id, display: display.clone(), renderer: Rc::clone(renderer), draw_bufs, storage_buf, unit_quad: Rc::clone(unit_quad), texture_copy_single_gl_prog: Rc::clone(texture_copy_single_gl_prog), texture_copy_multi_gl_prog: Rc::clone(texture_copy_multi_gl_prog) } } pub fn id(&self) -> imgui::TextureId { self.id } fn create( sampling: Sampling, prev_id: &Option<imgui::TextureId>, width: u32, height: u32, format: glium::texture::UncompressedFloatFormat, display: &glium::Display, renderer: &mut imgui_glium_renderer::Renderer ) -> (imgui::TextureId, Buffers, Rc<Texture2d>) { let draw_bufs = match sampling { Sampling::Single => Buffers::SingleSampling( Texture2d::empty_with_format( display, format, glium::texture::MipmapsOption::NoMipmap, width, height ).unwrap(), DepthTexture2d::empty_with_format( display, DEPTH_FORMAT, glium::texture::MipmapsOption::NoMipmap, width, height ).unwrap() ), Sampling::Multi => Buffers::MultiSampling( Texture2dMultisample::empty_with_format( display, format, glium::texture::MipmapsOption::NoMipmap, width, height, NUM_SAMPLES ).unwrap(), DepthTexture2dMultisample::empty_with_format( display, DEPTH_FORMAT, glium::texture::MipmapsOption::NoMipmap, width,
random
[ { "content": "pub fn handle_gui(\n\n ui: &imgui::Ui,\n\n gui_state: &mut GuiState,\n\n program_data: &mut data::ProgramData,\n\n renderer: &Rc<RefCell<imgui_glium_renderer::Renderer>>,\n\n display: &glium::Display\n\n) {\n\n unsafe { imgui::sys::igDockSpaceOverViewport(\n\n imgui::sys::igGetMainViewport(),\n\n imgui::sys::ImGuiDockNodeFlags_PassthruCentralNode as i32,\n\n std::ptr::null()\n\n ); }\n\n\n\n handle_main_menu(ui, program_data, renderer, display);\n\n\n\n program_data.cylindrical_lambert_views().retain_mut(|view| handle_cylindrical_lambert_view(ui, gui_state, view));\n\n program_data.gnomonic_views().retain_mut(|view| handle_gnomonic_view(ui, gui_state, view));\n\n program_data.orthographic_views().retain_mut(|view| handle_orthographic_view(ui, gui_state, view));\n\n program_data.stereographic_views().retain_mut(|view| handle_stereographic_view(ui, gui_state, view));\n\n}\n\n\n", "file_path": "src/gui/mod.rs", "rank": 1, "score": 64388.346283098625 }, { "content": "fn create_texture_from_image(path: &str, display: &glium::Display)\n\n-> glium::texture::texture2d::Texture2d {\n\n let max_texture_size = display.get_capabilities().max_texture_size as u32;\n\n\n\n let mut map_image = image::open(path).unwrap();\n\n\n\n let dims = map_image.dimensions();\n\n if dims.0 > max_texture_size || dims.1 > max_texture_size {\n\n map_image = map_image.resize(\n\n max_texture_size.min(dims.0),\n\n max_texture_size.min(dims.1),\n\n image::imageops::FilterType::CatmullRom\n\n );\n\n }\n\n let dims = map_image.dimensions();\n\n\n\n let img_buffer = match map_image {\n\n image::DynamicImage::ImageRgb8(image) => image,\n\n _ => panic!(\"expected an RGB8 image\")\n\n };\n", "file_path": "src/data.rs", "rank": 2, "score": 60356.01611534752 }, { "content": "fn create_map_from_shape_file(path: &str, display: &glium::Display)\n\n-> LonLatGlBuffers {\n\n let mut reader = shapefile::Reader::from_path(path).unwrap();\n\n\n\n let mut vertex_data: Vec<LonLatVertex> = vec![];\n\n let mut index_data: Vec<u32> = vec![];\n\n\n\n for shape_record in reader.iter_shapes_and_records() {\n\n let (shape, _record) = shape_record.unwrap();\n\n\n\n // let scalerank: f64 = match record.get(\"scalerank\").unwrap() {\n\n // shapefile::dbase::FieldValue::Numeric(value) => value.unwrap(),\n\n // _ => panic!(\"unexpected field type\")\n\n // };\n\n\n\n /*if scalerank == 6.0*/ {\n\n match shape {\n\n shapefile::Shape::Polyline(polyline) => {\n\n for part in polyline.parts() {\n\n for (idx, point) in part.iter().enumerate() {\n", "file_path": "src/data.rs", "rank": 3, "score": 58925.10198514395 }, { "content": "pub fn init() -> Option<ClipboardSupport> {\n\n ClipboardContext::new()\n\n .ok()\n\n .map(|ctx| ClipboardSupport(ctx))\n\n}\n\n\n\nimpl ClipboardBackend for ClipboardSupport {\n\n fn get(&mut self) -> Option<String> {\n\n self.0.get_contents().ok().map(|text| text.into())\n\n }\n\n fn set(&mut self, text: &str) {\n\n let _ = self.0.set_contents(text.to_string());\n\n }\n\n}\n", "file_path": "src/runner/clipboard_support.rs", "rank": 4, "score": 52667.33925046654 }, { "content": "fn create_gl_program_pair(vertex_shader_source: &str, display: &glium::Display) -> GlProgramPair {\n\n GlProgramPair{\n\n lines: Rc::new(program!(display,\n\n 330 => {\n\n vertex: vertex_shader_source,\n\n geometry: include_str!(\"resources/shaders/lines.geom\"),\n\n fragment: include_str!(\"resources/shaders/uniform_color.frag\")\n\n }\n\n ).unwrap()),\n\n\n\n triangles: Rc::new(program!(display,\n\n 330 => {\n\n vertex: vertex_shader_source,\n\n geometry: include_str!(\"resources/shaders/tris.geom\"),\n\n fragment: include_str!(\"resources/shaders/globe_texturing.frag\")\n\n }\n\n ).unwrap())\n\n }\n\n}\n\n\n", "file_path": "src/data.rs", "rank": 5, "score": 51460.10624349545 }, { "content": "pub fn create_runner(logical_font_size: f64) -> Runner {\n\n let event_loop = glium::glutin::event_loop::EventLoop::new();\n\n let context = glium::glutin::ContextBuilder::new().with_vsync(true);\n\n let builder = glium::glutin::window::WindowBuilder::new()\n\n .with_title(\"Projections\".to_owned())\n\n .with_inner_size(glium::glutin::dpi::LogicalSize::new(1280f64, 768f64));\n\n let display =\n\n glium::Display::new(builder, context, &event_loop).expect(\"Failed to initialize display.\");\n\n\n\n let mut imgui = imgui::Context::create();\n\n imgui.set_ini_filename(None);\n\n\n\n if let Some(backend) = clipboard_support::init() {\n\n imgui.set_clipboard_backend(backend);\n\n } else {\n\n eprintln!(\"Failed to initialize clipboard.\");\n\n }\n\n\n\n let mut platform = imgui_winit_support::WinitPlatform::init(&mut imgui);\n\n {\n", "file_path": "src/runner/mod.rs", "rank": 6, "score": 47704.52170146342 }, { "content": "fn handle_view_common(ui: &imgui::Ui, gui_state: &mut GuiState, view: &mut views::ViewBase) {\n\n ui.button(\"reset\");\n\n if ui.is_item_active() {\n\n view.set_orientation(cgmath::Basis3::one());\n\n }\n\n if ui.is_item_hovered() {\n\n ui.tooltip_text(\"Reset view to default orientation\");\n\n }\n\n ui.same_line();\n\n\n\n unsafe { imgui::sys::igSeparatorEx(imgui::sys::ImGuiSeparatorFlags_Vertical as i32); }\n\n ui.same_line();\n\n\n\n if ui.checkbox(\"graticule\", &mut view.draw_graticule) {\n\n view.refresh();\n\n }\n\n ui.same_line();\n\n\n\n unsafe { imgui::sys::igSeparatorEx(imgui::sys::ImGuiSeparatorFlags_Vertical as i32); }\n\n ui.same_line();\n", "file_path": "src/gui/mod.rs", "rank": 7, "score": 44426.992625516716 }, { "content": "fn main() {\n\n let runner = runner::create_runner(18.0);\n\n\n\n let mut data = data::ProgramData::new(runner.display());\n\n\n\n let mut gui_state = gui::GuiState::new(runner.platform().hidpi_factor());\n\n\n\n runner.main_loop(move |_, ui, display, renderer| {\n\n gui::handle_gui(ui, &mut gui_state, &mut data, renderer, display);\n\n });\n\n}\n", "file_path": "src/main.rs", "rank": 8, "score": 36877.911296573766 }, { "content": "struct AdjustedImageSize {\n\n logical_size: [f32; 2],\n\n physical_size: [u32; 2]\n\n}\n\n\n", "file_path": "src/gui/mod.rs", "rank": 9, "score": 36777.372094629594 }, { "content": "pub trait ToArray {\n\n type Output;\n\n fn to_array(&self) -> Self::Output;\n\n}\n\n\n\nimpl<T: Copy> ToArray for cgmath::Matrix3<T>\n\n{\n\n type Output = [[T; 3]; 3];\n\n fn to_array(&self) -> Self::Output {\n\n (*self).into()\n\n }\n\n}\n\n\n\nimpl<T: Copy> ToArray for cgmath::Matrix4<T>\n\n{\n\n type Output = [[T; 4]; 4];\n\n fn to_array(&self) -> Self::Output {\n\n (*self).into()\n\n }\n\n}\n", "file_path": "src/data.rs", "rank": 10, "score": 35921.65839117108 }, { "content": "fn create_graticule(\n\n step: cgmath::Deg<f64>,\n\n num_substeps: usize,\n\n display: &glium::Display\n\n) -> LonLatGlBuffers {\n\n let mut vertex_data: Vec<LonLatVertex> = vec![];\n\n let mut index_data: Vec<u32> = vec![];\n\n\n\n let mut longitude = cgmath::Deg(-180.0);\n\n while longitude <= cgmath::Deg(180.0) {\n\n let mut latitude = cgmath::Deg(-90.0);\n\n let mut parallel_starts = true;\n\n while latitude <= cgmath::Deg(90.0) {\n\n vertex_data.push(LonLatVertex{ lonlat_position: [longitude.0 as f32, latitude.0 as f32] });\n\n if !parallel_starts {\n\n index_data.push((vertex_data.len() - 2) as u32);\n\n index_data.push((vertex_data.len() - 1) as u32);\n\n }\n\n latitude += step / num_substeps as f64;\n\n parallel_starts = false;\n", "file_path": "src/data.rs", "rank": 11, "score": 35488.39614171401 }, { "content": "fn create_globe_mesh(\n\n step: cgmath::Deg<f64>,\n\n display: &glium::Display\n\n) -> LonLatGlBuffers {\n\n assert!((360.0 / step.0).fract() == 0.0);\n\n\n\n let grid_size_lon = (360.0 / step.0) as usize + 1;\n\n let grid_size_lat = (180.0 / step.0) as usize - 1;\n\n\n\n let mut vertex_data: Vec<LonLatVertex> = vec![];\n\n\n\n let mut latitude = -90.0 + step.0;\n\n for _ in 0..grid_size_lat {\n\n let mut longitude = -180.0;\n\n for _ in 0..grid_size_lon {\n\n vertex_data.push(LonLatVertex{ lonlat_position: [longitude as f32, latitude as f32] });\n\n longitude += step.0;\n\n }\n\n latitude += step.0;\n\n }\n", "file_path": "src/data.rs", "rank": 12, "score": 34258.89979309201 }, { "content": "/// Returns `false` if view should be deleted.\n\nfn handle_gnomonic_view(\n\n ui: &imgui::Ui,\n\n gui_state: &mut GuiState,\n\n view: &mut views::GnomonicView\n\n) -> bool {\n\n let mut opened = true;\n\n\n\n imgui::Window::new(ui, &format!(\"Gnomonic###gnomonic_{}\", view.unique_id()))\n\n .size([640.0, 640.0], imgui::Condition::FirstUseEver)\n\n .opened(&mut opened)\n\n .build(|| {\n\n handle_view_common(ui, gui_state, view.base_mut());\n\n }\n\n );\n\n\n\n opened\n\n}\n\n\n", "file_path": "src/gui/mod.rs", "rank": 13, "score": 33163.28520705233 }, { "content": "fn handle_main_menu(\n\n ui: &imgui::Ui,\n\n program_data: &mut data::ProgramData,\n\n renderer: &Rc<RefCell<imgui_glium_renderer::Renderer>>,\n\n display: &glium::Display\n\n) {\n\n let mut orthographic_clicked = false;\n\n let mut stereographic_clicked = false;\n\n let mut gnomonic_clicked = false;\n\n let mut cylindrical_lambert_clicked = false;\n\n let mut about_clicked = false;\n\n let mut instructions_clicked = false;\n\n\n\n match ui.begin_main_menu_bar() {\n\n None => (),\n\n Some(token) => {\n\n ui.menu(\"View\", || {\n\n ui.menu(\"New\", || {\n\n if ui.menu_item(\"Orthographic\") {\n\n orthographic_clicked = true;\n", "file_path": "src/gui/mod.rs", "rank": 14, "score": 33163.28520705233 }, { "content": "/// Returns `false` if view should be deleted.\n\nfn handle_orthographic_view(\n\n ui: &imgui::Ui,\n\n gui_state: &mut GuiState,\n\n view: &mut views::OrthographicView\n\n) -> bool {\n\n let mut opened = true;\n\n\n\n imgui::Window::new(ui, &format!(\"Orthographic###orthographic_{}\", view.unique_id()))\n\n .size([640.0, 640.0], imgui::Condition::FirstUseEver)\n\n .opened(&mut opened)\n\n .build(|| {\n\n handle_view_common(ui, gui_state, view.base_mut());\n\n }\n\n );\n\n\n\n opened\n\n}\n\n\n", "file_path": "src/gui/mod.rs", "rank": 15, "score": 33163.28520705233 }, { "content": "/// Returns `false` if view should be deleted.\n\nfn handle_stereographic_view(\n\n ui: &imgui::Ui,\n\n gui_state: &mut GuiState,\n\n view: &mut views::StereographicView\n\n) -> bool {\n\n let mut opened = true;\n\n\n\n imgui::Window::new(ui, &format!(\"Stereographic###stereographic_{}\", view.unique_id()))\n\n .size([640.0, 640.0], imgui::Condition::FirstUseEver)\n\n .opened(&mut opened)\n\n .build(|| {\n\n handle_view_common(ui, gui_state, view.base_mut());\n\n }\n\n );\n\n\n\n opened\n\n}\n", "file_path": "src/gui/mod.rs", "rank": 16, "score": 33163.28520705233 }, { "content": "/// Returns `false` if view should be deleted.\n\nfn handle_cylindrical_lambert_view(\n\n ui: &imgui::Ui,\n\n gui_state: &mut GuiState,\n\n view: &mut views::CylindricalLambertView\n\n) -> bool {\n\n let mut opened = true;\n\n\n\n imgui::Window::new(ui, &format!(\"Lambert cylindrical###cylindrical_lambert_{}\", view.unique_id()))\n\n .size([640.0, 320.0], imgui::Condition::FirstUseEver)\n\n .opened(&mut opened)\n\n .build(|| {\n\n handle_view_common(ui, gui_state, view.base_mut());\n\n }\n\n );\n\n\n\n opened\n\n}\n\n\n", "file_path": "src/gui/mod.rs", "rank": 17, "score": 32180.813632109086 }, { "content": "/// Adjusts cursor screen position and returns size to be used for an `imgui::Image` (meant to fill the remaining window\n\n/// space) to ensure exact 1:1 pixel rendering when high-DPI scaling is enabled.\n\nfn adjust_pos_for_exact_hidpi_scaling(\n\n ui: &imgui::Ui,\n\n vertical_space_after: f32,\n\n hidpi_factor: f32\n\n) -> AdjustedImageSize {\n\n let scr_pos = ui.cursor_screen_pos();\n\n\n\n let adjusted_pos_x = if (scr_pos[0] * hidpi_factor).fract() != 0.0 {\n\n (scr_pos[0] * hidpi_factor).trunc() / hidpi_factor\n\n } else {\n\n scr_pos[0]\n\n };\n\n\n\n let adjusted_pos_y = if (scr_pos[1] * hidpi_factor).fract() != 0.0 {\n\n (scr_pos[1] * hidpi_factor).trunc() / hidpi_factor\n\n } else {\n\n scr_pos[1]\n\n };\n\n\n\n ui.set_cursor_screen_pos([adjusted_pos_x, adjusted_pos_y]);\n", "file_path": "src/gui/mod.rs", "rank": 18, "score": 31299.414084196193 }, { "content": "fn convert_touch_to_mouse<'a, T>(event: glium::glutin::event::Event<'a, T>) -> glium::glutin::event::Event<'a, T> {\n\n use glium::glutin::event;\n\n\n\n match event {\n\n event::Event::WindowEvent {\n\n window_id,\n\n event: event::WindowEvent::Touch(touch),\n\n } => {\n\n //TODO: do something better here, e.g. remember the last seen mouse device id\n\n let device_id = touch.device_id.clone();\n\n\n\n match touch.phase {\n\n event::TouchPhase::Started => event::Event::WindowEvent{\n\n window_id: window_id.clone(),\n\n event: event::WindowEvent::MouseInput{\n\n device_id,\n\n state: event::ElementState::Pressed,\n\n button: event::MouseButton::Left,\n\n modifiers: Default::default()\n\n },\n", "file_path": "src/runner/mod.rs", "rank": 34, "score": 15131.605672641706 }, { "content": " program_data: &data::ProgramData,\n\n renderer: &Rc<RefCell<imgui_glium_renderer::Renderer>>,\n\n display: &glium::Display\n\n ) -> OrthographicView {\n\n OrthographicView{\n\n base: ViewBase::new(\n\n OrthographicView::initial_orientation(),\n\n program_data,\n\n Rc::clone(&program_data.gl_programs.orthographic.lines),\n\n Rc::clone(&program_data.gl_programs.orthographic.triangles),\n\n display,\n\n renderer\n\n ),\n\n }\n\n }\n\n\n\n pub fn unique_id(&self) -> u32 { self.base.unique_id() }\n\n\n\n pub fn base_mut(&mut self) -> &mut ViewBase { &mut self.base }\n\n\n\n /// Returns identity matrix: observer facing long. 0°, lat. °.\n\n fn initial_orientation() -> cgmath::Basis3<f64> {\n\n cgmath::Basis3::one()\n\n }\n\n}\n", "file_path": "src/views/orthographic.rs", "rank": 35, "score": 14.929908098266406 }, { "content": " program_data: &data::ProgramData,\n\n renderer: &Rc<RefCell<imgui_glium_renderer::Renderer>>,\n\n display: &glium::Display\n\n ) -> StereographicView {\n\n StereographicView{\n\n base: ViewBase::new(\n\n StereographicView::initial_orientation(),\n\n program_data,\n\n Rc::clone(&program_data.gl_programs.stereographic.lines),\n\n Rc::clone(&program_data.gl_programs.stereographic.triangles),\n\n display,\n\n renderer\n\n ),\n\n }\n\n }\n\n\n\n pub fn unique_id(&self) -> u32 { self.base.unique_id() }\n\n\n\n pub fn base_mut(&mut self) -> &mut ViewBase { &mut self.base }\n\n\n\n /// Returns identity matrix: observer facing long. 0°, lat. °.\n\n fn initial_orientation() -> cgmath::Basis3<f64> {\n\n cgmath::Basis3::one()\n\n }\n\n}\n", "file_path": "src/views/stereographic.rs", "rank": 36, "score": 14.929908098266404 }, { "content": " program_data: &data::ProgramData,\n\n renderer: &Rc<RefCell<imgui_glium_renderer::Renderer>>,\n\n display: &glium::Display\n\n ) -> GnomonicView {\n\n GnomonicView{\n\n base: ViewBase::new(\n\n GnomonicView::initial_orientation(),\n\n program_data,\n\n Rc::clone(&program_data.gl_programs.gnomonic.lines),\n\n Rc::clone(&program_data.gl_programs.gnomonic.triangles),\n\n display,\n\n renderer\n\n ),\n\n }\n\n }\n\n\n\n pub fn unique_id(&self) -> u32 { self.base.unique_id() }\n\n\n\n pub fn base_mut(&mut self) -> &mut ViewBase { &mut self.base }\n\n\n\n /// Returns identity matrix: observer facing long. 0°, lat. °.\n\n fn initial_orientation() -> cgmath::Basis3<f64> {\n\n cgmath::Basis3::one()\n\n }\n\n}\n", "file_path": "src/views/gnomonic.rs", "rank": 37, "score": 14.929908098266404 }, { "content": " program_data: &data::ProgramData,\n\n renderer: &Rc<RefCell<imgui_glium_renderer::Renderer>>,\n\n display: &glium::Display\n\n ) -> CylindricalLambertView {\n\n CylindricalLambertView{\n\n base: ViewBase::new(\n\n CylindricalLambertView::initial_orientation(),\n\n program_data,\n\n Rc::clone(&program_data.gl_programs.cylindrical_lambert.lines),\n\n Rc::clone(&program_data.gl_programs.cylindrical_lambert.triangles),\n\n display,\n\n renderer\n\n ),\n\n }\n\n }\n\n\n\n pub fn unique_id(&self) -> u32 { self.base.unique_id() }\n\n\n\n pub fn base_mut(&mut self) -> &mut ViewBase { &mut self.base }\n\n\n\n /// Returns identity matrix: observer facing long. 0°, lat. °.\n\n fn initial_orientation() -> cgmath::Basis3<f64> {\n\n cgmath::Basis3::one()\n\n }\n\n}\n", "file_path": "src/views/cylindrical_lambert.rs", "rank": 38, "score": 14.565181955012633 }, { "content": " pub fn renderer(&self) -> &Rc<RefCell<imgui_glium_renderer::Renderer>> {\n\n &self.renderer\n\n }\n\n\n\n pub fn platform(&self) -> &imgui_winit_support::WinitPlatform {\n\n &self.platform\n\n }\n\n\n\n pub fn display(&self) -> &glium::Display {\n\n &self.display\n\n }\n\n\n\n pub fn main_loop<F>(self, mut run_ui: F)\n\n where F: FnMut(&mut bool, &mut imgui::Ui, &glium::Display, &Rc<RefCell<imgui_glium_renderer::Renderer>>) + 'static\n\n {\n\n let Runner {\n\n event_loop,\n\n display,\n\n mut imgui,\n\n mut platform,\n", "file_path": "src/runner/mod.rs", "rank": 39, "score": 13.936056114690164 }, { "content": " DragRotation::NSEW\n\n };\n\n\n\n ViewBase{\n\n unique_id: program_data.new_unique_id(),\n\n orientation,\n\n draw_graticule: true,\n\n wh_ratio: 1.0,\n\n view_mode: ViewMode::GlobeTexture,\n\n angle_ns: cgmath::Rad(0.0),\n\n angle_ew: cgmath::Rad(0.0),\n\n drag_rotation,\n\n zoom: 1.0,\n\n draw_buf: DrawBuffer::new(\n\n Sampling::Multi,\n\n &program_data.gl_programs.texture_copy_single,\n\n &program_data.gl_programs.texture_copy_multi,\n\n &program_data.unit_quad,\n\n display,\n\n &renderer\n", "file_path": "src/views/base.rs", "rank": 40, "score": 12.058091763075103 }, { "content": " ).unwrap();\n\n }\n\n }\n\n\n\n if self.draw_graticule {\n\n let uniforms = uniforms.add(uniform_names::UNIFORM_COLOR, [0.6f32, 0.6f32, 0.6f32, 1f32]);\n\n target.draw(\n\n &*self.graticule_gl_buf.vertices,\n\n &*self.graticule_gl_buf.indices,\n\n &self.lines_gl_prog,\n\n &uniforms,\n\n &draw_params\n\n ).unwrap();\n\n }\n\n\n\n self.draw_buf.update_storage_buf();\n\n }\n\n\n\n pub fn update_size(&mut self, width: u32, height: u32) {\n\n if height == 0 { return; }\n", "file_path": "src/views/base.rs", "rank": 41, "score": 11.923856196365188 }, { "content": "\n\npub struct GlProgramPair {\n\n /// OpenGL program for rendering lines.\n\n pub lines: Rc<glium::Program>,\n\n /// OpenGL program for rendering triangles.\n\n pub triangles: Rc<glium::Program>\n\n}\n\n\n\npub struct OpenGlPrograms {\n\n pub cylindrical_lambert: GlProgramPair,\n\n pub gnomonic: GlProgramPair,\n\n pub orthographic: GlProgramPair,\n\n pub stereographic: GlProgramPair,\n\n pub texture_copy_single: Rc<glium::Program>,\n\n pub texture_copy_multi: Rc<glium::Program>\n\n}\n\n\n\n#[derive(Clone)]\n\npub struct LonLatGlBuffers {\n\n pub vertices: Rc<glium::VertexBuffer<LonLatVertex>>,\n", "file_path": "src/data.rs", "rank": 42, "score": 11.369280477734222 }, { "content": " stereographic\n\n },\n\n\n\n unit_quad,\n\n }\n\n }\n\n\n\n pub fn new_unique_id(&self) -> u32 {\n\n let new_id = *self.id_counter.borrow();\n\n *self.id_counter.borrow_mut() += 1;\n\n\n\n new_id\n\n }\n\n\n\n pub fn cylindrical_lambert_views(&mut self) -> &mut Vec<CylindricalLambertView> {\n\n &mut self.cylindrical_lambert_views\n\n }\n\n\n\n pub fn gnomonic_views(&mut self) -> &mut Vec<GnomonicView> {\n\n &mut self.gnomonic_views\n", "file_path": "src/data.rs", "rank": 43, "score": 11.289688678332054 }, { "content": "\n\n if self.draw_buf.update_size(width, height) {\n\n self.wh_ratio = width as f32 / height as f32;\n\n self.render()\n\n }\n\n }\n\n\n\n pub (in crate::views) fn unique_id(&self) -> u32 { self.unique_id }\n\n\n\n pub(in crate::views) fn new(\n\n orientation: Basis3<f64>,\n\n program_data: &ProgramData,\n\n lines_gl_prog: Rc<glium::Program>,\n\n tris_gl_prog: Rc<glium::Program>,\n\n display: &glium::Display,\n\n renderer: &Rc<RefCell<imgui_glium_renderer::Renderer>>\n\n ) -> ViewBase {\n\n let drag_rotation = if orientation != Basis3::one() {\n\n DragRotation::Free\n\n } else {\n", "file_path": "src/views/base.rs", "rank": 44, "score": 10.62001202501525 }, { "content": "\n\n pub fn set_view_mode(&mut self, view_mode: ViewMode) {\n\n self.view_mode = view_mode;\n\n self.render();\n\n }\n\n\n\n pub fn draw_buf_id(&self) -> imgui::TextureId { self.draw_buf.id() }\n\n\n\n pub fn drag_rotation(&self) -> DragRotation { self.drag_rotation }\n\n\n\n pub fn zoom_by(&mut self, relative_zoom: f64) {\n\n self.zoom *= relative_zoom;\n\n if self.zoom < 0.5 { self.zoom = 0.5; }\n\n self.render();\n\n }\n\n\n\n pub fn orientation(&self) -> &cgmath::Basis3<f64> { &self.orientation }\n\n\n\n pub fn set_orientation(&mut self, orientation: cgmath::Basis3<f64>) {\n\n if orientation != Basis3::one() {\n", "file_path": "src/views/base.rs", "rank": 45, "score": 10.535630920310762 }, { "content": "//\n\n// Map Projections\n\n// Copyright (c) 2022 Filip Szczerek <[email protected]>\n\n//\n\n// This project is licensed under the terms of the MIT license\n\n// (see the LICENSE file for details).\n\n//\n\n\n\nuse crate::draw_buffer::{Sampling, DrawBuffer};\n\nuse crate::data::{LonLatGlBuffers, ProgramData, ToArray};\n\nuse cgmath::{Basis3, Vector3, InnerSpace, Rotation3, One, Matrix3};\n\nuse std::rc::Rc;\n\nuse std::cell::RefCell;\n\nuse glium::Surface;\n\n\n\n#[derive(Copy, Clone, PartialEq)]\n\npub enum DragRotation {\n\n NSEW,\n\n Free\n\n}\n", "file_path": "src/views/base.rs", "rank": 46, "score": 10.210181513795444 }, { "content": " }\n\n\n\n longitude += step;\n\n }\n\n\n\n let mut latitude = cgmath::Deg(-90.0);\n\n while latitude <= cgmath::Deg(90.0) {\n\n let mut longitude = cgmath::Deg(-180.0);\n\n let mut meridian_starts = true;\n\n while longitude <= cgmath::Deg(180.0) {\n\n vertex_data.push(LonLatVertex{ lonlat_position: [longitude.0 as f32, latitude.0 as f32] });\n\n if !meridian_starts {\n\n index_data.push((vertex_data.len() - 2) as u32);\n\n index_data.push((vertex_data.len() - 1) as u32);\n\n }\n\n longitude += step / num_substeps as f64;\n\n meridian_starts = false;\n\n }\n\n\n\n latitude += step;\n\n }\n\n\n\n let vertices = Rc::new(glium::VertexBuffer::new(display, &vertex_data).unwrap());\n\n let indices = Rc::new(glium::IndexBuffer::new(display, glium::index::PrimitiveType::LinesList, &index_data).unwrap());\n\n\n\n LonLatGlBuffers{ vertices, indices }\n\n}\n\n\n", "file_path": "src/data.rs", "rank": 47, "score": 10.130146159580361 }, { "content": "\n\n glium::glutin::event::Event::RedrawRequested(_) => {\n\n let mut ui = imgui.frame();\n\n\n\n let mut run = true;\n\n run_ui(&mut run, &mut ui, &display, &renderer);\n\n if !run {\n\n *control_flow = glium::glutin::event_loop::ControlFlow::Exit;\n\n }\n\n\n\n let gl_window = display.gl_window();\n\n let mut target = display.draw();\n\n target.clear_color_srgb(1.0, 1.0, 1.0, 1.0);\n\n platform.prepare_render(&ui, gl_window.window());\n\n let draw_data = imgui.render();\n\n renderer.borrow_mut()\n\n .render(&mut target, draw_data)\n\n .expect(\"Rendering failed.\");\n\n target.finish().expect(\"Failed to swap buffers.\");\n\n },\n", "file_path": "src/runner/mod.rs", "rank": 48, "score": 10.04713807813645 }, { "content": " }),\n\n },\n\n ]);\n\n\n\n imgui.io_mut().font_global_scale = (1.0 / hidpi_factor) as f32;\n\n imgui.io_mut().config_flags |= imgui::ConfigFlags::DOCKING_ENABLE;\n\n imgui.io_mut().config_windows_move_from_title_bar_only = true;\n\n\n\n let renderer = imgui_glium_renderer::Renderer::init(&mut imgui, &display).expect(\"Failed to initialize renderer.\");\n\n\n\n Runner {\n\n event_loop,\n\n display,\n\n imgui,\n\n platform,\n\n renderer: Rc::new(RefCell::new(renderer))\n\n }\n\n}\n\n\n\nimpl Runner {\n", "file_path": "src/runner/mod.rs", "rank": 49, "score": 10.018274125997397 }, { "content": " vertex_data.push(LonLatVertex{ lonlat_position: [point.x as f32, point.y as f32] });\n\n if idx > 0 {\n\n index_data.push((vertex_data.len() - 2) as u32);\n\n index_data.push((vertex_data.len() - 1) as u32);\n\n }\n\n }\n\n }\n\n },\n\n _ => ()\n\n }\n\n }\n\n }\n\n\n\n let vertices = Rc::new(glium::VertexBuffer::new(display, &vertex_data).unwrap());\n\n let indices = Rc::new(glium::IndexBuffer::new(display, glium::index::PrimitiveType::LinesList, &index_data).unwrap());\n\n\n\n LonLatGlBuffers{ vertices, indices }\n\n}", "file_path": "src/data.rs", "rank": 50, "score": 9.33099336148383 }, { "content": " pub indices: Rc<glium::IndexBuffer<u32>>,\n\n}\n\n\n\npub struct ProgramData {\n\n id_counter: Rc<RefCell<u32>>,\n\n\n\n pub gl_programs: OpenGlPrograms,\n\n\n\n pub unit_quad: Rc<glium::VertexBuffer<XyVertex>>,\n\n\n\n pub globe_texture: Rc<glium::Texture2d>,\n\n\n\n pub globe_gl_buf: LonLatGlBuffers,\n\n\n\n pub graticule_gl_buf: LonLatGlBuffers,\n\n\n\n pub map_gl_buf: LonLatGlBuffers,\n\n\n\n pub cylindrical_lambert_views: Vec<CylindricalLambertView>,\n\n\n\n pub gnomonic_views: Vec<GnomonicView>,\n\n\n\n pub orthographic_views: Vec<OrthographicView>,\n\n\n\n pub stereographic_views: Vec<StereographicView>\n\n}\n\n\n", "file_path": "src/data.rs", "rank": 51, "score": 9.314539305602352 }, { "content": "//\n\n// Map Projections\n\n// Copyright (c) 2022 Filip Szczerek <[email protected]>\n\n//\n\n// This project is licensed under the terms of the MIT license\n\n// (see the LICENSE file for details).\n\n//\n\n\n\nuse glium::Surface;\n\nuse std::cell::RefCell;\n\nuse std::rc::Rc;\n\n\n\nmod clipboard_support;\n\n\n\npub struct Runner {\n\n event_loop: glium::glutin::event_loop::EventLoop<()>,\n\n display: glium::Display,\n\n imgui: imgui::Context,\n\n platform: imgui_winit_support::WinitPlatform,\n\n renderer: Rc<RefCell<imgui_glium_renderer::Renderer>>\n\n}\n\n\n", "file_path": "src/runner/mod.rs", "rank": 52, "score": 8.775517375471509 }, { "content": " }\n\n ).unwrap());\n\n\n\n let texture_copy_multi = Rc::new(program!(display,\n\n 330 => {\n\n vertex: include_str!(\"resources/shaders/pass-through.vert\"),\n\n fragment: include_str!(\"resources/shaders/texturing_multi-sample.frag\"),\n\n }\n\n ).unwrap());\n\n\n\n let cylindrical_lambert = create_gl_program_pair(\n\n include_str!(\"resources/shaders/cylindrical_lambert.vert\"),\n\n display\n\n );\n\n let gnomonic = create_gl_program_pair(\n\n include_str!(\"resources/shaders/gnomonic.vert\"),\n\n display\n\n );\n\n let orthographic = create_gl_program_pair(\n\n include_str!(\"resources/shaders/orthographic.vert\"),\n", "file_path": "src/data.rs", "rank": 53, "score": 8.656556222461813 }, { "content": "\n\n globe_gl_buf: LonLatGlBuffers,\n\n\n\n graticule_gl_buf: LonLatGlBuffers,\n\n\n\n map_gl_buf: LonLatGlBuffers,\n\n\n\n globe_texture: Rc<glium::texture::texture2d::Texture2d>,\n\n\n\n lines_gl_prog: Rc<glium::Program>,\n\n\n\n tris_gl_prog: Rc<glium::Program>\n\n}\n\n\n\nimpl ViewBase {\n\n pub fn refresh(&self) {\n\n self.render();\n\n }\n\n\n\n pub fn view_mode(&self) -> ViewMode { self.view_mode }\n", "file_path": "src/views/base.rs", "rank": 54, "score": 8.271170595175885 }, { "content": "pub struct ViewBase {\n\n unique_id: u32,\n\n\n\n orientation: Basis3<f64>,\n\n\n\n pub draw_graticule: bool,\n\n\n\n wh_ratio: f32,\n\n\n\n angle_ns: cgmath::Rad<f64>,\n\n\n\n angle_ew: cgmath::Rad<f64>,\n\n\n\n view_mode: ViewMode,\n\n\n\n zoom: f64,\n\n\n\n drag_rotation: DragRotation,\n\n\n\n draw_buf: DrawBuffer,\n", "file_path": "src/views/base.rs", "rank": 55, "score": 8.031097651191633 }, { "content": " display\n\n );\n\n let stereographic = create_gl_program_pair(\n\n include_str!(\"resources/shaders/stereographic.vert\"),\n\n display\n\n );\n\n\n\n let unit_quad_data = [\n\n XyVertex{ position: [-1.0, -1.0] },\n\n XyVertex{ position: [ 1.0, -1.0] },\n\n XyVertex{ position: [ 1.0, 1.0] },\n\n XyVertex{ position: [-1.0, 1.0] }\n\n ];\n\n let unit_quad = Rc::new(glium::VertexBuffer::new(display, &unit_quad_data).unwrap());\n\n\n\n ProgramData{\n\n id_counter: Rc::new(RefCell::new(0)),\n\n\n\n globe_texture,\n\n\n", "file_path": "src/data.rs", "rank": 56, "score": 7.656104378164102 }, { "content": " let s_cap_idx = vertex_data.len() as u32 - 1;\n\n vertex_data.push(LonLatVertex{ lonlat_position: [0.0, 90.0] }); // north cap\n\n let n_cap_idx = vertex_data.len() as u32 - 1;\n\n\n\n for i_lon in 0..grid_size_lon {\n\n // south cap\n\n index_data.push(v_index!(i_lon, 0));\n\n index_data.push(v_index!(i_lon + 1, 0));\n\n index_data.push(s_cap_idx);\n\n\n\n // north cap\n\n index_data.push(v_index!(i_lon, grid_size_lat - 1));\n\n index_data.push(v_index!(i_lon + 1, grid_size_lat - 1));\n\n index_data.push(n_cap_idx);\n\n }\n\n\n\n let vertices = Rc::new(glium::VertexBuffer::new(display, &vertex_data).unwrap());\n\n let indices = Rc::new(glium::IndexBuffer::new(display, glium::index::PrimitiveType::TrianglesList, &index_data).unwrap());\n\n\n\n LonLatGlBuffers{ vertices, indices }\n\n}\n\n\n", "file_path": "src/data.rs", "rank": 57, "score": 7.576018301025067 }, { "content": "\n\n let layout = img_buffer.as_flat_samples().layout;\n\n //TODO: handle line padding\n\n assert!(layout.height_stride == layout.width as usize * layout.channels as usize);\n\n\n\n let texture = glium::texture::texture2d::Texture2d::with_format(\n\n display,\n\n glium::texture::RawImage2d{\n\n data: std::borrow::Cow::<[u8]>::from(img_buffer.as_flat_samples().samples),\n\n width: dims.0,\n\n height: dims.1,\n\n format: glium::texture::ClientFormat::U8U8U8\n\n },\n\n glium::texture::UncompressedFloatFormat::U8U8U8,\n\n glium::texture::MipmapsOption::AutoGeneratedMipmaps\n\n ).unwrap();\n\n\n\n texture\n\n}\n\n\n", "file_path": "src/data.rs", "rank": 58, "score": 7.50774370954543 }, { "content": " &self,\n\n //view_specific_uniforms: glium::uniforms::UniformsStorage<'_, T, R>\n\n ) {\n\n // no need for a depth test; depending on particular view, either the projection clips the rear hemisphere,\n\n // or the vertex shader outputs vertices on a plane\n\n let draw_params = glium::DrawParameters::default();\n\n\n\n let uniforms = uniform! {\n\n globe_orientation: Matrix3::from(self.orientation).cast::<f32>().unwrap().to_array(),\n\n zoom: self.zoom as f32,\n\n wh_ratio : self.wh_ratio,\n\n source_texture: glium::uniforms::Sampler::new(&*self.globe_texture)\n\n .wrap_function(glium::uniforms::SamplerWrapFunction::Clamp)\n\n };\n\n\n\n let mut target = self.draw_buf.frame_buf();\n\n\n\n match self.view_mode {\n\n ViewMode::GlobeTexture => {\n\n target.clear_color(0.5, 0.5, 0.5, 1.0);\n", "file_path": "src/views/base.rs", "rank": 59, "score": 7.353818669356219 }, { "content": "//\n\n// Map Projections\n\n// Copyright (c) 2022 Filip Szczerek <[email protected]>\n\n//\n\n// This project is licensed under the terms of the MIT license\n\n// (see the LICENSE file for details).\n\n//\n\n\n\nuse cgmath::One;\n\nuse std::rc::Rc;\n\nuse crate::data;\n\nuse crate::views::{base::ViewBase};\n\nuse std::cell::RefCell;\n\n\n\npub struct StereographicView {\n\n base: ViewBase,\n\n}\n\n\n\nimpl StereographicView {\n\n pub fn new(\n", "file_path": "src/views/stereographic.rs", "rank": 60, "score": 7.339832857006756 }, { "content": "//\n\n// Map Projections\n\n// Copyright (c) 2022 Filip Szczerek <[email protected]>\n\n//\n\n// This project is licensed under the terms of the MIT license\n\n// (see the LICENSE file for details).\n\n//\n\n\n\nuse cgmath::One;\n\nuse std::rc::Rc;\n\nuse crate::data;\n\nuse crate::views::{base::ViewBase};\n\nuse std::cell::RefCell;\n\n\n\npub struct OrthographicView {\n\n base: ViewBase,\n\n}\n\n\n\nimpl OrthographicView {\n\n pub fn new(\n", "file_path": "src/views/orthographic.rs", "rank": 61, "score": 7.339832857006755 }, { "content": "//\n\n// Map Projections\n\n// Copyright (c) 2022 Filip Szczerek <[email protected]>\n\n//\n\n// This project is licensed under the terms of the MIT license\n\n// (see the LICENSE file for details).\n\n//\n\n\n\nuse cgmath::One;\n\nuse std::rc::Rc;\n\nuse crate::data;\n\nuse crate::views::{base::ViewBase};\n\nuse std::cell::RefCell;\n\n\n\npub struct GnomonicView {\n\n base: ViewBase,\n\n}\n\n\n\nimpl GnomonicView {\n\n pub fn new(\n", "file_path": "src/views/gnomonic.rs", "rank": 62, "score": 7.339832857006755 }, { "content": "//\n\n// Map Projections\n\n// Copyright (c) 2022 Filip Szczerek <[email protected]>\n\n//\n\n// This project is licensed under the terms of the MIT license\n\n// (see the LICENSE file for details).\n\n//\n\n\n\nuse cgmath::One;\n\nuse std::rc::Rc;\n\nuse crate::data;\n\nuse crate::views::{base::ViewBase};\n\nuse std::cell::RefCell;\n\n\n\npub struct CylindricalLambertView {\n\n base: ViewBase,\n\n}\n\n\n\nimpl CylindricalLambertView {\n\n pub fn new(\n", "file_path": "src/views/cylindrical_lambert.rs", "rank": 63, "score": 7.252388289653245 }, { "content": "impl ProgramData {\n\n pub fn new(display: &glium::Display) -> ProgramData {\n\n let globe_texture = Rc::new(create_texture_from_image(\n\n \"data/world.topo.bathy.200412.3x8192x4096.jpg\",\n\n display\n\n ));\n\n\n\n let globe_gl_buf = create_globe_mesh(cgmath::Deg(2.0), display);\n\n\n\n let graticule_gl_buf = create_graticule(cgmath::Deg(10.0), 10, display);\n\n\n\n let map_gl_buf = create_map_from_shape_file(\n\n \"data/ne_10m_coastline/ne_10m_coastline.shp\",\n\n display\n\n );\n\n\n\n let texture_copy_single = Rc::new(program!(display,\n\n 330 => {\n\n vertex: include_str!(\"resources/shaders/pass-through.vert\"),\n\n fragment: include_str!(\"resources/shaders/texturing.frag\"),\n", "file_path": "src/data.rs", "rank": 64, "score": 7.176178113178864 }, { "content": "//\n\n// Map Projections\n\n// Copyright (c) 2022 Filip Szczerek <[email protected]>\n\n//\n\n// This project is licensed under the terms of the MIT license\n\n// (see the LICENSE file for details).\n\n//\n\n\n\nuse cgmath::{Rotation, One};\n\nuse crate::data;\n\nuse crate::views;\n\nuse crate::views::{DragRotation, ViewMode};\n\nuse retain_mut::RetainMut;\n\nuse std::cell::RefCell;\n\nuse std::rc::Rc;\n\n\n\nconst MOUSE_WHEEL_ZOOM_FACTOR: f64 = 1.2;\n\n\n\n#[derive(Default)]\n\npub struct GuiState {\n", "file_path": "src/gui/mod.rs", "rank": 65, "score": 7.1409609052583845 }, { "content": "\n\n target.draw(\n\n &*self.globe_gl_buf.vertices,\n\n &*self.globe_gl_buf.indices,\n\n &*self.tris_gl_prog,\n\n &uniforms,\n\n &draw_params\n\n ).unwrap();\n\n },\n\n\n\n ViewMode::VectorMap => {\n\n target.clear_color(0.87, 0.87, 0.87, 1.0);\n\n\n\n let uniforms = uniforms.clone().add(uniform_names::UNIFORM_COLOR, [0f32, 0f32, 0f32, 1f32]);\n\n target.draw(\n\n &*self.map_gl_buf.vertices,\n\n &*self.map_gl_buf.indices,\n\n &self.lines_gl_prog,\n\n &uniforms,\n\n &draw_params\n", "file_path": "src/views/base.rs", "rank": 66, "score": 6.8844940233958765 }, { "content": "\n\n#[derive(Copy, Clone, PartialEq)]\n\npub enum ViewMode {\n\n VectorMap,\n\n GlobeTexture\n\n}\n\n\n\nmod uniform_names {\n\n pub const UNIFORM_COLOR: &str = \"uniform_color\";\n\n}\n\n\n\n/// Base struct representing a view.\n\n///\n\n/// The underlying globe being projected is oriented as per `orientation`. The globe is centered\n\n/// at (0, 0, 0) with radius equal to 1.\n\n///\n\n/// The camera is located at (1, 0, 0) looking at (0, 0, 0); when `orientation`\n\n/// is an identity matrix, the observer looks at lat. 0°, long. 0° (i.e. the line\n\n/// from globe center to lat. 0°, long. 0° overlaps with the X axis).\n\n///\n", "file_path": "src/views/base.rs", "rank": 67, "score": 6.83555957461906 }, { "content": " renderer,\n\n ..\n\n } = self;\n\n\n\n let mut last_frame = std::time::Instant::now();\n\n\n\n event_loop.run(move |event, _, control_flow| match event {\n\n glium::glutin::event::Event::NewEvents(_) => {\n\n let now = std::time::Instant::now();\n\n imgui.io_mut().update_delta_time(now - last_frame);\n\n last_frame = now;\n\n },\n\n\n\n glium::glutin::event::Event::MainEventsCleared => {\n\n let gl_window = display.gl_window();\n\n platform\n\n .prepare_frame(imgui.io_mut(), &gl_window.window())\n\n .expect(\"Failed to prepare frame\");\n\n gl_window.window().request_redraw();\n\n },\n", "file_path": "src/runner/mod.rs", "rank": 68, "score": 6.715415255108118 }, { "content": " }\n\n\n\n pub fn orthographic_views(&mut self) -> &mut Vec<OrthographicView> {\n\n &mut self.orthographic_views\n\n }\n\n\n\n pub fn stereographic_views(&mut self) -> &mut Vec<StereographicView> {\n\n &mut self.stereographic_views\n\n }\n\n\n\n pub fn add_cylindrical_lambert_view(&mut self, view: CylindricalLambertView) {\n\n self.cylindrical_lambert_views.push(view);\n\n }\n\n\n\n pub fn add_gnomonic_view(&mut self, view: GnomonicView) {\n\n self.gnomonic_views.push(view);\n\n }\n\n\n\n pub fn add_orthographic_view(&mut self, view: OrthographicView) {\n\n self.orthographic_views.push(view);\n\n }\n\n\n\n pub fn add_stereographic_view(&mut self, view: StereographicView) {\n\n self.stereographic_views.push(view);\n\n }\n\n}\n\n\n", "file_path": "src/data.rs", "rank": 69, "score": 6.3699889947732675 }, { "content": " ),\n\n globe_gl_buf: program_data.globe_gl_buf.clone(),\n\n graticule_gl_buf: program_data.graticule_gl_buf.clone(),\n\n map_gl_buf: program_data.map_gl_buf.clone(),\n\n globe_texture: program_data.globe_texture.clone(),\n\n lines_gl_prog,\n\n tris_gl_prog\n\n }\n\n }\n\n\n\n /// Elements of `start` and `end` denote normalized mouse position within the view,\n\n /// with values from [-1, 1] (i.e., bottom-left is [-1, -1], and top-right is [1, 1]).\n\n pub fn rotate_by_dragging(&mut self, start: [f32; 2], end: [f32; 2]) {\n\n match self.drag_rotation {\n\n // simulates \"space ball\" rotation\n\n DragRotation::Free => {\n\n let start_vec = Vector3{ x: 1.0, y: start[0] as f64, z: start[1] as f64 };\n\n let end_vec = Vector3{ x: 1.0, y: end[0] as f64, z: end[1] as f64 };\n\n\n\n let axis_of_rotation = start_vec.cross(end_vec).normalize();\n", "file_path": "src/views/base.rs", "rank": 70, "score": 6.362710664249893 }, { "content": " self.drag_rotation = DragRotation::Free;\n\n };\n\n self.orientation = orientation;\n\n // TODO: if rotation mode is NSEW, we should actually calculate current angles here\n\n self.angle_ew = cgmath::Rad(0.0);\n\n self.angle_ns = cgmath::Rad(0.0);\n\n self.render();\n\n }\n\n\n\n pub fn set_drag_rotation(&mut self, drag_rotation: DragRotation) {\n\n self.drag_rotation = drag_rotation;\n\n if drag_rotation == DragRotation::NSEW {\n\n self.orientation = Basis3::one();\n\n self.angle_ew = cgmath::Rad(0.0);\n\n self.angle_ns = cgmath::Rad(0.0);\n\n self.render();\n\n }\n\n }\n\n\n\n pub(in crate::views) fn render(\n", "file_path": "src/views/base.rs", "rank": 71, "score": 6.304987900459199 }, { "content": "//\n\n// Map Projections\n\n// Copyright (c) 2022 Filip Szczerek <[email protected]>\n\n//\n\n// This project is licensed under the terms of the MIT license\n\n// (see the LICENSE file for details).\n\n//\n\n\n\n#[macro_use]\n\nextern crate imgui_glium_renderer;\n\n\n\nmod data;\n\nmod draw_buffer;\n\nmod gui;\n\nmod runner;\n\nmod views;\n\n\n\nuse std::{rc::Rc, io::Write};\n\n\n", "file_path": "src/main.rs", "rank": 72, "score": 6.19280309106124 }, { "content": "//\n\n// Map Projections\n\n// Copyright (c) 2022 Filip Szczerek <[email protected]>\n\n//\n\n// This project is licensed under the terms of the MIT license\n\n// (see the LICENSE file for details).\n\n//\n\n\n\nmod base;\n\nmod cylindrical_lambert;\n\nmod gnomonic;\n\nmod orthographic;\n\nmod stereographic;\n\n\n\npub use base::{ViewBase, DragRotation, ViewMode};\n\npub use cylindrical_lambert::CylindricalLambertView;\n\npub use gnomonic::GnomonicView;\n\npub use orthographic::OrthographicView;\n\npub use stereographic::StereographicView;\n", "file_path": "src/views/mod.rs", "rank": 73, "score": 6.130982920422306 }, { "content": " }\n\n });\n\n\n\n token.end();\n\n }\n\n }\n\n\n\n if orthographic_clicked {\n\n program_data.add_orthographic_view(views::OrthographicView::new(\n\n program_data, renderer, display\n\n ));\n\n }\n\n if stereographic_clicked {\n\n program_data.add_stereographic_view(views::StereographicView::new(\n\n program_data, renderer, display\n\n ));\n\n }\n\n if gnomonic_clicked {\n\n program_data.add_gnomonic_view(views::GnomonicView::new(\n\n program_data, renderer, display\n", "file_path": "src/gui/mod.rs", "rank": 74, "score": 5.537495308659459 }, { "content": " ));\n\n }\n\n if cylindrical_lambert_clicked {\n\n program_data.add_cylindrical_lambert_view(views::CylindricalLambertView::new(\n\n program_data, renderer, display\n\n ));\n\n }\n\n\n\n if instructions_clicked {\n\n ui.open_popup(\"Instructions\");\n\n unsafe { imgui::sys::igSetNextWindowSize(\n\n imgui::sys::ImVec2{ x: 600.0, y: 300.0},\n\n imgui::sys::ImGuiCond_FirstUseEver as i32\n\n ); }\n\n }\n\n ui.popup_modal(\"Instructions\").build(ui, || {\n\n ui.text_wrapped(\"Within a view window, use the left mouse button to change the orientation of the projected globe. \\\n\nUse the mouse wheel to zoom in/out.\\n\\n\");\n\n ui.separator();\n\n if ui.button(\"Close\") {\n", "file_path": "src/gui/mod.rs", "rank": 75, "score": 5.200839210465535 }, { "content": "pub struct LonLatVertex {\n\n // values in degrees; -180° ⩽ longitude ⩽ 180°, -90° ⩽ latitude ⩽ 90°\n\n lonlat_position: [f32; 2]\n\n}\n\nglium::implement_vertex!(LonLatVertex, lonlat_position);\n\n\n\n#[derive(Copy, Clone)]\n\npub struct XyVertex {\n\n position: [f32; 2]\n\n}\n\nglium::implement_vertex!(XyVertex, position);\n\n\n\n#[derive(Copy, Clone)]\n\npub struct XyzVertex {\n\n position: [f32; 3]\n\n}\n\nglium::implement_vertex!(XyzVertex, position);\n\n\n", "file_path": "src/data.rs", "rank": 76, "score": 5.191497667980675 }, { "content": " },\n\n\n\n event::TouchPhase::Ended => event::Event::WindowEvent{\n\n window_id: window_id.clone(),\n\n event: event::WindowEvent::MouseInput{\n\n device_id,\n\n state: event::ElementState::Released,\n\n button: event::MouseButton::Left,\n\n modifiers: Default::default()\n\n },\n\n },\n\n\n\n _ => event\n\n }\n\n },\n\n\n\n _ => event\n\n }\n\n}", "file_path": "src/runner/mod.rs", "rank": 77, "score": 5.013036497941547 }, { "content": "//\n\n// Map Projections\n\n// Copyright (c) 2022 Filip Szczerek <[email protected]>\n\n//\n\n// This project is licensed under the terms of the MIT license\n\n// (see the LICENSE file for details).\n\n//\n\n\n\nuse crate::views::{\n\n CylindricalLambertView,\n\n GnomonicView,\n\n OrthographicView,\n\n StereographicView\n\n};\n\nuse glium::CapabilitiesSource;\n\nuse image::{GenericImageView};\n\nuse std::cell::RefCell;\n\nuse std::rc::Rc;\n\n\n\n#[derive(Copy, Clone)]\n", "file_path": "src/data.rs", "rank": 78, "score": 5.001250607004689 }, { "content": "\n\n let mut size = ui.content_region_avail();\n\n size[1] -= vertical_space_after;\n\n\n\n let mut adjusted_size_x = size[0].trunc();\n\n if (adjusted_size_x * hidpi_factor).fract() != 0.0 {\n\n adjusted_size_x = (adjusted_size_x * hidpi_factor).trunc() / hidpi_factor;\n\n }\n\n\n\n let mut adjusted_size_y = size[1].trunc();\n\n if (adjusted_size_y * hidpi_factor).fract() != 0.0 {\n\n adjusted_size_y = (adjusted_size_y * hidpi_factor).trunc() / hidpi_factor;\n\n }\n\n\n\n let physical_size = [\n\n (adjusted_size_x * hidpi_factor).trunc() as u32,\n\n (adjusted_size_y * hidpi_factor).trunc() as u32\n\n ];\n\n\n\n AdjustedImageSize{\n\n logical_size: [adjusted_size_x, adjusted_size_y],\n\n physical_size\n\n }\n\n}\n\n\n", "file_path": "src/gui/mod.rs", "rank": 79, "score": 4.577509958108816 }, { "content": " hidpi_factor: f64,\n\n mouse_drag_origin: [f32; 2]\n\n}\n\n\n\nimpl GuiState {\n\n pub fn new(hidpi_factor: f64) -> GuiState {\n\n GuiState{\n\n hidpi_factor,\n\n ..Default::default()\n\n }\n\n }\n\n}\n\n\n", "file_path": "src/gui/mod.rs", "rank": 80, "score": 4.517019281743895 }, { "content": "//\n\n// Map Projections\n\n// Copyright (c) 2022 Filip Szczerek <[email protected]>\n\n//\n\n// This project is licensed under the terms of the MIT license\n\n// (see the LICENSE file for details).\n\n//\n\n\n\nextern crate clipboard;\n\nextern crate imgui;\n\n\n\nuse self::clipboard::{ClipboardContext, ClipboardProvider};\n\nuse self::imgui::{ClipboardBackend};\n\n\n\npub struct ClipboardSupport(ClipboardContext);\n\n\n", "file_path": "src/runner/clipboard_support.rs", "rank": 81, "score": 4.438201482015732 }, { "content": " globe_gl_buf,\n\n\n\n graticule_gl_buf,\n\n\n\n map_gl_buf,\n\n\n\n cylindrical_lambert_views: vec![],\n\n\n\n gnomonic_views: vec![],\n\n\n\n orthographic_views: vec![],\n\n\n\n stereographic_views: vec![],\n\n\n\n gl_programs: OpenGlPrograms {\n\n texture_copy_single,\n\n texture_copy_multi,\n\n cylindrical_lambert,\n\n gnomonic,\n\n orthographic,\n", "file_path": "src/data.rs", "rank": 82, "score": 3.973267430313574 }, { "content": "\n\n let mut index_data: Vec<u32> = vec![];\n\n\n\n macro_rules! v_index {\n\n ($i_lon:expr, $i_lat:expr) => { (($i_lon) + ($i_lat) * grid_size_lon) as u32 }\n\n }\n\n\n\n for i_lon in 0..grid_size_lon {\n\n for i_lat in 0..grid_size_lat - 1 {\n\n index_data.push(v_index!(i_lon, i_lat));\n\n index_data.push(v_index!(i_lon, i_lat + 1));\n\n index_data.push(v_index!(i_lon + 1, i_lat));\n\n\n\n index_data.push(v_index!(i_lon + 1, i_lat));\n\n index_data.push(v_index!(i_lon, i_lat + 1));\n\n index_data.push(v_index!(i_lon + 1, i_lat + 1));\n\n }\n\n }\n\n\n\n vertex_data.push(LonLatVertex{ lonlat_position: [0.0, -90.0] }); // south cap\n", "file_path": "src/data.rs", "rank": 83, "score": 3.4583052990817373 }, { "content": "\n\n glium::glutin::event::Event::WindowEvent {\n\n event: glium::glutin::event::WindowEvent::CloseRequested,\n\n ..\n\n } => *control_flow = glium::glutin::event_loop::ControlFlow::Exit,\n\n\n\n event => {\n\n let converted_event = convert_touch_to_mouse(event);\n\n\n\n let gl_window = display.gl_window();\n\n platform.handle_event(imgui.io_mut(), gl_window.window(), &converted_event);\n\n }\n\n })\n\n }\n\n}\n\n\n", "file_path": "src/runner/mod.rs", "rank": 84, "score": 3.404331285961706 }, { "content": " let gl_window = display.gl_window();\n\n let window = gl_window.window();\n\n platform.attach_window(imgui.io_mut(), &window, imgui_winit_support::HiDpiMode::Default);\n\n }\n\n\n\n let hidpi_factor = platform.hidpi_factor();\n\n let font_size = (logical_font_size * hidpi_factor) as f32;\n\n\n\n imgui.fonts().add_font(&[\n\n imgui::FontSource::TtfData {\n\n data: include_bytes!(\n\n \"../resources/fonts/NotoSans-Regular.ttf\"\n\n ),\n\n size_pixels: font_size,\n\n config: Some(imgui::FontConfig {\n\n glyph_ranges: imgui::FontGlyphRanges::from_slice(&[\n\n 0x0020, 0x00FF, // Basic Latin, Latin-1 Supplement\n\n 0\n\n ]),\n\n ..imgui::FontConfig::default()\n", "file_path": "src/runner/mod.rs", "rank": 85, "score": 2.5460290101684286 }, { "content": "# Map Projections\n\nCopyright (C) 2022 Filip Szczerek ([email protected])\n\n\n\n*This program is licensed under MIT license (see LICENSE.txt for details).*\n\n\n\n----------------------------------------\n\n\n\n![Screenshot](screenshot.png)\n\n\n\n## Instructions\n\n\n\nTo run the program: install the Rust toolchain, clone the source code and execute in the source directory:\n\n```\n\n$ cargo run --release\n\n```\n\n\n\n## Datasets\n\n\n\nEarth topo- and bathygraphy texture courtesy of NASA.\n\n\n", "file_path": "README.md", "rank": 86, "score": 1.5713501854719794 }, { "content": " view.set_drag_rotation(DragRotation::Free);\n\n }\n\n\n\n let hidpi_f = gui_state.hidpi_factor as f32;\n\n\n\n let adjusted = adjust_pos_for_exact_hidpi_scaling(ui, 0.0, hidpi_f);\n\n\n\n view.update_size(\n\n adjusted.physical_size[0],\n\n adjusted.physical_size[1]\n\n );\n\n\n\n let img_pos_in_app_window = ui.cursor_screen_pos();\n\n\n\n let image_start_pos = ui.cursor_pos();\n\n imgui::Image::new(view.draw_buf_id(), adjusted.logical_size).build(ui);\n\n\n\n let mouse_pos_in_app_window = ui.io().mouse_pos;\n\n if ui.is_item_clicked_with_button(imgui::MouseButton::Left) {\n\n gui_state.mouse_drag_origin = [\n", "file_path": "src/gui/mod.rs", "rank": 87, "score": 1.3408889537174637 }, { "content": " let angle = cgmath::Rad(\n\n 1.0 / self.zoom * ((start[0] - end[0]).powi(2) + (start[1] - end[1]).powi(2)).sqrt() as f64\n\n );\n\n\n\n let rotation = cgmath::Basis3::from_axis_angle(axis_of_rotation, angle);\n\n\n\n self.orientation = rotation * self.orientation;\n\n },\n\n\n\n DragRotation::NSEW => {\n\n let new_angle_ns = self.angle_ns + cgmath::Rad(1.0 / self.zoom * (start[1] - end[1]) as f64);\n\n if new_angle_ns.0.abs() <= cgmath::Rad::from(cgmath::Deg(90.0)).0 {\n\n self.angle_ns = new_angle_ns;\n\n }\n\n\n\n self.angle_ew += cgmath::Rad(1.0 / self.zoom * (end[0] - start[0]) as f64);\n\n\n\n let rotation_ns = cgmath::Basis3::from_angle_y(self.angle_ns);\n\n let rotation_ew = cgmath::Basis3::from_angle_z(self.angle_ew);\n\n\n\n self.orientation = rotation_ns * rotation_ew;\n\n }\n\n }\n\n\n\n self.render();\n\n }\n\n}\n", "file_path": "src/views/base.rs", "rank": 88, "score": 1.3353772120470846 } ]
Rust
pallets/ai/src/lib.rs
DNFT-Team/dnft-substrate-node
f51822a2b84d4bcfc3dbcb2d1c9829f4c98582a8
#![cfg_attr(not(feature = "std"), no_std)] use codec::Encode; use frame_support::{ decl_error, decl_event, decl_module, decl_storage, ensure, traits::{Currency, Get, Randomness, Time}, StorageMap, StorageValue, }; use frame_system::ensure_signed; use pallet_randomness_collective_flip as randomness; use sp_io::hashing::blake2_256; use sp_runtime::DispatchResult; use sp_std::prelude::*; use utilities::{ AIData, AIDataId, AIModel, AIModelHighlight, AIModelId, ClassId, CollectionId, DataIndustry, DataResource, DataTechnology, ModelLanguage, NFT2006Manager, NFTId, }; type MomentOf<T> = <<T as Config>::Time as Time>::Moment; type BalanceOf<T> = <<T as Config>::Currency as Currency<<T as frame_system::Config>::AccountId>>::Balance; pub trait Config: frame_system::Config { type Event: From<Event<Self>> + Into<<Self as frame_system::Config>::Event>; type NFT2006: NFT2006Manager<Self::AccountId, BalanceOf<Self>>; type Currency: Currency<Self::AccountId>; type Time: Time; } decl_event!( pub enum Event<T> where <T as frame_system::Config>::AccountId, { CreateAIData(AccountId), CreateAIModel(AccountId), BoundAIDataWithNFT(AccountId), BoundAIDataWithCollection(AccountId), BoundAIModelWithNFT(AccountId), } ); decl_error! { pub enum Error for Module<T: Config> { NoPermission, AIDataNotExist, NotAIDataOwner, NFTAlreadyBounded, NFTMintERR, CollectionAlreadyBounded, CollectionCreatERR, NotAIModelOwner, AIModelNotExist, } } decl_storage! { trait Store for Module<T: Config> as AI { pub AIDatas get(fn ai_datas): map hasher(twox_64_concat) AIDataId => Option<AIData<T::AccountId, MomentOf<T>>>; pub AIDataCount get(fn ai_data_count): u64; pub AIDataIndex get(fn ai_data_index): map hasher(blake2_128_concat) u64 => AIDataId; pub AIModels get(fn ai_models): map hasher(twox_64_concat) AIModelId => Option<AIModel<T::AccountId, MomentOf<T>>>; pub AIModelCount get(fn ai_model_count): u64; pub AIModelIndex get(fn ai_model_index): map hasher(blake2_128_concat) u64 => AIModelId; pub DNonce get(fn dnonce): u64; pub MNonce get(fn mnonce): u64; } } decl_module! { pub struct Module<T: Config> for enum Call where origin: T::Origin { type Error = Error<T>; fn deposit_event() = default; #[weight = 10_000 + T::DbWeight::get().reads_writes(1,4)] pub fn create_ai_data( origin, industry: DataIndustry, technology: DataTechnology, resource: DataResource, timestamp: MomentOf<T>, ) { let who = ensure_signed(origin)?; Self::_create_ai_data(industry, technology, resource, timestamp, who.clone())?; Self::deposit_event(RawEvent::CreateAIData(who)); } #[weight = 10_000 + T::DbWeight::get().reads_writes(1,4)] pub fn bound_ai_data_with_nft( origin, ai_data_id: AIDataId, class_id: ClassId, info: Vec<u8>, metadata: Vec<u8>, price: BalanceOf<T>, ) { let who = ensure_signed(origin)?; let ai_data = Self::ai_datas(ai_data_id.clone()).ok_or(Error::<T>::AIDataNotExist)?; ensure!(ai_data.creator == who.clone(), Error::<T>::NotAIDataOwner); ensure!(ai_data.nft_id == None, Error::<T>::NFTAlreadyBounded); let nft_id = T::NFT2006::mint_nft(class_id.clone(), info.clone(), metadata.clone(), price.clone(), who.clone()); ensure!(nft_id != None, Error::<T>::NFTMintERR); Self::_bound_ai_data_nft(ai_data_id, nft_id.unwrap())?; Self::deposit_event(RawEvent::BoundAIDataWithNFT(who)); } #[weight = 10_000 + T::DbWeight::get().reads_writes(1,4)] pub fn bound_ai_data_with_collection( origin, ai_data_id: AIDataId, collection_id: CollectionId, ) { let who = ensure_signed(origin)?; let ai_data = Self::ai_datas(ai_data_id.clone()).ok_or(Error::<T>::AIDataNotExist)?; ensure!(ai_data.creator == who.clone(), Error::<T>::NotAIDataOwner); ensure!(ai_data.collection_id == None, Error::<T>::CollectionAlreadyBounded); let collection = T::NFT2006::get_collection(collection_id.clone()); ensure!(collection != None, Error::<T>::CollectionCreatERR); ensure!(collection.unwrap().owner == who, Error::<T>::NoPermission); Self::_bound_ai_data_collection(ai_data_id, collection_id)?; Self::deposit_event(RawEvent::BoundAIDataWithCollection(who)); } #[weight = 10_000 + T::DbWeight::get().reads_writes(1,4)] pub fn create_ai_model( origin, title: Vec<u8>, language: ModelLanguage, framwork: Vec<u8>, timestamp: MomentOf<T>, highlight: Vec<AIModelHighlight>, ) { let who = ensure_signed(origin)?; Self::_create_ai_model(title, language, framwork, timestamp, highlight, who.clone())?; Self::deposit_event(RawEvent::CreateAIModel(who)); } #[weight = 10_000 + T::DbWeight::get().reads_writes(1,4)] pub fn bound_ai_model_with_nft( origin, ai_model_id: AIModelId, class_id: ClassId, info: Vec<u8>, metadata: Vec<u8>, price: BalanceOf<T>, ) { let who = ensure_signed(origin)?; let ai_model = Self::ai_models(ai_model_id.clone()).ok_or(Error::<T>::AIModelNotExist)?; ensure!(ai_model.creator == who.clone(), Error::<T>::NotAIModelOwner); ensure!(ai_model.nft_id == None, Error::<T>::NFTAlreadyBounded); let nft_id = T::NFT2006::mint_nft(class_id.clone(), info.clone(), metadata.clone(), price.clone(), who.clone()); ensure!(nft_id != None, Error::<T>::NFTMintERR); Self::_bound_ai_model_nft(ai_model_id, nft_id.unwrap())?; Self::deposit_event(RawEvent::BoundAIModelWithNFT(who)); } } } impl<T: Config> Module<T> { fn _create_ai_data( industry: DataIndustry, technology: DataTechnology, resource: DataResource, timestamp: MomentOf<T>, creator: T::AccountId, ) -> DispatchResult { let nonce = Self::get_dnonce(); let random_seed = <randomness::Module<T>>::random_seed(); let encoded = (random_seed, creator.clone(), nonce).encode(); let did = blake2_256(&encoded); let new_ai_data_id = AIDataId { did }; let new_ai_data = AIData { creator: creator.clone(), industry: industry.clone(), technology: technology.clone(), resource: resource.clone(), stars: 0, timestamp: timestamp.clone(), nft_id: None, collection_id: None, }; <AIDatas<T>>::insert(new_ai_data_id.clone(), &new_ai_data); <AIDataCount>::put(nonce.clone() + 1); <AIDataIndex>::insert(nonce.clone(), new_ai_data_id.clone()); Ok(()) } fn _bound_ai_data_nft(ai_data_id: AIDataId, nft_id: NFTId) -> DispatchResult { let mut ai_data = Self::ai_datas(ai_data_id.clone()).ok_or(Error::<T>::AIDataNotExist)?; ai_data.nft_id = Some(nft_id.clone()); <AIDatas<T>>::insert(ai_data_id.clone(), &ai_data); Ok(()) } fn _bound_ai_data_collection( ai_data_id: AIDataId, collection_id: CollectionId, ) -> DispatchResult { let mut ai_data = Self::ai_datas(ai_data_id.clone()).ok_or(Error::<T>::AIDataNotExist)?; ai_data.collection_id = Some(collection_id.clone()); <AIDatas<T>>::insert(ai_data_id.clone(), &ai_data); Ok(()) } fn get_dnonce() -> u64 { let nonce = <DNonce>::get(); <DNonce>::mutate(|n| *n += 1u64); nonce } } impl<T: Config> Module<T> { fn _create_ai_model( title: Vec<u8>, language: ModelLanguage, framwork: Vec<u8>, timestamp: MomentOf<T>, highlight: Vec<AIModelHighlight>, creator: T::AccountId, ) -> DispatchResult { let nonce = Self::get_mnonce(); let random_seed = <randomness::Module<T>>::random_seed(); let encoded = (random_seed, creator.clone(), nonce).encode(); let did = blake2_256(&encoded); let new_ai_model_id = AIModelId { did }; let new_ai_model = AIModel { creator: creator.clone(), title: title.clone(), language: language.clone(), framwork: framwork.clone(), stars: 0, timestamp: timestamp.clone(), highlight: highlight.clone(), nft_id: None, }; <AIModels<T>>::insert(new_ai_model_id.clone(), &new_ai_model); <AIModelCount>::put(nonce.clone() + 1); <AIModelIndex>::insert(nonce.clone(), new_ai_model_id.clone()); Ok(()) } fn _bound_ai_model_nft(ai_model_id: AIModelId, nft_id: NFTId) -> DispatchResult { let mut ai_model = Self::ai_models(ai_model_id.clone()).ok_or(Error::<T>::AIModelNotExist)?; ai_model.nft_id = Some(nft_id.clone()); <AIModels<T>>::insert(ai_model_id.clone(), &ai_model); Ok(()) } fn get_mnonce() -> u64 { let nonce = <MNonce>::get(); <MNonce>::mutate(|n| *n += 1u64); nonce } }
#![cfg_attr(not(feature = "std"), no_std)] use codec::Encode; use frame_support::{ decl_error, decl_event, decl_module, decl_storage, ensure, traits::{Currency, Get, Randomness, Time}, StorageMap, StorageValue, }; use frame_system::ensure_signed; use pallet_randomness_collective_flip as randomness; use sp_io::hashing::blake2_256; use sp_runtime::DispatchResult; use sp_std::prelude::*; use utilities::{ AIData, AIDataId, AIModel, AIModelHighlight, AIModelId, ClassId, CollectionId, DataIndustry, DataResource, DataTechnology, ModelLanguage, NFT2006Manager, NFTId, }; type MomentOf<T> = <<T as Config>::Time as Time>::Moment; type BalanceOf<T> = <<T as Config>::Currency as Currency<<T as frame_system::Config>::AccountId>>::Balance; pub trait Config: frame_system::Config { type Event: From<Event<Self>> + Into<<Self as frame_system::Config>::Event>; type NFT2006: NFT2006Manager<Self::AccountId, BalanceOf<Self>>; type Currency: Currency<Self::AccountId>; type Time: Time; } decl_event!( pub enum Event<T> where <T as frame_system::Config>::AccountId, { CreateAIData(AccountId), CreateAIModel(AccountId), BoundAIDataWithNFT(AccountId), BoundAIDataWithCollection(AccountId), BoundAIModelWithNFT(AccountId), } ); decl_error! { pub enum Error for Module<T: Config> { NoPermission, AIDataNotExist, NotAIDataOwner, NFTAlreadyBounded, NFTMintERR, CollectionAlreadyBounded, CollectionCreatERR, NotAIModelOwner, AIModelNotExist, } } decl_storage! { trait Store for Module<T: Config> as AI { pub AIDatas get(fn ai_datas): map hasher(twox_64_concat) AIDataId => Option<AIData<T::AccountId, MomentOf<T>>>; pub AIDataCount get(fn ai_data_count): u64; pub AIDataIndex get(fn ai_data_index): map hasher(blake2_128_concat) u64 => AIDataId; pub AIModels get(fn ai_models): map hasher(twox_64_concat) AIModelId => Option<AIModel<T::AccountId, MomentOf<T>>>; pub AIModelCount get(fn ai_model_count): u64; pub AIModelIndex get(fn ai_model_index): map hasher(blake2_128_concat) u64 => AIModelId; pub DNonce get(fn dnonce): u64; pub MNonce get(fn mnonce): u64; } } decl_module! { pub struct Module<T: Config> for enum Call where origin: T::Origin { type Error = Error<T>; fn deposit_event() = default; #[weight = 10_000 + T::DbWeight::get().reads_writes(1,4)] pub fn create_ai_data( origin, industry: DataIndustry, technology: DataTechnology, resource: DataResource, timestamp: MomentOf<T>, ) { let who = ensure_signed(origin)?; Self::_create_ai_data(industry, technology, resource, timestamp, who.clone())?; Self::deposit_event(RawEvent::CreateAIData(who)); } #[weight = 10_000 + T::DbWeight::get().reads_writes(1,4)] pub fn bound_ai_data_with_nft( origin, ai_data_id: AIDataId, class_id: ClassId, info: Vec<u8>, metadata: Vec<u8>, price: BalanceOf<T>, ) { let who = ensure_signed(origin)?; let ai_data = Self::ai_datas(ai_data_id.clone()).ok_or(Error::<T>::AIDataNotExist)?; ensure!(ai_data.creator == who.clone(), Error::<T>::NotAIDataOwner); ensure!(ai_data.nft_id == None, Error::<T>::NFTAlreadyBounded); let nft_id = T::NFT2006::mint_nft(class_id.clone(), info.clone(), metadata.clone(), price.clone(), who.clone()); ensure!(nft_id != None, Error::<T>::NFTMintERR); Self::_bound_ai_data_nft(ai_data_id, nft_id.unwrap())?; Self::deposit_event(RawEvent::BoundAIDataWithNFT(who)); } #[weight = 10_000 + T::DbWeight::get().reads_writes(1,4)] pub fn bound_ai_data_with_collection( origin, ai_data_id: AIDataId, collection_id: CollectionId, ) { let who = ensure_signed(origin)?; let ai_data = Self::ai_datas(ai_data_id.clone()).ok_or(Error::<T>::AIDataNotExist)?; ensure!(ai_data.creator == who.clone(), Error::<T>::NotAIDataOwner); ensure!(ai_data.collection_id == None, Error::<T>::CollectionAlreadyBounded); let collection = T::NFT2006::get_collection(collection_id.clone()); ensure!(collection != None, Error::<T>::CollectionCreatERR); ensure!(collection.unwrap().owner == who, Error::<T>::NoPermission); Self::_bound_ai_data_collection(ai_data_id, collection_id)?; Self::deposit_event(RawEvent::BoundAIDataWithCollection(who)); } #[weight = 10_000 + T::DbWeight::get().reads_writes(1,4)] pub fn create_ai_model( origin, title: Vec<u8>, language: ModelLanguage, framwork: Vec<u8>, timestamp: MomentOf<T>, highlight: Vec<AIModelHighlight>, ) { let who = ensure_signed(origin)?; Self::_create_ai_model(title, language, framwork, timestamp, highlight, who.clone())?; Self::deposit_event(RawEvent::CreateAIModel(who)); } #[weight = 10_000 + T::DbWeight::get().reads_writes(1,4)] pub fn bound_ai_model_with_nft( origin, ai_model_id: AIModelId, class_id: ClassId, info: Vec<u8>, metadata: Vec<u8>, price: BalanceOf<T>, ) { let who = ensure_signed(origin)?; let ai_model = Self::ai_models(ai_model_id.clone()).ok_or(Error::<T>::AIModelNotExist)?; ensure!(ai_model.creator == who.clone(), Error::<T>::NotAIModelOwner); ensure!(ai_model.nft_id == None, Error::<T>::NFTAlreadyBounded); let nft_id = T::NFT2006::mint_nft(class_id.clone(), info.clone(), metadata.clone(), price.clone(), who.clone()); ensure!(nft_id != None, Error::<T>::NFTMintERR); Self::_bound_ai_model_nft(ai_model_id, nft_id.unwrap())?; Self::deposit_event(RawEvent::BoundAIModelWithNFT(who)); } } } impl<T: Config> Module<T> { fn _create_ai_data( industry: DataIndustry, technology: DataTechnology, resource: DataResource, timestamp: MomentOf<T>, creator: T::AccountId, ) -> DispatchResult { let nonce = Self::get_dnonce(); let random_seed = <randomness::Module<T>>::random_seed(); let encoded = (random_seed, creator.clone(), nonce).encode(); let did = blake2_256(&encoded); let new_ai_data_id = AIDataId { did }; let new_ai_data = AIData { creator: creator.clone(), industry: industry.clone(), technology: technology.clone(), resource: resource.clone(), stars: 0, timestamp: timestamp.clone(), nft_id: None, collection_id: None, }; <AIDatas<T>>::insert(new_ai_data_id.clone(), &new_ai_data); <AIDataCount>::put(nonce.clone() + 1); <AIDataIndex>::insert(nonce.clone(), new_ai_data_id.clone()); Ok(()) } fn _bound_ai_data_nft(ai_data_id: AIDataId, nft_id: NFTId) -> DispatchResult { let mut ai_data = Self::ai_datas(ai_data_id.clone()).ok_or(Error::<T>::AIDataNotExist)?; ai_data.nft_id = Some(nft_id.clone()); <AIDatas<T>>::insert(ai_data_id.clone(), &ai_data); Ok(()) }
fn get_dnonce() -> u64 { let nonce = <DNonce>::get(); <DNonce>::mutate(|n| *n += 1u64); nonce } } impl<T: Config> Module<T> { fn _create_ai_model( title: Vec<u8>, language: ModelLanguage, framwork: Vec<u8>, timestamp: MomentOf<T>, highlight: Vec<AIModelHighlight>, creator: T::AccountId, ) -> DispatchResult { let nonce = Self::get_mnonce(); let random_seed = <randomness::Module<T>>::random_seed(); let encoded = (random_seed, creator.clone(), nonce).encode(); let did = blake2_256(&encoded); let new_ai_model_id = AIModelId { did }; let new_ai_model = AIModel { creator: creator.clone(), title: title.clone(), language: language.clone(), framwork: framwork.clone(), stars: 0, timestamp: timestamp.clone(), highlight: highlight.clone(), nft_id: None, }; <AIModels<T>>::insert(new_ai_model_id.clone(), &new_ai_model); <AIModelCount>::put(nonce.clone() + 1); <AIModelIndex>::insert(nonce.clone(), new_ai_model_id.clone()); Ok(()) } fn _bound_ai_model_nft(ai_model_id: AIModelId, nft_id: NFTId) -> DispatchResult { let mut ai_model = Self::ai_models(ai_model_id.clone()).ok_or(Error::<T>::AIModelNotExist)?; ai_model.nft_id = Some(nft_id.clone()); <AIModels<T>>::insert(ai_model_id.clone(), &ai_model); Ok(()) } fn get_mnonce() -> u64 { let nonce = <MNonce>::get(); <MNonce>::mutate(|n| *n += 1u64); nonce } }
fn _bound_ai_data_collection( ai_data_id: AIDataId, collection_id: CollectionId, ) -> DispatchResult { let mut ai_data = Self::ai_datas(ai_data_id.clone()).ok_or(Error::<T>::AIDataNotExist)?; ai_data.collection_id = Some(collection_id.clone()); <AIDatas<T>>::insert(ai_data_id.clone(), &ai_data); Ok(()) }
function_block-full_function
[ { "content": "pub trait Config: frame_system::Config {\n\n type Event: From<Event<Self>> + Into<<Self as frame_system::Config>::Event>;\n\n type Currency: Currency<Self::AccountId>;\n\n type Token: TokenManager<Self::AccountId>;\n\n}\n\n\n\ndecl_event!(\n\n pub enum Event<T> where\n\n <T as frame_system::Config>::AccountId,\n\n {\n\n CreateClass(AccountId),\n\n\n\n MintNFT(AccountId),\n\n\n\n TransferSingleNFT(AccountId),\n\n\n\n OfferNFT(AccountId),\n\n\n\n BuyNFT(AccountId),\n\n\n", "file_path": "pallets/nft2006/src/lib.rs", "rank": 1, "score": 188792.5449828197 }, { "content": " trait Store for Module<T: Config> as NFT2006 {\n\n\n\n // Class\n\n pub ClassInfos get(fn class_infos): map hasher(twox_64_concat) ClassId => Option<ClassInfo<T::AccountId>>;\n\n pub ClassCount get(fn class_count): u64;\n\n pub ClassIndex get(fn class_index): map hasher(blake2_128_concat) u64 => ClassId;\n\n pub ClassMintIndex get(fn class_mint_index): map hasher(blake2_128_concat) ClassId => u64;\n\n\n\n // NFT\n\n pub NFTInfos get(fn nft_infos): map hasher(twox_64_concat) NFTId => Option<NFTInfo<T::AccountId, BalanceOf<T>> >;\n\n pub NFTsCount get(fn nfts_count): u64;\n\n pub NFTsIndex get(fn nfts_index): map hasher(blake2_128_concat) u64 => NFTId;\n\n\n\n pub NFTByClassIndex get(fn nft_by_class_index):\n\n double_map hasher(blake2_128_concat) ClassId, hasher(blake2_128_concat) u64 => Option<NFTId>;\n\n\n\n // CNonce\n\n pub CNonce get(fn cnonce): u64;\n\n // TNonce\n\n pub TNonce get(fn tnonce): u64;\n", "file_path": "pallets/nft2006/src/lib.rs", "rank": 3, "score": 186395.82620481093 }, { "content": "/// Builds a new service for a light client.\n\npub fn new_light(mut config: Configuration) -> Result<TaskManager, ServiceError> {\n\n\tlet (client, backend, keystore_container, mut task_manager, on_demand) =\n\n\t\tsc_service::new_light_parts::<Block, RuntimeApi, Executor>(&config)?;\n\n\n\n\tconfig.network.extra_sets.push(sc_finality_grandpa::grandpa_peers_set_config());\n\n\n\n\tlet select_chain = sc_consensus::LongestChain::new(backend.clone());\n\n\n\n\tlet transaction_pool = Arc::new(sc_transaction_pool::BasicPool::new_light(\n\n\t\tconfig.transaction_pool.clone(),\n\n\t\tconfig.prometheus_registry(),\n\n\t\ttask_manager.spawn_handle(),\n\n\t\tclient.clone(),\n\n\t\ton_demand.clone(),\n\n\t));\n\n\n\n\tlet (grandpa_block_import, _) = sc_finality_grandpa::block_import(\n\n\t\tclient.clone(),\n\n\t\t&(client.clone() as Arc<_>),\n\n\t\tselect_chain.clone(),\n", "file_path": "node/src/service.rs", "rank": 4, "score": 178410.73129780777 }, { "content": "/// Builds a new service for a full client.\n\npub fn new_full(mut config: Configuration) -> Result<TaskManager, ServiceError> {\n\n\tlet sc_service::PartialComponents {\n\n\t\tclient,\n\n\t\tbackend,\n\n\t\tmut task_manager,\n\n\t\timport_queue,\n\n\t\tmut keystore_container,\n\n\t\tselect_chain,\n\n\t\ttransaction_pool,\n\n\t\tinherent_data_providers,\n\n\t\tother: (block_import, grandpa_link),\n\n\t} = new_partial(&config)?;\n\n\n\n\tif let Some(url) = &config.keystore_remote {\n\n\t\tmatch remote_keystore(url) {\n\n\t\t\tOk(k) => keystore_container.set_remote_keystore(k),\n\n\t\t\tErr(e) => {\n\n\t\t\t\treturn Err(ServiceError::Other(\n\n\t\t\t\t\tformat!(\"Error hooking up remote keystore for {}: {}\", url, e)))\n\n\t\t\t}\n", "file_path": "node/src/service.rs", "rank": 5, "score": 178410.73129780777 }, { "content": "pub trait Config: frame_system::Config {\n\n type Event: From<Event<Self>> + Into<<Self as frame_system::Config>::Event>;\n\n type Currency: Currency<Self::AccountId>;\n\n type NFT721: NFT721Manager<Self::AccountId, BalanceOf<Self>>;\n\n type NFT1155: NFT1155Manager<Self::AccountId, BalanceOf<Self>>;\n\n type NFT2006: NFT2006Manager<Self::AccountId, BalanceOf<Self>>;\n\n type DAO: DAOManager<Self::AccountId, BalanceOf<Self>>;\n\n}\n\n\n\ndecl_event!(\n\n pub enum Event<T> where\n\n <T as frame_system::Config>::AccountId,\n\n {\n\n\n\n MintNFT721WithTax(AccountId),\n\n\n\n MintNFT1155WithTax(AccountId),\n\n\n\n MintNFT2006WithTax(AccountId),\n\n\n", "file_path": "pallets/tax/src/lib.rs", "rank": 7, "score": 161516.86887457408 }, { "content": "pub trait Config: frame_system::Config {\n\n type Event: From<Event<Self>> + Into<<Self as frame_system::Config>::Event>;\n\n type Common: CommonManager<Self::AccountId>;\n\n}\n\n\n\ndecl_storage! {\n", "file_path": "pallets/token/src/lib.rs", "rank": 8, "score": 161516.8688745741 }, { "content": "pub trait Config: frame_system::Config {\n\n type Event: From<Event<Self>> + Into<<Self as frame_system::Config>::Event>;\n\n type Currency: Currency<Self::AccountId>;\n\n}\n\n\n\ndecl_event!(\n\n pub enum Event<T> where\n\n <T as frame_system::Config>::AccountId,\n\n {\n\n\n\n CreateClass(AccountId),\n\n\n\n MintNFT(AccountId),\n\n\n\n TransferNFT(AccountId),\n\n\n\n OfferNFT(AccountId),\n\n\n\n BuyNFT(AccountId),\n\n\n", "file_path": "pallets/nft721/src/lib.rs", "rank": 9, "score": 161516.86887457408 }, { "content": "pub trait Config: frame_system::Config {\n\n type Event: From<Event<Self>> + Into<<Self as frame_system::Config>::Event>;\n\n type Currency: Currency<Self::AccountId>;\n\n}\n\n\n\ndecl_event!(\n\n pub enum Event<T> where\n\n <T as frame_system::Config>::AccountId,\n\n {\n\n SetDAOAcc(AccountId),\n\n\n\n SetDAOTax(AccountId),\n\n\n\n UpdateDAOTax(AccountId),\n\n\n\n NewProposal(AccountId),\n\n\n\n VoteProposal(AccountId),\n\n }\n\n);\n\n\n\ndecl_error! {\n\n pub enum Error for Module<T: Config> {\n\n NoPermission,\n\n ParamERR,\n\n }\n\n}\n\n\n", "file_path": "pallets/dao/src/lib.rs", "rank": 10, "score": 161516.86887457408 }, { "content": "pub trait Config: frame_system::Config {\n\n\ttype Event: From<Event<Self>> + Into<<Self as frame_system::Config>::Event>;\n\n}\n\n\n\ndecl_storage! {\n", "file_path": "pallets/common/src/lib.rs", "rank": 11, "score": 161516.86887457408 }, { "content": "pub trait Config: frame_system::Config {\n\n type Event: From<Event<Self>> + Into<<Self as frame_system::Config>::Event>;\n\n type Currency: Currency<Self::AccountId>;\n\n}\n\n\n\ndecl_event!(\n\n pub enum Event<T> where\n\n <T as frame_system::Config>::AccountId,\n\n {\n\n CreateClass(AccountId),\n\n\n\n MintNFT(AccountId),\n\n\n\n TransferSingleNFT(AccountId),\n\n\n\n OfferNFT(AccountId),\n\n\n\n BuyNFT(AccountId),\n\n\n\n BurnNFT(AccountId),\n", "file_path": "pallets/nft1155/src/lib.rs", "rank": 12, "score": 161516.86887457408 }, { "content": "pub trait Config: frame_system::Config {\n\n type Event: From<Event<Self>> + Into<<Self as frame_system::Config>::Event>;\n\n type Token: TokenManager<Self::AccountId>;\n\n type Common: CommonManager<Self::AccountId>;\n\n}\n\n\n\ndecl_storage! {\n", "file_path": "pallets/trade_pair/src/lib.rs", "rank": 13, "score": 158650.378344971 }, { "content": "pub trait Config: frame_system::Config {\n\n type Event: From<Event<Self>> + Into<<Self as frame_system::Config>::Event>;\n\n type Currency: Currency<Self::AccountId>;\n\n type Time: Time;\n\n type NFT721: NFT721Manager<Self::AccountId, BalanceOf<Self>>;\n\n type NFT1155: NFT1155Manager<Self::AccountId, BalanceOf<Self>>;\n\n type NFT2006: NFT2006Manager<Self::AccountId, BalanceOf<Self>>;\n\n}\n\n\n\ndecl_storage! {\n", "file_path": "pallets/swap_auction/src/lib.rs", "rank": 14, "score": 158650.378344971 }, { "content": "pub trait Config: frame_system::Config {\n\n type Event: From<Event<Self>> + Into<<Self as frame_system::Config>::Event>;\n\n type Time: Time;\n\n type Token: TokenManager<Self::AccountId>;\n\n type Common: CommonManager<Self::AccountId>;\n\n type TradePair: TradePairManager<Self::AccountId>;\n\n}\n\n\n\ndecl_event!(\n\n pub enum Event<T> where\n\n <T as frame_system::Config>::AccountId,\n\n {\n\n\n\n LimitOrderCreated(AccountId, Did, OrderType, u64, u64),\n\n\n\n OrderCanceled(AccountId, Did),\n\n }\n\n);\n\n\n\ndecl_error! {\n", "file_path": "pallets/swap_orderbook/src/lib.rs", "rank": 15, "score": 158650.378344971 }, { "content": "pub trait Config: frame_system::Config {\n\n type Event: From<Event<Self>> + Into<<Self as frame_system::Config>::Event>;\n\n type Token: TokenManager<Self::AccountId>;\n\n type Common: CommonManager<Self::AccountId>;\n\n type TradePair: TradePairManager<Self::AccountId>;\n\n}\n\n\n\ndecl_storage! {\n", "file_path": "pallets/swap_amm/src/lib.rs", "rank": 16, "score": 158650.378344971 }, { "content": "pub trait NFT2006Manager<AccountId, Balance> {\n\n // nft class\n\n fn issue_nft_class(\n\n name: Vec<u8>,\n\n info: Vec<u8>,\n\n supply: u64,\n\n issuer: AccountId,\n\n ) -> DispatchResult;\n\n\n\n fn get_class(class_id: ClassId) -> Option<ClassInfo<AccountId>>;\n\n\n\n // NFT\n\n fn mint_nft(\n\n class_id: ClassId,\n\n info: Vec<u8>,\n\n metadata: Vec<u8>,\n\n price: Balance,\n\n miner: AccountId,\n\n ) -> Option<NFTId>;\n\n\n", "file_path": "pallets/utilities/src/lib.rs", "rank": 17, "score": 146427.14277255844 }, { "content": "type MomentOf<T> = <<T as Config>::Time as Time>::Moment;\n", "file_path": "pallets/swap_auction/src/lib.rs", "rank": 18, "score": 136909.5104823586 }, { "content": "type MomentOf<T> = <<T as Config>::Time as Time>::Moment;\n\n\n", "file_path": "pallets/swap_orderbook/src/lib.rs", "rank": 19, "score": 136909.5104823586 }, { "content": " trait Store for Module<T: Config> as NFT1155 {\n\n\n\n // Class\n\n pub ClassInfos get(fn class_infos): map hasher(twox_64_concat) ClassId => Option<ClassInfo<T::AccountId>>;\n\n pub ClassCount get(fn class_count): u64;\n\n pub ClassIndex get(fn class_index): map hasher(blake2_128_concat) u64 => ClassId;\n\n pub ClassMintIndex get(fn class_mint_index): map hasher(blake2_128_concat) ClassId => u64;\n\n\n\n // NFT\n\n pub NFTInfos get(fn nft_infos): map hasher(twox_64_concat) NFTId => Option<NFTInfo<T::AccountId, BalanceOf<T>> >;\n\n pub NFTsCount get(fn nfts_count): u64;\n\n pub NFTsIndex get(fn nfts_index): map hasher(blake2_128_concat) u64 => NFTId;\n\n\n\n pub NFTByClassIndex get(fn nft_by_class_index):\n\n double_map hasher(blake2_128_concat) ClassId, hasher(blake2_128_concat) u64 => Option<NFTId>;\n\n\n\n // CNonce\n\n pub CNonce get(fn cnonce): u64;\n\n // TNonce\n\n pub TNonce get(fn tnonce): u64;\n", "file_path": "pallets/nft1155/src/lib.rs", "rank": 20, "score": 132008.3126794331 }, { "content": " trait Store for Module<T: Config> as Tax {\n\n\n\n // Tax\n\n pub NFTInTax get(fn nft_in_tax): map hasher(blake2_128_concat) T::AccountId => Vec<NFTId>;\n\n\n\n }\n\n}\n\n\n\ndecl_module! {\n\n pub struct Module<T: Config> for enum Call where origin: T::Origin {\n\n type Error = Error<T>;\n\n fn deposit_event() = default;\n\n\n\n #[weight = 10_000]\n\n pub fn mint_nft721_with_tax(\n\n origin,\n\n class_id: ClassId,\n\n info: Vec<u8>,\n\n metadata: Vec<u8>,\n\n price: BalanceOf<T>,\n", "file_path": "pallets/tax/src/lib.rs", "rank": 21, "score": 132008.3126794331 }, { "content": " trait Store for Module<T: Config> as NFT721 {\n\n\n\n // Class\n\n pub ClassInfos get(fn class_infos): map hasher(twox_64_concat) ClassId => Option<ClassInfo<T::AccountId>>;\n\n pub ClassCount get(fn class_count): u64;\n\n pub ClassIndex get(fn class_index): map hasher(blake2_128_concat) u64 => ClassId;\n\n pub ClassMintIndex get(fn class_mint_index): map hasher(blake2_128_concat) ClassId => u64;\n\n\n\n // NFT\n\n pub NFTInfos get(fn nft_infos): map hasher(twox_64_concat) NFTId => Option<NFTInfo<T::AccountId, BalanceOf<T>> >;\n\n pub NFTsCount get(fn nfts_count): u64;\n\n pub NFTsIndex get(fn nfts_index): map hasher(blake2_128_concat) u64 => NFTId;\n\n pub OwnedNFTs get(fn owned_nfts): map hasher(blake2_128_concat) T::AccountId => Vec<NFTId>;\n\n pub NFTByClassIndex get(fn nft_by_class_index):\n\n double_map hasher(blake2_128_concat) ClassId, hasher(blake2_128_concat) u64 => Option<NFTId>;\n\n\n\n // CNonce\n\n pub CNonce get(fn cnonce): u64;\n\n pub TNonce get(fn tnonce): u64;\n\n\n", "file_path": "pallets/nft721/src/lib.rs", "rank": 22, "score": 132008.3126794331 }, { "content": "\ttrait Store for Module<T: Config> as Common {\n\n\t\tpub GenDid get(fn gen_did): Did;\n\n\t\tpub GenHash get(fn gen_hash): H256;\n\n\t\tpub BufferCount get(fn get_buffer_count): u32;\n\n\t\tpub BufferMap get(fn get_value): map hasher(twox_64_concat) BufferIndex => ValueStruct;\n\n\t\tpub BufferRange get(fn range): (BufferIndex, BufferIndex) = (0, 0);\n\n\t}\n\n}\n\n\n\ndecl_event!(\n\n\tpub enum Event<T>\n\n\twhere\n\n\t\tAccountId = <T as frame_system::Config>::AccountId,\n\n\t{\n\n\t\tGenerateDid(AccountId, u64, Did),\n\n\t\tGenerateHash(AccountId, u64, H256),\n\n\t\tPopped(u32, bool),\n\n\t\tDummyEvent(AccountId),\n\n\t}\n\n);\n", "file_path": "pallets/common/src/lib.rs", "rank": 23, "score": 132008.3126794331 }, { "content": " trait Store for Module<T: Config> as Token {\n\n pub Tokens get(fn token): map hasher(blake2_128_concat) Did => Option<Token<T::AccountId>>;\n\n pub Balances get(fn balance_of): map hasher(blake2_128_concat) (T::AccountId, Did) => u64;\n\n pub StaticBalances get(fn static_balance_of): map hasher(blake2_128_concat) (Did, Did) => u64;\n\n pub FreeBalances get(fn free_balance_of): map hasher(blake2_128_concat) (T::AccountId, Did) => u64;\n\n pub FreezedBalances get(fn freezed_balance_of): map hasher(blake2_128_concat) (T::AccountId, Did) => u64;\n\n\n\n pub OwnedTokens get(fn owned_token): map hasher(blake2_128_concat) (T::AccountId, u64) => Option<Did>;\n\n pub OwnedTokensIndex get(fn owned_token_index): map hasher(blake2_128_concat) T::AccountId => u64;\n\n\n\n pub Nonce get(fn nonce): u64;\n\n\n\n }\n\n}\n\n\n\ndecl_event!(\n\n pub enum Event<T>\n\n where\n\n AccountId = <T as frame_system::Config>::AccountId,\n\n {\n", "file_path": "pallets/token/src/lib.rs", "rank": 24, "score": 132008.3126794331 }, { "content": " trait Store for Module<T: Config> as Dao {\n\n\n\n // DNFTDAO\n\n pub DAOAcc get(fn dao_acc): T::AccountId;\n\n pub DAOTax get(fn dao_tax): BalanceOf<T>;\n\n\n\n // Proposal\n\n pub Proposals get(fn proposals): map hasher(blake2_128_concat) ProposalId => Option<Proposal<T::AccountId, BalanceOf<T>>>;\n\n pub ProposalsCount get(fn proposals_count): u64;\n\n pub ProposalsIndex get(fn proposals_index): map hasher(blake2_128_concat) u64 => ProposalId;\n\n\n\n pub MemberProposals get(fn member_proposals):\n\n double_map hasher(blake2_128_concat) ProposalId, hasher(blake2_128_concat) T::AccountId => bool;\n\n pub PNonce get(fn pnonce): u64;\n\n }\n\n}\n\n\n\ndecl_module! {\n\n pub struct Module<T: Config> for enum Call where origin: T::Origin {\n\n type Error = Error<T>;\n", "file_path": "pallets/dao/src/lib.rs", "rank": 25, "score": 132008.3126794331 }, { "content": " trait Store for Module<T: Config> as Amm {\n\n\n\n ///\tLiquidityPoolId => TradePair\n\n LiquidityPools get(fn liquidity_pools): map hasher(blake2_128_concat) Did => Option<LiquidityPool>;\n\n /// Index => LiquidityPoolId\n\n LiquidityPoolIdByIndex get(fn liquidity_pool_id_by_index): map hasher(blake2_128_concat) u64 => Option<Did>;\n\n /// Index\n\n LiquidityPoolIndex get(fn liquidity_pool_index): u64;\n\n /// LiquidityPoolId => Vec<AccountId>\n\n LiquidityPoolProviders get(fn liquidity_pool_providers):map hasher(blake2_128_concat) Did => Vec<T::AccountId>;\n\n /// AccountId => Vec<Index>\n\n OwnedLiquidityPools get(fn owned_liquidity_pools):map hasher(blake2_128_concat) T::AccountId => Vec<Did>;\n\n /// (AccountId,LiquidityPoolId)=> Share\n\n OwnedLiquidityPoolShare get(fn owned_liquidity_pool_share):map hasher(blake2_128_concat) (T::AccountId,Did) => u64;\n\n\n\n\n\n /// AmmOrderId => AmmOrder\n\n AmmOrders get(fn amm_orders): map hasher(blake2_128_concat) Did => Option<AmmOrder<T::AccountId>>;\n\n /// Index => AmmOrderId\n\n AmmOrderIdByIndex get(fn amm_order_id_by_index): map hasher(blake2_128_concat) u64 => Option<Did>;\n", "file_path": "pallets/swap_amm/src/lib.rs", "rank": 26, "score": 129081.63079869791 }, { "content": " trait Store for Module<T: Config> as Auction {\n\n // Auction\n\n pub Auctions get(fn auctions): map hasher(twox_64_concat) AuctionId => Option<Auction<T::AccountId, BalanceOf<T>, MomentOf<T>>>;\n\n pub AuctionCount get(fn auction_count): u64;\n\n pub AuctionIndex get(fn auction_index): map hasher(blake2_128_concat) u64 => AuctionId;\n\n\n\n pub Bids get(fn bids): map hasher(blake2_128_concat) AuctionId => Vec<BidInfo<T::AccountId, BalanceOf<T>, MomentOf<T>>>;\n\n\n\n // Nonce\n\n pub ANonce get(fn anonce): u64;\n\n\n\n }\n\n}\n\n\n\ndecl_event!(\n\n pub enum Event<T>\n\n where\n\n <T as frame_system::Config>::AccountId,\n\n {\n\n LanuchAuction(AccountId),\n", "file_path": "pallets/swap_auction/src/lib.rs", "rank": 27, "score": 129081.63079869791 }, { "content": "pub trait TokenManager<AccountId> {\n\n // issue\n\n fn issue(from: AccountId, total_supply: u64, symbol: Vec<u8>) -> Did;\n\n\n\n // transfer\n\n fn transfer(\n\n from: AccountId,\n\n to: AccountId,\n\n token_id: Did,\n\n value: u64,\n\n memo: Option<Vec<u8>>,\n\n ) -> DispatchResult;\n\n\n\n // transfer\n\n fn static_transfer_in(from: AccountId, to: Did, token_id: Did, value: u64) -> DispatchResult;\n\n fn static_transfer_out(from: Did, to: AccountId, token_id: Did, value: u64) -> DispatchResult;\n\n\n\n // freeze\n\n fn freeze(from: AccountId, token_id: Did, value: u64) -> DispatchResult;\n\n\n", "file_path": "pallets/utilities/src/lib.rs", "rank": 28, "score": 126814.27404997265 }, { "content": "pub trait CommonManager<AccountId> {\n\n /// did\n\n fn generate_did(from: AccountId, nonce: u64) -> Did;\n\n fn generate_hash(from: AccountId, nonce: u64) -> H256;\n\n /// ringbuffer\n\n fn add_to_queue(id: u32, integer: u32, boolean: bool);\n\n fn add_multiple(id: u32, integers: Vec<u32>, boolean: bool);\n\n fn pop_from_queue(id: u32);\n\n fn get_buffer_range(id: u32) -> (BufferIndex, BufferIndex);\n\n fn get_buffer_value(id: u32, index: BufferIndex) -> ValueStruct;\n\n}\n\n\n\n/// token\n\n#[derive(Encode, Decode, PartialEq, Eq, Clone, RuntimeDebug)]\n\npub struct Token<AccountId> {\n\n pub tid: Did,\n\n pub owner: AccountId,\n\n pub symbol: Vec<u8>,\n\n pub total_supply: u64,\n\n}\n\n\n", "file_path": "pallets/utilities/src/lib.rs", "rank": 29, "score": 126814.27404997265 }, { "content": " trait Store for Module<T: Config> as TradePair {\n\n ///\tTradePairId => TradePair\n\n TradePairs get(fn trade_pairs): map hasher(blake2_128_concat) Did => Option<TradePair>;\n\n /// (BaseTokenId, quoteTokenId) => TradePairId\n\n TradePairIdByBaseQuote get(fn trade_pair_id_by_base_quote): map hasher(blake2_128_concat) (Did, Did) => Option<Did>;\n\n /// Index => TradePairId\n\n TradePairIdByIndex get(fn trade_pair_id_by_index): map hasher(blake2_128_concat) u64 => Option<Did>;\n\n /// Index\n\n TradePairIndex get(fn trade_pair_index): u64;\n\n\n\n Nonce: u64;\n\n\n\n }\n\n}\n\n\n\ndecl_event!(\n\n pub enum Event<T>\n\n where\n\n <T as frame_system::Config>::AccountId,\n\n {\n", "file_path": "pallets/trade_pair/src/lib.rs", "rank": 30, "score": 126354.04913640556 }, { "content": " trait Store for Module<T: Config> as OrderBook {\n\n\n\n /// OrderId => Order\n\n pub Orders get(fn order): map hasher(blake2_128_concat) Did => Option<LimitOrder<T::AccountId, MomentOf<T>>>;\n\n /// Index => OrderId\n\n pub OrderIdByIndex get(fn order_id_by_index): map hasher(blake2_128_concat) u32 => Option<Did>;\n\n /// Index\n\n pub OrderIndex get(fn order_index): u32;\n\n /// (AccoundId, Index) => OrderId\n\n pub OwnedOrders get(fn owned_order): map hasher(blake2_128_concat) (T::AccountId, u64) => Option<Did>;\n\n ///\tAccountId => Index\n\n pub OwnedOrdersIndex get(fn owned_orders_index): map hasher(blake2_128_concat) T::AccountId => u64;\n\n /// (OrderId, u64) => TradeId\n\n pub OrderOwnedTrades get(fn order_owned_trades): map hasher(blake2_128_concat) (Did, u64) => Option<Did>;\n\n /// (OrderId, u64) => TradeId\n\n pub OrderOwnedTradesIndex get(fn order_owned_trades_index): map hasher(blake2_128_concat) Did => u64;\n\n\n\n\n\n /// (AccountId, TradePairHash) => Vec<OrderId>\n\n pub OwnedTPOpenedOrders get(fn owned_tp_opened_orders): map hasher(blake2_128_concat) (T::AccountId, Did) => Vec<Did>;\n", "file_path": "pallets/swap_orderbook/src/lib.rs", "rank": 31, "score": 126354.04913640556 }, { "content": "pub trait TradePairManager<AccountId> {\n\n // create_trade_pair\n\n fn create_trade_pair(\n\n sender: AccountId,\n\n base: Did,\n\n quote: Did,\n\n method: TradeMethod,\n\n matched_price: Option<u64>,\n\n ) -> Result<Did, dispatch::DispatchError>;\n\n\n\n // update_trade_pair\n\n fn transfer(sender: AccountId, tpid: Did, new_trade_pair: TradePair) -> DispatchResult;\n\n\n\n // get_trade_pair\n\n fn get_trade_pair(tpid: Did) -> Option<TradePair>;\n\n //get_trade_pair_id_by_base_quote\n\n fn get_trade_pair_id_by_base_quote(base: Did, quote: Did) -> Option<Did>;\n\n}\n\n\n\n#[derive(Encode, Decode, PartialEq, Eq, Clone, RuntimeDebug)]\n", "file_path": "pallets/utilities/src/lib.rs", "rank": 32, "score": 123896.63147765926 }, { "content": "pub fn new_partial(config: &Configuration) -> Result<sc_service::PartialComponents<\n\n\tFullClient, FullBackend, FullSelectChain,\n\n\tsp_consensus::DefaultImportQueue<Block, FullClient>,\n\n\tsc_transaction_pool::FullPool<Block, FullClient>,\n\n\t(\n\n\t\tsc_consensus_aura::AuraBlockImport<\n\n\t\t\tBlock,\n\n\t\t\tFullClient,\n\n\t\t\tsc_finality_grandpa::GrandpaBlockImport<FullBackend, Block, FullClient, FullSelectChain>,\n\n\t\t\tAuraPair\n\n\t\t>,\n\n\t\tsc_finality_grandpa::LinkHalf<Block, FullClient, FullSelectChain>,\n\n\t)\n\n>, ServiceError> {\n\n\tif config.keystore_remote.is_some() {\n\n\t\treturn Err(ServiceError::Other(\n\n\t\t\tformat!(\"Remote Keystores are not supported.\")))\n\n\t}\n\n\tlet inherent_data_providers = InherentDataProviders::new();\n\n\n", "file_path": "node/src/service.rs", "rank": 33, "score": 120511.1501961273 }, { "content": "pub trait NFT721Manager<AccountId, Balance> {\n\n // Class\n\n fn issue_nft_class(\n\n name: Vec<u8>,\n\n info: Vec<u8>,\n\n total_supply: u64,\n\n issuer: AccountId,\n\n ) -> DispatchResult;\n\n\n\n fn get_class(class_id: ClassId) -> Option<ClassInfo<AccountId>>;\n\n\n\n // NFT\n\n fn mint_nft(\n\n class_id: ClassId,\n\n info: Vec<u8>,\n\n metadata: Vec<u8>,\n\n price: Balance,\n\n miner: AccountId,\n\n ) -> Option<NFTId>;\n\n\n\n fn get_nft(nft_id: NFTId) -> Option<NFTInfo<AccountId, Balance>>;\n\n\n\n // Todo safeTransfer\n\n fn transfer_single_nft(from: AccountId, to: AccountId, nft_id: NFTId) -> DispatchResult;\n\n\n\n fn destroy_single_nft(who: AccountId, nft_id: NFTId) -> DispatchResult;\n\n}\n\n\n", "file_path": "pallets/utilities/src/lib.rs", "rank": 34, "score": 120111.90882092685 }, { "content": "pub trait DAOManager<AccountId, Balance> {\n\n fn get_dao_account() -> AccountId;\n\n fn get_dao_tax() -> Balance;\n\n}\n\n\n\n#[derive(Encode, Decode, RuntimeDebug, Eq, PartialEq, Clone)]\n\npub struct AIModelHighlight {\n\n pub theme: Vec<u8>,\n\n pub info: Vec<u8>,\n\n pub score: u64,\n\n}\n\n\n\n#[derive(Encode, Decode, Copy, Clone, PartialEq, Eq, RuntimeDebug)]\n\npub enum ModelLanguage {\n\n Python = 0,\n\n Js,\n\n Java,\n\n Matlab,\n\n Lisp,\n\n Prolog,\n", "file_path": "pallets/utilities/src/lib.rs", "rank": 35, "score": 120111.90882092685 }, { "content": "pub trait NFT1155Manager<AccountId, Balance> {\n\n // nft class\n\n fn issue_nft_class(\n\n name: Vec<u8>,\n\n info: Vec<u8>,\n\n supply: u64,\n\n issuer: AccountId,\n\n ) -> DispatchResult;\n\n\n\n fn get_class(class_id: ClassId) -> Option<ClassInfo<AccountId>>;\n\n\n\n // NFT\n\n fn mint_nft(\n\n class_id: ClassId,\n\n info: Vec<u8>,\n\n metadata: Vec<u8>,\n\n price: Balance,\n\n miner: AccountId,\n\n ) -> Option<NFTId>;\n\n\n", "file_path": "pallets/utilities/src/lib.rs", "rank": 36, "score": 120111.90882092685 }, { "content": "// Build genesis storage according to the mock runtime.\n\npub fn new_test_ext() -> sp_io::TestExternalities {\n\n\tlet mut t = frame_system::GenesisConfig::default().build_storage::<Test>().unwrap();\n\n\n\n pallet_balances::GenesisConfig::<Test>{\n\n\t\tbalances: vec![(200, 500)],\n\n }.assimilate_storage(&mut t).unwrap();\n\n\t\n\n\tlet mut t: sp_io::TestExternalities = t.into();\n\n\n\n t.execute_with(|| System::set_block_number(1) );\n\n t\n\n}\n", "file_path": "pallets/nft2006/src/mock.rs", "rank": 37, "score": 114663.20320926976 }, { "content": "pub fn development_config() -> Result<ChainSpec, String> {\n\n\tlet wasm_binary = WASM_BINARY.ok_or_else(|| \"Development wasm not available\".to_string())?;\n\n\n\n\tOk(ChainSpec::from_genesis(\n\n\t\t// Name\n\n\t\t\"Development\",\n\n\t\t// ID\n\n\t\t\"dev\",\n\n\t\tChainType::Development,\n\n\t\tmove || testnet_genesis(\n\n\t\t\twasm_binary,\n\n\t\t\t// Initial PoA authorities\n\n\t\t\tvec![\n\n\t\t\t\tauthority_keys_from_seed(\"Alice\"),\n\n\t\t\t],\n\n\t\t\t// Sudo account\n\n\t\t\tget_account_id_from_seed::<sr25519::Public>(\"Alice\"),\n\n\t\t\t// Pre-funded accounts\n\n\t\t\tvec![\n\n\t\t\t\tget_account_id_from_seed::<sr25519::Public>(\"Alice\"),\n", "file_path": "node/src/chain_spec.rs", "rank": 38, "score": 114339.32088150718 }, { "content": "pub fn local_testnet_config() -> Result<ChainSpec, String> {\n\n\tlet wasm_binary = WASM_BINARY.ok_or_else(|| \"Development wasm not available\".to_string())?;\n\n\n\n\tOk(ChainSpec::from_genesis(\n\n\t\t// Name\n\n\t\t\"Local Testnet\",\n\n\t\t// ID\n\n\t\t\"local_testnet\",\n\n\t\tChainType::Local,\n\n\t\tmove || testnet_genesis(\n\n\t\t\twasm_binary,\n\n\t\t\t// Initial PoA authorities\n\n\t\t\tvec![\n\n\t\t\t\tauthority_keys_from_seed(\"Alice\"),\n\n\t\t\t\tauthority_keys_from_seed(\"Bob\"),\n\n\t\t\t],\n\n\t\t\t// Sudo account\n\n\t\t\tget_account_id_from_seed::<sr25519::Public>(\"Alice\"),\n\n\t\t\t// Pre-funded accounts\n\n\t\t\tvec![\n", "file_path": "node/src/chain_spec.rs", "rank": 39, "score": 111798.7066960585 }, { "content": "/// Trait object presenting the ringbuffer interface.\n\npub trait RingBufferTrait<Item>\n\nwhere\n\n\tItem: Codec + EncodeLike,\n\n{\n\n\t/// Store all changes made in the underlying storage.\n\n\t///\n\n\t/// Data is not guaranteed to be consistent before this call.\n\n\t///\n\n\t/// Implementation note: Call in `drop` to increase ergonomics.\n\n\tfn commit(&self);\n\n\t/// Push an item onto the end of the queue.\n\n\tfn push(&mut self, i: Item);\n\n\t/// Pop an item from the start of the queue.\n\n\t///\n\n\t/// Returns `None` if the queue is empty.\n\n\tfn pop(&mut self) -> Option<Item>;\n\n\t/// Return whether the queue is empty.\n\n\tfn is_empty(&self) -> bool;\n\n}\n\n\n", "file_path": "pallets/common/src/ringbuffer.rs", "rank": 40, "score": 109354.09460011832 }, { "content": "// There is no equivalent trait in std so we create one.\n\npub trait WrappingOps {\n\n\tfn wrapping_add(self, rhs: Self) -> Self;\n\n\tfn wrapping_sub(self, rhs: Self) -> Self;\n\n}\n\n\n\nmacro_rules! impl_wrapping_ops {\n\n\t($type:ty) => {\n\n\t\timpl WrappingOps for $type {\n\n\t\t\tfn wrapping_add(self, rhs: Self) -> Self {\n\n\t\t\t\tself.wrapping_add(rhs)\n\n\t\t\t}\n\n\t\t\tfn wrapping_sub(self, rhs: Self) -> Self {\n\n\t\t\t\tself.wrapping_sub(rhs)\n\n\t\t\t}\n\n\t\t}\n\n\t};\n\n}\n\n\n\nimpl_wrapping_ops!(u8);\n\nimpl_wrapping_ops!(u16);\n\nimpl_wrapping_ops!(u32);\n\nimpl_wrapping_ops!(u64);\n\n\n", "file_path": "pallets/common/src/ringbuffer.rs", "rank": 41, "score": 108075.6815327685 }, { "content": "/// Trait object presenting the ringbuffer interface.\n\npub trait RingBufferTrait<Item>\n\nwhere\n\n\tItem: Codec + EncodeLike,\n\n{\n\n\t/// Store all changes made in the underlying storage.\n\n\t///\n\n\t/// Data is not guaranteed to be consistent before this call.\n\n\t///\n\n\t/// Implementation note: Call in `drop` to increase ergonomics.\n\n\tfn commit(&self);\n\n\t/// Push an item onto the end of the queue.\n\n\tfn push(&mut self, i: Item);\n\n\t/// Pop an item from the start of the queue.\n\n\t///\n\n\t/// Returns `None` if the queue is empty.\n\n\tfn pop(&mut self) -> Option<Item>;\n\n\t/// Return whether the queue is empty.\n\n\tfn is_empty(&self) -> bool;\n\n}\n\n\n", "file_path": "pallets/swap_orderbook/src/ringbuffer.rs", "rank": 42, "score": 107460.89639250678 }, { "content": "// There is no equivalent trait in std so we create one.\n\npub trait WrappingOps {\n\n\tfn wrapping_add(self, rhs: Self) -> Self;\n\n\tfn wrapping_sub(self, rhs: Self) -> Self;\n\n}\n\n\n\nmacro_rules! impl_wrapping_ops {\n\n\t($type:ty) => {\n\n\t\timpl WrappingOps for $type {\n\n\t\t\tfn wrapping_add(self, rhs: Self) -> Self {\n\n\t\t\t\tself.wrapping_add(rhs)\n\n\t\t\t}\n\n\t\t\tfn wrapping_sub(self, rhs: Self) -> Self {\n\n\t\t\t\tself.wrapping_sub(rhs)\n\n\t\t\t}\n\n\t\t}\n\n\t};\n\n}\n\n\n\nimpl_wrapping_ops!(u8);\n\nimpl_wrapping_ops!(u16);\n\nimpl_wrapping_ops!(u32);\n\nimpl_wrapping_ops!(u64);\n\n\n", "file_path": "pallets/swap_orderbook/src/ringbuffer.rs", "rank": 43, "score": 105820.32333355205 }, { "content": "#[cfg(feature = \"std\")]\n\npub fn native_version() -> NativeVersion {\n\n NativeVersion {\n\n runtime_version: VERSION,\n\n can_author_with: Default::default(),\n\n }\n\n}\n\n\n\nconst NORMAL_DISPATCH_RATIO: Perbill = Perbill::from_percent(75);\n\n\n\nparameter_types! {\n\n pub const Version: RuntimeVersion = VERSION;\n\n pub const BlockHashCount: BlockNumber = 2400;\n\n /// We allow for 2 seconds of compute with a 6 second average block time.\n\n pub BlockWeights: frame_system::limits::BlockWeights = frame_system::limits::BlockWeights\n\n ::with_sensible_defaults(2 * WEIGHT_PER_SECOND, NORMAL_DISPATCH_RATIO);\n\n pub BlockLength: frame_system::limits::BlockLength = frame_system::limits::BlockLength\n\n ::max_with_normal_ratio(5 * 1024 * 1024, NORMAL_DISPATCH_RATIO);\n\n pub const SS58Prefix: u8 = 42;\n\n}\n\n\n", "file_path": "runtime/src/lib.rs", "rank": 44, "score": 101422.92554320453 }, { "content": "/// Instantiate all full RPC extensions.\n\npub fn create_full<C, P>(\n\n\tdeps: FullDeps<C, P>,\n\n) -> jsonrpc_core::IoHandler<sc_rpc::Metadata> where\n\n\tC: ProvideRuntimeApi<Block>,\n\n\tC: HeaderBackend<Block> + HeaderMetadata<Block, Error=BlockChainError> + 'static,\n\n\tC: Send + Sync + 'static,\n\n\tC::Api: substrate_frame_rpc_system::AccountNonceApi<Block, AccountId, Index>,\n\n\tC::Api: pallet_transaction_payment_rpc::TransactionPaymentRuntimeApi<Block, Balance>,\n\n\tC::Api: BlockBuilder<Block>,\n\n\tP: TransactionPool + 'static,\n\n{\n\n\tuse substrate_frame_rpc_system::{FullSystem, SystemApi};\n\n\tuse pallet_transaction_payment_rpc::{TransactionPayment, TransactionPaymentApi};\n\n\n\n\tlet mut io = jsonrpc_core::IoHandler::default();\n\n\tlet FullDeps {\n\n\t\tclient,\n\n\t\tpool,\n\n\t\tdeny_unsafe,\n\n\t} = deps;\n", "file_path": "node/src/rpc.rs", "rank": 45, "score": 97621.56331935598 }, { "content": "/// Parse and run command line arguments\n\npub fn run() -> sc_cli::Result<()> {\n\n\tlet cli = Cli::from_args();\n\n\n\n\tmatch &cli.subcommand {\n\n\t\tSome(Subcommand::Key(cmd)) => cmd.run(&cli),\n\n\t\tSome(Subcommand::BuildSpec(cmd)) => {\n\n\t\t\tlet runner = cli.create_runner(cmd)?;\n\n\t\t\trunner.sync_run(|config| cmd.run(config.chain_spec, config.network))\n\n\t\t},\n\n\t\tSome(Subcommand::CheckBlock(cmd)) => {\n\n\t\t\tlet runner = cli.create_runner(cmd)?;\n\n\t\t\trunner.async_run(|config| {\n\n\t\t\t\tlet PartialComponents { client, task_manager, import_queue, ..}\n\n\t\t\t\t\t= service::new_partial(&config)?;\n\n\t\t\t\tOk((cmd.run(client, import_queue), task_manager))\n\n\t\t\t})\n\n\t\t},\n\n\t\tSome(Subcommand::ExportBlocks(cmd)) => {\n\n\t\t\tlet runner = cli.create_runner(cmd)?;\n\n\t\t\trunner.async_run(|config| {\n", "file_path": "node/src/command.rs", "rank": 46, "score": 97621.56331935598 }, { "content": "/// Generate an account ID from seed.\n\npub fn get_account_id_from_seed<TPublic: Public>(seed: &str) -> AccountId where\n\n\tAccountPublic: From<<TPublic::Pair as Pair>::Public>\n\n{\n\n\tAccountPublic::from(get_from_seed::<TPublic>(seed)).into_account()\n\n}\n\n\n", "file_path": "node/src/chain_spec.rs", "rank": 47, "score": 96247.4446804513 }, { "content": "// Build genesis storage according to the mock runtime.\n\npub fn new_test_ext() -> sp_io::TestExternalities {\n\n\tlet mut t = frame_system::GenesisConfig::default().build_storage::<Test>().unwrap();\n\n\n\n pallet_balances::GenesisConfig::<Test>{\n\n\t\tbalances: vec![(200, 500)],\n\n }.assimilate_storage(&mut t).unwrap();\n\n\t\n\n\tlet mut t: sp_io::TestExternalities = t.into();\n\n\n\n t.execute_with(|| System::set_block_number(1) );\n\n t\n\n}\n", "file_path": "pallets/nft1155/src/mock.rs", "rank": 48, "score": 90079.28689803527 }, { "content": "// Build genesis storage according to the mock runtime.\n\npub fn new_test_ext() -> sp_io::TestExternalities {\n\n\tlet mut t = frame_system::GenesisConfig::default().build_storage::<Test>().unwrap();\n\n\n\n pallet_balances::GenesisConfig::<Test>{\n\n\t\tbalances: vec![(200, 500)],\n\n }.assimilate_storage(&mut t).unwrap();\n\n\t\n\n\tlet mut t: sp_io::TestExternalities = t.into();\n\n\n\n t.execute_with(|| System::set_block_number(1) );\n\n t\n\n}\n", "file_path": "pallets/nft721/src/mock.rs", "rank": 49, "score": 90079.28689803527 }, { "content": "/// Generate a crypto pair from seed.\n\npub fn get_from_seed<TPublic: Public>(seed: &str) -> <TPublic::Pair as Pair>::Public {\n\n\tTPublic::Pair::from_string(&format!(\"//{}\", seed), None)\n\n\t\t.expect(\"static values are valid; qed\")\n\n\t\t.public()\n\n}\n\n\n", "file_path": "node/src/chain_spec.rs", "rank": 50, "score": 89543.93722913277 }, { "content": "#[test]\n\nfn create_class_should_work() {\n\n new_test_ext().execute_with(|| {\n\n assert_ok!(NFT1155Module::create_class(\n\n Origin::signed(1),\n\n vec![1],\n\n vec![2],\n\n 1000\n\n ));\n\n })\n\n}\n\n\n", "file_path": "pallets/nft2006/src/tests.rs", "rank": 52, "score": 86559.90008843437 }, { "content": "#[test]\n\nfn mint_nft_should_work() {\n\n new_test_ext().execute_with(|| {\n\n let did = blake2_256(b\"test\");\n\n let new_class_id = ClassId { did };\n\n assert_ok!(NFT1155Module::mint_nft(\n\n Origin::signed(1),\n\n new_class_id,\n\n vec![1],\n\n vec![2],\n\n 100\n\n ));\n\n })\n\n}\n\n\n", "file_path": "pallets/nft2006/src/tests.rs", "rank": 53, "score": 86559.90008843437 }, { "content": "#[test]\n\nfn transfer_nft_should_work() {\n\n new_test_ext().execute_with(|| {\n\n let did = blake2_256(b\"test\");\n\n let new_class_id = ClassId { did };\n\n let nft_id = NFT1155Module::_mint_nft(new_class_id, vec![1], vec![2], 100, 1);\n\n assert_eq!(nft_id, None);\n\n })\n\n}\n", "file_path": "pallets/nft2006/src/tests.rs", "rank": 54, "score": 86559.90008843437 }, { "content": "type BalanceOf<T> =\n\n <<T as Config>::Currency as Currency<<T as frame_system::Config>::AccountId>>::Balance;\n\n\n\ndecl_storage! {\n", "file_path": "pallets/nft2006/src/lib.rs", "rank": 55, "score": 86529.99092712413 }, { "content": "type DefaultIdx = u16;\n\n/// Transient backing data that is the backbone of the trait object.\n\npub struct RingBufferTransient<Item, B, M, Index = DefaultIdx>\n\nwhere\n\n\tItem: Codec + EncodeLike,\n\n\tB: StorageValue<(Index, Index), Query = (Index, Index)>,\n\n\tM: StorageMap<Index, Item, Query = Item>,\n\n\tIndex: Codec + EncodeLike + Eq + WrappingOps + From<u8> + Copy,\n\n{\n\n\tstart: Index,\n\n\tend: Index,\n\n\t_phantom: PhantomData<(Item, B, M)>,\n\n}\n\n\n\nimpl<Item, B, M, Index> RingBufferTransient<Item, B, M, Index>\n\nwhere\n\n\tItem: Codec + EncodeLike,\n\n\tB: StorageValue<(Index, Index), Query = (Index, Index)>,\n\n\tM: StorageMap<Index, Item, Query = Item>,\n\n\tIndex: Codec + EncodeLike + Eq + WrappingOps + From<u8> + Copy,\n", "file_path": "pallets/common/src/ringbuffer.rs", "rank": 56, "score": 84857.04061472481 }, { "content": "type DefaultIdx = u16;\n\n/// Transient backing data that is the backbone of the trait object.\n\npub struct RingBufferTransient<Item, B, M, Index = DefaultIdx>\n\nwhere\n\n\tItem: Codec + EncodeLike,\n\n\tB: StorageValue<(Index, Index), Query = (Index, Index)>,\n\n\tM: StorageMap<Index, Item, Query = Item>,\n\n\tIndex: Codec + EncodeLike + Eq + WrappingOps + From<u8> + Copy,\n\n{\n\n\tstart: Index,\n\n\tend: Index,\n\n\t_phantom: PhantomData<(Item, B, M)>,\n\n}\n\n\n\nimpl<Item, B, M, Index> RingBufferTransient<Item, B, M, Index>\n\nwhere\n\n\tItem: Codec + EncodeLike,\n\n\tB: StorageValue<(Index, Index), Query = (Index, Index)>,\n\n\tM: StorageMap<Index, Item, Query = Item>,\n\n\tIndex: Codec + EncodeLike + Eq + WrappingOps + From<u8> + Copy,\n", "file_path": "pallets/swap_orderbook/src/ringbuffer.rs", "rank": 57, "score": 82586.75982506393 }, { "content": "/// Generate an Aura authority key.\n\npub fn authority_keys_from_seed(s: &str) -> (AuraId, GrandpaId) {\n\n\t(\n\n\t\tget_from_seed::<AuraId>(s),\n\n\t\tget_from_seed::<GrandpaId>(s),\n\n\t)\n\n}\n\n\n", "file_path": "node/src/chain_spec.rs", "rank": 58, "score": 82573.32290079075 }, { "content": "type Block = frame_system::mocking::MockBlock<Test>;\n\n\n\n// Configure a mock runtime to test the pallet.\n\nframe_support::construct_runtime!(\n\n\tpub enum Test where\n\n\t\tBlock = Block,\n\n\t\tNodeBlock = Block,\n\n\t\tUncheckedExtrinsic = UncheckedExtrinsic,\n\n\t{\n\n\t\tSystem: frame_system::{Module, Call, Config, Storage, Event<T>},\n\n\t\tBalances: pallet_balances::{Module, Call, Storage, Config<T>, Event<T>},\n\n\t\tNFT1155Module: pallet_nft1155::{Module, Call, Storage, Event<T>},\n\n\t}\n\n);\n\n\n\nparameter_types! {\n\n\tpub const BlockHashCount: u64 = 250;\n\n\tpub const SS58Prefix: u8 = 42;\n\n\tpub const ExistentialDeposit: u64 = 1;\n\n}\n", "file_path": "pallets/nft2006/src/mock.rs", "rank": 59, "score": 70124.79134912751 }, { "content": "type OrderType = amm::OrderType;\n\nuse support::Did;\n\n\n\n#[derive(Encode, Decode, Clone)]\n\n#[cfg_attr(feature = \"std\", derive(PartialEq, Eq, Debug))]\n\npub struct LinkedItem {\n\n pub prev: Option<u64>,\n\n pub next: Option<u64>,\n\n pub price: Option<u64>,\n\n pub buy_amount: u64,\n\n pub sell_amount: u64,\n\n pub orders: Vec<Did>, // remove the item at 0 index will caused performance issue, should be optimized\n\n}\n\n\n\npub struct LinkedList<T, S>(sp_std::marker::PhantomData<(T, S)>);\n\n\n\n/// LinkedItem LinkedItem\t\t\tLinkedItem LinkedItem LinkedItem\n\n/// Bottom Buy Order\t\t\tHead Sell Order Top\n\n/// \t\t\tNext\t ----> Price: 8\t<----\tPrev Next ----> Price: max\n\n/// max <---- Prev\t\t\t\tNext\t\t---->\tPrice:None <---- Prev Next ----> Price: 0\n", "file_path": "pallets/swap_auction/src/types.rs", "rank": 60, "score": 68213.97008129484 }, { "content": "type UncheckedExtrinsic = frame_system::mocking::MockUncheckedExtrinsic<Test>;\n", "file_path": "pallets/nft2006/src/mock.rs", "rank": 61, "score": 66868.09143081609 }, { "content": "fn main() {\n\n\tgenerate_cargo_keys();\n\n\n\n\trerun_if_git_head_changed();\n\n}\n", "file_path": "node/build.rs", "rank": 62, "score": 62710.343777591275 }, { "content": "fn main() {\n\n\tWasmBuilder::new()\n\n\t\t.with_current_project()\n\n\t\t.export_heap_base()\n\n\t\t.import_memory()\n\n\t\t.build()\n\n}\n", "file_path": "runtime/build.rs", "rank": 63, "score": 62710.343777591275 }, { "content": "#[test]\n\nfn cant_spend_more_than_you_have() {\n\n\tExtBuilder::build().execute_with(|| {\n\n\t\tassert_ok!(BasicToken::init(Origin::signed(1)));\n\n\t\tassert_noop!(\n\n\t\t\tBasicToken::transfer(Origin::signed(1), 2, 21000001),\n\n\t\t\tError::<TestRuntime>::InsufficientFunds\n\n\t\t);\n\n\t})\n\n}\n", "file_path": "pallets/token/src/tests.rs", "rank": 64, "score": 58358.59249425612 }, { "content": "/// Configure initial storage state for FRAME modules.\n\nfn testnet_genesis(\n\n\twasm_binary: &[u8],\n\n\tinitial_authorities: Vec<(AuraId, GrandpaId)>,\n\n\troot_key: AccountId,\n\n\tendowed_accounts: Vec<AccountId>,\n\n\t_enable_println: bool,\n\n) -> GenesisConfig {\n\n\tGenesisConfig {\n\n\t\tframe_system: Some(SystemConfig {\n\n\t\t\t// Add Wasm runtime to storage.\n\n\t\t\tcode: wasm_binary.to_vec(),\n\n\t\t\tchanges_trie_config: Default::default(),\n\n\t\t}),\n\n\t\tpallet_balances: Some(BalancesConfig {\n\n\t\t\t// Configure endowed accounts with initial balance of 1 << 60.\n\n\t\t\tbalances: endowed_accounts.iter().cloned().map(|k|(k, 1 << 60)).collect(),\n\n\t\t}),\n\n\t\tpallet_aura: Some(AuraConfig {\n\n\t\t\tauthorities: initial_authorities.iter().map(|x| (x.0.clone())).collect(),\n\n\t\t}),\n\n\t\tpallet_grandpa: Some(GrandpaConfig {\n\n\t\t\tauthorities: initial_authorities.iter().map(|x| (x.1.clone(), 1)).collect(),\n\n\t\t}),\n\n\t\tpallet_sudo: Some(SudoConfig {\n\n\t\t\t// Assign network admin rights.\n\n\t\t\tkey: root_key,\n\n\t\t}),\n\n\t}\n\n}\n", "file_path": "node/src/chain_spec.rs", "rank": 65, "score": 58358.59249425612 }, { "content": "#[test]\n\nfn transfer_works() {\n\n\tExtBuilder::build().execute_with(|| {\n\n\t\tassert_ok!(BasicToken::init(Origin::signed(1)));\n\n\n\n\t\t// Transfer 100 tokens from user 1 to user 2\n\n\t\tassert_ok!(BasicToken::transfer(Origin::signed(1), 2, 100));\n\n\n\n\t\tassert_eq!(BasicToken::get_balance(1), 20999900);\n\n\t\tassert_eq!(BasicToken::get_balance(2), 100);\n\n\t})\n\n}\n\n\n", "file_path": "pallets/token/src/tests.rs", "rank": 66, "score": 58358.59249425612 }, { "content": "#[test]\n\nfn init_works() {\n\n\tExtBuilder::build().execute_with(|| {\n\n\t\tassert_ok!(BasicToken::init(Origin::signed(1)));\n\n\t\tassert_eq!(BasicToken::get_balance(1), 21000000);\n\n\t})\n\n}\n\n\n", "file_path": "pallets/token/src/tests.rs", "rank": 67, "score": 58358.59249425612 }, { "content": "#[test]\n\nfn mint_nft_should_work() {\n\n new_test_ext().execute_with(|| {\n\n let did = blake2_256(b\"test\");\n\n let new_class_id = ClassId { did };\n\n assert_ok!(NFT721Module::mint_nft(\n\n Origin::signed(1),\n\n new_class_id,\n\n vec![1],\n\n vec![2],\n\n 100\n\n ));\n\n })\n\n}\n\n\n", "file_path": "pallets/nft721/src/tests.rs", "rank": 68, "score": 57136.45537206248 }, { "content": "#[test]\n\nfn mint_nft_should_work() {\n\n new_test_ext().execute_with(|| {\n\n let did = blake2_256(b\"test\");\n\n let new_class_id = ClassId { did };\n\n assert_ok!(NFT1155Module::mint_nft(\n\n Origin::signed(1),\n\n new_class_id,\n\n vec![1],\n\n vec![2],\n\n 100\n\n ));\n\n })\n\n}\n\n\n", "file_path": "pallets/nft1155/src/tests.rs", "rank": 69, "score": 57136.45537206248 }, { "content": "#[test]\n\nfn cant_double_init() {\n\n\tExtBuilder::build().execute_with(|| {\n\n\t\tassert_ok!(BasicToken::init(Origin::signed(1)));\n\n\t\tassert_noop!(\n\n\t\t\tBasicToken::init(Origin::signed(1)),\n\n\t\t\tError::<TestRuntime>::AlreadyInitialized\n\n\t\t);\n\n\t})\n\n}\n\n\n", "file_path": "pallets/token/src/tests.rs", "rank": 70, "score": 57136.45537206248 }, { "content": "#[test]\n\nfn create_class_should_work() {\n\n new_test_ext().execute_with(|| {\n\n assert_ok!(NFT1155Module::create_class(\n\n Origin::signed(1),\n\n vec![1],\n\n vec![2],\n\n 1000\n\n ));\n\n })\n\n}\n\n\n", "file_path": "pallets/nft1155/src/tests.rs", "rank": 71, "score": 57136.45537206248 }, { "content": "#[test]\n\nfn transfer_nft_should_work() {\n\n new_test_ext().execute_with(|| {\n\n let did = blake2_256(b\"test\");\n\n let new_class_id = ClassId { did };\n\n let nft_id = NFT721Module::_mint_nft(new_class_id, vec![1], vec![2], 100, 1);\n\n assert_eq!(nft_id, None);\n\n })\n\n}\n", "file_path": "pallets/nft721/src/tests.rs", "rank": 72, "score": 57136.45537206248 }, { "content": "#[test]\n\nfn transfer_nft_should_work() {\n\n new_test_ext().execute_with(|| {\n\n let did = blake2_256(b\"test\");\n\n let new_class_id = ClassId { did };\n\n let nft_id = NFT1155Module::_mint_nft(new_class_id, vec![1], vec![2], 100, 1);\n\n assert_eq!(nft_id, None);\n\n })\n\n}\n", "file_path": "pallets/nft1155/src/tests.rs", "rank": 73, "score": 57136.45537206248 }, { "content": "#[test]\n\nfn create_class_should_work() {\n\n new_test_ext().execute_with(|| {\n\n assert_ok!(NFT721Module::create_class(\n\n Origin::signed(1),\n\n vec![1],\n\n vec![2],\n\n 1000\n\n ));\n\n })\n\n}\n\n\n", "file_path": "pallets/nft721/src/tests.rs", "rank": 74, "score": 57136.45537206248 }, { "content": "type BalanceOf<T> =\n\n <<T as Config>::Currency as Currency<<T as frame_system::Config>::AccountId>>::Balance;\n\ndecl_storage! {\n", "file_path": "pallets/dao/src/lib.rs", "rank": 75, "score": 55900.62198661818 }, { "content": "type BalanceOf<T> =\n\n <<T as Config>::Currency as Currency<<T as frame_system::Config>::AccountId>>::Balance;\n\ndecl_storage! {\n", "file_path": "pallets/tax/src/lib.rs", "rank": 76, "score": 55900.62198661818 }, { "content": "type BalanceOf<T> =\n\n <<T as Config>::Currency as Currency<<T as frame_system::Config>::AccountId>>::Balance;\n\n\n\ndecl_storage! {\n", "file_path": "pallets/nft1155/src/lib.rs", "rank": 77, "score": 55900.62198661818 }, { "content": "type BalanceOf<T> =\n\n <<T as Config>::Currency as Currency<<T as frame_system::Config>::AccountId>>::Balance;\n\ndecl_storage! {\n", "file_path": "pallets/nft721/src/lib.rs", "rank": 78, "score": 55900.62198661818 }, { "content": "type BalanceOf<T> =\n\n <<T as Config>::Currency as Currency<<T as frame_system::Config>::AccountId>>::Balance;\n\n\n", "file_path": "pallets/swap_auction/src/lib.rs", "rank": 79, "score": 54681.01449455187 }, { "content": "fn main() -> sc_cli::Result<()> {\n\n\tcommand::run()\n\n}\n", "file_path": "node/src/main.rs", "rank": 80, "score": 51989.038656083794 }, { "content": "type AccountPublic = <Signature as Verify>::Signer;\n\n\n", "file_path": "node/src/chain_spec.rs", "rank": 81, "score": 46581.261723527394 }, { "content": "type FullBackend = sc_service::TFullBackend<Block>;\n", "file_path": "node/src/service.rs", "rank": 82, "score": 46340.276876400225 }, { "content": "type Block = frame_system::mocking::MockBlock<Test>;\n\n\n\n// Configure a mock runtime to test the pallet.\n\nframe_support::construct_runtime!(\n\n\tpub enum Test where\n\n\t\tBlock = Block,\n\n\t\tNodeBlock = Block,\n\n\t\tUncheckedExtrinsic = UncheckedExtrinsic,\n\n\t{\n\n\t\tSystem: frame_system::{Module, Call, Config, Storage, Event<T>},\n\n\t\tBalances: pallet_balances::{Module, Call, Storage, Config<T>, Event<T>},\n\n\t\tNFT721Module: pallet_nft721::{Module, Call, Storage, Event<T>},\n\n\t}\n\n);\n\n\n\nparameter_types! {\n\n\tpub const BlockHashCount: u64 = 250;\n\n\tpub const SS58Prefix: u8 = 42;\n\n\tpub const ExistentialDeposit: u64 = 1;\n\n}\n", "file_path": "pallets/nft721/src/mock.rs", "rank": 83, "score": 44704.66131409065 }, { "content": "type Block = frame_system::mocking::MockBlock<Test>;\n\n\n\n// Configure a mock runtime to test the pallet.\n\nframe_support::construct_runtime!(\n\n\tpub enum Test where\n\n\t\tBlock = Block,\n\n\t\tNodeBlock = Block,\n\n\t\tUncheckedExtrinsic = UncheckedExtrinsic,\n\n\t{\n\n\t\tSystem: frame_system::{Module, Call, Config, Storage, Event<T>},\n\n\t\tBalances: pallet_balances::{Module, Call, Storage, Config<T>, Event<T>},\n\n\t\tNFT1155Module: pallet_nft1155::{Module, Call, Storage, Event<T>},\n\n\t}\n\n);\n\n\n\nparameter_types! {\n\n\tpub const BlockHashCount: u64 = 250;\n\n\tpub const SS58Prefix: u8 = 42;\n\n\tpub const ExistentialDeposit: u64 = 1;\n\n}\n", "file_path": "pallets/nft1155/src/mock.rs", "rank": 84, "score": 44704.66131409065 }, { "content": "type FullSelectChain = sc_consensus::LongestChain<FullBackend, Block>;\n\n\n", "file_path": "node/src/service.rs", "rank": 85, "score": 43067.125266528106 }, { "content": "type UncheckedExtrinsic = frame_system::mocking::MockUncheckedExtrinsic<Test>;\n", "file_path": "pallets/nft721/src/mock.rs", "rank": 86, "score": 43067.125266528106 }, { "content": "type UncheckedExtrinsic = frame_system::mocking::MockUncheckedExtrinsic<Test>;\n", "file_path": "pallets/nft1155/src/mock.rs", "rank": 87, "score": 43067.125266528106 }, { "content": "type FullClient = sc_service::TFullClient<Block, RuntimeApi, Executor>;\n", "file_path": "node/src/service.rs", "rank": 88, "score": 40928.839410738 }, { "content": "fn remote_keystore(_url: &String) -> Result<Arc<LocalKeystore>, &'static str> {\n\n\t// FIXME: here would the concrete keystore be built,\n\n\t// must return a concrete type (NOT `LocalKeystore`) that\n\n\t// implements `CryptoStore` and `SyncCryptoStore`\n\n\tErr(\"Remote Keystore not supported.\")\n\n}\n\n\n", "file_path": "node/src/service.rs", "rank": 89, "score": 39191.582853215295 } ]
Rust
packages/storage-plus/src/iter_helpers.rs
DragonSBFinance/terra_smartcontract
9cfa31192a1b7d72c1ba95cca76a50befa030623
#![cfg(feature = "iterator")] use serde::de::DeserializeOwned; use cosmwasm_std::Pair; use cosmwasm_std::{from_slice, StdResult}; use crate::helpers::encode_length; pub(crate) fn deserialize_kv<T: DeserializeOwned>(kv: Pair) -> StdResult<Pair<T>> { let (k, v) = kv; let t = from_slice::<T>(&v)?; Ok((k, t)) } #[allow(dead_code)] pub(crate) fn to_length_prefixed(namespace: &[u8]) -> Vec<u8> { let mut out = Vec::with_capacity(namespace.len() + 2); out.extend_from_slice(&encode_length(namespace)); out.extend_from_slice(namespace); out } #[inline] pub(crate) fn trim(namespace: &[u8], key: &[u8]) -> Vec<u8> { key[namespace.len()..].to_vec() } #[inline] pub(crate) fn concat(namespace: &[u8], key: &[u8]) -> Vec<u8> { let mut k = namespace.to_vec(); k.extend_from_slice(key); k } #[cfg(test)] mod test { use super::*; #[test] fn to_length_prefixed_works() { assert_eq!(to_length_prefixed(b""), b"\x00\x00"); assert_eq!(to_length_prefixed(b"a"), b"\x00\x01a"); assert_eq!(to_length_prefixed(b"ab"), b"\x00\x02ab"); assert_eq!(to_length_prefixed(b"abc"), b"\x00\x03abc"); } #[test] fn to_length_prefixed_works_for_long_prefix() { let long_namespace1 = vec![0; 256]; let prefix1 = to_length_prefixed(&long_namespace1); assert_eq!(prefix1.len(), 256 + 2); assert_eq!(&prefix1[0..2], b"\x01\x00"); let long_namespace2 = vec![0; 30000]; let prefix2 = to_length_prefixed(&long_namespace2); assert_eq!(prefix2.len(), 30000 + 2); assert_eq!(&prefix2[0..2], b"\x75\x30"); let long_namespace3 = vec![0; 0xFFFF]; let prefix3 = to_length_prefixed(&long_namespace3); assert_eq!(prefix3.len(), 0xFFFF + 2); assert_eq!(&prefix3[0..2], b"\xFF\xFF"); } #[test] #[should_panic(expected = "only supports namespaces up to length 0xFFFF")] fn to_length_prefixed_panics_for_too_long_prefix() { let limit = 0xFFFF; let long_namespace = vec![0; limit + 1]; to_length_prefixed(&long_namespace); } #[test] fn to_length_prefixed_calculates_capacity_correctly() { let key = to_length_prefixed(b""); assert_eq!(key.capacity(), key.len()); let key = to_length_prefixed(b"h"); assert_eq!(key.capacity(), key.len()); let key = to_length_prefixed(b"hij"); assert_eq!(key.capacity(), key.len()); } } #[cfg(test)] #[cfg(not(feature = "iterator"))] mod namespace_test { use super::*; use cosmwasm_std::testing::MockStorage; #[test] fn test_range() { let mut storage = MockStorage::new(); let prefix = to_length_prefixed(b"foo"); let other_prefix = to_length_prefixed(b"food"); set_with_prefix(&mut storage, &prefix, b"bar", b"none"); set_with_prefix(&mut storage, &prefix, b"snowy", b"day"); set_with_prefix(&mut storage, &other_prefix, b"moon", b"buggy"); let mut iter = range_with_prefix(&storage, &prefix, None, None, Order::Descending); let first = iter.next().unwrap(); assert_eq!(first, (b"snowy".to_vec(), b"day".to_vec())); let second = iter.next().unwrap(); assert_eq!(second, (b"bar".to_vec(), b"none".to_vec())); assert!(iter.next().is_none()); let iter = storage.range(None, None, Order::Ascending); assert_eq!(3, iter.count()); let mut iter = storage.range(None, None, Order::Ascending); let first = iter.next().unwrap(); let expected_key = concat(&prefix, b"bar"); assert_eq!(first, (expected_key, b"none".to_vec())); } #[test] fn test_range_with_prefix_wrapover() { let mut storage = MockStorage::new(); let prefix = to_length_prefixed(b"f\xff\xff"); let other_prefix = to_length_prefixed(b"f\xff\x44"); set_with_prefix(&mut storage, &prefix, b"bar", b"none"); set_with_prefix(&mut storage, &prefix, b"snowy", b"day"); set_with_prefix(&mut storage, &other_prefix, b"moon", b"buggy"); let iter = range_with_prefix(&storage, &prefix, None, None, Order::Descending); let elements: Vec<Pair> = iter.collect(); assert_eq!( elements, vec![ (b"snowy".to_vec(), b"day".to_vec()), (b"bar".to_vec(), b"none".to_vec()), ] ); } #[test] fn test_range_with_start_end_set() { let mut storage = MockStorage::new(); let prefix = to_length_prefixed(b"f\xff\xff"); let other_prefix = to_length_prefixed(b"f\xff\x44"); set_with_prefix(&mut storage, &prefix, b"bar", b"none"); set_with_prefix(&mut storage, &prefix, b"snowy", b"day"); set_with_prefix(&mut storage, &other_prefix, b"moon", b"buggy"); let res: Vec<Pair> = range_with_prefix(&storage, &prefix, Some(b"b"), Some(b"c"), Order::Ascending) .collect(); assert_eq!(res.len(), 1); assert_eq!(res[0], (b"bar".to_vec(), b"none".to_vec())); let res: Vec<Pair> = range_with_prefix( &storage, &prefix, Some(b"bas"), Some(b"sno"), Order::Ascending, ) .collect(); assert_eq!(res.len(), 0); let res: Vec<Pair> = range_with_prefix(&storage, &prefix, Some(b"ant"), None, Order::Ascending).collect(); assert_eq!(res.len(), 2); assert_eq!(res[0], (b"bar".to_vec(), b"none".to_vec())); assert_eq!(res[1], (b"snowy".to_vec(), b"day".to_vec())); } #[test] fn test_namespace_upper_bound() { assert_eq!(namespace_upper_bound(b"bob"), b"boc".to_vec()); assert_eq!(namespace_upper_bound(b"fo\xfe"), b"fo\xff".to_vec()); assert_eq!(namespace_upper_bound(b"fo\xff"), b"fp\x00".to_vec()); assert_eq!( namespace_upper_bound(b"fo\xff\xff\xff"), b"fp\x00\x00\x00".to_vec() ); assert_eq!(namespace_upper_bound(b"\xffabc"), b"\xffabd".to_vec()); } }
#![cfg(feature = "iterator")] use serde::de::DeserializeOwned; use cosmwasm_std::Pair; use cosmwasm_std::{from_slice, StdResult}; use crate::helpers::encode_length; pub(crate) fn deserialize_kv<T: DeserializeOwned>(kv: Pair) -> StdResult<Pair<T>> { let (k, v) = kv; let t = from_slice::<T>(&v)?; Ok((k, t)) } #[allow(dead_code)] pub(crate) fn to_length_prefixed(namespace: &[u8]) -> Vec<u8> { let mut out = Vec::with_capacity(namespace.len() + 2); out.extend_from_slice(&encode_length(namespace)); out.extend_from_slice(namespace); out } #[inline] pub(crate) fn trim(namespace: &[u8], key: &[u8]) -> Vec<u8> { key[namespace.len()..].to_vec() } #[inline] pub(crate) fn concat(namespace: &[u8], key: &[u8]) -> Vec<u8> { let mut k = namespace.to_vec(); k.extend_from_slice(key); k } #[cfg(test)] mod test { use super::*; #[test] fn to_length_prefixed_works() { assert_eq!(to_length_prefixed(b""), b"\x00\x00"); assert_eq!(to_length_prefixed(b"a"), b"\x00\x01a"); assert_eq!(to_length_prefixed(b"ab"), b"\x00\x02ab"); assert_eq!(to_length_prefixed(b"abc"), b"\x00\x03abc"); } #[test] fn to_length_prefixed_works_for_long_prefix() { let long_namespace1 = vec![0; 256]; let prefix1 = to_length_prefixed(&long_namespace1); assert_eq!(prefix1.len(), 256 + 2); assert_eq!(&prefix1[0..2], b"\x01\x00"); let long_namespace2 = vec![0; 30000]; let prefix2 = to_length_prefixed(&long_namespace2); assert_eq!(prefix2.len(), 30000 + 2); assert_eq!(&prefix2[0..2], b"\x75\x30"); let long_namespace3 = vec![0; 0xFFFF]; let prefix3 = to_length_prefixed(&long_namespace3); assert_eq!(prefix3.len(), 0xFFFF + 2); assert_eq!(&prefix3[0..2], b"\xFF\xFF"); } #[test] #[should_panic(expected = "only supports namespaces up to length 0xFFFF")] fn to_length_prefixed_panics_for_too_long_prefix() { let limit = 0xFFFF; let long_namespace = vec![0; limit + 1]; to_length_prefixed(&long_namespace); } #[test] fn to_length_prefixed_calculates_capacity_correctly() { let key = to_length_prefixed(b""); assert_eq!(key.capacity(), key.len()); let key = to_length_prefixed(b"h"); assert_eq!(key.capacity(), key.len()); let key = to_length_prefixed(b"hij"); assert_eq!(key.capacity(), key.len()); } } #[cfg(test)] #[cfg(not(feature = "iterator"))] mod namespace_test { use super::*; use cosmwasm_std::testing::MockStorage; #[test] fn test_range() { let mut storage = MockStorage::new(); let prefix = to_length_prefixed(b"foo"); let other_prefix = to_length_prefixed(b"food"); set_with_prefix(&mut storage, &prefix, b"bar", b"none"); set_with_prefix(&mut storage, &prefix, b"snowy", b"day"); set_with_prefix(&mut storage, &other_prefix, b"moon", b"buggy"); let mut iter = range_with_prefix(&storage, &prefix, None, None, Order::Descending); let first = iter.next().unwrap(); assert_eq!(first, (b"snowy".to_vec(), b"day".to_vec())); let second = iter.next().unwrap(); assert_eq!(second, (b"bar".to_vec(), b"none".to_vec())); assert!(iter.next().is_none()); let iter = storage.range(None, None, Order::Ascending); assert_eq!(3, iter.count()); let mut iter = storage.range(None, None, Order::Ascending); let first = iter.next().unwrap(); let expected_key = concat(&prefix, b"bar"); assert_eq!(first, (expected_key, b"none".to_vec())); } #[test] fn test_range_with_prefix_wrapover() { let mut storage = MockStorage::new(); let prefix = to_length_prefixed(b"f\xff\xff"); let other_prefix = to_length_prefixed(b"f\xff\x44"); set_with_prefix(&mut storage, &prefix, b"bar", b"none"); set_with_prefix(&mut storage, &prefix, b"snowy", b"day"); set_with_prefix(&mut storage, &other_prefix, b"moon", b"buggy"); let iter = range_with_prefix(&storage, &prefix, None, None, Order::Descending); let elements: Vec<Pair> = iter.collect(); assert_eq!( elements, vec![ (b"snowy".to_vec(), b"day".to_vec()), (b"bar".to_vec(), b"none".to_vec()), ] ); } #[test] fn test_range_with_start_end_set() { let mut storage = MockStorage::new(); let prefix = to_length_prefixed(b"f\xff\xff"); let other_prefix = to_length_prefixed(b"f\xff\x44"); set_with_prefix(&mut storage, &prefix, b"bar", b"none"); set_with_prefix(&mut storage, &prefix, b"snowy", b"day"); set_with_prefix(&mut storage, &other_prefix, b"moon", b"buggy"); let res: Vec<Pair> = range_with_prefix(&storage, &prefix, Some(b"b"), Some(b"c"), Order::Ascending) .collect(); assert_eq!(res.len(), 1); assert_eq!(res[0], (b"bar".to_vec(), b"none".to_vec())); let res: Vec<Pair> =
.collect(); assert_eq!(res.len(), 0); let res: Vec<Pair> = range_with_prefix(&storage, &prefix, Some(b"ant"), None, Order::Ascending).collect(); assert_eq!(res.len(), 2); assert_eq!(res[0], (b"bar".to_vec(), b"none".to_vec())); assert_eq!(res[1], (b"snowy".to_vec(), b"day".to_vec())); } #[test] fn test_namespace_upper_bound() { assert_eq!(namespace_upper_bound(b"bob"), b"boc".to_vec()); assert_eq!(namespace_upper_bound(b"fo\xfe"), b"fo\xff".to_vec()); assert_eq!(namespace_upper_bound(b"fo\xff"), b"fp\x00".to_vec()); assert_eq!( namespace_upper_bound(b"fo\xff\xff\xff"), b"fp\x00\x00\x00".to_vec() ); assert_eq!(namespace_upper_bound(b"\xffabc"), b"\xffabd".to_vec()); } }
range_with_prefix( &storage, &prefix, Some(b"bas"), Some(b"sno"), Order::Ascending, )
call_expression
[ { "content": "fn one_byte_higher(limit: &[u8]) -> Vec<u8> {\n\n let mut v = limit.to_vec();\n\n v.push(0);\n\n v\n\n}\n\n\n", "file_path": "packages/storage-plus/src/prefix.rs", "rank": 0, "score": 360298.9457943783 }, { "content": "/// Returns a new vec of same length and last byte incremented by one\n\n/// If last bytes are 255, we handle overflow up the chain.\n\n/// If all bytes are 255, this returns wrong data - but that is never possible as a namespace\n\nfn namespace_upper_bound(input: &[u8]) -> Vec<u8> {\n\n let mut copy = input.to_vec();\n\n // zero out all trailing 255, increment first that is not such\n\n for i in (0..input.len()).rev() {\n\n if copy[i] == 255 {\n\n copy[i] = 0;\n\n } else {\n\n copy[i] += 1;\n\n break;\n\n }\n\n }\n\n copy\n\n}\n\n\n\n#[cfg(test)]\n\nmod test {\n\n use super::*;\n\n use cosmwasm_std::testing::MockStorage;\n\n\n\n #[test]\n", "file_path": "packages/storage-plus/src/prefix.rs", "rank": 1, "score": 331693.8253063683 }, { "content": "fn calc_start_bound(namespace: &[u8], bound: Option<Bound>) -> Vec<u8> {\n\n match bound {\n\n None => namespace.to_vec(),\n\n // this is the natural limits of the underlying Storage\n\n Some(Bound::Inclusive(limit)) => concat(namespace, &limit),\n\n Some(Bound::Exclusive(limit)) => concat(namespace, &one_byte_higher(&limit)),\n\n }\n\n}\n\n\n", "file_path": "packages/storage-plus/src/prefix.rs", "rank": 2, "score": 309554.31979110715 }, { "content": "fn calc_end_bound(namespace: &[u8], bound: Option<Bound>) -> Vec<u8> {\n\n match bound {\n\n None => namespace_upper_bound(namespace),\n\n // this is the natural limits of the underlying Storage\n\n Some(Bound::Exclusive(limit)) => concat(namespace, &limit),\n\n Some(Bound::Inclusive(limit)) => concat(namespace, &one_byte_higher(&limit)),\n\n }\n\n}\n\n\n", "file_path": "packages/storage-plus/src/prefix.rs", "rank": 3, "score": 309554.3197911072 }, { "content": "type DeserializeFn<T> = fn(&dyn Storage, &[u8], Pair) -> StdResult<Pair<T>>;\n\n\n\n#[derive(Clone)]\n\npub struct Prefix<T>\n\nwhere\n\n T: Serialize + DeserializeOwned,\n\n{\n\n /// all namespaces prefixes and concatenated with the key\n\n storage_prefix: Vec<u8>,\n\n // see https://doc.rust-lang.org/std/marker/struct.PhantomData.html#unused-type-parameters for why this is needed\n\n data: PhantomData<T>,\n\n pk_name: Vec<u8>,\n\n de_fn: DeserializeFn<T>,\n\n}\n\n\n\nimpl<T> Deref for Prefix<T>\n\nwhere\n\n T: Serialize + DeserializeOwned,\n\n{\n\n type Target = [u8];\n", "file_path": "packages/storage-plus/src/prefix.rs", "rank": 4, "score": 306519.9920196336 }, { "content": "pub fn index_triple(name: &str, age: u32, pk: Vec<u8>) -> (Vec<u8>, u32, Vec<u8>) {\n\n (index_string(name), age, pk)\n\n}\n\n\n", "file_path": "packages/storage-plus/src/indexes/mod.rs", "rank": 5, "score": 283384.18233070464 }, { "content": "pub fn index_triple(name: &str, age: u32, pk: Vec<u8>) -> (Vec<u8>, U32Key, Vec<u8>) {\n\n (index_string(name), U32Key::new(age), pk)\n\n}\n\n\n", "file_path": "packages/storage-plus/src/indexes.rs", "rank": 6, "score": 283323.48034447816 }, { "content": "pub fn index_string_tuple(data1: &str, data2: &str) -> (Vec<u8>, Vec<u8>) {\n\n (index_string(data1), index_string(data2))\n\n}\n\n\n", "file_path": "packages/storage-plus/src/indexes/mod.rs", "rank": 7, "score": 278027.73032395454 }, { "content": "fn deserialize_unique_kv<T: DeserializeOwned>(kv: Pair) -> StdResult<Pair<T>> {\n\n let (_, v) = kv;\n\n let t = from_slice::<UniqueRef<T>>(&v)?;\n\n Ok((t.pk.into(), t.value))\n\n}\n\n\n\nimpl<'a, K, T> UniqueIndex<'a, K, T>\n\nwhere\n\n T: Serialize + DeserializeOwned + Clone,\n\n K: PrimaryKey<'a>,\n\n{\n\n pub fn index_key(&self, k: K) -> Vec<u8> {\n\n k.joined_key()\n\n }\n\n\n\n pub fn prefix(&self, p: K::Prefix) -> Prefix<T> {\n\n Prefix::with_deserialization_function(self.idx_namespace, &p.prefix(), &[], |_, _, kv| {\n\n deserialize_unique_kv(kv)\n\n })\n\n }\n", "file_path": "packages/storage-plus/src/indexes.rs", "rank": 8, "score": 267567.56103949156 }, { "content": "pub fn index_string(data: &str) -> Vec<u8> {\n\n data.as_bytes().to_vec()\n\n}\n\n\n", "file_path": "packages/storage-plus/src/indexes/mod.rs", "rank": 9, "score": 265198.70351657394 }, { "content": "pub fn index_tuple(name: &str, age: u32) -> (Vec<u8>, u32) {\n\n (index_string(name), age)\n\n}\n\n\n", "file_path": "packages/storage-plus/src/indexes/mod.rs", "rank": 10, "score": 245736.64743498084 }, { "content": "pub fn index_tuple(name: &str, age: u32) -> (Vec<u8>, U32Key) {\n\n (index_string(name), U32Key::new(age))\n\n}\n\n\n", "file_path": "packages/storage-plus/src/indexes.rs", "rank": 11, "score": 245670.45831541187 }, { "content": "pub fn index_string_tuple(data1: &str, data2: &str) -> (Vec<u8>, Vec<u8>) {\n\n (index_string(data1), index_string(data2))\n\n}\n\n\n", "file_path": "packages/storage-plus/src/indexes.rs", "rank": 12, "score": 244912.07898802095 }, { "content": "/// Base128 varint decoding.\n\n/// The remaining of the data is kept in the data parameter.\n\nfn parse_protobuf_varint(data: &mut Vec<u8>, field_number: u8) -> Result<usize, ParseReplyError> {\n\n let data_len = data.len();\n\n let mut len: u64 = 0;\n\n let mut i = 0;\n\n while i < VARINT_MAX_BYTES {\n\n if data_len == i {\n\n return Err(ParseReplyError::ParseFailure(format!(\n\n \"failed to decode Protobuf message: field #{}: varint data too short\",\n\n field_number\n\n )));\n\n }\n\n len += ((data[i] & 0x7f) as u64) << (i * 7);\n\n if data[i] & 0x80 == 0 {\n\n break;\n\n }\n\n i += 1;\n\n }\n\n if i == VARINT_MAX_BYTES {\n\n return Err(ParseReplyError::ParseFailure(format!(\n\n \"failed to decode Protobuf message: field #{}: varint data too long\",\n\n field_number\n\n )));\n\n }\n\n *data = data[i + 1..].to_owned();\n\n\n\n Ok(len as usize) // Gently fall back to the arch's max addressable size\n\n}\n\n\n", "file_path": "packages/utils/src/parse_reply.rs", "rank": 13, "score": 242236.87160254765 }, { "content": "fn parse_protobuf_string(data: &mut Vec<u8>, field_number: u8) -> Result<String, ParseReplyError> {\n\n let str_field = parse_protobuf_length_prefixed(data, field_number)?;\n\n Ok(String::from_utf8(str_field)?)\n\n}\n\n\n", "file_path": "packages/utils/src/parse_reply.rs", "rank": 14, "score": 242236.87160254765 }, { "content": "fn deserialize_multi_kv<K: KeyDeserialize, T: DeserializeOwned>(\n\n store: &dyn Storage,\n\n pk_namespace: &[u8],\n\n kv: Record,\n\n) -> StdResult<(K::Output, T)> {\n\n let (key, pk_len) = kv;\n\n\n\n // Deserialize pk_len\n\n let pk_len = from_slice::<u32>(pk_len.as_slice())?;\n\n\n\n // Recover pk from last part of k\n\n let offset = key.len() - pk_len as usize;\n\n let pk = &key[offset..];\n\n\n\n let full_key = namespaces_with_key(&[pk_namespace], pk);\n\n\n\n let v = store\n\n .get(&full_key)\n\n .ok_or_else(|| StdError::generic_err(\"pk not found\"))?;\n\n let v = from_slice::<T>(&v)?;\n", "file_path": "packages/storage-plus/src/indexes/multi.rs", "rank": 15, "score": 234747.78705073387 }, { "content": "fn deserialize_unique_kv<K: KeyDeserialize, T: DeserializeOwned>(\n\n kv: Record,\n\n) -> StdResult<(K::Output, T)> {\n\n let (_, v) = kv;\n\n let t = from_slice::<UniqueRef<T>>(&v)?;\n\n Ok((K::from_vec(t.pk.0)?, t.value))\n\n}\n\n\n\nimpl<'a, IK, T, PK> UniqueIndex<'a, IK, T, PK>\n\nwhere\n\n T: Serialize + DeserializeOwned + Clone,\n\n IK: PrimaryKey<'a>,\n\n{\n\n pub fn index_key(&self, k: IK) -> Vec<u8> {\n\n k.joined_key()\n\n }\n\n\n\n fn no_prefix_raw(&self) -> Prefix<Vec<u8>, T, IK> {\n\n Prefix::with_deserialization_functions(\n\n self.idx_namespace,\n", "file_path": "packages/storage-plus/src/indexes/unique.rs", "rank": 16, "score": 234747.78705073387 }, { "content": "/// member_key is meant for raw queries for one member, given address\n\npub fn member_key(address: &str) -> Vec<u8> {\n\n // FIXME: Inlined here to avoid storage-plus import\n\n let mut key = [b\"\\x00\", &[MEMBERS_KEY.len() as u8], MEMBERS_KEY.as_bytes()].concat();\n\n key.extend_from_slice(address.as_bytes());\n\n key\n\n}\n", "file_path": "packages/cw4/src/query.rs", "rank": 17, "score": 234703.08358219854 }, { "content": "fn parse_length(value: &[u8]) -> StdResult<usize> {\n\n Ok(u16::from_be_bytes(\n\n value\n\n .try_into()\n\n .map_err(|_| StdError::generic_err(\"Could not read 2 byte length\"))?,\n\n )\n\n .into())\n\n}\n\n\n\nimpl<T: KeyDeserialize, U: KeyDeserialize> KeyDeserialize for (T, U) {\n\n type Output = (T::Output, U::Output);\n\n\n\n #[inline(always)]\n\n fn from_vec(mut value: Vec<u8>) -> StdResult<Self::Output> {\n\n let mut tu = value.split_off(2);\n\n let t_len = parse_length(&value)?;\n\n let u = tu.split_off(t_len);\n\n\n\n Ok((T::from_vec(tu)?, U::from_vec(u)?))\n\n }\n", "file_path": "packages/storage-plus/src/de.rs", "rank": 18, "score": 233251.0948446507 }, { "content": "/// The BTreeMap specific key-value pair reference type, as returned by BTreeMap<Vec<u8>, T>::range.\n\n/// This is internal as it can change any time if the map implementation is swapped out.\n\ntype BTreeMapPairRef<'a, T = Vec<u8>> = (&'a Vec<u8>, &'a T);\n\n\n", "file_path": "packages/multi-test/src/transactions.rs", "rank": 19, "score": 231254.1418899497 }, { "content": "#[cfg(feature = \"iterator\")]\n\nfn range_bounds(start: Option<&[u8]>, end: Option<&[u8]>) -> impl RangeBounds<Vec<u8>> {\n\n (\n\n start.map_or(Bound::Unbounded, |x| Bound::Included(x.to_vec())),\n\n end.map_or(Bound::Unbounded, |x| Bound::Excluded(x.to_vec())),\n\n )\n\n}\n\n\n\n#[cfg(test)]\n\nmod test {\n\n use super::*;\n\n use std::cell::RefCell;\n\n use std::ops::{Deref, DerefMut};\n\n\n\n use cosmwasm_std::MemoryStorage;\n\n\n\n #[test]\n\n fn wrap_storage() {\n\n let mut store = MemoryStorage::new();\n\n let mut wrap = StorageTransaction::new(&store);\n\n wrap.set(b\"foo\", b\"bar\");\n", "file_path": "packages/multi-test/src/transactions.rs", "rank": 20, "score": 231050.8787422725 }, { "content": "pub fn index_string(data: &str) -> Vec<u8> {\n\n data.as_bytes().to_vec()\n\n}\n\n\n", "file_path": "packages/storage-plus/src/indexes.rs", "rank": 21, "score": 229343.54223014344 }, { "content": "fn bench_unsigned_int_key(c: &mut Criterion) {\n\n let mut group = c.benchmark_group(\"Unsigned int keys\");\n\n\n\n fn k() -> u32 {\n\n // let k: u32 = 0x42434445;\n\n // k\n\n rand::thread_rng().gen_range(u32::MIN..u32::MAX)\n\n }\n\n // For the asserts\n\n let k_check = k();\n\n\n\n type Buf = [u8; mem::size_of::<u32>()];\n\n\n\n group.bench_function(\"u32 to_cw_bytes\", |b| {\n\n #[inline]\n\n fn to_cw_bytes(value: &u32) -> Buf {\n\n value.to_be_bytes()\n\n }\n\n\n\n assert_eq!(to_cw_bytes(&0), u32::to_cw_bytes(&0));\n", "file_path": "packages/storage-plus/benches/main.rs", "rank": 22, "score": 211276.91732722314 }, { "content": "fn bench_signed_int_key(c: &mut Criterion) {\n\n let mut group = c.benchmark_group(\"Signed int keys\");\n\n\n\n fn k() -> i32 {\n\n // let k: i32 = 0x42434445;\n\n // k\n\n rand::thread_rng().gen_range(i32::MIN..i32::MAX)\n\n }\n\n // For the asserts\n\n let k_check = k();\n\n\n\n type Buf = [u8; mem::size_of::<i32>()];\n\n\n\n group.bench_function(\"i32 to_cw_bytes: xored (u32) + to_be_bytes\", |b| {\n\n #[inline]\n\n fn to_cw_bytes(value: &i32) -> Buf {\n\n (*value as u32 ^ i32::MIN as u32).to_be_bytes()\n\n }\n\n\n\n assert_eq!(to_cw_bytes(&0), i32::to_cw_bytes(&0));\n", "file_path": "packages/storage-plus/benches/main.rs", "rank": 23, "score": 211276.9173272231 }, { "content": "// this will set the first key after the provided key, by appending a 0 byte\n\npub fn calc_range_start(start_after: Option<Addr>) -> Option<Vec<u8>> {\n\n start_after.map(|addr| {\n\n let mut v: Vec<u8> = addr.as_bytes().into();\n\n v.push(0);\n\n v\n\n })\n\n}\n\n\n", "file_path": "packages/cw0/src/pagination.rs", "rank": 24, "score": 181313.0137925582 }, { "content": "// this will set the first key after the provided key, by appending a 0 byte\n\npub fn calc_range_start(start_after: Option<Addr>) -> Option<Vec<u8>> {\n\n start_after.map(|addr| {\n\n let mut v: Vec<u8> = addr.as_bytes().into();\n\n v.push(0);\n\n v\n\n })\n\n}\n\n\n", "file_path": "packages/utils/src/pagination.rs", "rank": 25, "score": 181313.0137925582 }, { "content": "// set the end to the canonicalized format (used for Order::Descending)\n\npub fn calc_range_end(end_before: Option<Addr>) -> Option<Vec<u8>> {\n\n end_before.map(|addr| addr.as_bytes().into())\n\n}\n\n\n", "file_path": "packages/utils/src/pagination.rs", "rank": 26, "score": 181307.2319708719 }, { "content": "// set the end to the canonicalized format (used for Order::Descending)\n\npub fn calc_range_end(end_before: Option<Addr>) -> Option<Vec<u8>> {\n\n end_before.map(|addr| addr.as_bytes().into())\n\n}\n\n\n", "file_path": "packages/cw0/src/pagination.rs", "rank": 27, "score": 181307.2319708719 }, { "content": "// this will set the first key after the provided key, by appending a 0 byte\n\npub fn calc_range_start_string(start_after: Option<String>) -> Option<Vec<u8>> {\n\n start_after.map(|token_id| {\n\n let mut v: Vec<u8> = token_id.into_bytes();\n\n v.push(0);\n\n v\n\n })\n\n}\n\n\n\n#[cfg(test)]\n\nmod test {\n\n use super::*;\n\n use cosmwasm_std::{testing::mock_dependencies, Order};\n\n use cw_storage_plus::{Bound, Map};\n\n\n\n pub const HOLDERS: Map<&Addr, usize> = Map::new(\"some_data\");\n\n const LIMIT: usize = 30;\n\n\n\n fn addr_from_i(i: usize) -> Addr {\n\n Addr::unchecked(format!(\"addr{:0>8}\", i))\n\n }\n", "file_path": "packages/utils/src/pagination.rs", "rank": 28, "score": 179218.65151207364 }, { "content": "// this will set the first key after the provided key, by appending a 0 byte\n\npub fn calc_range_start_string(start_after: Option<String>) -> Option<Vec<u8>> {\n\n start_after.map(|token_id| {\n\n let mut v: Vec<u8> = token_id.into_bytes();\n\n v.push(0);\n\n v\n\n })\n\n}\n\n\n\n#[cfg(test)]\n\nmod test {\n\n use super::*;\n\n use cosmwasm_std::{testing::mock_dependencies, Order, StdError};\n\n use cw_storage_plus::{Bound, Map};\n\n\n\n pub const HOLDERS: Map<&Addr, usize> = Map::new(\"some_data\");\n\n const LIMIT: usize = 30;\n\n\n\n fn addr_from_i(i: usize) -> Addr {\n\n Addr::unchecked(format!(\"addr{:0>8}\", i))\n\n }\n", "file_path": "packages/cw0/src/pagination.rs", "rank": 29, "score": 179218.65151207364 }, { "content": "pub fn transactional<F, T>(base: &mut dyn Storage, action: F) -> AnyResult<T>\n\nwhere\n\n F: FnOnce(&mut dyn Storage, &dyn Storage) -> AnyResult<T>,\n\n{\n\n let mut cache = StorageTransaction::new(base);\n\n let res = action(&mut cache, base)?;\n\n cache.prepare().commit(base);\n\n Ok(res)\n\n}\n\n\n\npub struct StorageTransaction<'a> {\n\n /// read-only access to backing storage\n\n storage: &'a dyn Storage,\n\n /// these are local changes not flushed to backing storage\n\n local_state: BTreeMap<Vec<u8>, Delta>,\n\n /// a log of local changes not yet flushed to backing storage\n\n rep_log: RepLog,\n\n}\n\n\n\nimpl<'a> StorageTransaction<'a> {\n", "file_path": "packages/multi-test/src/transactions.rs", "rank": 30, "score": 177716.18839754802 }, { "content": "fn deserialize_unique_v<T: DeserializeOwned>(kv: Record) -> StdResult<Record<T>> {\n\n let (_, v) = kv;\n\n let t = from_slice::<UniqueRef<T>>(&v)?;\n\n Ok((t.pk.0, t.value))\n\n}\n\n\n", "file_path": "packages/storage-plus/src/indexes/unique.rs", "rank": 31, "score": 174091.42614910187 }, { "content": "pub fn next_block(block: &mut BlockInfo) {\n\n block.time = block.time.plus_seconds(5);\n\n block.height += 1;\n\n}\n\n\n\n/// Router is a persisted state. You can query this.\n\n/// Execution generally happens on the RouterCache, which then can be atomically committed or rolled back.\n\n/// We offer .execute() as a wrapper around cache, execute, commit/rollback process.\n\n///\n\n/// ExecC is the custom message returned init, handle, sudo (Response<C>).\n\n/// All contracts must return Response<C> or Response<Empty>.\n\n///\n\n/// Also `ExecC` is the custom message which is handled by custom message handler.\n\n///\n\n/// `QueryC` is custom query message handled by custom message handler.\n\npub struct App<ExecC = Empty, QueryC = Empty>\n\nwhere\n\n ExecC: Clone + fmt::Debug + PartialEq + JsonSchema + 'static,\n\n{\n\n router: Router<ExecC, QueryC>,\n", "file_path": "packages/multi-test/src/app.rs", "rank": 32, "score": 166920.0605474118 }, { "content": "pub fn range_with_prefix<'a>(\n\n storage: &'a dyn Storage,\n\n namespace: &[u8],\n\n start: Option<Bound>,\n\n end: Option<Bound>,\n\n order: Order,\n\n) -> Box<dyn Iterator<Item = Pair> + 'a> {\n\n let start = calc_start_bound(namespace, start);\n\n let end = calc_end_bound(namespace, end);\n\n\n\n // get iterator from storage\n\n let base_iterator = storage.range(Some(&start), Some(&end), order);\n\n\n\n // make a copy for the closure to handle lifetimes safely\n\n let prefix = namespace.to_vec();\n\n let mapped = base_iterator.map(move |(k, v)| (trim(&prefix, &k), v));\n\n Box::new(mapped)\n\n}\n\n\n", "file_path": "packages/storage-plus/src/prefix.rs", "rank": 33, "score": 160350.32795598148 }, { "content": "fn init_response<C>(res: &mut Response<C>, contact_address: &Addr)\n\nwhere\n\n C: Clone + fmt::Debug + PartialEq + JsonSchema,\n\n{\n\n let data = res.data.clone().unwrap_or_default().to_vec();\n\n let init_data = InstantiateData {\n\n address: contact_address.into(),\n\n data,\n\n };\n\n let mut new_data = Vec::<u8>::with_capacity(init_data.encoded_len());\n\n // the data must encode successfully\n\n init_data.encode(&mut new_data).unwrap();\n\n res.data = Some(new_data.into());\n\n}\n\n\n", "file_path": "packages/multi-test/src/wasm.rs", "rank": 34, "score": 154038.065702435 }, { "content": "/// Helper function to parse length-prefixed protobuf fields.\n\n/// The remaining of the data is kept in the data parameter.\n\nfn parse_protobuf_length_prefixed(\n\n data: &mut Vec<u8>,\n\n field_number: u8,\n\n) -> Result<Vec<u8>, ParseReplyError> {\n\n if data.is_empty() {\n\n return Ok(vec![]);\n\n };\n\n let mut rest_1 = data.split_off(1);\n\n let wire_type = data[0] & 0b11;\n\n let field = data[0] >> 3;\n\n\n\n if field != field_number {\n\n return Err(ParseReplyError::ParseFailure(format!(\n\n \"failed to decode Protobuf message: invalid field #{} for field #{}\",\n\n field, field_number\n\n )));\n\n }\n\n if wire_type != WIRE_TYPE_LENGTH_DELIMITED {\n\n return Err(ParseReplyError::ParseFailure(format!(\n\n \"failed to decode Protobuf message: field #{}: invalid wire type {}\",\n", "file_path": "packages/utils/src/parse_reply.rs", "rank": 35, "score": 152738.4249566098 }, { "content": "pub fn create_accounts(deps: &mut DepsMut, accounts: &[Cw20Coin]) -> StdResult<Uint128> {\n\n let mut total_supply = Uint128::zero();\n\n for row in accounts {\n\n let address = deps.api.addr_validate(&row.address)?;\n\n BALANCES.save(deps.storage, &address, &row.amount)?;\n\n total_supply += row.amount;\n\n }\n\n Ok(total_supply)\n\n}\n\n\n", "file_path": "src/contract.rs", "rank": 36, "score": 151296.5973894884 }, { "content": "fn deserialize_multi_kv<T: DeserializeOwned>(\n\n store: &dyn Storage,\n\n pk_namespace: &[u8],\n\n kv: Pair,\n\n) -> StdResult<Pair<T>> {\n\n let (key, pk_len) = kv;\n\n\n\n // Deserialize pk_len\n\n let pk_len = from_slice::<u32>(pk_len.as_slice())?;\n\n\n\n // Recover pk from last part of k\n\n let offset = key.len() - pk_len as usize;\n\n let pk = &key[offset..];\n\n\n\n let full_key = namespaces_with_key(&[pk_namespace], pk);\n\n\n\n let v = store\n\n .get(&full_key)\n\n .ok_or_else(|| StdError::generic_err(\"pk not found\"))?;\n\n let v = from_slice::<T>(&v)?;\n", "file_path": "packages/storage-plus/src/indexes.rs", "rank": 37, "score": 142414.29591004705 }, { "content": "/// Checks if data starts with XML preamble\n\nfn verify_xml_preamble(data: &[u8]) -> Result<(), ContractError> {\n\n // The easiest way to perform this check would be just match on regex, however regex\n\n // compilation is heavy and probably not worth it.\n\n\n\n let preamble = data\n\n .split_inclusive(|c| *c == b'>')\n\n .next()\n\n .ok_or(ContractError::InvalidXmlPreamble {})?;\n\n\n\n const PREFIX: &[u8] = b\"<?xml \";\n\n const POSTFIX: &[u8] = b\"?>\";\n\n\n\n if !(preamble.starts_with(PREFIX) && preamble.ends_with(POSTFIX)) {\n\n Err(ContractError::InvalidXmlPreamble {})\n\n } else {\n\n Ok(())\n\n }\n\n\n\n // Additionally attributes format could be validated as they are well defined, as well as\n\n // comments presence inside of preable, but it is probably not worth it.\n\n}\n\n\n", "file_path": "src/contract.rs", "rank": 38, "score": 131316.41101905328 }, { "content": "/// Validates XML logo\n\nfn verify_xml_logo(logo: &[u8]) -> Result<(), ContractError> {\n\n verify_xml_preamble(logo)?;\n\n\n\n if logo.len() > LOGO_SIZE_CAP {\n\n Err(ContractError::LogoTooBig {})\n\n } else {\n\n Ok(())\n\n }\n\n}\n\n\n", "file_path": "src/contract.rs", "rank": 39, "score": 131316.41101905328 }, { "content": "/// Validates png logo\n\nfn verify_png_logo(logo: &[u8]) -> Result<(), ContractError> {\n\n // PNG header format:\n\n // 0x89 - magic byte, out of ASCII table to fail on 7-bit systems\n\n // \"PNG\" ascii representation\n\n // [0x0d, 0x0a] - dos style line ending\n\n // 0x1a - dos control character, stop displaying rest of the file\n\n // 0x0a - unix style line ending\n\n const HEADER: [u8; 8] = [0x89, b'P', b'N', b'G', 0x0d, 0x0a, 0x1a, 0x0a];\n\n if logo.len() > LOGO_SIZE_CAP {\n\n Err(ContractError::LogoTooBig {})\n\n } else if !logo.starts_with(&HEADER) {\n\n Err(ContractError::InvalidPngHeader {})\n\n } else {\n\n Ok(())\n\n }\n\n}\n\n\n", "file_path": "src/contract.rs", "rank": 40, "score": 131316.41101905328 }, { "content": "// pub trait Prefixer<'a>: Copy {\n\npub trait Prefixer<'a> {\n\n /// returns 0 or more namespaces that should length-prefixed and concatenated for range searches\n\n fn prefix(&self) -> Vec<&[u8]>;\n\n}\n\n\n\nimpl<'a> Prefixer<'a> for () {\n\n fn prefix(&self) -> Vec<&[u8]> {\n\n vec![]\n\n }\n\n}\n\n\n\nimpl<'a> Prefixer<'a> for &'a [u8] {\n\n fn prefix(&self) -> Vec<&[u8]> {\n\n vec![self]\n\n }\n\n}\n\n\n\nimpl<'a, T: Prefixer<'a>, U: Prefixer<'a>> Prefixer<'a> for (T, U) {\n\n fn prefix(&self) -> Vec<&[u8]> {\n\n let mut res = self.0.prefix();\n", "file_path": "packages/storage-plus/src/keys.rs", "rank": 41, "score": 128985.21570644627 }, { "content": "fn migrate(deps: DepsMut, _env: Env, msg: MigrateMsg) -> Result<Response, StdError> {\n\n HACKATOM.update::<_, StdError>(deps.storage, |mut state| {\n\n state.beneficiary = msg.new_guy;\n\n Ok(state)\n\n })?;\n\n let resp = Response::new().add_attribute(\"migrate\", \"successful\");\n\n Ok(resp)\n\n}\n\n\n", "file_path": "packages/multi-test/src/test_helpers/contracts/hackatom.rs", "rank": 42, "score": 128329.25402974547 }, { "content": "fn sudo(deps: DepsMut, _env: Env, msg: SudoMsg) -> Result<Response, StdError> {\n\n COUNT.save(deps.storage, &msg.set_count)?;\n\n Ok(Response::default())\n\n}\n\n\n", "file_path": "packages/multi-test/src/test_helpers/contracts/payout.rs", "rank": 43, "score": 128329.25402974547 }, { "content": "// this is a marker for the Map.range() helper, so we can detect () in Generic bounds\n\npub trait EmptyPrefix {\n\n fn new() -> Self;\n\n}\n\n\n\nimpl EmptyPrefix for () {\n\n fn new() {}\n\n}\n\n\n\nimpl<'a> PrimaryKey<'a> for Vec<u8> {\n\n type Prefix = ();\n\n type SubPrefix = ();\n\n\n\n fn key(&self) -> Vec<&[u8]> {\n\n vec![&self]\n\n }\n\n}\n\n\n\nimpl<'a> Prefixer<'a> for Vec<u8> {\n\n fn prefix(&self) -> Vec<&[u8]> {\n\n vec![&self]\n", "file_path": "packages/storage-plus/src/keys.rs", "rank": 44, "score": 126254.01398389613 }, { "content": "type ReplyFn<C, E> = fn(deps: DepsMut, env: Env, msg: Reply) -> Result<Response<C>, E>;\n", "file_path": "packages/multi-test/src/contracts.rs", "rank": 45, "score": 126219.89630914661 }, { "content": "fn reply(deps: DepsMut, _env: Env, msg: Reply) -> Result<Response<CustomMsg>, StdError> {\n\n REFLECT.save(deps.storage, msg.id.into(), &msg)?;\n\n // add custom event here to test\n\n let event = Event::new(\"custom\")\n\n .add_attribute(\"from\", \"reply\")\n\n .add_attribute(\"to\", \"test\");\n\n Ok(Response::new().add_event(event))\n\n}\n\n\n", "file_path": "packages/multi-test/src/test_helpers/contracts/reflect.rs", "rank": 46, "score": 126087.76431125258 }, { "content": "type PermissionedFn<T, C, E> = fn(deps: DepsMut, env: Env, msg: T) -> Result<Response<C>, E>;\n", "file_path": "packages/multi-test/src/contracts.rs", "rank": 47, "score": 124144.72182880963 }, { "content": "#[allow(clippy::unnecessary_wraps)]\n\nfn reply<ExecC>(_deps: DepsMut, _env: Env, msg: Reply) -> Result<Response<ExecC>, StdError>\n\nwhere\n\n ExecC: Debug + PartialEq + Clone + JsonSchema + 'static,\n\n{\n\n if let Reply {\n\n result:\n\n ContractResult::Ok(SubMsgExecutionResponse {\n\n data: Some(data), ..\n\n }),\n\n ..\n\n } = msg\n\n {\n\n Ok(Response::new().set_data(data))\n\n } else {\n\n Ok(Response::new())\n\n }\n\n}\n\n\n", "file_path": "packages/multi-test/src/test_helpers/contracts/echo.rs", "rank": 48, "score": 122450.38726438535 }, { "content": "fn execute(\n\n _deps: DepsMut,\n\n _env: Env,\n\n _info: MessageInfo,\n\n msg: WasmMsg,\n\n) -> Result<Response, StdError> {\n\n let message = SubMsg::new(msg);\n\n\n\n Ok(Response::new().add_submessage(message))\n\n}\n\n\n", "file_path": "packages/multi-test/src/test_helpers/contracts/caller.rs", "rank": 49, "score": 119301.35589137513 }, { "content": "fn instantiate(\n\n deps: DepsMut,\n\n _env: Env,\n\n _info: MessageInfo,\n\n _msg: EmptyMsg,\n\n) -> Result<Response<CustomMsg>, StdError> {\n\n COUNT.save(deps.storage, &0)?;\n\n Ok(Response::default())\n\n}\n\n\n", "file_path": "packages/multi-test/src/test_helpers/contracts/reflect.rs", "rank": 50, "score": 119301.35589137513 }, { "content": "fn execute(\n\n deps: DepsMut,\n\n env: Env,\n\n _info: MessageInfo,\n\n _msg: EmptyMsg,\n\n) -> Result<Response, StdError> {\n\n let init = HACKATOM.load(deps.storage)?;\n\n let balance = deps.querier.query_all_balances(env.contract.address)?;\n\n\n\n let resp = Response::new().add_message(BankMsg::Send {\n\n to_address: init.beneficiary,\n\n amount: balance,\n\n });\n\n\n\n Ok(resp)\n\n}\n\n\n", "file_path": "packages/multi-test/src/test_helpers/contracts/hackatom.rs", "rank": 51, "score": 119301.35589137513 }, { "content": "fn instantiate(\n\n _deps: DepsMut,\n\n _env: Env,\n\n _info: MessageInfo,\n\n _msg: EmptyMsg,\n\n) -> Result<Response, StdError> {\n\n Ok(Response::default())\n\n}\n\n\n", "file_path": "packages/multi-test/src/test_helpers/contracts/caller.rs", "rank": 52, "score": 119301.35589137513 }, { "content": "fn instantiate(\n\n deps: DepsMut,\n\n _env: Env,\n\n _info: MessageInfo,\n\n msg: InstantiateMessage,\n\n) -> Result<Response, StdError> {\n\n PAYOUT.save(deps.storage, &msg)?;\n\n COUNT.save(deps.storage, &1)?;\n\n Ok(Response::default())\n\n}\n\n\n", "file_path": "packages/multi-test/src/test_helpers/contracts/payout.rs", "rank": 53, "score": 119301.35589137513 }, { "content": "fn instantiate(\n\n deps: DepsMut,\n\n _env: Env,\n\n _info: MessageInfo,\n\n msg: InstantiateMsg,\n\n) -> Result<Response, StdError> {\n\n HACKATOM.save(deps.storage, &msg)?;\n\n Ok(Response::default())\n\n}\n\n\n", "file_path": "packages/multi-test/src/test_helpers/contracts/hackatom.rs", "rank": 54, "score": 119301.35589137513 }, { "content": "fn execute(\n\n _deps: DepsMut,\n\n _env: Env,\n\n _info: MessageInfo,\n\n _msg: EmptyMsg,\n\n) -> Result<Response, StdError> {\n\n Err(StdError::generic_err(\"Handle failed\"))\n\n}\n\n\n", "file_path": "packages/multi-test/src/test_helpers/contracts/error.rs", "rank": 55, "score": 119301.35589137513 }, { "content": "fn execute(\n\n deps: DepsMut,\n\n _env: Env,\n\n info: MessageInfo,\n\n _msg: EmptyMsg,\n\n) -> Result<Response, StdError> {\n\n // always try to payout what was set originally\n\n let payout = PAYOUT.load(deps.storage)?;\n\n let msg = BankMsg::Send {\n\n to_address: info.sender.into(),\n\n amount: vec![payout.payout],\n\n };\n\n Ok(Response::new()\n\n .add_message(msg)\n\n .add_attribute(\"action\", \"payout\"))\n\n}\n\n\n", "file_path": "packages/multi-test/src/test_helpers/contracts/payout.rs", "rank": 56, "score": 119301.35589137513 }, { "content": "fn instantiate(\n\n _deps: DepsMut,\n\n _env: Env,\n\n _info: MessageInfo,\n\n _msg: EmptyMsg,\n\n) -> Result<Response, StdError> {\n\n Err(StdError::generic_err(\"Init failed\"))\n\n}\n\n\n", "file_path": "packages/multi-test/src/test_helpers/contracts/error.rs", "rank": 57, "score": 119301.35589137513 }, { "content": "fn execute(\n\n deps: DepsMut,\n\n _env: Env,\n\n _info: MessageInfo,\n\n msg: Message,\n\n) -> Result<Response<CustomMsg>, StdError> {\n\n COUNT.update::<_, StdError>(deps.storage, |old| Ok(old + 1))?;\n\n\n\n Ok(Response::new().add_submessages(msg.messages))\n\n}\n\n\n", "file_path": "packages/multi-test/src/test_helpers/contracts/reflect.rs", "rank": 58, "score": 119301.35589137513 }, { "content": "/// get_contract_version can be use in migrate to read the previous version of this contract\n\npub fn get_contract_version(store: &dyn Storage) -> StdResult<ContractVersion> {\n\n CONTRACT.load(store)\n\n}\n\n\n", "file_path": "packages/cw2/src/lib.rs", "rank": 59, "score": 117527.66113477829 }, { "content": "type ReplyClosure<C, E> = Box<dyn Fn(DepsMut, Env, Reply) -> Result<Response<C>, E>>;\n", "file_path": "packages/multi-test/src/contracts.rs", "rank": 60, "score": 116639.79618908404 }, { "content": "#[allow(clippy::unnecessary_wraps)]\n\nfn execute<ExecC>(\n\n _deps: DepsMut,\n\n _env: Env,\n\n _info: MessageInfo,\n\n msg: Message<ExecC>,\n\n) -> Result<Response<ExecC>, StdError>\n\nwhere\n\n ExecC: Debug + PartialEq + Clone + JsonSchema + 'static,\n\n{\n\n let mut resp = Response::new();\n\n\n\n if let Some(data) = msg.data {\n\n resp = resp.set_data(data.into_bytes());\n\n }\n\n\n\n Ok(resp\n\n .add_submessages(msg.sub_msg)\n\n .add_attributes(msg.attributes)\n\n .add_events(msg.events))\n\n}\n\n\n", "file_path": "packages/multi-test/src/test_helpers/contracts/echo.rs", "rank": 61, "score": 114812.26127494093 }, { "content": "#[allow(clippy::unnecessary_wraps)]\n\nfn instantiate<ExecC>(\n\n _deps: DepsMut,\n\n _env: Env,\n\n _info: MessageInfo,\n\n _msg: EmptyMsg,\n\n) -> Result<Response<ExecC>, StdError>\n\nwhere\n\n ExecC: Debug + PartialEq + Clone + JsonSchema + 'static,\n\n{\n\n Ok(Response::default())\n\n}\n\n\n", "file_path": "packages/multi-test/src/test_helpers/contracts/echo.rs", "rank": 62, "score": 114812.26127494093 }, { "content": "type PermissionedClosure<T, C, E> = Box<dyn Fn(DepsMut, Env, T) -> Result<Response<C>, E>>;\n", "file_path": "packages/multi-test/src/contracts.rs", "rank": 63, "score": 114433.33436719816 }, { "content": "fn customize_permissioned_fn<T, C, E>(\n\n raw_fn: PermissionedFn<T, Empty, E>,\n\n) -> PermissionedClosure<T, C, E>\n\nwhere\n\n T: DeserializeOwned + 'static,\n\n E: Display + Debug + Send + Sync + 'static,\n\n C: Clone + fmt::Debug + PartialEq + JsonSchema + 'static,\n\n{\n\n let customized = move |deps: DepsMut, env: Env, msg: T| -> Result<Response<C>, E> {\n\n raw_fn(deps, env, msg).map(customize_response::<C>)\n\n };\n\n Box::new(customized)\n\n}\n\n\n", "file_path": "packages/multi-test/src/contracts.rs", "rank": 64, "score": 112429.26338890565 }, { "content": "type ContractClosure<T, C, E> = Box<dyn Fn(DepsMut, Env, MessageInfo, T) -> Result<Response<C>, E>>;\n", "file_path": "packages/multi-test/src/contracts.rs", "rank": 65, "score": 110748.29827269584 }, { "content": "fn make_config() -> Criterion {\n\n Criterion::default()\n\n .without_plots()\n\n .measurement_time(Duration::new(5, 0))\n\n .sample_size(10)\n\n .configure_from_args()\n\n}\n\n\n\ncriterion_group!(\n\n name = signed_int_key;\n\n config = make_config();\n\n targets = bench_signed_int_key\n\n);\n\ncriterion_group!(\n\n name = unsigned_int_key;\n\n config = make_config();\n\n targets = bench_unsigned_int_key\n\n);\n\ncriterion_main!(signed_int_key, unsigned_int_key);\n", "file_path": "packages/storage-plus/benches/main.rs", "rank": 66, "score": 108264.39366508316 }, { "content": "pub fn contract() -> Box<dyn Contract<Empty>> {\n\n let contract = ContractWrapper::new(execute::<Empty>, instantiate::<Empty>, query)\n\n .with_reply(reply::<Empty>);\n\n Box::new(contract)\n\n}\n\n\n", "file_path": "packages/multi-test/src/test_helpers/contracts/echo.rs", "rank": 67, "score": 105992.4058573647 }, { "content": "pub fn contract() -> Box<dyn Contract<Empty>> {\n\n let contract = ContractWrapper::new(execute, instantiate, query).with_migrate(migrate);\n\n Box::new(contract)\n\n}\n\n\n", "file_path": "packages/multi-test/src/test_helpers/contracts/hackatom.rs", "rank": 68, "score": 105992.4058573647 }, { "content": "pub fn contract() -> Box<dyn Contract<CustomMsg>> {\n\n let contract = ContractWrapper::new(execute, instantiate, query).with_reply(reply);\n\n Box::new(contract)\n\n}\n", "file_path": "packages/multi-test/src/test_helpers/contracts/reflect.rs", "rank": 69, "score": 104726.41982106073 }, { "content": "pub fn contract<C>() -> Box<dyn Contract<C>>\n\nwhere\n\n C: Clone + fmt::Debug + PartialEq + JsonSchema + 'static,\n\n{\n\n let contract =\n\n ContractWrapper::new_with_empty(execute, instantiate, query).with_sudo_empty(sudo);\n\n Box::new(contract)\n\n}\n", "file_path": "packages/multi-test/src/test_helpers/contracts/payout.rs", "rank": 70, "score": 103800.24517024055 }, { "content": "pub fn contract<C>() -> Box<dyn Contract<C>>\n\nwhere\n\n C: Clone + fmt::Debug + PartialEq + JsonSchema + 'static,\n\n{\n\n let contract = ContractWrapper::new_with_empty(execute, instantiate, query);\n\n Box::new(contract)\n\n}\n", "file_path": "packages/multi-test/src/test_helpers/contracts/error.rs", "rank": 71, "score": 103800.24517024055 }, { "content": "pub fn contract<C>() -> Box<dyn Contract<C>>\n\nwhere\n\n C: Clone + fmt::Debug + PartialEq + JsonSchema + 'static,\n\n{\n\n let contract = ContractWrapper::new_with_empty(execute, instantiate, query);\n\n Box::new(contract)\n\n}\n", "file_path": "packages/multi-test/src/test_helpers/contracts/caller.rs", "rank": 72, "score": 103800.24517024055 }, { "content": "fn coins_to_string(coins: &[Coin]) -> String {\n\n coins\n\n .iter()\n\n .map(|c| format!(\"{}{}\", c.amount, c.denom))\n\n .join(\",\")\n\n}\n\n\n\nimpl Bank for BankKeeper {\n\n fn execute(\n\n &self,\n\n storage: &mut dyn Storage,\n\n sender: Addr,\n\n msg: BankMsg,\n\n ) -> AnyResult<AppResponse> {\n\n let mut bank_storage = prefixed(storage, NAMESPACE_BANK);\n\n match msg {\n\n BankMsg::Send { to_address, amount } => {\n\n // see https://github.com/cosmos/cosmos-sdk/blob/v0.42.7/x/bank/keeper/send.go#L142-L147\n\n let events = vec![Event::new(\"transfer\")\n\n .add_attribute(\"recipient\", &to_address)\n", "file_path": "packages/multi-test/src/bank.rs", "rank": 73, "score": 103142.6354585613 }, { "content": "pub fn custom_contract<C>() -> Box<dyn Contract<C>>\n\nwhere\n\n C: Clone + Debug + PartialEq + JsonSchema + DeserializeOwned + 'static,\n\n{\n\n let contract =\n\n ContractWrapper::new(execute::<C>, instantiate::<C>, query).with_reply(reply::<C>);\n\n Box::new(contract)\n\n}\n", "file_path": "packages/multi-test/src/test_helpers/contracts/echo.rs", "rank": 74, "score": 102572.9360529832 }, { "content": "#[allow(dead_code)]\n\npub fn custom_contract<C>() -> Box<dyn Contract<C>>\n\nwhere\n\n C: Clone + fmt::Debug + PartialEq + JsonSchema + 'static,\n\n{\n\n let contract =\n\n ContractWrapper::new_with_empty(execute, instantiate, query).with_migrate_empty(migrate);\n\n Box::new(contract)\n\n}\n", "file_path": "packages/multi-test/src/test_helpers/contracts/hackatom.rs", "rank": 75, "score": 102572.9360529832 }, { "content": "fn deserialize_multi_v<T: DeserializeOwned>(\n\n store: &dyn Storage,\n\n pk_namespace: &[u8],\n\n kv: Record,\n\n) -> StdResult<Record<T>> {\n\n let (key, pk_len) = kv;\n\n\n\n // Deserialize pk_len\n\n let pk_len = from_slice::<u32>(pk_len.as_slice())?;\n\n\n\n // Recover pk from last part of k\n\n let offset = key.len() - pk_len as usize;\n\n let pk = &key[offset..];\n\n\n\n let full_key = namespaces_with_key(&[pk_namespace], pk);\n\n\n\n let v = store\n\n .get(&full_key)\n\n .ok_or_else(|| StdError::generic_err(\"pk not found\"))?;\n\n let v = from_slice::<T>(&v)?;\n\n\n\n Ok((pk.to_vec(), v))\n\n}\n\n\n", "file_path": "packages/storage-plus/src/indexes/multi.rs", "rank": 76, "score": 101943.024328096 }, { "content": "fn customize_fn<T, C, E>(raw_fn: ContractFn<T, Empty, E>) -> ContractClosure<T, C, E>\n\nwhere\n\n T: DeserializeOwned + 'static,\n\n E: Display + Debug + Send + Sync + 'static,\n\n C: Clone + fmt::Debug + PartialEq + JsonSchema + 'static,\n\n{\n\n let customized =\n\n move |deps: DepsMut, env: Env, info: MessageInfo, msg: T| -> Result<Response<C>, E> {\n\n raw_fn(deps, env, info, msg).map(customize_response::<C>)\n\n };\n\n Box::new(customized)\n\n}\n\n\n", "file_path": "packages/multi-test/src/contracts.rs", "rank": 77, "score": 101848.56296603868 }, { "content": "fn query(_deps: Deps, _env: Env, _msg: EmptyMsg) -> Result<Binary, StdError> {\n\n Err(StdError::generic_err(\n\n \"query not implemented for the `caller` contract\",\n\n ))\n\n}\n\n\n", "file_path": "packages/multi-test/src/test_helpers/contracts/caller.rs", "rank": 78, "score": 95675.02766467072 }, { "content": "fn query(_deps: Deps, _env: Env, msg: EmptyMsg) -> Result<Binary, StdError> {\n\n to_binary(&msg)\n\n}\n\n\n", "file_path": "packages/multi-test/src/test_helpers/contracts/echo.rs", "rank": 79, "score": 95675.02766467072 }, { "content": "fn query(_deps: Deps, _env: Env, _msg: EmptyMsg) -> Result<Binary, StdError> {\n\n Err(StdError::generic_err(\"Query failed\"))\n\n}\n\n\n", "file_path": "packages/multi-test/src/test_helpers/contracts/error.rs", "rank": 80, "score": 95675.02766467072 }, { "content": "fn query(deps: Deps, _env: Env, msg: QueryMsg) -> Result<Binary, StdError> {\n\n match msg {\n\n QueryMsg::Beneficiary {} => {\n\n let res = HACKATOM.load(deps.storage)?;\n\n to_binary(&res)\n\n }\n\n }\n\n}\n\n\n", "file_path": "packages/multi-test/src/test_helpers/contracts/hackatom.rs", "rank": 81, "score": 95675.02766467072 }, { "content": "fn query(deps: Deps, _env: Env, msg: QueryMsg) -> Result<Binary, StdError> {\n\n match msg {\n\n QueryMsg::Count {} => {\n\n let count = COUNT.load(deps.storage)?;\n\n let res = CountResponse { count };\n\n to_binary(&res)\n\n }\n\n QueryMsg::Payout {} => {\n\n let payout = PAYOUT.load(deps.storage)?;\n\n to_binary(&payout)\n\n }\n\n }\n\n}\n\n\n", "file_path": "packages/multi-test/src/test_helpers/contracts/payout.rs", "rank": 82, "score": 95675.02766467072 }, { "content": "fn query(deps: Deps, _env: Env, msg: QueryMsg) -> Result<Binary, StdError> {\n\n match msg {\n\n QueryMsg::Count {} => {\n\n let count = COUNT.load(deps.storage)?;\n\n let res = payout::CountResponse { count };\n\n to_binary(&res)\n\n }\n\n QueryMsg::Reply { id } => {\n\n let reply = REFLECT.load(deps.storage, id.into())?;\n\n to_binary(&reply)\n\n }\n\n }\n\n}\n\n\n", "file_path": "packages/multi-test/src/test_helpers/contracts/reflect.rs", "rank": 83, "score": 95675.02766467072 }, { "content": "fn customize_response<C>(resp: Response<Empty>) -> Response<C>\n\nwhere\n\n C: Clone + fmt::Debug + PartialEq + JsonSchema,\n\n{\n\n let mut customized_resp = Response::<C>::new()\n\n .add_submessages(resp.messages.into_iter().map(customize_msg::<C>))\n\n .add_events(resp.events)\n\n .add_attributes(resp.attributes);\n\n customized_resp.data = resp.data;\n\n customized_resp\n\n}\n\n\n", "file_path": "packages/multi-test/src/contracts.rs", "rank": 84, "score": 95474.61497161431 }, { "content": "type QueryFn<T, E> = fn(deps: Deps, env: Env, msg: T) -> Result<Binary, E>;\n\n\n", "file_path": "packages/multi-test/src/contracts.rs", "rank": 85, "score": 95184.562150068 }, { "content": "// this parses the result from a wasm contract init\n\npub fn parse_contract_addr(data: &Option<Binary>) -> AnyResult<Addr> {\n\n let bin = data\n\n .as_ref()\n\n .ok_or_else(|| anyhow!(\"No data response\"))?\n\n .to_vec();\n\n // parse the protobuf struct\n\n let init_data = InstantiateData::decode(bin.as_slice())?;\n\n if init_data.address.is_empty() {\n\n bail!(\"no contract address provided\");\n\n }\n\n Ok(Addr::unchecked(init_data.address))\n\n}\n\n\n\n#[cfg(test)]\n\nmod test {\n\n use crate::custom_handler::PanickingCustomHandler;\n\n use cosmwasm_std::testing::{mock_env, mock_info, MockApi, MockQuerier, MockStorage};\n\n use cosmwasm_std::{coin, from_slice, to_vec, BankMsg, Coin, CosmosMsg, Empty, StdError};\n\n\n\n use crate::test_helpers::contracts::{error, payout};\n", "file_path": "packages/multi-test/src/wasm.rs", "rank": 86, "score": 94055.41977856841 }, { "content": "fn customize_msg<C>(msg: SubMsg<Empty>) -> SubMsg<C>\n\nwhere\n\n C: Clone + fmt::Debug + PartialEq + JsonSchema,\n\n{\n\n SubMsg {\n\n msg: match msg.msg {\n\n CosmosMsg::Wasm(wasm) => CosmosMsg::Wasm(wasm),\n\n CosmosMsg::Bank(bank) => CosmosMsg::Bank(bank),\n\n CosmosMsg::Staking(staking) => CosmosMsg::Staking(staking),\n\n CosmosMsg::Custom(_) => unreachable!(),\n\n #[cfg(feature = \"stargate\")]\n\n CosmosMsg::Ibc(ibc) => CosmosMsg::Ibc(ibc),\n\n #[cfg(feature = \"stargate\")]\n\n CosmosMsg::Stargate { type_url, value } => CosmosMsg::Stargate { type_url, value },\n\n _ => panic!(\"unknown message variant {:?}\", msg),\n\n },\n\n id: msg.id,\n\n gas_limit: msg.gas_limit,\n\n reply_on: msg.reply_on,\n\n }\n", "file_path": "packages/multi-test/src/contracts.rs", "rank": 87, "score": 92688.48443491005 }, { "content": "// pub trait PrimaryKey<'a>: Copy {\n\npub trait PrimaryKey<'a>: Clone {\n\n type Prefix: Prefixer<'a>;\n\n type SubPrefix: Prefixer<'a>;\n\n\n\n /// returns a slice of key steps, which can be optionally combined\n\n fn key(&self) -> Vec<&[u8]>;\n\n\n\n fn joined_key(&self) -> Vec<u8> {\n\n let keys = self.key();\n\n let l = keys.len();\n\n namespaces_with_key(&keys[0..l - 1], &keys[l - 1])\n\n }\n\n}\n\n\n\n// Empty / no primary key\n\nimpl<'a> PrimaryKey<'a> for () {\n\n type Prefix = ();\n\n type SubPrefix = ();\n\n\n\n fn key(&self) -> Vec<&[u8]> {\n", "file_path": "packages/storage-plus/src/keys.rs", "rank": 88, "score": 92264.79068588895 }, { "content": "#![cfg(feature = \"iterator\")]\n\nuse serde::de::DeserializeOwned;\n\nuse serde::Serialize;\n\nuse std::marker::PhantomData;\n\n\n\nuse cosmwasm_std::{Order, Pair, StdResult, Storage};\n\nuse std::ops::Deref;\n\n\n\nuse crate::helpers::nested_namespaces_with_key;\n\nuse crate::iter_helpers::{concat, deserialize_kv, trim};\n\nuse crate::Endian;\n\n\n\n/// Bound is used to defines the two ends of a range, more explicit than Option<u8>\n\n/// None means that we don't limit that side of the range at all.\n\n/// Include means we use the given bytes as a limit and *include* anything at that exact key\n\n/// Exclude means we use the given bytes as a limit and *exclude* anything at that exact key\n\n#[derive(Clone, Debug)]\n\npub enum Bound {\n\n Inclusive(Vec<u8>),\n\n Exclusive(Vec<u8>),\n", "file_path": "packages/storage-plus/src/prefix.rs", "rank": 89, "score": 89091.77066277752 }, { "content": " de_fn: DeserializeFn<T>,\n\n ) -> Self {\n\n // FIXME: we can use a custom function here, probably make this cleaner\n\n let storage_prefix = nested_namespaces_with_key(&[top_name], sub_names, b\"\");\n\n Prefix {\n\n storage_prefix,\n\n data: PhantomData,\n\n pk_name: pk_name.to_vec(),\n\n de_fn,\n\n }\n\n }\n\n\n\n pub fn range<'a>(\n\n &self,\n\n store: &'a dyn Storage,\n\n min: Option<Bound>,\n\n max: Option<Bound>,\n\n order: Order,\n\n ) -> Box<dyn Iterator<Item = StdResult<Pair<T>>> + 'a>\n\n where\n", "file_path": "packages/storage-plus/src/prefix.rs", "rank": 90, "score": 89084.82205624343 }, { "content": " T: 'a,\n\n {\n\n let de_fn = self.de_fn;\n\n let pk_name = self.pk_name.clone();\n\n let mapped = range_with_prefix(store, &self.storage_prefix, min, max, order)\n\n .map(move |kv| (de_fn)(store, &*pk_name, kv));\n\n Box::new(mapped)\n\n }\n\n\n\n pub fn keys<'a>(\n\n &self,\n\n store: &'a dyn Storage,\n\n min: Option<Bound>,\n\n max: Option<Bound>,\n\n order: Order,\n\n ) -> Box<dyn Iterator<Item = Vec<u8>> + 'a> {\n\n let mapped =\n\n range_with_prefix(store, &self.storage_prefix, min, max, order).map(|(k, _)| k);\n\n Box::new(mapped)\n\n }\n\n}\n\n\n", "file_path": "packages/storage-plus/src/prefix.rs", "rank": 91, "score": 89081.71224293359 }, { "content": " fn ensure_proper_range_bounds() {\n\n let mut store = MockStorage::new();\n\n // manually create this - not testing nested prefixes here\n\n let prefix = Prefix {\n\n storage_prefix: b\"foo\".to_vec(),\n\n data: PhantomData::<u64>,\n\n pk_name: vec![],\n\n de_fn: |_, _, kv| deserialize_kv(kv),\n\n };\n\n\n\n // set some data, we care about \"foo\" prefix\n\n store.set(b\"foobar\", b\"1\");\n\n store.set(b\"foora\", b\"2\");\n\n store.set(b\"foozi\", b\"3\");\n\n // these shouldn't match\n\n store.set(b\"foply\", b\"100\");\n\n store.set(b\"font\", b\"200\");\n\n\n\n let expected = vec![\n\n (b\"bar\".to_vec(), 1u64),\n", "file_path": "packages/storage-plus/src/prefix.rs", "rank": 92, "score": 89078.78448125621 }, { "content": " (b\"ra\".to_vec(), 2u64),\n\n (b\"zi\".to_vec(), 3u64),\n\n ];\n\n let expected_reversed: Vec<(Vec<u8>, u64)> = expected.iter().rev().cloned().collect();\n\n\n\n // let's do the basic sanity check\n\n let res: StdResult<Vec<_>> = prefix.range(&store, None, None, Order::Ascending).collect();\n\n assert_eq!(&expected, &res.unwrap());\n\n let res: StdResult<Vec<_>> = prefix\n\n .range(&store, None, None, Order::Descending)\n\n .collect();\n\n assert_eq!(&expected_reversed, &res.unwrap());\n\n\n\n // now let's check some ascending ranges\n\n let res: StdResult<Vec<_>> = prefix\n\n .range(\n\n &store,\n\n Some(Bound::Inclusive(b\"ra\".to_vec())),\n\n None,\n\n Order::Ascending,\n", "file_path": "packages/storage-plus/src/prefix.rs", "rank": 93, "score": 89075.5132788629 }, { "content": " Order::Descending,\n\n )\n\n .collect();\n\n assert_eq!(&expected_reversed[2..], res.unwrap().as_slice());\n\n // if we exclude something a little higher, we get matched\n\n let res: StdResult<Vec<_>> = prefix\n\n .range(\n\n &store,\n\n None,\n\n Some(Bound::Exclusive(b\"rb\".to_vec())),\n\n Order::Descending,\n\n )\n\n .collect();\n\n assert_eq!(&expected_reversed[1..], res.unwrap().as_slice());\n\n\n\n // now test when both sides are set\n\n let res: StdResult<Vec<_>> = prefix\n\n .range(\n\n &store,\n\n Some(Bound::Inclusive(b\"ra\".to_vec())),\n", "file_path": "packages/storage-plus/src/prefix.rs", "rank": 94, "score": 89069.64326732245 }, { "content": "\n\n fn deref(&self) -> &[u8] {\n\n &self.storage_prefix\n\n }\n\n}\n\n\n\nimpl<T> Prefix<T>\n\nwhere\n\n T: Serialize + DeserializeOwned,\n\n{\n\n pub fn new(top_name: &[u8], sub_names: &[&[u8]]) -> Self {\n\n Prefix::with_deserialization_function(top_name, sub_names, &[], |_, _, kv| {\n\n deserialize_kv(kv)\n\n })\n\n }\n\n\n\n pub fn with_deserialization_function(\n\n top_name: &[u8],\n\n sub_names: &[&[u8]],\n\n pk_name: &[u8],\n", "file_path": "packages/storage-plus/src/prefix.rs", "rank": 95, "score": 89068.13060150313 }, { "content": " )\n\n .collect();\n\n assert_eq!(&expected[1..], res.unwrap().as_slice());\n\n\n\n // now let's check some descending ranges\n\n let res: StdResult<Vec<_>> = prefix\n\n .range(\n\n &store,\n\n None,\n\n Some(Bound::Inclusive(b\"ra\".to_vec())),\n\n Order::Descending,\n\n )\n\n .collect();\n\n assert_eq!(&expected_reversed[1..], res.unwrap().as_slice());\n\n // skip excluded\n\n let res: StdResult<Vec<_>> = prefix\n\n .range(\n\n &store,\n\n None,\n\n Some(Bound::Exclusive(b\"ra\".to_vec())),\n", "file_path": "packages/storage-plus/src/prefix.rs", "rank": 96, "score": 89067.46267129823 }, { "content": " )\n\n .collect();\n\n assert_eq!(&expected[1..], res.unwrap().as_slice());\n\n // skip excluded\n\n let res: StdResult<Vec<_>> = prefix\n\n .range(\n\n &store,\n\n Some(Bound::Exclusive(b\"ra\".to_vec())),\n\n None,\n\n Order::Ascending,\n\n )\n\n .collect();\n\n assert_eq!(&expected[2..], res.unwrap().as_slice());\n\n // if we exclude something a little lower, we get matched\n\n let res: StdResult<Vec<_>> = prefix\n\n .range(\n\n &store,\n\n Some(Bound::Exclusive(b\"r\".to_vec())),\n\n None,\n\n Order::Ascending,\n", "file_path": "packages/storage-plus/src/prefix.rs", "rank": 97, "score": 89067.33217718692 }, { "content": " Some(Bound::Exclusive(b\"zi\".to_vec())),\n\n Order::Ascending,\n\n )\n\n .collect();\n\n assert_eq!(&expected[1..2], res.unwrap().as_slice());\n\n // and descending\n\n let res: StdResult<Vec<_>> = prefix\n\n .range(\n\n &store,\n\n Some(Bound::Inclusive(b\"ra\".to_vec())),\n\n Some(Bound::Exclusive(b\"zi\".to_vec())),\n\n Order::Descending,\n\n )\n\n .collect();\n\n assert_eq!(&expected[1..2], res.unwrap().as_slice());\n\n // Include both sides\n\n let res: StdResult<Vec<_>> = prefix\n\n .range(\n\n &store,\n\n Some(Bound::Inclusive(b\"ra\".to_vec())),\n", "file_path": "packages/storage-plus/src/prefix.rs", "rank": 98, "score": 89062.76853495014 }, { "content": " Some(Bound::Inclusive(b\"zi\".to_vec())),\n\n Order::Descending,\n\n )\n\n .collect();\n\n assert_eq!(&expected_reversed[..2], res.unwrap().as_slice());\n\n // Exclude both sides\n\n let res: StdResult<Vec<_>> = prefix\n\n .range(\n\n &store,\n\n Some(Bound::Exclusive(b\"ra\".to_vec())),\n\n Some(Bound::Exclusive(b\"zi\".to_vec())),\n\n Order::Ascending,\n\n )\n\n .collect();\n\n assert_eq!(res.unwrap().as_slice(), &[]);\n\n }\n\n}\n", "file_path": "packages/storage-plus/src/prefix.rs", "rank": 99, "score": 89061.98467737905 } ]
Rust
src/base/codec/decode.rs
sergeyboyko0791/redis-asio
8de643fddb2353a68f48b15b20943c9d9fa59d8d
use super::{RedisResult, RedisError, RedisErrorKind, RespInternalValue}; use std::io::Cursor; use std::error::Error; use byteorder::ReadBytesExt; pub struct ParseResult<T> { pub value: T, pub value_src_len: usize, } pub type OptParseResult<T> = Option<ParseResult<T>>; pub fn parse_resp_value(data: &[u8]) -> RedisResult<OptParseResult<RespInternalValue>> { let value_id = match Cursor::new(data).read_u8() { Ok(x) => x, Err(_) => return Ok(None) }; let data = &data[1..]; let opt_parse_result = match value_id { resp_start_bytes::ERROR => parse_error(data), resp_start_bytes::STATUS => parse_status(data), resp_start_bytes::INT => parse_int(data), resp_start_bytes::BULK_STRING => parse_bulkstring(data), resp_start_bytes::ARRAY => parse_array(data), _ => Err(RedisError::new( RedisErrorKind::ParseError, format!("Unknown RESP start byte {}", value_id))) }?; Ok(opt_parse_result .map( |ParseResult { value, value_src_len }| { let value_src_len = value_src_len + 1; ParseResult { value, value_src_len } } ) ) } mod resp_start_bytes { pub const ERROR: u8 = b'-'; pub const STATUS: u8 = b'+'; pub const INT: u8 = b':'; pub const BULK_STRING: u8 = b'$'; pub const ARRAY: u8 = b'*'; } const CRLF: (u8, u8) = (b'\r', b'\n'); const CRLF_LEN: usize = 2; fn parse_error(data: &[u8]) -> RedisResult<OptParseResult<RespInternalValue>> { parse_simple_string(data) .map(|opt_parse_result| opt_parse_result.map(|ParseResult { value, value_src_len }| { let value = RespInternalValue::Error(value); ParseResult { value, value_src_len } })) } fn parse_status(data: &[u8]) -> RedisResult<OptParseResult<RespInternalValue>> { parse_simple_string(data) .map(|opt_parse_result| opt_parse_result.map(|ParseResult { value, value_src_len }| { let value = RespInternalValue::Status(value); ParseResult { value, value_src_len } })) } fn parse_int(data: &[u8]) -> RedisResult<OptParseResult<RespInternalValue>> { parse_simple_int(data) .map(|opt_parse_result| opt_parse_result.map(|ParseResult { value, value_src_len }| { let value = RespInternalValue::Int(value); ParseResult { value, value_src_len } })) } fn parse_bulkstring(data: &[u8]) -> RedisResult<OptParseResult<RespInternalValue>> { let does_end_with_crlf = |data: &[u8]| data.ends_with(&[CRLF.0, CRLF.1]); let make_parse_error = || RedisError::new( RedisErrorKind::ParseError, "An actual data within a bulk string does not end with the CRLF".to_string()); let ParseResult { value, value_src_len: len_len } = match parse_simple_int(data)? { Some(x) => x, _ => return Ok(None), }; if value < 0 { if data.len() < len_len + CRLF_LEN { return Ok(None); } match does_end_with_crlf(&data[..len_len + CRLF_LEN]) { true => return Ok(Some( ParseResult { value: RespInternalValue::Nil, value_src_len: len_len + CRLF_LEN })), false => return Err(make_parse_error()) }; } let string_len = value as usize; let value_src_len = len_len + string_len + CRLF_LEN; if data.len() < value_src_len { return Ok(None); } if !data[..value_src_len].ends_with(&[CRLF.0, CRLF.1]) { return Err(make_parse_error()); } let value_data = data[len_len..len_len + string_len].to_vec(); let value = RespInternalValue::BulkString(value_data); Ok(Some(ParseResult { value, value_src_len })) } fn parse_array(data: &[u8]) -> RedisResult<OptParseResult<RespInternalValue>> { let ParseResult { value: array_len, value_src_len: len_len } = match parse_simple_int(data)? { Some(x) => x, _ => return Ok(None), }; if array_len < 0 { return Ok(Some(ParseResult { value: RespInternalValue::Nil, value_src_len: len_len })); } let array_len = array_len as usize; let mut pos = len_len; let mut result: Vec<RespInternalValue> = Vec::with_capacity(array_len); for _ in 0..array_len { let ParseResult { value, value_src_len } = match parse_resp_value(&data[pos..])? { Some(x) => x, _ => return Ok(None), }; result.push(value); pos = pos + value_src_len; }; Ok(Some(ParseResult { value: RespInternalValue::Array(result), value_src_len: pos })) } fn parse_simple_string(data: &[u8]) -> RedisResult<OptParseResult<String>> { let string_src_len = match data.iter().position(|x| *x == CRLF.0) { Some(x) => x, _ => return Ok(None), }; if string_src_len >= data.len() - 1 { return Ok(None); } if data[string_src_len + 1] != CRLF.1 { return Err(RedisError::new( RedisErrorKind::ParseError, "A status or an Error does not contain the CRLF".to_string())); } match String::from_utf8(data[0..string_src_len].to_vec()) { Ok(value) => { let value_src_len = string_src_len + CRLF_LEN; Ok(Some(ParseResult { value, value_src_len })) } Err(err) => Err( RedisError::new( RedisErrorKind::ParseError, format!("Could not parse a status from bytes: {}", err.description())) ) } } fn parse_simple_int(data: &[u8]) -> RedisResult<OptParseResult<i64>> { let opt_parse_result = parse_simple_string(data)?; let ParseResult { value, value_src_len } = match opt_parse_result { Some(x) => x, _ => return Ok(None), }; let value = match value.parse::<i64>() { Ok(x) => x, Err(err) => return Err( RedisError::new( RedisErrorKind::ParseError, format!("Could not parse an i64 from the {:?}, error: {}", value, err.description()), ) ), }; Ok(Some(ParseResult { value, value_src_len })) } #[cfg(test)] mod tests { use super::*; #[test] fn test_parse_status() { let data = Vec::from("+OK\r\n"); let ParseResult { value, value_src_len } = parse_resp_value(data.as_slice()).unwrap().unwrap(); assert_eq!(RespInternalValue::Status("OK".to_string()), value); assert_eq!(data.len(), value_src_len); assert!(parse_resp_value(Vec::from("+OK\r").as_mut_slice()).unwrap().is_none(), "expected Ok(None)"); assert!(parse_resp_value(Vec::from("+OK\r$").as_mut_slice()).is_err(), "expected Err"); } #[test] fn test_parse_error() { let data = Vec::from("-Error\r\n"); let ParseResult { value, value_src_len } = parse_resp_value(data.as_slice()).unwrap().unwrap(); assert_eq!(RespInternalValue::Error("Error".to_string()), value); assert_eq!(data.len(), value_src_len); assert!(parse_resp_value(Vec::from("-Error\r").as_mut_slice()).unwrap().is_none(), "expected Ok(None)"); assert!(parse_resp_value(Vec::from("-Error\r$").as_mut_slice()).is_err(), "expected Err"); } #[test] fn test_parse_int() { let data = Vec::from(":-12345\r\n"); let ParseResult { value, value_src_len } = parse_resp_value(data.as_slice()).unwrap().unwrap(); assert_eq!(RespInternalValue::Int(-12345i64), value); assert_eq!(data.len(), value_src_len); assert!(parse_resp_value(Vec::from(":-12345\r").as_mut_slice()).unwrap().is_none(), "expected Ok(None)"); assert!(parse_resp_value(Vec::from(":-12345\r$").as_mut_slice()).is_err(), "expected Err"); assert!(parse_resp_value(Vec::from(":-12X45\r\n").as_mut_slice()).is_err(), "expected Err"); } #[test] fn test_parse_bulkstring() { let origin_msg = "foo\r\nbar".to_string(); let mut raw_data = format!("${}\r\n{}\r\n", origin_msg.len(), origin_msg).into_bytes(); let expected_value_len = raw_data.len(); raw_data.append(&mut "trash".as_bytes().to_vec()); let ParseResult { value, value_src_len } = parse_resp_value(raw_data.as_slice()).unwrap().unwrap(); assert_eq!(RespInternalValue::BulkString(origin_msg.into_bytes()), value); assert_eq!(expected_value_len, value_src_len); assert!(parse_resp_value(Vec::from("$7\r").as_mut_slice()).unwrap().is_none(), "expected Ok(None)"); assert!(parse_resp_value(Vec::from("$7\r\n$").as_mut_slice()).unwrap().is_none(), "expected Ok(None)"); assert!(parse_resp_value(Vec::from("$7\r\n1234567\r$").as_mut_slice()).is_err(), "expected Err"); } #[test] fn test_parse_bulkstring_nil() { let mut raw_data = Vec::from("$-10\r\n\r\n"); let expected_value_len = raw_data.len(); raw_data.append(&mut "trash".as_bytes().to_vec()); let ParseResult { value, value_src_len } = parse_resp_value(raw_data.as_slice()).unwrap().unwrap(); assert_eq!(RespInternalValue::Nil, value); assert_eq!(expected_value_len, value_src_len); assert!(parse_resp_value(Vec::from("$-10\r").as_mut_slice()).unwrap().is_none(), "expected Ok(None)"); assert!(parse_resp_value(Vec::from("$-10\r\n$").as_mut_slice()).unwrap().is_none(), "expected Ok(None)"); assert!(parse_resp_value(Vec::from("$-10\r\n%$").as_mut_slice()).is_err(), "expected Err"); } #[test] fn test_parse_array() { let mut nil_value_data = Vec::from("$-1\r\n\r\n"); let mut error_value_data = Vec::from("-Error message\r\n"); let mut status_value_data = Vec::from("+Status message\r\n"); let mut int_value_data = Vec::from(":-1423\r\n"); let mut bulkstring_value_data = Vec::from("$20\r\nBulk\r\nstring\tmessage\r\n"); let mut array_value_data = Vec::from("*3\r\n:1\r\n:2\r\n:3\r\n"); let mut array_data: Vec<u8> = Vec::from("*6\r\n"); array_data.append(&mut nil_value_data); array_data.append(&mut error_value_data); array_data.append(&mut status_value_data); array_data.append(&mut int_value_data); array_data.append(&mut bulkstring_value_data); array_data.append(&mut array_value_data); let expected_value_len = array_data.len(); array_data.append(&mut "trash".as_bytes().to_vec()); let origin = RespInternalValue::Array( vec![RespInternalValue::Nil, RespInternalValue::Error("Error message".to_string()), RespInternalValue::Status("Status message".to_string()), RespInternalValue::Int(-1423), RespInternalValue::BulkString("Bulk\r\nstring\tmessage".as_bytes().to_vec()), RespInternalValue::Array(vec![RespInternalValue::Int(1), RespInternalValue::Int(2), RespInternalValue::Int(3)]) ]); let ParseResult { value, value_src_len } = parse_resp_value(&array_data).unwrap().unwrap(); assert_eq!(origin, value); assert_eq!(expected_value_len, value_src_len); } #[test] fn test_parse_array_empty() { let mut array_data: Vec<u8> = Vec::from("0\r\n"); let expected_value_len = array_data.len(); array_data.append(&mut "trash".as_bytes().to_vec()); let origin = RespInternalValue::Array(Vec::new()); let ParseResult { value, value_src_len } = parse_array(&array_data).unwrap().unwrap(); assert_eq!(origin, value); assert_eq!(expected_value_len, value_src_len); } #[test] fn test_parse_array_boundaries() { assert!(parse_resp_value(Vec::from("*7\r").as_mut_slice()).unwrap().is_none(), "expected Ok(None)"); assert!(parse_resp_value(Vec::from("*7\r\n*").as_mut_slice()).unwrap().is_none(), "expected Ok(None)"); assert!(parse_resp_value(Vec::from("*1\r\n$").as_mut_slice()).unwrap().is_none(), "expected Ok(None)"); assert!(parse_resp_value(Vec::from("*1\r#$").as_mut_slice()).is_err(), "expected Err"); assert!(parse_resp_value(Vec::from("*1\r\n:12\r$").as_mut_slice()).is_err(), "expected Err"); } }
use super::{RedisResult, RedisError, RedisErrorKind, RespInternalValue}; use std::io::Cursor; use std::error::Error; use byteorder::ReadBytesExt; pub struct ParseResult<T> { pub value: T, pub value_src_len: usize, } pub type OptParseResult<T> = Option<ParseResult<T>>; pub fn parse_resp_value(data: &[u8]) -> RedisResult<OptParseResult<RespInternalValue>> { let value_id = match Cursor::new(data).read_u8() { Ok(x) => x, Err(_) => return Ok(None) }; let data = &data[1..]; let opt_parse_result = match value_id { resp_start_bytes::ERROR => parse_error(data), resp_start_bytes::STATUS => parse_status(data), resp_start_bytes::INT => parse_int(data), resp_start_bytes::BULK_STRING => parse_bulkstring(data), resp_start_bytes::ARRAY => parse_array(data), _ => Err(RedisError::new( RedisErrorKind::ParseError, format!("Unknown RESP start byte {}", value_id))) }?; Ok(opt_parse_result .map( |ParseResult { value, value_src_len }| { let value_src_len = value_src_len + 1; ParseResult { value, value_src_len } } ) ) } mod resp_start_bytes { pub const ERROR: u8 = b'-'; pub const STATUS: u8 = b'+'; pub const INT: u8 = b':'; pub const BULK_STRING: u8 = b'$'; pub const ARRAY: u8 = b'*'; } const CRLF: (u8, u8) = (b'\r', b'\n'); const CRLF_LEN: usize = 2;
fn parse_status(data: &[u8]) -> RedisResult<OptParseResult<RespInternalValue>> { parse_simple_string(data) .map(|opt_parse_result| opt_parse_result.map(|ParseResult { value, value_src_len }| { let value = RespInternalValue::Status(value); ParseResult { value, value_src_len } })) } fn parse_int(data: &[u8]) -> RedisResult<OptParseResult<RespInternalValue>> { parse_simple_int(data) .map(|opt_parse_result| opt_parse_result.map(|ParseResult { value, value_src_len }| { let value = RespInternalValue::Int(value); ParseResult { value, value_src_len } })) } fn parse_bulkstring(data: &[u8]) -> RedisResult<OptParseResult<RespInternalValue>> { let does_end_with_crlf = |data: &[u8]| data.ends_with(&[CRLF.0, CRLF.1]); let make_parse_error = || RedisError::new( RedisErrorKind::ParseError, "An actual data within a bulk string does not end with the CRLF".to_string()); let ParseResult { value, value_src_len: len_len } = match parse_simple_int(data)? { Some(x) => x, _ => return Ok(None), }; if value < 0 { if data.len() < len_len + CRLF_LEN { return Ok(None); } match does_end_with_crlf(&data[..len_len + CRLF_LEN]) { true => return Ok(Some( ParseResult { value: RespInternalValue::Nil, value_src_len: len_len + CRLF_LEN })), false => return Err(make_parse_error()) }; } let string_len = value as usize; let value_src_len = len_len + string_len + CRLF_LEN; if data.len() < value_src_len { return Ok(None); } if !data[..value_src_len].ends_with(&[CRLF.0, CRLF.1]) { return Err(make_parse_error()); } let value_data = data[len_len..len_len + string_len].to_vec(); let value = RespInternalValue::BulkString(value_data); Ok(Some(ParseResult { value, value_src_len })) } fn parse_array(data: &[u8]) -> RedisResult<OptParseResult<RespInternalValue>> { let ParseResult { value: array_len, value_src_len: len_len } = match parse_simple_int(data)? { Some(x) => x, _ => return Ok(None), }; if array_len < 0 { return Ok(Some(ParseResult { value: RespInternalValue::Nil, value_src_len: len_len })); } let array_len = array_len as usize; let mut pos = len_len; let mut result: Vec<RespInternalValue> = Vec::with_capacity(array_len); for _ in 0..array_len { let ParseResult { value, value_src_len } = match parse_resp_value(&data[pos..])? { Some(x) => x, _ => return Ok(None), }; result.push(value); pos = pos + value_src_len; }; Ok(Some(ParseResult { value: RespInternalValue::Array(result), value_src_len: pos })) } fn parse_simple_string(data: &[u8]) -> RedisResult<OptParseResult<String>> { let string_src_len = match data.iter().position(|x| *x == CRLF.0) { Some(x) => x, _ => return Ok(None), }; if string_src_len >= data.len() - 1 { return Ok(None); } if data[string_src_len + 1] != CRLF.1 { return Err(RedisError::new( RedisErrorKind::ParseError, "A status or an Error does not contain the CRLF".to_string())); } match String::from_utf8(data[0..string_src_len].to_vec()) { Ok(value) => { let value_src_len = string_src_len + CRLF_LEN; Ok(Some(ParseResult { value, value_src_len })) } Err(err) => Err( RedisError::new( RedisErrorKind::ParseError, format!("Could not parse a status from bytes: {}", err.description())) ) } } fn parse_simple_int(data: &[u8]) -> RedisResult<OptParseResult<i64>> { let opt_parse_result = parse_simple_string(data)?; let ParseResult { value, value_src_len } = match opt_parse_result { Some(x) => x, _ => return Ok(None), }; let value = match value.parse::<i64>() { Ok(x) => x, Err(err) => return Err( RedisError::new( RedisErrorKind::ParseError, format!("Could not parse an i64 from the {:?}, error: {}", value, err.description()), ) ), }; Ok(Some(ParseResult { value, value_src_len })) } #[cfg(test)] mod tests { use super::*; #[test] fn test_parse_status() { let data = Vec::from("+OK\r\n"); let ParseResult { value, value_src_len } = parse_resp_value(data.as_slice()).unwrap().unwrap(); assert_eq!(RespInternalValue::Status("OK".to_string()), value); assert_eq!(data.len(), value_src_len); assert!(parse_resp_value(Vec::from("+OK\r").as_mut_slice()).unwrap().is_none(), "expected Ok(None)"); assert!(parse_resp_value(Vec::from("+OK\r$").as_mut_slice()).is_err(), "expected Err"); } #[test] fn test_parse_error() { let data = Vec::from("-Error\r\n"); let ParseResult { value, value_src_len } = parse_resp_value(data.as_slice()).unwrap().unwrap(); assert_eq!(RespInternalValue::Error("Error".to_string()), value); assert_eq!(data.len(), value_src_len); assert!(parse_resp_value(Vec::from("-Error\r").as_mut_slice()).unwrap().is_none(), "expected Ok(None)"); assert!(parse_resp_value(Vec::from("-Error\r$").as_mut_slice()).is_err(), "expected Err"); } #[test] fn test_parse_int() { let data = Vec::from(":-12345\r\n"); let ParseResult { value, value_src_len } = parse_resp_value(data.as_slice()).unwrap().unwrap(); assert_eq!(RespInternalValue::Int(-12345i64), value); assert_eq!(data.len(), value_src_len); assert!(parse_resp_value(Vec::from(":-12345\r").as_mut_slice()).unwrap().is_none(), "expected Ok(None)"); assert!(parse_resp_value(Vec::from(":-12345\r$").as_mut_slice()).is_err(), "expected Err"); assert!(parse_resp_value(Vec::from(":-12X45\r\n").as_mut_slice()).is_err(), "expected Err"); } #[test] fn test_parse_bulkstring() { let origin_msg = "foo\r\nbar".to_string(); let mut raw_data = format!("${}\r\n{}\r\n", origin_msg.len(), origin_msg).into_bytes(); let expected_value_len = raw_data.len(); raw_data.append(&mut "trash".as_bytes().to_vec()); let ParseResult { value, value_src_len } = parse_resp_value(raw_data.as_slice()).unwrap().unwrap(); assert_eq!(RespInternalValue::BulkString(origin_msg.into_bytes()), value); assert_eq!(expected_value_len, value_src_len); assert!(parse_resp_value(Vec::from("$7\r").as_mut_slice()).unwrap().is_none(), "expected Ok(None)"); assert!(parse_resp_value(Vec::from("$7\r\n$").as_mut_slice()).unwrap().is_none(), "expected Ok(None)"); assert!(parse_resp_value(Vec::from("$7\r\n1234567\r$").as_mut_slice()).is_err(), "expected Err"); } #[test] fn test_parse_bulkstring_nil() { let mut raw_data = Vec::from("$-10\r\n\r\n"); let expected_value_len = raw_data.len(); raw_data.append(&mut "trash".as_bytes().to_vec()); let ParseResult { value, value_src_len } = parse_resp_value(raw_data.as_slice()).unwrap().unwrap(); assert_eq!(RespInternalValue::Nil, value); assert_eq!(expected_value_len, value_src_len); assert!(parse_resp_value(Vec::from("$-10\r").as_mut_slice()).unwrap().is_none(), "expected Ok(None)"); assert!(parse_resp_value(Vec::from("$-10\r\n$").as_mut_slice()).unwrap().is_none(), "expected Ok(None)"); assert!(parse_resp_value(Vec::from("$-10\r\n%$").as_mut_slice()).is_err(), "expected Err"); } #[test] fn test_parse_array() { let mut nil_value_data = Vec::from("$-1\r\n\r\n"); let mut error_value_data = Vec::from("-Error message\r\n"); let mut status_value_data = Vec::from("+Status message\r\n"); let mut int_value_data = Vec::from(":-1423\r\n"); let mut bulkstring_value_data = Vec::from("$20\r\nBulk\r\nstring\tmessage\r\n"); let mut array_value_data = Vec::from("*3\r\n:1\r\n:2\r\n:3\r\n"); let mut array_data: Vec<u8> = Vec::from("*6\r\n"); array_data.append(&mut nil_value_data); array_data.append(&mut error_value_data); array_data.append(&mut status_value_data); array_data.append(&mut int_value_data); array_data.append(&mut bulkstring_value_data); array_data.append(&mut array_value_data); let expected_value_len = array_data.len(); array_data.append(&mut "trash".as_bytes().to_vec()); let origin = RespInternalValue::Array( vec![RespInternalValue::Nil, RespInternalValue::Error("Error message".to_string()), RespInternalValue::Status("Status message".to_string()), RespInternalValue::Int(-1423), RespInternalValue::BulkString("Bulk\r\nstring\tmessage".as_bytes().to_vec()), RespInternalValue::Array(vec![RespInternalValue::Int(1), RespInternalValue::Int(2), RespInternalValue::Int(3)]) ]); let ParseResult { value, value_src_len } = parse_resp_value(&array_data).unwrap().unwrap(); assert_eq!(origin, value); assert_eq!(expected_value_len, value_src_len); } #[test] fn test_parse_array_empty() { let mut array_data: Vec<u8> = Vec::from("0\r\n"); let expected_value_len = array_data.len(); array_data.append(&mut "trash".as_bytes().to_vec()); let origin = RespInternalValue::Array(Vec::new()); let ParseResult { value, value_src_len } = parse_array(&array_data).unwrap().unwrap(); assert_eq!(origin, value); assert_eq!(expected_value_len, value_src_len); } #[test] fn test_parse_array_boundaries() { assert!(parse_resp_value(Vec::from("*7\r").as_mut_slice()).unwrap().is_none(), "expected Ok(None)"); assert!(parse_resp_value(Vec::from("*7\r\n*").as_mut_slice()).unwrap().is_none(), "expected Ok(None)"); assert!(parse_resp_value(Vec::from("*1\r\n$").as_mut_slice()).unwrap().is_none(), "expected Ok(None)"); assert!(parse_resp_value(Vec::from("*1\r#$").as_mut_slice()).is_err(), "expected Err"); assert!(parse_resp_value(Vec::from("*1\r\n:12\r$").as_mut_slice()).is_err(), "expected Err"); } }
fn parse_error(data: &[u8]) -> RedisResult<OptParseResult<RespInternalValue>> { parse_simple_string(data) .map(|opt_parse_result| opt_parse_result.map(|ParseResult { value, value_src_len }| { let value = RespInternalValue::Error(value); ParseResult { value, value_src_len } })) }
function_block-full_function
[ { "content": "pub fn encode_resp_value(value: RespInternalValue) -> Vec<u8> {\n\n match value {\n\n RespInternalValue::Nil => \"$-1\\r\\n\".as_bytes().to_vec(),\n\n RespInternalValue::Error(x) => format!(\"-{}\\r\\n\", x).into_bytes(),\n\n RespInternalValue::Status(x) => format!(\"+{}\\r\\n\", x).into_bytes(),\n\n RespInternalValue::Int(x) => format!(\":{}\\r\\n\", x.to_string()).into_bytes(),\n\n RespInternalValue::BulkString(mut x) => {\n\n let mut res = format!(\"${}\\r\\n\", x.len()).into_bytes();\n\n res.append(&mut x);\n\n res.append(&mut \"\\r\\n\".as_bytes().to_vec());\n\n res\n\n }\n\n RespInternalValue::Array(x) => {\n\n let mut res = format!(\"*{}\\r\\n\", x.len()).into_bytes();\n\n for val in x.into_iter() {\n\n res.append(&mut encode_resp_value(val))\n\n }\n\n res\n\n }\n\n }\n", "file_path": "src/base/codec/encode.rs", "rank": 1, "score": 139423.47508779727 }, { "content": "fn conversion_error_from_value<T>(src_value: &T, dst_type: &str) -> RedisError\n\n where T: fmt::Debug {\n\n RedisError::new(RedisErrorKind::IncorrectConversion,\n\n format!(\"{:?} is not convertible to {}\", src_value, dst_type))\n\n}\n\n\n", "file_path": "src/base/value.rs", "rank": 7, "score": 106431.13080478288 }, { "content": "fn to_redis_error(err: ParseIntError) -> RedisError {\n\n RedisError::new(RedisErrorKind::ParseError, err.description().to_string())\n\n}\n\n\n\nimpl FromRedisValue for EntryInfo {\n\n fn from_redis_value(value: &RedisValue) -> RedisResult<Self> {\n\n let (id, key_values): (String, HashMap<String, RedisValue>) = from_redis_value(value)?;\n\n\n\n Ok(EntryInfo { id, key_values })\n\n }\n\n}\n\n\n\nimpl FromRedisValue for StreamInfo {\n\n fn from_redis_value(value: &RedisValue) -> RedisResult<Self> {\n\n let (id, entries): (String, Vec<EntryInfo>) = from_redis_value(value)?;\n\n Ok(Self { id, entries })\n\n }\n\n}\n\n\n\n#[cfg(test)]\n", "file_path": "src/stream/entry.rs", "rank": 9, "score": 95960.51866036456 }, { "content": "fn to_conversion_error<T>(err: T) -> RedisError\n\n where T: Error {\n\n RedisError::new(RedisErrorKind::IncorrectConversion, err.description().to_string())\n\n}\n\n\n", "file_path": "src/base/value.rs", "rank": 10, "score": 90666.71095724832 }, { "content": "/// Convert `RedisValue` into `T` value.\n\n///\n\n/// # Example\n\n/// ```\n\n/// use redis_asio::{RedisValue, from_redis_value};\n\n///\n\n/// let redis_value = RedisValue::BulkString(b\"some data\".to_vec());\n\n/// let origin = \"some data\".to_string();\n\n/// let result : String = from_redis_value::<String>(&redis_value).unwrap();\n\n/// assert_eq!(origin, result);\n\n/// ```\n\npub fn from_redis_value<T: FromRedisValue>(value: &RedisValue) -> RedisResult<T> {\n\n T::from_redis_value(value)\n\n .map_err(|err|\n\n RedisError::new(\n\n err.error.clone(),\n\n format!(\"Couldn't convert the Redis value: \\\"{:?}\\\". Reason: \\\"{}\\\"\", value, err.description()\n\n ),\n\n )\n\n )\n\n}\n\n\n\nimpl FromRedisValue for RedisValue {\n\n fn from_redis_value(value: &RedisValue) -> RedisResult<Self> {\n\n Ok(value.clone())\n\n }\n\n}\n\n\n\nimpl FromRedisValue for u8 {\n\n fn from_redis_value(value: &RedisValue) -> RedisResult<Self> {\n\n int_from_redis_value::<u8>(value)\n", "file_path": "src/base/value.rs", "rank": 11, "score": 85802.36231573994 }, { "content": "/// Parse XRANGE result: RedisValue to vec of StreamEntry\n\npub fn parse_range_entries(value: RedisValue) -> RedisResult<Vec<RangeEntry>> {\n\n let entries: Vec<EntryInfo> = from_redis_value(&value)?;\n\n\n\n let mut result_entries: Vec<RangeEntry> = Vec::with_capacity(entries.len());\n\n\n\n // transform the Vec<EntryInfo> to Vec<RangeEntry>\n\n for entry in entries.into_iter() {\n\n let entry =\n\n RangeEntry::new(EntryId::from_string(entry.id)?, entry.key_values);\n\n\n\n result_entries.push(entry);\n\n }\n\n\n\n Ok(result_entries)\n\n}\n\n\n", "file_path": "src/stream/entry.rs", "rank": 13, "score": 76589.32591780726 }, { "content": "fn int_from_redis_value<T>(value: &RedisValue) -> RedisResult<T>\n\n where T: ToIntConvertible {\n\n match value {\n\n RedisValue::Int(x) => Ok(T::convert_from_int(*x)),\n\n RedisValue::BulkString(x) => {\n\n match String::from_utf8(x.clone()) {\n\n Ok(xstr) =>\n\n T::convert_from_str(xstr)\n\n .map_err(|_| conversion_error_from_value(&x, \"i64\")),\n\n Err(_) => Err(conversion_error_from_value(x, \"i64\"))\n\n }\n\n }\n\n _ => Err(conversion_error_from_value(value, \"i64\"))\n\n }\n\n}\n\n\n", "file_path": "src/base/value.rs", "rank": 14, "score": 76148.62829114808 }, { "content": "fn to_string(err: &RedisErrorKind) -> &'static str {\n\n match err {\n\n RedisErrorKind::InternalError => \"InternalError\",\n\n RedisErrorKind::IncorrectConversion => \"IncorrectConversion\",\n\n RedisErrorKind::ConnectionError => \"ConnectionError\",\n\n RedisErrorKind::ParseError => \"ParseError\",\n\n RedisErrorKind::ReceiveError => \"ReceiveError\",\n\n RedisErrorKind::InvalidOptions => \"InvalidOptions\",\n\n }\n\n}\n", "file_path": "src/base/error.rs", "rank": 15, "score": 72230.24859814475 }, { "content": "/// Trait interface requires to implement method to convert `RedisValue`\n\n/// into base type.\n\n///\n\n/// # Example\n\n///\n\n/// ```\n\n/// use redis_asio::{RedisResult, RedisError, RedisErrorKind, RedisValue,\n\n/// FromRedisValue, from_redis_value};\n\n///\n\n/// #[derive(PartialEq, Debug)]\n\n/// struct ClientStruct{\n\n/// data: String,\n\n/// }\n\n///\n\n/// impl FromRedisValue for ClientStruct {\n\n/// fn from_redis_value(value: &RedisValue) -> RedisResult<Self> {\n\n/// match value {\n\n/// RedisValue::BulkString(data) => {\n\n/// let data = String::from_utf8(data.clone())\n\n/// .map_err(|err|\n\n/// RedisError::new(RedisErrorKind::ParseError,\n\n/// \"Cannot parse\".to_string()))?;\n\n/// Ok(ClientStruct {data})\n\n/// }\n\n/// _ => Err(RedisError::new(RedisErrorKind::ParseError,\n\n/// \"Cannot parse\".to_string()))\n\n/// }\n\n/// }\n\n/// }\n\n///\n\n/// let redis_value = RedisValue::BulkString(b\"some data\".to_vec());\n\n/// let origin = ClientStruct {data: \"some data\".to_string()};\n\n/// assert_eq!(origin, from_redis_value::<ClientStruct>(&redis_value).unwrap());\n\n/// ```\n\npub trait FromRedisValue: Sized {\n\n fn from_redis_value(value: &RedisValue) -> RedisResult<Self>;\n\n\n\n fn from_redis_u8(_: u8) -> Option<Self> {\n\n None\n\n }\n\n}\n\n\n", "file_path": "src/base/value.rs", "rank": 16, "score": 68870.29569049974 }, { "content": "/// Make a Redis command represents array of `BulkString`s\n\n/// wrapped into `RedisCommand`.\n\n///\n\n/// # Example\n\n///\n\n/// ```\n\n/// use redis_asio::command;\n\n/// let cmd = redis_asio::command(\"SET\").arg(\"foo\").arg(\"bar\");\n\n/// ```\n\npub fn command(cmd: &str) -> RedisCommand {\n\n RedisCommand::cmd(cmd)\n\n}\n\n\n\n/// Enumeration of base types that can be put into\n\n/// `RedisCommand` chain as argument.\n\npub enum RedisArgument {\n\n Int(i64),\n\n String(String),\n\n Bytes(Vec<u8>),\n\n}\n\n\n\n/// Redis command wrapper represents array of `BulkString`s\n\n#[derive(Clone)]\n\npub struct RedisCommand {\n\n args: Vec<RespInternalValue>,\n\n}\n\n\n", "file_path": "src/base/command.rs", "rank": 17, "score": 64467.68669436257 }, { "content": "/// Creates and holds a connection to the Redis Server, waits new messages from\n\n/// the channel receiver (rx) and send them to a Redis stream.\n\nfn start_producer(rx: UnboundedReceiver<Message>,\n\n stream_name: String,\n\n group_name: String,\n\n redis_address: SocketAddr) {\n\n let touch_options = TouchGroupOptions::new(stream_name.clone(), group_name.clone());\n\n\n\n // Try to create a group.\n\n // If the group exists already, the future will not be set into an error.\n\n // The create_group variable is the Future<Item=(), Error=()>.\n\n let create_group = RedisStream::connect(&redis_address)\n\n .and_then(move |con|\n\n // Create group if the one does not exists yet.\n\n con.touch_group(touch_options))\n\n .then(|_| -> RedisResult<()> { Ok(()) });\n\n\n\n // Creates and holds a connection to the Redis Server, waits new messages from\n\n // the channel receiver (rx) and send them to a Redis stream.\n\n //\n\n // Note nothing will happen if the previous future has failed.\n\n // The producer variable in a result is the Future<Item=(), Error=()>.\n", "file_path": "examples/stream_producer.rs", "rank": 18, "score": 50860.95514613636 }, { "content": " RedisValue::Status(x) => RespInternalValue::Status(x),\n\n RedisValue::Int(x) => RespInternalValue::Int(x),\n\n RedisValue::BulkString(x) => RespInternalValue::BulkString(x),\n\n RedisValue::Array(x) =>\n\n RespInternalValue::Array(\n\n x.into_iter()\n\n .map(|val| RespInternalValue::from_redis_value(val))\n\n .collect())\n\n }\n\n }\n\n\n\n pub fn into_redis_value(self) -> RedisResult<RedisValue> {\n\n match self {\n\n RespInternalValue::Nil => Ok(RedisValue::Nil),\n\n RespInternalValue::Error(x) => Err(RedisError::new(RedisErrorKind::ReceiveError, x)),\n\n RespInternalValue::Status(x) => match x.as_str() {\n\n \"OK\" => Ok(RedisValue::Ok),\n\n _ => Ok(RedisValue::Status(x))\n\n },\n\n RespInternalValue::Int(x) => Ok(RedisValue::Int(x)),\n", "file_path": "src/base/resp_value.rs", "rank": 19, "score": 50650.36722319205 }, { "content": "use super::{RedisResult, RedisValue, RedisError, RedisErrorKind};\n\n\n\n\n\n/// Internal set of types that are immediately parsed to and from RESP binary packets.\n\n/// Represents RESP protocol: \"https://redis.io/topics/protocol\".\n\n#[derive(PartialEq, Eq, Debug, Clone)]\n\npub enum RespInternalValue {\n\n Nil,\n\n Error(String),\n\n Status(String),\n\n Int(i64),\n\n BulkString(Vec<u8>),\n\n Array(Vec<RespInternalValue>),\n\n}\n\n\n\nimpl RespInternalValue {\n\n pub fn from_redis_value(value: RedisValue) -> RespInternalValue {\n\n match value {\n\n RedisValue::Nil => RespInternalValue::Nil,\n\n RedisValue::Ok => RespInternalValue::Status(\"OK\".to_string()),\n", "file_path": "src/base/resp_value.rs", "rank": 20, "score": 50649.52875584602 }, { "content": " RespInternalValue::BulkString(x) => Ok(RedisValue::BulkString(x)),\n\n RespInternalValue::Array(x) => {\n\n let mut res: Vec<RedisValue> = Vec::with_capacity(x.len());\n\n for val in x.into_iter() {\n\n res.push(val.into_redis_value()?);\n\n }\n\n Ok(RedisValue::Array(res))\n\n }\n\n }\n\n }\n\n}\n", "file_path": "src/base/resp_value.rs", "rank": 21, "score": 50640.28916856964 }, { "content": "/// Internal structure is used to parse RedisValue into StreamEntry\n\nstruct StreamInfo {\n\n id: String,\n\n entries: Vec<EntryInfo>,\n\n}\n\n\n\n/// Internal structure is used to parse RedisValue into StreamEntry\n", "file_path": "src/stream/entry.rs", "rank": 22, "score": 45758.07142530313 }, { "content": "#[derive(Debug)]\n\nstruct EntryInfo {\n\n id: String,\n\n key_values: HashMap<String, RedisValue>,\n\n}\n\n\n\n#[derive(Clone)]\n\npub enum RangeType {\n\n Any,\n\n GreaterThan(EntryId),\n\n LessThan(EntryId),\n\n GreaterLessThan(EntryId, EntryId),\n\n}\n\n\n\nimpl RangeType {\n\n /// Check if the left bound is less than the right bound\n\n pub fn is_valid(&self) -> bool {\n\n match self {\n\n RangeType::GreaterLessThan(left, right) => left < right,\n\n _ => true\n\n }\n", "file_path": "src/stream/entry.rs", "rank": 23, "score": 45752.522483810586 }, { "content": "struct Message(String);\n\n\n\n/// Implements the trait to allow use the structure as a RedisArgument within RedisCommand::arg().\n\nimpl IntoRedisArgument for Message {\n\n fn into_redis_argument(self) -> RedisArgument {\n\n RedisArgument::String(self.0)\n\n }\n\n}\n\n\n\nimpl Message {\n\n fn into_redis_stream_entry(self) -> HashMap<String, RedisArgument> {\n\n let mut result = HashMap::new();\n\n result.insert(\"type\".to_string(), \"Message\".into_redis_argument());\n\n result.insert(\"data\".to_string(), self.into_redis_argument());\n\n result\n\n }\n\n}\n\n\n", "file_path": "examples/stream_producer.rs", "rank": 24, "score": 43769.57473774292 }, { "content": "#[derive(Debug)]\n\nstruct Message(String);\n\n\n\n/// Implements the trait to allow implicit conversion from RedisValue to Message\n\n/// via from_redis_value()\n\nimpl FromRedisValue for Message {\n\n fn from_redis_value(value: &RedisValue) -> RedisResult<Self> {\n\n match value {\n\n RedisValue::BulkString(data) => {\n\n let string = String::from_utf8(data.clone())\n\n .map_err(|err|\n\n RedisError::new(RedisErrorKind::ParseError,\n\n format!(\"Could not parse message: {}\", err))\n\n )?;\n\n // Construct a Message from received data\n\n Ok(Message(string))\n\n }\n\n _ => Err(RedisError::new(RedisErrorKind::ParseError,\n\n format!(\"Could not parse message from invalid RedisValue {:?}\", value)))\n\n }\n\n }\n", "file_path": "examples/stream_consumer.rs", "rank": 25, "score": 43769.57473774292 }, { "content": "trait ToIntConvertible: Sized + FromStr {\n\n fn convert_from_str(val: String) -> Result<Self, ParseIntError>;\n\n fn convert_from_int(val: i64) -> Self;\n\n}\n\n\n\nimpl ToIntConvertible for u8 {\n\n fn convert_from_str(val: String) -> Result<u8, ParseIntError> { val.parse::<u8>() }\n\n fn convert_from_int(val: i64) -> u8 { val as u8 }\n\n}\n\n\n\nmacro_rules! declare_to_int_convertible {\n\n ($itype:ty) => {\n\n impl ToIntConvertible for $itype {\n\n fn convert_from_str(val: String) -> Result<$itype, ParseIntError> { val.parse::<$itype>() }\n\n fn convert_from_int(val: i64) -> $itype { val as $itype }\n\n }\n\n\n\n impl FromRedisValue for $itype {\n\n fn from_redis_value(value: &RedisValue) -> RedisResult<Self> {\n\n int_from_redis_value::<$itype>(value)\n", "file_path": "src/base/value.rs", "rank": 26, "score": 43595.459438844286 }, { "content": "/// Trait interface requires to implement method to convert base type\n\n/// into `RedisArgument`.\n\n///\n\n/// # Example\n\n/// ```\n\n/// use redis_asio::{RedisArgument, IntoRedisArgument, command};\n\n///\n\n/// struct ClientStruct { pub data: String }\n\n///\n\n/// impl IntoRedisArgument for ClientStruct {\n\n/// fn into_redis_argument(self) -> RedisArgument {\n\n/// RedisArgument::String(self.data)\n\n/// }\n\n/// }\n\n///\n\n/// let value = ClientStruct { data: \"Hello, world\".to_string() };\n\n/// let cmd = command(\"SET\").arg(\"foo\").arg(value);\n\n/// ```\n\npub trait IntoRedisArgument {\n\n fn into_redis_argument(self) -> RedisArgument;\n\n}\n\n\n\nimpl RedisCommand {\n\n pub(crate) fn new() -> RedisCommand {\n\n RedisCommand { args: Vec::new() }\n\n }\n\n\n\n /// Method is used by `redis::command()`.\n\n pub(crate) fn cmd(cmd: &str) -> RedisCommand {\n\n RedisCommand {\n\n args: vec![RespInternalValue::BulkString(cmd.as_bytes().to_vec())]\n\n }\n\n }\n\n\n\n /// Add new argument into `RedisCommand` and move the one back.\n\n /// The argument should implement the `IntoRedisArgument` trait.\n\n pub fn arg<T: IntoRedisArgument>(mut self, arg: T) -> RedisCommand {\n\n self.args.push(arg.into_redis_argument().into_resp_value());\n", "file_path": "src/base/command.rs", "rank": 27, "score": 41923.94489566967 }, { "content": "fn main() {\n\n println!(\"Producer example has started\");\n\n println!(\"Please enter a STREAM to write to it\");\n\n let stream_name = read_stdin();\n\n println!(\"Please enter a GROUP (is used only to create if that does not exist)\");\n\n let group_name = read_stdin();\n\n\n\n let redis_address = env::var(\"REDIS_URL\")\n\n .unwrap_or(\"127.0.0.1:6379\".to_string())\n\n .parse::<SocketAddr>().expect(\"Couldn't parse Redis URl\");\n\n\n\n // Create an unbounded channel to allow the main thread notifies a child-network thread\n\n // of the need to send a Message to a Redis stream.\n\n let (tx, rx) = unbounded::<Message>();\n\n let child = thread::spawn(move ||\n\n // Spawn a child-network thread and run the producer\n\n start_producer(rx, stream_name, group_name, redis_address));\n\n\n\n println!(\"Please enter a message\");\n\n let stdin = tokio::io::lines(BufReader::new(tokio::io::stdin()));\n", "file_path": "examples/stream_producer.rs", "rank": 28, "score": 39203.07794429464 }, { "content": "fn main() {\n\n println!(\"Consumer example has started\");\n\n println!(\"Please enter a STREAM to listen on\");\n\n let stream_name = read_stdin();\n\n println!(\"Please enter a GROUP\");\n\n let group_name = read_stdin();\n\n println!(\"Please enter a CONSUMER\");\n\n let consumer_name = read_stdin();\n\n\n\n let redis_address = env::var(\"REDIS_URL\")\n\n .unwrap_or(\"127.0.0.1:6379\".to_string())\n\n .parse::<SocketAddr>().expect(\"Couldn't parse Redis URl\");\n\n\n\n let touch_options = TouchGroupOptions::new(stream_name.clone(), group_name.clone());\n\n\n\n // Try to create a group.\n\n // If the group exists already, the future will not be set into an error.\n\n // The create_group variable is the Future<Item=(), Error=()>.\n\n let create_group = RedisStream::connect(&redis_address)\n\n .and_then(move |con|\n", "file_path": "examples/stream_consumer.rs", "rank": 29, "score": 39203.07794429464 }, { "content": "fn read_stdin() -> String {\n\n let mut value = String::new();\n\n io::stdin().read_line(&mut value).expect(\"Expect a valid string\");\n\n if value.ends_with(\"\\n\") {\n\n value.pop().expect(\"Expect no empty string\");\n\n }\n\n\n\n assert!(!value.is_empty(), \"Expect no empty string\");\n\n value\n\n}\n", "file_path": "examples/stream_producer.rs", "rank": 30, "score": 35389.85613897191 }, { "content": "fn read_stdin() -> String {\n\n let mut value = String::new();\n\n io::stdin().read_line(&mut value).expect(\"Expect a valid string\");\n\n if value.ends_with(\"\\n\") {\n\n value.pop().expect(\"Expect no empty string\");\n\n }\n\n\n\n assert!(!value.is_empty(), \"Expect no empty string\");\n\n value\n\n}\n\n\n", "file_path": "examples/stream_consumer.rs", "rank": 31, "score": 35389.85613897191 }, { "content": "fn fwd_from_channel_to_srv<T>(to_srv: T,\n\n rx: Receiver<StreamInternalCommand>,\n\n options: SubscribeOptions)\n\n -> impl Future<Item=(), Error=RedisError> + Send + 'static\n\n where T: Sink<SinkItem=RedisCommand, SinkError=RedisError> + Send + 'static {\n\n rx\n\n .map_err(|_| RedisError::new(RedisErrorKind::InternalError,\n\n \"Cannot read from internal channel\".to_string()))\n\n .fold(to_srv, move |to_srv, msg| {\n\n match msg {\n\n StreamInternalCommand::ListenNextMessage =>\n\n to_srv.send(subscribe_cmd(options.clone()))\n\n }\n\n })\n\n .map(|_| ())\n\n}\n\n\n", "file_path": "src/stream/consume.rs", "rank": 32, "score": 30443.73336241306 }, { "content": "fn process_from_srv_and_notify_channel<F>(from_srv: F,\n\n tx: Sender<StreamInternalCommand>)\n\n -> impl Stream<Item=RedisValue, Error=RedisError> + Send + 'static\n\n where F: Stream<Item=RespInternalValue, Error=RedisError> + Send + 'static\n\n{\n\n from_srv\n\n .and_then(move |msg| {\n\n tx.clone().send(StreamInternalCommand::ListenNextMessage)\n\n .then(|res| {\n\n match res {\n\n Ok(_) => (),\n\n Err(err) =>\n\n return Err(RedisError::new(RedisErrorKind::ConnectionError,\n\n format!(\"Could not send listen request: {:?}\", err)))\n\n }\n\n // convert RespInternalValue to RedisValue\n\n // note: the function returns an error if the Resp value is Error\n\n // else returns RedisValue\n\n RedisValue::from_resp_value(msg)\n\n })\n\n })\n\n}\n", "file_path": "src/stream/consume.rs", "rank": 33, "score": 29627.42882171836 }, { "content": "//! Base module for low-level request sending and response handling\n\n//! via RESP protocol.\n\n\n\nmod error;\n\nmod value;\n\nmod codec;\n\nmod resp_value;\n\nmod command;\n\nmod connection;\n\n\n\npub use error::{RedisResult, RedisError, RedisErrorKind};\n\npub use resp_value::RespInternalValue;\n\npub use value::{RedisValue, FromRedisValue, from_redis_value};\n\npub use codec::RedisCodec;\n\npub use connection::RedisCoreConnection;\n\npub use command::{command, RedisCommand, RedisArgument, IntoRedisArgument};\n", "file_path": "src/base/mod.rs", "rank": 34, "score": 27396.769061629802 }, { "content": "//! Stream module that contains specific interfaces\n\n//! for work with Redis-Stream \"https://redis.io/topics/streams-intro\".\n\n\n\nmod entry;\n\nmod stream;\n\nmod produce;\n\nmod consume;\n\nmod manage;\n\n\n\npub use entry::{StreamEntry, EntryId, RangeEntry, RangeType};\n\npub use stream::RedisStream;\n\npub use produce::SendEntryOptions;\n\npub use consume::{SubscribeOptions, ReadExplicitOptions, RangeOptions, RedisGroup, Subscribe};\n\npub use manage::{AckOptions, PendingOptions, TouchGroupOptions, AckResponse};\n\n\n\nuse entry::{parse_stream_entries, parse_range_entries};\n\nuse produce::add_command;\n\nuse consume::{subscribe, subscribe_cmd, read_explicit_cmd, range_cmd};\n\nuse manage::{ack_entry_command, pending_list_command, touch_group_command};\n", "file_path": "src/stream/mod.rs", "rank": 35, "score": 27388.07765685928 }, { "content": "use std::fmt;\n\nuse std::error::Error;\n\n\n\n#[derive(Debug, Clone, PartialEq)]\n\npub enum RedisErrorKind {\n\n InternalError,\n\n IncorrectConversion,\n\n ConnectionError,\n\n ParseError,\n\n ReceiveError,\n\n InvalidOptions,\n\n}\n\n\n\n#[derive(Debug, Clone)]\n\npub struct RedisError {\n\n pub error: RedisErrorKind,\n\n desc: String,\n\n}\n\n\n\npub type RedisResult<T> = Result<T, RedisError>;\n", "file_path": "src/base/error.rs", "rank": 36, "score": 27350.7035604894 }, { "content": "\n\nimpl RedisError {\n\n pub fn new(error: RedisErrorKind, desc: String) -> RedisError {\n\n RedisError { error, desc }\n\n }\n\n}\n\n\n\nimpl fmt::Display for RedisError {\n\n fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {\n\n write!(f, \"error: \\\"{}\\\", description: \\\"{}\\\"\",\n\n to_string(&self.error),\n\n &self.desc)\n\n }\n\n}\n\n\n\nimpl std::error::Error for RedisError {\n\n fn description(&self) -> &str {\n\n &self.desc\n\n }\n\n}\n\n\n\nimpl From<std::io::Error> for RedisError {\n\n fn from(err: std::io::Error) -> Self {\n\n RedisError { error: RedisErrorKind::ConnectionError, desc: err.description().to_string() }\n\n }\n\n}\n\n\n", "file_path": "src/base/error.rs", "rank": 37, "score": 27346.592641495976 }, { "content": "use super::{RedisResult, RedisError, RedisErrorKind};\n\nuse std::error::Error;\n\nuse std::fmt;\n\nuse std::cmp::PartialEq;\n\nuse std::str::FromStr;\n\nuse std::collections::HashMap;\n\nuse std::hash::Hash;\n\nuse core::num::ParseIntError;\n\nuse crate::base::RespInternalValue;\n\n\n\n\n\n/// Set of types that are parsed to and from RESP binary packets.\n\n/// Represents RESP protocol: \"https://redis.io/topics/protocol\".\n\n#[derive(PartialEq, Eq, Clone, Debug)]\n\npub enum RedisValue {\n\n Nil,\n\n Ok,\n\n Status(String),\n\n Int(i64),\n\n BulkString(Vec<u8>),\n", "file_path": "src/base/value.rs", "rank": 38, "score": 26370.82196578911 }, { "content": " Array(Vec<RedisValue>),\n\n}\n\n\n\nimpl RedisValue {\n\n pub(crate) fn from_resp_value(resp_value: RespInternalValue) -> RedisResult<RedisValue> {\n\n match resp_value {\n\n RespInternalValue::Nil => Ok(RedisValue::Nil),\n\n RespInternalValue::Error(x) => Err(RedisError::new(RedisErrorKind::ReceiveError, x)),\n\n RespInternalValue::Status(x) => match x.as_str() {\n\n \"OK\" => Ok(RedisValue::Ok),\n\n _ => Ok(RedisValue::Status(x))\n\n },\n\n RespInternalValue::Int(x) => Ok(RedisValue::Int(x)),\n\n RespInternalValue::BulkString(x) => Ok(RedisValue::BulkString(x)),\n\n RespInternalValue::Array(x) => {\n\n let mut res: Vec<RedisValue> = Vec::with_capacity(x.len());\n\n for val in x.into_iter() {\n\n res.push(Self::from_resp_value(val)?);\n\n }\n\n Ok(RedisValue::Array(res))\n", "file_path": "src/base/value.rs", "rank": 39, "score": 26370.397484108984 }, { "content": "/// fn from_redis_value(value: &RedisValue) -> RedisResult<Self> {\n\n/// match value {\n\n/// RedisValue::BulkString(data) => {\n\n/// let data = String::from_utf8(data.clone())\n\n/// .map_err(|err|\n\n/// RedisError::new(RedisErrorKind::ParseError,\n\n/// \"Cannot parse\".to_string()))?;\n\n/// Ok(ClientStruct {data})\n\n/// }\n\n/// _ => Err(RedisError::new(RedisErrorKind::ParseError,\n\n/// \"Cannot parse\".to_string()))\n\n/// }\n\n/// }\n\n/// }\n\n///\n\n/// let redis_value = RedisValue::BulkString(b\"some data\".to_vec());\n\n/// let origin = ClientStruct {data: \"some data\".to_string()};\n\n/// assert_eq!(origin, from_redis_value::<ClientStruct>(&redis_value).unwrap());\n\n/// ```\n", "file_path": "src/base/value.rs", "rank": 40, "score": 26369.102377281273 }, { "content": " Ok(result)\n\n }\n\n _ => Err(conversion_error_from_value(value, \"Array\"))\n\n }\n\n }\n\n}\n\n\n\nimpl<K: FromRedisValue + Eq + Hash, V: FromRedisValue> FromRedisValue for HashMap<K, V> {\n\n fn from_redis_value(value: &RedisValue) -> RedisResult<Self> {\n\n match value {\n\n RedisValue::Array(key_values) => {\n\n const KEY_VALUE_CHUNK_LEN: usize = 2;\n\n const KEY_POS: usize = 0;\n\n const VALUE_POS: usize = 1;\n\n\n\n // count of keys and values should be evenl\n\n if key_values.len() % KEY_VALUE_CHUNK_LEN != 0 {\n\n return Err(conversion_error_from_value(value, \"HashMap\"));\n\n }\n\n\n", "file_path": "src/base/value.rs", "rank": 41, "score": 26368.123251876445 }, { "content": " fn common_test_from_redis_value() {\n\n #[derive(PartialEq, Debug)]\n\n struct ArrayNode { data: String }\n\n\n\n impl FromRedisValue for ArrayNode {\n\n fn from_redis_value(value: &RedisValue) -> RedisResult<Self> {\n\n Ok(ArrayNode { data: from_redis_value(value)? })\n\n }\n\n }\n\n\n\n let value = RedisValue::Array(\n\n vec![RedisValue::BulkString(String::from(\"data1\").into_bytes()),\n\n RedisValue::BulkString(String::from(\"data2\").into_bytes())]);\n\n\n\n let origin = vec![ArrayNode { data: String::from(\"data1\") },\n\n ArrayNode { data: String::from(\"data2\") }];\n\n assert_eq!(origin, from_redis_value::<Vec<ArrayNode>>(&value).unwrap());\n\n }\n\n\n\n #[test]\n", "file_path": "src/base/value.rs", "rank": 42, "score": 26367.897038835083 }, { "content": " fn from_redis_value(value: &RedisValue) -> RedisResult<Self> {\n\n match value {\n\n RedisValue::BulkString(bulk_data) => {\n\n let mut result: Vec<T> = Vec::with_capacity(bulk_data.len());\n\n for num in bulk_data.iter() {\n\n match T::from_redis_u8(*num) {\n\n Some(x) => result.push(x),\n\n _ => return Err(conversion_error_from_value(bulk_data, \"Vec\"))\n\n }\n\n }\n\n Ok(result)\n\n }\n\n RedisValue::Array(x) => {\n\n let mut result: Vec<T> = Vec::with_capacity(x.len());\n\n for val in x.iter() {\n\n match from_redis_value(val) {\n\n Ok(x) => result.push(x),\n\n Err(err) => return Err(err),\n\n }\n\n }\n", "file_path": "src/base/value.rs", "rank": 43, "score": 26366.996406484923 }, { "content": " = vec![RedisValue::Nil,\n\n RedisValue::Ok,\n\n RedisValue::Status(String::from(\"Status\")),\n\n RedisValue::Int(12345),\n\n RedisValue::BulkString(vec![1, 2, 3, 4, 5]),\n\n RedisValue::Array(\n\n vec![RedisValue::Int(9876),\n\n RedisValue::BulkString(String::from(\"BulkString\").into_bytes())])];\n\n\n\n let val1 = RedisValue::Array(data.clone());\n\n assert_eq!(data, from_redis_value::<Vec<RedisValue>>(&val1).unwrap());\n\n }\n\n}\n", "file_path": "src/base/value.rs", "rank": 44, "score": 26366.423108422045 }, { "content": " }\n\n }\n\n }\n\n}\n\n\n\n/// Trait interface requires to implement method to convert `RedisValue`\n\n/// into base type.\n\n///\n\n/// # Example\n\n///\n\n/// ```\n\n/// use redis_asio::{RedisResult, RedisError, RedisErrorKind, RedisValue,\n\n/// FromRedisValue, from_redis_value};\n\n///\n\n/// #[derive(PartialEq, Debug)]\n\n/// struct ClientStruct{\n\n/// data: String,\n\n/// }\n\n///\n\n/// impl FromRedisValue for ClientStruct {\n", "file_path": "src/base/value.rs", "rank": 45, "score": 26366.09160502267 }, { "content": " }\n\n\n\n fn from_redis_u8(num: u8) -> Option<Self> {\n\n Some(num)\n\n }\n\n}\n\n\n\nimpl FromRedisValue for String {\n\n fn from_redis_value(value: &RedisValue) -> RedisResult<Self> {\n\n match value {\n\n RedisValue::Status(x) => Ok(x.clone()),\n\n RedisValue::BulkString(x) => {\n\n String::from_utf8(x.clone()).map_err(|err| to_conversion_error(err))\n\n }\n\n _ => Err(conversion_error_from_value(value, \"String\"))\n\n }\n\n }\n\n}\n\n\n\nimpl<T: FromRedisValue> FromRedisValue for Vec<T> {\n", "file_path": "src/base/value.rs", "rank": 46, "score": 26365.227910565205 }, { "content": " fn test_from_bulkstring_value() {\n\n let raw_data = vec![1, 2, 250, 251, 255];\n\n let string_data = String::from(\"BulkString\");\n\n let val1 = RedisValue::BulkString(raw_data.clone());\n\n let val2 = RedisValue::BulkString(string_data.clone().into_bytes());\n\n\n\n assert!(from_redis_value::<String>(&val1).is_err(),\n\n \"expected Err on cannot convert raw data to String\");\n\n assert_eq!(raw_data, from_redis_value::<Vec<u8>>(&val1).unwrap());\n\n assert!(from_redis_value::<Vec<i8>>(&val1).is_err(), \"expected Err\");\n\n assert!(from_redis_value::<Vec<i64>>(&val1).is_err(), \"expected Err\");\n\n assert!(from_redis_value::<i64>(&val1).is_err(), \"expected Err\");\n\n\n\n assert_eq!(string_data, from_redis_value::<String>(&val2).unwrap());\n\n assert_eq!(string_data.into_bytes(), from_redis_value::<Vec<u8>>(&val2).unwrap());\n\n }\n\n\n\n #[test]\n\n fn test_from_array_value() {\n\n let data\n", "file_path": "src/base/value.rs", "rank": 47, "score": 26365.146274464732 }, { "content": " }\n\n }\n\n };\n\n}\n\n\n\ndeclare_to_int_convertible!(i8);\n\ndeclare_to_int_convertible!(i16);\n\ndeclare_to_int_convertible!(u16);\n\ndeclare_to_int_convertible!(i32);\n\ndeclare_to_int_convertible!(u32);\n\ndeclare_to_int_convertible!(i64);\n\ndeclare_to_int_convertible!(u64);\n\ndeclare_to_int_convertible!(isize);\n\ndeclare_to_int_convertible!(usize);\n\n\n\n#[cfg(test)]\n\nmod tests {\n\n use super::*;\n\n\n\n #[test]\n", "file_path": "src/base/value.rs", "rank": 48, "score": 26363.305816159063 }, { "content": " let mut result =\n\n HashMap::with_capacity(key_values.len() / KEY_VALUE_CHUNK_LEN);\n\n\n\n for chunk in key_values.chunks_exact(KEY_VALUE_CHUNK_LEN) {\n\n let key: K = from_redis_value(&chunk[KEY_POS])?;\n\n let value: V = from_redis_value(&chunk[VALUE_POS])?;\n\n result.insert(key, value);\n\n }\n\n\n\n Ok(result)\n\n }\n\n _ => Err(conversion_error_from_value(value, \"HashMap\"))\n\n }\n\n }\n\n}\n\n\n\n// TODO make macro and implement that for (T, ..., T)\n\nimpl<T1, T2> FromRedisValue for (T1, T2)\n\n where T1: FromRedisValue + fmt::Debug,\n\n T2: FromRedisValue + fmt::Debug {\n", "file_path": "src/base/value.rs", "rank": 49, "score": 26360.254489108083 }, { "content": " assert!(from_redis_value::<Vec<i64>>(&val).is_err(), \"expected Err\");\n\n }\n\n\n\n #[test]\n\n fn test_from_int_value() {\n\n let src: i64 = std::i64::MAX - 5;\n\n let val = RedisValue::Int(src);\n\n assert_eq!(src as i8, from_redis_value::<i8>(&val).unwrap());\n\n assert_eq!(src as u8, from_redis_value::<u8>(&val).unwrap());\n\n assert_eq!(src as i16, from_redis_value::<i16>(&val).unwrap());\n\n assert_eq!(src as u16, from_redis_value::<u16>(&val).unwrap());\n\n assert_eq!(src as i32, from_redis_value::<i32>(&val).unwrap());\n\n assert_eq!(src as u32, from_redis_value::<u32>(&val).unwrap());\n\n assert_eq!(src as i64, from_redis_value::<i64>(&val).unwrap());\n\n assert_eq!(src as u64, from_redis_value::<u64>(&val).unwrap());\n\n assert!(from_redis_value::<String>(&val).is_err(), \"expected Err\");\n\n assert!(from_redis_value::<Vec<i64>>(&val).is_err(), \"expected Err\");\n\n }\n\n\n\n #[test]\n", "file_path": "src/base/value.rs", "rank": 50, "score": 26360.109961018305 }, { "content": " fn from_redis_value(value: &RedisValue) -> RedisResult<Self> {\n\n let values: Vec<RedisValue> = from_redis_value(value)?;\n\n if values.len() != 2 {\n\n return Err(\n\n RedisError::new(\n\n RedisErrorKind::ParseError,\n\n format!(\"Couldn't convert the Redis value: \\\"{:?}\\\" to tuple of 2 elements\",\n\n values)));\n\n }\n\n\n\n let first: T1 = from_redis_value(&values[0])?;\n\n let second: T2 = from_redis_value(&values[1])?;\n\n\n\n Ok((first, second))\n\n }\n\n}\n\n\n", "file_path": "src/base/value.rs", "rank": 51, "score": 26359.59102712916 }, { "content": " fn test_from_nil_value() {\n\n let val = RedisValue::Nil;\n\n assert!(from_redis_value::<i64>(&val).is_err(), \"expected Err\");\n\n assert!(from_redis_value::<String>(&val).is_err(), \"expected Err\");\n\n assert!(from_redis_value::<Vec<i64>>(&val).is_err(), \"expected Err\");\n\n }\n\n\n\n #[test]\n\n fn test_from_ok_value() {\n\n let val = RedisValue::Ok;\n\n assert!(from_redis_value::<i64>(&val).is_err(), \"expected Err\");\n\n assert!(from_redis_value::<String>(&val).is_err(), \"expected Err\");\n\n assert!(from_redis_value::<Vec<i64>>(&val).is_err(), \"expected Err\");\n\n }\n\n\n\n #[test]\n\n fn test_from_status_value() {\n\n let val = RedisValue::Status(String::from(\"Status\"));\n\n assert_eq!(String::from(\"Status\"), from_redis_value::<String>(&val).unwrap());\n\n assert!(from_redis_value::<i64>(&val).is_err(), \"expected Err\");\n", "file_path": "src/base/value.rs", "rank": 52, "score": 26356.444634019554 }, { "content": "use tokio_codec::{Encoder, Decoder};\n\nuse bytes::BytesMut;\n\n\n\nuse super::{RedisResult, RespInternalValue, RedisError, RedisErrorKind, RedisCommand};\n\n\n\nmod encode;\n\nmod decode;\n\n\n\nuse encode::encode_resp_value;\n\nuse decode::{ParseResult, parse_resp_value};\n\n\n\n\n\npub struct RedisCodec;\n\n\n\nimpl Encoder for RedisCodec {\n\n type Item = RedisCommand;\n\n type Error = RedisError;\n\n\n\n fn encode(&mut self, item: Self::Item, dst: &mut BytesMut) -> Result<(), Self::Error> {\n\n dst.extend_from_slice(encode_resp_value(item.into_resp_value()).as_ref());\n", "file_path": "src/base/codec/mod.rs", "rank": 53, "score": 25887.32684597551 }, { "content": " Ok(())\n\n }\n\n}\n\n\n\nimpl Decoder for RedisCodec {\n\n type Item = RespInternalValue;\n\n type Error = RedisError;\n\n\n\n fn decode(&mut self, buf: &mut BytesMut) -> Result<Option<Self::Item>, Self::Error> {\n\n let ParseResult { value, value_src_len } =\n\n match parse_resp_value(buf.as_ref())? {\n\n Some(x) => x,\n\n _ => return Ok(None),\n\n };\n\n\n\n assert!(value_src_len <= buf.len());\n\n let _ = buf.split_to(value_src_len);\n\n\n\n Ok(Some(value))\n\n }\n", "file_path": "src/base/codec/mod.rs", "rank": 54, "score": 25880.975362365345 }, { "content": "}\n\n\n\n#[cfg(test)]\n\nmod tests {\n\n use super::*;\n\n use crate::command;\n\n\n\n #[test]\n\n fn test_encode() {\n\n let mut codec = RedisCodec {};\n\n let mut buf = BytesMut::new();\n\n let cmd = command(\"PING\");\n\n codec.encode(cmd, &mut buf).unwrap();\n\n assert_eq!(\"*1\\r\\n$4\\r\\nPING\\r\\n\".as_bytes(), buf.as_ref());\n\n }\n\n\n\n #[test]\n\n fn test_decode() {\n\n let mut codec = RedisCodec {};\n\n let mut buf = BytesMut::from(\"+OK\\r\\ntrash\".as_bytes().to_vec());\n", "file_path": "src/base/codec/mod.rs", "rank": 55, "score": 25876.433554252962 }, { "content": " assert_eq!(RespInternalValue::Status(\"OK\".to_string()),\n\n codec.decode(&mut buf).unwrap().unwrap());\n\n assert_eq!(\"trash\".as_bytes().to_vec(), buf.as_ref());\n\n\n\n let mut buf = BytesMut::from(\"+OK\\r\".as_bytes().to_vec());\n\n // receive an incomplete message\n\n assert!(codec.decode(&mut buf).unwrap().is_none());\n\n\n\n // receive an empty message\n\n let mut buf = BytesMut::from(Vec::new());\n\n assert!(codec.decode(&mut buf).unwrap().is_none());\n\n\n\n let mut buf = BytesMut::from(\"+OK\\r$\".as_bytes().to_vec());\n\n assert!(codec.decode(&mut buf).is_err());\n\n }\n\n}\n", "file_path": "src/base/codec/mod.rs", "rank": 56, "score": 25875.097542701296 }, { "content": "fn process_stream_entries(acknowledger: UnboundedSender<EntryId>, entries: Vec<StreamEntry>)\n\n -> RedisResult<()> {\n\n entries.into_iter()\n\n .for_each(move |entry| {\n\n let message =\n\n Message::from_redis_stream_entry(&entry.values);\n\n match message {\n\n Ok(message) =>\n\n println!(\"Received message(ID={:?}): {:?}\", entry.id.to_string(), message),\n\n Err(err) => {\n\n eprintln!(\"{}\", err);\n\n // do not acknowledge the message\n\n return;\n\n }\n\n }\n\n\n\n // Notifies the manager about the received and processed entry.\n\n let future = acknowledger.clone()\n\n .send(entry.id)\n\n .map(|_| ())\n\n .map_err(|_| ());\n\n tokio::spawn(future);\n\n });\n\n Ok(())\n\n}\n", "file_path": "examples/stream_consumer.rs", "rank": 57, "score": 24331.868464481908 }, { "content": "fn ack_stream_entry(manager: RedisStream, stream: String, group: String, id_to_ack: EntryId)\n\n -> impl Future<Item=RedisStream, Error=RedisError> {\n\n let options = AckOptions::new(stream.clone(), group.clone(), id_to_ack.clone());\n\n\n\n manager.ack_entry(options)\n\n .map(move |(manager, response)| {\n\n match response {\n\n AckResponse::Ok => println!(\"{:?} is acknowledged\", id_to_ack.to_string()),\n\n AckResponse::NotExists =>\n\n eprintln!(\"Couldn't acknowledge {:?}\", id_to_ack.to_string())\n\n };\n\n manager\n\n })\n\n}\n\n\n", "file_path": "examples/stream_consumer.rs", "rank": 58, "score": 22344.62655485796 }, { "content": "}\n\n\n\n#[cfg(test)]\n\nmod tests {\n\n use super::*;\n\n\n\n #[test]\n\n fn test_encode() {\n\n assert_eq!(\"$-1\\r\\n\".as_bytes().to_vec(), encode_resp_value(RespInternalValue::Nil));\n\n assert_eq!(\"-Error message\\r\\n\".as_bytes().to_vec(),\n\n encode_resp_value(RespInternalValue::Error(\"Error message\".to_string())));\n\n assert_eq!(\":1000\\r\\n\".as_bytes().to_vec(),\n\n encode_resp_value(RespInternalValue::Int(1000)));\n\n assert_eq!(\"$8\\r\\nfoo\\r\\nbar\\r\\n\".as_bytes().to_vec(),\n\n encode_resp_value(RespInternalValue::BulkString(\"foo\\r\\nbar\".as_bytes().to_vec())));\n\n assert_eq!(\"*2\\r\\n$3\\r\\nfoo\\r\\n$3\\r\\nbar\\r\\n\".as_bytes().to_vec(),\n\n encode_resp_value(\n\n RespInternalValue::Array(\n\n vec![RespInternalValue::BulkString(\"foo\".as_bytes().to_vec()),\n\n RespInternalValue::BulkString(\"bar\".as_bytes().to_vec())]\n\n )\n\n )\n\n );\n\n }\n\n}\n", "file_path": "src/base/codec/encode.rs", "rank": 62, "score": 18.058957682404035 }, { "content": "use crate::{RedisValue, RedisResult, RedisError, RedisErrorKind, FromRedisValue, from_redis_value};\n\nuse std::num::ParseIntError;\n\nuse std::error::Error;\n\nuse std::fmt;\n\nuse std::collections::HashMap;\n\n\n\n#[derive(Clone, PartialEq, PartialOrd)]\n\npub struct EntryId((u64, u64));\n\n\n\n/// Structure that wraps a entry received on XREAD/XREADGROUP request.\n\n#[derive(Clone, PartialEq)]\n\npub struct StreamEntry {\n\n /// Stream name\n\n pub stream: String,\n\n /// Stream entry id is a simple string \"milliseconds-id\"\n\n pub id: EntryId,\n\n /// Note Redis allows to use key as a binary Bulk String\n\n /// but in the library it is forbidden for easy of use API.\n\n /// Value may be any of the RedisValue types\n\n pub values: HashMap<String, RedisValue>,\n", "file_path": "src/stream/entry.rs", "rank": 66, "score": 14.931949698335007 }, { "content": "//! let mut request: HashMap<String, RedisArgument> = HashMap::new();\n\n//! request.insert(\"type\".to_string(), 3i32.into_redis_argument());\n\n//! request.insert(\"data\".to_string(), \"Hello, world!\".into_redis_argument());\n\n//!\n\n//! let future = RedisStream::connect(address)\n\n//! .and_then(move |stream: RedisStream| {\n\n//! // HashMap<String, RedisArgument> satisfies the\n\n//! // HashMap<String, ToRedisArgument>\n\n//! stream.send_entry(send_options, request)\n\n//! })\n\n//! .map(|(_, inserted_entry_id): (RedisStream, EntryId)| {\n\n//! println!(\"{:?} has sent\", inserted_entry_id.to_string());\n\n//! })\n\n//! .map_err(|err| eprintln!(\"something went wrong: {}\", err));\n\n//! tokio::run(future);\n\n//! ```\n\n\n\nmod base;\n\npub mod stream;\n\n\n\npub use base::{RedisCoreConnection, RedisResult, RedisValue, RedisCommand, RedisError,\n\n RedisErrorKind, RedisArgument, FromRedisValue, IntoRedisArgument, command,\n\n from_redis_value};\n\n\n\nuse base::{RespInternalValue, RedisCodec};\n", "file_path": "src/lib.rs", "rank": 67, "score": 14.670169939322747 }, { "content": " match packet_type.as_str() {\n\n \"Message\" => {\n\n let data: Message = from_redis_value(get_value(\"data\")?)?;\n\n Ok(data)\n\n }\n\n _ => Err(RedisError::new(RedisErrorKind::ParseError,\n\n \"Unknown message type\".to_string()))\n\n }\n\n }\n\n}\n\n\n", "file_path": "examples/stream_consumer.rs", "rank": 68, "score": 14.454557079978326 }, { "content": "}\n\n\n\nimpl Message {\n\n /// Tries to convert a Message from HashMap<String, RedisValue> (represents a Redis Stream entry).\n\n /// The entry should have the following structure:\n\n /// \"type Message data \\\"Some data\\\"\"\n\n fn from_redis_stream_entry(key_values: &HashMap<String, RedisValue>) -> RedisResult<Self> {\n\n if key_values.len() != 2 {\n\n return Err(RedisError::new(RedisErrorKind::ParseError,\n\n \"Invalid packet\".to_string()));\n\n }\n\n\n\n let get_value =\n\n |key: &str| match key_values.get(key) {\n\n Some(x) => Ok(x),\n\n _ => Err(RedisError::new(RedisErrorKind::ParseError,\n\n \"Invalid packet\".to_string()))\n\n };\n\n\n\n let packet_type: String = from_redis_value(get_value(\"type\")?)?;\n", "file_path": "examples/stream_consumer.rs", "rank": 72, "score": 13.662525993122484 }, { "content": "\n\nimpl RedisArgument {\n\n pub(crate) fn into_resp_value(self) -> RespInternalValue {\n\n match self {\n\n RedisArgument::Int(x) => RespInternalValue::BulkString(x.to_string().into()),\n\n RedisArgument::String(x) => RespInternalValue::BulkString(x.into()),\n\n RedisArgument::Bytes(x) => RespInternalValue::BulkString(x),\n\n }\n\n }\n\n}\n\n\n\nimpl IntoRedisArgument for RedisArgument {\n\n fn into_redis_argument(self) -> RedisArgument {\n\n self\n\n }\n\n}\n\n\n\nimpl IntoRedisArgument for &str {\n\n fn into_redis_argument(self) -> RedisArgument {\n\n RedisArgument::String(self.to_string())\n", "file_path": "src/base/command.rs", "rank": 73, "score": 13.313778759542068 }, { "content": "use crate::{RedisResult, RedisValue, RedisError, RedisErrorKind, RespInternalValue,\n\n RedisCommand, command};\n\nuse super::{EntryId, RangeType, StreamEntry, parse_stream_entries};\n\nuse futures::{Stream, Future, Sink};\n\nuse futures::sync::mpsc::{channel, Sender, Receiver};\n\nuse futures::Async;\n\n\n\n/// Set of options that are required by `RedisStream::subscribe()`\n\n#[derive(Clone)]\n\npub struct SubscribeOptions {\n\n /// List of listen streams\n\n pub(crate) streams: Vec<String>,\n\n /// Optional group info\n\n pub(crate) group: Option<RedisGroup>,\n\n}\n\n\n\n/// Set of options that are required by `RedisStream::read_explicit()`\n\n#[derive(Clone)]\n\npub struct ReadExplicitOptions {\n\n /// Get entries from the following streams with ID greater than the corresponding entry IDs\n", "file_path": "src/stream/consume.rs", "rank": 76, "score": 11.899654110457913 }, { "content": " /// ```\n\n pub fn send_entry<T>(self, options: SendEntryOptions, key_values: HashMap<String, T>)\n\n -> impl Future<Item=(RedisStream, EntryId), Error=RedisError> + Send + 'static\n\n where T: IntoRedisArgument {\n\n self.connection.send(add_command(options, key_values))\n\n .and_then(|(connection, response)| {\n\n let entry_id_string = from_redis_value(&response)?;\n\n let entry_id = EntryId::from_string(entry_id_string)?;\n\n Ok((Self { connection }, entry_id))\n\n })\n\n }\n\n\n\n /// Read entries with IDs greater than specified `start_id`.\n\n ///\n\n /// # Example\n\n ///\n\n /// ```rust,no_run\n\n /// use std::net::SocketAddr;\n\n /// use std::collections::HashMap;\n\n /// use futures::Future;\n", "file_path": "src/stream/stream.rs", "rank": 77, "score": 11.785792625076361 }, { "content": "## Send an entry into a Redis Stream\n\n\n\nSend an entry into a Redis stream.\n\nRequest that will be sent to push a specified entry in the following example:\n\n\"XADD mystream * type 3 data \\\"Hello, world\\\"\"\n\n\n\n```rust\n\nuse std::net::SocketAddr;\n\nuse std::collections::HashMap;\n\nuse futures::Future;\n\nuse redis_asio::{RedisArgument, IntoRedisArgument};\n\nuse redis_asio::stream::{RedisStream, SendEntryOptions, EntryId};\n\n\n\nlet address = &\"127.0.0.1:6379\".parse::<SocketAddr>().unwrap();\n\n// create options to pass it into RedisStream::send_entry()\n\nlet send_options = SendEntryOptions::new(\"mystream\".to_string());\n\n\n\n// create key-value pairs\n\nlet mut request: HashMap<String, RedisArgument> = HashMap::new();\n\nrequest.insert(\"type\".to_string(), 3i32.into_redis_argument());\n\nrequest.insert(\"data\".to_string(), \"Hello, world!\".into_redis_argument());\n\n\n\nlet future = RedisStream::connect(address)\n\n .and_then(move |stream: RedisStream| {\n\n // HashMap<String, RedisArgument> satisfies the\n\n // HashMap<String, ToRedisArgument>\n\n stream.send_entry(send_options, request)\n\n })\n\n .map(|(_, inserted_entry_id): (RedisStream, EntryId)| {\n\n println!(\"{:?} has sent\", inserted_entry_id.to_string());\n\n })\n\n .map_err(|err| eprintln!(\"something went wrong: {}\", err));\n\ntokio::run(future);\n\n```\n", "file_path": "README.md", "rank": 78, "score": 11.520680892265945 }, { "content": "use tokio_codec::Decoder;\n\nuse tokio_tcp::TcpStream;\n\nuse futures::{Future, Stream, Sink, Async, try_ready};\n\nuse crate::{RedisValue, RedisCommand, RespInternalValue, RedisCodec, RedisError, RedisErrorKind};\n\nuse std::net::SocketAddr;\n\nuse core::marker::Send as SendMarker;\n\nuse std::error::Error;\n\n\n\n\n\n/// Actual Redis connection converts packets from `RESP` packets into `RedisValue`\n\n/// and from `RedisCommand` into `RESP` packets.\n\n///\n\n/// # Example\n\n/// ```rust,no_run\n\n/// use std::net::SocketAddr;\n\n/// use futures::Future;\n\n/// use redis_asio::{RedisCoreConnection, RedisValue, command, from_redis_value};\n\n///\n\n/// let address = &\"127.0.0.1:6379\".parse::<SocketAddr>().unwrap();\n\n///\n", "file_path": "src/base/connection.rs", "rank": 79, "score": 11.428066333940533 }, { "content": "use crate::{RedisValue, RedisCoreConnection, RedisError, RedisErrorKind,\n\n IntoRedisArgument, from_redis_value};\n\nuse super::*;\n\n\n\nuse std::error::Error;\n\nuse std::net::SocketAddr;\n\nuse std::collections::HashMap;\n\nuse futures::{Future, Sink};\n\n\n\n\n\n/// The structure represents a Redis connection that provides interface for\n\n/// working with Redis Stream \"https://redis.io/topics/streams-intro\".\n\n///\n\n/// The structure wraps an actual `RedisCoreConnection`,\n\n/// converts RedisValue into and from considered structures that are easier\n\n/// to use in Redis Stream context.\n\n///\n\n/// See more examples in `examples` directory.\n\npub struct RedisStream {\n\n connection: RedisCoreConnection,\n", "file_path": "src/stream/stream.rs", "rank": 80, "score": 11.261351278885371 }, { "content": "mod tests {\n\n use super::*;\n\n\n\n #[test]\n\n fn common_test_parse_stream_entry() {\n\n let entry1 = RedisValue::Array(vec![\n\n RedisValue::BulkString(b\"1581870410019-0\".to_vec()),\n\n RedisValue::Array(vec![\n\n RedisValue::BulkString(b\"1key1\".to_vec()),\n\n RedisValue::BulkString(b\"1value1\".to_vec()),\n\n RedisValue::BulkString(b\"1key2\".to_vec()),\n\n RedisValue::Int(2)\n\n ])\n\n ]);\n\n\n\n let entry2 = RedisValue::Array(vec![\n\n RedisValue::BulkString(b\"1581870414714-0\".to_vec()),\n\n RedisValue::Array(vec![\n\n RedisValue::BulkString(b\"2key1\".to_vec()),\n\n RedisValue::BulkString(b\"2value1\".to_vec()),\n", "file_path": "src/stream/entry.rs", "rank": 81, "score": 11.070310655698375 }, { "content": " self\n\n }\n\n\n\n /// Add new argument into `RedisCommand` through object changing.\n\n /// The argument should implement the `IntoRedisArgument` trait.\n\n pub fn arg_mut<T: IntoRedisArgument>(&mut self, arg: T) {\n\n self.args.push(arg.into_redis_argument().into_resp_value());\n\n }\n\n\n\n /// Append the other `RedisCommand`'s arguments into self arguments.\n\n pub fn append(&mut self, mut other: RedisCommand) {\n\n self.args.append(&mut other.args);\n\n }\n\n\n\n // TODO make it pub(crate) maybe.\n\n /// Convert the self into `RespInternalValue`.\n\n pub fn into_resp_value(self) -> RespInternalValue {\n\n RespInternalValue::Array(self.args)\n\n }\n\n}\n", "file_path": "src/base/command.rs", "rank": 82, "score": 11.007364826732225 }, { "content": " pub(crate) group: String,\n\n /// Consumer name\n\n pub(crate) consumer: String,\n\n}\n\n\n\n/// The `Stream<Item=Vec<StreamEntry>, Error=RedisError>` wrapper\n\npub struct Subscribe {\n\n pub(crate) stream: Box<dyn Stream<Item=RedisValue, Error=RedisError> + Send + 'static>,\n\n}\n\n\n\nimpl Stream for Subscribe {\n\n type Item = Vec<StreamEntry>;\n\n type Error = RedisError;\n\n\n\n fn poll(&mut self) -> Result<Async<Option<Self::Item>>, Self::Error> {\n\n self.stream.poll()\n\n .and_then(|value| {\n\n let value = match value {\n\n Async::Ready(x) => x,\n\n _ => return Ok(Async::NotReady)\n", "file_path": "src/stream/consume.rs", "rank": 84, "score": 10.708673259616754 }, { "content": " /// stream.ack_entry(ack_options)\n\n /// })\n\n /// .map(|(_, response): (RedisStream, AckResponse)| {\n\n /// assert_eq!(AckResponse::Ok, response);\n\n /// })\n\n /// .map_err(|err| eprintln!(\"something went wrong: {}\", err));\n\n /// tokio::run(future);\n\n /// ```\n\n pub fn ack_entry(self, options: AckOptions)\n\n -> impl Future<Item=(Self, AckResponse), Error=RedisError> + Send + 'static {\n\n self.connection.send(ack_entry_command(options))\n\n .and_then(|(connection, response)| {\n\n let response = match response {\n\n RedisValue::Int(x) => AckResponse::new(x),\n\n _ => return Err(RedisError::new(RedisErrorKind::ParseError, \"Expect integer reply on XACK request\".to_string())),\n\n };\n\n Ok((RedisStream { connection }, response))\n\n })\n\n }\n\n\n", "file_path": "src/stream/stream.rs", "rank": 85, "score": 10.493174842701592 }, { "content": "}\n\n\n\n/// Structure that wraps an range entry received on XRANGE request.\n\n#[derive(Clone, PartialEq)]\n\npub struct RangeEntry {\n\n /// Stream entry id is a simple string \"milliseconds-id\"\n\n pub id: EntryId,\n\n /// Note Redis allows to use key as a binary Bulk String\n\n /// but in the library it is forbidden for easy of use API.\n\n /// Value may be any of the RedisValue types\n\n pub values: HashMap<String, RedisValue>,\n\n}\n\n\n\nimpl StreamEntry {\n\n pub(crate) fn new(stream: String, id: EntryId, values: HashMap<String, RedisValue>) -> Self {\n\n StreamEntry {\n\n stream,\n\n id,\n\n values,\n\n }\n", "file_path": "src/stream/entry.rs", "rank": 86, "score": 10.353534774669754 }, { "content": " RedisValue::Int(2)\n\n ])\n\n ]);\n\n\n\n let stream = RedisValue::Array(vec![\n\n RedisValue::BulkString(b\"stream\".to_vec()),\n\n RedisValue::Array(vec![entry])\n\n ]);\n\n\n\n let value = RedisValue::Array(vec![stream]);\n\n\n\n assert!(parse_stream_entries(value).is_err(), \"Expect an parse error\");\n\n }\n\n\n\n #[test]\n\n fn test_invalid_key_value() {\n\n let entry = RedisValue::Array(vec![\n\n RedisValue::BulkString(b\"1581855076637-0\".to_vec()),\n\n RedisValue::Array(vec![\n\n // there is only key without value\n", "file_path": "src/stream/entry.rs", "rank": 87, "score": 10.332698830295799 }, { "content": "/// let set_req = command(\"SET\").arg(\"foo\").arg(123);\n\n/// let get_req = command(\"GET\").arg(\"foo\");\n\n///\n\n/// let future = RedisCoreConnection::connect(address)\n\n/// .and_then(move |con| con.send(set_req))\n\n/// .and_then(|(con, response)| {\n\n/// assert_eq!(RedisValue::Ok, response, \"Expect Ok\");\n\n/// con.send(get_req)\n\n/// })\n\n/// .map(move |(_, response)|\n\n/// assert_eq!(123, from_redis_value(&response).unwrap()))\n\n/// .map_err(|_| unreachable!());\n\n/// tokio::run(future);\n\n/// ```\n\npub struct RedisCoreConnection {\n\n pub(crate) sender: Box<dyn Sink<SinkItem=RedisCommand, SinkError=RedisError> + SendMarker + 'static>,\n\n pub(crate) receiver: Box<dyn Stream<Item=RespInternalValue, Error=RedisError> + SendMarker + 'static>,\n\n}\n\n\n\nimpl RedisCoreConnection {\n", "file_path": "src/base/connection.rs", "rank": 88, "score": 10.318229248706137 }, { "content": "}\n\n\n\nimpl RedisStream {\n\n /// Open a connection to Redis server and wrap it into `RedisStream`,\n\n /// that will be available in the future.\n\n pub fn connect(addr: &SocketAddr)\n\n -> impl Future<Item=RedisStream, Error=RedisError> + Send + 'static {\n\n RedisCoreConnection::connect(addr)\n\n .map(|connection| Self { connection })\n\n }\n\n\n\n /// Send an entry that will be constructed by options and pairs of key-values.\n\n ///\n\n /// # Example\n\n ///\n\n /// ```rust,no_run\n\n /// use std::net::SocketAddr;\n\n /// use std::collections::HashMap;\n\n /// use futures::Future;\n\n /// use redis_asio::{RedisArgument, IntoRedisArgument};\n", "file_path": "src/stream/stream.rs", "rank": 89, "score": 10.275021657748972 }, { "content": " // The Item and Error are required by tokio::run().\n\n let producer = create_group\n\n .and_then(move |_| {\n\n RedisStream::connect(&redis_address)\n\n })\n\n .and_then(move |producer| {\n\n rx\n\n .map_err(|_|\n\n RedisError::new(RedisErrorKind::InternalError,\n\n \"Something went wrong with UnboundedChannel\".to_string()))\n\n // Use fold() to redirect messages from the channel receiver (rx) to the Redis stream.\n\n .fold(producer, move |producer, message| {\n\n let options = SendEntryOptions::new(stream_name.clone());\n\n\n\n // Serialize the message to pairs of key-value.\n\n let data = message.into_redis_stream_entry();\n\n\n\n producer\n\n .send_entry(options, data)\n\n .map(|(producer, added_entry_id)| {\n", "file_path": "examples/stream_producer.rs", "rank": 91, "score": 9.965451529473574 }, { "content": "# redis-asio\n\n\n\nredis-asio is a Redis client library written in pure Rust based on\n\nasynchronous `tokio` library.\n\n\n\nThe library provides a `base` module for low-level request sending and\n\nresponse handling, and a `stream` module that contains specific interfaces\n\nfor work with Redis-Stream \"https://redis.io/topics/streams-intro\".\n\n\n\nThe library works with binary-safe strings that allows users to serialize\n\ntheir message structures and send via\n\nRESP protocol \"https://redis.io/topics/protocol\".\n\n\n\n# Use in project\n\n\n\nDepend on the redis-asio in project via Cargo:\n\n\n\n```toml\n\n[dependencies]\n\nredis-async = \"0.1\"\n\n```\n\n\n\nResolve the crate interfaces:\n\n\n\n```rust\n\nextern crate redis_asio;\n\n```\n\n\n\n# Motivating examples\n\n\n\n## SET, GET value from cache\n\n```rust\n\nuse std::net::SocketAddr;\n\nuse futures::Future;\n\nuse redis_asio::{RedisCoreConnection, RedisValue, from_redis_value};\n\n\n\nlet address = &\"127.0.0.1:6379\".parse::<SocketAddr>().unwrap();\n\n\n\nlet set_req = command(\"SET\").arg(\"foo\").arg(123);\n\nlet get_req = command(\"GET\").arg(\"foo\");\n\n\n\nlet future = RedisCoreConnection::connect(address)\n\n .and_then(move |con| {\n\n // send \"SET foo 123\" request\n\n con.send(set_req)\n\n })\n\n .and_then(|(con, response)| {\n\n // check if the value has been set\n\n assert_eq!(RedisValue::Ok, response);\n\n // send \"GET foo\" request\n\n con.send(get_req)\n\n })\n\n .map(move |(_, response)|\n\n // check if the received value is the same\n\n assert_eq!(123, from_redis_value(&response).unwrap()))\n\n .map_err(|_| unreachable!());\n\n// start the Tokio runtime using the `future`\n\ntokio::run(future);\n\n```\n\n\n", "file_path": "README.md", "rank": 92, "score": 9.836361106182462 }, { "content": " ])\n\n ]);\n\n\n\n let stream2 = RedisValue::Array(vec![\n\n RedisValue::BulkString(b\"stream2\".to_vec()),\n\n RedisValue::Array(vec![entry3])\n\n ]);\n\n\n\n let value = RedisValue::Array(vec![stream1, stream2]);\n\n\n\n let result = parse_stream_entries(value).unwrap();\n\n\n\n let mut entry1: HashMap<String, RedisValue> = HashMap::new();\n\n entry1.insert(\"1key1\".to_string(), RedisValue::BulkString(b\"1value1\".to_vec()));\n\n entry1.insert(\"1key2\".to_string(), RedisValue::Int(2));\n\n\n\n let mut entry2: HashMap<String, RedisValue> = HashMap::new();\n\n entry2.insert(\"2key1\".to_string(), RedisValue::BulkString(b\"2value1\".to_vec()));\n\n entry2.insert(\"2key2\".to_string(), RedisValue::BulkString(b\"2value2\".to_vec()));\n\n entry2.insert(\"2key3\".to_string(), RedisValue::BulkString(b\"2value3\".to_vec()));\n", "file_path": "src/stream/entry.rs", "rank": 93, "score": 9.75509221857736 }, { "content": "use crate::RespInternalValue;\n\n\n\n\n\n/// Make a Redis command represents array of `BulkString`s\n\n/// wrapped into `RedisCommand`.\n\n///\n\n/// # Example\n\n///\n\n/// ```\n\n/// use redis_asio::command;\n\n/// let cmd = redis_asio::command(\"SET\").arg(\"foo\").arg(\"bar\");\n\n/// ```\n", "file_path": "src/base/command.rs", "rank": 94, "score": 9.517385925249496 }, { "content": " SubscribeOptions { streams: stream, group }\n\n }\n\n}\n\n\n\nimpl ReadExplicitOptions {\n\n pub fn new(stream: String, start_id: EntryId, count: u16) -> ReadExplicitOptions {\n\n let streams = vec![(stream, start_id)];\n\n ReadExplicitOptions { streams, count }\n\n }\n\n\n\n pub fn add_stream(&mut self, stream: String, start_id: EntryId) {\n\n self.streams.push((stream, start_id))\n\n }\n\n}\n\n\n\nimpl RangeOptions {\n\n pub fn new(stream: String, count: u16, range: RangeType) -> RedisResult<RangeOptions> {\n\n if !range.is_valid() {\n\n return Err(\n\n RedisError::new(RedisErrorKind::InvalidOptions,\n", "file_path": "src/stream/consume.rs", "rank": 95, "score": 9.432219673267337 }, { "content": "extern crate tokio;\n\nextern crate futures;\n\n\n\nuse std::env;\n\nuse std::io;\n\nuse std::net::SocketAddr;\n\nuse std::collections::HashMap;\n\nuse futures::{Future, Stream, Sink};\n\nuse futures::sync::mpsc::{UnboundedSender, unbounded};\n\n\n\nuse redis_asio::{RedisResult, RedisValue, RedisError, RedisErrorKind, FromRedisValue, from_redis_value};\n\nuse redis_asio::stream::{RedisStream, StreamEntry, EntryId, AckResponse, SubscribeOptions,\n\n RedisGroup, TouchGroupOptions, AckOptions};\n\n\n\n#[derive(Debug)]\n", "file_path": "examples/stream_consumer.rs", "rank": 96, "score": 9.403911504172513 }, { "content": " const ENTRY_ID_CHUNK_LEN: usize = 2;\n\n const ENTRY_ID_MS_POS: usize = 0;\n\n const ENTRY_ID_ID_POS: usize = 1;\n\n\n\n let tokens: Vec<&str>\n\n = id.split('-').filter(|token| !token.is_empty()).collect();\n\n if tokens.len() != ENTRY_ID_CHUNK_LEN {\n\n return Err(\n\n RedisError::new(\n\n RedisErrorKind::ParseError,\n\n format!(\"Couldn't parse a Redis entry id: {:?}\", &id))\n\n );\n\n }\n\n\n\n let ms = tokens[ENTRY_ID_MS_POS].parse::<u64>().map_err(&to_redis_error)?;\n\n let id = tokens[ENTRY_ID_ID_POS].parse::<u64>().map_err(&to_redis_error)?;\n\n Ok(Self((ms, id)))\n\n }\n\n\n\n pub fn to_string(&self) -> String {\n\n format!(\"{}-{}\", (self.0).0, (self.0).1)\n\n }\n\n}\n\n\n", "file_path": "src/stream/entry.rs", "rank": 97, "score": 9.303754553932905 }, { "content": " /// Open a connection to Redis server and wrap it into `RedisCoreConnection`,\n\n /// that will be available in the future.\n\n pub fn connect(addr: &SocketAddr) -> impl Future<Item=Self, Error=RedisError> {\n\n TcpStream::connect(addr)\n\n .map_err(|err| RedisError::new(RedisErrorKind::ConnectionError, err.description().to_string()))\n\n .map(|stream| {\n\n let codec = RedisCodec;\n\n let (tx, rx) = codec.framed(stream).split();\n\n Self::new(tx, rx)\n\n })\n\n }\n\n\n\n pub(crate) fn new<S, R>(sender: S, receiver: R) -> RedisCoreConnection\n\n where S: Sink<SinkItem=RedisCommand, SinkError=RedisError> + SendMarker + 'static,\n\n R: Stream<Item=RespInternalValue, Error=RedisError> + SendMarker + 'static {\n\n let sender = Box::new(sender);\n\n let receiver = Box::new(receiver);\n\n RedisCoreConnection { sender, receiver }\n\n }\n\n\n", "file_path": "src/base/connection.rs", "rank": 98, "score": 9.151698543131742 }, { "content": "use super::RespInternalValue;\n\n\n", "file_path": "src/base/codec/encode.rs", "rank": 99, "score": 9.059260160249957 } ]
Rust
src/global/logging.rs
HristoKolev/xdxd-snapshot-rotator
6cc807819d7a1002ab15bc087f90bbb2caa4013b
use std::sync::Mutex; use std::path::{PathBuf, Path}; use std::fs::{File, OpenOptions}; use std::io::{SeekFrom, Write, Seek}; use chrono::Utc; use super::prelude::*; pub struct LoggingConfiguration { pub max_length: u64, pub file_path: PathBuf, } pub struct FileAppenderState { file_handle: File, file_length: u64, } pub struct FileAppender { state: Mutex<FileAppenderState>, config: LoggingConfiguration, } impl FileAppender { pub fn new(config: LoggingConfiguration) -> Result<FileAppender> { ::std::fs::create_dir_all(config.file_path.get_directory())?; let mut file_handle = FileAppender::create_file_handle(&config.file_path)?; let file_length = file_handle.seek(SeekFrom::End(0))?; Ok(FileAppender { state: Mutex::new(FileAppenderState { file_handle, file_length, }), config, }) } fn create_file_handle(file_path: &Path) -> Result<File> { let file_handle = OpenOptions::new() .write(true) .create(true) .open(file_path)?; Ok(file_handle) } fn roll_file(&self, state: &mut FileAppenderState) -> Result { let file_stem = self.config.file_path.file_stem_as_string()?; let file_extension = self.config.file_path.extension_as_string()?; let directory = self.config.file_path.get_directory_as_string()?; let now = Utc::now(); let formatted_date = now.format("%Y_%m_%d__").to_string(); let nanos = now.timestamp_nanos(); let new_file_path= format!("{}/{}__{}{}.{}", directory, file_stem, formatted_date, nanos, file_extension); let new_path = Path::new(&new_file_path); state.file_handle.sync_all()?; ::std::fs::rename(&self.config.file_path, new_path)?; let file_handle = FileAppender::create_file_handle(&self.config.file_path)?; state.file_handle = file_handle; state.file_length = 0; Ok(()) } pub fn writeln(&self, message: &str) -> Result { let mut state = self.state.lock()?; if state.file_length >= self.config.max_length { self.roll_file(&mut state)?; } let len = state.file_handle.write(format!("{}\n", message).as_bytes())? as u64; state.file_length += len; Ok(()) } } pub struct ConsoleAppender; impl ConsoleAppender { pub fn new() -> ConsoleAppender { ConsoleAppender {} } #[allow(unused)] pub fn writeln(&self, message: &str) -> Result { let stdout = &mut ::std::io::stdout(); write!(stdout, "{}\n", message)?; Ok(()) } #[allow(unused)] pub fn ewriteln(&self, message: &str) -> Result { let stderr = &mut ::std::io::stderr(); write!(stderr, "{}\n", message)?; Ok(()) } } pub struct InMemoryAppender { pub entries: Mutex<Vec<String>>, } impl InMemoryAppender { pub fn new() -> InMemoryAppender { InMemoryAppender { entries: Mutex::new(Vec::new()) } } pub fn add_entry(&self, message: &str) -> Result { let mut vec = self.entries.lock()?; vec.push(message.to_string()); Ok(()) } } pub struct Logger { file_appender: FileAppender, console_appender: ConsoleAppender, in_memory_appender: InMemoryAppender, } impl Logger { pub fn new(config: LoggingConfiguration) -> Result<Logger> { Ok(Logger { console_appender: ConsoleAppender::new(), in_memory_appender: InMemoryAppender::new(), file_appender: FileAppender::new(config)? }) } fn format_message(&self, message: &str) -> Result<String> { let now = Utc::now(); let formatted_date = now.format("%Y-%m-%d %H:%M:%S").to_string(); Ok(format!("{} | {}", formatted_date, message)) } pub fn log(&self, message: &str) -> Result { let formatted_message = self.format_message(message)?; let console_appender_result = self.console_appender.writeln(&formatted_message); let in_memory_appender_result = self.in_memory_appender.add_entry(message); let file_appender_result = self.file_appender.writeln(&formatted_message); console_appender_result?; in_memory_appender_result?; file_appender_result?; Ok(()) } #[allow(unused)] pub fn elog(&self, message: &str) -> Result { let formatted_message = self.format_message(message)?; let console_appender_result = self.console_appender.ewriteln(&formatted_message); let in_memory_appender_result = self.in_memory_appender.add_entry(message); let file_appender_result = self.file_appender.writeln(&formatted_message); console_appender_result?; in_memory_appender_result?; file_appender_result?; Ok(()) } #[allow(unused)] pub fn get_logs(&self) -> Result<Vec<String>> { let logs = self.in_memory_appender.entries.lock()?; Ok(logs.clone()) } }
use std::sync::Mutex; use std::path::{PathBuf, Path}; use std::fs::{File, OpenOptions}; use std::io::{SeekFrom, Write, Seek}; use chrono::Utc; use super::prelude::*; pub struct LoggingConfiguration { pub max_length: u64, pub file_path: PathBuf, } pub struct FileAppenderState { file_handle: File, file_length: u64, } pub struct FileAppender { state: Mutex<FileAppenderState>, config: LoggingConfiguration, } impl FileAppender { pub fn new(config: LoggingConfiguration) -> Result<FileAppender> { ::std::fs::create_dir_all(config.file_path.get_directory())?; let mut file_handle = FileAppender::create_file_handle(&config.file_path)?; let file_length = file_handle.seek(SeekFrom::End(0))?; Ok(FileAppender { state: Mutex::new(FileAppenderState { file_handle, file_length, }), config, }) } fn create_file_handle(file_path: &Path) -> Result<File> { let file_handle = OpenOptions::new() .write(true) .create(true) .open(file_path)?; Ok(file_handle) } fn roll_file(&self, state: &mut FileAppenderState) -> Result { let file_stem = self.config.file_path.file_stem_as_string()?; let file_extension = self.config.file_path.extension_as_string()?; let directory = self.config.file_path.get_directory_as_string()?; let now = Utc::now(); let formatted_date = now.format("%Y_%m_%d__").to_string(); let nanos = now.timestamp_nanos(); let new_file_path= format!("{}/{}__{}{}.{}", directory, file_stem, formatted_date, nanos, file_extension); let new_path = Path::new(&new_file_path); state.file_handle.sync_all()?; ::std::fs::rename(&self.config.file_path, new_path)?; let file_handle = FileAppender::create_file_handle(&self.config.file_path)?; state.file_handle = file_handle; state.file_length = 0; Ok(()) } pub fn writeln(&self, message: &str) -> Result { let mut state = self.state.lock()?; if state.file_length >= self.config.max_length { self.roll_file(&mut state)?; } let len = state.file_handle.write(format!("{}\n", message).as_bytes())? as u64; state.file_length += len; Ok(()) } } pub struct ConsoleAppender; impl ConsoleAppender { pub fn new() -> ConsoleAppender { ConsoleAppender {} } #[allow(unused)] pub fn writeln(&self, message: &str) -> Result { let stdout = &mut ::std::io::stdout(); write!(stdout, "{}\n", message)?; Ok(()) } #[allow(unused)] pub fn ewriteln(&self, message: &str) -> Result { let stderr = &mut ::std::io::stderr(); write!(stderr, "{}\n", message)?; Ok(()) } } pub struct InMemoryAppender { pub entries: Mutex<Vec<String>>, } impl InMemoryAppender { pub fn new() -> InMemoryAppender { InMemoryAppender { entries: Mutex::new(Vec::new()) } } pub fn add_entry(&self, message: &str) -> Result { let mut vec = self.entries.lock()?; vec.push(message.to_string()); Ok(()) } } pub struct Logger { file_appender: FileAppender, console_appender: ConsoleAppender, in_memory_appender: InMemoryAppender, } impl Logger { pub fn new(config: LoggingConfiguration) -> Result<Logger> {
} fn format_message(&self, message: &str) -> Result<String> { let now = Utc::now(); let formatted_date = now.format("%Y-%m-%d %H:%M:%S").to_string(); Ok(format!("{} | {}", formatted_date, message)) } pub fn log(&self, message: &str) -> Result { let formatted_message = self.format_message(message)?; let console_appender_result = self.console_appender.writeln(&formatted_message); let in_memory_appender_result = self.in_memory_appender.add_entry(message); let file_appender_result = self.file_appender.writeln(&formatted_message); console_appender_result?; in_memory_appender_result?; file_appender_result?; Ok(()) } #[allow(unused)] pub fn elog(&self, message: &str) -> Result { let formatted_message = self.format_message(message)?; let console_appender_result = self.console_appender.ewriteln(&formatted_message); let in_memory_appender_result = self.in_memory_appender.add_entry(message); let file_appender_result = self.file_appender.writeln(&formatted_message); console_appender_result?; in_memory_appender_result?; file_appender_result?; Ok(()) } #[allow(unused)] pub fn get_logs(&self) -> Result<Vec<String>> { let logs = self.in_memory_appender.entries.lock()?; Ok(logs.clone()) } }
Ok(Logger { console_appender: ConsoleAppender::new(), in_memory_appender: InMemoryAppender::new(), file_appender: FileAppender::new(config)? })
call_expression
[ { "content": "#[allow(unused)]\n\npub fn wait_for_lock(file_path: &str) -> Result<File> {\n\n loop {\n\n if let Some(file) = lock_file(file_path)? {\n\n return Ok(file);\n\n }\n\n\n\n std::thread::sleep(Duration::from_millis(100));\n\n }\n\n}\n", "file_path": "src/global/file_lock.rs", "rank": 0, "score": 219383.492392402 }, { "content": "pub fn read_config(file_path: &str) -> Result<AppConfig> {\n\n\n\n let json_content = ::std::fs::read_to_string(file_path)?;\n\n\n\n let materialized = ::serde_json::from_str(&json_content)?;\n\n\n\n Ok(materialized)\n\n}\n", "file_path": "src/global/app_config.rs", "rank": 1, "score": 217265.69746465352 }, { "content": "#[allow(unsafe_code)]\n\n#[allow(unused)]\n\nfn lock_file(file_path: &str) -> Result<Option<File>> {\n\n\n\n let file = OpenOptions::new()\n\n .write(true)\n\n .create(true)\n\n .open(file_path)?;\n\n\n\n unsafe {\n\n let rc = flock(file.as_raw_fd(), LOCK_EX | LOCK_NB);\n\n let is_locked = rc == 0 || EWOULDBLOCK != *__errno_location();\n\n\n\n if is_locked {\n\n Ok(Some(file))\n\n } else {\n\n Ok(None)\n\n }\n\n }\n\n}\n\n\n", "file_path": "src/global/file_lock.rs", "rank": 2, "score": 190697.74280241632 }, { "content": "pub fn list_snapshots(config: &VmConfig) -> Result<Vec<VmSnapshot>> {\n\n let ps = bash_exec_no_log!(\"virsh snapshot-list --domain {} --internal\", config.vm_name);\n\n\n\n let lines: Vec<&str> = ps.stdout\n\n .split('\\n')\n\n .skip(2)\n\n .filter(|x| x != &\"\")\n\n .collect_vec();\n\n\n\n let snapshots = lines.into_iter()\n\n .map(|line| {\n\n let line_parts: Vec<&str> = line.split(' ')\n\n .filter(|x| x != &\"\")\n\n .collect_vec();\n\n\n\n line_parts.get(0).and_then(|snapsnot_name| {\n\n let parts: Vec<&str> = snapsnot_name.split('.').collect_vec();\n\n\n\n parts.get(parts.len() - 1)\n\n .and_then(|x| x.parse::<i64>().ok())\n", "file_path": "src/snapshot_helper.rs", "rank": 3, "score": 171515.85886732186 }, { "content": "pub fn config_command() -> Result {\n\n\n\n let app_config = app_config();\n\n\n\n let json = serde_json::to_string_pretty(app_config)?;\n\n\n\n let stdout = &mut ::std::io::stdout();\n\n\n\n write!(stdout, \"{}\\n\", json)?;\n\n\n\n Ok(())\n\n}\n", "file_path": "src/config.rs", "rank": 4, "score": 152333.87671507377 }, { "content": "pub fn clear_cache(config: &VmConfig) -> Result {\n\n let snapshots = list_snapshots(config)?;\n\n\n\n let take_count = if ((snapshots.len() as i32) - config.min_snapshot_count) < 0 {\n\n 0\n\n } else {\n\n (snapshots.len() as i32) - config.min_snapshot_count\n\n };\n\n\n\n let for_delete = snapshots\n\n .into_iter()\n\n .order_by(|x| x.date)\n\n .take(take_count as usize)\n\n .collect_vec();\n\n\n\n for snapshot in for_delete {\n\n log!(\"Deleting snapshot `{}` ...\", snapshot.snapsnot_name);\n\n\n\n bash_exec!(\"virsh snapshot-delete --domain {} --snapshotname {}\", snapshot.vm_name, snapshot.snapsnot_name);\n\n }\n\n\n\n bash_exec_no_log!(\"virsh snapshot-list --domain {} --internal\", config.vm_name);\n\n\n\n Ok(())\n\n}", "file_path": "src/snapshot_helper.rs", "rank": 5, "score": 150813.7398299601 }, { "content": "/// Checks whether the function name starts with the given pattern.\n\n///\n\n/// In trait implementations, the original type name is wrapped in \"_< ... >\" and colons are\n\n/// replaced with dots. This function accounts for differences while checking.\n\npub fn function_starts_with(mut func_name: &str, mut pattern: &str) -> bool {\n\n if pattern.starts_with('<') {\n\n while pattern.starts_with('<') {\n\n pattern = &pattern[1..];\n\n\n\n if func_name.starts_with('<') {\n\n func_name = &func_name[1..];\n\n } else if func_name.starts_with(\"_<\") {\n\n func_name = &func_name[2..];\n\n } else {\n\n return false;\n\n }\n\n }\n\n } else {\n\n func_name = func_name.trim_start_matches('<').trim_start_matches(\"_<\");\n\n }\n\n\n\n if !func_name.is_char_boundary(pattern.len()) {\n\n return false;\n\n }\n\n\n\n func_name\n\n .chars()\n\n .zip(pattern.chars())\n\n .all(|(f, p)| f == p || f == '.' && p == ':')\n\n}\n", "file_path": "src/global/sentry_backtrace.rs", "rank": 6, "score": 148206.97923489904 }, { "content": "pub fn exec(command: &str) -> Result<CommandResult> {\n\n\n\n exec_internal(command, true)\n\n}\n\n\n", "file_path": "src/global/bash_shell.rs", "rank": 7, "score": 142521.39486438397 }, { "content": "pub fn exec_without_log(command: &str) -> Result<CommandResult> {\n\n\n\n exec_internal(command, false)\n\n}\n\n\n\n\n\n#[derive(Debug)]\n\npub struct CommandResult {\n\n pub status_code: Option<i32>,\n\n pub stdout: String,\n\n pub stderr: String,\n\n pub command: String,\n\n pub success: bool,\n\n}\n\n\n\nimpl CommandResult {\n\n\n\n //noinspection RsSelfConvention\n\n pub fn as_result(self) -> Result<CommandResult> {\n\n if self.success {\n", "file_path": "src/global/bash_shell.rs", "rank": 8, "score": 137320.7081610122 }, { "content": "#[allow(unused)]\n\npub fn logger() -> &'static Logger {\n\n\n\n &GLOBAL_INSTANCE.logger\n\n}\n\n\n", "file_path": "src/global/mod.rs", "rank": 9, "score": 131578.62240767438 }, { "content": "pub fn strip_symbol(s: &str) -> &str {\n\n HASH_FUNC_RE\n\n .captures(s)\n\n .map(|c| c.get(1).unwrap().as_str())\n\n .unwrap_or(s)\n\n}\n\n\n", "file_path": "src/global/sentry_backtrace.rs", "rank": 10, "score": 120915.1540852302 }, { "content": "pub fn send_success_report(vm: &VmConfig) -> Result {\n\n\n\n let app_config = app_config();\n\n\n\n let subject = format!(\n\n \"[SUCCESS] xdxd-snapshot-rotator | Snapshot was created for vm `{}` on host `{}`.\",\n\n vm.vm_name,\n\n app_config.hostname\n\n );\n\n\n\n let html_template = include_str!(\"email-template.html\");\n\n\n\n let logs = logger().get_logs()?.join(\"\\n\");\n\n\n\n let registry = Handlebars::new();\n\n\n\n let now = app_start_time();\n\n\n\n let report_content = registry.render_template(\n\n html_template,\n", "file_path": "src/global/email_report.rs", "rank": 11, "score": 118278.57477245637 }, { "content": "fn send_mail(subject: &str, content: &str) -> Result {\n\n\n\n let app_config = app_config();\n\n\n\n let email_client = email::EmailClient::new(\n\n &app_config.email_config.smtp_username,\n\n &app_config.email_config.smtp_password,\n\n &app_config.email_config.smtp_host,\n\n app_config.email_config.smtp_port,\n\n );\n\n\n\n let message = email::EmailMessage::new(\n\n app_config.email_config.notification_emails.clone(),\n\n subject,\n\n content,\n\n );\n\n\n\n email_client.send(&message)?;\n\n\n\n Ok(())\n\n}\n", "file_path": "src/global/email_report.rs", "rank": 12, "score": 116714.7179669536 }, { "content": "pub fn list_shapshot_command() -> Result {\n\n let options = list_command_options()?;\n\n\n\n let config = app_config().snapshot_config.as_ref()\n\n .and_then(|x| x.get(&options.vm_name).cloned())\n\n .or_error(&format!(\"``xdxd-snapshot-rotator` not configured for vm `{}`\", options.vm_name))?;\n\n\n\n let snapshots = list_snapshots(&config)?;\n\n\n\n for snapshot in snapshots {\n\n log!(\"{} {}\", snapshot.vm_name, snapshot.date);\n\n }\n\n\n\n Ok(())\n\n}\n\n\n", "file_path": "src/list_snapshot.rs", "rank": 13, "score": 113748.74735356815 }, { "content": "pub fn create_shapshot_command() -> Result {\n\n\n\n let options = create_command_options()?;\n\n\n\n let config = app_config().snapshot_config.as_ref()\n\n .and_then(|x| x.get(&options.vm_name).cloned())\n\n .or_error(&format!(\"``xdxd-snapshot-rotator` not configured for vm `{}`\", options.vm_name))?;\n\n\n\n let now = app_start_time();\n\n\n\n let snapshot_name = format!(\n\n \"{}.{}.{}\",\n\n config.vm_name,\n\n now.format(\"%Y-%m-%d_%H-%M-%S\").to_string(),\n\n now.timestamp().to_string()\n\n );\n\n\n\n bash_exec!(\"virsh snapshot-create-as {} --name {}\", config.vm_name, snapshot_name);\n\n\n\n clear_cache(&config)?;\n\n\n\n email_report::send_success_report(&config)?;\n\n\n\n Ok(())\n\n}\n\n\n", "file_path": "src/create_snapshot.rs", "rank": 14, "score": 113748.74735356815 }, { "content": "pub fn clear_cache_command() -> Result {\n\n\n\n let options = clear_cache_command_options()?;\n\n\n\n let config = app_config().snapshot_config.as_ref()\n\n .and_then(|x| x.get(&options.vm_name).cloned())\n\n .or_error(&format!(\"``xdxd-snapshot-rotator` not configured for vm `{}`\", options.vm_name))?;\n\n\n\n clear_cache(&config)?;\n\n\n\n Ok(())\n\n}", "file_path": "src/clear_cache.rs", "rank": 15, "score": 113748.74735356815 }, { "content": "pub fn filename(s: &str) -> String {\n\n s.rsplitn(2, &['/', '\\\\'][..])\n\n .next()\n\n .unwrap()\n\n .to_string()\n\n}\n\n\n", "file_path": "src/global/sentry_backtrace.rs", "rank": 16, "score": 108816.66656532724 }, { "content": "pub fn demangle_symbol(s: &str) -> String {\n\n COMMON_RUST_SYMBOL_ESCAPES_RE\n\n .replace_all(s, |caps: &Captures<'_>| {\n\n match &caps[1] {\n\n \"SP\" => \"@\",\n\n \"BP\" => \"*\",\n\n \"RF\" => \"&\",\n\n \"LT\" => \"<\",\n\n \"GT\" => \">\",\n\n \"LP\" => \"(\",\n\n \"RP\" => \")\",\n\n \"C\" => \",\",\n\n \"u7e\" => \"~\",\n\n \"u20\" => \" \",\n\n \"u27\" => \"'\",\n\n \"u5b\" => \"[\",\n\n \"u5d\" => \"]\",\n\n \"u7b\" => \"{\",\n\n \"u7d\" => \"}\",\n\n \"u3b\" => \";\",\n\n \"u2b\" => \"+\",\n\n \"u22\" => \"\\\"\",\n\n _ => unreachable!(),\n\n }\n\n .to_string()\n\n })\n\n .to_string()\n\n}\n\n\n", "file_path": "src/global/sentry_backtrace.rs", "rank": 17, "score": 106323.29014755914 }, { "content": "/// Checks if a function is considered to be not in-app\n\npub fn is_sys_function(func: &str) -> bool {\n\n WELL_KNOWN_SYS_MODULES\n\n .iter()\n\n .any(|m| function_starts_with(func, m))\n\n}\n\n\n", "file_path": "src/global/sentry_backtrace.rs", "rank": 18, "score": 104011.63799907576 }, { "content": "fn parse_dsn(dsn: &str) -> Result<CustomDsn> {\n\n\n\n let url = Url::parse(dsn)?;\n\n\n\n let domain = url.domain().or_error(\"Invalid dsn domain.\")?;\n\n let port = url.port().unwrap_or(80);\n\n let scheme = url.scheme();\n\n let last_index = url.path().last_index_of('/').unwrap_or(0);\n\n let path = &url.path()[0..last_index];\n\n let project_id = &url.path()[(last_index + 1)..];\n\n let public_key = url.username();\n\n\n\n Ok(CustomDsn {\n\n scheme: scheme.to_string(),\n\n domain: domain.to_string(),\n\n port,\n\n path: path.to_string(),\n\n project_id: project_id.to_string(),\n\n public_key: public_key.to_string(),\n\n })\n\n}\n\n\n\nlazy_static::lazy_static! {\n\n static ref CRATE_RE: Regex = Regex::new(r\"^(?:_<)?([a-zA-Z0-9_]+?)(?:\\.\\.|::)\").unwrap();\n\n}\n\n\n", "file_path": "src/global/custom_sentry_client.rs", "rank": 19, "score": 102824.21957136929 }, { "content": "fn exec_internal(command: &str, log_output: bool) -> Result<CommandResult> {\n\n\n\n let mut process = Command::new(\"/usr/bin/env\")\n\n .arg(\"bash\")\n\n .stdout(Stdio::piped())\n\n .stderr(Stdio::piped())\n\n .stdin(Stdio::piped())\n\n .spawn()?;\n\n\n\n let stdout = process.stdout.take()\n\n .or_error(\"stdout was not redirected.\")?;\n\n\n\n let stderr = process.stderr.take()\n\n .or_error(\"stderr was not redirected.\")?;\n\n\n\n let stdin = process.stdin.as_mut()\n\n .or_error(\"stdin was not redirected.\")?;\n\n\n\n let stdout_thread : JoinHandle<Result<String>> = thread::spawn(move || {\n\n\n", "file_path": "src/global/bash_shell.rs", "rank": 20, "score": 102003.89679885359 }, { "content": "/// The default error handler.\n\npub fn handle_error(error: &CustomError) -> Result {\n\n\n\n let log_result = logger().log(&format!(\"An error occurred: {:#?}\", error));\n\n let sentry_result = sentry_client().send_error(error);\n\n\n\n log_result?;\n\n sentry_result?;\n\n\n\n Ok(())\n\n}\n\n\n", "file_path": "src/global/error_handler.rs", "rank": 21, "score": 100477.10474328691 }, { "content": "#[allow(unused)]\n\npub fn app_config() -> &'static AppConfig {\n\n\n\n &GLOBAL_INSTANCE.app_config\n\n}\n\n\n", "file_path": "src/global/mod.rs", "rank": 22, "score": 99479.29065570369 }, { "content": "pub fn send_error_report(error: &CustomError) -> Result {\n\n\n\n let app_config = app_config();\n\n\n\n let subject = format!(\n\n \"[FAILURE] xdxd-snapshot-rotator | An error occurred on `{}`.\",\n\n app_config.hostname\n\n );\n\n\n\n let html_template = include_str!(\"email-template.html\");\n\n\n\n let logs = logger().get_logs()?.join(\"\\n\");\n\n\n\n let registry = Handlebars::new();\n\n\n\n let now = app_start_time();\n\n\n\n let report_content = registry.render_template(\n\n html_template,\n\n &json!({\n", "file_path": "src/global/email_report.rs", "rank": 23, "score": 98486.75951833485 }, { "content": "pub fn handle_fatal_error(error: &CustomError) -> Result {\n\n\n\n let standard_error_handler_result = handle_error(error);\n\n let email_result = email_report::send_error_report(&error);\n\n\n\n standard_error_handler_result?;\n\n email_result?;\n\n\n\n Ok(())\n\n}\n\n\n", "file_path": "src/global/error_handler.rs", "rank": 24, "score": 98486.75951833485 }, { "content": "#[allow(unused)]\n\npub fn trim_stacktrace<F>(stacktrace: &mut Stacktrace, f: F)\n\n where\n\n F: Fn(&Frame, &Stacktrace) -> bool,\n\n{\n\n let known_cutoff = stacktrace\n\n .frames\n\n .iter()\n\n .rev()\n\n .position(|frame| match frame.function {\n\n Some(ref func) => is_well_known(&func) || f(frame, stacktrace),\n\n None => false,\n\n });\n\n\n\n if let Some(cutoff) = known_cutoff {\n\n let secondary = {\n\n let func = stacktrace.frames[stacktrace.frames.len() - cutoff - 1]\n\n .function\n\n .as_ref()\n\n .unwrap();\n\n\n", "file_path": "src/global/sentry_backtrace.rs", "rank": 25, "score": 94251.72104213861 }, { "content": "fn main_result() -> Result {\n\n\n\n cli().register_command(\"clear-cache\", Box::new(clear_cache_command))?;\n\n cli().register_command(\"list\", Box::new(list_shapshot_command))?;\n\n cli().register_command(\"create\", Box::new(create_shapshot_command))?;\n\n cli().register_command(\"config\", Box::new(config_command))?;\n\n\n\n match cli().run() {\n\n Err(err) => {\n\n if let CustomErrorKind::UserError(message) = err.kind {\n\n log!(\"Error: {}\", message);\n\n ::std::process::exit(1);\n\n } else {\n\n return Err(err);\n\n }\n\n },\n\n Ok(_) => ()\n\n };\n\n\n\n Ok(())\n\n}\n", "file_path": "src/main.rs", "rank": 26, "score": 92477.7818566667 }, { "content": "/// Creates the global object.\n\nfn create_global_result() -> Result<Global> {\n\n\n\n let config_directory= ::std::env::var_os(\"CONFIG_DIRECTORY\")\n\n .map_result(|x| Ok(x.get_as_string()?))?\n\n .map(|x| Path::new(&x).to_path_buf())\n\n .unwrap_or_else_result(|| Ok(::std::env::current_exe()?.get_directory()))?;\n\n\n\n let config_file_path = config_directory.join(APP_CONFIG_FILE_NAME);\n\n\n\n if !config_file_path.exists() {\n\n\n\n eprintln!(\"The `{}` file is missing.\", APP_CONFIG_FILE_NAME);\n\n\n\n ::std::process::exit(1);\n\n }\n\n\n\n let app_config = read_config(&config_file_path.get_as_string()?)\n\n .crash_on_early_error();\n\n\n\n let sentry = CustomSentryClient::new(&app_config.sentry_dsn)?;\n", "file_path": "src/global/mod.rs", "rank": 27, "score": 84284.63934594812 }, { "content": "/// Runs the initialization code.\n\n/// Should be called first thing in the entry point.\n\npub fn initialize() {\n\n\n\n ::std::env::set_var(\"RUST_BACKTRACE\", \"1\");\n\n\n\n set_panic_hook();\n\n\n\n lazy_static::initialize(&GLOBAL_INSTANCE)\n\n}\n\n\n", "file_path": "src/global/mod.rs", "rank": 28, "score": 81000.2362931275 }, { "content": "#[allow(unused)]\n\npub fn run<FDo, TRes>(fdo: FDo) -> FinStruct<TRes>\n\n where FDo: FnOnce() -> Result<TRes> {\n\n\n\n let result = fdo();\n\n\n\n FinStruct {\n\n result\n\n }\n\n}\n", "file_path": "src/global/do_try.rs", "rank": 29, "score": 75049.83524671147 }, { "content": "/// Checks if a function is a well-known system function\n\nfn is_well_known(func: &str) -> bool {\n\n WELL_KNOWN_BORDER_FRAMES\n\n .iter()\n\n .any(|m| function_starts_with(&func, m))\n\n}\n\n\n", "file_path": "src/global/sentry_backtrace.rs", "rank": 30, "score": 73742.82273993951 }, { "content": "fn create_command_options() -> Result<CreateCommandOptions> {\n\n\n\n const VM_NAME_VALUE: &str = \"vm-name\";\n\n\n\n let matches = cli().command_config(|x| {\n\n\n\n x.arg(Arg::with_name(VM_NAME_VALUE)\n\n .short(\"n\")\n\n .long(VM_NAME_VALUE)\n\n .value_name(VM_NAME_VALUE)\n\n .help(\"The name of virtual machine.\")\n\n .required(true)\n\n .takes_value(true)\n\n )\n\n });\n\n\n\n let vm_name = matches.value_of(VM_NAME_VALUE)\n\n .or_error(&format!(\"No value for: {}\", VM_NAME_VALUE))?;\n\n\n\n Ok(CreateCommandOptions {\n\n vm_name: vm_name.to_string()\n\n })\n\n}\n\n\n", "file_path": "src/create_snapshot.rs", "rank": 31, "score": 73016.26117737858 }, { "content": "fn list_command_options() -> Result<ListCommandOptions> {\n\n const VM_NAME_VALUE: &str = \"vm-name\";\n\n\n\n let matches = cli().command_config(|x| {\n\n x.arg(Arg::with_name(VM_NAME_VALUE)\n\n .short(\"n\")\n\n .long(VM_NAME_VALUE)\n\n .value_name(VM_NAME_VALUE)\n\n .help(\"The name of virtual machine.\")\n\n .required(true)\n\n .takes_value(true)\n\n )\n\n });\n\n\n\n let vm_name = matches.value_of(VM_NAME_VALUE)\n\n .or_error(&format!(\"No value for: {}\", VM_NAME_VALUE))?;\n\n\n\n Ok(ListCommandOptions {\n\n vm_name: vm_name.to_string()\n\n })\n\n}\n\n\n", "file_path": "src/list_snapshot.rs", "rank": 32, "score": 73016.26117737858 }, { "content": "#[allow(unused)]\n\npub fn cli() -> &'static CliRunner {\n\n\n\n &GLOBAL_INSTANCE.cli\n\n}\n\n\n\n#[allow(unused_macros)]\n\nmacro_rules! log {\n\n ($x:expr) => {\n\n crate::global::logger().log(&format!(\"{}\", $x))?\n\n };\n\n ($($x:expr),*) => {\n\n crate::global::logger().log(&format!($($x,)*))?\n\n };\n\n}\n\n\n\n#[allow(unused_macros)]\n\nmacro_rules! elog {\n\n ($x:expr) => {\n\n crate::global::logger().elog(&format!(\"{}\", $x))?\n\n };\n", "file_path": "src/global/mod.rs", "rank": 33, "score": 70703.13683921927 }, { "content": "fn clear_cache_command_options() -> Result<ClearCacheCommandOptions> {\n\n const VM_NAME_VALUE: &str = \"vm-name\";\n\n\n\n let matches = cli().command_config(|x| {\n\n x.arg(Arg::with_name(VM_NAME_VALUE)\n\n .short(\"n\")\n\n .long(VM_NAME_VALUE)\n\n .value_name(VM_NAME_VALUE)\n\n .help(\"The name of virtual machine.\")\n\n .required(true)\n\n .takes_value(true)\n\n )\n\n });\n\n\n\n let vm_name = matches.value_of(VM_NAME_VALUE)\n\n .or_error(&format!(\"No value for: {}\", VM_NAME_VALUE))?;\n\n\n\n Ok(ClearCacheCommandOptions {\n\n vm_name: vm_name.to_string()\n\n })\n\n}\n\n\n", "file_path": "src/clear_cache.rs", "rank": 34, "score": 70261.7909441673 }, { "content": "#[allow(unused)]\n\npub fn sentry_client() -> &'static CustomSentryClient {\n\n\n\n &GLOBAL_INSTANCE.sentry\n\n}\n\n\n", "file_path": "src/global/mod.rs", "rank": 35, "score": 67549.20497074476 }, { "content": "/// Tries to parse the rust crate from a function name.\n\nfn parse_crate_name(func_name: &str) -> Option<String> {\n\n CRATE_RE\n\n .captures(func_name)\n\n .and_then(|caps| caps.get(1))\n\n .map(|cr| cr.as_str().into())\n\n}\n", "file_path": "src/global/custom_sentry_client.rs", "rank": 36, "score": 66099.17453856848 }, { "content": "pub trait PathExtensions {\n\n fn get_as_string(&self) -> Result<String>;\n\n fn extension_as_string(&self) -> Result<String>;\n\n fn file_stem_as_string(&self) -> Result<String>;\n\n fn file_name_as_string(&self) -> Result<String>;\n\n fn get_directory_as_string(&self) -> Result<String>;\n\n fn get_directory(&self) -> PathBuf;\n\n fn create_directory(&self) -> Result<PathBuf>;\n\n fn change_extension(&self, new_extension: &str) -> Result<PathBuf>;\n\n}\n\n\n\nimpl PathExtensions for Path {\n\n\n\n fn get_as_string(&self) -> Result<String> {\n\n Ok(self.to_str()\n\n .or_error(\"The Path cannot be converted to &str because it is not valid.\")?\n\n .to_string())\n\n }\n\n\n\n fn extension_as_string(&self) -> Result<String> {\n", "file_path": "src/global/extensions.rs", "rank": 37, "score": 65706.52967657527 }, { "content": "#[allow(unused)]\n\npub fn app_start_time() -> &'static DateTime<Utc> {\n\n\n\n &GLOBAL_INSTANCE.app_start_time\n\n}\n\n\n", "file_path": "src/global/mod.rs", "rank": 38, "score": 64329.94419631334 }, { "content": "pub fn backtrace_to_stacktrace(bt: &Backtrace) -> Option<Stacktrace> {\n\n let frames = bt\n\n .frames()\n\n .iter()\n\n .flat_map(|frame| {\n\n // For each frame, there may be multiple symbols if a function was inlined, so\n\n // add an entry for each symbol.\n\n let symbols = frame.symbols();\n\n symbols\n\n .iter()\n\n .map(move |sym| {\n\n let abs_path = sym.filename().map(|m| m.to_string_lossy().to_string());\n\n let filename = abs_path.as_ref().map(|p| filename(p));\n\n let real_symbol = sym.name().map_or(\"<unknown>\".into(), |n| n.to_string());\n\n let symbol = strip_symbol(&real_symbol);\n\n let function = demangle_symbol(symbol);\n\n Frame {\n\n symbol: if symbol != function {\n\n Some(symbol.into())\n\n } else {\n", "file_path": "src/global/sentry_backtrace.rs", "rank": 39, "score": 62745.07291542104 }, { "content": "pub trait ResultExtensions<T>{\n\n\n\n fn map_result<U, F: FnOnce(&T) -> Result<U>>(self, f: F) -> Result<U>;\n\n}\n\n\n\nimpl<T> ResultExtensions<T> for Result<T> {\n\n\n\n\n\n fn map_result<U, F: FnOnce(&T) -> Result<U>>(self, f: F) -> Result<U> {\n\n match self {\n\n Ok(x) => Ok(f(&x)?),\n\n Err(err) => Err(err),\n\n }\n\n }\n\n\n\n}\n\n\n\n\n", "file_path": "src/global/extensions.rs", "rank": 40, "score": 61579.66337484596 }, { "content": "pub trait ResultExtensionsReplaceError<R> {\n\n\n\n fn replace_error<ErrFunc>(self, err_func: ErrFunc) -> Result<R>\n\n where ErrFunc: FnOnce() -> CustomError;\n\n\n\n fn on_error(self, msg: &str) -> Result<R>;\n\n}\n\n\n\nimpl<R, E> ResultExtensionsReplaceError<R> for std::result::Result<R, E> {\n\n\n\n fn replace_error<ErrFunc>(self, err_func: ErrFunc) -> Result<R>\n\n where ErrFunc: FnOnce() -> CustomError {\n\n match self {\n\n Ok(res) => Ok(res),\n\n Err(_) => Err(err_func())\n\n }\n\n }\n\n\n\n fn on_error(self, msg: &str) -> Result<R> {\n\n\n\n self.replace_error(|| CustomError::from_message(msg))\n\n }\n\n}\n", "file_path": "src/global/errors.rs", "rank": 41, "score": 58114.79978697398 }, { "content": "pub fn error_typename<D: fmt::Debug>(error: D) -> String {\n\n format!(\"{:?}\", error)\n\n .split(&['(', '{'][..])\n\n .next()\n\n .unwrap()\n\n .trim()\n\n .into()\n\n}\n\n\n", "file_path": "src/global/sentry_backtrace.rs", "rank": 42, "score": 57555.5845409992 }, { "content": "pub trait ResultExtensionsCrashOnError<R> {\n\n\n\n fn crash_on_error(self) -> R;\n\n fn crash_on_early_error(self) -> R;\n\n}\n\n\n\nimpl<R> ResultExtensionsCrashOnError<R> for Result<R> {\n\n\n\n fn crash_on_error(self) -> R {\n\n\n\n self.unwrap_or_else(|err| {\n\n handle_fatal_error(&err)\n\n .expect(&format!(\"An error occurred while handling an error. {:#?}\", &err));\n\n\n\n ::std::process::exit(1)\n\n })\n\n }\n\n\n\n // This is called when an error occurs while initializing the global state.\n\n // Using the normal error handler to handle the error causes\n", "file_path": "src/global/error_handler.rs", "rank": 43, "score": 56571.76472808077 }, { "content": "struct ListCommandOptions {\n\n vm_name: String,\n\n}\n\n\n", "file_path": "src/list_snapshot.rs", "rank": 44, "score": 50094.72374721564 }, { "content": "struct CreateCommandOptions {\n\n vm_name: String,\n\n}\n\n\n", "file_path": "src/create_snapshot.rs", "rank": 45, "score": 50094.72374721564 }, { "content": "struct ClearCacheCommandOptions {\n\n vm_name: String,\n\n}\n\n\n", "file_path": "src/clear_cache.rs", "rank": 46, "score": 49071.55898726497 }, { "content": "fn main() {\n\n\n\n global::initialize();\n\n\n\n main_result().crash_on_error();\n\n}\n\n\n", "file_path": "src/main.rs", "rank": 47, "score": 42961.99595490981 }, { "content": "pub trait StringExtensions {\n\n fn last_index_of(self, c: char) -> Option<usize>;\n\n fn pad_left(self, pad: usize, c: char) -> String;\n\n fn pad_right(self, pad: usize, c: char) -> String;\n\n}\n\n\n\nimpl StringExtensions for &str {\n\n\n\n fn last_index_of(self, c: char) -> Option<usize> {\n\n\n\n let mut i = self.len() - 1;\n\n\n\n for x in self.chars().rev() {\n\n\n\n if x == c {\n\n return Some(i);\n\n }\n\n\n\n if i > 0 {\n\n i -= 1;\n", "file_path": "src/global/extensions.rs", "rank": 48, "score": 40699.0379380628 }, { "content": "pub trait OsStringExtensions {\n\n\n\n fn get_as_string(&self) -> Result<String>;\n\n}\n\n\n\nimpl OsStringExtensions for OsStr {\n\n\n\n fn get_as_string(&self) -> Result<String> {\n\n\n\n Ok(self.to_str()\n\n .or_error(\"The OsStr cannot be converted to &str because it is not valid.\")\n\n ?.to_string())\n\n }\n\n}\n\n\n\nimpl OsStringExtensions for OsString {\n\n\n\n fn get_as_string(&self) -> Result<String> {\n\n\n\n Ok(self.to_str()\n\n .or_error(\"The OsStr cannot be converted to &str because it is not valid.\")\n\n ?.to_string())\n\n }\n\n}\n\n\n", "file_path": "src/global/extensions.rs", "rank": 49, "score": 39732.20281911953 }, { "content": "fn set_panic_hook () {\n\n\n\n ::std::panic::set_hook(Box::new(|info| {\n\n\n\n let backtrace = backtrace::Backtrace::new();\n\n\n\n let message: &str = match info.payload().downcast_ref::<&'static str>() {\n\n Some(s) => *s,\n\n None => match info.payload().downcast_ref::<String>() {\n\n Some(s) => &**s,\n\n None => \"Box<Any>\",\n\n },\n\n };\n\n\n\n let error = CustomError::from_panic_message(message, backtrace);\n\n\n\n handle_error(&error)\n\n .expect(&format!(\"An error occurred while handling an error from panic. {:#?}\", &error));\n\n }));\n\n}\n\n\n", "file_path": "src/global/mod.rs", "rank": 50, "score": 39537.25354427145 }, { "content": "pub trait OptionExtensions<T> {\n\n fn map<U, F: FnOnce(&T) -> U>(&self, f: F) -> Option<U>;\n\n fn map_result<U, F: FnOnce(&T) -> Result<U>>(&self, f: F) -> Result<Option<U>>;\n\n fn or_error(self, error_message: &str) -> Result<T>;\n\n fn unwrap_or_else_result<F: FnOnce() -> Result<T>>(self, f: F) -> Result<T>;\n\n}\n\n\n\nimpl<T> OptionExtensions<T> for Option<T> {\n\n\n\n fn map<U, F: FnOnce(&T) -> U>(&self, f: F) -> Option<U> {\n\n match self {\n\n Some(x) => Some(f(x)),\n\n None => None,\n\n }\n\n }\n\n\n\n fn map_result<U, F: FnOnce(&T) -> Result<U>>(&self, f: F) -> Result<Option<U>> {\n\n Ok(match self {\n\n Some(x) => Some(f(x)?),\n\n None => None,\n", "file_path": "src/global/extensions.rs", "rank": 51, "score": 38435.77551304432 }, { "content": "pub trait IteratorExtensions: Iterator {\n\n\n\n fn order_by<K, F>(self, f: F) -> ::std::vec::IntoIter<Self::Item>\n\n where Self: Sized, K: Ord, F: FnMut(&Self::Item) -> K {\n\n\n\n let mut vec = self.collect_vec();\n\n vec.sort_by_key(f);\n\n vec.into_iter()\n\n }\n\n\n\n fn order_by_desc<K, F>(self, f: F) -> ::std::vec::IntoIter<Self::Item>\n\n where Self: Sized, K: Ord, F: FnMut(&Self::Item) -> K {\n\n\n\n let mut vec = self.collect_vec();\n\n vec.sort_by_key(f);\n\n vec.reverse();\n\n vec.into_iter()\n\n }\n\n\n\n fn group_by<K, F>(self, f: F) -> ::std::collections::hash_map::IntoIter<K, Vec<Self::Item>>\n", "file_path": "src/global/extensions.rs", "rank": 52, "score": 38435.77551304432 }, { "content": "/// Error wrapper of the global object builder.\n\n/// In case of an error handles it\n\n/// and exits the process with code 1.\n\nfn create_global() -> Global {\n\n\n\n create_global_result()\n\n .crash_on_error()\n\n}\n\n\n", "file_path": "src/global/mod.rs", "rank": 53, "score": 38205.48479321815 }, { "content": "use std::io::{Write};\n\n\n\nuse crate::global::prelude::*;\n\n\n", "file_path": "src/config.rs", "rank": 54, "score": 29978.358873693793 }, { "content": "use std::time::Duration;\n\nuse std::fs::{File, OpenOptions};\n\nuse std::os::unix::io::AsRawFd;\n\n\n\nuse libc::{flock, LOCK_EX, LOCK_NB, EWOULDBLOCK, __errno_location};\n\n\n\nuse super::prelude::*;\n\n\n\n#[allow(unsafe_code)]\n\n#[allow(unused)]\n", "file_path": "src/global/file_lock.rs", "rank": 55, "score": 27345.179650300015 }, { "content": "use serde::{Serialize, Deserialize};\n\n\n\nuse super::prelude::*;\n\nuse std::collections::HashMap;\n\n\n\n#[derive(Serialize, Deserialize, Debug, Clone)]\n\npub struct EmailConfig {\n\n pub notification_emails: Vec<String>,\n\n pub smtp_username: String,\n\n pub smtp_password: String,\n\n pub smtp_host: String,\n\n pub smtp_port: u16,\n\n}\n\n\n\n#[derive(Serialize, Deserialize, Debug, Clone)]\n\npub struct VmConfig {\n\n pub vm_name: String,\n\n pub min_snapshot_count: i32,\n\n}\n\n\n\n#[derive(Serialize, Deserialize, Debug, Clone)]\n\npub struct AppConfig {\n\n pub hostname: String,\n\n pub sentry_dsn: String,\n\n pub email_config: EmailConfig,\n\n pub snapshot_config: Option<HashMap<String, VmConfig>>,\n\n}\n\n\n\n\n", "file_path": "src/global/app_config.rs", "rank": 56, "score": 27185.710700726613 }, { "content": "\n\nuse self::prelude::*;\n\nuse self::app_config::{AppConfig, read_config};\n\nuse self::custom_sentry_client::CustomSentryClient;\n\nuse self::error_handler::handle_error;\n\nuse self::logging::*;\n\nuse self::cli::CliRunner;\n\n\n\nstatic APP_CONFIG_FILE_NAME: &str = \"app-config.json\";\n\nstatic LOG_FILE_NAME: &str = \"log/log.txt\";\n\nstatic LOG_FILE_MAX_LENGTH: u64 = 1024000; // 10MB\n\n\n\n/// The global object struct.\n\npub struct Global {\n\n pub app_config: AppConfig,\n\n pub sentry: CustomSentryClient,\n\n pub logger: Logger,\n\n pub config_directory: PathBuf,\n\n pub app_start_time: DateTime<Utc>,\n\n pub cli: CliRunner,\n\n}\n\n\n\n/// Error wrapper of the global object builder.\n\n/// In case of an error handles it\n\n/// and exits the process with code 1.\n", "file_path": "src/global/mod.rs", "rank": 65, "score": 16.354686113187583 }, { "content": "\n\n let log_file_path = config_directory.join(LOG_FILE_NAME);\n\n\n\n let logger = Logger::new(LoggingConfiguration {\n\n max_length: LOG_FILE_MAX_LENGTH,\n\n file_path: log_file_path\n\n })?;\n\n\n\n Ok(Global {\n\n app_config,\n\n sentry,\n\n logger,\n\n config_directory,\n\n app_start_time: Utc::now(),\n\n cli: CliRunner::new()\n\n })\n\n}\n\n\n\nlazy_static! {\n\n\n\n /// The hidden instance reference.\n\n static ref GLOBAL_INSTANCE: Global = create_global();\n\n}\n\n\n", "file_path": "src/global/mod.rs", "rank": 66, "score": 15.76788398372894 }, { "content": " let buff = BufReader::new(stdout);\n\n\n\n let mut result = String::new();\n\n\n\n for line_result in buff.lines() {\n\n\n\n let line = line_result?;\n\n result.push_str(&format!(\"{}\\n\", line));\n\n\n\n if log_output {\n\n logger().log(&format!(\"OUT | {}\", line))?;\n\n }\n\n }\n\n\n\n Ok(result)\n\n });\n\n\n\n let stderr_thread : JoinHandle<Result<String>> = thread::spawn(move || {\n\n\n\n let buff = BufReader::new(stderr);\n", "file_path": "src/global/bash_shell.rs", "rank": 67, "score": 15.70883912304689 }, { "content": " let copy = self.to_path_buf();\n\n\n\n ::std::fs::create_dir_all(copy.get_as_string()?)?;\n\n\n\n Ok(copy)\n\n }\n\n\n\n fn change_extension(&self, new_extension: &str) -> Result<PathBuf> {\n\n\n\n let mut directory = self.get_directory();\n\n\n\n let file_stem = self.file_stem_as_string()?;\n\n\n\n directory.push(format!(\"{}.{}\", &file_stem, new_extension));\n\n\n\n Ok(directory)\n\n }\n\n}\n\n\n", "file_path": "src/global/extensions.rs", "rank": 68, "score": 14.901127137245837 }, { "content": "\n\npub struct EmailMessage {\n\n to_addresses: Vec<String>,\n\n content: String,\n\n subject: String,\n\n}\n\n\n\nimpl EmailMessage {\n\n\n\n pub fn new(to_address: Vec<String>,\n\n subject: &str,\n\n content: &str,\n\n ) -> EmailMessage {\n\n EmailMessage {\n\n to_addresses: to_address,\n\n content: content.to_string(),\n\n subject: subject.to_string(),\n\n }\n\n }\n\n}\n", "file_path": "src/global/email.rs", "rank": 70, "score": 13.86247789247102 }, { "content": "\n\n let mut result = String::new();\n\n\n\n for line_result in buff.lines() {\n\n\n\n let line = line_result?;\n\n result.push_str(&format!(\"{}\\n\", line));\n\n\n\n if log_output {\n\n logger().log(&format!(\"ERR | {}\", line))?;\n\n }\n\n }\n\n\n\n Ok(result)\n\n });\n\n\n\n stdin.write_all(\"set -exu\\n\".as_bytes())?;\n\n stdin.write_all(format!(\"{}\\n\", command).as_bytes())?;\n\n stdin.write_all(\"exit $?;\\n\".as_bytes())?;\n\n\n", "file_path": "src/global/bash_shell.rs", "rank": 71, "score": 13.857159194093725 }, { "content": "}\n\n\n\n#[derive(Serialize, Deserialize, Debug)]\n\npub struct CustomSentryClient {\n\n dsn: CustomDsn,\n\n}\n\n\n\nimpl CustomSentryClient {\n\n\n\n pub fn new(dsn_string: &str) -> Result<CustomSentryClient> {\n\n\n\n let dsn = parse_dsn(dsn_string)?;\n\n\n\n Ok(CustomSentryClient {\n\n dsn\n\n })\n\n }\n\n\n\n #[allow(unused)]\n\n pub fn send_message(&self, message: &str) -> Result {\n", "file_path": "src/global/custom_sentry_client.rs", "rank": 72, "score": 13.817204899727527 }, { "content": " result.push_str(self);\n\n\n\n result\n\n }\n\n\n\n fn pad_right(self, pad: usize, c: char) -> String {\n\n\n\n let mut result = String::new();\n\n\n\n let len = self.len();\n\n\n\n result.push_str(self);\n\n\n\n if pad > len {\n\n\n\n for _ in 0..pad-len {\n\n\n\n result.push(c);\n\n }\n\n }\n", "file_path": "src/global/extensions.rs", "rank": 73, "score": 13.453748242684611 }, { "content": " for item in self {\n\n\n\n if f(&item)? {\n\n return Ok(true);\n\n }\n\n }\n\n\n\n Ok(false)\n\n }\n\n\n\n fn map_result<K, F>(self, f: F) -> Result<::std::vec::IntoIter<K>>\n\n where Self: Sized, F: Fn(&Self::Item) -> Result<K> {\n\n\n\n let source = self.collect_vec();\n\n\n\n let mut destination = Vec::new();\n\n\n\n for item in source {\n\n\n\n destination.push(f(&item)?);\n", "file_path": "src/global/extensions.rs", "rank": 74, "score": 12.88429298451174 }, { "content": "use super::prelude::*;\n\n\n\npub struct FinStruct<TRes> {\n\n result: Result<TRes>\n\n}\n\n\n\nimpl<TRes> FinStruct<TRes> {\n\n\n\n #[allow(unused)]\n\n pub fn finally<FFinally>(self, ff: FFinally) -> Result<TRes>\n\n where FFinally : FnOnce() -> Result {\n\n\n\n let finally_result = ff();\n\n\n\n match self.result {\n\n Err(err) => Err(err),\n\n Ok(res) => {\n\n if let Err(finally_err) = finally_result {\n\n Err(finally_err)\n\n } else {\n\n Ok(res)\n\n }\n\n }\n\n }\n\n }\n\n}\n\n\n\n#[allow(unused)]\n", "file_path": "src/global/do_try.rs", "rank": 75, "score": 12.801395929275893 }, { "content": "\n\n pub fn command_config<F>(&self, f: F) -> ArgMatches\n\n where F: for<'a, 'b> FnOnce(App<'a, 'b>) -> App<'a, 'b> {\n\n\n\n let mut matches = App::new(format!(\"XDXD Snapshot Rotator\"))\n\n .version(env!(\"CARGO_PKG_VERSION\"))\n\n .author(\"Hristo Kolev\")\n\n .about(\"Rotates snapshot.\");\n\n\n\n matches = f(matches);\n\n\n\n let mut i = 0;\n\n let args = ::std::env::args_os().filter(|_| {\n\n\n\n let result = i != 1;\n\n\n\n i += 1;\n\n\n\n result\n\n }).collect_vec();\n", "file_path": "src/global/cli.rs", "rank": 76, "score": 12.013013842341351 }, { "content": " })\n\n }\n\n\n\n fn or_error(self, msg: &str) -> Result<T> {\n\n\n\n self.ok_or_else(|| CustomError::from_message(msg))\n\n }\n\n\n\n fn unwrap_or_else_result<F: FnOnce() -> Result<T>>(self, f: F) -> Result<T> {\n\n match self {\n\n Some(x) => Ok(x),\n\n None => f(),\n\n }\n\n }\n\n}\n\n\n", "file_path": "src/global/extensions.rs", "rank": 77, "score": 12.008840466944955 }, { "content": "\n\npub use super::error_handler::ResultExtensionsCrashOnError;\n\npub use super::errors::{Result, CustomError, ResultExtensionsReplaceError};\n\npub use super::app_config::{AppConfig, VmConfig};\n\npub use super::app_start_time;\n\npub use super::extensions::*;\n\npub use crate::global::*;", "file_path": "src/global/prelude.rs", "rank": 79, "score": 11.896332824949182 }, { "content": "\n\nimpl CustomError {\n\n pub fn from_message(message: &str) -> CustomError {\n\n CustomError {\n\n kind: ErrorMessage(message.to_string()),\n\n backtrace: Backtrace::new(),\n\n }\n\n }\n\n\n\n pub fn user_error(message: &str) -> CustomError {\n\n CustomError {\n\n kind: UserError(message.to_string()),\n\n backtrace: Backtrace::new(),\n\n }\n\n }\n\n\n\n pub fn from_panic_message(message: &str, backtrace: Backtrace) -> CustomError {\n\n CustomError {\n\n kind: PanicErrorMessage(message.to_string()),\n\n backtrace,\n", "file_path": "src/global/errors.rs", "rank": 80, "score": 11.748740489666332 }, { "content": "use std::sync::Mutex;\n\nuse std::collections::HashMap;\n\n\n\nuse clap::{App, ArgMatches};\n\n\n\nuse crate::global::prelude::*;\n\n\n\npub type CommandFunc = Box<dyn Fn() -> Result + Send + Sync>;\n\n\n\npub struct CliRunner {\n\n pub command_map: Mutex<HashMap<String, CommandFunc>>,\n\n}\n\n\n\nimpl CliRunner {\n\n\n\n pub fn new() -> CliRunner {\n\n CliRunner {\n\n command_map: Mutex::new(HashMap::new())\n\n }\n\n }\n", "file_path": "src/global/cli.rs", "rank": 81, "score": 11.703941023940931 }, { "content": " fn get_directory_as_string(&self) -> Result<String> {\n\n\n\n let mut copy = self.to_path_buf();\n\n\n\n copy.pop();\n\n\n\n copy.get_as_string()\n\n }\n\n\n\n fn get_directory(&self) -> PathBuf {\n\n\n\n let mut copy = self.to_path_buf();\n\n\n\n copy.pop();\n\n\n\n copy\n\n }\n\n\n\n fn create_directory(&self) -> Result<PathBuf> {\n\n\n", "file_path": "src/global/extensions.rs", "rank": 82, "score": 11.419044003394822 }, { "content": "use std::fmt;\n\n\n\nuse backtrace::Backtrace;\n\nuse regex::{Captures, Regex};\n\n\n\nuse sentry::protocol::{Frame, Stacktrace};\n\n\n\nlazy_static::lazy_static! {\n\n\n\n static ref HASH_FUNC_RE: Regex = Regex::new(r#\"(?x)\n\n ^(.*)::h[a-f0-9]{16}$\n\n \"#).unwrap();\n\n\n\n pub static ref WELL_KNOWN_SYS_MODULES: Vec<&'static str> = {\n\n #[allow(unused_mut)]\n\n let mut rv = vec![\n\n \"std::\",\n\n \"core::\",\n\n \"alloc::\",\n\n \"backtrace::\",\n", "file_path": "src/global/sentry_backtrace.rs", "rank": 83, "score": 11.191091070042347 }, { "content": " }\n\n }\n\n\n\n None\n\n }\n\n\n\n fn pad_left(self, pad: usize, c: char) -> String {\n\n\n\n let mut result = String::new();\n\n\n\n let len = self.len();\n\n\n\n if pad > len {\n\n\n\n for _ in 0..pad-len {\n\n\n\n result.push(c);\n\n }\n\n }\n\n\n", "file_path": "src/global/extensions.rs", "rank": 84, "score": 10.74106553255048 }, { "content": " let out_result = stdout_thread.join()\n\n .on_error(\"The stdout thread failed for some reason.\")??;\n\n\n\n let err_result = stderr_thread.join()\n\n .on_error(\"The stderr thread failed for some reason.\")??;\n\n\n\n let exit_status = process.wait()?;\n\n\n\n return Ok(CommandResult {\n\n status_code: exit_status.code(),\n\n success: exit_status.success(),\n\n stdout: out_result,\n\n stderr: err_result,\n\n command: command.to_string()\n\n });\n\n}\n\n\n", "file_path": "src/global/bash_shell.rs", "rank": 85, "score": 10.135925947890101 }, { "content": "use super::prelude::*;\n\n\n\nuse lettre_email::Email;\n\nuse lettre::{SmtpClient, ClientSecurity, Transport};\n\nuse lettre::smtp::authentication::{Credentials, Mechanism};\n\n\n\npub struct EmailClient {\n\n username: String,\n\n password: String,\n\n smtp_host: String,\n\n smtp_port: u16,\n\n}\n\n\n\nimpl EmailClient {\n\n\n\n pub fn new(username: &str,\n\n password: &str,\n\n smtp_host: &str,\n\n smtp_port: u16,\n\n ) -> EmailClient\n", "file_path": "src/global/email.rs", "rank": 86, "score": 10.133462989361748 }, { "content": " pub static ref SECONDARY_BORDER_FRAMES: Vec<(&'static str, &'static str)> = {\n\n #![allow(unused_mut)]\n\n let mut rv = Vec::new();\n\n rv.push((\"error_chain::make_backtrace\", \"<T as core::convert::Into<U>>::into\"));\n\n {rv}\n\n };\n\n\n\n pub static ref COMMON_RUST_SYMBOL_ESCAPES_RE: Regex = Regex::new(r#\"(?x)\n\n \\$\n\n (SP|BP|RF|LT|GT|LP|RP|C|\n\n u7e|u20|u27|u5b|u5d|u7b|u7d|u3b|u2b|u22)\n\n \\$\n\n \"#).unwrap();\n\n}\n\n\n", "file_path": "src/global/sentry_backtrace.rs", "rank": 87, "score": 9.659307216048346 }, { "content": "pub mod app_config;\n\npub mod errors;\n\npub mod extensions;\n\npub mod sentry_backtrace;\n\npub mod custom_sentry_client;\n\npub mod error_handler;\n\npub mod logging;\n\npub mod prelude;\n\n\n\n#[macro_use]\n\npub mod bash_shell;\n\npub mod do_try;\n\npub mod email;\n\npub mod email_report;\n\npub mod cli;\n\npub mod file_lock;\n\n\n\nuse std::path::{PathBuf, Path};\n\nuse chrono::{DateTime, Utc};\n\nuse lazy_static::lazy_static;\n", "file_path": "src/global/mod.rs", "rank": 88, "score": 9.57372428560552 }, { "content": " \"sentry::\",\n\n \"sentry_types::\",\n\n // these are not modules but things like __rust_maybe_catch_panic\n\n \"__rust_\",\n\n \"failure::\",\n\n ];\n\n rv\n\n };\n\n\n\n pub static ref WELL_KNOWN_BORDER_FRAMES: Vec<&'static str> = {\n\n #[allow(unused_mut)]\n\n let mut rv = vec![\n\n \"std::panicking::begin_panic\",\n\n ];\n\n rv.push(\"failure::error_message::err_msg\");\n\n rv.push(\"failure::backtrace::Backtrace::new\");\n\n rv.push(\"error_chain::make_backtrace\");\n\n rv\n\n };\n\n\n", "file_path": "src/global/sentry_backtrace.rs", "rank": 89, "score": 9.521684320718633 }, { "content": " where Self: Sized, K: Eq, K: Hash, F: Fn(&Self::Item) -> K {\n\n\n\n let mut group_map = HashMap::new();\n\n\n\n for item in self {\n\n\n\n let value = group_map\n\n .entry(f(&item))\n\n .or_insert(Vec::new());\n\n\n\n value.push(item);\n\n }\n\n\n\n group_map.into_iter()\n\n }\n\n\n\n fn filter_first<F>(self, f: F) -> Option<Self::Item>\n\n where Self: Sized, Self::Item: Clone, F: Fn(&Self::Item) -> bool {\n\n\n\n let vec = self.filter(f).take(1).collect_vec();\n", "file_path": "src/global/extensions.rs", "rank": 90, "score": 9.221342919093804 }, { "content": "\n\n vec.first().map(|x| x.clone())\n\n }\n\n\n\n fn first(self) -> Option<Self::Item>\n\n where Self: Sized, Self::Item: Clone {\n\n\n\n let vec = self.take(1).collect_vec();\n\n\n\n vec.first().map(|x| x.clone())\n\n }\n\n\n\n fn has_any(&mut self) -> bool {\n\n\n\n self.next().is_some()\n\n }\n\n\n\n fn any_result<F>(self, f: F) -> Result<bool>\n\n where Self: Sized, F: Fn(&Self::Item) -> Result<bool> {\n\n\n", "file_path": "src/global/extensions.rs", "rank": 91, "score": 9.14160441976264 }, { "content": "\n\n let mut event = self.create_event();\n\n event.message = Some(message.to_string());\n\n\n\n self.send_event(&event)?;\n\n\n\n Ok(())\n\n }\n\n\n\n pub fn send_error(&self, error: &CustomError) -> Result {\n\n\n\n let stacktrace = self.get_stacktrace(error)?;\n\n\n\n let mut event = self.create_event();\n\n\n\n let exception = Exception {\n\n value: Some(error.kind.to_string()),\n\n ty: error_typename(&error.kind),\n\n stacktrace,\n\n ..Default::default()\n", "file_path": "src/global/custom_sentry_client.rs", "rank": 92, "score": 9.036883964498116 }, { "content": " Ok(self)\n\n } else {\n\n Err(CustomError::from_message(&format!(\n\n \"A command exited with a non 0 exit code or with a signal. '{}'\",\n\n self.command\n\n )))\n\n }\n\n }\n\n\n\n //noinspection RsSelfConvention\n\n #[allow(unused)]\n\n pub fn as_result_ref(&self) -> Result<&CommandResult> {\n\n if self.success {\n\n Ok(self)\n\n } else {\n\n Err(CustomError::from_message(&format!(\n\n \"A command exited with a non 0 exit code or with a signal. '{}'\",\n\n self.command\n\n )))\n\n }\n", "file_path": "src/global/bash_shell.rs", "rank": 93, "score": 8.82464583653799 }, { "content": "use std::path::{Path, PathBuf};\n\nuse std::ffi::{OsStr, OsString};\n\nuse std::collections::HashMap;\n\nuse std::hash::Hash;\n\n\n\nuse super::prelude::*;\n\n\n", "file_path": "src/global/extensions.rs", "rank": 94, "score": 8.688753851055015 }, { "content": "\n\n matches.get_matches_from(args)\n\n }\n\n\n\n pub fn register_command(&self, command_name: &str, func: CommandFunc) -> Result {\n\n\n\n let mut map = self.command_map.lock()?;\n\n\n\n map.insert(command_name.to_string(), func);\n\n\n\n Ok(())\n\n }\n\n\n\n pub fn run(&self) -> Result {\n\n\n\n let command_map = self.command_map.lock()?;\n\n\n\n let available_commands = command_map.iter()\n\n .map(|(key, _val)| key.to_string())\n\n .order_by(|x| x.to_string())\n", "file_path": "src/global/cli.rs", "rank": 95, "score": 8.675889974158359 }, { "content": " {\n\n EmailClient {\n\n username: username.to_string(),\n\n password: password.to_string(),\n\n smtp_host: smtp_host.to_string(),\n\n smtp_port,\n\n }\n\n }\n\n\n\n pub fn send(self, message: &EmailMessage) -> Result {\n\n\n\n let address = (&*self.smtp_host, self.smtp_port);\n\n\n\n let credentials = Credentials::new(\n\n self.username.clone(),\n\n self.password.clone()\n\n );\n\n\n\n let mut smtp_client = SmtpClient::new(address,ClientSecurity::None)?\n\n .credentials(credentials)\n", "file_path": "src/global/email.rs", "rank": 96, "score": 8.606661533373764 }, { "content": "use serde_json::json;\n\nuse handlebars::Handlebars;\n\n\n\nuse super::email;\n\nuse super::prelude::*;\n\nuse crate::global::logger;\n\nuse crate::global::app_config::VmConfig;\n\n\n", "file_path": "src/global/email_report.rs", "rank": 97, "score": 8.535936022300186 }, { "content": "\n\nimpl From<roxmltree::Error> for CustomError {\n\n fn from(err: roxmltree::Error) -> Self {\n\n CustomError {\n\n kind: XmlError(err),\n\n backtrace: Backtrace::new(),\n\n }\n\n }\n\n}\n\n\n\npub type Result<T = ()> = ::std::result::Result<T, CustomError>;\n\n\n", "file_path": "src/global/errors.rs", "rank": 98, "score": 8.512171846373175 }, { "content": " HandlebarsError(handlebars::TemplateRenderError),\n\n UserError(String),\n\n XmlError(roxmltree::Error),\n\n SendErrorFile(std::sync::mpsc::SendError<std::fs::File>),\n\n RecvError(std::sync::mpsc::RecvError),\n\n}\n\n\n\n#[derive(Debug)]\n\npub struct CustomError {\n\n pub kind: CustomErrorKind,\n\n pub backtrace: Backtrace,\n\n}\n\n\n\nimpl fmt::Debug for CustomErrorKind {\n\n fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {\n\n match self {\n\n ErrorMessage(err) => return err.fmt(f),\n\n PanicErrorMessage(err) => return err.fmt(f),\n\n IoError(err) => return err.fmt(f),\n\n JsonError(err) => return err.fmt(f),\n", "file_path": "src/global/errors.rs", "rank": 99, "score": 8.47954530475387 } ]
Rust
crates/components/token/erc20/tests/mocks/erc20_mock.rs
zl910627/metis
b38193188614f9bd8391a6afed1a876495d0a771
#![cfg_attr(not(feature = "std"), no_std)] #[metis_lang::contract] pub mod erc20_contract { use super::super::behavior; pub use erc20::{ Error, Result, }; use metis_erc20 as erc20; use metis_lang::{ import, metis, }; #[ink(storage)] #[import(erc20)] pub struct Erc20 { erc20: erc20::Data<Erc20>, } #[cfg(not(feature = "ink-as-dependency"))] impl erc20::Impl<Erc20> for Erc20 {} type Event = <Erc20 as ink_lang::BaseEvent>::Type; #[ink(event)] #[metis(erc20)] pub struct Transfer { #[ink(topic)] pub from: Option<AccountId>, #[ink(topic)] pub to: Option<AccountId>, pub value: Balance, } #[ink(event)] #[metis(erc20)] pub struct Approval { #[ink(topic)] pub owner: AccountId, #[ink(topic)] pub spender: AccountId, pub value: Balance, } impl behavior::IERC20New<Erc20> for Erc20 { fn new_erc20( name: String, symbol: String, decimals: u8, initial_supply: Balance, ) -> Self { Self::new(name, symbol, decimals, initial_supply) } fn next_call_by(account: AccountId) { let callee = ink_env::account_id::<ink_env::DefaultEnvironment>() .unwrap_or([0x0; 32].into()); let mut data = ink_env::test::CallData::new(ink_env::call::Selector::new([0x00; 4])); data.push_arg(&account.clone()); ink_env::test::push_execution_context::<ink_env::DefaultEnvironment>( account.clone(), callee, 1000000, 1000000, data, ); } } impl behavior::IERC20Event<Erc20> for Erc20 { fn decode_transfer_event( event: &ink_env::test::EmittedEvent, ) -> (Option<AccountId>, Option<AccountId>, Balance) { let decoded_event = <Event as scale::Decode>::decode(&mut &event.data[..]) .expect("encountered invalid contract event data buffer"); if let Event::Transfer(Transfer { from, to, value }) = decoded_event { return (from, to, value) } panic!("encountered unexpected event kind: expected a Transfer event") } fn decode_approval_event( event: &ink_env::test::EmittedEvent, ) -> (AccountId, AccountId, Balance) { let decoded_event = <Event as scale::Decode>::decode(&mut &event.data[..]) .expect("encountered invalid contract event data buffer"); if let Event::Approval(Approval { owner, spender, value, }) = decoded_event { return (owner, spender, value) } panic!("encountered unexpected event kind: expected a Transfer event") } fn assert_topics( event: &ink_env::test::EmittedEvent, expected_topics: &Vec<Hash>, ) { for (n, (actual_topic, expected_topic)) in event.topics.iter().zip(expected_topics).enumerate() { let topic = actual_topic .decode::<Hash>() .expect("encountered invalid topic encoding"); assert_eq!(topic, *expected_topic, "encountered invalid topic at {}", n); } } } impl Erc20 { #[ink(constructor)] pub fn new( name: String, symbol: String, decimals: u8, initial_supply: Balance, ) -> Self { let mut instance = Self { erc20: erc20::Data::new(), }; erc20::Impl::init(&mut instance, name, symbol, decimals, initial_supply); instance } #[ink(message)] pub fn name(&self) -> String { erc20::Impl::name(self) } #[ink(message)] pub fn symbol(&self) -> String { erc20::Impl::symbol(self) } #[ink(message)] pub fn decimals(&self) -> u8 { erc20::Impl::decimals(self) } #[ink(message)] pub fn total_supply(&self) -> Balance { erc20::Impl::total_supply(self) } #[ink(message)] pub fn balance_of(&self, owner: AccountId) -> Balance { erc20::Impl::balance_of(self, owner) } #[ink(message)] pub fn allowance(&self, owner: AccountId, spender: AccountId) -> Balance { erc20::Impl::allowance(self, owner, spender) } #[ink(message)] pub fn transfer(&mut self, to: AccountId, value: Balance) -> Result<()> { erc20::Impl::transfer(self, to, value) } #[ink(message)] pub fn approve(&mut self, spender: AccountId, value: Balance) -> Result<()> { erc20::Impl::approve(self, spender, value) } #[ink(message)] pub fn transfer_from( &mut self, from: AccountId, to: AccountId, value: Balance, ) -> Result<()> { erc20::Impl::transfer_from(self, from, to, value) } #[ink(message)] pub fn mint(&mut self, to: AccountId, value: Balance) -> Result<()> { erc20::Impl::_mint(self, to, value) } #[ink(message)] pub fn burn(&mut self, to: AccountId, value: Balance) -> Result<()> { erc20::Impl::_burn(self, to, value) } #[ink(message)] pub fn transfer_internal( &mut self, from: AccountId, to: AccountId, value: Balance, ) -> Result<()> { erc20::Impl::_transfer_from_to(self, from, to, value) } #[ink(message)] pub fn approve_internal( &mut self, owner: AccountId, spender: AccountId, value: Balance, ) -> Result<()> { erc20::Impl::_approve(self, owner, spender, value) } } }
#![cfg_attr(not(feature = "std"), no_std)] #[metis_lang::contract] pub mod erc20_contract { use super::super::behavior; pub use erc20::{ Error, Result, }; use metis_erc20 as erc20; use metis_lang::{ import, metis, }; #[ink(storage)] #[import(erc20)] pub struct Erc20 { erc20: erc20::Data<Erc20>, } #[cfg(not(feature = "ink-as-dependency"))] impl erc20::Impl<Erc20> for Erc20 {} type Event = <Erc20 as ink_lang::BaseEvent>::Type; #[ink(event)] #[metis(erc20)] pub struct Transfer { #[ink(topic)] pub from: Option<AccountId>, #[ink(topic)] pub to: Option<AccountId>, pub value: Balance, } #[ink(event)] #[metis(erc20)] pub struct Approval { #[ink(topic)] pub owner: AccountId, #[ink(topic)] pub spender: AccountId, pub value: Balance, } impl behavior::IERC20New<Erc20> for Erc20 { fn new_erc20( name: String, symbol: String, decimals: u8, initial_supply: Balance, ) -> Self { Self::new(name, symbol, decimals, initial_supply) } fn next_call_by(account: AccountId) { let callee = ink_env::account_id::<ink_env::DefaultEnvironment>() .unwrap_or([0x0; 32].into()); let mut data = ink_env::test::CallData::new(ink_env::call::Selector::new([0x00; 4])); data.push_arg(&account.clone()); ink_env::test::push_execution_context::<ink_env::DefaultEnvironment>( account.clone(), callee, 1000000, 1000000, data, ); } } impl behavior::IERC20Event<Erc20> for Erc20 { fn decode_transfer_event( event: &ink_env::test::EmittedEvent, ) -> (Option<AccountId>, Option<AccountId>, Balance) { let decoded_event = <Event as scale::Decode>::decode(&mut &event.data[..]) .expect("encountered invalid contract event data buffer"); if let Event::Transfer(Transfer { from, to, value }) = decoded_event { return (from, to, value) } panic!("encountered unexpected event kind: expected a Transfer event") } fn decode_approval_event( event: &ink_env::test::EmittedEvent, ) -> (AccountId, AccountId, Balance) { let decoded_event = <Event as scale::Decode>::decode(&mut &event.data[..]) .expect("encountered invalid contract event data buffer"); if let Event::Approval(Approval { owner, spender, value, }) = decoded_event { return (owner, spender, value) } panic!("encountered unexpected event kind: expected a Transfer event") } fn assert_topics( event: &ink_env::test::EmittedEvent, expected_topics: &Vec<Hash>, ) { for (n, (actual_topic, expected_topic)) in event.topics.iter().zip(expected_topics).enumerate() { let topic = actual_topic .decode::<Hash>() .expect("encountered invalid topic encoding"); assert_eq!(topic, *expected_topic, "encountered invalid topic at {}", n); } } } impl Erc20 { #[ink(constructor)] pub fn new( name: String, symbol: String, decimals: u8, initial_supply: Balance, ) -> Self { let mut instance = Self { erc20: erc20::Data::new(), }; erc20::Impl::init(&mut instance, name, symbol, decimals, initial_supply); instance } #[ink(message)] pub fn name(&self) -> String { erc20::Impl::name(self) } #[ink(message)] pub fn symbol(&self) -> String { erc20::Impl::symbol(self) } #[ink(message)] pub fn decimals(&self) -> u8 { erc20::Impl::decimals(self) } #[ink(message)] pub fn total_supply(&self) -> Balance { erc20::Impl::total_supply(self) } #[ink(message)] pub fn balance_of(&self, owner: AccountId) -> Balance { erc20::Impl::balance_of(self, owner) } #[ink(message)] pub fn allowance(&self, owner: AccountId, spender: AccountId) -> Balance { erc20::Impl::allowance(self, owner, spender) } #[ink(message)] pub fn transfer(&mut self, to: AccountId, value: Balance) -> Result<()> { erc20::Impl::transfer(self, to, value) } #[ink(message)] pub fn approve(&mut self, spender: AccountId, value: Balance) -> Result<()> { erc20::Impl::approve(self, spender, value) } #[ink(message)] pub fn transfer_from( &mut self, from: AccountId, to: AccountId, value: Balance, ) -> Result<()> { erc20::Impl::transfer_from(self, from, to, value) } #[ink(message)] pub fn mint(&mut self, to: AccountId, value: Balance) -> Result<()> { erc20::Impl::_mint(self, to, value) } #[ink(message)] pub fn burn(&mut self, to: AccountId, value: Balance) -> Result<()> { erc20::Impl::_burn(self, to, value) } #[ink(message)] pub fn transfer_internal( &mut self, from: AccountI
#[ink(message)] pub fn approve_internal( &mut self, owner: AccountId, spender: AccountId, value: Balance, ) -> Result<()> { erc20::Impl::_approve(self, owner, spender, value) } } }
d, to: AccountId, value: Balance, ) -> Result<()> { erc20::Impl::_transfer_from_to(self, from, to, value) }
function_block-function_prefixed
[ { "content": "fn get_storage_mod_type(contract: &Contract, ext_mod: &Ident) -> Result<TokenStream2> {\n\n let storage = contract.module().storage();\n\n let mod_to_get = Some(ext_mod.clone());\n\n\n\n for f in storage.fields() {\n\n if f.ident == mod_to_get {\n\n if let syn::Type::Path(path_fields) = f.ty.clone() {\n\n return Ok(quote! {#path_fields})\n\n }\n\n }\n\n }\n\n\n\n Err(syn::Error::new_spanned(\n\n ext_mod,\n\n \"no found storage mod item which imported\",\n\n ))\n\n}\n", "file_path": "crates/lang/codegen/src/import.rs", "rank": 0, "score": 318034.51179911057 }, { "content": "pub fn generate_code(contract: &Contract) -> Result<TokenStream2> {\n\n let storage = contract.module().storage();\n\n let storage_ident = storage.ident();\n\n let attrs = storage.attrs();\n\n\n\n let import_mods = get_item_attr(attrs, \"import\");\n\n\n\n let import_mods_codes = import_mods.iter().map(|ext_mod| {\n\n generate_import_mod(contract, storage_ident, ext_mod)\n\n .expect(\"no found storage mod item which imported\")\n\n });\n\n\n\n let code = quote! {\n\n #(#import_mods_codes)*\n\n };\n\n\n\n Ok(code)\n\n}\n\n\n", "file_path": "crates/lang/codegen/src/import.rs", "rank": 1, "score": 303370.3368128187 }, { "content": "pub fn generate_code(contract: &Contract, storage_ident: &Ident) -> Result<TokenStream2> {\n\n let mods = contract\n\n .module()\n\n .events()\n\n .filter(|evt| is_metis_item(evt.attrs()))\n\n .flat_map(|evt| {\n\n get_metis_item_attr(evt.attrs())\n\n .iter()\n\n .map(|mod_ident| mod_ident.clone())\n\n .collect::<Vec<_>>()\n\n })\n\n .collect::<Set<_>>();\n\n\n\n let evt2mods = &contract\n\n .module()\n\n .events()\n\n .filter(|evt| is_metis_item(evt.attrs()))\n\n .flat_map(|evt| {\n\n get_metis_item_attr(evt.attrs())\n\n .iter()\n", "file_path": "crates/lang/codegen/src/event.rs", "rank": 2, "score": 283201.3406854961 }, { "content": "/// The `Impl` define erc20 component impl funcs, with `_before_token_transfer` as hook\n\n/// To use erc20 Impl need impl the trait as:\n\n///\n\n/// impl erc20::hookable::Impl<Contract> for Contract {\n\n/// fn _before_token_transfer(\n\n/// &mut self,\n\n/// _from: &AccountId,\n\n/// _to: &AccountId,\n\n/// _amount: Balance,\n\n/// ) -> Result<()> {\n\n/// Ok(())\n\n/// }\n\n/// }\n\npub trait Impl<E: Env>: Storage<E, Data<E>> + EventEmit<E> {\n\n /// Initialize the erc20 component\n\n fn init(\n\n &mut self,\n\n name: String,\n\n symbol: String,\n\n decimals: u8,\n\n initial_supply: E::Balance,\n\n ) {\n\n let caller = Self::caller();\n\n\n\n self.get_mut().set_total_supply(initial_supply);\n\n self.get_mut().set_balance(caller.clone(), initial_supply);\n\n self.get_mut().set_symbols(name, symbol, decimals);\n\n\n\n self.emit_event_transfer(None, Some(caller), initial_supply);\n\n }\n\n\n\n /// Hook that is called before any transfer of tokens. This includes\n\n /// minting and burning.\n", "file_path": "crates/components/token/erc20/src/erc20_basic.rs", "rank": 3, "score": 244563.37179393845 }, { "content": "/// Generates `#[cfg(..)]` code to guard against compilation under `ink-as-dependency`.\n\n/// From ink! code\n\npub fn gen_cross_calling_conflict_cfg(contract: &Contract) -> TokenStream2 {\n\n if contract.config().is_compile_as_dependency_enabled() {\n\n return quote! { #[cfg(feature = \"__ink_DO_NOT_COMPILE\")] }\n\n }\n\n quote! { #[cfg(not(feature = \"ink-as-dependency\"))] }\n\n}\n", "file_path": "crates/lang/codegen/src/utils.rs", "rank": 4, "score": 240023.27341944695 }, { "content": "#[allow(dead_code)]\n\npub fn encoded_into_hash<T>(entity: &T) -> Hash\n\nwhere\n\n T: scale::Encode,\n\n{\n\n let mut result = Hash::clear();\n\n let len_result = result.as_ref().len();\n\n let encoded = entity.encode();\n\n let len_encoded = encoded.len();\n\n if len_encoded <= len_result {\n\n result.as_mut()[..len_encoded].copy_from_slice(&encoded);\n\n return result\n\n }\n\n let mut hash_output = <<Blake2x256 as HashOutput>::Type as Default>::default();\n\n <Blake2x256 as CryptoHash>::hash(&encoded, &mut hash_output);\n\n let copy_len = core::cmp::min(hash_output.len(), len_result);\n\n result.as_mut()[0..copy_len].copy_from_slice(&hash_output[0..copy_len]);\n\n result\n\n}\n", "file_path": "crates/components/token/erc20/tests/utils/event.rs", "rank": 5, "score": 236861.5836104483 }, { "content": "#[allow(dead_code)]\n\npub fn assert_emitted_event_len(expected: usize) -> Vec<ink_env::test::EmittedEvent> {\n\n // Transfer event triggered during initial construction.\n\n let emitted_events = ink_env::test::recorded_events().collect::<Vec<_>>();\n\n assert_eq!(expected, emitted_events.len());\n\n emitted_events\n\n}\n\n\n\n/// get_last_emitted_event\n", "file_path": "crates/components/token/erc20/tests/utils/event.rs", "rank": 6, "score": 231230.22869526705 }, { "content": "#[allow(dead_code)]\n\npub fn next_call_by(account: &ink_env::AccountId) {\n\n // Get contract address.\n\n let callee =\n\n ink_env::account_id::<ink_env::DefaultEnvironment>().unwrap_or([0x0; 32].into());\n\n // Create call.\n\n let mut data = ink_env::test::CallData::new(ink_env::call::Selector::new([0x00; 4]));\n\n\n\n data.push_arg(account);\n\n\n\n // Push the new execution context to set from as caller.\n\n ink_env::test::push_execution_context::<ink_env::DefaultEnvironment>(\n\n account.clone(),\n\n callee,\n\n 1000000,\n\n 1000000,\n\n data,\n\n );\n\n}\n", "file_path": "crates/components/token/erc20/tests/utils/env.rs", "rank": 7, "score": 219800.53002361255 }, { "content": "pub fn generate_hash_string_or_err(input: TokenStream2) -> Result<TokenStream2> {\n\n let bytes = blake2b_256_str(input.to_string()); // is \\\"string\\\", should delete \\\"\n\n\n\n // println!(\"{}\", input.to_string());\n\n\n\n let mut segments = Punctuated::new();\n\n bytes.iter().for_each(|item| {\n\n segments.push_value(quote! { #item });\n\n segments.push_punct(<syn::Token![,]>::default());\n\n });\n\n\n\n Ok(quote! { [#segments] })\n\n}\n\n\n", "file_path": "crates/lang/macro/src/utils.rs", "rank": 8, "score": 213722.7296724624 }, { "content": "/// Extension of {ERC20} that adds a cap to the supply of tokens.\n\npub trait Impl<E>: crate::hookable::Impl<E> + Storage<E, Data<E>>\n\nwhere\n\n E: Env,\n\n{\n\n /// Returns the cap on the token's total supply.\n\n fn cap(&self) -> E::Balance {\n\n Storage::<E, Data<E>>::get(self).cap()\n\n }\n\n\n\n /// See {ERC20-_mint}.\n\n fn _mint(&mut self, account: E::AccountId, amount: E::Balance) -> Result<()> {\n\n assert!(\n\n ERC20::total_supply(self) + amount <= self.cap(),\n\n \"ERC20Capped: cap exceeded\"\n\n );\n\n\n\n ERC20::_mint(self, account, amount)\n\n }\n\n}\n", "file_path": "crates/components/token/erc20/src/extensions/capped.rs", "rank": 9, "score": 213609.93578251224 }, { "content": "fn blake2b_256(input: &[u8], output: &mut [u8]) {\n\n use ::blake2::digest::{\n\n Update as _,\n\n VariableOutput as _,\n\n };\n\n let mut blake2 = blake2::VarBlake2b::new_keyed(&[], 32);\n\n blake2.update(input);\n\n blake2.finalize_variable(|result| output.copy_from_slice(result));\n\n}\n\n\n", "file_path": "crates/lang/macro/src/utils.rs", "rank": 10, "score": 210801.50960313505 }, { "content": "pub trait Impl<E>: crate::hookable::Impl<E> + metis_pausable::Impl<E>\n\nwhere\n\n E: Env,\n\n{\n\n}\n\n\n\nimpl<E: Env, I: Impl<E>> crate::hookable::Impl<E> for I {\n\n /// Hook that is called before any transfer of tokens. This includes\n\n /// minting and burning.\n\n ///\n\n /// Calling conditions:\n\n ///\n\n /// - when `from` and `to` are both non-zero, `amount` of ``from``'s tokens\n\n /// will be to transferred to `to`.\n\n /// - when `from` is zero, `amount` tokens will be minted for `to`.\n\n /// - when `to` is zero, `amount` of ``from``'s tokens will be burned.\n\n /// - `from` and `to` are never both zero.\n\n fn before_token_transfer(\n\n &mut self,\n\n _from: &E::AccountId,\n\n _to: &E::AccountId,\n\n _amount: &E::Balance,\n\n ) -> Result<()> {\n\n metis_pausable::Impl::<E>::ensure_not_paused(self);\n\n\n\n Ok(())\n\n }\n\n}\n", "file_path": "crates/components/token/erc20/src/extensions/pausable.rs", "rank": 11, "score": 209477.07551446187 }, { "content": "#[allow(dead_code)]\n\npub fn get_last_emitted_event() -> ink_env::test::EmittedEvent {\n\n // Transfer event triggered during initial construction.\n\n let emitted_events = ink_env::test::recorded_events().collect::<Vec<_>>();\n\n emitted_events[emitted_events.len() - 1].clone()\n\n}\n\n\n\n/// get_last_emitted_event\n", "file_path": "crates/components/token/erc20/tests/utils/event.rs", "rank": 12, "score": 209333.53526276816 }, { "content": "#[allow(dead_code)]\n\npub fn get_emitted_events() -> Vec<ink_env::test::EmittedEvent> {\n\n ink_env::test::recorded_events().collect::<Vec<_>>()\n\n}\n\n\n\n/// For calculating the event topic hash.\n\npub struct PrefixedValue<'a, 'b, T> {\n\n pub prefix: &'a [u8],\n\n pub value: &'b T,\n\n}\n\n\n\nimpl<X> scale::Encode for PrefixedValue<'_, '_, X>\n\nwhere\n\n X: scale::Encode,\n\n{\n\n #[inline]\n\n fn size_hint(&self) -> usize {\n\n self.prefix.size_hint() + self.value.size_hint()\n\n }\n\n\n\n #[inline]\n\n fn encode_to<T: scale::Output + ?Sized>(&self, dest: &mut T) {\n\n self.prefix.encode_to(dest);\n\n self.value.encode_to(dest);\n\n }\n\n}\n\n\n", "file_path": "crates/components/token/erc20/tests/utils/event.rs", "rank": 13, "score": 206594.22311621727 }, { "content": "pub trait Impl<E>: access_control::Impl<E> + EventEmit<E> + Storage<E, Data<E>>\n\nwhere\n\n E: Env,\n\n{\n\n /// initial the state of contract\n\n fn init(\n\n &mut self,\n\n min_delay: E::Timestamp,\n\n proposers: Vec<E::AccountId>,\n\n executors: Vec<E::AccountId>,\n\n ) {\n\n access_control::Impl::_set_role_admin(\n\n self,\n\n TIMELOCK_ADMIN_ROLE,\n\n TIMELOCK_ADMIN_ROLE,\n\n );\n\n access_control::Impl::_set_role_admin(self, PROPOSER_ROLE, TIMELOCK_ADMIN_ROLE);\n\n access_control::Impl::_set_role_admin(self, EXECUTOR_ROLE, TIMELOCK_ADMIN_ROLE);\n\n\n\n // deployer + self administration\n", "file_path": "crates/components/governance/timelock-controller/src/lib.rs", "rank": 14, "score": 205328.86337026977 }, { "content": "/// The `Impl` define ownable component impl funcs\n\npub trait Impl<E: Env>: Storage<E, Data> + EventEmit<E> {\n\n /// init Initializes the contract setting\n\n fn init(&mut self) {}\n\n\n\n /// Pause the contract, will emit the Paused Event\n\n ///\n\n /// Requirements:\n\n ///\n\n /// - The contract must be not paused.\n\n fn _pause(&mut self) {\n\n self.ensure_not_paused();\n\n self.get_mut().pause();\n\n self.emit_event_paused(Self::caller());\n\n }\n\n\n\n /// Unpause the contract, will emit the `Unpaused` Event\n\n ///\n\n /// Requirements:\n\n ///\n\n /// - The contract must be paused.\n", "file_path": "crates/components/security/pausable/src/lib.rs", "rank": 15, "score": 204456.72299818063 }, { "content": "pub fn generate_or_err(attr: TokenStream2, input: TokenStream2) -> Result<TokenStream2> {\n\n generate_code(attr, input)\n\n}\n", "file_path": "crates/lang/macro/src/contract.rs", "rank": 16, "score": 202570.36869904152 }, { "content": "/// The `Impl` define erc721-receiver component impl funcs\n\npub trait Impl<E: Env>: EventEmit<E> + Storage<E, Data> {\n\n /// init Initializes the contract setting the deployer as the initial owner.\n\n fn init(&mut self) {}\n\n\n\n fn on_erc721_received(\n\n &mut self,\n\n operator: E::AccountId,\n\n from: E::AccountId,\n\n token_id: TokenId,\n\n data: Vec<u8>,\n\n ) -> [u8; 4] {\n\n Self::emit_event_erc_721_received(self, operator, from, token_id, data);\n\n\n\n metis_lang::selector_id!(on_erc721_received)\n\n }\n\n}\n\n\n\nimpl<E: Env, T: EventEmit<E> + Storage<E, Data>> Impl<E> for T {}\n", "file_path": "crates/components/token/receiver/erc721/src/lib.rs", "rank": 17, "score": 201776.3138916948 }, { "content": "/// The `Impl` define erc721-receiver component impl funcs\n\npub trait Impl<E: Env>: EventEmit<E> + Storage<E, Data> {\n\n /// init Initializes the contract setting the deployer as the initial owner.\n\n fn init(&mut self) {}\n\n\n\n fn on_erc1155_received(\n\n &mut self,\n\n operator: E::AccountId,\n\n from: Option<E::AccountId>,\n\n id: TokenId,\n\n value: E::Balance,\n\n data: Vec<u8>,\n\n ) -> [u8; 4] {\n\n Self::emit_event_erc_1155_received(\n\n self,\n\n operator,\n\n from,\n\n vec![id],\n\n vec![value],\n\n data,\n\n );\n\n\n\n metis_lang::selector_id!(on_erc1155_received)\n\n }\n\n}\n\n\n\nimpl<E: Env, T: EventEmit<E> + Storage<E, Data>> Impl<E> for T {}\n", "file_path": "crates/components/token/receiver/erc1155/src/lib.rs", "rank": 18, "score": 201776.3138916948 }, { "content": "/// The `Impl` define erc20 component impl funcs, with `_before_token_transfer` as hook\n\n/// To use erc20 Impl need impl the trait as:\n\n///\n\n/// impl erc20::hookable::Impl<Contract> for Contract {\n\n/// fn _before_token_transfer(\n\n/// &mut self,\n\n/// _from: &AccountId,\n\n/// _to: &AccountId,\n\n/// _amount: Balance,\n\n/// ) -> Result<()> {\n\n/// Ok(())\n\n/// }\n\n/// }\n\npub trait Impl<E: Env>: Storage<E, Data<E>> + EventEmit<E> {\n\n /// Initialize the erc20 component\n\n fn init(&mut self, name: String, symbol: String) {\n\n self.get_mut().set_symbols(name, symbol);\n\n }\n\n\n\n /// Hook that is called before any token transfer. This includes minting\n\n /// and burning.\n\n ///\n\n /// Calling conditions:\n\n ///\n\n /// - When `from` and `to` are both non-zero, `from`'s `token_id` will be\n\n /// transferred to `to`.\n\n /// - When `from` is zero, `token_id` will be minted for `to`.\n\n /// - When `to` is zero, `from`'s `token_id` will be burned.\n\n /// - `from` and `to` are never both zero.\n\n fn _before_token_transfer(\n\n &mut self,\n\n from: Option<E::AccountId>,\n\n to: Option<E::AccountId>,\n", "file_path": "crates/components/token/erc721/src/basic.rs", "rank": 19, "score": 199165.88871337555 }, { "content": "/// The `Impl` define erc1155 component impl funcs, with `_before_token_transfer` as hook\n\n/// To use erc1155 Impl need impl the trait as:\n\n///\n\n/// impl erc1155::Impl<Contract> for Contract {\n\n/// fn _before_token_transfer(\n\n/// &mut self,\n\n/// _from: &AccountId,\n\n/// _to: &AccountId,\n\n/// _amount: Balance,\n\n/// ) -> Result<()> {\n\n/// Ok(())\n\n/// }\n\n/// }\n\npub trait Impl<E: Env>: Storage<E, Data<E>> + EventEmit<E> {\n\n /// Initialize the erc1155 component\n\n fn init(&mut self, url: String) {\n\n self.get_mut().set_url(url)\n\n }\n\n\n\n /// Returns the URI for token type `id`.\n\n ///\n\n /// This implementation returns the same URI for *all* token types. It relies\n\n /// on the token type ID substitution mechanism\n\n /// https://eips.ethereum.org/EIPS/eip-1155#metadata[defined in the EIP].\n\n ///\n\n /// Clients calling this function must replace the `\\{id\\}` substring with the\n\n /// actual token type ID.\n\n fn url(&self, _id: TokenId) -> String {\n\n self.get().get_url()\n\n }\n\n\n\n /// Returns the amount of tokens of token type `id` owned by `account`.\n\n ///\n", "file_path": "crates/components/token/erc1155/src/basic.rs", "rank": 20, "score": 199160.35931278428 }, { "content": "/// The `Impl` define erc777 component impl funcs, with `_before_token_transfer` as hook\n\npub trait Impl<E: Env>: Storage<E, Data<E>> + EventEmit<E> {\n\n /// Initialize the erc777 component\n\n fn init(\n\n &mut self,\n\n name: String,\n\n symbol: String,\n\n decimals: u8,\n\n initial_supply: E::Balance,\n\n ) {\n\n let caller = &Self::caller();\n\n\n\n self.get_mut().set_total_supply(initial_supply);\n\n self.get_mut().set_balance(caller, initial_supply);\n\n self.get_mut().set_symbols(name, symbol, decimals);\n\n\n\n self.emit_event_transfer(None, Some(caller.clone()), initial_supply);\n\n }\n\n\n\n /// Returns the name of the token.\n\n fn name(&self) -> String {\n", "file_path": "crates/components/token/erc777/src/basic.rs", "rank": 21, "score": 199129.24716264743 }, { "content": "/// The `Impl` define component impl funcs\n\npub trait Impl<E: Env>: Storage<E, Data<E>> + EventEmit<E> {\n\n /// Returns `true` if `account` has been granted `role`.\n\n fn has_role(&self, role: RoleId, account: E::AccountId) -> bool {\n\n self.get().has_role(role, account)\n\n }\n\n\n\n /// @dev Returns the admin role that controls `role`. See {grantRole} and\n\n /// {revokeRole}.\n\n ///\n\n /// To change a role's admin, use {_setRoleAdmin}.\n\n fn get_role_admin(&self, role: RoleId) -> Option<RoleId> {\n\n self.get().admin_roles.get(&role).copied()\n\n }\n\n\n\n /// Panic if `owner` is not an owner\n\n fn ensure_role(&self, role: RoleId, account: E::AccountId) {\n\n assert!(self.has_role(role, account), \"role missing\");\n\n }\n\n\n\n /// Panic if caller is not granted role\n", "file_path": "crates/components/access/control/src/lib.rs", "rank": 22, "score": 199124.50187633286 }, { "content": "/// The `Impl` define ownable component impl funcs\n\npub trait Impl<E: Env>: Storage<E, Data<E>> + EventEmit<E> {\n\n /// init Initializes the contract setting the deployer as the initial owner.\n\n fn init(&mut self) {\n\n self.get_mut().set_ownership(&Some(Self::caller()));\n\n }\n\n\n\n /// Leaves the contract without owner. It will not be possible to call\n\n /// `ensure_xxx` functions anymore. Can only be called by the current owner.\n\n /// NOTE: Renouncing ownership will leave the contract without an owner,\n\n /// thereby removing any functionality that is only available to the owner.\n\n fn renounce_ownership(&mut self) {\n\n self.ensure_caller_is_owner();\n\n\n\n self.emit_event_ownership_transferred(self.get().get_ownership().clone(), None);\n\n\n\n self.get_mut().set_ownership(&None);\n\n }\n\n\n\n /// Transfers ownership of the contract to a new account (`new_owner`).\n\n /// Can only be called by the current owner.\n", "file_path": "crates/components/access/ownable/src/lib.rs", "rank": 23, "score": 199124.4756227851 }, { "content": "fn ext_mod_data_ident(ext_mod: &Ident) -> Ident {\n\n format_ident!(\"{}\", ext_mod)\n\n}\n\n\n", "file_path": "crates/lang/codegen/src/import.rs", "rank": 24, "score": 198111.21058228659 }, { "content": "#[allow(dead_code)]\n\npub fn encoded_into_hash<T>(entity: &T) -> Hash\n\nwhere\n\n T: scale::Encode,\n\n{\n\n let mut result = Hash::clear();\n\n let len_result = result.as_ref().len();\n\n let encoded = entity.encode();\n\n let len_encoded = encoded.len();\n\n if len_encoded <= len_result {\n\n result.as_mut()[..len_encoded].copy_from_slice(&encoded);\n\n return result\n\n }\n\n let mut hash_output = <<Blake2x256 as HashOutput>::Type as Default>::default();\n\n <Blake2x256 as CryptoHash>::hash(&encoded, &mut hash_output);\n\n let copy_len = core::cmp::min(hash_output.len(), len_result);\n\n result.as_mut()[0..copy_len].copy_from_slice(&hash_output[0..copy_len]);\n\n result\n\n}\n", "file_path": "crates/components/token/erc777/tests/utils/event.rs", "rank": 25, "score": 198071.13131279155 }, { "content": "pub fn encoded_into_hash<T>(entity: &T) -> Hash\n\nwhere\n\n T: scale::Encode,\n\n{\n\n let mut result = Hash::clear();\n\n let len_result = result.as_ref().len();\n\n let encoded = entity.encode();\n\n let len_encoded = encoded.len();\n\n if len_encoded <= len_result {\n\n result.as_mut()[..len_encoded].copy_from_slice(&encoded);\n\n return result\n\n }\n\n let mut hash_output = <<Blake2x256 as HashOutput>::Type as Default>::default();\n\n <Blake2x256 as CryptoHash>::hash(&encoded, &mut hash_output);\n\n let copy_len = core::cmp::min(hash_output.len(), len_result);\n\n result.as_mut()[0..copy_len].copy_from_slice(&hash_output[0..copy_len]);\n\n result\n\n}\n", "file_path": "crates/components/access/control/tests/utils/event.rs", "rank": 26, "score": 198071.13131279155 }, { "content": "fn blake2b_256_str(input: String) -> [u8; 32] {\n\n let mut output = [0_u8; 32];\n\n\n\n blake2b_256(&input.into_bytes(), &mut output);\n\n\n\n output\n\n}\n", "file_path": "crates/lang/macro/src/utils.rs", "rank": 27, "score": 197373.49935059273 }, { "content": "/// assert_emitted_event_len check event emitted current len is expected\n\npub fn assert_emitted_event_len(expected: usize) -> Vec<ink_env::test::EmittedEvent> {\n\n // Transfer event triggered during initial construction.\n\n let emitted_events = ink_env::test::recorded_events().collect::<Vec<_>>();\n\n assert_eq!(expected, emitted_events.len());\n\n emitted_events\n\n}\n\n\n\npub struct PrefixedValue<'a, 'b, T> {\n\n pub prefix: &'a [u8],\n\n pub value: &'b T,\n\n}\n\nimpl<X> scale::Encode for PrefixedValue<'_, '_, X>\n\nwhere\n\n X: scale::Encode,\n\n{\n\n #[inline]\n\n fn size_hint(&self) -> usize {\n\n self.prefix.size_hint() + self.value.size_hint()\n\n }\n\n #[inline]\n\n fn encode_to<T: scale::Output + ?Sized>(&self, dest: &mut T) {\n\n self.prefix.encode_to(dest);\n\n self.value.encode_to(dest);\n\n }\n\n}\n\n\n", "file_path": "crates/components/access/control/tests/utils/event.rs", "rank": 28, "score": 196298.87549038554 }, { "content": "#[allow(dead_code)]\n\npub fn assert_emitted_event_len(expected: usize) -> Vec<ink_env::test::EmittedEvent> {\n\n // Transfer event triggered during initial construction.\n\n let emitted_events = ink_env::test::recorded_events().collect::<Vec<_>>();\n\n assert_eq!(expected, emitted_events.len());\n\n emitted_events\n\n}\n\n\n\n/// get_last_emitted_event\n", "file_path": "crates/components/token/erc777/tests/utils/event.rs", "rank": 29, "score": 196288.1773962339 }, { "content": "/// The `Impl` define erc20 component impl funcs\n\n/// To Use this, should impl it:\n\n///\n\n/// impl metis_erc20::default::Impl<Contract> for Contract {}\n\npub trait Impl<E>: super::Impl<E>\n\nwhere\n\n E: Env,\n\n{\n\n}\n\n\n\n// TODO: default impl\n\n\n\n// No impl this for default\n\n// impl<E: Env, T: Storage<E, Data<E>> + EventEmit<E>> ImplBurnable<E> for T {}\n", "file_path": "crates/components/token/erc20/src/erc20.rs", "rank": 30, "score": 193866.76589587552 }, { "content": "#[allow(dead_code)]\n\npub fn is_metis_item_has_attr<'a, I>(attrs: I, expect_attr: &Ident) -> bool\n\nwhere\n\n I: IntoIterator<Item = &'a syn::Attribute>,\n\n{\n\n get_metis_item_attr(attrs)\n\n .iter()\n\n .any(|attr| attr == expect_attr)\n\n}\n\n\n", "file_path": "crates/lang/codegen/src/utils.rs", "rank": 31, "score": 190579.320050472 }, { "content": "/// The `Impl` define ownable component impl funcs\n\npub trait Impl<E: Env>: Storage<E, Data<E>> + EventEmit<E> + Ownable<E> {\n\n /// init Initializes the contract setting the deployer as the initial owner.\n\n fn init(&mut self) {}\n\n\n\n /// Return the deposits of payee\n\n fn deposits_of(&self, payee: &E::AccountId) -> E::Balance {\n\n Storage::<E, Data<E>>::get(self).get(payee)\n\n }\n\n\n\n /// @dev Stores the sent amount as credit to be withdrawn.\n\n /// @param payee The destination address of the funds.\n\n fn deposit(&mut self, payee: E::AccountId) {\n\n self.ensure_caller_is_owner();\n\n\n\n let amount = Self::transferred_balance();\n\n\n\n Storage::<E, Data<E>>::get_mut(self).add(&payee, &amount);\n\n\n\n self.emit_event_deposited(payee, amount);\n\n }\n", "file_path": "crates/components/utils/escrow/src/lib.rs", "rank": 32, "score": 189488.00615668652 }, { "content": "fn generate_event_emit_impl(evt: &Event) -> TokenStream2 {\n\n let span = evt.span();\n\n let ident = evt.ident();\n\n let params_call = evt.fields().map(|evt_field| {\n\n let span = evt_field.span();\n\n let ident = evt_field.ident();\n\n let ty = evt_field.ty();\n\n quote_spanned!(span=>\n\n #ident : #ty\n\n )\n\n });\n\n\n\n let params_evt = evt.fields().map(|evt_field| {\n\n let span = evt_field.span();\n\n let ident = evt_field.ident();\n\n quote_spanned!(span=>\n\n #ident\n\n )\n\n });\n\n\n", "file_path": "crates/lang/codegen/src/event.rs", "rank": 33, "score": 187434.42206523445 }, { "content": "#[allow(dead_code)]\n\npub fn next_call_by(account: &ink_env::AccountId) {\n\n // Get contract address.\n\n let callee =\n\n ink_env::account_id::<ink_env::DefaultEnvironment>().unwrap_or([0x0; 32].into());\n\n // Create call.\n\n let mut data = ink_env::test::CallData::new(ink_env::call::Selector::new([0x00; 4]));\n\n\n\n data.push_arg(account);\n\n\n\n // Push the new execution context to set from as caller.\n\n ink_env::test::push_execution_context::<ink_env::DefaultEnvironment>(\n\n account.clone(),\n\n callee,\n\n 1000000,\n\n 1000000,\n\n data,\n\n );\n\n}\n", "file_path": "crates/components/token/erc777/tests/utils/env.rs", "rank": 34, "score": 181709.2848442995 }, { "content": "pub trait Impl<E>: crate::Impl<E>\n\nwhere\n\n E: Env,\n\n{\n\n /// Hook that is called before any transfer of tokens. This will call in hook\n\n fn before_token_transfer(\n\n &mut self,\n\n from: &E::AccountId,\n\n to: &E::AccountId,\n\n amount: &E::Balance,\n\n ) -> Result<()>;\n\n}\n\n\n\nimpl<E: Env, I: Impl<E>> crate::Impl<E> for I {\n\n /// Hook that is called before any transfer of tokens. This includes\n\n /// minting and burning.\n\n ///\n\n /// Calling conditions:\n\n ///\n\n /// - when `from` and `to` are both non-zero, `amount` of ``from``'s tokens\n", "file_path": "crates/components/token/erc20/src/extensions/hookable.rs", "rank": 35, "score": 180451.2529691087 }, { "content": "/// Extension of {ERC20} that adds a cap to the supply of tokens.\n\npub trait Impl<E>: access_control::Impl<E> + Storage<E, Data<E>>\n\nwhere\n\n E: Env,\n\n{\n\n /// Returns one of the accounts that have `role`. `index` must be a\n\n /// value between 0 and {getRoleMemberCount}, non-inclusive.\n\n ///\n\n /// Role bearers are not sorted in any particular way, and their ordering may\n\n /// change at any point.\n\n ///\n\n /// WARNING: When using {getRoleMember} and {getRoleMemberCount}, make sure\n\n /// you perform all queries on the same block. See the following\n\n /// https://forum.openzeppelin.com/t/iterating-over-elements-on-enumerableset-in-openzeppelin-contracts/2296[forum post]\n\n /// for more information.\n\n fn get_role_member(&self, role: &RoleId, index: usize) -> E::AccountId {\n\n match Storage::<E, Data<E>>::get(self).role_members.get(role) {\n\n None => panic!(\"no found role by id\"),\n\n Some(members) => members[index].clone(), // will panic when out of index\n\n }\n\n }\n", "file_path": "crates/components/access/control-enumerable/src/lib.rs", "rank": 36, "score": 179988.31057810524 }, { "content": "// For Events\n\npub trait IERC20Event<E>: IERC20New<E>\n\nwhere\n\n E: Env,\n\n{\n\n fn decode_transfer_event(\n\n event: &ink_env::test::EmittedEvent,\n\n ) -> (Option<E::AccountId>, Option<E::AccountId>, E::Balance);\n\n\n\n fn decode_approval_event(\n\n event: &ink_env::test::EmittedEvent,\n\n ) -> (E::AccountId, E::AccountId, E::Balance);\n\n\n\n fn assert_topics(event: &ink_env::test::EmittedEvent, expected_topics: &Vec<E::Hash>);\n\n\n\n fn encoded_into_hash<T>(entity: &T) -> E::Hash\n\n where\n\n T: scale::Encode,\n\n {\n\n let mut result = E::Hash::clear();\n\n let len_result = result.as_ref().len();\n", "file_path": "crates/components/token/erc20/tests/mocks/behavior.rs", "rank": 37, "score": 178124.13295305526 }, { "content": "/// The `Impl` define ownable component impl funcs\n\npub trait Impl<E: Env>: Storage<E, Data> {\n\n /// is_entered is current is paused\n\n fn _check_nonreentrant(&self) {\n\n assert!(!self.get().is_entered(), \"ReentrancyGuard: reentrant call\");\n\n }\n\n\n\n /// set current status to entered\n\n fn _set_entered(&mut self) {\n\n self.get_mut().set_entered();\n\n }\n\n\n\n /// set current status to not entered\n\n fn _set_not_entered(&mut self) {\n\n self.get_mut().set_not_entered();\n\n }\n\n}\n\n\n\nimpl<E: Env, T: Storage<E, Data>> Impl<E> for T {}\n", "file_path": "crates/components/security/reentrancy-guard/src/lib.rs", "rank": 38, "score": 176446.87318048874 }, { "content": "fn generate_import_mod(\n\n contract: &Contract,\n\n storage_ident: &Ident,\n\n ext_mod: &Ident,\n\n) -> Result<TokenStream2> {\n\n let data_ident = ext_mod_data_ident(ext_mod);\n\n let no_cross_calling_cfg = gen_cross_calling_conflict_cfg(contract);\n\n let ext_mod_data_typ = get_storage_mod_type(contract, ext_mod)?;\n\n\n\n Ok(quote! {\n\n #no_cross_calling_cfg\n\n const _: () = {\n\n use #ext_mod;\n\n\n\n impl metis_lang::Storage<#storage_ident, #ext_mod_data_typ> for #storage_ident {\n\n fn get(&self) -> &#ext_mod_data_typ {\n\n &self.#data_ident\n\n }\n\n fn get_mut(&mut self) -> &mut #ext_mod_data_typ {\n\n &mut self.#data_ident\n\n }\n\n }\n\n };\n\n })\n\n}\n\n\n", "file_path": "crates/lang/codegen/src/import.rs", "rank": 39, "score": 176047.2086570968 }, { "content": "#[proc_macro_attribute]\n\npub fn import(_: TokenStream, item: TokenStream) -> TokenStream {\n\n item\n\n}\n\n\n", "file_path": "crates/lang/macro/src/lib.rs", "rank": 40, "score": 175909.1183961259 }, { "content": "/// Extension of {ERC20} that allows token holders to destroy both their own\n\n/// tokens and those that they have an allowance for, in a way that can be\n\n/// recognized off-chain (via event analysis).\n\npub trait Impl<E>: crate::hookable::Impl<E>\n\nwhere\n\n E: Env,\n\n{\n\n /// Destroys `amount` tokens from the caller.\n\n fn burn(&mut self, amount: E::Balance) -> Result<()> {\n\n self._burn(Self::caller(), amount)\n\n }\n\n\n\n /// Destroys `amount` tokens from `account`, deducting from the caller's\n\n /// allowance.\n\n ///\n\n /// See {ERC20-_burn} and {ERC20-allowance}.\n\n ///\n\n /// Requirements:\n\n ///\n\n /// - the caller must have allowance for ``accounts``'s tokens of at least\n\n /// `amount`.\n\n fn burn_from(&mut self, account: E::AccountId, amount: E::Balance) -> Result<()> {\n\n let caller = Self::caller();\n", "file_path": "crates/components/token/erc20/src/extensions/burnable.rs", "rank": 41, "score": 175884.00857670413 }, { "content": "pub fn generate_msg_selector_id_or_err(input: TokenStream2) -> Result<TokenStream2> {\n\n let output = blake2b_256_str(input.to_string()); // is \\\"string\\\", should delete \\\"\n\n\n\n // println!(\"{}\", input.to_string());\n\n let id = [output[0], output[1], output[2], output[3]];\n\n\n\n let mut segments = Punctuated::new();\n\n id.iter().for_each(|item| {\n\n segments.push_value(quote! { #item });\n\n segments.push_punct(<syn::Token![,]>::default());\n\n });\n\n\n\n Ok(quote! { [#segments] })\n\n}\n\n\n", "file_path": "crates/lang/macro/src/utils.rs", "rank": 42, "score": 173028.91716973184 }, { "content": "#[allow(dead_code)]\n\npub fn get_last_emitted_event() -> ink_env::test::EmittedEvent {\n\n // Transfer event triggered during initial construction.\n\n let emitted_events = ink_env::test::recorded_events().collect::<Vec<_>>();\n\n emitted_events[emitted_events.len() - 1].clone()\n\n}\n\n\n\n/// get_last_emitted_event\n", "file_path": "crates/components/token/erc777/tests/utils/event.rs", "rank": 43, "score": 172567.7153602884 }, { "content": "#[proc_macro_attribute]\n\npub fn contract(attr: TokenStream, item: TokenStream) -> TokenStream {\n\n contract::generate(attr.into(), item.into()).into()\n\n}\n\n\n", "file_path": "crates/lang/macro/src/lib.rs", "rank": 44, "score": 172162.58995248392 }, { "content": " def transfer(self):\n\n supply = self.api.total_supply(self.alice)\n\n self.assertEqual(supply, 1000000 * (10 ** 15))\n\n\n\n res = self.api.transfer(self.alice, self.bob.ss58_address, 10000, gas_limit=default_gas_limit)\n\n self.assertTrue(res.is_success)\n", "file_path": "apis/py/token/erc20/test/test_erc20.py", "rank": 45, "score": 171629.59983882474 }, { "content": " def transfer_from(self):\n\n res = self.api.transfer_from(self.alice,\n\n self.alice.ss58_address, \n\n self.bob.ss58_address, \n\n 10000, gas_limit=default_gas_limit)\n", "file_path": "apis/py/token/erc20/test/test_erc20.py", "rank": 46, "score": 171629.59983882474 }, { "content": "fn main() {}\n", "file_path": "crates/lang/macro/tests/contract/02-flipper-owner-contract.rs", "rank": 47, "score": 171407.5470520755 }, { "content": "pub trait Impl<E>: ERC721<E> + Storage<E, Data>\n\nwhere\n\n E: Env,\n\n{\n\n /// Returns the Uniform Resource Identifier (URI) for `token_id` token.\n\n fn token_url(&self, token_id: &TokenId) -> String {\n\n assert!(\n\n self._exists(token_id),\n\n \"ERC721Metadata: URI query for nonexistent token\"\n\n );\n\n\n\n let token_uri = Storage::<E, Data>::get(self).url_storage.get(token_id);\n\n let base_url = self._base_url().clone();\n\n\n\n // If there is no base URI, return the token URI.\n\n if base_url.len() == 0 {\n\n return token_uri.unwrap_or(&String::from(\"\")).clone()\n\n }\n\n\n\n // If both are set, concatenate the baseURI and tokenURI (via abi.encodePacked).\n", "file_path": "crates/components/token/erc721/src/extensions/urlstorage.rs", "rank": 48, "score": 170948.22048912814 }, { "content": "#[allow(dead_code)]\n\npub fn get_emitted_events() -> Vec<ink_env::test::EmittedEvent> {\n\n ink_env::test::recorded_events().collect::<Vec<_>>()\n\n}\n\n\n\n/// For calculating the event topic hash.\n\npub struct PrefixedValue<'a, 'b, T> {\n\n pub prefix: &'a [u8],\n\n pub value: &'b T,\n\n}\n\n\n\nimpl<X> scale::Encode for PrefixedValue<'_, '_, X>\n\nwhere\n\n X: scale::Encode,\n\n{\n\n #[inline]\n\n fn size_hint(&self) -> usize {\n\n self.prefix.size_hint() + self.value.size_hint()\n\n }\n\n\n\n #[inline]\n\n fn encode_to<T: scale::Output + ?Sized>(&self, dest: &mut T) {\n\n self.prefix.encode_to(dest);\n\n self.value.encode_to(dest);\n\n }\n\n}\n\n\n", "file_path": "crates/components/token/erc777/tests/utils/event.rs", "rank": 49, "score": 169828.4032137375 }, { "content": "pub trait Impl<E>: ERC1155<E> + metis_pausable::Impl<E>\n\nwhere\n\n E: Env,\n\n{\n\n fn _before_token_transfer(\n\n &mut self,\n\n _operator: &E::AccountId,\n\n _from: &Option<&E::AccountId>,\n\n _to: &Option<&E::AccountId>,\n\n _ids: &Vec<TokenId>,\n\n _amounts: &Vec<E::Balance>,\n\n _data: &Vec<u8>,\n\n ) -> Result<()>;\n\n}\n\n\n\nimpl<E, C> ERC1155<E> for C\n\nwhere\n\n C: Impl<E>,\n\n E: Env,\n\n{\n", "file_path": "crates/components/token/erc1155/src/extensions/pausable.rs", "rank": 50, "score": 169730.1498819879 }, { "content": "pub trait Impl<E>: ERC721<E> + metis_pausable::Impl<E>\n\nwhere\n\n E: Env,\n\n{\n\n fn _base_url(&self) -> String;\n\n fn _before_token_transfer(\n\n &mut self,\n\n from: Option<E::AccountId>,\n\n to: Option<E::AccountId>,\n\n token_id: &TokenId,\n\n ) -> Result<()>;\n\n}\n\n\n\nimpl<E, C> ERC721<E> for C\n\nwhere\n\n C: Impl<E>,\n\n E: Env,\n\n{\n\n /// @dev Hook that is called before any token transfer. This includes minting\n\n /// and burning.\n", "file_path": "crates/components/token/erc721/src/extensions/pausable.rs", "rank": 51, "score": 169730.1498819879 }, { "content": " #[ink::trait_definition]\n\n pub trait IErc20 {\n\n /// Creates a new ERC-20 contract with the specified initial supply.\n\n #[ink(constructor)]\n\n fn new(\n\n initial_supply: Balance,\n\n name: Option<String>,\n\n symbol: Option<String>,\n\n decimals: Option<u8>,\n\n ) -> Self;\n\n\n\n /// Returns the token name.\n\n #[ink(message)]\n\n fn token_name(&self) -> Option<String>;\n\n\n\n /// Returns the token symbol.\n\n #[ink(message)]\n\n fn token_symbol(&self) -> Option<String>;\n\n\n\n /// Returns the token decimals.\n\n #[ink(message)]\n", "file_path": "contracts/traits/token/erc20/lib.rs", "rank": 52, "score": 169532.7526784932 }, { "content": "pub fn get_item_attr<'a, I>(attrs: I, name: &str) -> Set<Ident>\n\nwhere\n\n I: IntoIterator<Item = &'a syn::Attribute>,\n\n{\n\n for attr in attrs.into_iter() {\n\n if attr.path.is_ident(name) {\n\n let vars = syn::parse2::<proc_macro2::Group>(attr.tokens.clone())\n\n .expect(\"get key item attr parse err\");\n\n let tags = syn::parse2::<Args>(vars.stream())\n\n .expect(\"get key attr item should be a,b,c\");\n\n\n\n return tags.vars\n\n }\n\n }\n\n\n\n Set::default()\n\n}\n\n\n", "file_path": "crates/lang/codegen/src/utils.rs", "rank": 53, "score": 167059.16427018872 }, { "content": "pub fn generate_code(attr: TokenStream2, input: TokenStream2) -> Result<TokenStream2> {\n\n let item_mod = syn::parse2::<syn::ItemMod>(input.clone())\n\n .expect(\"`#[contract]` marco should use for mod\");\n\n\n\n let contract_ink = Contract::new(attr.clone(), input)?;\n\n let module = contract_ink.module();\n\n let ident = module.ident();\n\n let attrs = module.attrs();\n\n let vis = module.vis();\n\n let storage_ident = module.storage().ident();\n\n\n\n let items = match item_mod.content {\n\n Some((_brace, items)) => items,\n\n None => {\n\n return Err(ink_lang_ir::format_err_spanned!(\n\n item_mod,\n\n \"out-of-line ink! modules are not supported, use `#[ink::contract] mod name {{ ... }}`\",\n\n ))\n\n }\n\n };\n", "file_path": "crates/lang/codegen/src/lib.rs", "rank": 54, "score": 166021.4032205677 }, { "content": "pub fn generate_code(_attr: TokenStream2, input: TokenStream2) -> Result<TokenStream2> {\n\n let typ = syn::parse2::<syn::ItemStruct>(input.clone())?;\n\n let ident = typ.ident.clone();\n\n\n\n Ok(quote! {\n\n #input\n\n\n\n #[cfg(feature = \"ink-as-dependency\")]\n\n const _: () = {\n\n impl metis_lang::Env for #ident {\n\n type AccountId = <::ink_env::DefaultEnvironment as ::ink_env::Environment>::AccountId;\n\n type Balance = <::ink_env::DefaultEnvironment as ::ink_env::Environment>::Balance;\n\n type Hash = <::ink_env::DefaultEnvironment as ::ink_env::Environment>::Hash;\n\n type Timestamp = <::ink_env::DefaultEnvironment as ::ink_env::Environment>::Timestamp;\n\n type BlockNumber = <::ink_env::DefaultEnvironment as ::ink_env::Environment>::BlockNumber;\n\n }\n\n\n\n impl<E> metis_lang::FromAccountId<E> for #ident\n\n where\n\n E: metis_lang::Env,\n", "file_path": "crates/lang/codegen/src/stub.rs", "rank": 55, "score": 166021.4032205677 }, { "content": "pub fn generate_or_err(attr: TokenStream2, input: TokenStream2) -> Result<TokenStream2> {\n\n metis_lang_codegen::stub::generate_code(attr, input)\n\n}\n", "file_path": "crates/lang/macro/src/stub.rs", "rank": 56, "score": 166021.4032205677 }, { "content": "pub fn generate_or_err(attr: TokenStream2, input: TokenStream2) -> Result<TokenStream2> {\n\n metis_lang_codegen::component::erc165::generate_code(attr, input)\n\n}\n", "file_path": "crates/lang/macro/src/erc165.rs", "rank": 57, "score": 166021.4032205677 }, { "content": "pub fn generate_code(attr: TokenStream2, input: TokenStream2) -> Result<TokenStream2> {\n\n // #[metis::supports(interface(new, default), interface(flip, get))]\n\n // attr : interface(new, default), interface(flip, get)\n\n\n\n let params = syn::parse2::<FuncParams>(attr)?;\n\n let impl_codes = generate_supports_message(params)?;\n\n\n\n Ok(quote! {\n\n #input\n\n #impl_codes\n\n })\n\n}\n", "file_path": "crates/lang/codegen/src/components/erc165.rs", "rank": 58, "score": 164081.16216109844 }, { "content": "pub fn generate_or_err(attr: TokenStream2, input: TokenStream2) -> Result<TokenStream2> {\n\n metis_lang_codegen::component::reentrancy_guard::generate_code(attr, input)\n\n}\n", "file_path": "crates/lang/macro/src/reentrancy_guard.rs", "rank": 59, "score": 164081.16216109844 }, { "content": "pub fn is_metis_item<'a, I>(attrs: I) -> bool\n\nwhere\n\n I: IntoIterator<Item = &'a syn::Attribute>,\n\n{\n\n attrs.into_iter().any(|attr| attr.path.is_ident(\"metis\"))\n\n}\n\n\n", "file_path": "crates/lang/codegen/src/utils.rs", "rank": 60, "score": 163868.06914909236 }, { "content": "fn generate_code_for_mod_evts(\n\n contract: &Contract,\n\n storage_ident: &Ident,\n\n mod_ident: &Ident,\n\n evts: &Vec<&Event>,\n\n) -> TokenStream2 {\n\n let no_cross_calling_cfg = gen_cross_calling_conflict_cfg(contract);\n\n let evt_impl_funcs = evts\n\n .iter()\n\n .flat_map(|evt| generate_event_emit_impl(evt))\n\n .collect::<Vec<_>>()\n\n .iter()\n\n .fold(quote! {}, |codes, new| quote! {#codes #new});\n\n\n\n quote! {\n\n #no_cross_calling_cfg\n\n const _: () = {\n\n impl #mod_ident::EventEmit<#storage_ident> for #storage_ident {\n\n #evt_impl_funcs\n\n }\n\n };\n\n }\n\n}\n\n\n", "file_path": "crates/lang/codegen/src/event.rs", "rank": 61, "score": 162285.14026114251 }, { "content": "pub fn generate_code(_attr: TokenStream2, input: TokenStream2) -> Result<TokenStream2> {\n\n let mut msg = syn::parse2::<syn::ItemFn>(input.clone())?;\n\n\n\n let mut codes = gen_enter_codes()?;\n\n let leave_codes = gen_leave_codes()?;\n\n\n\n codes.extend_from_slice(&msg.block.stmts);\n\n codes.extend_from_slice(&leave_codes);\n\n msg.block.stmts = codes;\n\n\n\n Ok(quote! {\n\n #msg\n\n })\n\n}\n", "file_path": "crates/lang/codegen/src/components/reentrancy_guard.rs", "rank": 62, "score": 162206.16366305333 }, { "content": "#[cfg(feature = \"std\")]\n\npub trait Balance:\n\n 'static\n\n + scale::Codec\n\n + std::fmt::Debug\n\n + Copy\n\n + Clone\n\n + PartialEq\n\n + Eq\n\n + AtLeast32BitUnsigned\n\n + Default\n\n + ::scale_info::TypeInfo\n\n + ::ink_storage::traits::StorageLayout\n\n + SpreadLayout\n\n + PackedLayout\n\n + Into<u128>\n\n{\n\n}\n\n\n\n#[cfg(feature = \"std\")]\n\nimpl<T> Balance for T where\n", "file_path": "crates/lang/contract/src/traits.rs", "rank": 63, "score": 160717.5250376951 }, { "content": "pub fn get_metis_item_attr<'a, I>(attrs: I) -> Set<Ident>\n\nwhere\n\n I: IntoIterator<Item = &'a syn::Attribute>,\n\n{\n\n for attr in attrs.into_iter() {\n\n if attr.path.is_ident(\"metis\") {\n\n let vars = syn::parse2::<proc_macro2::Group>(attr.tokens.clone())\n\n .expect(\"metis item attr parse err\");\n\n let tags = syn::parse2::<Args>(vars.stream())\n\n .expect(\"metis attr item should be a,b,c\");\n\n\n\n return tags.vars\n\n }\n\n }\n\n\n\n Set::default()\n\n}\n\n\n", "file_path": "crates/lang/codegen/src/utils.rs", "rank": 64, "score": 154577.53249618816 }, { "content": "#[proc_macro_attribute]\n\npub fn metis(_: TokenStream, item: TokenStream) -> TokenStream {\n\n item\n\n}\n\n\n\n/// The macro to generate _supports_interface for impl erc165\n\n/// Use like\n\n/// #[metis::supports(interface(new, default), interface(flip, get))]\n\n/// impl Flipper {}\n\n/// This will generate this two interface:\n\n/// - Selector(new) ^ Selector(default)\n\n/// - Selector(flip) ^ Selector(get)\n", "file_path": "crates/lang/macro/src/lib.rs", "rank": 65, "score": 154476.24323582792 }, { "content": "pub fn generate(attr: TokenStream2, input: TokenStream2) -> TokenStream2 {\n\n match generate_or_err(attr, input) {\n\n Ok(tokens) => tokens,\n\n Err(err) => err.to_compile_error(),\n\n }\n\n}\n\n\n", "file_path": "crates/lang/macro/src/contract.rs", "rank": 66, "score": 152039.6090285976 }, { "content": "# ERC20 Interface\n\n\n\n## Usage\n\n### Cargo.toml Setting\n\n```\n\n[dependencies]\n\nerc20 = { package = \"erc20\", version = \"0.1.0\", git = \"https://github.com/patractlabs/metis.git\", default-features = false, features = [\"ink-as-dependency\"] }\n\n\n\n[features]\n\ndefault = [\"std\"]\n\nstd = [\n\n \"erc20/std\",\n\n]\n\n```\n\n### Example Contract\n\n```rust\n\n#![cfg_attr(not(feature = \"std\"), no_std)]\n\n\n\nuse ink_lang as ink;\n\n\n\n#[ink::contract]\n\nmod delegate {\n\n use erc20::{\n\n Erc20,\n\n StandardToken,\n\n };\n\n use ink_env::call::FromAccountId;\n\n\n\n #[ink(storage)]\n\n pub struct Delegate {\n\n token: StandardToken,\n\n }\n\n\n\n impl Delegate {\n\n #[ink(constructor)]\n\n pub fn new(contract_account: AccountId) -> Self {\n\n let token: StandardToken = FromAccountId::from_account_id(contract_account);\n\n Self { token }\n\n }\n\n\n\n #[ink(message)]\n\n pub fn call(&self, owner: AccountId) -> Balance {\n\n self.token.balance_of(owner)\n\n }\n\n }\n\n}\n\n```\n", "file_path": "contracts/impls/token/erc20/README.md", "rank": 67, "score": 150717.93155646656 }, { "content": "pub trait _Impl<E>: ERC721<E> + Storage<E, Data<E>>\n\nwhere\n\n E: Env,\n\n{\n\n /// @dev Private function to add a token to this extension's ownership-tracking data structures.\n\n /// @param to address representing the new owner of the given token ID\n\n /// @param token_id uint256 ID of the token to be added to the tokens list of the given address\n\n fn _add_token_to_owner_enumeration(&mut self, to: E::AccountId, token_id: &TokenId) {\n\n let length = ERC721::balance_of(self, &to);\n\n\n\n Storage::<E, Data<E>>::get_mut(self)\n\n .owned_tokens\n\n .insert((to, length), token_id.clone());\n\n Storage::<E, Data<E>>::get_mut(self)\n\n .owned_tokens_index\n\n .insert(token_id.clone(), length);\n\n }\n\n\n\n /// @dev Private function to add a token to this extension's token tracking data structures.\n\n /// @param token_id uint256 ID of the token to be added to the tokens list\n", "file_path": "crates/components/token/erc721/src/extensions/enumerable.rs", "rank": 68, "score": 148382.57502452028 }, { "content": "pub trait IERC20New<E>\n\nwhere\n\n E: Env,\n\n{\n\n fn new_erc20(\n\n name: String,\n\n symbol: String,\n\n decimals: u8,\n\n initial_supply: E::Balance,\n\n ) -> Self;\n\n fn next_call_by(account: E::AccountId);\n\n}\n\n\n", "file_path": "crates/components/token/erc20/tests/mocks/behavior.rs", "rank": 69, "score": 148322.9237891618 }, { "content": "/// The `EventEmit` impl the event emit api for erc20 component.\n\npub trait EventEmit<E: Env>: EnvAccess<E> {\n\n /// Emitted when `value` tokens are moved from one account (`from`) to\n\n /// another (`to`).\n\n ///\n\n /// Note that `value` may be zero.\n\n fn emit_event_transfer(\n\n &mut self,\n\n from: Option<E::AccountId>,\n\n to: Option<E::AccountId>,\n\n value: E::Balance,\n\n );\n\n\n\n /// Emitted when the allowance of a `spender` for an `owner` is set by\n\n /// a call to {approve}. `value` is the new allowance.\n\n fn emit_event_approval(\n\n &mut self,\n\n owner: E::AccountId,\n\n spender: E::AccountId,\n\n value: E::Balance,\n\n );\n\n}\n\n\n", "file_path": "crates/components/token/erc20/src/erc20_basic.rs", "rank": 70, "score": 146185.97962773332 }, { "content": "#[cfg(feature = \"std\")]\n\npub trait AccountId:\n\n EnvAccountId\n\n + Default\n\n + ::scale_info::TypeInfo\n\n + ::ink_storage::traits::StorageLayout\n\n + SpreadLayout\n\n + PackedLayout\n\n{\n\n}\n\n\n\n#[cfg(feature = \"std\")]\n\nimpl<T> AccountId for T where\n\n T: EnvAccountId\n\n + Default\n\n + ::scale_info::TypeInfo\n\n + ::ink_storage::traits::StorageLayout\n\n + SpreadLayout\n\n + PackedLayout\n\n{\n\n}\n\n\n", "file_path": "crates/lang/contract/src/traits.rs", "rank": 71, "score": 142149.53867705053 }, { "content": "pub fn generate_code(\n\n contract: &Contract,\n\n storage_ident: &syn::Ident,\n\n) -> Result<TokenStream2> {\n\n let no_cross_calling_cfg = gen_cross_calling_conflict_cfg(contract);\n\n let env = quote! {\n\n #no_cross_calling_cfg\n\n use ::ink_lang::{EmitEvent, Env, StaticEnv};\n\n\n\n #no_cross_calling_cfg\n\n impl metis_lang::Env for #storage_ident {\n\n type AccountId = <::ink_env::DefaultEnvironment as ::ink_env::Environment>::AccountId;\n\n type Balance = <::ink_env::DefaultEnvironment as ::ink_env::Environment>::Balance;\n\n type Hash = <::ink_env::DefaultEnvironment as ::ink_env::Environment>::Hash;\n\n type Timestamp = <::ink_env::DefaultEnvironment as ::ink_env::Environment>::Timestamp;\n\n type BlockNumber = <::ink_env::DefaultEnvironment as ::ink_env::Environment>::BlockNumber;\n\n }\n\n\n\n #no_cross_calling_cfg\n\n impl metis_lang::EnvAccess<#storage_ident > for #storage_ident {\n", "file_path": "crates/lang/codegen/src/env.rs", "rank": 72, "score": 141809.37376149758 }, { "content": " name: Option<String>,\n\n symbol: Option<String>,\n\n decimals: Option<u8>,\n\n ) -> Self {\n\n let caller = Self::env().caller();\n\n let mut balances = StorageHashMap::new();\n\n balances.insert(caller, initial_supply);\n\n let instance = Self {\n\n total_supply: Lazy::new(initial_supply),\n\n balances,\n\n allowances: StorageHashMap::new(),\n\n name,\n\n symbol,\n\n decimals,\n\n };\n\n Self::env().emit_event(Transfer {\n\n from: None,\n\n to: Some(caller),\n\n value: initial_supply,\n\n });\n", "file_path": "contracts/impls/token/erc20/lib.rs", "rank": 73, "score": 140591.87466738594 }, { "content": "#![cfg_attr(not(feature = \"std\"), no_std)]\n\n\n\npub use self::erc20::Erc20;\n\nuse ink_lang as ink;\n\n\n\n#[ink::contract]\n\nmod erc20 {\n\n use erc20_trait::{Error, IErc20, Result};\n\n use ink_prelude::string::String;\n\n\n\n #[cfg(not(feature = \"ink-as-dependency\"))]\n\n use ink_lang::{EmitEvent, Env};\n\n #[cfg(not(feature = \"ink-as-dependency\"))]\n\n use ink_storage::{collections::HashMap as StorageHashMap, lazy::Lazy};\n\n\n\n // TODO event can't be defined in the contracts which has \"ink-as-dependency\" feature.\n\n /// Event emitted when a token transfer occurs.\n\n #[ink(event)]\n\n pub struct Transfer {\n\n #[ink(topic)]\n", "file_path": "contracts/impls/token/erc20/lib.rs", "rank": 74, "score": 140586.16791746963 }, { "content": " ///\n\n /// Returns `InsufficientBalance` error if there are not enough tokens on\n\n /// the caller's account balance.\n\n #[ink(message)]\n\n fn transfer(&mut self, to: AccountId, value: Balance) -> Result<()> {\n\n let from = self.env().caller();\n\n self.transfer_from_to(from, to, value)\n\n }\n\n\n\n /// Returns the amount which `spender` is still allowed to withdraw from `owner`.\n\n ///\n\n /// Returns `0` if no allowance has been set `0`.\n\n #[ink(message)]\n\n fn allowance(&self, owner: AccountId, spender: AccountId) -> Balance {\n\n self.allowances.get(&(owner, spender)).copied().unwrap_or(0)\n\n }\n\n\n\n /// Transfers `value` tokens on the behalf of `from` to the account `to`.\n\n ///\n\n /// This can be used to allow a contract to transfer tokens on ones behalf and/or\n", "file_path": "contracts/impls/token/erc20/lib.rs", "rank": 75, "score": 140583.03232610144 }, { "content": " pub struct Erc20 {\n\n /// Total token supply.\n\n total_supply: Lazy<Balance>,\n\n /// Mapping from owner to number of owned token.\n\n balances: StorageHashMap<AccountId, Balance>,\n\n /// Mapping of the token amount which an account is allowed to withdraw\n\n /// from another account.\n\n allowances: StorageHashMap<(AccountId, AccountId), Balance>,\n\n /// Name of the token\n\n name: Option<String>,\n\n /// Symbol of the token\n\n symbol: Option<String>,\n\n /// Decimals of the token\n\n decimals: Option<u8>,\n\n }\n\n\n\n impl IErc20 for Erc20 {\n\n #[ink(constructor)]\n\n fn new(\n\n initial_supply: Balance,\n", "file_path": "contracts/impls/token/erc20/lib.rs", "rank": 76, "score": 140580.89080358687 }, { "content": " }\n\n\n\n impl Erc20 {\n\n /// Transfers `value` amount of tokens from the caller's account to account `to`.\n\n ///\n\n /// On success a `Transfer` event is emitted.\n\n ///\n\n /// # Errors\n\n ///\n\n /// Returns `InsufficientBalance` error if there are not enough tokens on\n\n /// the caller's account balance.\n\n fn transfer_from_to(\n\n &mut self,\n\n from: AccountId,\n\n to: AccountId,\n\n value: Balance,\n\n ) -> Result<()> {\n\n let from_balance = self.balance_of(from);\n\n if from_balance < value {\n\n return Err(Error::InsufficientBalance);\n", "file_path": "contracts/impls/token/erc20/lib.rs", "rank": 77, "score": 140579.63486995554 }, { "content": " Ok(())\n\n }\n\n\n\n /// Allows `spender` to withdraw from the caller's account multiple times, up to\n\n /// the `value` amount.\n\n ///\n\n /// If this function is called again it overwrites the current allowance with `value`.\n\n ///\n\n /// An `Approval` event is emitted.\n\n #[ink(message)]\n\n fn approve(&mut self, spender: AccountId, value: Balance) -> Result<()> {\n\n let owner = self.env().caller();\n\n self.allowances.insert((owner, spender), value);\n\n self.env().emit_event(Approval {\n\n owner,\n\n spender,\n\n value,\n\n });\n\n Ok(())\n\n }\n", "file_path": "contracts/impls/token/erc20/lib.rs", "rank": 78, "score": 140576.2778451561 }, { "content": " pub from: Option<AccountId>,\n\n #[ink(topic)]\n\n pub to: Option<AccountId>,\n\n #[ink(topic)]\n\n pub value: Balance,\n\n }\n\n /// Event emitted when an approval occurs that `spender` is allowed to withdraw\n\n /// up to the amount of `value` tokens from `owner`.\n\n #[ink(event)]\n\n pub struct Approval {\n\n #[ink(topic)]\n\n pub owner: AccountId,\n\n #[ink(topic)]\n\n pub spender: AccountId,\n\n #[ink(topic)]\n\n pub value: Balance,\n\n }\n\n\n\n /// Basic version of StandardToken, with no allowances.\n\n #[ink(storage)]\n", "file_path": "contracts/impls/token/erc20/lib.rs", "rank": 79, "score": 140574.38177306348 }, { "content": " instance\n\n }\n\n\n\n /// Returns the token name.\n\n #[ink(message)]\n\n fn token_name(&self) -> Option<String> {\n\n self.name.clone()\n\n }\n\n\n\n /// Returns the token symbol.\n\n #[ink(message)]\n\n fn token_symbol(&self) -> Option<String> {\n\n self.symbol.clone()\n\n }\n\n\n\n /// Returns the token decimals.\n\n #[ink(message)]\n\n fn token_decimals(&self) -> Option<u8> {\n\n self.decimals\n\n }\n", "file_path": "contracts/impls/token/erc20/lib.rs", "rank": 80, "score": 140570.53609961792 }, { "content": " /// to charge fees in sub-currencies, for example.\n\n ///\n\n /// On success a `Transfer` event is emitted.\n\n ///\n\n /// # Errors\n\n ///\n\n /// Returns `InsufficientAllowance` error if there are not enough tokens allowed\n\n /// for the caller to withdraw from `from`.\n\n ///\n\n /// Returns `InsufficientBalance` error if there are not enough tokens on\n\n /// the the account balance of `from`.\n\n #[ink(message)]\n\n fn transfer_from(&mut self, from: AccountId, to: AccountId, value: Balance) -> Result<()> {\n\n let caller = self.env().caller();\n\n let allowance = self.allowance(from, caller);\n\n if allowance < value {\n\n return Err(Error::InsufficientAllowance);\n\n }\n\n self.transfer_from_to(from, to, value)?;\n\n self.allowances.insert((from, caller), allowance - value);\n", "file_path": "contracts/impls/token/erc20/lib.rs", "rank": 81, "score": 140570.23359889924 }, { "content": "\n\n /// Returns the total token supply.\n\n #[ink(message)]\n\n fn total_supply(&self) -> Balance {\n\n *self.total_supply\n\n }\n\n\n\n /// Returns the account balance for the specified `owner`.\n\n ///\n\n /// Returns `0` if the account is non-existent.\n\n #[ink(message)]\n\n fn balance_of(&self, owner: AccountId) -> Balance {\n\n self.balances.get(&owner).copied().unwrap_or(0)\n\n }\n\n\n\n /// Transfers `value` amount of tokens from the caller's account to account `to`.\n\n ///\n\n /// On success a `Transfer` event is emitted.\n\n ///\n\n /// # Errors\n", "file_path": "contracts/impls/token/erc20/lib.rs", "rank": 82, "score": 140566.56656826002 }, { "content": " }\n\n self.balances.insert(from, from_balance - value);\n\n let to_balance = self.balance_of(to);\n\n self.balances.insert(to, to_balance + value);\n\n self.env().emit_event(Transfer {\n\n from: Some(from),\n\n to: Some(to),\n\n value,\n\n });\n\n Ok(())\n\n }\n\n }\n\n}\n", "file_path": "contracts/impls/token/erc20/lib.rs", "rank": 83, "score": 140554.24932836505 }, { "content": "// For Events\n\npub trait IERC20Event<E>: IERC20New<E>\n\nwhere\n\n E: Env,\n\n{\n\n fn decode_transfer_event(\n\n event: &ink_env::test::EmittedEvent,\n\n ) -> (Option<E::AccountId>, Option<E::AccountId>, E::Balance);\n\n\n\n fn decode_approval_event(\n\n event: &ink_env::test::EmittedEvent,\n\n ) -> (E::AccountId, E::AccountId, E::Balance);\n\n\n\n fn assert_topics(event: &ink_env::test::EmittedEvent, expected_topics: &Vec<E::Hash>);\n\n\n\n fn encoded_into_hash<T>(entity: &T) -> E::Hash\n\n where\n\n T: scale::Encode,\n\n {\n\n let mut result = E::Hash::clear();\n\n let len_result = result.as_ref().len();\n", "file_path": "crates/components/token/erc777/tests/mocks/behavior.rs", "rank": 84, "score": 139333.6806553985 }, { "content": "pub trait Impl<E>: _Impl<E>\n\nwhere\n\n E: Env,\n\n{\n\n fn before_token_transfer(\n\n &mut self,\n\n from: Option<E::AccountId>,\n\n to: Option<E::AccountId>,\n\n token_id: &TokenId,\n\n ) -> Result<()> {\n\n if from.is_none() {\n\n _Impl::_add_token_to_all_tokens_enumeration(self, token_id.clone());\n\n } else if from != to {\n\n _Impl::_remove_token_from_owner_enumeration(\n\n self,\n\n from.clone().expect(\"ERC721Enumerable: none from get\"),\n\n token_id,\n\n );\n\n }\n\n\n", "file_path": "crates/components/token/erc721/src/extensions/enumerable.rs", "rank": 85, "score": 136357.84777125315 }, { "content": " def approve(self):\n\n res = self.api.approve(self.alice, self.bob.ss58_address, 10000, gas_limit=default_gas_limit)\n\n self.assertTrue(res.is_success)\n\n allowance = self.api.allowance(self.alice, self.alice.ss58_address, self.bob.ss58_address)\n", "file_path": "apis/py/token/erc20/test/test_erc20.py", "rank": 86, "score": 135708.17166160842 }, { "content": " def check_balance_of(self, acc, value):\n\n res = self.api.balance_of(self.alice, acc)\n", "file_path": "apis/py/token/erc20/test/test_erc20.py", "rank": 87, "score": 133472.69279366193 }, { "content": "fn main() {}\n", "file_path": "crates/lang/macro/tests/contract/01-flipper-contract.rs", "rank": 88, "score": 128855.88544608268 }, { "content": "/// @dev Extension of {ERC1155} that allows token holders to destroy both their\n\n/// own tokens and those that they have been approved to use.\n\npub trait Impl<E>: ERC1155<E>\n\nwhere\n\n E: Env,\n\n{\n\n /// @dev Burns `id` by `value`\n\n ///\n\n /// Requirements:\n\n ///\n\n /// - The caller must own `id` or be an approved operator.\n\n fn burn(\n\n &mut self,\n\n account: E::AccountId,\n\n id: TokenId,\n\n value: E::Balance,\n\n ) -> Result<()> {\n\n let caller = Self::caller();\n\n assert!(\n\n account == caller || self.is_approved_for_all(&account, &caller),\n\n \"ERC1155: caller is not owner nor approved\"\n\n );\n", "file_path": "crates/components/token/erc1155/src/extensions/burnable.rs", "rank": 89, "score": 124802.97765031244 }, { "content": "/// @title ERC721 Burnable Token\n\n/// @dev ERC721 Token that can be irreversibly burned (destroyed).\n\npub trait Impl<E>: ERC721<E>\n\nwhere\n\n E: Env,\n\n{\n\n /// @dev Burns `tokenId`. See {ERC721-_burn}.\n\n ///\n\n /// Requirements:\n\n ///\n\n /// - The caller must own `tokenId` or be an approved operator.\n\n fn burn(&mut self, token_id: &TokenId) -> Result<()> {\n\n let caller = &Self::caller();\n\n assert!(\n\n ERC721::_is_approved_or_owner(self, caller, token_id),\n\n \"ERC721Burnable: caller is not owner nor approved\"\n\n );\n\n ERC721::_burn(self, token_id)\n\n }\n\n}\n\n\n\n// No impl this for default\n", "file_path": "crates/components/token/erc721/src/extensions/burnable.rs", "rank": 90, "score": 124792.94693536876 }, { "content": "fn gen_leave_codes() -> Result<Vec<syn::Stmt>> {\n\n // metis_reentrancy_guard::Impl::_set_not_entered(self);\n\n\n\n Ok(vec![syn::parse2::<syn::Stmt>(\n\n quote! {metis_reentrancy_guard::Impl::_set_not_entered(self);},\n\n )?])\n\n}\n\n\n", "file_path": "crates/lang/codegen/src/components/reentrancy_guard.rs", "rank": 91, "score": 124264.87650120792 }, { "content": "fn gen_enter_codes() -> Result<Vec<syn::Stmt>> {\n\n // metis_reentrancy_guard::Impl::_check_nonreentrant(self);\n\n // metis_reentrancy_guard::Impl::_set_entered(self);\n\n\n\n Ok(vec![\n\n syn::parse2::<syn::Stmt>(\n\n quote! {metis_reentrancy_guard::Impl::_check_nonreentrant(self);},\n\n )?,\n\n syn::parse2::<syn::Stmt>(\n\n quote! {metis_reentrancy_guard::Impl::_set_entered(self);},\n\n )?,\n\n ])\n\n}\n\n\n", "file_path": "crates/lang/codegen/src/components/reentrancy_guard.rs", "rank": 92, "score": 124264.87650120792 }, { "content": "#[proc_macro]\n\npub fn hash(input: TokenStream) -> TokenStream {\n\n match utils::generate_hash_string_or_err(input.into()) {\n\n Ok(tokens) => tokens,\n\n Err(err) => err.to_compile_error(),\n\n }\n\n .into()\n\n}\n\n\n\n/// Gen selector id form input message name.\n", "file_path": "crates/lang/macro/src/lib.rs", "rank": 93, "score": 123780.67307357173 }, { "content": "#[proc_macro]\n\npub fn selector_id(input: TokenStream) -> TokenStream {\n\n match utils::generate_msg_selector_id_or_err(input.into()) {\n\n Ok(tokens) => tokens,\n\n Err(err) => err.to_compile_error(),\n\n }\n\n .into()\n\n}\n", "file_path": "crates/lang/macro/src/lib.rs", "rank": 94, "score": 122234.4642013547 }, { "content": "#[test]\n\nfn tests() {\n\n let t = trybuild::TestCases::new();\n\n t.pass(\"tests/contract/01-flipper-contract.rs\");\n\n t.pass(\"tests/contract/02-flipper-owner-contract.rs\");\n\n t.pass(\"tests/contract/03-stub.rs\");\n\n // t.pass(\"tests/02-create-builder.rs\");\n\n // t.pass(\"tests/03-call-setters.rs\");\n\n // t.pass(\"tests/04-call-build.rs\");\n\n // t.pass(\"tests/05-method-chaining.rs\");\n\n // t.pass(\"tests/06-optional-field.rs\");\n\n // t.pass(\"tests/07-repeated-field.rs\");\n\n // t.compile_fail(\"tests/08-unrecognized-attribute.rs\");\n\n // t.pass(\"tests/09-redefined-prelude-types.rs\");\n\n}\n", "file_path": "crates/lang/macro/tests/contract.rs", "rank": 95, "score": 122172.17018035328 }, { "content": "fn generate_supports_message(func_params: FuncParams) -> Result<TokenStream2> {\n\n let mut interface_ids = func_params\n\n .funcs\n\n .iter()\n\n .filter(|f| f.name == \"interface\")\n\n .map(|f| calculate_interface_id(&f.attrs))\n\n .into_iter()\n\n .collect::<Vec<_>>();\n\n\n\n // for supports_interface\n\n interface_ids.push(calculate_interface_id(&vec![Ident::new(\n\n \"supports_interface\",\n\n Span::call_site(),\n\n )]));\n\n\n\n let match_id_trues = interface_ids\n\n .iter()\n\n .map(|interface_id| {\n\n quote! {\n\n #interface_id => true,\n", "file_path": "crates/lang/codegen/src/components/erc165.rs", "rank": 96, "score": 121432.89409327877 }, { "content": "fn main() {}\n", "file_path": "crates/lang/macro/tests/contract/03-stub.rs", "rank": 97, "score": 120234.74582618987 }, { "content": "#[cfg(not(feature = \"std\"))]\n\npub trait AccountId: EnvAccountId + Default + SpreadLayout + PackedLayout {}\n\n\n\n#[cfg(not(feature = \"std\"))]\n\nimpl<T> AccountId for T where T: EnvAccountId + Default + SpreadLayout + PackedLayout {}\n\n\n", "file_path": "crates/lang/contract/src/traits.rs", "rank": 98, "score": 115245.84375432771 }, { "content": "```\n\n\n\nTo use this component, we can import this to contract:\n\n\n\n```rust\n\n#![cfg_attr(not(feature = \"std\"), no_std)]\n\n\n\n#[metis_lang::contract] // use `metis_lang::contract`\n\npub mod contract {\n\n // use the component: xxx1 and xxx2\n\n use metis_component_xxx1 as xxx1;\n\n use metis_component_xxx2 as xxx2;\n\n\n\n // use `import` and `metis` marco\n\n use metis_lang::{\n\n import,\n\n metis,\n\n };\n\n\n\n #[ink(storage)]\n\n #[import(xxx1, xxx2)] // import the component\n\n pub struct Contract {\n\n // add data to storage, which use Contract as Env to Data\n\n xxx1: xxx1::Data<Contract>,\n\n xxx2: xxx2::Data<Contract>,\n\n }\n\n\n\n /// add event for component\n\n /// in emit it will be emit_event_ownership_transferred\n\n #[ink(event)]\n\n #[metis(xxx1)] // event for xxx1\n\n pub struct OwnershipTransferred {\n\n /// previous owner account id\n\n #[ink(topic)]\n\n previous_owner: Option<AccountId>,\n\n /// new owner account id\n\n #[ink(topic)]\n\n new_owner: Option<AccountId>,\n\n }\n\n\n\n /// Event emitted when payee withdraw\n\n #[ink(event)]\n\n #[metis(xxx2)] // event for xxx1\n\n pub struct OtherEvent {\n\n #[ink(topic)]\n\n pub payee: AccountId,\n\n pub amount: Balance,\n\n }\n\n\n\n impl xxx1::Impl<Contract> for Contract {\n\n fn hook(\n\n &mut self,\n\n params: &E::Balance\n\n ) -> Result<()> {\n\n // some logic\n\n\n\n Ok(())\n\n }\n\n }\n\n\n\n // impl\n\n impl Contract {\n\n #[ink(constructor)]\n\n pub fn new() -> Self {\n\n // impl for default\n\n let mut instance = Self {\n\n xxx1: xxx1::Data::new(),\n\n xxx2: xxx2::Data::new(),\n\n };\n\n\n\n // init call\n\n xxx1::Impl::init(&mut instance);\n\n xxx2::Impl::init(&mut instance);\n\n\n\n // return instance\n\n instance\n", "file_path": "docs/zh-cn/use-component.md", "rank": 99, "score": 96.85492302818282 } ]
Rust
src/pymodule/mod.rs
ripe-tech/pconvert-rust
cf9ffcfc59d5838cf4d74a2c6c666e3f94f7cdc3
pub mod conversions; pub mod utils; use crate::blending::params::{BlendAlgorithmParams, Options}; use crate::blending::{ blend_images, demultiply_image, get_blending_algorithm, is_algorithm_multiplied, BlendAlgorithm, }; use crate::constants; use crate::errors::PConvertError; use crate::parallelism::{ResultMessage, ThreadPool}; use crate::utils::{read_png_from_file, write_png_parallel, write_png_to_file}; use pyo3::exceptions::PyException; use pyo3::prelude::*; use pyo3::types::{IntoPyDict, PyDict, PySequence}; use std::sync::mpsc; use utils::{ build_algorithm, build_params, get_compression_type, get_filter_type, get_num_threads, }; static mut THREAD_POOL: Option<ThreadPool> = None; #[pymodule] fn pconvert_rust(_py: Python, module: &PyModule) -> PyResult<()> { unsafe { let mut thread_pool = ThreadPool::new(constants::DEFAULT_THREAD_POOL_SIZE).unwrap(); thread_pool.start(); THREAD_POOL = Some(thread_pool); } module.add("COMPILATION_DATE", constants::COMPILATION_DATE)?; module.add("COMPILATION_TIME", constants::COMPILATION_TIME)?; module.add("VERSION", constants::VERSION)?; module.add("ALGORITHMS", constants::ALGORITHMS.to_vec())?; module.add("COMPILER", constants::COMPILER)?; module.add("COMPILER_VERSION", constants::COMPILER_VERSION)?; module.add("LIBPNG_VERSION", constants::LIBPNG_VERSION)?; module.add("FEATURES", constants::FEATURES.to_vec())?; module.add("PLATFORM_CPU_BITS", constants::PLATFORM_CPU_BITS)?; let filters: Vec<String> = constants::FILTER_TYPES .to_vec() .iter() .map(|x| format!("{:?}", x)) .collect(); module.add("FILTER_TYPES", filters)?; let compressions: Vec<String> = constants::COMPRESSION_TYPES .to_vec() .iter() .map(|x| format!("{:?}", x)) .collect(); module.add("COMPRESSION_TYPES", compressions)?; #[pyfn(module, "blend_images")] fn blend_images_py( py: Python, bot_path: String, top_path: String, target_path: String, algorithm: Option<String>, is_inline: Option<bool>, options: Option<Options>, ) -> PyResult<()> { py.allow_threads(|| -> PyResult<()> { let num_threads = get_num_threads(&options); if num_threads <= 0 { blend_images_single_thread( bot_path, top_path, target_path, algorithm, is_inline, options, ) } else { unsafe { blend_images_multi_thread( bot_path, top_path, target_path, algorithm, is_inline, options, num_threads, ) } } }) } #[pyfn(module, "blend_multiple")] fn blend_multiple_py( py: Python, img_paths: &PySequence, out_path: String, algorithm: Option<String>, algorithms: Option<&PySequence>, is_inline: Option<bool>, options: Option<Options>, ) -> PyResult<()> { let img_paths: Vec<String> = img_paths.extract()?; let num_images = img_paths.len(); let algorithms_to_apply: Vec<(BlendAlgorithm, Option<BlendAlgorithmParams>)> = if let Some(algorithms) = algorithms { build_params(algorithms)? } else if let Some(algorithm) = algorithm { let algorithm = build_algorithm(&algorithm)?; vec![(algorithm, None); num_images - 1] } else { vec![(BlendAlgorithm::Multiplicative, None); num_images - 1] }; py.allow_threads(|| -> PyResult<()> { let num_threads = get_num_threads(&options); if num_threads <= 0 { blend_multiple_single_thread( img_paths, out_path, algorithms_to_apply, is_inline, options, ) } else { unsafe { blend_multiple_multi_thread( img_paths, out_path, algorithms_to_apply, is_inline, options, num_threads, ) } } }) } #[pyfn(module, "get_thread_pool_status")] fn get_thread_pool_status(py: Python) -> PyResult<&PyDict> { unsafe { match &mut THREAD_POOL { Some(thread_pool) => { let status_dict = thread_pool.get_status().into_py_dict(py); Ok(status_dict) } None => Err(PyException::new_err( "Acessing global thread pool".to_string(), )), } } } Ok(()) } fn blend_images_single_thread( bot_path: String, top_path: String, target_path: String, algorithm: Option<String>, is_inline: Option<bool>, options: Option<Options>, ) -> PyResult<()> { let algorithm = algorithm.unwrap_or_else(|| String::from("multiplicative")); let algorithm = build_algorithm(&algorithm)?; let _is_inline = is_inline.unwrap_or(false); let demultiply = is_algorithm_multiplied(&algorithm); let algorithm_fn = get_blending_algorithm(&algorithm); let mut bot = read_png_from_file(bot_path, demultiply)?; let top = read_png_from_file(top_path, demultiply)?; blend_images(&mut bot, &top, &algorithm_fn, &None); let compression_type = get_compression_type(&options); let filter_type = get_filter_type(&options); write_png_to_file(target_path, &bot, compression_type, filter_type)?; Ok(()) } unsafe fn blend_images_multi_thread( bot_path: String, top_path: String, target_path: String, algorithm: Option<String>, is_inline: Option<bool>, options: Option<Options>, num_threads: i32, ) -> PyResult<()> { let algorithm = algorithm.unwrap_or_else(|| String::from("multiplicative")); let algorithm = build_algorithm(&algorithm)?; let _is_inline = is_inline.unwrap_or(false); let demultiply = is_algorithm_multiplied(&algorithm); let algorithm_fn = get_blending_algorithm(&algorithm); let thread_pool = match &mut THREAD_POOL { Some(thread_pool) => thread_pool, None => panic!("Unable to access global pconvert thread pool"), }; thread_pool.expand_to(num_threads as usize); let bot_result_channel = thread_pool .execute(move || ResultMessage::ImageResult(read_png_from_file(bot_path, demultiply))); let top_result_channel = thread_pool .execute(move || ResultMessage::ImageResult(read_png_from_file(top_path, demultiply))); let mut bot = match bot_result_channel.recv().unwrap() { ResultMessage::ImageResult(result) => result, }?; let top = match top_result_channel.recv().unwrap() { ResultMessage::ImageResult(result) => result, }?; blend_images(&mut bot, &top, &algorithm_fn, &None); let compression_type = get_compression_type(&options); let filter_type = get_filter_type(&options); write_png_parallel(target_path, &bot, compression_type, filter_type)?; Ok(()) } fn blend_multiple_single_thread( img_paths: Vec<String>, out_path: String, algorithms: Vec<(BlendAlgorithm, Option<BlendAlgorithmParams>)>, is_inline: Option<bool>, options: Option<Options>, ) -> PyResult<()> { let num_images = img_paths.len(); if num_images < 1 { return Err(PyErr::from(PConvertError::ArgumentError( "ArgumentError: 'img_paths' must contain at least one path".to_string(), ))); } if algorithms.len() != num_images - 1 { return Err(PyErr::from(PConvertError::ArgumentError(format!( "ArgumentError: 'algorithms' must be of size {} (one per blending operation)", num_images - 1 )))); }; let _is_inline = is_inline.unwrap_or(false); let mut img_paths_iter = img_paths.iter(); let first_path = img_paths_iter.next().unwrap().to_string(); let first_demultiply = is_algorithm_multiplied(&algorithms[0].0); let mut composition = read_png_from_file(first_path, first_demultiply)?; let zip_iter = img_paths_iter.zip(algorithms.iter()); for pair in zip_iter { let path = pair.0.to_string(); let (algorithm, algorithm_params) = pair.1; let demultiply = is_algorithm_multiplied(&algorithm); let algorithm_fn = get_blending_algorithm(&algorithm); let current_layer = read_png_from_file(path, demultiply)?; blend_images( &mut composition, &current_layer, &algorithm_fn, algorithm_params, ); } let compression_type = get_compression_type(&options); let filter_type = get_filter_type(&options); write_png_to_file(out_path, &composition, compression_type, filter_type)?; Ok(()) } unsafe fn blend_multiple_multi_thread( img_paths: Vec<String>, out_path: String, algorithms: Vec<(BlendAlgorithm, Option<BlendAlgorithmParams>)>, is_inline: Option<bool>, options: Option<Options>, num_threads: i32, ) -> PyResult<()> { let num_images = img_paths.len(); if num_images < 1 { return Err(PyErr::from(PConvertError::ArgumentError( "ArgumentError: 'img_paths' must contain at least one path".to_string(), ))); } if algorithms.len() != num_images - 1 { return Err(PyErr::from(PConvertError::ArgumentError(format!( "ArgumentError: 'algorithms' must be of size {} (one per blending operation)", num_images - 1 )))); }; let _is_inline = is_inline.unwrap_or(false); let thread_pool = match &mut THREAD_POOL { Some(thread_pool) => thread_pool, None => panic!("Unable to access global pconvert thread pool"), }; thread_pool.expand_to(num_threads as usize); let mut png_channels: Vec<mpsc::Receiver<ResultMessage>> = Vec::with_capacity(num_images); for path in img_paths.into_iter() { let result_channel = thread_pool.execute(move || -> ResultMessage { ResultMessage::ImageResult(read_png_from_file(path, false)) }); png_channels.push(result_channel); } let first_demultiply = is_algorithm_multiplied(&algorithms[0].0); let mut composition = match png_channels[0].recv().unwrap() { ResultMessage::ImageResult(result) => result, }?; if first_demultiply { demultiply_image(&mut composition) } for i in 1..png_channels.len() { let (algorithm, algorithm_params) = &algorithms[i - 1]; let demultiply = is_algorithm_multiplied(&algorithm); let algorithm_fn = get_blending_algorithm(&algorithm); let mut current_layer = match png_channels[i].recv().unwrap() { ResultMessage::ImageResult(result) => result, }?; if demultiply { demultiply_image(&mut current_layer) } blend_images( &mut composition, &current_layer, &algorithm_fn, algorithm_params, ); } let compression_type = get_compression_type(&options); let filter_type = get_filter_type(&options); write_png_parallel(out_path, &composition, compression_type, filter_type)?; Ok(()) }
pub mod conversions; pub mod utils; use crate::blending::params::{BlendAlgorithmParams, Options}; use crate::blending::{ blend_images, demultiply_image, get_blending_algorithm, is_algorithm_multiplied, BlendAlgorithm, }; use crate::constants; use crate::errors::PConvertError; use crate::parallelism::{ResultMessage, ThreadPool}; use crate::utils::{read_png_from_file, write_png_parallel, write_png_to_file}; use pyo3::exceptions::PyException; use pyo3::prelude::*; use pyo3::types::{IntoPyDict, PyDict, PySequence}; use std::sync::mpsc; use utils::{ build_algorithm, build_params, get_compression_type, get_filter_type, get_num_threads, }; static mut THREAD_POOL: Option<ThreadPool> = None; #[pymodule] fn pconvert_rust(_py: Python, module: &PyModule) -> PyResult<()> { unsafe { let mut thread_pool = ThreadPool::new(constants::DEFAULT_THREAD_POOL_SIZE).unwrap(); thread_pool.start(); THREAD_POOL = Some(thread_pool); } module.add("COMPILATION_DATE", constants::COMPILATION_DATE)?; module.add("COMPILATION_TIME", constants::COMPILATION_TIME)?; module.add("VERSION", constants::VERSION)?; module.add("ALGORITHMS", constants::ALGORITHMS.to_vec())?; module.add("COMPILER", constants::COMPILER)?; module.add("COMPILER_VERSION", constants::COMPILER_VERSION)?; module.add("LIBPNG_VERSION", constants::LIBPNG_VERSION)?; module.add("FEATURES", constants::FEATURES.to_vec())?; module.add("PLATFORM_CPU_BITS", constants::PLATFORM_CPU_BITS)?; let filters: Vec<String> = constants::FILTER_TYPES .to_vec() .iter() .map(|x| format!("{:?}", x)) .collect(); module.add("FILTER_TYPES", filters)?; let compressions: Vec<String> = constants::COMPRESSION_TYPES .to_vec() .iter() .map(|x| format!("{:?}", x)) .collect(); module.add("COMPRESSION_TYPES", compressions)?; #[pyfn(module, "blend_images")] fn blend_images_py( py: Python, bot_path: String, top_path: String, target_path: String, algorithm: Option<String>, is_inline: Option<bool>, options: Option<Options>, ) -> PyResult<()> { py.allow_threads(|| -> PyResult<()> { let num_threads = get_num_threads(&options); if num_threads <= 0 { blend_images_single_thread( bot_path, top_path, target_path, algorithm, is_inline, options, ) } else { unsafe { blend_images_multi_thread( bot_path, top_path, target_path, algorithm, is_inline, options, num_threads, ) } } }) } #[pyfn(module, "blend_multiple")] fn blend_multiple_py( py: Python, img_paths: &PySequence, out_path: String, algorithm: Option<String>, algorithms: Option<&PySequence>, is_inline: Option<bool>, options: Option<Options>, ) -> PyResult<()> { let img_paths: Vec<String> = img_paths.extract()?; let num_images =
#[pyfn(module, "get_thread_pool_status")] fn get_thread_pool_status(py: Python) -> PyResult<&PyDict> { unsafe { match &mut THREAD_POOL { Some(thread_pool) => { let status_dict = thread_pool.get_status().into_py_dict(py); Ok(status_dict) } None => Err(PyException::new_err( "Acessing global thread pool".to_string(), )), } } } Ok(()) } fn blend_images_single_thread( bot_path: String, top_path: String, target_path: String, algorithm: Option<String>, is_inline: Option<bool>, options: Option<Options>, ) -> PyResult<()> { let algorithm = algorithm.unwrap_or_else(|| String::from("multiplicative")); let algorithm = build_algorithm(&algorithm)?; let _is_inline = is_inline.unwrap_or(false); let demultiply = is_algorithm_multiplied(&algorithm); let algorithm_fn = get_blending_algorithm(&algorithm); let mut bot = read_png_from_file(bot_path, demultiply)?; let top = read_png_from_file(top_path, demultiply)?; blend_images(&mut bot, &top, &algorithm_fn, &None); let compression_type = get_compression_type(&options); let filter_type = get_filter_type(&options); write_png_to_file(target_path, &bot, compression_type, filter_type)?; Ok(()) } unsafe fn blend_images_multi_thread( bot_path: String, top_path: String, target_path: String, algorithm: Option<String>, is_inline: Option<bool>, options: Option<Options>, num_threads: i32, ) -> PyResult<()> { let algorithm = algorithm.unwrap_or_else(|| String::from("multiplicative")); let algorithm = build_algorithm(&algorithm)?; let _is_inline = is_inline.unwrap_or(false); let demultiply = is_algorithm_multiplied(&algorithm); let algorithm_fn = get_blending_algorithm(&algorithm); let thread_pool = match &mut THREAD_POOL { Some(thread_pool) => thread_pool, None => panic!("Unable to access global pconvert thread pool"), }; thread_pool.expand_to(num_threads as usize); let bot_result_channel = thread_pool .execute(move || ResultMessage::ImageResult(read_png_from_file(bot_path, demultiply))); let top_result_channel = thread_pool .execute(move || ResultMessage::ImageResult(read_png_from_file(top_path, demultiply))); let mut bot = match bot_result_channel.recv().unwrap() { ResultMessage::ImageResult(result) => result, }?; let top = match top_result_channel.recv().unwrap() { ResultMessage::ImageResult(result) => result, }?; blend_images(&mut bot, &top, &algorithm_fn, &None); let compression_type = get_compression_type(&options); let filter_type = get_filter_type(&options); write_png_parallel(target_path, &bot, compression_type, filter_type)?; Ok(()) } fn blend_multiple_single_thread( img_paths: Vec<String>, out_path: String, algorithms: Vec<(BlendAlgorithm, Option<BlendAlgorithmParams>)>, is_inline: Option<bool>, options: Option<Options>, ) -> PyResult<()> { let num_images = img_paths.len(); if num_images < 1 { return Err(PyErr::from(PConvertError::ArgumentError( "ArgumentError: 'img_paths' must contain at least one path".to_string(), ))); } if algorithms.len() != num_images - 1 { return Err(PyErr::from(PConvertError::ArgumentError(format!( "ArgumentError: 'algorithms' must be of size {} (one per blending operation)", num_images - 1 )))); }; let _is_inline = is_inline.unwrap_or(false); let mut img_paths_iter = img_paths.iter(); let first_path = img_paths_iter.next().unwrap().to_string(); let first_demultiply = is_algorithm_multiplied(&algorithms[0].0); let mut composition = read_png_from_file(first_path, first_demultiply)?; let zip_iter = img_paths_iter.zip(algorithms.iter()); for pair in zip_iter { let path = pair.0.to_string(); let (algorithm, algorithm_params) = pair.1; let demultiply = is_algorithm_multiplied(&algorithm); let algorithm_fn = get_blending_algorithm(&algorithm); let current_layer = read_png_from_file(path, demultiply)?; blend_images( &mut composition, &current_layer, &algorithm_fn, algorithm_params, ); } let compression_type = get_compression_type(&options); let filter_type = get_filter_type(&options); write_png_to_file(out_path, &composition, compression_type, filter_type)?; Ok(()) } unsafe fn blend_multiple_multi_thread( img_paths: Vec<String>, out_path: String, algorithms: Vec<(BlendAlgorithm, Option<BlendAlgorithmParams>)>, is_inline: Option<bool>, options: Option<Options>, num_threads: i32, ) -> PyResult<()> { let num_images = img_paths.len(); if num_images < 1 { return Err(PyErr::from(PConvertError::ArgumentError( "ArgumentError: 'img_paths' must contain at least one path".to_string(), ))); } if algorithms.len() != num_images - 1 { return Err(PyErr::from(PConvertError::ArgumentError(format!( "ArgumentError: 'algorithms' must be of size {} (one per blending operation)", num_images - 1 )))); }; let _is_inline = is_inline.unwrap_or(false); let thread_pool = match &mut THREAD_POOL { Some(thread_pool) => thread_pool, None => panic!("Unable to access global pconvert thread pool"), }; thread_pool.expand_to(num_threads as usize); let mut png_channels: Vec<mpsc::Receiver<ResultMessage>> = Vec::with_capacity(num_images); for path in img_paths.into_iter() { let result_channel = thread_pool.execute(move || -> ResultMessage { ResultMessage::ImageResult(read_png_from_file(path, false)) }); png_channels.push(result_channel); } let first_demultiply = is_algorithm_multiplied(&algorithms[0].0); let mut composition = match png_channels[0].recv().unwrap() { ResultMessage::ImageResult(result) => result, }?; if first_demultiply { demultiply_image(&mut composition) } for i in 1..png_channels.len() { let (algorithm, algorithm_params) = &algorithms[i - 1]; let demultiply = is_algorithm_multiplied(&algorithm); let algorithm_fn = get_blending_algorithm(&algorithm); let mut current_layer = match png_channels[i].recv().unwrap() { ResultMessage::ImageResult(result) => result, }?; if demultiply { demultiply_image(&mut current_layer) } blend_images( &mut composition, &current_layer, &algorithm_fn, algorithm_params, ); } let compression_type = get_compression_type(&options); let filter_type = get_filter_type(&options); write_png_parallel(out_path, &composition, compression_type, filter_type)?; Ok(()) }
img_paths.len(); let algorithms_to_apply: Vec<(BlendAlgorithm, Option<BlendAlgorithmParams>)> = if let Some(algorithms) = algorithms { build_params(algorithms)? } else if let Some(algorithm) = algorithm { let algorithm = build_algorithm(&algorithm)?; vec![(algorithm, None); num_images - 1] } else { vec![(BlendAlgorithm::Multiplicative, None); num_images - 1] }; py.allow_threads(|| -> PyResult<()> { let num_threads = get_num_threads(&options); if num_threads <= 0 { blend_multiple_single_thread( img_paths, out_path, algorithms_to_apply, is_inline, options, ) } else { unsafe { blend_multiple_multi_thread( img_paths, out_path, algorithms_to_apply, is_inline, options, num_threads, ) } } }) }
function_block-function_prefixed
[ { "content": "/// Attempts to parse a `&String` to a `BlendAlgorithm`.\n\n/// Returns the enum variant if it succeeds. Otherwise it returns a `PyErr`.\n\npub fn build_algorithm(algorithm: &str) -> Result<BlendAlgorithm, PyErr> {\n\n match BlendAlgorithm::from_str(algorithm) {\n\n Ok(algorithm) => Ok(algorithm),\n\n Err(algorithm) => Err(PyErr::from(PConvertError::ArgumentError(format!(\n\n \"ArgumentError: invalid algorithm '{}'\",\n\n algorithm\n\n )))),\n\n }\n\n}\n\n\n", "file_path": "src/pymodule/utils.rs", "rank": 0, "score": 233059.14059103525 }, { "content": "/// Converts a `String` to a `image::codecs::png::FilterType`.\n\n/// This can not be done by implementing the trait `From<String> for FilterType` due to Rust's\n\n/// [orphan rule](https://doc.rust-lang.org/book/ch10-02-traits.html#implementing-a-trait-on-a-type).\n\npub fn image_filter_from(filter: String) -> FilterType {\n\n match filter.trim().to_lowercase().as_str() {\n\n \"avg\" => FilterType::Avg,\n\n \"nofilter\" => FilterType::NoFilter,\n\n \"paeth\" => FilterType::Paeth,\n\n \"sub\" => FilterType::Sub,\n\n \"up\" => FilterType::Up,\n\n _ => FilterType::NoFilter,\n\n }\n\n}\n\n\n", "file_path": "src/utils.rs", "rank": 1, "score": 217765.7872716211 }, { "content": "/// Retrieves the `image::codecs::png::CompressionType` value from the `Options` map if it exists.\n\n/// Otherwise it returns the default value: `CompressionType::Fast`.\n\npub fn get_compression_type(options: &Option<Options>) -> CompressionType {\n\n options.clone().map_or(CompressionType::Fast, |options| {\n\n options\n\n .get(\"compression\")\n\n .map_or(CompressionType::Fast, |compression| match compression {\n\n Value::Str(compression) => image_compression_from(compression.to_string()),\n\n _ => CompressionType::Fast,\n\n })\n\n })\n\n}\n\n\n", "file_path": "src/pymodule/utils.rs", "rank": 3, "score": 213584.79640203313 }, { "content": "/// Retrieves the `image::codecs::png::FilterType` value from the `Options` map if it exists.\n\n/// Otherwise it returns the default value: `FilterType::NoFilter`.\n\npub fn get_filter_type(options: &Option<Options>) -> FilterType {\n\n options.clone().map_or(FilterType::NoFilter, |options| {\n\n options\n\n .get(\"filter\")\n\n .map_or(FilterType::NoFilter, |filter| match filter {\n\n Value::Str(filter) => image_filter_from(filter.to_string()),\n\n _ => FilterType::NoFilter,\n\n })\n\n })\n\n}\n\n\n", "file_path": "src/pymodule/utils.rs", "rank": 4, "score": 213559.24148766723 }, { "content": "/// Retrieves the `image::codecs::png::CompressionType` value from the\n\n/// `HashMap<String, JSONValue>` map if it exists.\n\n/// Otherwise it returns the default value: `CompressionType::Fast`.\n\npub fn get_compression_type(options: &Option<HashMap<String, JSONValue>>) -> CompressionType {\n\n options.as_ref().map_or(CompressionType::Fast, |options| {\n\n options\n\n .get(\"compression\")\n\n .map_or(CompressionType::Fast, |compression| match compression {\n\n JSONValue::String(compression) => image_compression_from(compression.to_string()),\n\n _ => CompressionType::Fast,\n\n })\n\n })\n\n}\n\n\n", "file_path": "src/wasm/utils.rs", "rank": 5, "score": 204766.17995572998 }, { "content": "/// Retrieves the `image::codecs::png::FilterType` value from the\n\n/// `HashMap<String, JSONValue>` map if it exists.\n\n/// Otherwise it returns the default value: `FilterType::NoFilter`.\n\npub fn get_filter_type(options: &Option<HashMap<String, JSONValue>>) -> FilterType {\n\n options.as_ref().map_or(FilterType::NoFilter, |options| {\n\n options\n\n .get(\"filter\")\n\n .map_or(FilterType::NoFilter, |filter| match filter {\n\n JSONValue::String(filter) => image_filter_from(filter.to_string()),\n\n _ => FilterType::NoFilter,\n\n })\n\n })\n\n}\n\n\n", "file_path": "src/wasm/utils.rs", "rank": 6, "score": 204742.75776946606 }, { "content": "/// Converts a `String` to a `image::codecs::png::CompressionType`.\n\n/// This can not be done by implementing the trait `From<String> for CompressionType` due to Rust's.\n\n/// [orphan rule](https://doc.rust-lang.org/book/ch10-02-traits.html#implementing-a-trait-on-a-type).\n\npub fn image_compression_from(compression: String) -> CompressionType {\n\n match compression.trim().to_lowercase().as_str() {\n\n \"best\" => CompressionType::Best,\n\n \"default\" => CompressionType::Default,\n\n \"fast\" => CompressionType::Fast,\n\n \"huffman\" => CompressionType::Huffman,\n\n \"rle\" => CompressionType::Rle,\n\n _ => CompressionType::Fast,\n\n }\n\n}\n\n\n", "file_path": "src/utils.rs", "rank": 7, "score": 196630.00165614183 }, { "content": "/// Returns whether or not a `BlendAlgorithm` enum variant corresponds to a\n\n/// multiplied blending algorithm.\n\n///\n\n/// # Arguments\n\n///\n\n/// * `algorithm` - The BlendAlgorithm enum variant.\n\npub fn is_algorithm_multiplied(algorithm: &BlendAlgorithm) -> bool {\n\n match algorithm {\n\n BlendAlgorithm::Alpha => false,\n\n BlendAlgorithm::Multiplicative => false,\n\n BlendAlgorithm::SourceOver => false,\n\n BlendAlgorithm::DestinationOver => false,\n\n BlendAlgorithm::MaskTop => false,\n\n BlendAlgorithm::FirstTop => false,\n\n BlendAlgorithm::FirstBottom => false,\n\n BlendAlgorithm::DisjointOver => true,\n\n BlendAlgorithm::DisjointUnder => true,\n\n BlendAlgorithm::DisjointDebug => true,\n\n }\n\n}\n\n\n", "file_path": "src/blending/mod.rs", "rank": 8, "score": 187563.95418997368 }, { "content": "/// Attempts to parse a `&String` to a `BlendAlgorithm`.\n\n/// Returns the enum variant if it suceeds. Otherwise it returns a `PConvertError`.\n\npub fn build_algorithm(algorithm: &str) -> Result<BlendAlgorithm, PConvertError> {\n\n match BlendAlgorithm::from_str(&algorithm) {\n\n Ok(algorithm) => Ok(algorithm),\n\n Err(algorithm) => Err(PConvertError::ArgumentError(format!(\n\n \"Invalid algorithm '{}'\",\n\n algorithm\n\n ))),\n\n }\n\n}\n\n\n", "file_path": "src/wasm/utils.rs", "rank": 9, "score": 185961.65290298115 }, { "content": "/// Retrieves the number of threads value from the `Options` map if it exists.\n\n/// Otherwise it returns the default value: 0.\n\npub fn get_num_threads(options: &Option<Options>) -> i32 {\n\n options.clone().map_or(0, |options| {\n\n options\n\n .get(\"num_threads\")\n\n .map_or(0, |num_threads| match num_threads {\n\n Value::Int(num_threads) => *num_threads,\n\n _ => 0,\n\n })\n\n })\n\n}\n", "file_path": "src/pymodule/utils.rs", "rank": 10, "score": 184409.81550884977 }, { "content": "/// Matches a `BlendAlgorithm` enum variant with a blend function.\n\n///\n\n/// # Arguments\n\n///\n\n/// * `algorithm` - The BlendAlgorithm enum variant.\n\npub fn get_blending_algorithm(\n\n algorithm: &BlendAlgorithm,\n\n) -> impl Fn((&mut Rgba<u8>, &Rgba<u8>), &Option<BlendAlgorithmParams>) {\n\n match algorithm {\n\n BlendAlgorithm::Alpha => blend_alpha,\n\n BlendAlgorithm::Multiplicative => blend_multiplicative,\n\n BlendAlgorithm::SourceOver => blend_source_over,\n\n BlendAlgorithm::DestinationOver => blend_destination_over,\n\n BlendAlgorithm::MaskTop => blend_mask_top,\n\n BlendAlgorithm::FirstTop => blend_first_top,\n\n BlendAlgorithm::FirstBottom => blend_first_bottom,\n\n BlendAlgorithm::DisjointOver => blend_disjoint_over,\n\n BlendAlgorithm::DisjointUnder => blend_disjoint_under,\n\n BlendAlgorithm::DisjointDebug => blend_disjoint_debug,\n\n }\n\n}\n\n\n", "file_path": "src/blending/mod.rs", "rank": 11, "score": 178680.64457354485 }, { "content": "/// Attempts to build a vector of blending operations and extra parameters.\n\n/// One pair per blending operation. Returns a `PyErr` if it fails parsing.\n\npub fn build_params(\n\n algorithms: &PySequence,\n\n) -> Result<Vec<(BlendAlgorithm, Option<BlendAlgorithmParams>)>, PyErr> {\n\n let mut result = Vec::new();\n\n\n\n // parses the parameter sequence which is a python sequence (tuple or list)\n\n // made of either algorithms or more sequences of algorithms and special parameters\n\n for i in 0..algorithms.len()? {\n\n let element = algorithms.get_item(i)?;\n\n\n\n if let Ok(string) = element.cast_as::<PyString>() {\n\n let algorithm = build_algorithm(&string.to_string())?;\n\n result.push((algorithm, None));\n\n } else if let Ok(sequence) = element.cast_as::<PySequence>() {\n\n let algorithm = sequence.get_item(0)?.extract::<String>()?;\n\n let algorithm = build_algorithm(&algorithm)?;\n\n\n\n let mut blending_params = BlendAlgorithmParams::new();\n\n let params_sequence = sequence.get_item(1)?;\n\n if let Ok(params_sequence) = params_sequence.cast_as::<PySequence>() {\n", "file_path": "src/pymodule/utils.rs", "rank": 12, "score": 156400.51768224218 }, { "content": "#[cfg(feature = \"wasm-extension\")]\n\npub fn write_png_parallel(\n\n file_out: String,\n\n png: &ImageBuffer<Rgba<u8>, Vec<u8>>,\n\n compression: CompressionType,\n\n filter: FilterType,\n\n) -> Result<(), PConvertError> {\n\n write_png_to_file(file_out, png, compression, filter)\n\n}\n\n\n", "file_path": "src/utils.rs", "rank": 13, "score": 154976.60684463056 }, { "content": "/// Testing utility that applies a blue-ish filter to an image\n\npub fn apply_blue_filter(pixel: &mut Rgba<u8>) {\n\n // sets red value to 0 and green value to the blue one (blue filter effect)\n\n pixel[0] = 0;\n\n pixel[1] = pixel[2];\n\n}\n", "file_path": "src/compose.rs", "rank": 14, "score": 149838.03036496625 }, { "content": "#[cfg(not(feature = \"wasm-extension\"))]\n\nfn mtpng_filter_from(filter: FilterType) -> mtpng::Filter {\n\n match filter {\n\n FilterType::Avg => mtpng::Filter::Average,\n\n FilterType::Paeth => mtpng::Filter::Paeth,\n\n FilterType::Sub => mtpng::Filter::Sub,\n\n FilterType::Up => mtpng::Filter::Up,\n\n FilterType::NoFilter => mtpng::Filter::None,\n\n _ => mtpng::Filter::None,\n\n }\n\n}\n\n\n", "file_path": "src/utils.rs", "rank": 15, "score": 138576.33902994244 }, { "content": "#[wasm_bindgen(js_name = getModuleConstants)]\n\npub fn get_module_constants_js() -> JsValue {\n\n let filters: Vec<String> = constants::FILTER_TYPES\n\n .to_vec()\n\n .iter()\n\n .map(|x| format!(\"{:?}\", x))\n\n .collect();\n\n\n\n let compressions: Vec<String> = constants::COMPRESSION_TYPES\n\n .to_vec()\n\n .iter()\n\n .map(|x| format!(\"{:?}\", x))\n\n .collect();\n\n\n\n JsValue::from_serde(&json!({\n\n \"COMPILATION_DATE\": constants::COMPILATION_DATE,\n\n \"COMPILATION_TIME\": constants::COMPILATION_TIME,\n\n \"VERSION\": constants::VERSION,\n\n \"ALGORITHMS\": constants::ALGORITHMS,\n\n \"COMPILER\": constants::COMPILER,\n\n \"COMPILER_VERSION\": constants::COMPILER_VERSION,\n", "file_path": "src/wasm/mod.rs", "rank": 16, "score": 137650.68207595017 }, { "content": "/// Encodes a PNG and writes it to a buffer.\n\n///\n\n/// # Arguments\n\n///\n\n/// * `writable_buff` - Any buffer structure that implements the `Write` trait.\n\n/// * `png` - A byte buffer with the image data.\n\n/// * `compression` - Compression type to use in the encoding.\n\n/// * `filter` - Filter type to use in the encoding.\n\npub fn encode_png(\n\n writable_buff: impl Write,\n\n png: &ImageBuffer<Rgba<u8>, Vec<u8>>,\n\n compression: CompressionType,\n\n filter: FilterType,\n\n) -> Result<(), PConvertError> {\n\n let buff = BufWriter::new(writable_buff);\n\n let encoder = PngEncoder::new_with_quality(buff, compression, filter);\n\n Ok(encoder.encode(&png, png.width(), png.height(), ColorType::Rgba8)?)\n\n}\n\n\n", "file_path": "src/utils.rs", "rank": 18, "score": 131479.94713139613 }, { "content": "/// Decodes and returns a PNG.\n\n///\n\n/// # Arguments\n\n///\n\n/// * `readable_stream` - Any structure that implements the `Read` trait.\n\n/// * `demultiply` - Whether or not to demultiply the PNG.\n\npub fn decode_png(\n\n readable_stream: impl Read,\n\n demultiply: bool,\n\n) -> Result<ImageBuffer<Rgba<u8>, Vec<u8>>, PConvertError> {\n\n let decoder = PngDecoder::new(readable_stream)?;\n\n let (width, height) = decoder.dimensions();\n\n\n\n let mut reader = decoder.into_reader()?;\n\n\n\n let mut bytes = Vec::<u8>::new();\n\n reader.read_to_end(&mut bytes)?;\n\n\n\n let mut img = ImageBuffer::from_vec(width, height, bytes).unwrap();\n\n\n\n if demultiply {\n\n demultiply_image(&mut img)\n\n }\n\n\n\n Ok(img)\n\n}\n\n\n", "file_path": "src/utils.rs", "rank": 19, "score": 131470.18228458456 }, { "content": "/// Multiplies an image buffer, running the opposite operation over the\n\n/// complete set of pixels in the image buffer.\n\n///\n\n/// # Arguments\n\n///\n\n/// * `img` - The image buffer to multiply.\n\npub fn multiply_image(img: &mut ImageBuffer<Rgba<u8>, Vec<u8>>) {\n\n for pixel in img.pixels_mut() {\n\n multiply_pixel(pixel);\n\n }\n\n}\n\n\n", "file_path": "src/blending/mod.rs", "rank": 20, "score": 128498.64155978226 }, { "content": "/// Demultiplies an image buffer, by applying the demultiply operation over the\n\n/// complete set of pixels in the provided image buffer.\n\n///\n\n/// # Arguments\n\n///\n\n/// * `img` - The image buffer to demultiply.\n\npub fn demultiply_image(img: &mut ImageBuffer<Rgba<u8>, Vec<u8>>) {\n\n for pixel in img.pixels_mut() {\n\n demultiply_pixel(pixel);\n\n }\n\n}\n\n\n", "file_path": "src/blending/mod.rs", "rank": 21, "score": 128498.64155978226 }, { "content": "#[inline]\n\npub fn blend_alpha(\n\n (bot_pixel, top_pixel): (&mut Rgba<u8>, &Rgba<u8>),\n\n _params: &Option<BlendAlgorithmParams>,\n\n) {\n\n let (rb, gb, bb, ab) = (bot_pixel[0], bot_pixel[1], bot_pixel[2], bot_pixel[3]);\n\n let (rt, gt, bt, at) = (top_pixel[0], top_pixel[1], top_pixel[2], top_pixel[3]);\n\n\n\n let abf = 1.0 * (ab as f32 / 255.0);\n\n let atf = 1.0 * (at as f32 / 255.0);\n\n let af = atf + abf * (1.0 - atf);\n\n\n\n let mut r = if af == 0.0 {\n\n 0.0\n\n } else {\n\n (rb as f32 * abf + rt as f32 * atf * (1.0 - abf)) / af\n\n };\n\n let mut g = if af == 0.0 {\n\n 0.0\n\n } else {\n\n (gb as f32 * abf + gt as f32 * atf * (1.0 - abf)) / af\n", "file_path": "src/blending/algorithms.rs", "rank": 22, "score": 128434.45248362076 }, { "content": "#[inline]\n\npub fn blend_disjoint_under(\n\n (bot_pixel, top_pixel): (&mut Rgba<u8>, &Rgba<u8>),\n\n _params: &Option<BlendAlgorithmParams>,\n\n) {\n\n let (rb, gb, bb, ab) = (bot_pixel[0], bot_pixel[1], bot_pixel[2], bot_pixel[3]);\n\n let (rt, gt, bt, at) = (top_pixel[0], top_pixel[1], top_pixel[2], top_pixel[3]);\n\n\n\n let abf = 1.0 * (ab as f32 / 255.0);\n\n let atf = 1.0 * (at as f32 / 255.0);\n\n\n\n let mut r = if atf * abf > 0.0 {\n\n rt as f32 / atf * (1.0 - abf) + rb as f32\n\n } else {\n\n rt as f32 * (1.0 - abf) + rb as f32\n\n };\n\n let mut g = if atf * abf > 0.0 {\n\n gt as f32 / atf * (1.0 - abf) + gb as f32\n\n } else {\n\n gt as f32 * (1.0 - abf) + gb as f32\n\n };\n", "file_path": "src/blending/algorithms.rs", "rank": 23, "score": 128434.45248362076 }, { "content": "#[inline]\n\npub fn blend_destination_over(\n\n (bot_pixel, top_pixel): (&mut Rgba<u8>, &Rgba<u8>),\n\n _params: &Option<BlendAlgorithmParams>,\n\n) {\n\n let (rb, gb, bb, ab) = (bot_pixel[0], bot_pixel[1], bot_pixel[2], bot_pixel[3]);\n\n let (rt, gt, bt, at) = (top_pixel[0], top_pixel[1], top_pixel[2], top_pixel[3]);\n\n\n\n let abf = 1.0 * (ab as f32 / 255.0);\n\n let atf = 1.0 * (at as f32 / 255.0);\n\n let af = atf + abf * (1.0 - atf);\n\n\n\n let mut r = if af == 0.0 {\n\n 0.0\n\n } else {\n\n (rt as f32 * atf + rb as f32 * abf * (1.0 - atf)) / af\n\n };\n\n let mut g = if af == 0.0 {\n\n 0.0\n\n } else {\n\n (gt as f32 * atf + gb as f32 * abf * (1.0 - atf)) / af\n", "file_path": "src/blending/algorithms.rs", "rank": 24, "score": 128434.45248362076 }, { "content": "#[inline]\n\npub fn blend_disjoint_over(\n\n (bot_pixel, top_pixel): (&mut Rgba<u8>, &Rgba<u8>),\n\n _params: &Option<BlendAlgorithmParams>,\n\n) {\n\n let (rb, gb, bb, ab) = (bot_pixel[0], bot_pixel[1], bot_pixel[2], bot_pixel[3]);\n\n let (rt, gt, bt, at) = (top_pixel[0], top_pixel[1], top_pixel[2], top_pixel[3]);\n\n\n\n let abf = 1.0 * (ab as f32 / 255.0);\n\n let atf = 1.0 * (at as f32 / 255.0);\n\n\n\n let mut r = if atf + abf < 1.0 {\n\n rt as f32 + rb as f32 * (1.0 - atf) / abf\n\n } else {\n\n rt as f32 + rb as f32\n\n };\n\n let mut g = if atf + abf < 1.0 {\n\n gt as f32 + gb as f32 * (1.0 - atf) / abf\n\n } else {\n\n gt as f32 + gb as f32\n\n };\n", "file_path": "src/blending/algorithms.rs", "rank": 25, "score": 128434.45248362076 }, { "content": "#[inline]\n\npub fn blend_multiplicative(\n\n (bot_pixel, top_pixel): (&mut Rgba<u8>, &Rgba<u8>),\n\n _params: &Option<BlendAlgorithmParams>,\n\n) {\n\n let (rb, gb, bb, ab) = (bot_pixel[0], bot_pixel[1], bot_pixel[2], bot_pixel[3]);\n\n let (rt, gt, bt, at) = (top_pixel[0], top_pixel[1], top_pixel[2], top_pixel[3]);\n\n\n\n let atf = 1.0 * (at as f32 / 255.0);\n\n\n\n let mut r = rb as f32 * (1.0 - atf) + rt as f32 * atf;\n\n let mut g = gb as f32 * (1.0 - atf) + gt as f32 * atf;\n\n let mut b = bb as f32 * (1.0 - atf) + bt as f32 * atf;\n\n let a = max(0, min(255, at as u16 + ab as u16));\n\n\n\n r = max(0.0, min(255.0, r));\n\n g = max(0.0, min(255.0, g));\n\n b = max(0.0, min(255.0, b));\n\n\n\n bot_pixel[0] = r as u8;\n\n bot_pixel[1] = g as u8;\n\n bot_pixel[2] = b as u8;\n\n bot_pixel[3] = a as u8;\n\n}\n\n\n", "file_path": "src/blending/algorithms.rs", "rank": 26, "score": 128434.45248362076 }, { "content": "#[inline]\n\npub fn blend_source_over(\n\n (bot_pixel, top_pixel): (&mut Rgba<u8>, &Rgba<u8>),\n\n _params: &Option<BlendAlgorithmParams>,\n\n) {\n\n let (rb, gb, bb, ab) = (bot_pixel[0], bot_pixel[1], bot_pixel[2], bot_pixel[3]);\n\n let (rt, gt, bt, at) = (top_pixel[0], top_pixel[1], top_pixel[2], top_pixel[3]);\n\n\n\n let abf = 1.0 * (ab as f32 / 255.0);\n\n let atf = 1.0 * (at as f32 / 255.0);\n\n let af = abf + atf * (1.0 - abf);\n\n\n\n let mut r = if af == 0.0 {\n\n 0.0\n\n } else {\n\n (rb as f32 * abf + rt as f32 * atf * (1.0 - abf)) / af\n\n };\n\n let mut g = if af == 0.0 {\n\n 0.0\n\n } else {\n\n (gb as f32 * abf + gt as f32 * atf * (1.0 - abf)) / af\n", "file_path": "src/blending/algorithms.rs", "rank": 27, "score": 128434.45248362076 }, { "content": "/// Writes a PNG to the local file system using the provided compression\n\n/// and filter definitions.\n\n///\n\n/// # Arguments\n\n///\n\n/// * `file_out` - Local file system path where to write the PNG file.\n\n/// * `png` - A byte buffer with the image data.\n\n/// * `compression` - Compression type to use in the encoding.\n\n/// * `filter` - Filter type to use in the encoding.\n\npub fn write_png_to_file(\n\n file_out: String,\n\n png: &ImageBuffer<Rgba<u8>, Vec<u8>>,\n\n compression: CompressionType,\n\n filter: FilterType,\n\n) -> Result<(), PConvertError> {\n\n let file = File::create(&file_out)?;\n\n encode_png(file, png, compression, filter)\n\n}\n\n\n", "file_path": "src/utils.rs", "rank": 28, "score": 128117.95050539073 }, { "content": "/// Logs one line (algorithm, compression, filter, blend time, read time, write time)\n\n/// of the benchmarks table to the browser console (with `console.log`).\n\npub fn log_benchmark(\n\n algorithm: String,\n\n compression: CompressionType,\n\n filter: FilterType,\n\n blend_time: f64,\n\n read_time: f64,\n\n write_time: f64,\n\n) {\n\n console_log!(\n\n \"{:<20}{:<20}{:<20}{:<20}\",\n\n algorithm,\n\n format!(\"{:#?}\", compression),\n\n format!(\"{:#?}\", filter),\n\n format!(\n\n \"{}ms (blend {}ms, read {}ms, write {}ms)\",\n\n read_time + blend_time + write_time,\n\n blend_time,\n\n read_time,\n\n write_time\n\n )\n\n );\n\n}\n\n\n", "file_path": "src/wasm/utils.rs", "rank": 29, "score": 128115.5922672837 }, { "content": "/// Writes a PNG to the local file system using the default\n\n/// compression and filter settings.\n\n///\n\n/// Avoid the usage of external enumeration values.\n\n///\n\n/// # Arguments\n\n///\n\n/// * `file_out` - Local file system path where to write the PNG file.\n\n/// * `png` - A byte buffer with the image data.\n\npub fn write_png_to_file_d(\n\n file_out: String,\n\n png: &ImageBuffer<Rgba<u8>, Vec<u8>>,\n\n) -> Result<(), PConvertError> {\n\n let file = File::create(&file_out)?;\n\n encode_png(file, png, CompressionType::Fast, FilterType::NoFilter)\n\n}\n\n\n\n/// [NOT SUPPORTED IN WASM] Multi-threaded write version of a\n\n/// PNG to the local file system.\n\n///\n\n/// # Arguments\n\n///\n\n/// * `file_out` - Local file system path where to write the PNG file.\n\n/// * `png` - A byte buffer with the image data.\n\n/// * `compression` - Compression type to use in the encoding.\n\n/// * `filter` - Filter type to use in the encoding.\n", "file_path": "src/utils.rs", "rank": 30, "score": 128114.60150123943 }, { "content": "/// Receives png buffer data and encodes it as a `File` with specified\n\n/// `CompressionType` and `FilterType`.\n\npub fn encode_file(\n\n image_buffer: ImageBuffer<Rgba<u8>, Vec<u8>>,\n\n compression: CompressionType,\n\n filter: FilterType,\n\n target_file_name: String,\n\n) -> Result<File, JsValue> {\n\n let mut encoded_data = Vec::<u8>::with_capacity(image_buffer.to_vec().capacity());\n\n encode_png(&mut encoded_data, &image_buffer, compression, filter)?;\n\n\n\n unsafe {\n\n let array_buffer = Uint8Array::view(&encoded_data);\n\n File::new_with_u8_array_sequence(&Array::of1(&array_buffer), &target_file_name)\n\n }\n\n}\n\n\n", "file_path": "src/wasm/utils.rs", "rank": 31, "score": 128113.59689356436 }, { "content": "/// Reads a PNG from the local file system.\n\n///\n\n/// # Arguments\n\n///\n\n/// * `file_in` - Local file system path to the PNG file.\n\n/// * `demultiply` - Whether or not to demultiply the PNG.\n\npub fn read_png_from_file(\n\n file_in: String,\n\n demultiply: bool,\n\n) -> Result<ImageBuffer<Rgba<u8>, Vec<u8>>, PConvertError> {\n\n let file = File::open(file_in)?;\n\n decode_png(file, demultiply)\n\n}\n\n\n", "file_path": "src/utils.rs", "rank": 32, "score": 128107.44603542931 }, { "content": "/// Attempts to build a vector of blending operations and extra parameters.\n\n/// One pair per blending operation. Returns a `PConvertError` if it fails parsing.\n\npub fn build_params(\n\n algorithms: &[JsValue],\n\n) -> Result<Vec<(BlendAlgorithm, Option<BlendAlgorithmParams>)>, PConvertError> {\n\n let mut result = Vec::new();\n\n\n\n for algorithm in algorithms {\n\n if algorithm.is_string() {\n\n let algorithm =\n\n build_algorithm(&algorithm.as_string().unwrap_or_else(|| \"multiplicative\".to_string()))?;\n\n\n\n result.push((algorithm, None));\n\n } else if algorithm.is_object() {\n\n let params: JSONParams = algorithm.into_serde::<JSONParams>().unwrap();\n\n let algorithm = build_algorithm(&params.algorithm)?;\n\n\n\n let mut blending_params = BlendAlgorithmParams::new();\n\n for (param_name, param_value) in params.params {\n\n let param_value: Value = param_value.into();\n\n blending_params.insert(param_name, param_value);\n\n }\n\n\n\n result.push((algorithm, Some(blending_params)));\n\n }\n\n }\n\n\n\n Ok(result)\n\n}\n\n\n", "file_path": "src/wasm/utils.rs", "rank": 33, "score": 128107.44603542931 }, { "content": "/// Blends two images buffers with the given blending function and\n\n/// optional parameters.\n\n///\n\n/// # Arguments\n\n///\n\n/// * `bot` - An image buffer corresponding to the bottom layer, in typical\n\n/// composition language this should be considered the `source`.\n\n/// * `top` - An image buffer corresponding to the top layer, in typical\n\n/// composition language this should be considered the `destination`.\n\n/// * `blending_algorithm` - A function that blends two pixels according\n\n/// to optional blending parameters.\n\n/// * `algorithm_params` - A optional map of key-value pairs of blending\n\n/// properties and values.\n\n///\n\n/// # Examples\n\n///\n\n/// ```no_run\n\n/// use pconvert_rust::blending::{blend_images, get_blending_algorithm, BlendAlgorithm};\n\n/// use pconvert_rust::utils::read_png_from_file;\n\n///\n\n/// let mut bot = read_png_from_file(\"bot.png\".to_string(), false).unwrap();\n\n/// let top = read_png_from_file(\"top.png\".to_string(), false).unwrap();\n\n/// let algorithm_fn = get_blending_algorithm(&BlendAlgorithm::Alpha);\n\n///\n\n/// blend_images(&mut bot, &top, &algorithm_fn, &None);\n\n/// ```\n\npub fn blend_images(\n\n bot: &mut ImageBuffer<Rgba<u8>, Vec<u8>>,\n\n top: &ImageBuffer<Rgba<u8>, Vec<u8>>,\n\n blending_algorithm: &impl Fn((&mut Rgba<u8>, &Rgba<u8>), &Option<BlendAlgorithmParams>),\n\n algorithm_params: &Option<BlendAlgorithmParams>,\n\n) {\n\n for pixel_pair in bot.pixels_mut().zip(top.pixels()) {\n\n blending_algorithm(pixel_pair, algorithm_params);\n\n }\n\n}\n\n\n", "file_path": "src/blending/mod.rs", "rank": 34, "score": 127463.56841691904 }, { "content": "#[inline]\n\npub fn blend_disjoint_debug(\n\n (bot_pixel, top_pixel): (&mut Rgba<u8>, &Rgba<u8>),\n\n _params: &Option<BlendAlgorithmParams>,\n\n) {\n\n let ab = bot_pixel[3];\n\n let at = top_pixel[3];\n\n\n\n let abf = 1.0 * (ab as f32 / 255.0);\n\n let atf = 1.0 * (at as f32 / 255.0);\n\n\n\n let mut r = if atf + abf < 1.0 { 0 } else { 255 };\n\n let mut g = if atf + abf < 1.0 { 255 } else { 0 };\n\n let mut b = 0;\n\n let a = max(0, min(255, at as u16 + ab as u16));\n\n\n\n r = max(0, min(255, r));\n\n g = max(0, min(255, g));\n\n b = max(0, min(255, b));\n\n\n\n bot_pixel[0] = r;\n\n bot_pixel[1] = g;\n\n bot_pixel[2] = b;\n\n bot_pixel[3] = a as u8;\n\n}\n", "file_path": "src/blending/algorithms.rs", "rank": 35, "score": 125312.04837119009 }, { "content": "#[inline]\n\npub fn blend_first_bottom(\n\n (bot_pixel, top_pixel): (&mut Rgba<u8>, &Rgba<u8>),\n\n _params: &Option<BlendAlgorithmParams>,\n\n) {\n\n let (rb, gb, bb, ab) = (bot_pixel[0], bot_pixel[1], bot_pixel[2], bot_pixel[3]);\n\n let (rt, gt, bt, at) = (top_pixel[0], top_pixel[1], top_pixel[2], top_pixel[3]);\n\n\n\n let mut r = if ab == 0 { rt } else { rb };\n\n let mut g = if ab == 0 { gt } else { gb };\n\n let mut b = if ab == 0 { bt } else { bb };\n\n let mut a = if ab == 0 { at } else { ab };\n\n\n\n r = max(0, min(255, r));\n\n g = max(0, min(255, g));\n\n b = max(0, min(255, b));\n\n a = max(0, min(255, a));\n\n\n\n bot_pixel[0] = r;\n\n bot_pixel[1] = g;\n\n bot_pixel[2] = b;\n\n bot_pixel[3] = a;\n\n}\n\n\n", "file_path": "src/blending/algorithms.rs", "rank": 36, "score": 125312.04837119009 }, { "content": "#[inline]\n\npub fn blend_mask_top(\n\n (bot_pixel, top_pixel): (&mut Rgba<u8>, &Rgba<u8>),\n\n params: &Option<BlendAlgorithmParams>,\n\n) {\n\n let (rb, gb, bb, ab) = (bot_pixel[0], bot_pixel[1], bot_pixel[2], bot_pixel[3]);\n\n let (rt, gt, bt, at) = (top_pixel[0], top_pixel[1], top_pixel[2], top_pixel[3]);\n\n\n\n let factor = params\n\n .as_ref()\n\n .and_then(|params| params.get(\"factor\"))\n\n .and_then(|param| match param {\n\n Value::Float(float) => Some(*float),\n\n _ => None,\n\n })\n\n .unwrap_or(1.0) as f32;\n\n\n\n let atf = factor * (at as f32 / 255.0);\n\n let abf = 1.0 - atf;\n\n\n\n let mut r = rb as f32 * abf + rt as f32 * atf;\n", "file_path": "src/blending/algorithms.rs", "rank": 37, "score": 125312.04837119009 }, { "content": "#[inline]\n\npub fn blend_first_top(\n\n (bot_pixel, top_pixel): (&mut Rgba<u8>, &Rgba<u8>),\n\n _params: &Option<BlendAlgorithmParams>,\n\n) {\n\n let (rb, gb, bb, ab) = (bot_pixel[0], bot_pixel[1], bot_pixel[2], bot_pixel[3]);\n\n let (rt, gt, bt, at) = (top_pixel[0], top_pixel[1], top_pixel[2], top_pixel[3]);\n\n\n\n let mut r = if at == 0 { rb } else { rt };\n\n let mut g = if at == 0 { gb } else { gt };\n\n let mut b = if at == 0 { bb } else { bt };\n\n let mut a = if at == 0 { ab } else { at };\n\n\n\n r = max(0, min(255, r));\n\n g = max(0, min(255, g));\n\n b = max(0, min(255, b));\n\n a = max(0, min(255, a));\n\n\n\n bot_pixel[0] = r;\n\n bot_pixel[1] = g;\n\n bot_pixel[2] = b;\n\n bot_pixel[3] = a;\n\n}\n\n\n", "file_path": "src/blending/algorithms.rs", "rank": 38, "score": 125312.04837119009 }, { "content": "/// Receives png buffer data and encodes it as an `ImageData` object with\n\n/// specified `CompressionType` and `FilterType`.\n\npub fn encode_image_data(\n\n image_buffer: ImageBuffer<Rgba<u8>, Vec<u8>>,\n\n compression: CompressionType,\n\n filter: FilterType,\n\n) -> Result<ImageData, JsValue> {\n\n let (width, height) = image_buffer.dimensions();\n\n\n\n let mut encoded_data = Vec::<u8>::with_capacity(image_buffer.to_vec().capacity());\n\n encode_png(&mut encoded_data, &image_buffer, compression, filter)?;\n\n\n\n let bytes = &mut image_buffer.to_vec();\n\n let clamped_bytes: Clamped<&[u8]> = Clamped(bytes);\n\n\n\n ImageData::new_with_u8_clamped_array_and_sh(clamped_bytes, width, height)\n\n}\n\n\n", "file_path": "src/wasm/utils.rs", "rank": 39, "score": 125003.2833586213 }, { "content": "/// Logs the header/column names of the benchmarks table to the browser\n\n/// console (with `console.log`).\n\npub fn log_benchmark_header() {\n\n console_log!(\n\n \"{:<20}{:<20}{:<20}{:<20}\",\n\n \"Algorithm\",\n\n \"Compression\",\n\n \"Filter\",\n\n \"Times\"\n\n );\n\n}\n\n\n", "file_path": "src/wasm/utils.rs", "rank": 40, "score": 124997.3245791542 }, { "content": "/// Blends two image buffers using `algorithm` and the extra\n\n/// `options` given. Algorithm defaults to `BlendAlgorithm::Multiplicative`.\n\npub fn blend_image_buffers(\n\n bot: &mut ImageBuffer<Rgba<u8>, Vec<u8>>,\n\n top: &mut ImageBuffer<Rgba<u8>, Vec<u8>>,\n\n algorithm: Option<String>,\n\n is_inline: Option<bool>,\n\n) -> Result<(), PConvertError> {\n\n let algorithm = algorithm.unwrap_or_else(|| String::from(\"multiplicative\"));\n\n let algorithm = build_algorithm(&algorithm)?;\n\n let algorithm_fn = get_blending_algorithm(&algorithm);\n\n let demultiply = is_algorithm_multiplied(&algorithm);\n\n let _is_inline = is_inline.unwrap_or(false);\n\n\n\n if demultiply {\n\n demultiply_image(bot);\n\n demultiply_image(top);\n\n }\n\n\n\n blend_images(bot, &top, &algorithm_fn, &None);\n\n Ok(())\n\n}\n", "file_path": "src/wasm/mod.rs", "rank": 41, "score": 124369.57146912292 }, { "content": "#[wasm_bindgen(js_name = blendMultipleFs)]\n\npub fn blend_multiple_fs(\n\n image_paths: Vec<JsValue>,\n\n out_path: String,\n\n algorithm: Option<String>,\n\n algorithms: Option<Vec<JsValue>>,\n\n is_inline: Option<bool>,\n\n options: JsValue,\n\n) -> Result<(), JsValue> {\n\n let num_images = image_paths.len();\n\n\n\n if num_images < 1 {\n\n return Err(PConvertError::ArgumentError(\n\n \"ArgumentError: 'img_paths' must contain at least one path\".to_string(),\n\n )\n\n .into());\n\n }\n\n\n\n let options = match options.is_object() {\n\n true => options.into_serde::<HashMap<String, JSONValue>>().ok(),\n\n false => None,\n", "file_path": "src/wasm/mod.rs", "rank": 42, "score": 124359.8935160872 }, { "content": "#[wasm_bindgen(js_name = blendMultipleData)]\n\npub fn blend_multiple_data_js(\n\n images: &JsValue,\n\n algorithm: Option<String>,\n\n algorithms: Option<Vec<JsValue>>,\n\n is_inline: Option<bool>,\n\n options: JsValue,\n\n) -> Result<ImageData, JsValue> {\n\n let options = match options.is_object() {\n\n true => options.into_serde::<HashMap<String, JSONValue>>().ok(),\n\n false => None,\n\n };\n\n\n\n let mut image_buffers: Vec<RgbaImage> = Vec::new();\n\n let mut images = try_iter(images).unwrap().unwrap();\n\n while let Some(Ok(img_data)) = images.next() {\n\n let img_data: ImageData = img_data.into();\n\n let img_buffer: RgbaImage = ImageBuffer::from_vec(\n\n img_data.width(),\n\n img_data.height(),\n\n img_data.data().to_vec(),\n", "file_path": "src/wasm/mod.rs", "rank": 43, "score": 121498.0277520527 }, { "content": "#[wasm_bindgen(js_name = blendImagesData)]\n\npub fn blend_images_data_js(\n\n bot: ImageData,\n\n top: ImageData,\n\n algorithm: Option<String>,\n\n is_inline: Option<bool>,\n\n options: JsValue,\n\n) -> Result<ImageData, JsValue> {\n\n let options = match options.is_object() {\n\n true => options.into_serde::<HashMap<String, JSONValue>>().ok(),\n\n false => None,\n\n };\n\n\n\n let (width, height) = (bot.width(), bot.height());\n\n let mut bot = ImageBuffer::from_vec(width, height, bot.data().to_vec())\n\n .ok_or_else(|| PConvertError::ArgumentError(\"Could not parse \\\"bot\\\"\".to_string()))?;\n\n let mut top = ImageBuffer::from_vec(width, height, top.data().to_vec())\n\n .ok_or_else(|| PConvertError::ArgumentError(\"Could not parse \\\"top\\\"\".to_string()))?;\n\n\n\n blend_image_buffers(&mut bot, &mut top, algorithm, is_inline)?;\n\n\n\n encode_image_data(\n\n bot,\n\n get_compression_type(&options),\n\n get_filter_type(&options),\n\n )\n\n}\n\n\n", "file_path": "src/wasm/mod.rs", "rank": 44, "score": 121498.0277520527 }, { "content": "/// Minimum of two values that implement the `PartialOrd` trait.\n\npub fn min<T: PartialOrd>(x: T, y: T) -> T {\n\n if x < y {\n\n x\n\n } else {\n\n y\n\n }\n\n}\n", "file_path": "src/utils.rs", "rank": 45, "score": 115940.19235329074 }, { "content": "/// Maximum of two values that implement the `PartialOrd` trait.\n\npub fn max<T: PartialOrd>(x: T, y: T) -> T {\n\n if x > y {\n\n x\n\n } else {\n\n y\n\n }\n\n}\n\n\n", "file_path": "src/utils.rs", "rank": 46, "score": 115940.19235329074 }, { "content": "pub fn pconvert(args: &mut env::Args) -> Result<(), PConvertError> {\n\n let file_in = match args.next() {\n\n Some(name) => name,\n\n None => {\n\n return Err(PConvertError::ArgumentError(\n\n \"ArgumentError: 'file_in' not specified\".to_string(),\n\n ))\n\n }\n\n };\n\n\n\n let file_out = match args.next() {\n\n Some(name) => name,\n\n None => {\n\n return Err(PConvertError::ArgumentError(\n\n \"ArgumentError: 'file_out' not specified\".to_string(),\n\n ))\n\n }\n\n };\n\n\n\n let mut img = read_png_from_file(file_in, false)?;\n\n\n\n for pixel in img.pixels_mut() {\n\n apply_blue_filter(pixel);\n\n }\n\n\n\n img.save_with_format(file_out, ImageFormat::Png)?;\n\n\n\n Ok(())\n\n}\n\n\n", "file_path": "src/cli.rs", "rank": 47, "score": 114148.56214610534 }, { "content": "pub fn pbenchmark(args: &mut env::Args) -> Result<(), PConvertError> {\n\n let dir = match args.next() {\n\n Some(name) => {\n\n if name.ends_with('/') {\n\n name\n\n } else {\n\n format!(\"{}/\", name)\n\n }\n\n }\n\n None => {\n\n return Err(PConvertError::ArgumentError(\n\n \"ArgumentError: 'directory' not specified\".to_string(),\n\n ))\n\n }\n\n };\n\n\n\n let run_parallel = match args.next() {\n\n Some(flag) => flag.eq(\"--parallel\"),\n\n _ => false,\n\n };\n", "file_path": "src/cli.rs", "rank": 48, "score": 114148.56214610534 }, { "content": "pub fn pcompose(args: &mut env::Args) -> Result<(), PConvertError> {\n\n let dir = match args.next() {\n\n Some(name) => {\n\n if name.ends_with('/') {\n\n name\n\n } else {\n\n format!(\"{}/\", name)\n\n }\n\n }\n\n None => {\n\n return Err(PConvertError::ArgumentError(\n\n \"ArgumentError: 'directory' not specified\".to_string(),\n\n ))\n\n }\n\n };\n\n\n\n let mut benchmark = Benchmark::new();\n\n\n\n let backgrounds = vec![\n\n Background::Alpha,\n", "file_path": "src/cli.rs", "rank": 49, "score": 114148.56214610534 }, { "content": "fn multiply_pixel(pixel: &mut Rgba<u8>) {\n\n let (r, g, b, a) = (pixel[0], pixel[1], pixel[2], pixel[3]);\n\n let af = a as f32 / 255.0;\n\n\n\n let r = (r as f32 / af).round() as u8;\n\n let g = (g as f32 / af).round() as u8;\n\n let b = (b as f32 / af).round() as u8;\n\n\n\n pixel[0] = r;\n\n pixel[1] = g;\n\n pixel[2] = b;\n\n}\n", "file_path": "src/blending/mod.rs", "rank": 50, "score": 112434.65239103712 }, { "content": "fn demultiply_pixel(pixel: &mut Rgba<u8>) {\n\n let (r, g, b, a) = (pixel[0], pixel[1], pixel[2], pixel[3]);\n\n let af = a as f32 / 255.0;\n\n\n\n let r = (r as f32 * af).round() as u8;\n\n let g = (g as f32 * af).round() as u8;\n\n let b = (b as f32 * af).round() as u8;\n\n\n\n pixel[0] = r;\n\n pixel[1] = g;\n\n pixel[2] = b;\n\n}\n\n\n", "file_path": "src/blending/mod.rs", "rank": 51, "score": 112434.65239103712 }, { "content": "#[cfg(not(feature = \"wasm-extension\"))]\n\nfn mtpng_compression_from(compression: CompressionType) -> mtpng::CompressionLevel {\n\n match compression {\n\n CompressionType::Default => mtpng::CompressionLevel::Default,\n\n CompressionType::Best => mtpng::CompressionLevel::High,\n\n CompressionType::Fast => mtpng::CompressionLevel::Fast,\n\n _ => mtpng::CompressionLevel::Fast,\n\n }\n\n}\n\n\n", "file_path": "src/utils.rs", "rank": 52, "score": 106991.88594984193 }, { "content": "/// Testing utility that composes an image made up of the specified\n\n/// background image, using the specified algorithm, compression and filter types.\n\n/// Looks for the layers and outputs the final composition to the given `dir` and\n\n/// takes track of times spent in each phase in the benchmark struct\n\npub fn compose(\n\n dir: &str,\n\n algorithm: BlendAlgorithm,\n\n background: &Background,\n\n compression: CompressionType,\n\n filter: FilterType,\n\n benchmark: &mut Benchmark,\n\n) -> Result<String, PConvertError> {\n\n let demultiply = is_algorithm_multiplied(&algorithm);\n\n\n\n let algorithm_fn = get_blending_algorithm(&algorithm);\n\n\n\n // reads one PNG at the time and blends it with the current result\n\n // these values are hardcoded by the multiple layer files\n\n let background_file = format!(\"background_{}.png\", background);\n\n let png_file_names = vec![\n\n \"sole.png\",\n\n \"back.png\",\n\n \"front.png\",\n\n \"shoelace.png\",\n", "file_path": "src/compose.rs", "rank": 53, "score": 104610.81853440001 }, { "content": "pub fn pversion() {\n\n println!(\n\n \"P(NG)Convert Rust {} ({} {}) [{} {} {} bit] [libpng {}] {:?}\",\n\n constants::VERSION,\n\n constants::COMPILATION_DATE,\n\n constants::COMPILATION_TIME,\n\n constants::COMPILER,\n\n constants::COMPILER_VERSION,\n\n constants::PLATFORM_CPU_BITS,\n\n constants::LIBPNG_VERSION,\n\n constants::FEATURES\n\n );\n\n println!(\"Copyright (c) 2008-2021 Platforme International Limited. All rights reserved.\");\n\n}\n", "file_path": "src/cli.rs", "rank": 54, "score": 104598.7925214837 }, { "content": "/// Multi-threaded version of the `compose` testing utility\n\n/// Reads each PNG in a different thread and makes use of the\n\n/// `mtpng` library to write the final composition\n\npub fn compose_parallel(\n\n dir: &str,\n\n algorithm: BlendAlgorithm,\n\n background: &Background,\n\n compression: CompressionType,\n\n filter: FilterType,\n\n benchmark: &mut Benchmark,\n\n) -> Result<String, PConvertError> {\n\n let demultiply = is_algorithm_multiplied(&algorithm);\n\n let algorithm_fn = get_blending_algorithm(&algorithm);\n\n\n\n let mut thread_pool = ThreadPool::new(THREAD_POOL_SIZE)?;\n\n thread_pool.start();\n\n\n\n // sends the PNG reading tasks to multiple threads\n\n // these values are hardcoded by the multiple layer files\n\n let background_file = format!(\"background_{}.png\", background);\n\n let png_file_names = vec![\n\n \"sole.png\",\n\n \"back.png\",\n", "file_path": "src/compose.rs", "rank": 56, "score": 102196.48739283104 }, { "content": "pub fn print_usage() {\n\n println!(\"Usage: pconvert-rust <command> [args...]\\nwhere command can be one of the following: compose, convert, benchmark, version\");\n\n}\n\n\n", "file_path": "src/cli.rs", "rank": 57, "score": 102190.78323746576 }, { "content": "/// Wrapper function for nodejs `fs.readFileSync`.\n\npub fn node_read_file_sync(fs: &NodeFs, path: &str) -> Vec<u8> {\n\n fs.readFileSync(path)\n\n}\n\n\n", "file_path": "src/wasm/utils.rs", "rank": 58, "score": 90721.6470865893 }, { "content": "/// Wrapper function for nodejs `fs.writeFileSync`.\n\npub fn node_write_file_sync(fs: &NodeFs, path: &str, data: &[u8]) {\n\n fs.writeFileSync(path, data);\n\n}\n", "file_path": "src/wasm/utils.rs", "rank": 59, "score": 90721.6470865893 }, { "content": "/// Rust Future from nodejs `fs.readFile` Promise (awaitable in node).\n\npub fn node_read_file_async(fs: &NodeFs, path: &str) -> wasm_bindgen_futures::JsFuture {\n\n let promise = js_sys::Promise::new(&mut |resolve, reject| {\n\n let callback = js_sys::Function::new_with_args(\n\n \"resolve, reject, err, data\",\n\n \"err ? reject(err) : resolve(data);\",\n\n )\n\n .bind2(&JsValue::NULL, &resolve, &reject);\n\n fs.readFile(path, callback)\n\n });\n\n\n\n wasm_bindgen_futures::JsFuture::from(promise)\n\n}\n\n\n", "file_path": "src/wasm/utils.rs", "rank": 60, "score": 85835.44518137931 }, { "content": "#[test]\n\nfn test_convert() {\n\n let file_in = format!(\"{}{}\", TEST_DIR, TEST_FILE);\n\n let mut img = read_png_from_file(file_in.clone(), false)\n\n .unwrap_or_else(|_| panic!(\"failure reading {}\", file_in));\n\n\n\n for pixel in img.pixels_mut() {\n\n apply_blue_filter(pixel);\n\n }\n\n\n\n let out = format!(\"{}{}\", TEST_DIR, TEST_FILE_OUT);\n\n img.save_with_format(out.clone(), ImageFormat::Png)\n\n .unwrap_or_else(|_| panic!(\"failure writing {}\", out));\n\n}\n", "file_path": "src/test/mod.rs", "rank": 61, "score": 80638.74231939245 }, { "content": "#[test]\n\nfn test_benchmark() {\n\n let mut benchmark1 = Benchmark::new();\n\n Benchmark::add_blend_time(&mut benchmark1, 100);\n\n Benchmark::add_read_png_time(&mut benchmark1, 200);\n\n Benchmark::add_write_png_time(&mut benchmark1, 150);\n\n\n\n assert!(benchmark1.total() == 100 + 200 + 150);\n\n\n\n let mut benchmark2 = Benchmark::new();\n\n Benchmark::add_blend_time(&mut benchmark2, 50);\n\n Benchmark::add_read_png_time(&mut benchmark2, 100);\n\n Benchmark::add_write_png_time(&mut benchmark2, 75);\n\n\n\n assert!(benchmark2.total() == 50 + 100 + 75);\n\n\n\n let sum_benchmark = benchmark1 + benchmark2;\n\n assert!(sum_benchmark.total() == 100 + 200 + 150 + 50 + 100 + 75);\n\n}\n\n\n", "file_path": "src/test/mod.rs", "rank": 62, "score": 80638.74231939245 }, { "content": "#[test]\n\nfn test_compose() {\n\n let mut benchmark = Benchmark::new();\n\n let backgrounds = vec![\n\n Background::Alpha,\n\n Background::Blue,\n\n Background::Texture,\n\n Background::White,\n\n ];\n\n\n\n // composes with different combinations of blending algorithms and backgrounds\n\n for background in &backgrounds {\n\n for algorithm in constants::ALGORITHMS.iter() {\n\n compose(\n\n &TEST_DIR,\n\n BlendAlgorithm::from_str(algorithm).unwrap(),\n\n background,\n\n CompressionType::Fast,\n\n FilterType::NoFilter,\n\n &mut benchmark,\n\n )\n\n .unwrap_or_else(|_| panic!(\"failed composing with algorithm={} background={} compression=Fast filter=NoFilter\", algorithm, background));\n\n }\n\n }\n\n}\n\n\n", "file_path": "src/test/mod.rs", "rank": 63, "score": 80638.74231939245 }, { "content": "fn blend_multiple_buffers(\n\n image_buffers: Vec<ImageBuffer<Rgba<u8>, Vec<u8>>>,\n\n algorithm: Option<String>,\n\n algorithms: Option<Vec<JsValue>>,\n\n is_inline: Option<bool>,\n\n) -> Result<ImageBuffer<Rgba<u8>, Vec<u8>>, PConvertError> {\n\n let num_images = image_buffers.len();\n\n if num_images < 1 {\n\n return Err(PConvertError::ArgumentError(\n\n \"'images' must contain at least one path\".to_string(),\n\n ));\n\n }\n\n\n\n if algorithms.is_some() && algorithms.as_ref().unwrap().len() != num_images - 1 {\n\n return Err(PConvertError::ArgumentError(format!(\n\n \"'algorithms' must be of size {} (one per blending operation)\",\n\n num_images - 1\n\n )));\n\n };\n\n\n", "file_path": "src/wasm/mod.rs", "rank": 64, "score": 78424.57435074756 }, { "content": "#[test]\n\nfn test_compose_parallel() {\n\n let mut benchmark = Benchmark::new();\n\n let backgrounds = vec![\n\n Background::Alpha,\n\n Background::Blue,\n\n Background::Texture,\n\n Background::White,\n\n ];\n\n\n\n // composes with different combinations of blending algorithms and backgrounds\n\n for background in backgrounds {\n\n for algorithm in constants::ALGORITHMS.iter() {\n\n compose_parallel(\n\n &TEST_DIR,\n\n BlendAlgorithm::from_str(algorithm).unwrap(),\n\n &background,\n\n CompressionType::Fast,\n\n FilterType::NoFilter,\n\n &mut benchmark,\n\n )\n\n .unwrap_or_else(|_| panic!(\"failed composing with algorithm={} background={} compression=Fast filter=NoFilter\", algorithm, background));\n\n }\n\n }\n\n}\n\n\n", "file_path": "src/test/mod.rs", "rank": 65, "score": 78424.57435074756 }, { "content": "fn write_str_constant_to_file(file: &mut File, key: &str, val: &str) {\n\n writeln!(file, \"pub const {}: &str = \\\"{}\\\";\", key, val)\n\n .unwrap_or_else(|_| panic!(\"Failed to write '{}' to 'build_constants.rs'\", key));\n\n}\n\n\n", "file_path": "build.rs", "rank": 66, "score": 76466.37343935552 }, { "content": "fn write_constant_to_file<T>(file: &mut File, key: &str, val: T)\n\nwhere\n\n T: std::fmt::Display,\n\n{\n\n writeln!(\n\n file,\n\n \"pub const {}: {} = {};\",\n\n key,\n\n std::any::type_name::<T>(),\n\n val\n\n )\n\n .unwrap_or_else(|_| panic!(\"Failed to write '{}' to 'build_constants.rs'\", key));\n\n}\n\n\n", "file_path": "build.rs", "rank": 67, "score": 74741.92693558674 }, { "content": "fn write_vec_constant_to_file<T>(file: &mut File, key: &str, vec: Vec<T>)\n\nwhere\n\n T: std::fmt::Display,\n\n{\n\n let mut list_str = String::new();\n\n for value in &vec {\n\n list_str.push_str(&format!(\"\\\"{}\\\",\", value))\n\n }\n\n list_str.pop();\n\n writeln!(\n\n file,\n\n \"pub const {}: [{}; {}] = [{}];\",\n\n key,\n\n std::any::type_name::<T>(),\n\n vec.len(),\n\n list_str\n\n )\n\n .unwrap_or_else(|_| panic!(\"Failed to write '{}' to 'build_constants.rs'\", key));\n\n}\n\n\n", "file_path": "build.rs", "rank": 68, "score": 70509.6934192343 }, { "content": "fn write_enum_variants_to_file<T>(file: &mut File, key: &str, vec: Vec<T>)\n\nwhere\n\n T: std::fmt::Debug,\n\n{\n\n let mut list_str = String::new();\n\n for value in &vec {\n\n list_str.push_str(&format!(\"{}::{:?},\", std::any::type_name::<T>(), value))\n\n }\n\n list_str.pop();\n\n writeln!(\n\n file,\n\n \"pub const {}: [{}; {}] = [{}];\",\n\n key,\n\n std::any::type_name::<T>(),\n\n vec.len(),\n\n list_str\n\n )\n\n .unwrap_or_else(|_| panic!(\"Failed to write '{}' to 'build_constants.rs'\", key));\n\n}\n", "file_path": "build.rs", "rank": 69, "score": 70509.6934192343 }, { "content": "#!/usr/bin/python\n\n# -*- coding: utf-8 -*-\n\n\n\nimport os\n\nimport pconvert_rust as pconvert\n\n\n\nPATH_TO_ASSETS = os.path.join(os.path.dirname(__file__), \"../../assets/demo/\")\n\n\n\nprint(f\"VERSION: {pconvert.VERSION}\")\n\nprint(f\"COMPILED ON: {pconvert.COMPILATION_DATE}, {pconvert.COMPILATION_TIME}\")\n\n\n\npconvert.blend_multiple(\n\n (\n\n os.path.abspath(f\"{PATH_TO_ASSETS}sole.png\"),\n\n os.path.abspath(f\"{PATH_TO_ASSETS}back.png\"),\n\n os.path.abspath(f\"{PATH_TO_ASSETS}front.png\")\n\n ),\n\n os.path.abspath(\"result.basic.png\")\n\n)\n", "file_path": "examples/python/blend_multiple.py", "rank": 70, "score": 69622.41956754768 }, { "content": "#!/usr/bin/python\n\n# -*- coding: utf-8 -*-\n\n\n\nimport os\n\nimport pconvert_rust as pconvert\n\n\n\nPATH_TO_ASSETS = os.path.join(os.path.dirname(__file__), \"../../assets/demo/\")\n\n\n\nprint(f\"VERSION: {pconvert.VERSION}\")\n\nprint(f\"COMPILED ON: {pconvert.COMPILATION_DATE}, {pconvert.COMPILATION_TIME}\")\n\n\n\npconvert.blend_images(\n\n os.path.abspath(f\"{PATH_TO_ASSETS}sole.png\"),\n\n os.path.abspath(f\"{PATH_TO_ASSETS}back.png\"),\n\n os.path.abspath(\"result.png\")\n\n)\n\n\n\npconvert.blend_images(\n\n os.path.abspath(\"result.png\"),\n\n os.path.abspath(f\"{PATH_TO_ASSETS}front.png\"),\n\n os.path.abspath(\"result.png\")\n\n)\n", "file_path": "examples/python/blend_images.py", "rank": 71, "score": 69622.41956754768 }, { "content": "#!/usr/bin/python\n\n# -*- coding: utf-8 -*-\n\n\n\n# Sets of tests related to MDN documentation @ https://developer.mozilla.org/docs/Web/API/Canvas_API/Tutorial/Compositing/Example\n\n\n\nimport os\n\nimport pconvert_rust as pconvert\n\n\n\nPATH_TO_ASSETS = os.path.join(os.path.dirname(__file__), \"../../assets/mozilla/\")\n\n\n\nprint(f\"VERSION: {pconvert.VERSION}\")\n\nprint(f\"COMPILED ON: {pconvert.COMPILATION_DATE}, {pconvert.COMPILATION_TIME}\")\n\n\n\npconvert.blend_images(\n\n os.path.abspath(f\"{PATH_TO_ASSETS}source.png\"),\n\n os.path.abspath(f\"{PATH_TO_ASSETS}destination.png\"),\n\n os.path.abspath(\"result.source_over.mozilla.png\"),\n\n \"source_over\"\n\n)\n\n\n\npconvert.blend_images(\n\n os.path.abspath(f\"{PATH_TO_ASSETS}source.png\"),\n\n os.path.abspath(f\"{PATH_TO_ASSETS}destination.png\"),\n\n os.path.abspath(\"result.destination_over.mozilla.png\"),\n\n \"destination_over\"\n\n)\n", "file_path": "examples/python/blend_images_mozilla.py", "rank": 72, "score": 67893.54796098548 }, { "content": "#!/usr/bin/python\n\n# -*- coding: utf-8 -*-\n\n\n\nimport os\n\nimport time\n\nimport threading\n\nimport pconvert_rust as pconvert\n\n\n\nPATH_TO_ASSETS = os.path.join(os.path.dirname(__file__), \"../../assets/demo/\")\n\n\n\nprint(f\"VERSION: {pconvert.VERSION}\")\n\nprint(f\"COMPILED ON: {pconvert.COMPILATION_DATE}, {pconvert.COMPILATION_TIME}\")\n\n\n\ndef print_pool_status():\n\n while True:\n\n print(pconvert.get_thread_pool_status())\n\n time.sleep(0.1)\n\n\n\ndef blend(i):\n\n pconvert.blend_multiple(\n\n (\n\n os.path.abspath(f\"{PATH_TO_ASSETS}sole.png\"),\n\n os.path.abspath(f\"{PATH_TO_ASSETS}back.png\"),\n\n os.path.abspath(f\"{PATH_TO_ASSETS}front.png\"),\n\n os.path.abspath(f\"{PATH_TO_ASSETS}shoelace.png\"),\n\n os.path.abspath(f\"{PATH_TO_ASSETS}background_alpha.png\"),\n\n ),\n\n os.path.abspath(f\"result{i}.png\"),\n\n options = {\n\n \"num_threads\": 20\n\n }\n\n )\n\n\n\npool_status_thread = threading.Thread(target = print_pool_status)\n\npool_status_thread.daemon = True\n\npool_status_thread.start()\n\n\n\nblending_threads = [threading.Thread(target = blend, args = (x,)) for x in range(1000)]\n\n\n\nfor blending_thread in blending_threads:\n\n blending_thread.start()\n\n\n\nfor blending_thread in blending_threads:\n\n blending_thread.join()\n", "file_path": "examples/python/blend_multiple_multithread.py", "rank": 73, "score": 67893.54796098548 }, { "content": "#!/usr/bin/python\n\n# -*- coding: utf-8 -*-\n\n\n\nimport os\n\nimport time\n\nimport threading\n\nimport pconvert_rust as pconvert\n\n\n\nPATH_TO_ASSETS = os.path.join(os.path.dirname(__file__), \"../../assets/demo/\")\n\n\n\nprint(f\"VERSION: {pconvert.VERSION}\")\n\nprint(f\"COMPILED ON: {pconvert.COMPILATION_DATE}, {pconvert.COMPILATION_TIME}\")\n\n\n\ndef print_pool_status():\n\n while True:\n\n print(pconvert.get_thread_pool_status())\n\n time.sleep(0.1)\n\n\n\ndef blend(i):\n\n pconvert.blend_images(\n\n os.path.abspath(f\"{PATH_TO_ASSETS}sole.png\"),\n\n os.path.abspath(f\"{PATH_TO_ASSETS}back.png\"),\n\n os.path.abspath(f\"result{i}.png\"),\n\n options = {\n\n \"num_threads\": 20\n\n }\n\n )\n\n\n\npool_status_thread = threading.Thread(target = print_pool_status)\n\npool_status_thread.daemon = True\n\npool_status_thread.start()\n\n\n\nblending_threads = [threading.Thread(target = blend, args = (x,)) for x in range(1000)]\n\n\n\nfor blending_thread in blending_threads:\n\n blending_thread.start()\n\n\n\nfor blending_thread in blending_threads:\n\n blending_thread.join()\n", "file_path": "examples/python/blend_images_multithread.py", "rank": 74, "score": 67893.54796098548 }, { "content": "//! Utility functions for argument parsing from python input to inner-crate rust types.\n\n\n\nuse crate::blending::params::{BlendAlgorithmParams, Options, Value};\n\nuse crate::blending::BlendAlgorithm;\n\nuse crate::errors::PConvertError;\n\nuse crate::utils::{image_compression_from, image_filter_from};\n\nuse image::codecs::png::{CompressionType, FilterType};\n\nuse pyo3::prelude::*;\n\nuse pyo3::types::{PySequence, PyString};\n\nuse std::str::FromStr;\n\n\n\n/// Attempts to parse a `&String` to a `BlendAlgorithm`.\n\n/// Returns the enum variant if it succeeds. Otherwise it returns a `PyErr`.\n", "file_path": "src/pymodule/utils.rs", "rank": 75, "score": 63932.070686622545 }, { "content": " for j in 0..params_sequence.len()? {\n\n if let Ok(property_value) = params_sequence.get_item(j)?.cast_as::<PySequence>()\n\n {\n\n let param_name = property_value.get_item(0)?.extract::<String>()?;\n\n let param_value = property_value.get_item(1)?;\n\n let param_value = param_value.extract::<Value>()?;\n\n blending_params.insert(param_name, param_value);\n\n }\n\n }\n\n } else {\n\n return Err(PyErr::from(PConvertError::ArgumentError(\n\n \"Parameters should be given as a python sequence object\".to_string(),\n\n )));\n\n }\n\n\n\n result.push((algorithm, Some(blending_params)));\n\n }\n\n }\n\n\n\n Ok(result)\n\n}\n\n\n", "file_path": "src/pymodule/utils.rs", "rank": 76, "score": 63918.018190624956 }, { "content": "fn main() {\n\n // in case we're running under docs.rs then we must return the control\n\n // flow immediately as it's not possible to generated files under the\n\n // expected read only file system present in docs.rs build environment\n\n if std::env::var(\"DOCS_RS\").is_ok() {\n\n return;\n\n }\n\n\n\n let dest_path = Path::new(SOURCE_DIR).join(Path::new(BUILD_OUT_FILE));\n\n let mut file = OpenOptions::new()\n\n .truncate(true)\n\n .write(true)\n\n .create(true)\n\n .open(dest_path)\n\n .unwrap_or_else(|_| panic!(\"Can't open '{}'\", BUILD_OUT_FILE));\n\n\n\n let module_doc_string = \"//! Global constants, such as compiler version used, algorithms, compression and filters supported and others\\n\";\n\n writeln!(file, \"{}\", module_doc_string).unwrap();\n\n\n\n let now_utc = Utc::now();\n", "file_path": "build.rs", "rank": 93, "score": 55953.25555119295 }, { "content": "def blend(i):\n\n pconvert.blend_images(\n\n os.path.abspath(f\"{PATH_TO_ASSETS}sole.png\"),\n\n os.path.abspath(f\"{PATH_TO_ASSETS}back.png\"),\n\n os.path.abspath(f\"result{i}.png\"),\n\n options = {\n\n \"num_threads\": 20\n\n }\n", "file_path": "examples/python/blend_images_multithread.py", "rank": 94, "score": 47870.277152366994 }, { "content": "def blend(i):\n\n pconvert.blend_multiple(\n\n (\n\n os.path.abspath(f\"{PATH_TO_ASSETS}sole.png\"),\n\n os.path.abspath(f\"{PATH_TO_ASSETS}back.png\"),\n\n os.path.abspath(f\"{PATH_TO_ASSETS}front.png\"),\n\n os.path.abspath(f\"{PATH_TO_ASSETS}shoelace.png\"),\n\n os.path.abspath(f\"{PATH_TO_ASSETS}background_alpha.png\"),\n\n ),\n\n os.path.abspath(f\"result{i}.png\"),\n\n options = {\n\n \"num_threads\": 20\n\n }\n", "file_path": "examples/python/blend_multiple_multithread.py", "rank": 95, "score": 47870.277152366994 }, { "content": " def test_module_constants(self):\n\n mandatory = [\n\n \"ALGORITHMS\",\n\n \"COMPILATION_DATE\",\n\n \"COMPILATION_TIME\",\n\n \"COMPILER\",\n\n \"COMPILER_VERSION\",\n\n \"COMPRESSION_TYPES\",\n\n \"FEATURES\",\n\n \"FILTER_TYPES\",\n\n \"LIBPNG_VERSION\",\n\n \"PLATFORM_CPU_BITS\",\n\n \"VERSION\"\n\n ];\n", "file_path": "pconvert_rust/test/blending.py", "rank": 96, "score": 46486.73644022455 }, { "content": "fn main() -> Result<(), PConvertError> {\n\n let mut args = env::args();\n\n\n\n // skips program name, facilitating the parsing\n\n // of the extra argument from command line\n\n args.next();\n\n\n\n match args.next() {\n\n Some(action) => match &action[..] {\n\n \"convert\" => pconvert(&mut args)?,\n\n \"compose\" => pcompose(&mut args)?,\n\n \"benchmark\" => pbenchmark(&mut args)?,\n\n \"version\" => pversion(),\n\n _ => print_usage(),\n\n },\n\n None => print_usage(),\n\n };\n\n\n\n Ok(())\n\n}\n", "file_path": "src/main.rs", "rank": 97, "score": 45995.247646412274 }, { "content": "def print_pool_status():\n\n while True:\n\n print(pconvert.get_thread_pool_status())\n", "file_path": "examples/python/blend_images_multithread.py", "rank": 98, "score": 44935.55963552316 }, { "content": "#[wasm_bindgen(js_name = blendMultipleBenchmarkAll)]\n\npub async fn blend_multiple_benchmark_all_js(\n\n image_files: JsValue,\n\n is_inline: Option<bool>,\n\n) -> Result<(), JsValue> {\n\n log_benchmark_header();\n\n for algorithm in constants::ALGORITHMS.iter() {\n\n for compression in constants::COMPRESSION_TYPES.iter() {\n\n for filter in constants::FILTER_TYPES.iter() {\n\n blend_multiple_benchmark_js(\n\n image_files.clone(),\n\n \"\".to_string(),\n\n Some(algorithm.to_string()),\n\n None,\n\n is_inline,\n\n *compression,\n\n *filter,\n\n )\n\n .await?;\n\n }\n", "file_path": "src/wasm/benchmark.rs", "rank": 99, "score": 19.259186887751536 } ]
Rust
src/lib.rs
estchd/passable_guard
0549276b278e11e75c6e8f0b65a689d2eab812e2
use std::marker::PhantomData; use std::ffi::CString; #[derive(Debug, Clone)] pub enum ReconstituteError<PTR, PAS: Passable<PTR>> { PointerMismatch{passed: *mut PTR, reconstituted: *mut PTR}, ReconstituteError{error: PAS::ReconstituteError} } #[derive(Debug, Clone)] pub struct PassableContainer<PTR, PAS: Passable<PTR>> { value: PAS, _phantom: PhantomData<PTR> } impl<PTR, PAS: Passable<PTR>> PassableContainer<PTR, PAS> { pub fn new(passable: PAS) -> Self { Self { value: passable, _phantom: Default::default() } } pub fn into_inner(self) -> PAS { self.value } pub fn pass(self) -> (PassableGuard<PTR, PAS>, *mut PTR) { let ptr = self.value.pass(); let guard = PassableGuard { ptr, _phantom: Default::default() }; (guard, ptr) } pub unsafe fn pass_unguarded(self) -> *mut PTR { self.value.pass() } } #[derive(Debug, Clone)] pub struct PassableGuard<PTR, PAS: Passable<PTR>> { ptr: *mut PTR, _phantom: PhantomData<PAS> } impl<PTR, PAS: Passable<PTR>> PassableGuard<PTR, PAS> { pub unsafe fn reconstitute(self, ptr: *mut PTR) -> Result<PassableContainer<PTR, PAS>, ReconstituteError<PTR, PAS>> { if self.ptr != ptr { return Err( ReconstituteError::PointerMismatch { passed: self.ptr, reconstituted: ptr } ); } PAS::reconstitute(ptr) .map(|passable| PassableContainer::new(passable)) .map_err( |err| ReconstituteError::ReconstituteError {error: err} ) } } impl<PTR, PAS: Passable<PTR>> Drop for PassableGuard<PTR, PAS> { fn drop(&mut self) { panic!("Passable Guard dropped before being reconstituted"); } } pub trait Passable<PTR> : Sized { type ReconstituteError; fn pass(self) -> *mut PTR; unsafe fn reconstitute(ptr: *mut PTR) -> Result<Self, Self::ReconstituteError>; } impl Passable<u8> for CString { type ReconstituteError = (); fn pass(self) -> *mut u8 { self.into_raw() as *mut u8 } unsafe fn reconstitute(ptr: *mut u8) -> Result<Self, Self::ReconstituteError> { Ok(CString::from_raw(ptr as *mut i8)) } }
use std::marker::PhantomData; use std::ffi::CString; #[derive(Debug, Clone)] pub enum ReconstituteError<PTR, PAS: Passable<PTR>> { PointerMismatch{passed: *mut PTR, reconstituted: *mut PTR}, ReconstituteError{error: PAS::ReconstituteError} } #[derive(Debug, Clone)] pub struct PassableContainer<PTR, PAS: Passable<PTR>> { value: PAS, _phantom: PhantomData<PTR> } impl<PTR, PAS: Passable<PTR>> PassableContainer<PTR, PAS> { pub fn new(passable: PAS) -> Self { Self { value: passable, _phantom: Default::default() } } pub fn into_inner(self) -> PAS { self.value } pub fn pass(self) -> (PassableGuard<PTR, PAS>, *mut PTR) { let ptr = self.value.pass(); let guard = PassableGuard { ptr, _phantom: Default::default() }; (guard, ptr) } pub unsafe fn pass_unguarded(self) -> *mut PTR { self.value.pass() } } #[derive(Debug, Clone)] pub struct PassableGuard<PTR, PAS: Passable<PTR>> { ptr: *mut PTR, _phantom: PhantomData<PAS> } impl<PTR, PAS: Passable<PTR>> PassableGuard<PTR, PAS> { pub unsafe fn reconstitute(self, ptr: *mut PTR) -> Result<PassableContainer<PTR, PAS>, ReconstituteError<PTR, PAS>> { if self.ptr != ptr { return
; } PAS::reconstitute(ptr) .map(|passable| PassableContainer::new(passable)) .map_err( |err| ReconstituteError::ReconstituteError {error: err} ) } } impl<PTR, PAS: Passable<PTR>> Drop for PassableGuard<PTR, PAS> { fn drop(&mut self) { panic!("Passable Guard dropped before being reconstituted"); } } pub trait Passable<PTR> : Sized { type ReconstituteError; fn pass(self) -> *mut PTR; unsafe fn reconstitute(ptr: *mut PTR) -> Result<Self, Self::ReconstituteError>; } impl Passable<u8> for CString { type ReconstituteError = (); fn pass(self) -> *mut u8 { self.into_raw() as *mut u8 } unsafe fn reconstitute(ptr: *mut u8) -> Result<Self, Self::ReconstituteError> { Ok(CString::from_raw(ptr as *mut i8)) } }
Err( ReconstituteError::PointerMismatch { passed: self.ptr, reconstituted: ptr } )
call_expression
[ { "content": "# Passable Guard\n\n\n\nThe Passable Guard Crate provides a way to check for FFI memory leaks at runtime.\n\n\n\nThis is achieved by providing a PassableContainer class that encapsulates\n\na Passable Object that can be converted to a raw pointer to pass it over a FFI boundary.\n\n\n\nThis PassableContainer combines the raw pointer with a PassableGuard\n\nwhen converting the Passable.\n\n\n\nThis PassableGuard will panic if it is dropped before recombining it with the raw pointer.\n\n\n\nThat way, you will at least get a panic instead of leaking memory\n\n\n\n## Example\n\n\n\nFor this example, we will create a CString and pass it to a fictional FFI function `setName`,\n\nusing a PassableContainer to guard against Memory Leaks\n\n\n\n``` rust\n\nuse std::ffi::CString;\n\nuse passable_guard::PassableContainer;\n\n\n\nextern \"C\" {\n\n /// Takes a pointer to a NULL-Terminated utf-8 string\n\n /// Returns 0 on failure and >0 on success\n\n fn setName(ptr: *mut u8) -> u8;\n\n}\n\n\n\nfn passable_example(name: CString) -> Result<(),()> {\n\n let passable = PassableContainer::new(name); // Create the Container from the name CString\n\n\n\n let (guard, ptr) = passable.pass(); // Convert the Container into a raw pointer (and get the guard for it as well)\n\n\n\n let result = unsafe {\n\n setName(ptr) // Call the FFI function and give it our pointer\n\n };\n\n\n\n unsafe {\n\n // Reconstitute the Guard and Pointer back into a Container\n\n // The pointers will be the same since we use the pointer we got from the pass method\n\n // This might cause UB if setName modifies the Memory\n\n guard.reconstitute(ptr).unwrap();\n\n }\n\n drop(ptr); // Drop the Pointer so we do not use it again\n\n\n\n return if result == 0 {\n\n Err(())\n\n }\n\n else {\n\n Ok(())\n\n }\n\n}\n\n```\n\n\n\nLet's look at an example that Panics\n\n\n\n``` rust\n\nuse std::ffi::CString;\n\nuse passable_guard::PassableContainer;\n\n\n\nextern \"C\" {\n\n /// Takes a pointer to a NULL-Terminated utf-8 string\n\n /// Returns 0 on failure and >0 on success\n\n fn setName(ptr: *mut u8) -> u8;\n", "file_path": "README.md", "rank": 1, "score": 18583.5590951406 }, { "content": "}\n\n\n\nfn passable_example(name: CString) -> Result<(),()> {\n\n let passable = PassableContainer::new(name); // Create the Container from the name CString\n\n\n\n let (guard, ptr) = passable.pass(); // Convert the Container into a raw pointer (and get the guard for it as well)\n\n\n\n let result = unsafe {\n\n setName(ptr) // Call the FFI function and give it our pointer\n\n };\n\n\n\n // Drop the Pointer so we do not use it again\n\n // This means that we cannot possibly reconstitute the Guard and pointer\n\n drop(ptr);\n\n\n\n return if result == 0 {\n\n Err(())\n\n }\n\n else {\n\n Ok(())\n\n }\n\n // The Function will panic here since the Guard has been dropped without being reconstituted\n\n // Without the Guard, we would have now subtly leaked the String Memory\n\n}\n\n```\n", "file_path": "README.md", "rank": 2, "score": 18583.051256477243 }, { "content": "# Passable Guard\n\n\n\nThe Passable Guard Crate provides a way to check for FFI memory leaks at runtime.\n\n\n\nThis is achieved by providing a [PassableContainer] class that encapsulates\n\na [Passable] Object that can be converted to a raw pointer to pass it over a FFI boundary.\n\n\n\nThis [PassableContainer] combines the raw pointer with a [PassableGuard]\n\nwhen converting the [Passable].\n\n\n\nThis [PassableGuard] will panic if it is dropped before recombining it with the raw pointer.\n\n\n\nThat way, you will at least get a panic instead of leaking memory\n\n\n\n## Example\n\n\n\nFor this example, we will create a CString and pass it to a fictional FFI function `setName`,\n\nusing a [PassableContainer] to guard against Memory Leaks\n\n\n\n```\n\nuse std::ffi::CString;\n\nuse passable_guard::PassableContainer;\n\n\n\nextern \"C\" {\n\n /// Takes a pointer to a NULL-Terminated utf-8 string\n\n /// Returns 0 on failure and >0 on success\n\n fn setName(ptr: *mut u8) -> u8;\n\n}\n\n\n\nfn passable_example(name: CString) -> Result<(),()> {\n\n let passable = PassableContainer::new(name); // Create the Container from the name CString\n\n\n\n let (guard, ptr) = passable.pass(); // Convert the Container into a raw pointer (and get the guard for it as well)\n\n\n\n let result = unsafe {\n\n setName(ptr) // Call the FFI function and give it our pointer\n\n };\n\n\n\n unsafe {\n\n // Reconstitute the Guard and Pointer back into a Container\n\n // The pointers will be the same since we use the pointer we got from the pass method\n\n // This might cause UB if setName modifies the Memory\n\n guard.reconstitute(ptr).unwrap();\n\n }\n\n drop(ptr); // Drop the Pointer so we do not use it again\n\n\n\n return if result == 0 {\n\n Err(())\n\n }\n\n else {\n\n Ok(())\n\n }\n\n}\n\n```\n\n\n\nLet's look at an example that Panics\n\n\n\n```\n\nuse std::ffi::CString;\n\nuse passable_guard::PassableContainer;\n\n\n\nextern \"C\" {\n\n /// Takes a pointer to a NULL-Terminated utf-8 string\n\n /// Returns 0 on failure and >0 on success\n\n fn setName(ptr: *mut u8) -> u8;\n", "file_path": "src/README.md", "rank": 3, "score": 17941.25571603401 }, { "content": "}\n\n\n\nfn passable_example(name: CString) -> Result<(),()> {\n\n let passable = PassableContainer::new(name); // Create the Container from the name CString\n\n\n\n let (guard, ptr) = passable.pass(); // Convert the Container into a raw pointer (and get the guard for it as well)\n\n\n\n let result = unsafe {\n\n setName(ptr) // Call the FFI function and give it our pointer\n\n };\n\n\n\n // Drop the Pointer so we do not use it again\n\n // This means that we cannot possibly reconstitute the Guard and pointer\n\n drop(ptr);\n\n\n\n return if result == 0 {\n\n Err(())\n\n }\n\n else {\n\n Ok(())\n\n }\n\n // The Function will panic here since the Guard has been dropped without being reconstituted\n\n // Without the Guard, we would have now subtly leaked the String Memory\n\n}\n", "file_path": "src/README.md", "rank": 4, "score": 17940.70723746085 } ]
Rust
liblumen_core/src/sys/unix/dynamic_call.rs
mlwilkerson/lumen
048df6c0840c11496e2d15aa9af2e4a8d07a6e0f
use crate::sys::dynamic_call::DynamicCallee; extern "C" { #[unwind(allowed)] #[link_name = "__lumen_dynamic_apply"] pub fn apply(f: DynamicCallee, argv: *const usize, argc: usize) -> usize; } #[cfg(all(target_os = "macos", target_arch = "x86_64"))] global_asm!(include_str!("dynamic_call/lumen_dynamic_apply_macos.s")); #[cfg(all(target_os = "linux", target_arch = "x86_64"))] global_asm!(include_str!("dynamic_call/lumen_dynamic_apply_linux.s")); #[cfg(test)] mod tests { use super::*; use core::mem; #[test] fn basic_apply_test() { let callee = adder as *const (); let callee = unsafe { mem::transmute::<*const (), DynamicCallee>(callee) }; let args = &[22, 11]; let argv = args.as_ptr(); let argc = args.len(); let result = unsafe { apply(callee, argv, argc) }; assert_eq!(result, 33); } #[test] fn basic_apply_rustcc_test() { let callee = adder_rust as *const (); let callee = unsafe { mem::transmute::<*const (), DynamicCallee>(callee) }; let args = &[22, 11]; let argv = args.as_ptr(); let argc = args.len(); let result = unsafe { apply(callee, argv, argc) }; assert_eq!(result, 33); } #[test] fn spilled_args_even_spills_apply_test() { let callee = spilled_args_even as *const (); let callee = unsafe { mem::transmute::<*const (), DynamicCallee>(callee) }; let args = &[1, 1, 1, 1, 1, 1, 1, 1, 1]; let argv = args.as_ptr(); let argc = args.len(); let result = unsafe { apply(callee, argv, argc) }; assert_eq!(result, 8); } #[test] fn spilled_args_odd_spills_apply_test() { let callee = spilled_args_odd as *const (); let callee = unsafe { mem::transmute::<*const (), DynamicCallee>(callee) }; let args = &[1, 1, 1, 1, 1, 1, 1, 1]; let argv = args.as_ptr(); let argc = args.len(); let result = unsafe { apply(callee, argv, argc) }; assert_eq!(result, 7); } #[test] #[should_panic] fn panic_apply_test() { let callee = panicky as *const (); let callee = unsafe { mem::transmute::<*const (), DynamicCallee>(callee) }; let args = &[22, 11]; let argv = args.as_ptr(); let argc = args.len(); let _result = unsafe { apply(callee, argv, argc) }; } #[test] #[should_panic] fn panic_apply_spills_test() { let callee = panicky_spilled as *const (); let callee = unsafe { mem::transmute::<*const (), DynamicCallee>(callee) }; let args = &[1, 1, 1, 1, 1, 1, 1, 1]; let argv = args.as_ptr(); let argc = args.len(); let _result = unsafe { apply(callee, argv, argc) }; } fn panicky(_x: usize, _y: usize) -> usize { panic!("panicky"); } #[unwind(allowed)] extern "C" fn panicky_spilled( _a: usize, _b: usize, _c: usize, _d: usize, _e: usize, _f: usize, _g: usize, ) -> usize { panic!("panicky"); } extern "C" fn adder(x: usize, y: usize) -> usize { x + y } fn adder_rust(x: usize, y: usize) -> usize { x + y } extern "C" fn spilled_args_even( a: usize, b: usize, c: usize, d: usize, e: usize, f: usize, g: usize, h: usize, ) -> usize { a + b + c + d + e + f + g + h } extern "C" fn spilled_args_odd( a: usize, b: usize, c: usize, d: usize, e: usize, f: usize, g: usize, ) -> usize { a + b + c + d + e + f + g } }
use crate::sys::dynamic_call::DynamicCallee; extern "C" { #[unwind(allowed)] #[link_name = "__lumen_dynamic_apply"] pub fn apply(f: DynamicCallee, argv: *const usize, argc: usize) -> usize; } #[cfg(all(target_os = "macos", target_arch = "x86_64"))] global_asm!(include_str!("dynamic_call/lumen_dynamic_apply_macos.s")); #[cfg(all(target_os = "linux", target_arch = "x86_64"))] global_asm!(include_str!("dynamic_call/lumen_dynamic_apply_linux.s")); #[cfg(test)] mod tests { use super::*; use core::mem; #[test] fn basic_apply_test() { let callee = adder as *const (); let callee = unsafe { mem::transmute::<*const (), DynamicCallee>(callee) }; let args = &[22, 11]; let argv = args.as_ptr(); let argc = args.len(); let result = unsafe { apply(callee, argv, argc) }; assert_eq!(result, 33); } #[test] fn basic_apply_rustcc_test() { let callee = adder_rust as *const (); let callee = unsafe { mem::transmute::<*const (), DynamicCallee>(callee) }; let args = &[22, 11]; let argv = args.as_ptr(); let argc = args.len(); let result = unsafe { apply(callee, argv, argc) }; assert_eq!(result, 33); } #[test] fn spilled_args_even_spills_apply_test() { let callee = spilled_args_even as *const (); let callee = unsafe { mem::transmute::<*const (), DynamicCallee>(callee) }; let args = &[1, 1, 1, 1, 1, 1, 1, 1, 1]; let argv = args.as_ptr(); let argc = args.len(); let result = unsafe { apply(callee, argv, argc) }; assert_eq!(result, 8); } #[test] fn spilled_args_odd_spills_apply_test() { let callee = spilled_args_odd as *const (); let callee = unsafe { mem::transmute::<*const (), DynamicCallee>(callee) }; let args = &[1, 1, 1, 1, 1, 1, 1, 1]; let argv = args.as_ptr(); let argc = args.len(); let result = unsafe { apply(callee, argv, argc) }; assert_eq!(result, 7); } #[test] #[should_panic] fn panic_apply_test() { let callee = panicky as *const (); let callee = unsafe { mem::transmute::<*const (), DynamicCallee>(callee) }; let args = &[22, 11]; let argv = args.as_ptr(); let argc = args.len(); let _result = unsafe { apply(callee, argv, argc) }; } #[test] #[should_panic] fn panic_apply_spills_test() { let callee = panicky_spilled as *const (); let callee = unsafe { mem::transmute::<*const (), DynamicCallee>(callee) }; let args = &[1, 1, 1, 1, 1, 1, 1, 1]; let argv = args.as_ptr(); let argc = args.len(); let _result = unsafe { apply(callee, argv, argc) }; } fn panicky(_x: usize, _y: usize) -> usize { panic!("panicky"); } #[unwind(allowed)] extern "C" fn panicky_spilled( _a: usize, _b: usize, _c: usize, _d: usize, _e: usize, _f: usize, _g: usize, ) -> usize { panic!("panicky"); } extern "C" fn adder(x: usize, y: usize) -> usize { x + y } fn adder_rust(x: usize, y: usize) -> usize { x + y }
extern "C" fn spilled_args_odd( a: usize, b: usize, c: usize, d: usize, e: usize, f: usize, g: usize, ) -> usize { a + b + c + d + e + f + g } }
extern "C" fn spilled_args_even( a: usize, b: usize, c: usize, d: usize, e: usize, f: usize, g: usize, h: usize, ) -> usize { a + b + c + d + e + f + g + h }
function_block-full_function
[ { "content": "/// Invoke the statically linked `lld` linker with the given arguments.\n\n///\n\n/// NOTE: Assumes that the first value of the argument vector contains the\n\n/// program name which informs lld which flavor of linker is being run.\n\npub fn link(argv: &[CString]) -> Result<(), ()> {\n\n // Acquire exclusive access to stdout/stderr for the linker\n\n let stdout = io::stdout();\n\n let stderr = io::stderr();\n\n let stdout_lock = stdout.lock();\n\n let stderr_lock = stderr.lock();\n\n let stdout_fd = fs::get_file_descriptor(&stdout_lock);\n\n let stderr_fd = fs::get_file_descriptor(&stderr_lock);\n\n\n\n let argc = argv.len();\n\n let mut c_argv = Vec::with_capacity(argc);\n\n for arg in argv {\n\n c_argv.push(arg.as_ptr());\n\n }\n\n let is_ok = unsafe {\n\n LLVMLumenLink(argc as libc::c_int, c_argv.as_ptr(), stdout_fd, stderr_fd)\n\n };\n\n\n\n if is_ok {\n\n Ok(())\n\n } else {\n\n Err(())\n\n }\n\n}\n", "file_path": "compiler/codegen/src/linker/builtin.rs", "rank": 0, "score": 410867.6539020926 }, { "content": "pub fn external() -> BoxedStrategy<usize> {\n\n super::id()\n\n .prop_filter(\"Can't be local node ID\", |id| {\n\n id != &crate::runtime::distribution::nodes::node::id()\n\n })\n\n .boxed()\n\n}\n", "file_path": "native_implemented/otp/src/test/strategy/node/id.rs", "rank": 1, "score": 331615.2537397031 }, { "content": "pub fn without_timer_returns_false(result: fn(&Process, Term) -> exception::Result<Term>) {\n\n with_process(|process| {\n\n let timer_reference = process.next_reference();\n\n\n\n assert_eq!(result(process, timer_reference), Ok(false.into()));\n\n });\n\n}\n", "file_path": "native_implemented/otp/src/test.rs", "rank": 2, "score": 327603.5382969475 }, { "content": "#[inline(always)]\n\npub fn distance_absolute<T: Sized>(a: *const T, b: *const T) -> usize {\n\n unsafe { a.offset_from(b).abs() as usize }\n\n}\n\n\n\n/// Returns true if `ptr` is in the memory region between `start` and `end`,\n\n/// specifically if `ptr` falls in the range including `start` but excluding `end`\n\n///\n\n/// NOTE: If any of the given pointers are null, then false will be returned\n", "file_path": "liblumen_core/src/util/pointer.rs", "rank": 3, "score": 303451.2084710544 }, { "content": "pub fn run_compiler(cwd: PathBuf, args: ArgsOs) -> anyhow::Result<()> {\n\n run_compiler_with_emitter(cwd, args, None)\n\n}\n\n\n", "file_path": "compiler/driver/src/driver.rs", "rank": 4, "score": 301832.5050619679 }, { "content": "#[native_implemented::function(erlang:band/2)]\n\npub fn result(\n\n process: &Process,\n\n left_integer: Term,\n\n right_integer: Term,\n\n) -> exception::Result<Term> {\n\n bitwise_infix_operator!(left_integer, right_integer, process, bitand)\n\n}\n", "file_path": "native_implemented/otp/src/erlang/band_2.rs", "rank": 5, "score": 299813.74121594673 }, { "content": "#[native_implemented::function(Elixir.Lumen.Web.Executor:apply/4)]\n\npub fn result(\n\n process: &Process,\n\n executor: Term,\n\n module: Term,\n\n function: Term,\n\n arguments: Term,\n\n) -> Term {\n\n process.queue_frame_with_arguments(\n\n erlang::apply_3::frame().with_arguments(false, &[module, function, arguments]),\n\n );\n\n process.queue_frame_with_arguments(label_1::frame().with_arguments(true, &[executor]));\n\n\n\n Term::NONE\n\n}\n", "file_path": "native_implemented/web/src/executor/apply_4.rs", "rank": 6, "score": 299813.74121594673 }, { "content": "#[native_implemented::function(erlang:send/3)]\n\npub fn result(\n\n process: &Process,\n\n destination: Term,\n\n message: Term,\n\n options: Term,\n\n) -> exception::Result<Term> {\n\n let send_options: send::Options = options.try_into()?;\n\n\n\n send(destination, message, send_options, process)\n\n .map(|sent| match sent {\n\n Sent::Sent => \"ok\",\n\n Sent::ConnectRequired => \"noconnect\",\n\n Sent::SuspendRequired => \"nosuspend\",\n\n })\n\n .map(Atom::str_to_term)\n\n .map_err(From::from)\n\n}\n", "file_path": "native_implemented/otp/src/erlang/send_3.rs", "rank": 7, "score": 299813.74121594673 }, { "content": "#[native_implemented::function(erlang:bor/2)]\n\npub fn result(\n\n process: &Process,\n\n left_integer: Term,\n\n right_integer: Term,\n\n) -> exception::Result<Term> {\n\n bitwise_infix_operator!(left_integer, right_integer, process, bitor)\n\n}\n", "file_path": "native_implemented/otp/src/erlang/bor_2.rs", "rank": 8, "score": 299813.74121594673 }, { "content": "#[native_implemented::function(erlang:spawn/3)]\n\npub fn result(\n\n process: &Process,\n\n module: Term,\n\n function: Term,\n\n arguments: Term,\n\n) -> exception::Result<Term> {\n\n spawn_apply_3::result(process, Default::default(), module, function, arguments)\n\n}\n", "file_path": "native_implemented/otp/src/erlang/spawn_3.rs", "rank": 9, "score": 299813.74121594673 }, { "content": "#[native_implemented::function(erlang:send_after/4)]\n\npub fn result(\n\n arc_process: Arc<Process>,\n\n time: Term,\n\n destination: Term,\n\n message: Term,\n\n options: Term,\n\n) -> exception::Result<Term> {\n\n let timer_start_options: timer::start::Options = options.try_into()?;\n\n\n\n start_timer(\n\n time,\n\n destination,\n\n Format::Message,\n\n message,\n\n timer_start_options,\n\n arc_process,\n\n )\n\n .map_err(From::from)\n\n}\n", "file_path": "native_implemented/otp/src/erlang/send_after_4.rs", "rank": 10, "score": 299813.74121594673 }, { "content": "#[native_implemented::function(erlang:bxor/2)]\n\npub fn result(\n\n process: &Process,\n\n left_integer: Term,\n\n right_integer: Term,\n\n) -> exception::Result<Term> {\n\n bitwise_infix_operator!(left_integer, right_integer, process, bitxor)\n\n}\n", "file_path": "native_implemented/otp/src/erlang/bxor_2.rs", "rank": 11, "score": 299813.74121594673 }, { "content": "#[native_implemented::function(erlang:send_after/3)]\n\npub fn result(\n\n arc_process: Arc<Process>,\n\n time: Term,\n\n destination: Term,\n\n message: Term,\n\n) -> exception::Result<Term> {\n\n start_timer(\n\n time,\n\n destination,\n\n Format::Message,\n\n message,\n\n Default::default(),\n\n arc_process,\n\n )\n\n .map_err(From::from)\n\n}\n", "file_path": "native_implemented/otp/src/erlang/send_after_3.rs", "rank": 12, "score": 299813.74121594673 }, { "content": "#[inline(always)]\n\npub fn effective_alignment<T>(ptr: *const T) -> usize {\n\n 1usize << (ptr as usize).trailing_zeros()\n\n}\n\n\n\n/// Given a reference to an object, formats the reference\n\n/// as a hexadecimal memory address\n", "file_path": "liblumen_core/src/alloc/utils.rs", "rank": 13, "score": 299598.3730241368 }, { "content": "pub fn module_id() -> usize {\n\n module().id()\n\n}\n\n\n", "file_path": "native_implemented/otp/src/test.rs", "rank": 14, "score": 299038.13590642146 }, { "content": "#[native_implemented::function(erlang:insert_element/3)]\n\npub fn result(\n\n process: &Process,\n\n index: Term,\n\n tuple: Term,\n\n element: Term,\n\n) -> exception::Result<Term> {\n\n let initial_inner_tuple = term_try_into_tuple!(tuple)?;\n\n let length = initial_inner_tuple.len();\n\n let index_one_based: OneBasedIndex = index\n\n .try_into()\n\n .with_context(|| term_is_not_in_one_based_range(index, length + 1))?;\n\n let index_zero_based: usize = index_one_based.into();\n\n\n\n // can be equal to arity when insertion is at the end\n\n if index_zero_based <= length {\n\n let mut final_element_vec = initial_inner_tuple[..].to_vec();\n\n if index_zero_based < length {\n\n final_element_vec.insert(index_zero_based, element);\n\n } else {\n\n final_element_vec.push(element);\n", "file_path": "native_implemented/otp/src/erlang/insert_element_3.rs", "rank": 15, "score": 296680.66814168514 }, { "content": "#[native_implemented::function(erlang:start_timer/4)]\n\npub fn result(\n\n arc_process: Arc<Process>,\n\n time: Term,\n\n destination: Term,\n\n message: Term,\n\n options: Term,\n\n) -> exception::Result<Term> {\n\n let timer_start_options: timer::start::Options = options.try_into()?;\n\n\n\n start_timer(\n\n time,\n\n destination,\n\n Format::TimeoutTuple,\n\n message,\n\n timer_start_options,\n\n arc_process,\n\n )\n\n .map_err(From::from)\n\n}\n", "file_path": "native_implemented/otp/src/erlang/start_timer_4.rs", "rank": 16, "score": 296680.66814168514 }, { "content": "#[native_implemented::function(erlang:spawn_link/3)]\n\npub fn result(\n\n process: &Process,\n\n module: Term,\n\n function: Term,\n\n arguments: Term,\n\n) -> exception::Result<Term> {\n\n let mut options: Options = Default::default();\n\n options.link = true;\n\n\n\n spawn_apply_3::result(process, options, module, function, arguments)\n\n}\n", "file_path": "native_implemented/otp/src/erlang/spawn_link_3.rs", "rank": 17, "score": 296680.66814168514 }, { "content": "#[native_implemented::function(erlang:start_timer/3)]\n\npub fn result(\n\n arc_process: Arc<Process>,\n\n time: Term,\n\n destination: Term,\n\n message: Term,\n\n) -> exception::Result<Term> {\n\n start_timer(\n\n time,\n\n destination,\n\n Format::TimeoutTuple,\n\n message,\n\n Default::default(),\n\n arc_process,\n\n )\n\n .map_err(From::from)\n\n}\n", "file_path": "native_implemented/otp/src/erlang/start_timer_3.rs", "rank": 18, "score": 296680.66814168514 }, { "content": "#[native_implemented::function(Elixir.Lumen.Web.Element:set_attribute/3)]\n\npub fn result(\n\n process: &Process,\n\n element_term: Term,\n\n name: Term,\n\n value: Term,\n\n) -> exception::Result<Term> {\n\n let element = element::from_term(element_term)?;\n\n\n\n let name_string: String = binary_to_string(name)?;\n\n let value_string: String = binary_to_string(value)?;\n\n\n\n match element.set_attribute(&name_string, &value_string) {\n\n Ok(()) => Ok(atom!(\"ok\")),\n\n // InvalidCharacterError JsValue\n\n Err(_) => {\n\n let name_tag = Atom::str_to_term(\"name\");\n\n let reason = process.tuple_from_slice(&[name_tag, name]);\n\n\n\n let error = atom!(\"error\");\n\n\n\n Ok(process.tuple_from_slice(&[error, reason]))\n\n }\n\n }\n\n}\n", "file_path": "native_implemented/web/src/element/set_attribute_3.rs", "rank": 19, "score": 296680.66814168514 }, { "content": "#[native_implemented::function(erlang:spawn_opt/4)]\n\npub fn result(\n\n process: &Process,\n\n module: Term,\n\n function: Term,\n\n arguments: Term,\n\n options: Term,\n\n) -> exception::Result<Term> {\n\n let options_options: Options = options.try_into()?;\n\n\n\n spawn_apply_3::result(process, options_options, module, function, arguments)\n\n}\n", "file_path": "native_implemented/otp/src/erlang/spawn_opt_4.rs", "rank": 20, "score": 296680.66814168514 }, { "content": "#[native_implemented::function(erlang:binary_part/3)]\n\npub fn result(\n\n process: &Process,\n\n binary: Term,\n\n start: Term,\n\n length: Term,\n\n) -> exception::Result<Term> {\n\n let start_usize: usize = start\n\n .try_into()\n\n .with_context(|| term_is_not_non_negative_integer(\"start\", start))?;\n\n let length_isize = term_try_into_isize!(length)?;\n\n\n\n match binary.decode().unwrap() {\n\n TypedTerm::HeapBinary(heap_binary) => {\n\n let available_byte_count = heap_binary.full_byte_len();\n\n let PartRange {\n\n byte_offset,\n\n byte_len,\n\n } = start_length_to_part_range(start_usize, length_isize, available_byte_count)?;\n\n\n\n let binary_part = if (byte_offset == 0) && (byte_len == available_byte_count) {\n", "file_path": "native_implemented/otp/src/erlang/binary_part_3.rs", "rank": 21, "score": 296680.66814168514 }, { "content": "#[native_implemented::function(erlang:spawn_monitor/3)]\n\npub fn result(\n\n process: &Process,\n\n module: Term,\n\n function: Term,\n\n arguments: Term,\n\n) -> exception::Result<Term> {\n\n let options = Options {\n\n monitor: true,\n\n ..Default::default()\n\n };\n\n\n\n spawn_apply_3::result(process, options, module, function, arguments)\n\n}\n", "file_path": "native_implemented/otp/src/erlang/spawn_monitor_3.rs", "rank": 22, "score": 296680.66814168514 }, { "content": "pub fn result(\n\n process: &Process,\n\n iolist_or_binary: Term,\n\n try_into: fn(&Process, Term) -> exception::Result<Term>,\n\n) -> exception::Result<Term> {\n\n match iolist_or_binary.decode()? {\n\n TypedTerm::Nil\n\n | TypedTerm::List(_)\n\n | TypedTerm::BinaryLiteral(_)\n\n | TypedTerm::HeapBinary(_)\n\n | TypedTerm::MatchContext(_)\n\n | TypedTerm::ProcBin(_)\n\n | TypedTerm::SubBinary(_) => try_into(process, iolist_or_binary),\n\n _ => Err(TypeError)\n\n .context(term_is_not_type(\n\n \"iolist_or_binary\",\n\n iolist_or_binary,\n\n &format!(\"an iolist ({}) or binary\", r#type::IOLIST),\n\n ))\n\n .map_err(From::from),\n\n }\n\n}\n\n\n", "file_path": "native_implemented/otp/src/erlang/iolist_or_binary.rs", "rank": 23, "score": 296680.66814168514 }, { "content": "#[native_implemented::function(erlang:make_tuple/3)]\n\npub fn result(\n\n process: &Process,\n\n arity: Term,\n\n default_value: Term,\n\n init_list: Term,\n\n) -> exception::Result<Term> {\n\n // arity by definition is only 0-225, so `u8`, but ...\n\n let arity_u8 = term_try_into_arity(arity)?;\n\n // ... everything else uses `usize`, so cast it back up\n\n let arity_usize: usize = arity_u8 as usize;\n\n\n\n let mut heap = process.acquire_heap();\n\n let mut tuple = heap.mut_tuple(arity_usize)?;\n\n\n\n for index in 0..arity_usize {\n\n tuple.set_element(index, default_value).unwrap();\n\n }\n\n\n\n match init_list.decode().unwrap() {\n\n TypedTerm::Nil => Ok(tuple.encode()?),\n", "file_path": "native_implemented/otp/src/erlang/make_tuple_3.rs", "rank": 24, "score": 296680.66814168514 }, { "content": "pub fn try_split_at(bytes: &[u8], mid: usize) -> InternalResult<(&[u8], &[u8])> {\n\n let available = bytes.len();\n\n\n\n if mid <= available {\n\n Ok(bytes.split_at(mid))\n\n } else {\n\n {\n\n Err(DecodeError::NotEnoughBytes {\n\n available,\n\n needed: mid,\n\n backtrace: Backtrace::capture(),\n\n }\n\n .into())\n\n }\n\n }\n\n}\n\n\n\n#[derive(Debug, Error)]\n\npub enum DecodeError {\n\n #[error(\"needed {needed} bytes, but only {available} available\")]\n", "file_path": "runtimes/core/src/distribution/external_term_format.rs", "rank": 25, "score": 294274.74112786935 }, { "content": "pub fn setup() {\n\n let working_directory = lumen_otp_directory().join(\"lib/snmp/mibs\");\n\n\n\n let mut command = Command::new(\"make\");\n\n command.current_dir(&working_directory);\n\n\n\n if let Err((command, output)) = crate::test::timeout(\n\n \"make\",\n\n working_directory.clone(),\n\n command,\n\n Duration::from_secs(10),\n\n ) {\n\n crate::test::command_failed(\"make\", working_directory, command, output)\n\n }\n\n}\n", "file_path": "native_implemented/otp/tests/external/lumen/otp/lib/snmp/mibs.rs", "rank": 26, "score": 294130.39771680126 }, { "content": "pub fn setup() {\n\n let working_directory = lumen_otp_directory().join(\"lib/public_key/asn1\");\n\n\n\n let mut command = Command::new(\"make\");\n\n command.current_dir(&working_directory);\n\n\n\n if let Err((command, output)) = crate::test::timeout(\n\n \"make\",\n\n working_directory.clone(),\n\n command,\n\n Duration::from_secs(10),\n\n ) {\n\n crate::test::command_failed(\"make\", working_directory, command, output)\n\n }\n\n}\n", "file_path": "native_implemented/otp/tests/external/lumen/otp/lib/public_key.rs", "rank": 27, "score": 294130.39771680126 }, { "content": "#[native_implemented::function(erlang:convert_time_unit/3)]\n\npub fn result(\n\n process: &Process,\n\n time: Term,\n\n from_unit: Term,\n\n to_unit: Term,\n\n) -> exception::Result<Term> {\n\n let time_big_int: BigInt = time\n\n .try_into()\n\n .with_context(|| format!(\"time ({}) must be an integer\", time))?;\n\n let from_unit_unit = term_try_into_time_unit!(from_unit)?;\n\n let to_unit_unit = term_try_into_time_unit!(to_unit)?;\n\n let converted_big_int = time::convert(time_big_int, from_unit_unit, to_unit_unit);\n\n let converted_term = process.integer(converted_big_int);\n\n\n\n Ok(converted_term)\n\n}\n", "file_path": "native_implemented/otp/src/erlang/convert_time_unit_3.rs", "rank": 28, "score": 293659.0217609097 }, { "content": "pub fn bits_to_bytes(bits: usize) -> usize {\n\n (bits + 7) / 8\n\n}\n\n\n", "file_path": "native_implemented/otp/src/test/strategy.rs", "rank": 29, "score": 291098.9299951008 }, { "content": "#[native_implemented::function(Elixir.Lumen.Web.Node.ReplaceChild3:with_new_child_returns_ok_replaced_child/0)]\n\npub fn result(process: &Process) -> Term {\n\n // ```elixir\n\n // # pushed to stack: ()\n\n // # returned from call: N/A\n\n // # full stack: ()\n\n // # returns: {:ok, parent_document}\n\n // ```\n\n process.queue_frame_with_arguments(document::new_0::frame().with_arguments(false, &[]));\n\n // ```elixir\n\n // # label 1\n\n // # pushed to stack: ()\n\n // # returned form call: {:ok, document}\n\n // # full stack: ({:ok, document})\n\n // # returns: {:ok parent}\n\n // {:ok, old_child} = Lumen.Web.Document.create_element(document, \"table\")\n\n // {:ok, parent} = Lumen.Web.Document.create_element(parent_document, \"div\")\n\n // :ok = Lumen.Web.Node.append_child(parent, old_child)\n\n // {:ok, new_child} = Lumen.Web.Document.create_element(document, \"ul\");\n\n // {:ok, replaced_child} = Lumen.Web.replace_child(parent, new_child, old_child)\n\n // ```\n\n process.queue_frame_with_arguments(label_1::frame().with_arguments(true, &[]));\n\n\n\n Term::NONE\n\n}\n", "file_path": "native_implemented/web/tests/web/node/replace_child_3/with_new_child_returns_ok_replaced_child.rs", "rank": 30, "score": 289634.60227618157 }, { "content": "#[native_implemented::function(erlang:node/0)]\n\npub fn result() -> Term {\n\n node::term()\n\n}\n", "file_path": "native_implemented/otp/src/erlang/node_0.rs", "rank": 31, "score": 286036.652629373 }, { "content": "#[native_implemented::function(erlang:is_alive/0)]\n\npub fn result() -> Term {\n\n false.into()\n\n}\n", "file_path": "native_implemented/otp/src/erlang/is_alive_0.rs", "rank": 32, "score": 286036.652629373 }, { "content": "pub fn main() -> anyhow::Result<()> {\n\n // Handle unexpected panics by presenting a user-friendly bug report prompt;\n\n // except when we're requesting debug info from the compiler explicitly, in\n\n // which case we don't want to hide the panic\n\n if env::var_os(\"LUMEN_LOG\").is_none() {\n\n human_panic::setup_panic!();\n\n }\n\n\n\n // Initialize logger\n\n let mut builder = env_logger::from_env(\"LUMEN_LOG\");\n\n builder.format_indent(Some(2));\n\n if let Ok(precision) = env::var(\"LUMEN_LOG_WITH_TIME\") {\n\n match precision.as_str() {\n\n \"s\" => builder.format_timestamp_secs(),\n\n \"ms\" => builder.format_timestamp_millis(),\n\n \"us\" => builder.format_timestamp_micros(),\n\n \"ns\" => builder.format_timestamp_nanos(),\n\n other => bail!(\n\n \"invalid LUMEN_LOG_WITH_TIME precision, expected one of [s, ms, us, ns], got '{}'\",\n\n other\n", "file_path": "lumen/src/main.rs", "rank": 33, "score": 283425.60951555724 }, { "content": "/// Parses the provided arguments\n\npub fn parse<'a>(args: impl Iterator<Item = OsString>) -> clap::Result<ArgMatches<'a>> {\n\n parser().get_matches_from_safe(args)\n\n}\n\n\n", "file_path": "compiler/driver/src/argparser.rs", "rank": 34, "score": 283031.3021001715 }, { "content": "pub fn external_arc_node() -> Arc<Node> {\n\n Arc::new(Node::new(\n\n 1,\n\n Atom::try_from_str(\"node@external\").unwrap(),\n\n 0,\n\n ))\n\n}\n\n\n", "file_path": "native_implemented/otp/src/test/proptest.rs", "rank": 35, "score": 281576.89753035485 }, { "content": "pub fn try_id_to_arc_node(id: &usize) -> Result<Arc<Node>, NodeNotFound> {\n\n match id_to_arc_node(id) {\n\n Some(arc_node) => Ok(arc_node),\n\n None => Err(NodeNotFound::ID {\n\n id: *id,\n\n backtrace: Backtrace::capture(),\n\n }),\n\n }\n\n}\n\n\n", "file_path": "runtimes/core/src/distribution/nodes.rs", "rank": 36, "score": 280447.4441003651 }, { "content": "pub fn number() -> BoxedStrategy<usize> {\n\n (0..=Pid::NUMBER_MAX).boxed()\n\n}\n\n\n", "file_path": "native_implemented/otp/src/test/strategy/term/pid.rs", "rank": 37, "score": 278107.23682751186 }, { "content": "pub fn strategy() -> BoxedStrategy<usize> {\n\n RANGE_INCLUSIVE.boxed()\n\n}\n", "file_path": "native_implemented/otp/src/test/strategy/size_range.rs", "rank": 38, "score": 278107.23682751186 }, { "content": "pub fn serial() -> BoxedStrategy<usize> {\n\n (0..=Pid::SERIAL_MAX).boxed()\n\n}\n", "file_path": "native_implemented/otp/src/test/strategy/term/pid.rs", "rank": 39, "score": 278107.23682751186 }, { "content": "pub fn external() -> BoxedStrategy<Atom> {\n\n any::<String>()\n\n .prop_map(|s| Atom::try_from_str(&format!(\"{}@external\", s)).unwrap())\n\n .boxed()\n\n}\n", "file_path": "native_implemented/otp/src/test/strategy/node/atom.rs", "rank": 40, "score": 277979.3038716413 }, { "content": "pub fn monitored_count(process: &Process) -> usize {\n\n process.monitored_pid_by_reference.len()\n\n}\n\n\n", "file_path": "native_implemented/otp/src/test/proptest.rs", "rank": 41, "score": 276784.1222237598 }, { "content": "pub fn monitor_count(process: &Process) -> usize {\n\n process.monitor_by_reference.len()\n\n}\n\n\n", "file_path": "native_implemented/otp/src/test/proptest.rs", "rank": 42, "score": 276784.1222237598 }, { "content": "#[native_implemented::function(erlang:not/1)]\n\npub fn result(boolean: Term) -> exception::Result<Term> {\n\n let boolean_bool: bool = term_try_into_bool(\"boolean\", boolean)?;\n\n let output = !boolean_bool;\n\n\n\n Ok(output.into())\n\n}\n", "file_path": "native_implemented/otp/src/erlang/not_1.rs", "rank": 43, "score": 276372.5119077774 }, { "content": "#[native_implemented::function(erlang:tl/1)]\n\npub fn result(list: Term) -> exception::Result<Term> {\n\n let cons: Boxed<Cons> = term_try_into_non_empty_list!(list)?;\n\n\n\n Ok(cons.tail)\n\n}\n", "file_path": "native_implemented/otp/src/erlang/tl_1.rs", "rank": 44, "score": 273833.71060627914 }, { "content": "#[native_implemented::function(erlang:unregister/1)]\n\npub fn result(name: Term) -> exception::Result<Term> {\n\n let atom = term_try_into_atom!(name)?;\n\n\n\n if registry::unregister(&atom) {\n\n Ok(true.into())\n\n } else {\n\n Err(anyhow!(\"name ({}) was not registered\", name).into())\n\n }\n\n}\n", "file_path": "native_implemented/otp/src/erlang/unregister_1.rs", "rank": 45, "score": 273833.71060627914 }, { "content": "#[native_implemented::function(erlang:hd/1)]\n\npub fn result(list: Term) -> exception::Result<Term> {\n\n let cons: Boxed<Cons> = term_try_into_non_empty_list!(list)?;\n\n\n\n Ok(cons.head)\n\n}\n", "file_path": "native_implemented/otp/src/erlang/hd_1.rs", "rank": 46, "score": 273833.71060627914 }, { "content": "#[native_implemented::function(erlang:throw/1)]\n\npub fn result(reason: Term) -> exception::Result<Term> {\n\n Err(throw(\n\n reason,\n\n Trace::capture(),\n\n Some(anyhow!(\"explicit throw from Erlang\").into()),\n\n )\n\n .into())\n\n}\n", "file_path": "native_implemented/otp/src/erlang/throw_1.rs", "rank": 47, "score": 273833.71060627914 }, { "content": "#[native_implemented::function(erlang:whereis/1)]\n\npub fn result(name: Term) -> exception::Result<Term> {\n\n let atom = term_try_into_atom!(name)?;\n\n let option = registry::atom_to_process(&atom).map(|arc_process| arc_process.pid());\n\n\n\n let term = match option {\n\n Some(pid) => pid.encode()?,\n\n None => atom!(\"undefined\"),\n\n };\n\n\n\n Ok(term)\n\n}\n", "file_path": "native_implemented/otp/src/erlang/whereis_1.rs", "rank": 48, "score": 273833.71060627914 }, { "content": "#[native_implemented::function(erlang:registered/0)]\n\npub fn result(process: &Process) -> exception::Result<Term> {\n\n registry::names(process)\n\n}\n", "file_path": "native_implemented/otp/src/erlang/registered_0.rs", "rank": 49, "score": 273833.71060627914 }, { "content": "#[native_implemented::function(erlang:error/1)]\n\npub fn result(reason: Term) -> exception::Result<Term> {\n\n Err(error(\n\n reason,\n\n None,\n\n Trace::capture(),\n\n Some(anyhow!(\"explicit error from Erlang\").into()),\n\n )\n\n .into())\n\n}\n", "file_path": "native_implemented/otp/src/erlang/error_1.rs", "rank": 50, "score": 273833.71060627914 }, { "content": "pub fn external() -> BoxedStrategy<Arc<Node>> {\n\n (id::external(), atom::external(), any::<u32>())\n\n .prop_map(|(id, atom, creation)| {\n\n let arc_node = Arc::new(Node::new(id, atom, creation));\n\n\n\n nodes::insert(arc_node.clone());\n\n\n\n arc_node\n\n })\n\n .boxed()\n\n}\n\n\n", "file_path": "native_implemented/otp/src/test/strategy/node.rs", "rank": 51, "score": 273056.3987919032 }, { "content": "#[inline(always)]\n\npub fn divide_round_up(x: usize, y: usize) -> usize {\n\n assert!(y > 0);\n\n (x + y - 1) / y\n\n}\n\n\n\n// Returns `size` rounded up to a multiple of `base`.\n", "file_path": "liblumen_core/src/alloc/utils.rs", "rank": 52, "score": 272005.4146724607 }, { "content": "#[native_implemented::function(erlang:+/1)]\n\npub fn result(number: Term) -> exception::Result<Term> {\n\n if number.is_number() {\n\n Ok(number)\n\n } else {\n\n Err(badarith(\n\n Trace::capture(),\n\n Some(anyhow!(\"number ({}) is not an integer or a float\", number).into()),\n\n )\n\n .into())\n\n }\n\n}\n", "file_path": "native_implemented/otp/src/erlang/number_or_badarith_1.rs", "rank": 53, "score": 271370.3787359764 }, { "content": "#[native_implemented::function(erlang:module_loaded/1)]\n\npub fn result(module: Term) -> exception::Result<Term> {\n\n let module_atom = term_try_into_atom!(module)?;\n\n\n\n Ok(module_loaded(module_atom).into())\n\n}\n", "file_path": "native_implemented/otp/src/erlang/module_loaded_1.rs", "rank": 54, "score": 271370.3787359764 }, { "content": "#[native_implemented::function(erlang:list_to_atom/1)]\n\npub fn result(string: Term) -> exception::Result<Term> {\n\n list_to_string(string).and_then(|s| match Atom::try_from_str(s) {\n\n Ok(atom) => Ok(atom.encode()?),\n\n Err(atom_error) => Err(atom_error)\n\n .context(format!(\"string ({}) cannot be converted to atom\", string))\n\n .map_err(From::from),\n\n })\n\n}\n", "file_path": "native_implemented/otp/src/erlang/list_to_atom_1.rs", "rank": 55, "score": 271370.3787359764 }, { "content": "#[native_implemented::function(erlang:nif_error/1)]\n\npub fn result(reason: Term) -> exception::Result<Term> {\n\n Err(error(\n\n reason,\n\n None,\n\n Trace::capture(),\n\n Some(anyhow!(\"explicit nif_error from Erlang\").into()),\n\n )\n\n .into())\n\n}\n", "file_path": "native_implemented/otp/src/erlang/nif_error_1.rs", "rank": 56, "score": 271370.3787359764 }, { "content": "#[native_implemented::function(erlang:system_info/1)]\n\npub fn result(item: Term) -> exception::Result<Term> {\n\n match item.decode().unwrap() {\n\n TypedTerm::Atom(atom) => match atom.name() {\n\n \"alloc_util_allocators\" => unimplemented!(),\n\n \"allocated_areas\" => unimplemented!(),\n\n \"allocator\" => unimplemented!(),\n\n \"atom_count\" => unimplemented!(),\n\n \"atom_limit\" => unimplemented!(),\n\n \"build_type\" => unimplemented!(),\n\n \"c_compiler_used\" => unimplemented!(),\n\n \"check_io\" => unimplemented!(),\n\n \"compat_rel\" => unimplemented!(),\n\n \"cpu_quota\" => unimplemented!(),\n\n \"cpu_topology\" => unimplemented!(),\n\n \"creation\" => unimplemented!(),\n\n \"debug_compiled\" => unimplemented!(),\n\n \"delayed_node_table_gc\" => unimplemented!(),\n\n \"dirty_cpu_schedulers\" => unimplemented!(),\n\n \"dirty_cpu_schedulers_online\" => unimplemented!(),\n\n \"dirty_io_schedulers\" => unimplemented!(),\n", "file_path": "native_implemented/otp/src/erlang/system_info_1.rs", "rank": 57, "score": 271370.3787359764 }, { "content": "pub fn byte_offset() -> BoxedStrategy<usize> {\n\n size_range::strategy()\n\n}\n\n\n", "file_path": "native_implemented/otp/src/test/strategy/term/binary/sub.rs", "rank": 58, "score": 271260.3713782528 }, { "content": "pub fn byte_count() -> BoxedStrategy<usize> {\n\n size_range::strategy()\n\n}\n\n\n", "file_path": "native_implemented/otp/src/test/strategy/term/binary/sub.rs", "rank": 59, "score": 271260.3713782528 }, { "content": "pub fn external() -> BoxedStrategy<Creator> {\n\n (node::external(), pid::number(), pid::serial())\n\n .prop_map(|(arc_node, number, serial)| ExternalPid::new(arc_node, number, serial).unwrap())\n\n .prop_map(|external_pid| Creator::External(external_pid))\n\n .boxed()\n\n}\n\n\n", "file_path": "native_implemented/otp/src/test/strategy/term/function/anonymous/creator.rs", "rank": 60, "score": 271136.6168078692 }, { "content": "#[native_implemented::function(erlang:list_to_existing_atom/1)]\n\npub fn result(string: Term) -> exception::Result<Term> {\n\n let string_string = list_to_string(string)?;\n\n let atom = Atom::try_from_str_existing(string_string)\n\n .with_context(|| format!(\"string ({})\", string))?;\n\n\n\n atom.encode().map_err(From::from)\n\n}\n", "file_path": "native_implemented/otp/src/erlang/list_to_existing_atom_1.rs", "rank": 61, "score": 268979.0923815926 }, { "content": "#[inline]\n\npub fn default_heap() -> AllocResult<(*mut Term, usize)> {\n\n let size = default_heap_size();\n\n PROC_ALLOC.alloc(size).map(|ptr| (ptr, size))\n\n}\n\n\n", "file_path": "liblumen_alloc/src/erts/process/alloc.rs", "rank": 62, "score": 267850.53388951893 }, { "content": "#[inline]\n\npub fn stack(num_pages: usize) -> AllocResult<Stack> {\n\n use liblumen_core::alloc::mmap;\n\n\n\n debug_assert!(num_pages > 0, \"stack size in pages must be greater than 0\");\n\n\n\n let ptr = unsafe { mmap::map_stack(num_pages)? };\n\n Ok(Stack::new(ptr.as_ptr(), num_pages))\n\n}\n\n\n\n/// Reallocate a process heap, in place\n\n///\n\n/// If reallocating and trying to grow the heap, if the allocation cannot be done\n\n/// in place, then `Err(AllocErr)` will be returned\n\n#[inline]\n\npub unsafe fn realloc(\n\n heap: *mut Term,\n\n size: usize,\n\n new_size: usize,\n\n) -> Result<*mut Term, AllocErr> {\n\n PROC_ALLOC.realloc_in_place(heap, size, new_size)\n\n}\n\n\n\n/// Deallocate a heap previously allocated via `heap`\n\n#[inline]\n\npub unsafe fn free(heap: *mut Term, size: usize) {\n\n PROC_ALLOC.dealloc(heap, size)\n\n}\n\n\n\n/// Calculates the next largest heap size equal to or greater than `size`\n", "file_path": "liblumen_alloc/src/erts/process/alloc.rs", "rank": 63, "score": 267850.53388951893 }, { "content": "pub fn timeout(\n\n message: &'static str,\n\n working_directory: PathBuf,\n\n mut command: Command,\n\n time_limit: Duration,\n\n) -> Result<(), (Command, Output)> {\n\n let process = command\n\n .stdin(Stdio::null())\n\n .stdout(Stdio::piped())\n\n .stderr(Stdio::piped())\n\n .spawn()\n\n .unwrap();\n\n\n\n match process\n\n .with_output_timeout(time_limit)\n\n .terminating()\n\n .wait()\n\n .unwrap()\n\n {\n\n Some(output) => {\n", "file_path": "native_implemented/otp/tests/test.rs", "rank": 64, "score": 267107.15034604096 }, { "content": "pub fn match_raw<B>(bin: B, _unit: u8, size: Option<usize>) -> Result<BinaryMatchResult, ()>\n\nwhere\n\n B: Bitstring + MaybePartialByte,\n\n{\n\n let size = size.unwrap_or(0);\n\n let total_bits = bin.total_bit_len();\n\n\n\n if size == 0 && total_bits == 0 {\n\n // TODO: t = bin_to_term\n\n let t = Term::NONE;\n\n return Ok(BinaryMatchResult::success(Term::NONE, t));\n\n }\n\n\n\n unimplemented!()\n\n}\n", "file_path": "liblumen_alloc/src/erts/term/binary/matcher.rs", "rank": 65, "score": 265776.92601344263 }, { "content": "pub fn non_empty() -> BoxedStrategy<usize> {\n\n NON_EMPTY_RANGE_INCLUSIVE.boxed()\n\n}\n", "file_path": "native_implemented/otp/src/test/strategy/term/binary/sub/byte_count.rs", "rank": 66, "score": 264846.60793114937 }, { "content": "pub fn check(bytes: &[u8]) -> InternalResult<&[u8]> {\n\n let (version, after_version_bytes) = u8::decode(bytes)?;\n\n\n\n if version == NUMBER {\n\n Ok(after_version_bytes)\n\n } else {\n\n Err(DecodeError::UnexpectedVersion {\n\n version,\n\n backtrace: Backtrace::capture(),\n\n }\n\n .into())\n\n }\n\n}\n", "file_path": "runtimes/core/src/distribution/external_term_format/version.rs", "rank": 67, "score": 264320.8413046525 }, { "content": "pub fn command_failed(\n\n message: &'static str,\n\n working_directory: PathBuf,\n\n command: Command,\n\n output: Output,\n\n) -> ! {\n\n let stdout = String::from_utf8_lossy(&output.stdout);\n\n let stderr = String::from_utf8_lossy(&output.stderr);\n\n let formatted_code = match output.status.code() {\n\n Some(code) => code.to_string(),\n\n None => \"\".to_string(),\n\n };\n\n let formatted_signal = signal(output.status);\n\n\n\n panic!(\n\n \"{} failed\\nCommands:\\ncd {}\\n{:?}\\n\\nstdout: {}\\nstderr: {}\\nStatus code: {}\\nSignal: {}\",\n\n message,\n\n working_directory.display(),\n\n command,\n\n stdout,\n\n stderr,\n\n formatted_code,\n\n formatted_signal\n\n );\n\n}\n\n\n", "file_path": "native_implemented/otp/tests/test.rs", "rank": 68, "score": 264168.6718908872 }, { "content": "#[inline]\n\npub fn heap(size: usize) -> AllocResult<*mut Term> {\n\n PROC_ALLOC.alloc(size)\n\n}\n\n\n\n/// Allocate a new process stack of the given size (in pages)\n", "file_path": "liblumen_alloc/src/erts/process/alloc.rs", "rank": 69, "score": 264123.90449884965 }, { "content": "#[native_implemented::function(erlang:is_list/1)]\n\npub fn result(term: Term) -> Term {\n\n term.is_list().into()\n\n}\n", "file_path": "native_implemented/otp/src/erlang/is_list_1.rs", "rank": 70, "score": 263402.57388942246 }, { "content": "#[native_implemented::function(erlang:get/0)]\n\npub fn result(process: &Process) -> Term {\n\n process.get_entries()\n\n}\n", "file_path": "native_implemented/otp/src/erlang/get_0.rs", "rank": 71, "score": 263402.57388942246 }, { "content": "#[native_implemented::function(erlang:time/0)]\n\npub fn result(process: &Process) -> Term {\n\n let time: [usize; 3] = datetime::local_time();\n\n\n\n process.tuple_from_slice(&[\n\n process.integer(time[0]),\n\n process.integer(time[1]),\n\n process.integer(time[2]),\n\n ])\n\n}\n", "file_path": "native_implemented/otp/src/erlang/time_0.rs", "rank": 72, "score": 263402.5738894224 }, { "content": "#[native_implemented::function(erlang:is_map/1)]\n\npub fn result(term: Term) -> Term {\n\n term.is_boxed_map().into()\n\n}\n", "file_path": "native_implemented/otp/src/erlang/is_map_1.rs", "rank": 73, "score": 263402.57388942246 }, { "content": "#[native_implemented::function(erlang:timestamp/0)]\n\npub fn result(process: &Process) -> Term {\n\n let big_int = system::time_in_unit(Microsecond);\n\n let erlang_timestamp = ErlangTimestamp::from_microseconds(&big_int);\n\n\n\n process.tuple_from_slice(&[\n\n process.integer(erlang_timestamp.megaseconds as usize),\n\n process.integer(erlang_timestamp.seconds as usize),\n\n process.integer(erlang_timestamp.microseconds as usize),\n\n ])\n\n}\n\n\n", "file_path": "native_implemented/otp/src/erlang/timestamp_0.rs", "rank": 74, "score": 263402.57388942246 }, { "content": "#[native_implemented::function(Elixir.Lumen.Web.Window:window/0)]\n\npub fn result(process: &Process) -> Term {\n\n let option_window = web_sys::window();\n\n\n\n option_to_ok_tuple_or_error(process, option_window)\n\n}\n", "file_path": "native_implemented/web/src/window/window_0.rs", "rank": 75, "score": 263402.5738894224 }, { "content": "#[native_implemented::function(erlang:is_tuple/1)]\n\npub fn result(term: Term) -> Term {\n\n match term.decode() {\n\n Ok(TypedTerm::Tuple(_)) => true.into(),\n\n _ => false.into(),\n\n }\n\n}\n", "file_path": "native_implemented/otp/src/erlang/is_tuple_1.rs", "rank": 76, "score": 263402.57388942246 }, { "content": "#[native_implemented::function(erlang:is_float/1)]\n\npub fn result(term: Term) -> Term {\n\n term.is_boxed_float().into()\n\n}\n", "file_path": "native_implemented/otp/src/erlang/is_float_1.rs", "rank": 77, "score": 263402.57388942246 }, { "content": "#[native_implemented::function(erlang:self/0)]\n\npub fn result(process: &Process) -> Term {\n\n process.pid_term()\n\n}\n", "file_path": "native_implemented/otp/src/erlang/self_0.rs", "rank": 78, "score": 263402.57388942246 }, { "content": "#[native_implemented::function(erlang:is_bitstring/1)]\n\npub fn result(term: Term) -> Term {\n\n term.is_bitstring().into()\n\n}\n", "file_path": "native_implemented/otp/src/erlang/is_bitstring_1.rs", "rank": 79, "score": 263402.5738894224 }, { "content": "#[native_implemented::function(erlang:is_number/1)]\n\npub fn result(term: Term) -> Term {\n\n term.is_number().into()\n\n}\n", "file_path": "native_implemented/otp/src/erlang/is_number_1.rs", "rank": 80, "score": 263402.5738894224 }, { "content": "#[native_implemented::function(erlang:display/1)]\n\npub fn result(term: Term) -> Term {\n\n runtime::sys::io::puts(&format!(\"{}\", term));\n\n\n\n atom!(\"ok\")\n\n}\n", "file_path": "native_implemented/otp/src/erlang/display_1.rs", "rank": 81, "score": 263402.57388942246 }, { "content": "#[native_implemented::function(erlang:is_reference/1)]\n\npub fn result(term: Term) -> Term {\n\n match term.decode().unwrap() {\n\n TypedTerm::Reference(_) => true,\n\n TypedTerm::ExternalReference(_) => true,\n\n TypedTerm::ResourceReference(_) => true,\n\n _ => false,\n\n }\n\n .into()\n\n}\n", "file_path": "native_implemented/otp/src/erlang/is_reference_1.rs", "rank": 82, "score": 263402.5738894224 }, { "content": "#[native_implemented::function(erlang:universaltime/0)]\n\npub fn result(process: &Process) -> Term {\n\n let now: [usize; 6] = datetime::utc_now();\n\n\n\n let date_tuple = process.tuple_from_slice(&[\n\n process.integer(now[0]),\n\n process.integer(now[1]),\n\n process.integer(now[2]),\n\n ]);\n\n let time_tuple = process.tuple_from_slice(&[\n\n process.integer(now[3]),\n\n process.integer(now[4]),\n\n process.integer(now[5]),\n\n ]);\n\n\n\n process.tuple_from_slice(&[date_tuple, time_tuple])\n\n}\n", "file_path": "native_implemented/otp/src/erlang/universaltime_0.rs", "rank": 83, "score": 263402.57388942246 }, { "content": "#[native_implemented::function(erlang:is_function/1)]\n\npub fn result(term: Term) -> Term {\n\n term.is_boxed_function().into()\n\n}\n", "file_path": "native_implemented/otp/src/erlang/is_function_1.rs", "rank": 84, "score": 263402.57388942246 }, { "content": "#[native_implemented::function(erlang:now/0)]\n\npub fn result(process: &Process) -> Term {\n\n timestamp_0::result(process)\n\n}\n", "file_path": "native_implemented/otp/src/erlang/now_0.rs", "rank": 85, "score": 263402.5738894224 }, { "content": "#[native_implemented::function(erlang:localtime/0)]\n\npub fn result(process: &Process) -> Term {\n\n let now: [usize; 6] = datetime::local_now();\n\n\n\n let date_tuple = process.tuple_from_slice(&[\n\n process.integer(now[0]),\n\n process.integer(now[1]),\n\n process.integer(now[2]),\n\n ]);\n\n let time_tuple = process.tuple_from_slice(&[\n\n process.integer(now[3]),\n\n process.integer(now[4]),\n\n process.integer(now[5]),\n\n ]);\n\n\n\n process.tuple_from_slice(&[date_tuple, time_tuple])\n\n}\n", "file_path": "native_implemented/otp/src/erlang/localtime_0.rs", "rank": 86, "score": 263402.5738894224 }, { "content": "#[native_implemented::function(erlang:is_atom/1)]\n\npub fn result(term: Term) -> Term {\n\n term.is_atom().into()\n\n}\n", "file_path": "native_implemented/otp/src/erlang/is_atom_1.rs", "rank": 87, "score": 263402.5738894224 }, { "content": "#[native_implemented::function(erlang:erase/0)]\n\npub fn result(process: &Process) -> Term {\n\n process.erase_entries()\n\n}\n", "file_path": "native_implemented/otp/src/erlang/erase_0.rs", "rank": 88, "score": 263402.5738894224 }, { "content": "#[native_implemented::function(erlang:is_boolean/1)]\n\npub fn result(term: Term) -> Term {\n\n term.is_boolean().into()\n\n}\n", "file_path": "native_implemented/otp/src/erlang/is_boolean_1.rs", "rank": 89, "score": 263402.57388942246 }, { "content": "#[native_implemented::function(erlang:is_pid/1)]\n\npub fn result(term: Term) -> Term {\n\n term.is_pid().into()\n\n}\n", "file_path": "native_implemented/otp/src/erlang/is_pid_1.rs", "rank": 90, "score": 263402.57388942246 }, { "content": "#[native_implemented::function(erlang:is_integer/1)]\n\npub fn result(term: Term) -> Term {\n\n term.is_integer().into()\n\n}\n", "file_path": "native_implemented/otp/src/erlang/is_integer_1.rs", "rank": 91, "score": 263402.57388942246 }, { "content": "#[native_implemented::function(erlang:date/0)]\n\npub fn result(process: &Process) -> Term {\n\n let date: [usize; 3] = datetime::local_date();\n\n\n\n process.tuple_from_slice(&[\n\n process.integer(date[0]),\n\n process.integer(date[1]),\n\n process.integer(date[2]),\n\n ])\n\n}\n", "file_path": "native_implemented/otp/src/erlang/date_0.rs", "rank": 92, "score": 263402.5738894224 }, { "content": "#[native_implemented::function(erlang:is_binary/1)]\n\npub fn result(term: Term) -> Term {\n\n term.is_binary().into()\n\n}\n", "file_path": "native_implemented/otp/src/erlang/is_binary_1.rs", "rank": 93, "score": 263402.57388942246 }, { "content": "#[native_implemented::function(test:return_from_fn/0)]\n\nfn result() -> Term {\n\n returned()\n\n}\n", "file_path": "native_implemented/otp/src/test/return_from_fn_0.rs", "rank": 94, "score": 262557.98417152104 }, { "content": "#[inline(always)]\n\npub fn test_nth_bit(value: u8, index: usize) -> bool {\n\n value & (1 << index) != 0\n\n}\n\n\n", "file_path": "runtimes/full/src/alloc/common.rs", "rank": 95, "score": 261714.93666816692 }, { "content": "#[native_implemented::function(erlang:get_stacktrace/0)]\n\npub fn result(process: &Process) -> Term {\n\n match *process.status.read() {\n\n Status::RuntimeException(ref exc) => exc.stacktrace().as_term().unwrap(),\n\n _ => Term::NIL,\n\n }\n\n}\n", "file_path": "native_implemented/otp/src/erlang/get_stacktrace_0.rs", "rank": 96, "score": 260586.66078449224 }, { "content": "#[native_implemented::function(erlang:group_leader/0)]\n\npub fn result(process: &Process) -> Term {\n\n process.get_group_leader_pid_term()\n\n}\n", "file_path": "native_implemented/otp/src/erlang/group_leader_0.rs", "rank": 97, "score": 260586.66078449224 }, { "content": "#[native_implemented::function(erlang:monotonic_time/0)]\n\npub fn result(process: &Process) -> Term {\n\n let big_int = monotonic::time_in_unit(Native);\n\n\n\n process.integer(big_int)\n\n}\n", "file_path": "native_implemented/otp/src/erlang/monotonic_time_0.rs", "rank": 98, "score": 260586.66078449224 }, { "content": "#[native_implemented::function(erlang:get_keys/0)]\n\npub fn result(process: &Process) -> Term {\n\n process.get_keys()\n\n}\n", "file_path": "native_implemented/otp/src/erlang/get_keys_0.rs", "rank": 99, "score": 260586.66078449224 } ]
Rust
ipp-util/src/util.rs
simlay/ipp-sys
3b894faf6eb0533663c2d83fea0c9e851ac2d188
use std::{ffi::OsString, io, path::PathBuf}; use futures::{future, Future}; use structopt::StructOpt; use tokio::io::AsyncRead; use ipp_client::{IppClient, IppClientBuilder, IppError}; use ipp_proto::ipp::DelimiterTag; use ipp_proto::{IppAttribute, IppOperationBuilder, IppValue}; fn new_client(uri: &str, params: &IppParams) -> IppClient { IppClientBuilder::new(&uri) .timeout(params.timeout) .ca_certs(&params.ca_certs) .verify_hostname(!params.no_verify_hostname) .verify_certificate(!params.no_verify_certificate) .build() } struct JobSource { inner: Box<dyn AsyncRead + Send>, } fn new_source(cmd: &IppPrintCmd) -> Box<dyn Future<Item = JobSource, Error = io::Error> + Send + 'static> { match cmd.file { Some(ref filename) => Box::new( tokio::fs::File::open(filename.to_owned()).and_then(|file| Ok(JobSource { inner: Box::new(file) })), ), None => Box::new(future::ok(JobSource { inner: Box::new(tokio::io::stdin()), })), } } fn do_print(params: &IppParams, cmd: IppPrintCmd) -> Result<(), IppError> { let mut runtime = tokio::runtime::Runtime::new().unwrap(); let client = new_client(&cmd.uri, params); if !cmd.no_check_state { runtime.block_on(client.check_ready())?; } runtime.block_on(new_source(&cmd).map_err(IppError::from).and_then(move |source| { let mut builder = IppOperationBuilder::print_job(source.inner); if let Some(jobname) = cmd.job_name { builder = builder.job_title(&jobname); } if let Some(username) = cmd.user_name { builder = builder.user_name(&username); } for arg in cmd.options { let mut kv = arg.split('='); if let Some(k) = kv.next() { if let Some(v) = kv.next() { let value = if let Ok(iv) = v.parse::<i32>() { IppValue::Integer(iv) } else if v == "true" || v == "false" { IppValue::Boolean(v == "true") } else { IppValue::Keyword(v.to_string()) }; builder = builder.attribute(IppAttribute::new(k, value)); } } } client.send(builder.build()).and_then(|attrs| { if let Some(group) = attrs.groups_of(DelimiterTag::JobAttributes).get(0) { for v in group.attributes().values() { println!("{}: {}", v.name(), v.value()); } } Ok(()) }) })) } fn do_status(params: &IppParams, cmd: IppStatusCmd) -> Result<(), IppError> { let client = new_client(&cmd.uri, &params); let operation = IppOperationBuilder::get_printer_attributes() .attributes(&cmd.attributes) .build(); let mut runtime = tokio::runtime::Runtime::new().unwrap(); let attrs = runtime.block_on(client.send(operation))?; if let Some(group) = attrs.groups_of(DelimiterTag::PrinterAttributes).get(0) { let mut values: Vec<_> = group.attributes().values().collect(); values.sort_by(|a, b| a.name().cmp(b.name())); for v in values { println!("{}: {}", v.name(), v.value()); } } Ok(()) } #[derive(StructOpt)] #[structopt(name = "IPP print utility", about = "", author = "", rename_all = "kebab-case")] struct IppParams { #[structopt( long = "ca-cert", short = "c", global = true, help = "Additional CA root certificates in PEM or DER format" )] ca_certs: Vec<String>, #[structopt( long = "no-verify-hostname", global = true, help = "Disable TLS host name verification (insecure!)" )] no_verify_hostname: bool, #[structopt( long = "no-verify-certificate", global = true, help = "Disable TLS certificate verification (insecure!)" )] no_verify_certificate: bool, #[structopt( default_value = "0", long = "timeout", short = "t", global = true, help = "IPP request timeout in seconds, 0 = no timeout" )] timeout: u64, #[structopt(subcommand)] command: IppCommand, } #[derive(StructOpt)] enum IppCommand { #[structopt(name = "print", about = "Print file to an IPP printer", author = "")] Print(IppPrintCmd), #[structopt(name = "status", about = "Get status of an IPP printer", author = "")] Status(IppStatusCmd), } #[derive(StructOpt, Clone)] #[structopt(name = "IPP print utility", about = "", author = "", rename_all = "kebab-case")] struct IppPrintCmd { #[structopt(help = "Printer URI")] uri: String, #[structopt( long = "no-check-state", short = "n", help = "Do not check printer state before printing" )] no_check_state: bool, #[structopt( long = "file", short = "f", help = "Input file name to print [default: standard input]" )] file: Option<PathBuf>, #[structopt(long = "job-name", short = "j", help = "Job name to send as job-name attribute")] job_name: Option<String>, #[structopt( long = "user-name", short = "u", help = "User name to send as requesting-user-name attribute" )] user_name: Option<String>, #[structopt(long = "option", short = "o", help = "Extra IPP job attributes in key=value format")] options: Vec<String>, } #[derive(StructOpt, Clone)] #[structopt(name = "IPP print utility", about = "", author = "", rename_all = "kebab-case")] struct IppStatusCmd { #[structopt(help = "Printer URI")] uri: String, #[structopt(long = "attribute", short = "a", help = "Attributes to query, default is to get all")] attributes: Vec<String>, } pub fn ipp_main<I, T>(args: I) -> Result<(), IppError> where I: IntoIterator<Item = T>, T: Into<OsString> + Clone, { let params = IppParams::from_iter_safe(args).map_err(|e| IppError::ParamError(e.to_string()))?; match params.command { IppCommand::Status(ref cmd) => do_status(&params, cmd.clone())?, IppCommand::Print(ref cmd) => do_print(&params, cmd.clone())?, } Ok(()) }
use std::{ffi::OsString, io, path::PathBuf}; use futures::{future, Future}; use structopt::StructOpt; use tokio::io::AsyncRead; use ipp_client::{IppClient, IppClientBuilder, IppError}; use ipp_proto::ipp::DelimiterTag; use ipp_proto::{IppAttribute, IppOperationBuilder, IppValue}; fn new_client(uri: &str, params: &IppParams) -> IppClient { IppClientBuilder::new(&uri) .timeout(params.timeou
struct JobSource { inner: Box<dyn AsyncRead + Send>, } fn new_source(cmd: &IppPrintCmd) -> Box<dyn Future<Item = JobSource, Error = io::Error> + Send + 'static> { match cmd.file { Some(ref filename) => Box::new( tokio::fs::File::open(filename.to_owned()).and_then(|file| Ok(JobSource { inner: Box::new(file) })), ), None => Box::new(future::ok(JobSource { inner: Box::new(tokio::io::stdin()), })), } } fn do_print(params: &IppParams, cmd: IppPrintCmd) -> Result<(), IppError> { let mut runtime = tokio::runtime::Runtime::new().unwrap(); let client = new_client(&cmd.uri, params); if !cmd.no_check_state { runtime.block_on(client.check_ready())?; } runtime.block_on(new_source(&cmd).map_err(IppError::from).and_then(move |source| { let mut builder = IppOperationBuilder::print_job(source.inner); if let Some(jobname) = cmd.job_name { builder = builder.job_title(&jobname); } if let Some(username) = cmd.user_name { builder = builder.user_name(&username); } for arg in cmd.options { let mut kv = arg.split('='); if let Some(k) = kv.next() { if let Some(v) = kv.next() { let value = if let Ok(iv) = v.parse::<i32>() { IppValue::Integer(iv) } else if v == "true" || v == "false" { IppValue::Boolean(v == "true") } else { IppValue::Keyword(v.to_string()) }; builder = builder.attribute(IppAttribute::new(k, value)); } } } client.send(builder.build()).and_then(|attrs| { if let Some(group) = attrs.groups_of(DelimiterTag::JobAttributes).get(0) { for v in group.attributes().values() { println!("{}: {}", v.name(), v.value()); } } Ok(()) }) })) } fn do_status(params: &IppParams, cmd: IppStatusCmd) -> Result<(), IppError> { let client = new_client(&cmd.uri, &params); let operation = IppOperationBuilder::get_printer_attributes() .attributes(&cmd.attributes) .build(); let mut runtime = tokio::runtime::Runtime::new().unwrap(); let attrs = runtime.block_on(client.send(operation))?; if let Some(group) = attrs.groups_of(DelimiterTag::PrinterAttributes).get(0) { let mut values: Vec<_> = group.attributes().values().collect(); values.sort_by(|a, b| a.name().cmp(b.name())); for v in values { println!("{}: {}", v.name(), v.value()); } } Ok(()) } #[derive(StructOpt)] #[structopt(name = "IPP print utility", about = "", author = "", rename_all = "kebab-case")] struct IppParams { #[structopt( long = "ca-cert", short = "c", global = true, help = "Additional CA root certificates in PEM or DER format" )] ca_certs: Vec<String>, #[structopt( long = "no-verify-hostname", global = true, help = "Disable TLS host name verification (insecure!)" )] no_verify_hostname: bool, #[structopt( long = "no-verify-certificate", global = true, help = "Disable TLS certificate verification (insecure!)" )] no_verify_certificate: bool, #[structopt( default_value = "0", long = "timeout", short = "t", global = true, help = "IPP request timeout in seconds, 0 = no timeout" )] timeout: u64, #[structopt(subcommand)] command: IppCommand, } #[derive(StructOpt)] enum IppCommand { #[structopt(name = "print", about = "Print file to an IPP printer", author = "")] Print(IppPrintCmd), #[structopt(name = "status", about = "Get status of an IPP printer", author = "")] Status(IppStatusCmd), } #[derive(StructOpt, Clone)] #[structopt(name = "IPP print utility", about = "", author = "", rename_all = "kebab-case")] struct IppPrintCmd { #[structopt(help = "Printer URI")] uri: String, #[structopt( long = "no-check-state", short = "n", help = "Do not check printer state before printing" )] no_check_state: bool, #[structopt( long = "file", short = "f", help = "Input file name to print [default: standard input]" )] file: Option<PathBuf>, #[structopt(long = "job-name", short = "j", help = "Job name to send as job-name attribute")] job_name: Option<String>, #[structopt( long = "user-name", short = "u", help = "User name to send as requesting-user-name attribute" )] user_name: Option<String>, #[structopt(long = "option", short = "o", help = "Extra IPP job attributes in key=value format")] options: Vec<String>, } #[derive(StructOpt, Clone)] #[structopt(name = "IPP print utility", about = "", author = "", rename_all = "kebab-case")] struct IppStatusCmd { #[structopt(help = "Printer URI")] uri: String, #[structopt(long = "attribute", short = "a", help = "Attributes to query, default is to get all")] attributes: Vec<String>, } pub fn ipp_main<I, T>(args: I) -> Result<(), IppError> where I: IntoIterator<Item = T>, T: Into<OsString> + Clone, { let params = IppParams::from_iter_safe(args).map_err(|e| IppError::ParamError(e.to_string()))?; match params.command { IppCommand::Status(ref cmd) => do_status(&params, cmd.clone())?, IppCommand::Print(ref cmd) => do_print(&params, cmd.clone())?, } Ok(()) }
t) .ca_certs(&params.ca_certs) .verify_hostname(!params.no_verify_hostname) .verify_certificate(!params.no_verify_certificate) .build() }
function_block-function_prefixed
[ { "content": "fn to_device_uri(uri: &str) -> Cow<str> {\n\n match Url::parse(&uri) {\n\n Ok(ref mut url) if !url.username().is_empty() => {\n\n let _ = url.set_username(\"\");\n\n let _ = url.set_password(None);\n\n Cow::Owned(url.to_string())\n\n }\n\n _ => Cow::Borrowed(uri),\n\n }\n\n}\n\n\n", "file_path": "ipp-client/src/client.rs", "rank": 1, "score": 93409.13669394591 }, { "content": "fn is_header_attr(attr: &str) -> bool {\n\n HEADER_ATTRS.iter().any(|&at| at == attr)\n\n}\n\n\n\n/// `IppAttribute` represents an IPP attribute\n\n#[derive(Clone, Debug)]\n\npub struct IppAttribute {\n\n /// Attribute name\n\n name: String,\n\n /// Attribute value\n\n value: IppValue,\n\n}\n\n\n\nimpl IppAttribute {\n\n /// Create new instance of the attribute\n\n ///\n\n /// * `name` - Attribute name<br/>\n\n /// * `value` - Attribute value<br/>\n\n pub fn new(name: &str, value: IppValue) -> IppAttribute {\n\n IppAttribute {\n", "file_path": "ipp-proto/src/attribute.rs", "rank": 2, "score": 82414.4014916997 }, { "content": "fn parse_uri(uri: String) -> impl Future<Item = Url, Error = IppError> {\n\n futures::lazy(move || match Url::parse(&uri) {\n\n Ok(mut url) => {\n\n match url.scheme() {\n\n \"ipp\" => {\n\n url.set_scheme(\"http\").unwrap();\n\n if url.port().is_none() {\n\n url.set_port(Some(631)).unwrap();\n\n }\n\n }\n\n \"ipps\" => {\n\n url.set_scheme(\"https\").unwrap();\n\n if url.port().is_none() {\n\n url.set_port(Some(443)).unwrap();\n\n }\n\n }\n\n _ => {}\n\n }\n\n Ok(url)\n\n }\n\n Err(e) => Err(IppError::ParamError(e.to_string())),\n\n })\n\n}\n\n\n", "file_path": "ipp-client/src/client.rs", "rank": 6, "score": 65258.55279291157 }, { "content": "fn parse_certs(certs: Vec<PathBuf>) -> impl Future<Item = Vec<Certificate>, Error = IppError> {\n\n futures::lazy(move || {\n\n let mut result = Vec::new();\n\n\n\n for cert_file in certs {\n\n let buf = match fs::read(&cert_file) {\n\n Ok(buf) => buf,\n\n Err(e) => return Err(IppError::from(e)),\n\n };\n\n let ca_cert = match Certificate::from_der(&buf).or_else(|_| Certificate::from_pem(&buf)) {\n\n Ok(ca_cert) => ca_cert,\n\n Err(e) => return Err(IppError::from(e)),\n\n };\n\n result.push(ca_cert);\n\n }\n\n Ok(result)\n\n })\n\n}\n\n\n\n/// IPP client.\n", "file_path": "ipp-client/src/client.rs", "rank": 7, "score": 59877.25288411954 }, { "content": "fn main() {\n\n let args = env::args().collect::<Vec<String>>();\n\n if args.len() < 2 {\n\n eprintln!(\"Usage: {} spooler_dir\", args[0]);\n\n std::process::exit(1);\n\n }\n\n\n\n env_logger::init();\n\n\n\n let _ = std::fs::create_dir_all(&args[1]);\n\n\n\n let test_server = TestServer {\n\n name: \"IPP server example\".to_string(),\n\n start_time: time::SystemTime::now(),\n\n printing: atomic::AtomicBool::new(false),\n\n spooler_dir: env::args().nth(1).unwrap().into(),\n\n };\n\n\n\n let fut = IppServerBuilder::new(([0, 0, 0, 0], 7631))\n\n .handler(Arc::new(test_server))\n\n .build()\n\n .map_err(|e| {\n\n eprintln!(\"ERROR: {:?}\", e);\n\n });\n\n\n\n hyper::rt::run(fut.map(|_| ()));\n\n}\n", "file_path": "ipp-server/examples/ipp-server.rs", "rank": 8, "score": 47347.44227807528 }, { "content": "fn supports_multi_doc(v: &IppValue) -> bool {\n\n v.as_enum()\n\n .map(|v| *v == Operation::CreateJob as i32 || *v == Operation::SendDocument as i32)\n\n .unwrap_or(false)\n\n}\n\n\n", "file_path": "ipp/examples/multi-doc.rs", "rank": 10, "score": 39163.49235465376 }, { "content": "pub fn main() -> Result<(), Box<dyn Error>> {\n\n env_logger::init();\n\n\n\n let args: Vec<_> = env::args().collect();\n\n\n\n if args.len() < 2 {\n\n println!(\"Usage: {} uri\", args[0]);\n\n exit(1);\n\n }\n\n\n\n let mut runtime = tokio::runtime::Runtime::new()?;\n\n let client = IppClientBuilder::new(&args[1]).build();\n\n let operation = CupsGetPrinters::new();\n\n\n\n let attrs = runtime.block_on(client.send(operation))?;\n\n\n\n for group in attrs.groups_of(DelimiterTag::PrinterAttributes) {\n\n let name = group.attributes()[\"printer-name\"].value();\n\n let uri = group.attributes()[\"device-uri\"].value();\n\n let state = group.attributes()[\"printer-state\"]\n", "file_path": "ipp/examples/get-printers.rs", "rank": 11, "score": 37170.15442854908 }, { "content": "pub fn main() -> Result<(), Box<dyn Error>> {\n\n env_logger::init();\n\n\n\n let args: Vec<_> = env::args().collect();\n\n\n\n if args.len() < 2 {\n\n println!(\"Usage: {} uri\", args[0]);\n\n exit(1);\n\n }\n\n\n\n let mut runtime = tokio::runtime::Runtime::new()?;\n\n let client = IppClientBuilder::new(&args[1]).build();\n\n let operation = CupsDeletePrinter::new();\n\n\n\n runtime.block_on(client.send(operation))?;\n\n\n\n Ok(())\n\n}\n", "file_path": "ipp/examples/delete-printer.rs", "rank": 12, "score": 37170.15442854908 }, { "content": "pub fn main() -> Result<(), Box<dyn Error>> {\n\n env_logger::init();\n\n\n\n let args: Vec<_> = env::args().collect();\n\n\n\n if args.len() < 2 {\n\n println!(\"Usage: {} uri [attrs]\", args[0]);\n\n exit(1);\n\n }\n\n\n\n let mut runtime = tokio::runtime::Runtime::new()?;\n\n let client = IppClientBuilder::new(&args[1]).build();\n\n let operation = IppOperationBuilder::get_printer_attributes()\n\n .attributes(&args[2..])\n\n .build();\n\n\n\n let attrs = runtime.block_on(client.send(operation))?;\n\n\n\n for v in attrs.groups_of(DelimiterTag::PrinterAttributes)[0]\n\n .attributes()\n\n .values()\n\n {\n\n println!(\"{}: {}\", v.name(), v.value());\n\n }\n\n\n\n Ok(())\n\n}\n", "file_path": "ipp/examples/get-attrs.rs", "rank": 13, "score": 37170.15442854908 }, { "content": "pub fn main() -> Result<(), Box<dyn Error>> {\n\n env_logger::init();\n\n\n\n let args: Vec<_> = env::args().collect();\n\n\n\n if args.len() < 3 {\n\n println!(\"Usage: {} uri filename [filename...]\", args[0]);\n\n exit(1);\n\n }\n\n\n\n let uri = args[1].clone();\n\n\n\n let mut runtime = tokio::runtime::Runtime::new()?;\n\n\n\n let client = IppClientBuilder::new(&uri).build();\n\n\n\n // check if printer supports create/send operations\n\n let get_op = IppOperationBuilder::get_printer_attributes()\n\n .attribute(OPERATIONS_SUPPORTED)\n\n .build();\n", "file_path": "ipp/examples/multi-doc.rs", "rank": 14, "score": 37170.15442854908 }, { "content": "pub fn main() -> Result<(), Box<dyn Error>> {\n\n env_logger::init();\n\n\n\n let args: Vec<_> = env::args().collect();\n\n\n\n if args.len() < 3 {\n\n println!(\"Usage: {} uri filename [key=value ...]\", args[0]);\n\n exit(1);\n\n }\n\n\n\n let mut runtime = tokio::runtime::Runtime::new()?;\n\n\n\n let fut = tokio::fs::File::open(args[2].to_owned())\n\n .map_err(IppError::from)\n\n .and_then(move |f| {\n\n let mut builder = IppOperationBuilder::print_job(f)\n\n .user_name(&env::var(\"USER\").unwrap_or_else(|_| String::new()))\n\n .job_title(&args[1]);\n\n\n\n for arg in &args[3..] {\n", "file_path": "ipp/examples/print-job.rs", "rank": 15, "score": 37170.15442854908 }, { "content": "// create a single value from one-element list, list otherwise\n\nfn list_or_value(mut list: Vec<IppValue>) -> IppValue {\n\n if list.len() == 1 {\n\n list.remove(0)\n\n } else {\n\n IppValue::ListOf(list)\n\n }\n\n}\n\n\n\n/// IPP parsing result\n\npub struct IppParseResult {\n\n pub header: IppHeader,\n\n pub attributes: IppAttributes,\n\n pub payload: Option<PayloadKind>,\n\n}\n\n\n\nimpl IppParseResult {\n\n fn new(header: IppHeader, attributes: IppAttributes) -> IppParseResult {\n\n IppParseResult {\n\n header,\n\n attributes,\n", "file_path": "ipp-proto/src/parser.rs", "rank": 16, "score": 35092.1516004294 }, { "content": "use std::{io, net::SocketAddr, sync::Arc};\n\n\n\nuse futures::future::IntoFuture;\n\nuse futures::{Future, Poll, Stream};\n\nuse hyper::{service::service_fn, Body, Chunk, Request, Response, Server};\n\nuse log::debug;\n\n\n\nuse ipp_proto::{\n\n attribute::STATUS_MESSAGE, ipp::DelimiterTag, AsyncIppParser, IppAttribute, IppRequestResponse, IppValue,\n\n};\n\n\n\nuse crate::handler::IppRequestHandler;\n\n\n", "file_path": "ipp-server/src/server.rs", "rank": 18, "score": 13.222481288589556 }, { "content": "#![allow(unused)]\n\n\n\nuse std::{\n\n env,\n\n fs::OpenOptions,\n\n io::{self, Cursor},\n\n mem,\n\n path::PathBuf,\n\n sync::{atomic, Arc},\n\n time,\n\n};\n\n\n\nuse futures::{future::Future, stream::Stream};\n\nuse hyper::{service::service_fn, Body, Chunk, Request, Response, Server};\n\nuse log::debug;\n\nuse tempfile::NamedTempFile;\n\n\n\nuse ipp_proto::{\n\n attribute::*,\n\n ipp::*,\n\n request::{IppRequestResponse, PayloadKind},\n\n AsyncIppParser, IppHeader, IppParser, IppValue,\n\n};\n\nuse ipp_server::{handler::*, server::IppServerBuilder};\n\nuse lazy_static::lazy_static;\n\n\n", "file_path": "ipp-server/examples/ipp-server.rs", "rank": 19, "score": 11.883680354237224 }, { "content": "//!\n\n//! IPP client\n\n//!\n\nuse std::{borrow::Cow, fs, io, path::PathBuf, time::Duration};\n\n\n\nuse futures::{future::IntoFuture, Future, Stream};\n\nuse log::debug;\n\nuse num_traits::FromPrimitive;\n\nuse reqwest::{\n\n r#async::{Chunk, Client},\n\n Certificate,\n\n};\n\nuse url::Url;\n\n\n\nuse ipp_proto::{\n\n attribute::{PRINTER_STATE, PRINTER_STATE_REASONS},\n\n ipp::{self, DelimiterTag, PrinterState},\n\n operation::IppOperation,\n\n request::IppRequestResponse,\n\n AsyncIppParser, IppAttributes, IppOperationBuilder,\n", "file_path": "ipp-client/src/client.rs", "rank": 21, "score": 10.296460771821263 }, { "content": "//!\n\n//! IPP stream parser\n\n//!\n\nuse std::{\n\n fmt,\n\n io::{self, Read},\n\n};\n\n\n\nuse byteorder::{BigEndian, ReadBytesExt};\n\nuse futures::{try_ready, Async, Future, Poll, Stream};\n\nuse log::{debug, error};\n\nuse num_traits::FromPrimitive;\n\n\n\nuse crate::{ipp::*, IppAttribute, IppAttributeGroup, IppAttributes, IppHeader, IppReadExt, IppValue, PayloadKind};\n\n\n\n/// Parse error enum\n\n#[derive(Debug)]\n\npub enum ParseError {\n\n InvalidTag(u8),\n\n InvalidVersion,\n", "file_path": "ipp-proto/src/parser.rs", "rank": 22, "score": 9.56900697769606 }, { "content": "//!\n\n//! Attribute-related structs\n\n//!\n\nuse std::{\n\n collections::HashMap,\n\n io::{self, Write},\n\n};\n\n\n\nuse byteorder::{BigEndian, WriteBytesExt};\n\n\n\nuse crate::{ipp::*, IppValue, IppWriter};\n\n\n\npub const ATTRIBUTES_CHARSET: &str = \"attributes-charset\";\n\npub const ATTRIBUTES_NATURAL_LANGUAGE: &str = \"attributes-natural-language\";\n\npub const CHARSET_CONFIGURED: &str = \"charset-configured\";\n\npub const CHARSET_SUPPORTED: &str = \"charset-supported\";\n\npub const COMPRESSION_SUPPORTED: &str = \"compression-supported\";\n\npub const DOCUMENT_FORMAT_DEFAULT: &str = \"document-format-default\";\n\npub const DOCUMENT_FORMAT_SUPPORTED: &str = \"document-format-supported\";\n\npub const GENERATED_NATURAL_LANGUAGE_SUPPORTED: &str = \"generated-natural-language-supported\";\n", "file_path": "ipp-proto/src/attribute.rs", "rank": 23, "score": 9.566316314885663 }, { "content": "//!\n\n//! IPP request\n\n//!\n\nuse std::io::{self, Cursor, Write};\n\n\n\nuse bytes::Bytes;\n\nuse enum_as_inner::EnumAsInner;\n\nuse futures::Stream;\n\nuse log::debug;\n\nuse tempfile::NamedTempFile;\n\n\n\nuse crate::{\n\n attribute::*,\n\n ipp::{DelimiterTag, IppVersion, Operation},\n\n parser::IppParseResult,\n\n value::*,\n\n IppHeader, IppJobSource, IppWriter, StatusCode,\n\n};\n\n\n\n/// Payload type inside the IppRequestResponse\n", "file_path": "ipp-proto/src/request.rs", "rank": 24, "score": 9.128358517881761 }, { "content": "use std::io::{self, Read, Write};\n\n\n\nuse byteorder::{BigEndian, ReadBytesExt, WriteBytesExt};\n\nuse bytes::{Bytes, BytesMut};\n\nuse futures::{try_ready, Async, Poll, Stream};\n\nuse num_traits::FromPrimitive;\n\nuse tokio::io::AsyncRead;\n\n\n\npub use crate::{\n\n attribute::{IppAttribute, IppAttributeGroup, IppAttributes},\n\n builder::{\n\n CreateJobBuilder, GetPrinterAttributesBuilder, IppOperationBuilder, PrintJobBuilder, SendDocumentBuilder,\n\n },\n\n ipp::{IppVersion, Operation, StatusCode},\n\n parser::{AsyncIppParser, IppParser, ParseError},\n\n request::{IppRequestResponse, PayloadKind},\n\n value::IppValue,\n\n};\n\n\n\npub mod attribute;\n", "file_path": "ipp-proto/src/lib.rs", "rank": 25, "score": 8.736955411658332 }, { "content": "use std::{env, error::Error, process::exit};\n\n\n\nuse futures::Future;\n\n\n\nuse ipp::{\n\n client::{IppClientBuilder, IppError},\n\n proto::{ipp::DelimiterTag, IppAttribute, IppOperationBuilder, IppValue},\n\n};\n\n\n", "file_path": "ipp/examples/print-job.rs", "rank": 26, "score": 7.704446520126528 }, { "content": "}\n\n\n\n/// IPP server\n\npub struct IppServer {\n\n inner: Box<dyn Future<Item = (), Error = ServerError> + Send>,\n\n}\n\n\n\nimpl IppServer {\n\n fn new(address: SocketAddr, handler: Arc<dyn IppRequestHandler + Send + Sync>) -> Result<IppServer, ServerError> {\n\n let inner = Server::try_bind(&address)?\n\n .serve(move || {\n\n let handler = handler.clone();\n\n service_fn(move |req: Request<Body>| {\n\n let stream: Box<dyn Stream<Item = Chunk, Error = io::Error> + Send> = Box::new(\n\n req.into_body()\n\n .map_err(|e| io::Error::new(io::ErrorKind::Other, e.to_string())),\n\n );\n\n\n\n let handler = handler.clone();\n\n\n", "file_path": "ipp-server/src/server.rs", "rank": 27, "score": 7.637790746944429 }, { "content": "use std::{env, error::Error, process::exit};\n\n\n\nuse futures::Future;\n\n\n\nuse ipp::{\n\n client::{IppClientBuilder, IppError},\n\n proto::{\n\n attribute::{JOB_ID, OPERATIONS_SUPPORTED},\n\n ipp::{DelimiterTag, Operation},\n\n IppOperationBuilder, IppValue,\n\n },\n\n};\n\n\n", "file_path": "ipp/examples/multi-doc.rs", "rank": 28, "score": 7.5645614479989725 }, { "content": "use std::{\n\n fmt, io,\n\n path::{Path, PathBuf},\n\n};\n\n\n\nuse ipp_proto::{ipp::StatusCode, ParseError};\n\n\n\npub use crate::client::IppClient;\n\n\n\npub mod client;\n\n\n\n/// IPP error\n\n#[derive(Debug)]\n\npub enum IppError {\n\n /// HTTP error\n\n HttpError(reqwest::Error),\n\n /// Network or file I/O error\n\n IOError(::std::io::Error),\n\n /// IPP status error\n\n StatusError(StatusCode),\n", "file_path": "ipp-client/src/lib.rs", "rank": 29, "score": 7.28463555780118 }, { "content": "//!\n\n//! IPP value\n\n//!\n\nuse std::{\n\n fmt,\n\n io::{self, Read, Write},\n\n};\n\n\n\nuse byteorder::{BigEndian, ReadBytesExt, WriteBytesExt};\n\nuse bytes::Bytes;\n\nuse enum_as_inner::EnumAsInner;\n\nuse num_traits::FromPrimitive;\n\n\n\nuse crate::{ipp::ValueTag, IppReadExt, IppWriter};\n\n\n\n/// IPP value enumeration\n\n#[derive(Clone, Debug, PartialEq, EnumAsInner)]\n\npub enum IppValue {\n\n Integer(i32),\n\n Enum(i32),\n", "file_path": "ipp-proto/src/value.rs", "rank": 30, "score": 6.526743951177356 }, { "content": "\n\nimpl IppWriter for IppHeader {\n\n /// Write header to a given writer\n\n fn write(&self, writer: &mut dyn Write) -> io::Result<usize> {\n\n writer.write_u16::<BigEndian>(self.version as u16)?;\n\n writer.write_u16::<BigEndian>(self.operation_status)?;\n\n writer.write_u32::<BigEndian>(self.request_id)?;\n\n\n\n Ok(8)\n\n }\n\n}\n\n\n\n#[cfg(test)]\n\nmod tests {\n\n use std::io::Cursor;\n\n\n\n use super::*;\n\n\n\n #[test]\n\n fn test_read_header_ok() {\n", "file_path": "ipp-proto/src/lib.rs", "rank": 31, "score": 6.4277699762348615 }, { "content": " IppError::ParamError(ref e) => write!(f, \"IPP param error: {}\", e),\n\n IppError::PrinterStateError(ref e) => write!(f, \"IPP printer state error: {:?}\", e),\n\n IppError::PrinterStopped => write!(f, \"IPP printer stopped\"),\n\n IppError::ParseError(ref e) => write!(f, \"{}\", e),\n\n IppError::MissingAttribute => write!(f, \"Missing attribute in response\"),\n\n IppError::InvalidAttributeType => write!(f, \"Invalid attribute type\"),\n\n }\n\n }\n\n}\n\n\n\nimpl From<io::Error> for IppError {\n\n fn from(error: io::Error) -> Self {\n\n IppError::IOError(error)\n\n }\n\n}\n\n\n\nimpl From<StatusCode> for IppError {\n\n fn from(code: StatusCode) -> Self {\n\n IppError::StatusError(code)\n\n }\n", "file_path": "ipp-client/src/lib.rs", "rank": 32, "score": 6.351579554048842 }, { "content": "};\n\n\n\nuse crate::IppError;\n\n\n\nconst ERROR_STATES: &[&str] = &[\n\n \"media-jam\",\n\n \"toner-empty\",\n\n \"spool-area-full\",\n\n \"cover-open\",\n\n \"door-open\",\n\n \"input-tray-missing\",\n\n \"output-tray-missing\",\n\n \"marker-supply-empty\",\n\n \"paused\",\n\n \"shutdown\",\n\n];\n\n\n", "file_path": "ipp-client/src/client.rs", "rank": 33, "score": 5.848164911480732 }, { "content": " );\n\n }\n\n\n\n #[test]\n\n fn test_async_parser_with_payload() {\n\n // split IPP into arbitrary chunks\n\n let data = vec![\n\n vec![1, 1, 0],\n\n vec![0, 0, 0, 0, 0, 4],\n\n vec![\n\n 0x21, 0x00, 0x04, b't', b'e', b's', b't', 0x00, 0x04, 0x12, 0x34, 0x56, 0x78, 3,\n\n ],\n\n vec![b'f'],\n\n vec![b'o', b'o'],\n\n ];\n\n\n\n let source: Box<dyn Stream<Item = Vec<u8>, Error = io::Error> + Send> =\n\n Box::new(futures::stream::iter_ok::<_, io::Error>(data));\n\n\n\n let parser = AsyncIppParser::from(source);\n", "file_path": "ipp-proto/src/parser.rs", "rank": 34, "score": 5.763446161867616 }, { "content": " }\n\n }\n\n}\n\n\n\nimpl<I, E> From<Box<dyn Stream<Item = I, Error = E> + Send>> for AsyncIppParser<I, E> {\n\n /// Construct asynchronous parser from the stream\n\n fn from(s: Box<dyn Stream<Item = I, Error = E> + Send>) -> AsyncIppParser<I, E> {\n\n AsyncIppParser {\n\n state: AsyncParseState::Headers(Vec::new()),\n\n stream: s,\n\n }\n\n }\n\n}\n\n\n\n#[cfg(test)]\n\nmod tests {\n\n use std::io::Cursor;\n\n\n\n use super::*;\n\n\n", "file_path": "ipp-proto/src/parser.rs", "rank": 35, "score": 5.7530650815691144 }, { "content": " name: name.to_string(),\n\n value,\n\n }\n\n }\n\n\n\n /// Return attribute name\n\n pub fn name(&self) -> &str {\n\n &self.name\n\n }\n\n\n\n /// Return attribute value\n\n pub fn value(&self) -> &IppValue {\n\n &self.value\n\n }\n\n}\n\n\n\nimpl IppWriter for IppAttribute {\n\n /// Serialize attribute into binary stream\n\n fn write(&self, writer: &mut dyn Write) -> io::Result<usize> {\n\n let mut retval = 0;\n", "file_path": "ipp-proto/src/attribute.rs", "rank": 36, "score": 5.390678807746505 }, { "content": " Ok(retval)\n\n }\n\n\n\n /// Convert request/response into Stream\n\n pub fn into_stream(self) -> Box<dyn Stream<Item = Bytes, Error = io::Error> + Send + 'static> {\n\n let mut cursor = Cursor::new(Vec::with_capacity(1024));\n\n let _ = self\n\n .header\n\n .write(&mut cursor)\n\n .and_then(|_| self.attributes.write(&mut cursor));\n\n\n\n let headers = futures::stream::once(Ok(cursor.into_inner().into()));\n\n\n\n match self.payload {\n\n Some(PayloadKind::JobSource(payload)) => Box::new(headers.chain(payload)),\n\n _ => Box::new(headers),\n\n }\n\n }\n\n}\n", "file_path": "ipp-proto/src/request.rs", "rank": 37, "score": 4.826626904453201 }, { "content": "pub const JOB_URI: &str = \"job-uri\";\n\npub const LAST_DOCUMENT: &str = \"last-document\";\n\npub const REQUESTING_USER_NAME: &str = \"requesting-user-name\";\n\npub const STATUS_MESSAGE: &str = \"status-message\";\n\npub const REQUESTED_ATTRIBUTES: &str = \"requested-attributes\";\n\npub const SIDES_SUPPORTED: &str = \"sides-supported\";\n\npub const OUTPUT_MODE_SUPPORTED: &str = \"output-mode-supported\";\n\npub const COLOR_SUPPORTED: &str = \"color-supported\";\n\npub const PRINTER_INFO: &str = \"printer-info\";\n\npub const PRINTER_LOCATION: &str = \"printer-location\";\n\npub const PRINTER_MORE_INFO: &str = \"printer-more-info\";\n\npub const PRINTER_RESOLUTION_DEFAULT: &str = \"printer-resolution-default\";\n\npub const PRINTER_RESOLUTION_SUPPORTED: &str = \"printer-resolution-supported\";\n\npub const COPIES_SUPPORTED: &str = \"copies-supported\";\n\npub const COPIES_DEFAULT: &str = \"copies-default\";\n\npub const SIDES_DEFAULT: &str = \"sides-default\";\n\npub const PRINT_QUALITY_DEFAULT: &str = \"print-quality-default\";\n\npub const PRINT_QUALITY_SUPPORTED: &str = \"print-quality-supported\";\n\npub const FINISHINGS_DEFAULT: &str = \"finishings-default\";\n\npub const FINISHINGS_SUPPORTED: &str = \"finishings-supported\";\n", "file_path": "ipp-proto/src/attribute.rs", "rank": 38, "score": 4.531275032418587 }, { "content": "pub const IPP_VERSIONS_SUPPORTED: &str = \"ipp-versions-supported\";\n\npub const NATURAL_LANGUAGE_CONFIGURED: &str = \"natural-language-configured\";\n\npub const OPERATIONS_SUPPORTED: &str = \"operations-supported\";\n\npub const PDL_OVERRIDE_SUPPORTED: &str = \"pdl-override-supported\";\n\npub const PRINTER_IS_ACCEPTING_JOBS: &str = \"printer-is-accepting-jobs\";\n\npub const PRINTER_MAKE_AND_MODEL: &str = \"printer-make-and-model\";\n\npub const PRINTER_NAME: &str = \"printer-name\";\n\npub const PRINTER_STATE: &str = \"printer-state\";\n\npub const PRINTER_STATE_MESSAGE: &str = \"printer-state-message\";\n\npub const PRINTER_STATE_REASONS: &str = \"printer-state-reasons\";\n\npub const PRINTER_UP_TIME: &str = \"printer-up-time\";\n\npub const PRINTER_URI: &str = \"printer-uri\";\n\npub const PRINTER_URI_SUPPORTED: &str = \"printer-uri-supported\";\n\npub const QUEUED_JOB_COUNT: &str = \"queued-job-count\";\n\npub const URI_AUTHENTICATION_SUPPORTED: &str = \"uri-authentication-supported\";\n\npub const URI_SECURITY_SUPPORTED: &str = \"uri-security-supported\";\n\npub const JOB_ID: &str = \"job-id\";\n\npub const JOB_NAME: &str = \"job-name\";\n\npub const JOB_STATE: &str = \"job-state\";\n\npub const JOB_STATE_REASONS: &str = \"job-state-reasons\";\n", "file_path": "ipp-proto/src/attribute.rs", "rank": 39, "score": 4.498686982811392 }, { "content": " /// Printer state error\n\n PrinterStateError(Vec<String>),\n\n /// Printer stopped\n\n PrinterStopped,\n\n /// Parameter error\n\n ParamError(String),\n\n /// Parsing error\n\n ParseError(ParseError),\n\n /// Missing attribute in response\n\n MissingAttribute,\n\n /// Invalid attribute type\n\n InvalidAttributeType,\n\n}\n\n\n\nimpl fmt::Display for IppError {\n\n fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {\n\n match *self {\n\n IppError::HttpError(ref e) => write!(f, \"{}\", e),\n\n IppError::IOError(ref e) => write!(f, \"{}\", e),\n\n IppError::StatusError(ref e) => write!(f, \"IPP status error: {}\", e),\n", "file_path": "ipp-client/src/lib.rs", "rank": 40, "score": 4.467346540082803 }, { "content": "pub const OUTPUT_BIN_DEFAULT: &str = \"output-bin-default\";\n\npub const OUTPUT_BIN_SUPPORTED: &str = \"output-bin-supported\";\n\npub const ORIENTATION_REQUESTED_DEFAULT: &str = \"orientation-requested-default\";\n\npub const ORIENTATION_REQUESTED_SUPPORTED: &str = \"orientation-requested-supported\";\n\npub const MEDIA_DEFAULT: &str = \"media-default\";\n\npub const MEDIA_SUPPORTED: &str = \"media-supported\";\n\npub const PAGES_PER_MINUTE: &str = \"pages-per-minute\";\n\npub const COLOR_MODE_SUPPORTED: &str = \"color-mode-supported\";\n\npub const PRINT_COLOR_MODE_SUPPORTED: &str = \"print-color-mode-supported\";\n\n\n\nconst HEADER_ATTRS: [&str; 3] = [ATTRIBUTES_CHARSET, ATTRIBUTES_NATURAL_LANGUAGE, PRINTER_URI];\n\n\n", "file_path": "ipp-proto/src/attribute.rs", "rank": 41, "score": 4.391056664514233 }, { "content": "//! }\n\n//! Ok(())\n\n//! }\n\n//!```\n\n\n\npub use ipp_proto as proto;\n\n\n\n#[cfg(feature = \"client\")]\n\npub use ipp_client as client;\n\n\n\n#[cfg(feature = \"server\")]\n\npub use ipp_server as server;\n\n\n\n#[cfg(feature = \"util\")]\n\npub use ipp_util as util;\n", "file_path": "ipp/src/lib.rs", "rank": 42, "score": 4.188826124627034 }, { "content": "# ipp.rs\n\n\n\nIPP protocol implementation for Rust\n\n\n\n[Documentation](https://docs.rs/ipp)\n\n\n\nThis crate implements IPP protocol as defined in RFC 2911. Not all features are implemented yet.<br/>\n\nTransport is based on asynchronous HTTP client from the `reqwest` crate.\n\n\n\nUsage example:\n\n\n\n```rust,no_run\n\nuse ipp::{\n\n client::IppClientBuilder,\n\n proto::{ipp::DelimiterTag, IppOperationBuilder},\n\n};\n\nuse tokio::runtime::Runtime;\n\n\n\nfn main() -> Result<(), Box<dyn std::error::Error>> {\n\n let mut runtime = Runtime::new()?;\n\n\n\n let operation = IppOperationBuilder::get_printer_attributes().build();\n\n let client = IppClientBuilder::new(\"http://localhost:631/printers/test-printer\").build();\n\n let attrs = runtime.block_on(client.send(operation))?;\n\n\n\n for (_, v) in attrs.groups_of(DelimiterTag::PrinterAttributes)[0].attributes() {\n\n println!(\"{}: {}\", v.name(), v.value());\n\n }\n\n Ok(())\n\n}\n\n```\n\n\n\n## License\n\n\n\nLicensed under MIT or Apache license ([LICENSE-MIT](https://opensource.org/licenses/MIT) or [LICENSE-APACHE](https://opensource.org/licenses/Apache-2.0))\n", "file_path": "ipp/README.md", "rank": 43, "score": 4.126893316663972 }, { "content": "# ipp.rs\n\n\n\nIPP protocol implementation for Rust\n\n\n\n[Documentation](https://docs.rs/ipp)\n\n\n\nThis crate implements IPP protocol as defined in RFC 2911. Not all features are implemented yet.<br/>\n\nTransport is based on asynchronous HTTP client from the `reqwest` crate.\n\n\n\nUsage example:\n\n\n\n```rust,no_run\n\nuse ipp::{\n\n client::IppClientBuilder,\n\n proto::{ipp::DelimiterTag, IppOperationBuilder},\n\n};\n\nuse tokio::runtime::Runtime;\n\n\n\nfn main() -> Result<(), Box<dyn std::error::Error>> {\n\n let mut runtime = Runtime::new()?;\n\n\n\n let operation = IppOperationBuilder::get_printer_attributes().build();\n\n let client = IppClientBuilder::new(\"http://localhost:631/printers/test-printer\").build();\n\n let attrs = runtime.block_on(client.send(operation))?;\n\n\n\n for (_, v) in attrs.groups_of(DelimiterTag::PrinterAttributes)[0].attributes() {\n\n println!(\"{}: {}\", v.name(), v.value());\n\n }\n\n Ok(())\n\n}\n\n```\n\n\n\n## License\n\n\n\nLicensed under MIT or Apache license ([LICENSE-MIT](https://opensource.org/licenses/MIT) or [LICENSE-APACHE](https://opensource.org/licenses/Apache-2.0))\n", "file_path": "README.md", "rank": 44, "score": 4.126893316663972 }, { "content": " InvalidCollection,\n\n Incomplete,\n\n IOError(io::Error),\n\n}\n\n\n\nimpl From<io::Error> for ParseError {\n\n fn from(error: io::Error) -> Self {\n\n match error.kind() {\n\n io::ErrorKind::UnexpectedEof => ParseError::Incomplete,\n\n _ => ParseError::IOError(error),\n\n }\n\n }\n\n}\n\n\n\nimpl fmt::Display for ParseError {\n\n fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {\n\n match self {\n\n ParseError::InvalidTag(tag) => write!(f, \"Invalid tag: {}\", tag),\n\n ParseError::InvalidVersion => write!(f, \"Invalid IPP protocol version\"),\n\n ParseError::InvalidCollection => write!(f, \"Invalid IPP collection\"),\n\n ParseError::Incomplete => write!(f, \"Incomplete IPP payload\"),\n\n ParseError::IOError(err) => write!(f, \"{}\", err.to_string()),\n\n }\n\n }\n\n}\n\n\n\nimpl std::error::Error for ParseError {}\n\n\n\n// create a single value from one-element list, list otherwise\n", "file_path": "ipp-proto/src/parser.rs", "rank": 45, "score": 3.9761852320951787 }, { "content": "use std::{env, error::Error, process::exit};\n\n\n\nuse num_traits::cast::FromPrimitive;\n\n\n\nuse ipp::{\n\n client::{IppClientBuilder, IppError},\n\n proto::{\n\n ipp::{DelimiterTag, PrinterState},\n\n operation::cups::CupsGetPrinters,\n\n },\n\n};\n\n\n", "file_path": "ipp/examples/get-printers.rs", "rank": 46, "score": 3.9662679380714754 }, { "content": "use std::{env, error::Error, process::exit};\n\n\n\nuse ipp::{client::IppClientBuilder, proto::operation::cups::CupsDeletePrinter};\n\n\n", "file_path": "ipp/examples/delete-printer.rs", "rank": 47, "score": 3.849967495852294 }, { "content": "use std::{env, error::Error, process::exit};\n\n\n\nuse ipp::{\n\n client::IppClientBuilder,\n\n proto::{ipp::DelimiterTag, IppOperationBuilder},\n\n};\n\n\n", "file_path": "ipp/examples/get-attrs.rs", "rank": 48, "score": 3.8282277180494586 }, { "content": "//!\n\n//! IPP print protocol implementation for Rust\n\n//!\n\n//! Usage examples:\n\n//!\n\n//!```rust,no_run\n\n//! // using raw API\n\n//! use ipp::client::IppClientBuilder;\n\n//! use ipp::proto::{ipp::Operation, request::IppRequestResponse, IppVersion};\n\n//! use tokio::runtime::Runtime;\n\n//!\n\n//! fn main() -> Result<(), Box<dyn std::error::Error>> {\n\n//! let mut runtime = Runtime::new()?;\n\n//! let uri = \"http://localhost:631/printers/test-printer\";\n\n//! let req = IppRequestResponse::new(\n\n//! IppVersion::Ipp11,\n\n//! Operation::GetPrinterAttributes,\n\n//! Some(uri)\n\n//! );\n\n//! let client = IppClientBuilder::new(&uri).build();\n", "file_path": "ipp/src/lib.rs", "rank": 49, "score": 3.728130856718732 }, { "content": " self.index += 1;\n\n Some(self.value)\n\n } else {\n\n None\n\n }\n\n }\n\n }\n\n }\n\n}\n\n\n\n#[cfg(test)]\n\nmod tests {\n\n use crate::{ipp::DelimiterTag, IppAttribute};\n\n\n\n use super::*;\n\n\n\n #[test]\n\n fn test_value_iterator_single() {\n\n let val = IppValue::Integer(1234);\n\n\n", "file_path": "ipp-proto/src/value.rs", "rank": 50, "score": 3.723110474162465 }, { "content": " }\n\n\n\n builder.send()\n\n })\n\n .and_then(|response| response.error_for_status())\n\n .map_err(IppError::HttpError)\n\n .and_then(|response| {\n\n let stream: Box<dyn Stream<Item = Chunk, Error = io::Error> + Send> = Box::new(\n\n response\n\n .into_body()\n\n .map_err(|e| io::Error::new(io::ErrorKind::Other, e.to_string())),\n\n );\n\n\n\n AsyncIppParser::from(stream)\n\n .map_err(IppError::from)\n\n .map(IppRequestResponse::from_parse_result)\n\n })\n\n })\n\n })\n\n }\n\n}\n", "file_path": "ipp-client/src/client.rs", "rank": 51, "score": 3.697814491195812 }, { "content": "//!\n\n//! CUPS-specific IPP operations\n\n//!\n\n\n\nuse crate::ipp::Operation;\n\nuse crate::operation::IppOperation;\n\nuse crate::request::IppRequestResponse;\n\n\n\n/// IPP operation CUPS-Get-Printers\n\n#[derive(Default)]\n\npub struct CupsGetPrinters;\n\n\n\nimpl CupsGetPrinters {\n\n /// Create CUPS-Get-Printers operation\n\n pub fn new() -> CupsGetPrinters {\n\n CupsGetPrinters::default()\n\n }\n\n}\n\n\n\nimpl IppOperation for CupsGetPrinters {\n", "file_path": "ipp-proto/src/operation/cups.rs", "rank": 52, "score": 3.6397614457612937 }, { "content": "//! let resp = runtime.block_on(client.send_request(req))?;\n\n//! if resp.header().operation_status <= 2 {\n\n//! println!(\"result: {:?}\", resp.attributes());\n\n//! }\n\n//! Ok(())\n\n//! }\n\n//!```\n\n//!```rust,no_run\n\n//! // using operations API\n\n//! use ipp::proto::{IppOperationBuilder, ipp::DelimiterTag};\n\n//! use ipp::client::IppClientBuilder;\n\n//! use tokio::runtime::Runtime;\n\n//!\n\n//! fn main() -> Result<(), Box<dyn std::error::Error>> {\n\n//! let mut runtime = Runtime::new()?;\n\n//! let operation = IppOperationBuilder::get_printer_attributes().build();\n\n//! let client = IppClientBuilder::new(\"http://localhost:631/printers/test-printer\").build();\n\n//! let attrs = runtime.block_on(client.send(operation))?;\n\n//! for (_, v) in attrs.groups_of(DelimiterTag::PrinterAttributes)[0].attributes() {\n\n//! println!(\"{}: {}\", v.name(), v.value());\n", "file_path": "ipp/src/lib.rs", "rank": 53, "score": 3.5710312631304877 }, { "content": "pub use util::ipp_main;\n\n\n\npub mod util;\n", "file_path": "ipp-util/src/lib.rs", "rank": 54, "score": 3.502120179287025 }, { "content": "//!\n\n//! Basic definitions for IPP server implementation\n\n//!\n\n#![allow(unused)]\n\n\n\nuse num_traits::FromPrimitive;\n\n\n\nuse ipp_proto::{\n\n ipp::{Operation, StatusCode},\n\n request::IppRequestResponse,\n\n IppVersion,\n\n};\n\n\n\npub type IppServerResult = Result<IppRequestResponse, StatusCode>;\n\n\n\n/// A trait which defines IPP operations\n", "file_path": "ipp-server/src/handler.rs", "rank": 55, "score": 3.4750217225651694 }, { "content": " }\n\n }\n\n}\n\n\n\npub(crate) trait IppWriter {\n\n fn write(&self, writer: &mut dyn Write) -> io::Result<usize>;\n\n}\n\n\n\n/// Trait which adds two methods to Read implementations: `read_string` and `read_bytes`\n\npub(crate) trait IppReadExt: Read {\n\n fn read_string(&mut self, len: usize) -> std::io::Result<String> {\n\n Ok(String::from_utf8_lossy(&self.read_bytes(len)?).to_string())\n\n }\n\n\n\n fn read_bytes(&mut self, len: usize) -> std::io::Result<Bytes> {\n\n let mut buf = BytesMut::with_capacity(len);\n\n buf.resize(len, 0);\n\n self.read_exact(&mut buf)?;\n\n\n\n Ok(buf.freeze())\n", "file_path": "ipp-proto/src/lib.rs", "rank": 56, "score": 3.4242657819914015 }, { "content": "//!\n\n//! Base IPP definitions and tags\n\n//!\n\nuse std::fmt;\n\n\n\nuse enum_primitive_derive::Primitive;\n\n\n\n/// IPP protocol version\n\n#[derive(Primitive, Debug, Copy, Clone, PartialEq)]\n\npub enum IppVersion {\n\n Ipp10 = 0x0100,\n\n Ipp11 = 0x0101,\n\n Ipp20 = 0x0200,\n\n Ipp21 = 0x0201,\n\n Ipp22 = 0x0202,\n\n}\n\n\n\n/// IPP operation constants\n\n#[derive(Primitive, Debug, Copy, Clone, PartialEq)]\n\npub enum Operation {\n", "file_path": "ipp-proto/src/ipp.rs", "rank": 57, "score": 3.338137919882847 }, { "content": " Err(ParseError::Incomplete) => {\n\n debug!(\"Incomplete request, awaiting for more data\");\n\n }\n\n Err(e) => {\n\n return Err(e);\n\n }\n\n }\n\n }\n\n AsyncParseState::Payload(ref mut result) => {\n\n let mut reader = io::Cursor::new(&item);\n\n match result.payload {\n\n Some(PayloadKind::ReceivedData(ref mut file)) => {\n\n debug!(\n\n \"Payload chunk received, appending to existing file: {}\",\n\n file.path().display()\n\n );\n\n io::copy(&mut reader, file)?;\n\n }\n\n None => {\n\n let mut temp = tempfile::NamedTempFile::new()?;\n", "file_path": "ipp-proto/src/parser.rs", "rank": 58, "score": 3.171074178998092 }, { "content": " where\n\n T: AsRef<str>,\n\n {\n\n CreateJob {\n\n job_name: job_name.map(|v| v.as_ref().to_string()),\n\n attributes: Vec::new(),\n\n }\n\n }\n\n\n\n /// Set extra job attribute for this operation, for example `colormodel=grayscale`\n\n pub fn add_attribute(&mut self, attribute: IppAttribute) {\n\n self.attributes.push(attribute);\n\n }\n\n}\n\n\n\nimpl IppOperation for CreateJob {\n\n fn into_ipp_request(self, uri: &str) -> IppRequestResponse {\n\n let mut retval = IppRequestResponse::new(self.version(), Operation::CreateJob, Some(uri));\n\n\n\n if let Some(ref job_name) = self.job_name {\n", "file_path": "ipp-proto/src/operation/mod.rs", "rank": 59, "score": 3.1549924830591975 }, { "content": " pub fn user_name(mut self, user_name: &str) -> Self {\n\n self.user_name = Some(user_name.to_owned());\n\n self\n\n }\n\n\n\n /// Specify job-name attribute\n\n pub fn job_title(mut self, job_title: &str) -> Self {\n\n self.job_title = Some(job_title.to_owned());\n\n self\n\n }\n\n\n\n /// Specify custom job attribute\n\n pub fn attribute(mut self, attribute: IppAttribute) -> Self {\n\n self.attributes.push(attribute);\n\n self\n\n }\n\n\n\n /// Build operation\n\n pub fn build(self) -> impl IppOperation {\n\n let op = PrintJob::new(self.source, self.user_name.as_ref(), self.job_title.as_ref());\n", "file_path": "ipp-proto/src/builder.rs", "rank": 60, "score": 3.140592255054328 }, { "content": " }\n\n\n\n /// Set attributes to request from the printer\n\n pub fn with_attributes<T>(attributes: &[T]) -> GetPrinterAttributes\n\n where\n\n T: AsRef<str>,\n\n {\n\n GetPrinterAttributes {\n\n attributes: attributes.iter().map(|a| a.as_ref().to_string()).collect(),\n\n }\n\n }\n\n}\n\n\n\nimpl IppOperation for GetPrinterAttributes {\n\n fn into_ipp_request(self, uri: &str) -> IppRequestResponse {\n\n let mut retval = IppRequestResponse::new(self.version(), Operation::GetPrinterAttributes, Some(uri));\n\n\n\n if !self.attributes.is_empty() {\n\n let vals: Vec<IppValue> = self.attributes.iter().map(|a| IppValue::Keyword(a.clone())).collect();\n\n retval.attributes_mut().add(\n", "file_path": "ipp-proto/src/operation/mod.rs", "rank": 61, "score": 3.0568778162280985 }, { "content": " fn into_ipp_request(self, _uri: &str) -> IppRequestResponse {\n\n IppRequestResponse::new(self.version(), Operation::CupsGetPrinters, None)\n\n }\n\n}\n\n\n\n/// IPP operation CUPS-Delete-Printer\n\n#[derive(Default)]\n\npub struct CupsDeletePrinter;\n\n\n\nimpl CupsDeletePrinter {\n\n /// Create CUPS-Get-Printers operation\n\n pub fn new() -> CupsDeletePrinter {\n\n CupsDeletePrinter::default()\n\n }\n\n}\n\n\n\nimpl IppOperation for CupsDeletePrinter {\n\n fn into_ipp_request(self, uri: &str) -> IppRequestResponse {\n\n IppRequestResponse::new(self.version(), Operation::CupsDeletePrinter, Some(uri))\n\n }\n\n}\n", "file_path": "ipp-proto/src/operation/cups.rs", "rank": 62, "score": 3.0433573857379215 }, { "content": "//!\n\n//! High-level IPP operation abstractions\n\n//!\n\nuse crate::{attribute::*, ipp::*, request::IppRequestResponse, IppJobSource, IppValue};\n\n\n\npub mod cups;\n\n\n\n/// Trait which represents a single IPP operation\n", "file_path": "ipp-proto/src/operation/mod.rs", "rank": 63, "score": 2.952968159896365 }, { "content": "pub struct IppServerBuilder {\n\n address: SocketAddr,\n\n handler: Arc<dyn IppRequestHandler + Send + Sync>,\n\n}\n\n\n\nimpl IppServerBuilder {\n\n /// Create builder for a given listening address\n\n pub fn new<S>(address: S) -> IppServerBuilder\n\n where\n\n SocketAddr: From<S>,\n\n {\n\n IppServerBuilder {\n\n address: address.into(),\n\n handler: Arc::new(DummyHandler),\n\n }\n\n }\n\n\n\n /// Set request handler\n\n pub fn handler(mut self, handler: Arc<dyn IppRequestHandler + Send + Sync>) -> Self {\n\n self.handler = handler;\n\n self\n\n }\n\n\n\n /// Build server\n\n pub fn build(self) -> impl Future<Item = IppServer, Error = ServerError> {\n\n IppServer::new(self.address, self.handler).into_future()\n\n }\n\n}\n", "file_path": "ipp-server/src/server.rs", "rank": 64, "score": 2.909602128966572 }, { "content": "## Asynchronous IPP client\n\n\n\nThis crate contains asynchronous IPP client based on futures and tokio runtime.\n\n\n\n## License\n\n\n\nLicensed under MIT or Apache license ([LICENSE-MIT](https://opensource.org/licenses/MIT) or [LICENSE-APACHE](https://opensource.org/licenses/Apache-2.0))\n", "file_path": "ipp-client/README.md", "rank": 65, "score": 2.8793574295013182 }, { "content": " ///\n\n /// * `source` - `IppJobSource`<br/>\n\n /// * `user_name` - name of the user (requesting-user-name)<br/>\n\n /// * `job_name` - job name (job-name)<br/>\n\n pub fn new<U, N>(source: IppJobSource, user_name: Option<U>, job_name: Option<N>) -> PrintJob\n\n where\n\n U: AsRef<str>,\n\n N: AsRef<str>,\n\n {\n\n PrintJob {\n\n source,\n\n user_name: user_name.map(|v| v.as_ref().to_string()),\n\n job_name: job_name.map(|v| v.as_ref().to_string()),\n\n attributes: Vec::new(),\n\n }\n\n }\n\n\n\n /// Set extra job attribute for this operation, for example `colormodel=grayscale`\n\n pub fn add_attribute(&mut self, attribute: IppAttribute) {\n\n self.attributes.push(attribute);\n", "file_path": "ipp-proto/src/operation/mod.rs", "rank": 66, "score": 2.8778836672964587 }, { "content": " while let Some(item) = try_ready!(self.stream.poll()) {\n\n match self.state {\n\n AsyncParseState::Headers(ref mut buffer) => {\n\n buffer.extend_from_slice(item.as_ref());\n\n let length = buffer.len() as u64;\n\n\n\n let mut reader = io::Cursor::new(buffer);\n\n let parser = IppParser::new(&mut reader);\n\n\n\n match parser.parse() {\n\n Ok(mut result) => {\n\n debug!(\"Parse ok, proceeding to payload state\");\n\n if reader.position() < length {\n\n debug!(\"Adding residual payload from this chunk\");\n\n let mut temp = tempfile::NamedTempFile::new()?;\n\n io::copy(&mut reader, &mut temp)?;\n\n result.payload = Some(PayloadKind::ReceivedData(temp));\n\n }\n\n self.state = AsyncParseState::Payload(result);\n\n }\n", "file_path": "ipp-proto/src/parser.rs", "rank": 67, "score": 2.8634538148086937 }, { "content": " );\n\n let mut buf = Vec::new();\n\n assert!(attr.write(&mut io::Cursor::new(&mut buf)).is_ok());\n\n\n\n assert_eq!(\n\n vec![\n\n 0x34, 0, 4, b'c', b'o', b'l', b'l', 0, 0, 0x21, 0, 0, 0, 4, 0x11, 0x11, 0x11, 0x11, 0x21, 0, 0, 0, 4,\n\n 0x22, 0x22, 0x22, 0x22, 0x37, 0, 0, 0, 0,\n\n ],\n\n buf\n\n );\n\n\n\n let mut data = vec![1, 1, 0, 0, 0, 0, 0, 0, 4];\n\n data.extend(buf);\n\n data.extend(vec![3]);\n\n\n\n let result = crate::parser::IppParser::new(&mut io::Cursor::new(data)).parse();\n\n assert!(result.is_ok());\n\n\n\n let res = result.ok().unwrap();\n\n let attrs = res.attributes.groups_of(DelimiterTag::PrinterAttributes)[0].attributes();\n\n let attr = attrs.get(\"coll\").unwrap();\n\n assert_eq!(\n\n attr.value().as_collection(),\n\n Some(&vec![IppValue::Integer(0x11111111), IppValue::Integer(0x22222222)])\n\n );\n\n }\n\n}\n", "file_path": "ipp-proto/src/value.rs", "rank": 68, "score": 2.7927783673406035 }, { "content": " self\n\n }\n\n\n\n /// Specify which attributes to retrieve from the printer\n\n pub fn attributes<T>(mut self, attributes: &[T]) -> Self\n\n where\n\n T: AsRef<str>,\n\n {\n\n self.attributes\n\n .extend(attributes.iter().map(|s| s.as_ref().to_string()));\n\n self\n\n }\n\n\n\n /// Build operation\n\n pub fn build(self) -> impl IppOperation {\n\n GetPrinterAttributes::with_attributes(&self.attributes)\n\n }\n\n}\n\n\n\n/// Builder to create CreateJob operation\n", "file_path": "ipp-proto/src/builder.rs", "rank": 69, "score": 2.713434000254688 }, { "content": " Response::new(Body::wrap_stream(response.into_stream()))\n\n })\n\n })\n\n })\n\n .map_err(ServerError::from);\n\n\n\n Ok(IppServer { inner: Box::new(inner) })\n\n }\n\n}\n\n\n\nimpl Future for IppServer {\n\n type Item = ();\n\n type Error = ServerError;\n\n\n\n fn poll(&mut self) -> Poll<Self::Item, Self::Error> {\n\n self.inner.poll()\n\n }\n\n}\n\n\n\n/// Builder to create IPP servers\n", "file_path": "ipp-server/src/server.rs", "rank": 70, "score": 2.6991044344443402 }, { "content": " verify_hostname: bool,\n\n verify_certificate: bool,\n\n timeout: u64,\n\n}\n\n\n\nimpl IppClientBuilder {\n\n /// Create a client builder for a given URI\n\n pub fn new(uri: &str) -> Self {\n\n IppClientBuilder {\n\n uri: uri.to_owned(),\n\n ca_certs: Vec::new(),\n\n verify_hostname: true,\n\n verify_certificate: true,\n\n timeout: 0,\n\n }\n\n }\n\n\n\n /// Add CA certificate\n\n pub fn ca_cert<P>(mut self, path: P) -> Self\n\n where\n", "file_path": "ipp-client/src/lib.rs", "rank": 71, "score": 2.4788293490373503 }, { "content": "pub struct CreateJobBuilder {\n\n job_name: Option<String>,\n\n attributes: Vec<IppAttribute>,\n\n}\n\n\n\nimpl CreateJobBuilder {\n\n fn new() -> CreateJobBuilder {\n\n CreateJobBuilder {\n\n job_name: None,\n\n attributes: Vec::new(),\n\n }\n\n }\n\n\n\n /// Specify job-name attribute\n\n pub fn job_name(mut self, job_name: &str) -> Self {\n\n self.job_name = Some(job_name.to_owned());\n\n self\n\n }\n\n\n\n /// Specify custom job attribute\n", "file_path": "ipp-proto/src/builder.rs", "rank": 72, "score": 2.4788293490373503 }, { "content": " IppValue::Other { .. } => ValueTag::Unknown,\n\n }\n\n }\n\n\n\n /// Read value from binary stream\n\n pub fn read(vtag: u8, reader: &mut dyn Read) -> io::Result<IppValue> {\n\n let vsize = reader.read_u16::<BigEndian>()?;\n\n\n\n let ipptag = match ValueTag::from_u8(vtag) {\n\n Some(x) => x,\n\n None => {\n\n return Ok(IppValue::Other {\n\n tag: vtag,\n\n data: reader.read_bytes(vsize as usize)?,\n\n });\n\n }\n\n };\n\n\n\n match ipptag {\n\n ValueTag::Integer => {\n", "file_path": "ipp-proto/src/value.rs", "rank": 73, "score": 2.4457690891857538 }, { "content": " is_last: bool,\n\n}\n\n\n\nimpl SendDocumentBuilder {\n\n fn new(job_id: i32, source: IppJobSource) -> SendDocumentBuilder {\n\n SendDocumentBuilder {\n\n job_id,\n\n source,\n\n user_name: None,\n\n is_last: true,\n\n }\n\n }\n\n\n\n /// Specify originating-user-name attribute\n\n pub fn user_name(mut self, user_name: &str) -> Self {\n\n self.user_name = Some(user_name.to_owned());\n\n self\n\n }\n\n\n\n /// Parameter which indicates whether this document is a last one\n", "file_path": "ipp-proto/src/builder.rs", "rank": 74, "score": 2.4436166607155747 }, { "content": " verify_certificate: self.verify_certificate,\n\n timeout: self.timeout,\n\n }\n\n }\n\n}\n\n\n\n#[cfg(test)]\n\nmod tests {\n\n use super::*;\n\n\n\n #[test]\n\n fn test_builder() {\n\n let mut builder = IppClientBuilder::new(\"foobar\");\n\n assert_eq!(builder.uri, \"foobar\");\n\n\n\n let cert = PathBuf::from(\"mycert\");\n\n builder = builder.ca_cert(&cert);\n\n assert_eq!(builder.ca_certs, vec![cert.clone()]);\n\n\n\n builder = builder.ca_certs(&[cert.clone()]);\n", "file_path": "ipp-client/src/lib.rs", "rank": 75, "score": 2.4423384079706745 }, { "content": " payload: None,\n\n }\n\n }\n\n}\n\n\n\n/// IPP parser implementation\n\npub struct IppParser<'a> {\n\n reader: &'a mut dyn Read,\n\n current_group: Option<IppAttributeGroup>,\n\n last_name: Option<String>,\n\n context: Vec<Vec<IppValue>>,\n\n attributes: IppAttributes,\n\n}\n\n\n\nimpl<'a> IppParser<'a> {\n\n /// Create IPP parser using the given Read\n\n pub fn new(reader: &'a mut dyn Read) -> IppParser<'a> {\n\n IppParser {\n\n reader,\n\n current_group: None,\n", "file_path": "ipp-proto/src/parser.rs", "rank": 76, "score": 2.390663953845645 }, { "content": " .map(ToOwned::to_owned)\n\n .collect::<Vec<_>>();\n\n\n\n if keywords.iter().any(|k| ERROR_STATES.contains(&&k[..])) {\n\n debug!(\"Printer is in error state: {:?}\", keywords);\n\n return Err(IppError::PrinterStateError(keywords.clone()));\n\n }\n\n }\n\n Ok(())\n\n })\n\n }\n\n\n\n /// send IPP operation\n\n pub fn send<T>(&self, operation: T) -> impl Future<Item = IppAttributes, Error = IppError>\n\n where\n\n T: IppOperation,\n\n {\n\n debug!(\"Sending IPP operation\");\n\n self.send_request(operation.into_ipp_request(&to_device_uri(&self.uri)))\n\n .and_then(|resp| {\n", "file_path": "ipp-client/src/client.rs", "rank": 77, "score": 2.3822027380211614 }, { "content": "pub mod builder;\n\npub mod ipp;\n\npub mod operation;\n\npub mod parser;\n\npub mod request;\n\npub mod value;\n\n\n\n/// Source for IPP data stream (job file)\n\npub struct IppJobSource {\n\n inner: Box<dyn AsyncRead + Send>,\n\n buffer: Vec<u8>,\n\n}\n\n\n\nimpl IppJobSource {\n\n const CHUNK_SIZE: usize = 32768;\n\n}\n\n\n\nimpl Stream for IppJobSource {\n\n type Item = Bytes;\n\n type Error = io::Error;\n", "file_path": "ipp-proto/src/lib.rs", "rank": 78, "score": 2.3772562295241095 }, { "content": " builder = certs\n\n .into_iter()\n\n .fold(builder, |builder, ca_cert| builder.add_root_certificate(ca_cert));\n\n\n\n builder\n\n .build()\n\n .into_future()\n\n .and_then(move |client| {\n\n let mut builder = client\n\n .post(url.clone())\n\n .header(\"Content-Type\", \"application/ipp\")\n\n .body(request.into_stream());\n\n\n\n if !url.username().is_empty() {\n\n debug!(\"Setting basic auth: {} ****\", url.username());\n\n builder = builder.basic_auth(\n\n url.username(),\n\n url.password()\n\n .map(|p| percent_encoding::percent_decode(p.as_bytes()).decode_utf8().unwrap()),\n\n );\n", "file_path": "ipp-client/src/client.rs", "rank": 79, "score": 2.3338468282760703 }, { "content": " self.attributes.into_iter().fold(op, |mut op, attr| {\n\n op.add_attribute(attr);\n\n op\n\n })\n\n }\n\n}\n\n\n\n/// Builder to create GetPrinterAttributes operation\n\npub struct GetPrinterAttributesBuilder {\n\n attributes: Vec<String>,\n\n}\n\n\n\nimpl GetPrinterAttributesBuilder {\n\n fn new() -> GetPrinterAttributesBuilder {\n\n GetPrinterAttributesBuilder { attributes: Vec::new() }\n\n }\n\n\n\n /// Specify which attribute to retrieve from the printer. Can be repeated.\n\n pub fn attribute(mut self, attribute: &str) -> Self {\n\n self.attributes.push(attribute.to_owned());\n", "file_path": "ipp-proto/src/builder.rs", "rank": 80, "score": 2.327877400621192 }, { "content": "use crate::{\n\n attribute::IppAttribute,\n\n operation::{CreateJob, GetPrinterAttributes, IppOperation, PrintJob, SendDocument},\n\n IppJobSource,\n\n};\n\n\n\n/// Builder to create IPP operations\n\npub struct IppOperationBuilder;\n\n\n\nimpl IppOperationBuilder {\n\n /// Create PrintJob operation\n\n ///\n\n /// * `source` - `IppJobSource`\n\n pub fn print_job<T>(source: T) -> PrintJobBuilder\n\n where\n\n IppJobSource: From<T>,\n\n {\n\n PrintJobBuilder::new(source.into())\n\n }\n\n\n", "file_path": "ipp-proto/src/builder.rs", "rank": 81, "score": 2.309233535887218 }, { "content": " }\n\n\n\n /// Get mutable payload\n\n pub fn payload_mut(&mut self) -> &mut Option<PayloadKind> {\n\n &mut self.payload\n\n }\n\n\n\n /// Set payload\n\n pub fn add_payload(&mut self, payload: IppJobSource) {\n\n self.payload = Some(PayloadKind::JobSource(payload))\n\n }\n\n\n\n /// Serialize request into the binary stream (TCP)\n\n pub fn write(&mut self, writer: &mut dyn Write) -> io::Result<usize> {\n\n let mut retval = self.header.write(writer)?;\n\n\n\n retval += self.attributes.write(writer)?;\n\n\n\n debug!(\"Wrote {} bytes IPP stream\", retval);\n\n\n", "file_path": "ipp-proto/src/request.rs", "rank": 82, "score": 2.2968303937761734 }, { "content": " if resp.header().operation_status > 2 {\n\n // IPP error\n\n Err(IppError::StatusError(\n\n ipp::StatusCode::from_u16(resp.header().operation_status)\n\n .unwrap_or(ipp::StatusCode::ServerErrorInternalError),\n\n ))\n\n } else {\n\n Ok(resp.attributes().clone())\n\n }\n\n })\n\n }\n\n\n\n /// Send request and return response\n\n pub fn send_request(\n\n &self,\n\n request: IppRequestResponse,\n\n ) -> impl Future<Item = IppRequestResponse, Error = IppError> + Send {\n\n // Some printers don't support gzip\n\n let mut builder = Client::builder().gzip(false).connect_timeout(Duration::from_secs(10));\n\n\n", "file_path": "ipp-client/src/client.rs", "rank": 83, "score": 2.2574734094665083 }, { "content": " crossfeed: reader.read_i32::<BigEndian>()?,\n\n feed: reader.read_i32::<BigEndian>()?,\n\n units: reader.read_i8()?,\n\n }),\n\n _ => Ok(IppValue::Other {\n\n tag: vtag,\n\n data: reader.read_bytes(vsize as usize)?,\n\n }),\n\n }\n\n }\n\n}\n\n\n\nimpl IppWriter for IppValue {\n\n /// Write value to binary stream\n\n fn write(&self, writer: &mut dyn Write) -> io::Result<usize> {\n\n match *self {\n\n IppValue::Integer(i) | IppValue::Enum(i) => {\n\n writer.write_u16::<BigEndian>(4)?;\n\n writer.write_i32::<BigEndian>(i)?;\n\n Ok(6)\n", "file_path": "ipp-proto/src/value.rs", "rank": 84, "score": 2.2511350046427765 }, { "content": " }\n\n\n\n fn validate_job(&self, req: IppRequestResponse) -> IppServerResult {\n\n println!(\"Validate-Job\");\n\n println!(\"{:?}\", req.header());\n\n println!(\"{:?}\", req.attributes());\n\n\n\n let resp = IppRequestResponse::new_response(self.version(), StatusCode::SuccessfulOK, req.header().request_id);\n\n\n\n Ok(resp)\n\n }\n\n\n\n fn get_printer_attributes(&self, req: IppRequestResponse) -> IppServerResult {\n\n static SUPPORTED_ATTRIBUTES: &[&'static str] = &[\n\n PRINTER_URI_SUPPORTED,\n\n URI_SECURITY_SUPPORTED,\n\n URI_AUTHENTICATION_SUPPORTED,\n\n PRINTER_NAME,\n\n PRINTER_STATE,\n\n PRINTER_STATE_REASONS,\n", "file_path": "ipp-server/examples/ipp-server.rs", "rank": 85, "score": 2.2226060681942954 }, { "content": " } else {\n\n let mut new_group = IppAttributeGroup::new(tag);\n\n new_group\n\n .attributes_mut()\n\n .insert(attribute.name().to_owned(), attribute);\n\n self.groups_mut().push(new_group);\n\n }\n\n }\n\n}\n\n\n\nimpl IppWriter for IppAttributes {\n\n /// Serialize attribute list into binary stream\n\n fn write(&self, writer: &mut dyn Write) -> io::Result<usize> {\n\n // first send the header attributes\n\n writer.write_u8(DelimiterTag::OperationAttributes as u8)?;\n\n\n\n let mut retval = 1;\n\n\n\n if let Some(group) = self.groups_of(DelimiterTag::OperationAttributes).get(0) {\n\n for hdr in &HEADER_ATTRS {\n", "file_path": "ipp-proto/src/attribute.rs", "rank": 86, "score": 2.2216683105267028 }, { "content": " debug!(\"Payload chunk received, creating new file: {}\", temp.path().display());\n\n io::copy(&mut reader, &mut temp)?;\n\n result.payload = Some(PayloadKind::ReceivedData(temp));\n\n }\n\n _ => panic!(\"Should not happen\"),\n\n }\n\n }\n\n }\n\n }\n\n\n\n match self.state {\n\n AsyncParseState::Headers(_) => Err(ParseError::Incomplete),\n\n AsyncParseState::Payload(ref mut result) => {\n\n debug!(\"Parsing finished, payload: {}\", result.payload.is_some());\n\n Ok(Async::Ready(IppParseResult {\n\n header: result.header.clone(),\n\n attributes: result.attributes.clone(),\n\n payload: result.payload.take(),\n\n }))\n\n }\n", "file_path": "ipp-proto/src/parser.rs", "rank": 87, "score": 2.1929630699012606 }, { "content": "\n\nimpl SendDocument {\n\n /// Create Send-Document operation\n\n ///\n\n /// * `job_id` - job ID returned by Create-Job operation<br/>\n\n /// * `source` - `IppJobSource`<br/>\n\n /// * `user_name` - name of the user (requesting-user-name)<br/>\n\n /// * `last` - whether this document is a last one<br/>\n\n pub fn new<S>(job_id: i32, source: IppJobSource, user_name: Option<S>, last: bool) -> SendDocument\n\n where\n\n S: AsRef<str>,\n\n {\n\n SendDocument {\n\n job_id,\n\n source,\n\n user_name: user_name.map(|v| v.as_ref().to_string()),\n\n last,\n\n }\n\n }\n\n}\n", "file_path": "ipp-proto/src/operation/mod.rs", "rank": 88, "score": 2.1803490111555957 }, { "content": "///\n\n/// IPP client is responsible for sending requests to IPP server.\n\npub struct IppClient {\n\n pub(crate) uri: String,\n\n pub(crate) ca_certs: Vec<PathBuf>,\n\n pub(crate) verify_hostname: bool,\n\n pub(crate) verify_certificate: bool,\n\n pub(crate) timeout: u64,\n\n}\n\n\n\nimpl IppClient {\n\n /// Check printer ready status\n\n pub fn check_ready(&self) -> impl Future<Item = (), Error = IppError> {\n\n debug!(\"Checking printer status\");\n\n let operation = IppOperationBuilder::get_printer_attributes()\n\n .attributes(&[PRINTER_STATE, PRINTER_STATE_REASONS])\n\n .build();\n\n\n\n self.send(operation).and_then(|attrs| {\n\n let state = attrs\n", "file_path": "ipp-client/src/client.rs", "rank": 89, "score": 2.118801004306522 }, { "content": " }\n\n}\n\n\n\nimpl IppOperation for PrintJob {\n\n fn into_ipp_request(self, uri: &str) -> IppRequestResponse {\n\n let mut retval = IppRequestResponse::new(self.version(), Operation::PrintJob, Some(uri));\n\n\n\n if let Some(ref user_name) = self.user_name {\n\n retval.attributes_mut().add(\n\n DelimiterTag::OperationAttributes,\n\n IppAttribute::new(REQUESTING_USER_NAME, IppValue::NameWithoutLanguage(user_name.clone())),\n\n );\n\n }\n\n\n\n if let Some(ref job_name) = self.job_name {\n\n retval.attributes_mut().add(\n\n DelimiterTag::OperationAttributes,\n\n IppAttribute::new(JOB_NAME, IppValue::NameWithoutLanguage(job_name.clone())),\n\n )\n\n }\n", "file_path": "ipp-proto/src/operation/mod.rs", "rank": 90, "score": 2.0877325057139697 }, { "content": " }\n\n}\n\nimpl<R: io::Read + ?Sized> IppReadExt for R {}\n\n\n\n/// IPP request and response header\n\n#[derive(Clone, Debug)]\n\npub struct IppHeader {\n\n /// IPP protocol version\n\n pub version: IppVersion,\n\n /// Operation tag for requests, status for responses\n\n pub operation_status: u16,\n\n /// ID of the request\n\n pub request_id: u32,\n\n}\n\n\n\nimpl IppHeader {\n\n /// Create IppHeader from the reader\n\n pub fn from_reader(reader: &mut dyn Read) -> Result<IppHeader, ParseError> {\n\n let retval = IppHeader::new(\n\n IppVersion::from_u16(reader.read_u16::<BigEndian>()?).ok_or_else(|| ParseError::InvalidVersion)?,\n", "file_path": "ipp-proto/src/lib.rs", "rank": 91, "score": 2.0474637753585685 }, { "content": " pub fn new(version: IppVersion, operation: Operation, uri: Option<&str>) -> IppRequestResponse {\n\n let hdr = IppHeader::new(version, operation as u16, 1);\n\n let mut retval = IppRequestResponse {\n\n header: hdr,\n\n attributes: IppAttributes::new(),\n\n payload: None,\n\n };\n\n\n\n retval.attributes_mut().add(\n\n DelimiterTag::OperationAttributes,\n\n IppAttribute::new(ATTRIBUTES_CHARSET, IppValue::Charset(\"utf-8\".to_string())),\n\n );\n\n retval.attributes_mut().add(\n\n DelimiterTag::OperationAttributes,\n\n IppAttribute::new(ATTRIBUTES_NATURAL_LANGUAGE, IppValue::NaturalLanguage(\"en\".to_string())),\n\n );\n\n\n\n if let Some(uri) = uri {\n\n retval.attributes_mut().add(\n\n DelimiterTag::OperationAttributes,\n", "file_path": "ipp-proto/src/request.rs", "rank": 92, "score": 2.026253324086177 }, { "content": "\n\nimpl IppOperation for SendDocument {\n\n fn into_ipp_request(self, uri: &str) -> IppRequestResponse {\n\n let mut retval = IppRequestResponse::new(self.version(), Operation::SendDocument, Some(uri));\n\n\n\n retval.attributes_mut().add(\n\n DelimiterTag::OperationAttributes,\n\n IppAttribute::new(JOB_ID, IppValue::Integer(self.job_id)),\n\n );\n\n\n\n if let Some(user_name) = self.user_name {\n\n retval.attributes_mut().add(\n\n DelimiterTag::OperationAttributes,\n\n IppAttribute::new(REQUESTING_USER_NAME, IppValue::NameWithoutLanguage(user_name.clone())),\n\n );\n\n }\n\n\n\n retval.attributes_mut().add(\n\n DelimiterTag::OperationAttributes,\n\n IppAttribute::new(LAST_DOCUMENT, IppValue::Boolean(self.last)),\n\n );\n\n\n\n retval.add_payload(self.source);\n\n\n\n retval\n\n }\n\n}\n", "file_path": "ipp-proto/src/operation/mod.rs", "rank": 93, "score": 1.9350791293596412 } ]
Rust
ovium/src/server.rs
snoir/ovium
357723ee3eb78b46c11ed4ce4b2b6c8e5fedb383
use crate::error::{ConfigError, Error, ErrorKind, OviumError}; use crate::types::*; use crossbeam_channel::unbounded; use crossbeam_utils::thread; use log::{error, info}; use serde::Deserialize; use signal_hook::{iterator::Signals, SIGINT}; use ssh2::Session; use std::collections::HashMap; use std::fs::File; use std::io::prelude::*; use std::io::{self, BufRead, BufReader}; use std::net::TcpStream; use std::os::unix::net::{UnixListener, UnixStream}; use std::path::Path; use std::time::Duration; pub struct Server<'a> { socket_path: &'a str, config: ServerConfig, listener: UnixListener, } #[derive(Deserialize, Debug)] pub struct ServerConfig { pub nodes: HashMap<String, Node>, #[serde(default)] pub groups: HashMap<String, Vec<String>>, } impl ServerConfig { pub fn is_group(&self, name: &str) -> bool { self.groups.contains_key(name) } } impl Server<'_> { pub fn new<'a>(socket_path: &'a str, config_path: &'a str) -> Result<Server<'a>, OviumError> { let server_config = ServerConfig::new(Path::new(config_path))?; let listener = UnixListener::bind(socket_path).map_err(|err| (ErrorKind::Bind, err.into()))?; listener .set_nonblocking(true) .map_err(|err| (ErrorKind::Bind, err.into()))?; Ok(Server { socket_path, config: server_config, listener, }) } pub fn run(&self) -> Result<(), OviumError> { thread::scope(|s| -> Result<(), OviumError> { let (signal_sender, signal_receiver) = unbounded(); let signals = Signals::new(&[SIGINT]).unwrap(); s.spawn(move |_| { for sig in signals.forever() { println!("Received signal {:?}", sig); if sig == signal_hook::SIGINT { signal_sender.clone().send(sig).unwrap(); break; } } }); for stream in self.listener.incoming() { if signal_receiver.clone().try_recv().is_ok() { break; } match stream { Ok(stream) => { /* connection succeeded */ let stream_receiver = signal_receiver.clone(); s.spawn::<_, Result<(), OviumError>>(move |_| { self.handle_client(stream, stream_receiver) .map_err(|err| (ErrorKind::Handle, err))?; Ok(()) }); } Err(ref e) if e.kind() == io::ErrorKind::WouldBlock => { std::thread::sleep(Duration::from_millis(500)); continue; } Err(_) => { /* connection failed */ break; } } } Ok(()) }) .unwrap()?; Ok(()) } fn handle_client( &self, stream: UnixStream, _signal_receiver: crossbeam_channel::Receiver<i32>, ) -> Result<(), Error> { let mut reader = BufReader::new(&stream); loop { let mut resp = Vec::new(); let read_bytes = reader.read_until(b'\n', &mut resp); match read_bytes { Ok(read_bytes) => { if read_bytes == 0 { info!("connection closed by remote"); } else { let recv_request = Request::decode(&resp)?; let handler = match recv_request { Request::Cmd(inner_req) => { ServerHandler::<CmdRequest>::new(stream, inner_req) } }; handler.validate_request(&self.config)?; handler.handle(&self.config)?; }; break; } Err(err) => match err.kind() { io::ErrorKind::Interrupted => continue, _ => break, }, } } Ok(()) } pub fn execute_cmd(node: &Node, cmd: String) -> Result<SshSuccess, Error> { let node_addr = format!("{}:{}", node.ip, node.port); let tcp = TcpStream::connect(node_addr)?; let mut sess = Session::new()?; sess.set_tcp_stream(tcp); sess.handshake()?; sess.userauth_agent(&node.user)?; let mut channel = sess.channel_session()?; channel.exec(&cmd)?; let mut stdout_string = String::new(); let mut stderr_string = String::new(); channel.read_to_string(&mut stdout_string)?; channel.stderr().read_to_string(&mut stderr_string)?; channel.wait_close()?; let stdout_string = stdout_string.replace("\n", "\\n"); let stderr_string = stderr_string.replace("\n", "\\n"); let stderr = if stderr_string.is_empty() { None } else { Some(stderr_string) }; let stdout = if stdout_string.is_empty() { None } else { Some(stdout_string) }; let exit_status = channel.exit_status()?; Ok(SshSuccess { stdout, stderr, exit_status, }) } } impl Drop for Server<'_> { fn drop(&mut self) { std::fs::remove_file(&self.socket_path).unwrap(); } } impl ServerConfig { pub fn new(config_dir: &Path) -> Result<ServerConfig, OviumError> { let nodes_file_path = config_dir.join("nodes.toml"); let nodes_config_string = match read_file(&nodes_file_path) { Ok(config_string) => config_string, Err(err) => { error!("Unable to load file {:?}: {}", &nodes_file_path, err); return Err(OviumError::from((ErrorKind::LoadConfig, err))); } }; let config: ServerConfig = toml::from_str(&nodes_config_string) .map_err(|err| (ErrorKind::InvalidConfig, ConfigError::Parse(err).into()))?; validate_config(&config).map_err(|err| (ErrorKind::InvalidConfig, err.into()))?; Ok(config) } } fn validate_config(config: &ServerConfig) -> Result<(), ConfigError> { let mut unknown_nodes: Vec<String> = Vec::new(); for node_group in &config.groups { for node in node_group.1 { if !config.nodes.contains_key(node) { unknown_nodes.push(node.to_string()); } } } if !unknown_nodes.is_empty() { return Err(ConfigError::UnknownNodes(unknown_nodes)); } Ok(()) } fn read_file(file: &Path) -> Result<String, Error> { let mut f = File::open(file)?; let mut file_string = String::new(); f.read_to_string(&mut file_string)?; Ok(file_string) }
use crate::error::{ConfigError, Error, ErrorKind, OviumError}; use crate::types::*; use crossbeam_channel::unbounded; use crossbeam_utils::thread; use log::{error, info}; use serde::Deserialize; use signal_hook::{iterator::Signals, SIGINT}; use ssh2::Session; use std::collections::HashMap; use std::fs::File; use std::io::prelude::*; use std::io::{self, BufRead, BufReader}; use std::net::TcpStream; use std::os::unix::net::{UnixListener, UnixStream}; use std::path::Path; use std::time::Duration; pub struct Server<'a> { socket_path: &'a str, config: ServerConfig, listener: UnixListener, } #[derive(Deserialize, Debug)] pub struct ServerConfig { pub nodes: HashMap<String, Node>, #[serde(default)] pub groups: HashMap<String, Vec<String>>, } impl ServerConfig { pub fn is_group(&self, name: &str) -> bool { self.groups.contains_key(name) } } impl Server<'_> { pub fn new<'a>(socket_path: &'a str, config_path: &'a str) -> Result<Server<'a>, OviumError> { let server_config = ServerConfig::new(Path::new(config_path))?; let listener = UnixListener::bind(socket_path).map_err(|err| (ErrorKind::Bind, err.into()))?; listener .set_nonblocking(true) .map_err(|err| (ErrorKind::Bind, err.into()))?; Ok(Server { socket_path, config: server_config, listener, }) } pub fn run(&self) -> Result<(), OviumError> { thread::scope(|s| -> Result<(), OviumError> { let (signal_sender, signal_receiver) = unbounded(); let signals = Signals::new(&[SIGINT]).unwrap(); s.spawn(move |_| { for sig in signals.forever() { println!("Received signal {:?}", sig); if sig == signal_hook::SIGINT { signal_sender.clone().send(sig).unwrap(); break; } } }); for stream in self.listener.incoming() { if signal_receiver.clone().try_recv().is_ok() { break; } match stream { Ok(stream) => { /* connection succeeded */ let stream_receiver = signal_receiver.clone(); s.spawn::<_, Result<(), OviumError>>(move |_| { self.handle_client(stream, stream_receiver) .map_err(|err| (ErrorKind::Handle, err))?; Ok(()) }); } Err(ref e) if e.kind() == io::ErrorKind::WouldBlock => { std::thread::sleep(Duration::from_millis(500)); continue; } Err(_) => { /* connection failed */ break; } } } Ok(()) }) .unwrap()?; Ok(()) }
pub fn execute_cmd(node: &Node, cmd: String) -> Result<SshSuccess, Error> { let node_addr = format!("{}:{}", node.ip, node.port); let tcp = TcpStream::connect(node_addr)?; let mut sess = Session::new()?; sess.set_tcp_stream(tcp); sess.handshake()?; sess.userauth_agent(&node.user)?; let mut channel = sess.channel_session()?; channel.exec(&cmd)?; let mut stdout_string = String::new(); let mut stderr_string = String::new(); channel.read_to_string(&mut stdout_string)?; channel.stderr().read_to_string(&mut stderr_string)?; channel.wait_close()?; let stdout_string = stdout_string.replace("\n", "\\n"); let stderr_string = stderr_string.replace("\n", "\\n"); let stderr = if stderr_string.is_empty() { None } else { Some(stderr_string) }; let stdout = if stdout_string.is_empty() { None } else { Some(stdout_string) }; let exit_status = channel.exit_status()?; Ok(SshSuccess { stdout, stderr, exit_status, }) } } impl Drop for Server<'_> { fn drop(&mut self) { std::fs::remove_file(&self.socket_path).unwrap(); } } impl ServerConfig { pub fn new(config_dir: &Path) -> Result<ServerConfig, OviumError> { let nodes_file_path = config_dir.join("nodes.toml"); let nodes_config_string = match read_file(&nodes_file_path) { Ok(config_string) => config_string, Err(err) => { error!("Unable to load file {:?}: {}", &nodes_file_path, err); return Err(OviumError::from((ErrorKind::LoadConfig, err))); } }; let config: ServerConfig = toml::from_str(&nodes_config_string) .map_err(|err| (ErrorKind::InvalidConfig, ConfigError::Parse(err).into()))?; validate_config(&config).map_err(|err| (ErrorKind::InvalidConfig, err.into()))?; Ok(config) } } fn validate_config(config: &ServerConfig) -> Result<(), ConfigError> { let mut unknown_nodes: Vec<String> = Vec::new(); for node_group in &config.groups { for node in node_group.1 { if !config.nodes.contains_key(node) { unknown_nodes.push(node.to_string()); } } } if !unknown_nodes.is_empty() { return Err(ConfigError::UnknownNodes(unknown_nodes)); } Ok(()) } fn read_file(file: &Path) -> Result<String, Error> { let mut f = File::open(file)?; let mut file_string = String::new(); f.read_to_string(&mut file_string)?; Ok(file_string) }
fn handle_client( &self, stream: UnixStream, _signal_receiver: crossbeam_channel::Receiver<i32>, ) -> Result<(), Error> { let mut reader = BufReader::new(&stream); loop { let mut resp = Vec::new(); let read_bytes = reader.read_until(b'\n', &mut resp); match read_bytes { Ok(read_bytes) => { if read_bytes == 0 { info!("connection closed by remote"); } else { let recv_request = Request::decode(&resp)?; let handler = match recv_request { Request::Cmd(inner_req) => { ServerHandler::<CmdRequest>::new(stream, inner_req) } }; handler.validate_request(&self.config)?; handler.handle(&self.config)?; }; break; } Err(err) => match err.kind() { io::ErrorKind::Interrupted => continue, _ => break, }, } } Ok(()) }
function_block-full_function
[ { "content": "#[proc_macro_derive(FromParsedResource)]\n\npub fn from_parsed_resource(input: TokenStream) -> TokenStream {\n\n let input = parse_macro_input!(input as DeriveInput);\n\n let fields_name = match input.data {\n\n Data::Struct(data_struct) => {\n\n let mut fields = Vec::new();\n\n for field in data_struct.fields {\n\n match field.ident {\n\n Some(ident) => fields.push(ident),\n\n None => panic!(\"Field doesn't have ident!\"),\n\n }\n\n }\n\n fields\n\n }\n\n _ => panic!(\"FromParsedResource only works for structs\"),\n\n };\n\n let st_name = input.ident;\n\n let st_name_string = st_name.to_string();\n\n let st_name_simple_ident = Ident::new(\n\n st_name_string.strip_prefix(\"Ovl\").unwrap(),\n\n Span::call_site(),\n", "file_path": "ovl_derive/src/lib.rs", "rank": 2, "score": 75890.1021936448 }, { "content": "fn unescape_new_line<'de, D>(deserializer: D) -> Result<SshSuccess, D::Error>\n\nwhere\n\n D: Deserializer<'de>,\n\n{\n\n let mut ssh_success: SshSuccess = Deserialize::deserialize(deserializer)?;\n\n if let Some(stdout) = ssh_success.stdout {\n\n ssh_success.stdout = Some(stdout.replace(\"\\\\n\", \"\\n\"));\n\n }\n\n\n\n if let Some(stderr) = ssh_success.stderr {\n\n ssh_success.stderr = Some(stderr.replace(\"\\\\n\", \"\\n\"));\n\n }\n\n\n\n Ok(ssh_success)\n\n}\n\n\n", "file_path": "ovium/src/types.rs", "rank": 3, "score": 66040.61496519584 }, { "content": "fn print_usage(program: &str, opts: &Options) {\n\n let brief = format!(\"Usage: {} [options]\", program);\n\n print!(\"{}\", opts.usage(&brief));\n\n}\n", "file_path": "ovium/src/client.rs", "rank": 4, "score": 56415.98717136743 }, { "content": "fn value_from_key<'a>(keys: &'a [String], values: &'a [String], v: &'a str) -> &'a str {\n\n let indice = keys.iter().position(|x| x == v).unwrap();\n\n &values[indice]\n\n}\n", "file_path": "ovl/src/lib.rs", "rank": 5, "score": 56350.55285784892 }, { "content": "pub trait FromParsedResource {\n\n fn from_parsed_resource(parsed_resource: &ParsedResource) -> Resource;\n\n}\n\n\n\nimpl ParsedResource {\n\n fn parse(self) -> Resource {\n\n match self.resource_type.as_str() {\n\n \"File\" => OvlFile::from_parsed_resource(&self),\n\n \"Cmd\" => OvlCmd::from_parsed_resource(&self),\n\n _ => panic!(\"Unknown resource type!\"),\n\n }\n\n }\n\n}\n\n\n\n#[derive(Debug)]\n\npub enum Operator {\n\n Plus,\n\n Minus,\n\n}\n\n\n", "file_path": "ovl/src/lib.rs", "rank": 6, "score": 34591.83818399694 }, { "content": "fn default_port() -> u32 {\n\n 22\n\n}\n\n\n", "file_path": "ovium/src/types.rs", "rank": 7, "score": 33609.89722557134 }, { "content": "fn default_user() -> String {\n\n \"root\".to_string()\n\n}\n\n\n", "file_path": "ovium/src/types.rs", "rank": 8, "score": 33609.89722557134 }, { "content": "pub trait Message: Serialize {\n\n fn decode<'a>(slice: &'a [u8]) -> Result<Self, Error>\n\n where\n\n Self: Sized + Deserialize<'a>,\n\n {\n\n Ok(bincode::deserialize(slice)?)\n\n }\n\n\n\n fn encode(&self) -> Result<Vec<u8>, Error> {\n\n let mut message = bincode::serialize(&self)?;\n\n message.extend(\"\\n\".as_bytes());\n\n Ok(message)\n\n }\n\n}\n\n\n\nimpl Message for Request {}\n\nimpl Message for Response {}\n\n\n\n#[derive(Debug)]\n\npub struct ServerHandler<T> {\n\n pub stream: UnixStream,\n\n pub req: T,\n\n}\n\n\n\nimpl<T> ServerHandler<T> {\n\n pub fn new(stream: UnixStream, req: T) -> ServerHandler<T> {\n\n ServerHandler::<T> { stream, req }\n\n }\n\n}\n\n\n", "file_path": "ovium/src/types.rs", "rank": 9, "score": 32931.34612188481 }, { "content": "pub trait ClientActions<T> {\n\n #[allow(clippy::new_ret_no_self)]\n\n fn new(response: T) -> ClientHandler<T> {\n\n ClientHandler { response }\n\n }\n\n\n\n fn handle(self) -> Result<(), Error>;\n\n}\n\n\n\nimpl Display for CmdReturn {\n\n fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {\n\n match &self.data {\n\n SshReturn::SshSuccess(success) => {\n\n if success.exit_status == 0 {\n\n write!(f, \"{}\", GREEN)?;\n\n write!(f, \"{} | SUCCESS:\", self.node_name)?;\n\n } else {\n\n write!(f, \"{}\", RED)?;\n\n write!(f, \"{} | FAILED:\", self.node_name)?;\n\n }\n", "file_path": "ovium/src/types.rs", "rank": 10, "score": 32091.889134281657 }, { "content": "pub trait ServerActions<T> {\n\n fn handle(self, server_config: &ServerConfig) -> Result<(), Error>;\n\n\n\n fn validate_request(&self, server_config: &ServerConfig) -> Result<(), Error>;\n\n}\n\n\n\n#[derive(Debug)]\n\npub struct ClientHandler<T> {\n\n pub response: T,\n\n}\n\n\n", "file_path": "ovium/src/types.rs", "rank": 11, "score": 32091.889134281657 }, { "content": "impl fmt::Display for Error {\n\n fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {\n\n match self {\n\n Error::Io(err) => write!(f, \"I/O error: {}\", err),\n\n Error::Ssh(err) => write!(f, \"Ssh error: {}\", err),\n\n Error::Json(err) => write!(f, \"Json error: {}\", err),\n\n Error::Bincode(err) => write!(f, \"Bincode error: {}\", err),\n\n Error::ConfigError(err) => write!(f, \"{}\", err),\n\n Error::RequestError(err) => write!(f, \"{}\", err),\n\n }\n\n }\n\n}\n\n\n\nimpl fmt::Display for ConfigError {\n\n fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {\n\n match self {\n\n ConfigError::Parse(err) => write!(f, \"Parsing error: {}\", err),\n\n ConfigError::UnknownNodes(err) => write!(f, \"Unknown nodes: '{}'\", err.join(\", \")),\n\n }\n\n }\n", "file_path": "ovium/src/error.rs", "rank": 12, "score": 23040.486183841553 }, { "content": "}\n\n\n\nimpl fmt::Display for RequestError {\n\n fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {\n\n match self {\n\n RequestError::UnknownNodes(err) => write!(f, \"Unknown nodes: '{}'\", err.join(\", \")),\n\n }\n\n }\n\n}\n\n\n\nimpl fmt::Display for OviumError {\n\n fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {\n\n match &self.kind {\n\n ErrorKind::InvalidConfig => writeln!(f, \"Invalid configuration\"),\n\n ErrorKind::LoadConfig => writeln!(f, \"Failed to load configuration\"),\n\n ErrorKind::Handle => writeln!(f, \"Handle error\"),\n\n ErrorKind::Bind => writeln!(f, \"Error while binding socket\"),\n\n ErrorKind::ClientRun => writeln!(f, \"Error running Ovium client\"),\n\n }?;\n\n\n", "file_path": "ovium/src/error.rs", "rank": 13, "score": 23040.118898646506 }, { "content": "#[derive(Debug)]\n\npub enum ConfigError {\n\n UnknownNodes(Vec<String>),\n\n Parse(toml::de::Error),\n\n}\n\n\n\n#[derive(Debug)]\n\npub enum RequestError {\n\n UnknownNodes(Vec<String>),\n\n}\n\n\n\n#[derive(Debug)]\n\npub enum ErrorKind {\n\n InvalidConfig,\n\n LoadConfig,\n\n Handle,\n\n Bind,\n\n ClientRun,\n\n}\n\n\n", "file_path": "ovium/src/error.rs", "rank": 14, "score": 23037.80825404273 }, { "content": "use std::fmt;\n\nuse std::io;\n\n\n\n#[derive(Debug)]\n\npub enum Error {\n\n Ssh(ssh2::Error),\n\n Io(io::Error),\n\n Json(serde_json::Error),\n\n Bincode(Box<bincode::ErrorKind>),\n\n ConfigError(ConfigError),\n\n RequestError(RequestError),\n\n}\n\n\n\n#[derive(Debug)]\n\npub struct OviumError {\n\n kind: ErrorKind,\n\n source: Error,\n\n detail: Option<String>,\n\n}\n\n\n", "file_path": "ovium/src/error.rs", "rank": 15, "score": 23036.868011440205 }, { "content": "\n\nimpl From<ConfigError> for Error {\n\n fn from(error: ConfigError) -> Self {\n\n Error::ConfigError(error)\n\n }\n\n}\n\n\n\nimpl From<RequestError> for Error {\n\n fn from(error: RequestError) -> Self {\n\n Error::RequestError(error)\n\n }\n\n}\n\n\n\nimpl From<(ErrorKind, Error)> for OviumError {\n\n fn from((kind, source): (ErrorKind, Error)) -> Self {\n\n OviumError {\n\n kind,\n\n source,\n\n detail: None,\n\n }\n", "file_path": "ovium/src/error.rs", "rank": 16, "score": 23033.29518709087 }, { "content": " }\n\n}\n\n\n\nimpl From<ssh2::Error> for Error {\n\n fn from(error: ssh2::Error) -> Self {\n\n Error::Ssh(error)\n\n }\n\n}\n\n\n\nimpl From<serde_json::Error> for Error {\n\n fn from(error: serde_json::Error) -> Self {\n\n Error::Json(error)\n\n }\n\n}\n\n\n\nimpl From<Box<bincode::ErrorKind>> for Error {\n\n fn from(error: Box<bincode::ErrorKind>) -> Self {\n\n Error::Bincode(error)\n\n }\n\n}\n", "file_path": "ovium/src/error.rs", "rank": 17, "score": 23030.773570653106 }, { "content": " if let Some(detail) = &self.detail {\n\n write!(f, \" Caused by: {}\", &self.source)?;\n\n write!(f, \" Detail: {}\", detail)\n\n } else {\n\n write!(f, \" Caused by: {}\", &self.source)\n\n }\n\n }\n\n}\n\n\n\nimpl std::error::Error for Error {}\n\n\n\nimpl std::error::Error for OviumError {\n\n fn source(&self) -> Option<&(dyn std::error::Error + 'static)> {\n\n Some(&self.source)\n\n }\n\n}\n\n\n\nimpl From<io::Error> for Error {\n\n fn from(error: io::Error) -> Self {\n\n Error::Io(error)\n", "file_path": "ovium/src/error.rs", "rank": 18, "score": 23030.683195674552 }, { "content": " }\n\n}\n\n\n\nimpl From<(ErrorKind, Error, String)> for OviumError {\n\n fn from((kind, source, detail): (ErrorKind, Error, String)) -> Self {\n\n OviumError {\n\n kind,\n\n source,\n\n detail: Some(detail),\n\n }\n\n }\n\n}\n", "file_path": "ovium/src/error.rs", "rank": 19, "score": 23030.04216873401 }, { "content": "use crate::error::Error;\n\nuse crate::server::ServerConfig;\n\nuse serde::{Deserialize, Deserializer, Serialize};\n\nuse std::fmt::{self, Display};\n\nuse std::os::unix::net::UnixStream;\n\n\n\nconst RED: &str = \"\\x1b[0;31m\";\n\nconst GREEN: &str = \"\\x1b[0;32m\";\n\nconst NC: &str = \"\\x1b[0m\";\n\n\n\n#[derive(Serialize, Deserialize, Debug)]\n\npub struct CmdReturn {\n\n pub node_name: String,\n\n pub data: SshReturn,\n\n}\n\n\n\n#[derive(Serialize, Deserialize, Debug)]\n\npub struct CmdRequest {\n\n pub nodes: Vec<String>,\n\n pub command: String,\n", "file_path": "ovium/src/types.rs", "rank": 27, "score": 17.53977022815163 }, { "content": " // If node_tx.send should failed\n\n for th in threads {\n\n if let Err(err) = th.join().unwrap() {\n\n warn!(\"A command execution thread failed with error: {}\", err);\n\n }\n\n }\n\n })\n\n .unwrap();\n\n\n\n let mut results = Vec::new();\n\n for _ in 0..nodes_nb {\n\n if let Ok(recv) = rx.recv() {\n\n results.push(recv);\n\n }\n\n }\n\n\n\n let cmd_response = Response::Cmd(results);\n\n\n\n let mut writer = BufWriter::new(&self.stream);\n\n writer.write_all(&cmd_response.encode()?)?;\n", "file_path": "ovium/src/handlers.rs", "rank": 28, "score": 15.910545834064031 }, { "content": "use crate::error::{Error, RequestError};\n\nuse crate::server::*;\n\nuse crate::types::*;\n\nuse crossbeam_utils::thread;\n\nuse log::{error, info, warn};\n\nuse std::io::{BufWriter, Write};\n\nuse std::sync::mpsc::{self, channel};\n\nuse std::sync::Arc;\n\n\n\nimpl ServerActions<CmdRequest> for ServerHandler<CmdRequest> {\n\n fn handle(self, server_config: &ServerConfig) -> Result<(), Error> {\n\n let mut nodes: Vec<&String> = Vec::new();\n\n for node in &self.req.nodes {\n\n if server_config.is_group(node) {\n\n if let Some(members) = server_config.groups.get(node) {\n\n nodes.extend(members);\n\n }\n\n } else {\n\n nodes.push(node);\n\n }\n", "file_path": "ovium/src/handlers.rs", "rank": 29, "score": 15.877666270381386 }, { "content": "use crate::error::Error;\n\nuse crate::types::*;\n\nuse getopts::Options;\n\nuse std::io::{BufRead, BufReader, BufWriter, Write};\n\nuse std::os::unix::net::UnixStream;\n\nuse std::process;\n\n\n\npub struct Client<'a> {\n\n pub socket_path: &'a str,\n\n}\n\n\n\nimpl Client<'_> {\n\n pub fn new(socket_path: &str) -> Client {\n\n Client { socket_path }\n\n }\n\n\n\n pub fn run(self, request: Request) -> Result<Response, Error> {\n\n let stream = UnixStream::connect(self.socket_path)?;\n\n let mut reader = BufReader::new(&stream);\n\n let mut writer = BufWriter::new(&stream);\n", "file_path": "ovium/src/client.rs", "rank": 30, "score": 15.747476292306306 }, { "content": " .req\n\n .nodes\n\n .iter()\n\n .cloned()\n\n .filter(|n| !available_names.contains(&n))\n\n .collect();\n\n\n\n if !not_in_config.is_empty() {\n\n error!(\n\n \"Some nodes or groups are unknown (not in config): [{}]\",\n\n not_in_config.join(\", \")\n\n );\n\n\n\n let error_response =\n\n Response::Error(ResponseError::UnknownNodes(not_in_config.clone()));\n\n let mut writer = BufWriter::new(&self.stream);\n\n writer.write_all(&error_response.encode()?)?;\n\n\n\n return Err(Error::from(RequestError::UnknownNodes(not_in_config)));\n\n }\n", "file_path": "ovium/src/handlers.rs", "rank": 31, "score": 14.380424609788385 }, { "content": "\n\n Ok(())\n\n }\n\n\n\n fn validate_request(&self, server_config: &ServerConfig) -> Result<(), Error> {\n\n let available_names = &mut server_config\n\n .nodes\n\n .keys()\n\n .into_iter()\n\n .collect::<Vec<&String>>();\n\n\n\n available_names.extend(\n\n server_config\n\n .groups\n\n .keys()\n\n .into_iter()\n\n .collect::<Vec<&String>>(),\n\n );\n\n\n\n let not_in_config: Vec<String> = self\n", "file_path": "ovium/src/handlers.rs", "rank": 32, "score": 13.864809106313244 }, { "content": " info!(\"Launching '{}' on node: {}\", node_cmd, node_name);\n\n let exec_return = Server::execute_cmd(\n\n &node_server_config.nodes[&node_name.to_owned()],\n\n node_cmd,\n\n );\n\n let ssh_return = match exec_return {\n\n Ok(ssh_return) => SshReturn::SshSuccess(ssh_return),\n\n Err(err) => SshReturn::SshFailure(err.to_string()),\n\n };\n\n let cmd_return = CmdReturn {\n\n node_name: node_name.clone(),\n\n data: ssh_return,\n\n };\n\n node_tx.send(cmd_return)?;\n\n Ok(())\n\n });\n\n\n\n threads.push(node_thread);\n\n }\n\n\n", "file_path": "ovium/src/handlers.rs", "rank": 33, "score": 13.641696895770725 }, { "content": " }\n\n }\n\n }\n\n}\n\n\n\nimpl Display for ResponseError {\n\n fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {\n\n write!(f, \"{}\", RED)?;\n\n match &self {\n\n ResponseError::UnknownNodes(ukn_nodes) => write!(\n\n f,\n\n \"ERROR: Unknown nodes or groups: [{}]\",\n\n ukn_nodes.join(\", \")\n\n )?,\n\n };\n\n write!(f, \"{}\", NC)\n\n }\n\n}\n", "file_path": "ovium/src/types.rs", "rank": 35, "score": 12.593390298990613 }, { "content": " }\n\n nodes.sort();\n\n nodes.dedup();\n\n\n\n let cmd = &self.req.command;\n\n let (tx, rx) = channel();\n\n let nodes_nb = nodes.len();\n\n // Can't use join() on Vec<&String>\n\n // Might be a bug: https://github.com/rust-lang/rust/issues/82910\n\n info!(\"Received command '{}' for nodes: {:?}\", cmd, nodes);\n\n let server_config = Arc::new(&server_config);\n\n\n\n thread::scope(move |s| {\n\n let mut threads = Vec::new();\n\n\n\n for node_name in nodes {\n\n let node_tx = tx.clone();\n\n let node_cmd = cmd.clone();\n\n let node_server_config = Arc::clone(&server_config);\n\n let node_thread = s.spawn(move |_| -> Result<(), mpsc::SendError<_>> {\n", "file_path": "ovium/src/handlers.rs", "rank": 36, "score": 11.343031387904762 }, { "content": " opts.optopt(\"s\", \"\", \"server socket path\", \"sock\");\n\n opts.optopt(\"c\", \"\", \"remote command to launch\", \"command\");\n\n opts.optopt(\"n\", \"\", \"nodes to manage\", \"nodes\");\n\n opts.optflag(\"h\", \"help\", \"print this help menu\");\n\n\n\n Cli { opts, args }\n\n }\n\n\n\n pub fn parse(&self) -> (String, Request) {\n\n let program_name = &self.args[0];\n\n let matches = match self.opts.parse(&self.args[1..]) {\n\n Ok(m) => m,\n\n Err(f) => panic!(\"{}\", f.to_string()),\n\n };\n\n\n\n if matches.opt_present(\"h\") || self.args.len() < 2 {\n\n print_usage(program_name, &self.opts);\n\n process::exit(0);\n\n }\n\n\n", "file_path": "ovium/src/client.rs", "rank": 37, "score": 10.695076648330016 }, { "content": " Variable { name: String, body: Box<AstNode> },\n\n}\n\n\n\n#[derive(Debug)]\n\npub enum Expr {\n\n Rel {\n\n op: RelOperator,\n\n lhs: Box<AstNode>,\n\n rhs: Box<AstNode>,\n\n },\n\n}\n\n\n\npeg::parser! {\n\n pub grammar parser() for str {\n\n pub rule ovl() -> Vec<AstNode> = _ o:node()* _ {\n\n o\n\n }\n\n\n\n rule _() = [' ' | '\\t' | '\\r' | '\\n']*\n\n\n", "file_path": "ovl/src/lib.rs", "rank": 38, "score": 10.49649761719984 }, { "content": " Ok(())\n\n }\n\n}\n\n\n\nimpl ClientActions<ResponseError> for ClientHandler<ResponseError> {\n\n fn handle(self) -> Result<(), Error> {\n\n println!(\"{}\", &self.response);\n\n\n\n Ok(())\n\n }\n\n}\n", "file_path": "ovium/src/handlers.rs", "rank": 39, "score": 9.750867257833834 }, { "content": "\n\n Ok(())\n\n }\n\n}\n\n\n\nimpl ClientActions<Response> for ClientHandler<Response> {\n\n fn handle(self) -> Result<(), Error> {\n\n match self.response {\n\n Response::Cmd(inner_resp) => ClientHandler::<Vec<CmdReturn>>::new(inner_resp).handle(),\n\n Response::Error(inner_resp) => ClientHandler::<ResponseError>::new(inner_resp).handle(),\n\n }\n\n }\n\n}\n\n\n\nimpl ClientActions<Vec<CmdReturn>> for ClientHandler<Vec<CmdReturn>> {\n\n fn handle(self) -> Result<(), Error> {\n\n for cmd_return in self.response {\n\n println!(\"{}\", cmd_return);\n\n }\n\n\n", "file_path": "ovium/src/handlers.rs", "rank": 40, "score": 9.078507284767102 }, { "content": "use ovl_derive::FromParsedResource;\n\n\n\n#[derive(Debug, Clone)]\n\npub struct ParsedResource {\n\n name: String,\n\n resource_type: String,\n\n content: Vec<(String, String)>,\n\n}\n\n\n\n#[derive(Debug)]\n\npub struct Resource {\n\n name: String,\n\n resource: ResourceType,\n\n}\n\n\n\n#[derive(Debug, Default, FromParsedResource)]\n\npub struct OvlFile {\n\n path: String,\n\n mode: i64,\n\n owner: String,\n", "file_path": "ovl/src/lib.rs", "rank": 41, "score": 9.069175404635272 }, { "content": "}\n\n\n\n#[derive(Serialize, Deserialize, Debug)]\n\npub enum Request {\n\n Cmd(CmdRequest),\n\n}\n\n\n\n#[derive(Serialize, Deserialize, Debug)]\n\npub enum ResponseError {\n\n UnknownNodes(Vec<String>),\n\n}\n\n\n\n#[derive(Serialize, Deserialize, Debug)]\n\npub struct Node {\n\n pub ip: String,\n\n #[serde(default = \"default_port\")]\n\n pub port: u32,\n\n #[serde(default = \"default_user\")]\n\n pub user: String,\n\n}\n\n\n", "file_path": "ovium/src/types.rs", "rank": 42, "score": 8.971304594166554 }, { "content": " let socket_path = match matches.opt_str(\"s\") {\n\n Some(s) => s,\n\n None => {\n\n eprintln!(\"socket path is required!\");\n\n process::exit(1);\n\n }\n\n };\n\n\n\n if let Some(c) = matches.opt_str(\"c\") {\n\n if let Some(n) = matches.opt_str(\"n\") {\n\n let nodes: Vec<String> = n.split(',').map(String::from).collect();\n\n let request = Request::Cmd(CmdRequest { nodes, command: c });\n\n (socket_path, request)\n\n } else {\n\n eprintln!(\"nodes list is required!\");\n\n process::exit(1);\n\n }\n\n } else {\n\n process::exit(1);\n\n }\n\n }\n\n}\n\n\n", "file_path": "ovium/src/client.rs", "rank": 43, "score": 7.732515508641013 }, { "content": " group: String,\n\n}\n\n\n\n#[derive(Debug, Default, FromParsedResource)]\n\npub struct OvlCmd {\n\n command: String,\n\n}\n\n\n\n#[derive(Debug)]\n\npub enum ResourceType {\n\n File(OvlFile),\n\n Cmd(OvlCmd),\n\n}\n\n\n", "file_path": "ovl/src/lib.rs", "rank": 44, "score": 7.316739703542629 }, { "content": "}\n\n\n\n#[derive(Serialize, Deserialize, Debug)]\n\npub enum SshReturn {\n\n #[serde(deserialize_with = \"unescape_new_line\")]\n\n SshSuccess(SshSuccess),\n\n SshFailure(String),\n\n}\n\n\n\n#[derive(Serialize, Deserialize, Debug)]\n\npub struct SshSuccess {\n\n pub stdout: Option<String>,\n\n pub stderr: Option<String>,\n\n pub exit_status: i32,\n\n}\n\n\n\n#[derive(Serialize, Deserialize, Debug)]\n\npub enum Response {\n\n Cmd(Vec<CmdReturn>),\n\n Error(ResponseError),\n", "file_path": "ovium/src/types.rs", "rank": 45, "score": 7.258813948047896 }, { "content": " }\n\n\n\n rule node_int() -> AstNode = s:int() {\n\n AstNode::Integer(s.parse::<i32>().unwrap())\n\n }\n\n\n\n rule node_float() -> AstNode = s:float() {\n\n AstNode::Float(s.parse::<f64>().unwrap())\n\n }\n\n\n\n rule resource_type() -> String = t:$(['A'..='Z']+ ['a'..='z']*) {\n\n t.to_string()\n\n }\n\n\n\n rule resource() -> AstNode\n\n = _ resource_type:resource_type() _ name:string() _ \"{\"\n\n _ content:member() ** member_separator() _ \"}\" _ {\n\n AstNode::Resource(\n\n ParsedResource {\n\n name,\n", "file_path": "ovl/src/lib.rs", "rank": 46, "score": 7.1074444411022935 }, { "content": "#[derive(Debug)]\n\npub enum RelOperator {\n\n Eq,\n\n Ge,\n\n Gt,\n\n Le,\n\n Lt,\n\n Ne,\n\n}\n\n\n\n// Idea: it might be nice / easier at some point to split Integer, Float,\n\n// String and Array inside an other enum (Values ?).\n\n#[derive(Debug)]\n\npub enum AstNode {\n\n Resource(Resource),\n\n Integer(i32),\n\n Float(f64),\n\n String(String),\n\n Array(Vec<AstNode>),\n\n IfStmt { cond: Box<Expr>, body: Vec<AstNode> },\n", "file_path": "ovl/src/lib.rs", "rank": 47, "score": 6.536585365033923 }, { "content": " );\n\n let (impl_generics, ty_generics, where_clause) = input.generics.split_for_impl();\n\n let fields_name_string: Vec<String> = fields_name.iter().map(|f| f.to_string()).collect();\n\n\n\n let token = quote! {\n\n impl FromParsedResource for #impl_generics #st_name #ty_generics #where_clause {\n\n fn from_parsed_resource(parsed_resource: &ParsedResource) -> Resource {\n\n let keys: Vec<String> = parsed_resource.content.iter().map(|k| k.0.clone()).collect();\n\n let values: Vec<String> = parsed_resource.content.iter().map(|k| k.1.clone()).collect();\n\n let mut resource = #st_name::default();\n\n\n\n #(\n\n if !keys.contains(&#fields_name_string.to_string()) {\n\n panic!(\"Missing field '{}' for struct '{}'\", #fields_name_string, #st_name_string);\n\n }\n\n )*\n\n\n\n #(\n\n resource.#fields_name = value_from_key(&keys, &values, &#fields_name_string).parse().unwrap();\n\n )*\n\n\n\n Resource { name: parsed_resource.name.clone(), resource: ResourceType::#st_name_simple_ident(resource) }\n\n }\n\n }\n\n };\n\n\n\n token.into()\n\n}\n", "file_path": "ovl_derive/src/lib.rs", "rank": 48, "score": 6.189898290574202 }, { "content": " lhs: Box::new(AstNode::Integer(lhs)),\n\n rhs: Box::new(AstNode::Integer(rhs)),\n\n }\n\n }\n\n\n\n rule rel_expr_float() -> Expr\n\n = lhs:float() _ op:rel_operator() _ rhs:float() {\n\n let lhs = lhs.parse::<f64>().unwrap();\n\n let rhs = rhs.parse::<f64>().unwrap();\n\n Expr::Rel {\n\n op,\n\n lhs: Box::new(AstNode::Float(lhs)),\n\n rhs: Box::new(AstNode::Float(rhs)),\n\n }\n\n }\n\n\n\n rule operator() -> Operator = o:$(\"+\" / \"-\") {\n\n match o {\n\n \"+\" => Operator::Plus,\n\n \"-\" => Operator::Minus,\n", "file_path": "ovl/src/lib.rs", "rank": 50, "score": 5.702636878734171 }, { "content": " _ => unreachable!()\n\n }\n\n }\n\n\n\n rule rel_operator() -> RelOperator\n\n = r:$(\"==\" / \"<\" / \"<=\" / \">\" / \">=\" / \"!=\") {\n\n match r {\n\n \"==\" => RelOperator::Eq,\n\n \"<\" => RelOperator::Lt,\n\n \"<=\" => RelOperator::Le,\n\n \">\" => RelOperator::Gt,\n\n \">=\" => RelOperator::Ge,\n\n \"!=\" => RelOperator::Ne,\n\n _ => unreachable!()\n\n }\n\n }\n\n\n\n rule variable() -> AstNode = _ n:unquoted_string() _ \"=\" _ v:node() _ {\n\n AstNode::Variable { name: n, body: Box::new(v) }\n\n }\n", "file_path": "ovl/src/lib.rs", "rank": 51, "score": 5.650289627759742 }, { "content": "\n\n let mut resp = Vec::new();\n\n writer.write_all(&request.encode()?)?;\n\n writer.flush()?;\n\n reader.read_until(b'\\n', &mut resp)?;\n\n\n\n let response = Response::decode(&resp)?;\n\n\n\n Ok(response)\n\n }\n\n}\n\n\n\npub struct Cli {\n\n opts: getopts::Options,\n\n args: Vec<String>,\n\n}\n\n\n\nimpl Cli {\n\n pub fn new(args: Vec<String>) -> Cli {\n\n let mut opts = Options::new();\n", "file_path": "ovium/src/client.rs", "rank": 52, "score": 5.513710234012821 }, { "content": "use proc_macro::TokenStream;\n\nuse proc_macro2::Span;\n\nuse quote::quote;\n\nuse syn::parse_macro_input;\n\nuse syn::Data;\n\nuse syn::DeriveInput;\n\nuse syn::Ident;\n\n\n\n#[proc_macro_derive(FromParsedResource)]\n", "file_path": "ovl_derive/src/lib.rs", "rank": 53, "score": 5.199800385993976 }, { "content": "pub mod client;\n\npub mod error;\n\npub mod handlers;\n\npub mod server;\n\npub mod types;\n", "file_path": "ovium/src/lib.rs", "rank": 54, "score": 5.168755149257354 }, { "content": "\n\n rule array() -> AstNode\n\n = \"[\" _ v:node() ** (_ \",\" _) _ \"]\" {\n\n for (i, member) in v.iter().enumerate() {\n\n if (i > 0 && !(std::mem::discriminant(member)\n\n == std::mem::discriminant(&v[i - 1]))) {\n\n // To improve by returning Err\n\n panic!(\"Array members are not of the same type!\");\n\n }\n\n }\n\n AstNode::Array(v)\n\n }\n\n }\n\n}\n\n\n", "file_path": "ovl/src/lib.rs", "rank": 55, "score": 4.550168277732229 }, { "content": " AstNode::IfStmt { cond: Box::new(rel_expr), body }\n\n }\n\n\n\n rule expr() -> Expr\n\n = rel_expr_string() / rel_expr_float() / rel_expr_int()\n\n\n\n rule rel_expr_string() -> Expr\n\n = lhs:string() _ op:rel_operator() _ rhs:string() {\n\n Expr::Rel {\n\n op,\n\n lhs: Box::new(AstNode::String(lhs)),\n\n rhs: Box::new(AstNode::String(rhs)),\n\n }\n\n }\n\n\n\n rule rel_expr_int() -> Expr= lhs:int() _ op:rel_operator() _ rhs:int() {\n\n let lhs = lhs.parse::<i32>().unwrap();\n\n let rhs = rhs.parse::<i32>().unwrap();\n\n Expr::Rel {\n\n op,\n", "file_path": "ovl/src/lib.rs", "rank": 56, "score": 3.82766390120151 }, { "content": " write!(f, \"\\n exit_status: {}\", success.exit_status)?;\n\n if let Some(stdout) = &success.stdout {\n\n write!(f, \"\\n stdout:\\n\")?;\n\n for line in stdout.trim().lines() {\n\n writeln!(f, \" {}\", line)?;\n\n }\n\n }\n\n if let Some(stderr) = &success.stderr {\n\n write!(f, \"\\n stderr:\\n\")?;\n\n for line in stderr.trim().lines() {\n\n writeln!(f, \" {}\", line)?;\n\n }\n\n }\n\n write!(f, \"{}\", NC)\n\n }\n\n SshReturn::SshFailure(failure) => {\n\n write!(f, \"{}\", RED)?;\n\n writeln!(f, \"{} | TRANSPORT FAILURE:\", self.node_name)?;\n\n writeln!(f, \" {}\", failure)?;\n\n write!(f, \"{}\", NC)\n", "file_path": "ovium/src/types.rs", "rank": 57, "score": 2.9483368736400273 }, { "content": " resource_type,\n\n content,\n\n }.parse()\n\n )\n\n }\n\n\n\n rule node() -> AstNode\n\n = resource() / if_stmt() / variable() / node_string() /\n\n node_float() / node_int() / array()\n\n\n\n rule member() -> (String, String)\n\n = k:unquoted_string() key_value_separator() _ v:resource_value() {\n\n (k, v)\n\n }\n\n\n\n rule key_value_separator() = \":\"\n\n\n\n rule if_stmt() -> AstNode\n\n = \"if\" _ \"(\" _ rel_expr:expr() _ \")\" _\n\n \"{\" _ body:(node())* _ \"}\" _ {\n", "file_path": "ovl/src/lib.rs", "rank": 58, "score": 2.7574893430970913 }, { "content": " rule resource_value() -> String = float() / int() / string()\n\n\n\n rule member_separator() = _ \",\" _\n\n\n\n rule int() -> String = n:$(\"-\"?['0'..='9']+) { n.to_string() }\n\n\n\n rule float() -> String = n:$(\"-\"?['0'..='9']+\".\"['0'..='9']+) {\n\n n.to_string()\n\n }\n\n\n\n rule string() -> String = \"\\\"\" s:$(!\"\\\"\" [_])* \"\\\"\" {\n\n s.into_iter().collect()\n\n }\n\n\n\n rule unquoted_string() -> String = k:$(['a'..='z'])* {\n\n k.into_iter().collect()\n\n }\n\n\n\n rule node_string() -> AstNode = s:string() {\n\n AstNode::String(s)\n", "file_path": "ovl/src/lib.rs", "rank": 59, "score": 2.3388852390303696 } ]
Rust
tough/tests/target_path_safety.rs
flavio/tough
0ebe90c54d1b993d64c265a2d315cad3ad9a1699
mod test_utils; use chrono::{DateTime, TimeZone, Utc}; use maplit::hashmap; use ring::rand::SystemRandom; use std::collections::HashMap; use std::fs::{self, create_dir_all, File}; use std::num::NonZeroU64; use std::path::Path; use tempfile::TempDir; use test_utils::{dir_url, test_data, DATA_1, DATA_2, DATA_3}; use tough::editor::signed::SignedRole; use tough::editor::RepositoryEditor; use tough::key_source::{KeySource, LocalKeySource}; use tough::schema::{KeyHolder, PathPattern, PathSet, RoleKeys, RoleType, Root, Signed, Target}; use tough::{Prefix, RepositoryLoader, TargetName}; fn later() -> DateTime<Utc> { Utc.ymd(2999, 1, 1).and_hms(0, 0, 0) } fn create_root(root_path: &Path, consistent_snapshot: bool) -> Vec<Box<dyn KeySource>> { let keys: Vec<Box<dyn KeySource>> = vec![Box::new(LocalKeySource { path: test_data().join("snakeoil.pem"), })]; let key_pair = keys.iter().next().unwrap().as_sign().unwrap().tuf_key(); let key_id = key_pair.key_id().unwrap(); let empty_keys = RoleKeys { keyids: vec![key_id.clone()], threshold: NonZeroU64::new(1).unwrap(), _extra: Default::default(), }; let mut root = Signed { signed: Root { spec_version: "1.0.0".into(), consistent_snapshot, version: NonZeroU64::new(1).unwrap(), expires: later(), keys: HashMap::new(), roles: hashmap! { RoleType::Root => empty_keys.clone(), RoleType::Snapshot => empty_keys.clone(), RoleType::Targets => empty_keys.clone(), RoleType::Timestamp => empty_keys.clone(), }, _extra: HashMap::new(), }, signatures: Vec::new(), }; root.signed.keys.insert(key_id.clone(), key_pair.clone()); let signed_root = SignedRole::new( root.signed.clone(), &KeyHolder::Root(root.signed.clone()), &keys, &SystemRandom::new(), ) .unwrap(); std::fs::write(&root_path, signed_root.buffer()).unwrap(); keys } #[test] fn safe_target_paths() { let tempdir = TempDir::new().unwrap(); let root_path = tempdir.path().join("root.json"); let keys = create_root(&root_path, false); let one = NonZeroU64::new(1).unwrap(); let mut editor = RepositoryEditor::new(&root_path).unwrap(); editor .snapshot_version(one) .snapshot_expires(later()) .timestamp_version(one) .timestamp_expires(later()) .delegate_role( "delegated", &keys, PathSet::Paths(vec![PathPattern::new("delegated/*").unwrap()]), one, later(), one, ) .unwrap(); let repo_dir = tempdir.path().join("repo"); let targets_dir = repo_dir.join("targets"); fs::create_dir_all(targets_dir.join("foo/bar")).unwrap(); fs::create_dir_all(targets_dir.join("delegated/subdir")).unwrap(); let targets_file_1 = targets_dir.join("data1.txt"); let targets_file_2 = targets_dir.join("foo/bar/data2.txt"); let targets_file_3 = targets_dir.join("delegated/subdir/data3.txt"); fs::write(&targets_file_1, DATA_1).unwrap(); fs::write(&targets_file_2, DATA_2).unwrap(); fs::write(&targets_file_3, DATA_3).unwrap(); let target_name_1 = TargetName::new("foo/../bar/../baz/../../../../data1.txt").unwrap(); let target_1 = Target::from_path(&targets_file_1).unwrap(); let target_name_2 = TargetName::new("foo/bar/baz/../data2.txt").unwrap(); let target_2 = Target::from_path(&targets_file_2).unwrap(); let target_name_3 = TargetName::new("../delegated/foo/../subdir/data3.txt").unwrap(); let target_3 = Target::from_path(&targets_file_3).unwrap(); editor.add_target(target_name_1.clone(), target_1).unwrap(); editor.add_target(target_name_2.clone(), target_2).unwrap(); editor .targets_version(one) .unwrap() .targets_expires(later()) .unwrap() .sign_targets_editor(&keys) .unwrap() .change_delegated_targets("delegated") .unwrap() .add_target(target_name_3.clone(), target_3) .unwrap() .targets_version(one) .unwrap() .targets_expires(later()) .unwrap() .sign_targets_editor(&keys) .unwrap(); let signed_repo = editor.sign(&keys).unwrap(); let metadata_dir = repo_dir.join("metadata"); signed_repo.write(&metadata_dir).unwrap(); let loaded_repo = RepositoryLoader::new( File::open(&root_path).unwrap(), dir_url(&metadata_dir), dir_url(&targets_dir), ) .load() .unwrap(); let outdir = tempdir.path().join("outdir"); create_dir_all(&outdir).unwrap(); loaded_repo .save_target(&target_name_1, &outdir, Prefix::None) .unwrap(); loaded_repo .save_target(&target_name_2, &outdir, Prefix::None) .unwrap(); loaded_repo .save_target(&target_name_3, &outdir, Prefix::None) .unwrap(); assert!(!outdir.join("bar").exists()); assert!(!outdir.join("baz").exists()); assert!(!outdir.join("foo/bar/baz").exists()); assert!(!outdir.join("../delegated/foo/../subdir/data3.txt").exists()); assert_eq!( fs::read_to_string(outdir.join("data1.txt")).unwrap(), DATA_1 ); assert_eq!( fs::read_to_string(outdir.join("foo/bar/data2.txt")).unwrap(), DATA_2 ); assert_eq!( fs::read_to_string(outdir.join("delegated/subdir/data3.txt")).unwrap(), DATA_3 ); }
mod test_utils; use chrono::{DateTime, TimeZone, Utc}; use maplit::hashmap; use ring::rand::SystemRandom; use std::collections::HashMap; use std::fs::{self, create_dir_all, File}; use std::num::NonZeroU64; use std::path::Path; use tempfile
ap(); editor.add_target(target_name_2.clone(), target_2).unwrap(); editor .targets_version(one) .unwrap() .targets_expires(later()) .unwrap() .sign_targets_editor(&keys) .unwrap() .change_delegated_targets("delegated") .unwrap() .add_target(target_name_3.clone(), target_3) .unwrap() .targets_version(one) .unwrap() .targets_expires(later()) .unwrap() .sign_targets_editor(&keys) .unwrap(); let signed_repo = editor.sign(&keys).unwrap(); let metadata_dir = repo_dir.join("metadata"); signed_repo.write(&metadata_dir).unwrap(); let loaded_repo = RepositoryLoader::new( File::open(&root_path).unwrap(), dir_url(&metadata_dir), dir_url(&targets_dir), ) .load() .unwrap(); let outdir = tempdir.path().join("outdir"); create_dir_all(&outdir).unwrap(); loaded_repo .save_target(&target_name_1, &outdir, Prefix::None) .unwrap(); loaded_repo .save_target(&target_name_2, &outdir, Prefix::None) .unwrap(); loaded_repo .save_target(&target_name_3, &outdir, Prefix::None) .unwrap(); assert!(!outdir.join("bar").exists()); assert!(!outdir.join("baz").exists()); assert!(!outdir.join("foo/bar/baz").exists()); assert!(!outdir.join("../delegated/foo/../subdir/data3.txt").exists()); assert_eq!( fs::read_to_string(outdir.join("data1.txt")).unwrap(), DATA_1 ); assert_eq!( fs::read_to_string(outdir.join("foo/bar/data2.txt")).unwrap(), DATA_2 ); assert_eq!( fs::read_to_string(outdir.join("delegated/subdir/data3.txt")).unwrap(), DATA_3 ); }
::TempDir; use test_utils::{dir_url, test_data, DATA_1, DATA_2, DATA_3}; use tough::editor::signed::SignedRole; use tough::editor::RepositoryEditor; use tough::key_source::{KeySource, LocalKeySource}; use tough::schema::{KeyHolder, PathPattern, PathSet, RoleKeys, RoleType, Root, Signed, Target}; use tough::{Prefix, RepositoryLoader, TargetName}; fn later() -> DateTime<Utc> { Utc.ymd(2999, 1, 1).and_hms(0, 0, 0) } fn create_root(root_path: &Path, consistent_snapshot: bool) -> Vec<Box<dyn KeySource>> { let keys: Vec<Box<dyn KeySource>> = vec![Box::new(LocalKeySource { path: test_data().join("snakeoil.pem"), })]; let key_pair = keys.iter().next().unwrap().as_sign().unwrap().tuf_key(); let key_id = key_pair.key_id().unwrap(); let empty_keys = RoleKeys { keyids: vec![key_id.clone()], threshold: NonZeroU64::new(1).unwrap(), _extra: Default::default(), }; let mut root = Signed { signed: Root { spec_version: "1.0.0".into(), consistent_snapshot, version: NonZeroU64::new(1).unwrap(), expires: later(), keys: HashMap::new(), roles: hashmap! { RoleType::Root => empty_keys.clone(), RoleType::Snapshot => empty_keys.clone(), RoleType::Targets => empty_keys.clone(), RoleType::Timestamp => empty_keys.clone(), }, _extra: HashMap::new(), }, signatures: Vec::new(), }; root.signed.keys.insert(key_id.clone(), key_pair.clone()); let signed_root = SignedRole::new( root.signed.clone(), &KeyHolder::Root(root.signed.clone()), &keys, &SystemRandom::new(), ) .unwrap(); std::fs::write(&root_path, signed_root.buffer()).unwrap(); keys } #[test] fn safe_target_paths() { let tempdir = TempDir::new().unwrap(); let root_path = tempdir.path().join("root.json"); let keys = create_root(&root_path, false); let one = NonZeroU64::new(1).unwrap(); let mut editor = RepositoryEditor::new(&root_path).unwrap(); editor .snapshot_version(one) .snapshot_expires(later()) .timestamp_version(one) .timestamp_expires(later()) .delegate_role( "delegated", &keys, PathSet::Paths(vec![PathPattern::new("delegated/*").unwrap()]), one, later(), one, ) .unwrap(); let repo_dir = tempdir.path().join("repo"); let targets_dir = repo_dir.join("targets"); fs::create_dir_all(targets_dir.join("foo/bar")).unwrap(); fs::create_dir_all(targets_dir.join("delegated/subdir")).unwrap(); let targets_file_1 = targets_dir.join("data1.txt"); let targets_file_2 = targets_dir.join("foo/bar/data2.txt"); let targets_file_3 = targets_dir.join("delegated/subdir/data3.txt"); fs::write(&targets_file_1, DATA_1).unwrap(); fs::write(&targets_file_2, DATA_2).unwrap(); fs::write(&targets_file_3, DATA_3).unwrap(); let target_name_1 = TargetName::new("foo/../bar/../baz/../../../../data1.txt").unwrap(); let target_1 = Target::from_path(&targets_file_1).unwrap(); let target_name_2 = TargetName::new("foo/bar/baz/../data2.txt").unwrap(); let target_2 = Target::from_path(&targets_file_2).unwrap(); let target_name_3 = TargetName::new("../delegated/foo/../subdir/data3.txt").unwrap(); let target_3 = Target::from_path(&targets_file_3).unwrap(); editor.add_target(target_name_1.clone(), target_1).unwr
random
[ { "content": "fn round_time(time: DateTime<Utc>) -> DateTime<Utc> {\n\n // `Timelike::with_nanosecond` returns None only when passed a value >= 2_000_000_000\n\n time.with_nanosecond(0).unwrap()\n\n}\n\n\n", "file_path": "tuftool/src/root.rs", "rank": 0, "score": 81033.12215003767 }, { "content": "/// Ensures that system time has not stepped backward since it was last sampled\n\nfn system_time(datastore: &Datastore) -> Result<DateTime<Utc>> {\n\n let file = \"latest_known_time.json\";\n\n // Get 'current' system time\n\n let sys_time = Utc::now();\n\n // Load the latest known system time, if it exists\n\n if let Some(Ok(latest_known_time)) = datastore\n\n .reader(file)?\n\n .map(serde_json::from_reader::<_, DateTime<Utc>>)\n\n {\n\n // Make sure the sampled system time did not go back in time\n\n ensure!(\n\n sys_time >= latest_known_time,\n\n error::SystemTimeSteppedBackwardSnafu {\n\n sys_time,\n\n latest_known_time\n\n }\n\n );\n\n }\n\n // Store the latest known time\n\n // Serializes RFC3339 time string and store to datastore\n\n datastore.create(file, &sys_time)?;\n\n Ok(sys_time)\n\n}\n\n\n", "file_path": "tough/src/lib.rs", "rank": 2, "score": 61543.54374533289 }, { "content": "/// Asserts that the named file in `indir` exactly matches the file in `tuf-reference-impl/`\n\nfn assert_reference_file_match(indir: &TempDir, filename: &str, filetype: FileType) {\n\n let got = read_to_string(indir.path().join(filename)).unwrap();\n\n\n\n let ref_dir = match filetype {\n\n FileType::Metadata => \"metadata\",\n\n FileType::Target => \"targets\",\n\n };\n\n let reference = read_to_string(\n\n test_utils::test_data()\n\n .join(\"tuf-reference-impl\")\n\n .join(ref_dir)\n\n .join(filename),\n\n )\n\n .unwrap();\n\n\n\n assert_eq!(got, reference, \"{} contents do not match.\", filename);\n\n}\n\n\n", "file_path": "tuftool/tests/clone_command.rs", "rank": 3, "score": 45946.37469514731 }, { "content": "#![allow(clippy::used_underscore_binding)] // #20\n\n\n\n//! Provides the schema objects as defined by the TUF spec.\n\n\n\nmod de;\n\npub mod decoded;\n\nmod error;\n\nmod iter;\n\npub mod key;\n\nmod spki;\n\nmod verify;\n\n\n\nuse crate::schema::decoded::{Decoded, Hex};\n\npub use crate::schema::error::{Error, Result};\n\nuse crate::schema::iter::KeysIter;\n\nuse crate::schema::key::Key;\n\nuse crate::sign::Sign;\n\npub use crate::transport::{FilesystemTransport, Transport};\n\nuse crate::{encode_filename, TargetName};\n\nuse chrono::{DateTime, Utc};\n", "file_path": "tough/src/schema/mod.rs", "rank": 4, "score": 44289.9811899929 }, { "content": "// Copyright 2019 Amazon.com, Inc. or its affiliates. All Rights Reserved.\n\n// SPDX-License-Identifier: MIT OR Apache-2.0\n\n#![allow(clippy::used_underscore_binding)] // #20\n\n\n\n//! Provides a `RepositoryEditor` object for building and editing TUF repositories.\n\n\n\nmod keys;\n\npub mod signed;\n\npub mod targets;\n\nmod test;\n\n\n\nuse crate::editor::signed::{SignedDelegatedTargets, SignedRepository, SignedRole};\n\nuse crate::editor::targets::TargetsEditor;\n\nuse crate::error::{self, Result};\n\nuse crate::fetch::fetch_max_size;\n\nuse crate::key_source::KeySource;\n\nuse crate::schema::decoded::{Decoded, Hex};\n\nuse crate::schema::key::Key;\n\nuse crate::schema::{\n\n Hashes, KeyHolder, PathSet, Role, RoleType, Root, Signed, Snapshot, SnapshotMeta, Target,\n", "file_path": "tough/src/editor/mod.rs", "rank": 5, "score": 44285.73091291086 }, { "content": " Targets, Timestamp, TimestampMeta,\n\n};\n\nuse crate::transport::Transport;\n\nuse crate::{encode_filename, Limits};\n\nuse crate::{Repository, TargetName};\n\nuse chrono::{DateTime, Utc};\n\nuse ring::digest::{SHA256, SHA256_OUTPUT_LEN};\n\nuse ring::rand::SystemRandom;\n\nuse serde_json::Value;\n\nuse snafu::{ensure, OptionExt, ResultExt};\n\nuse std::borrow::Cow;\n\nuse std::collections::HashMap;\n\nuse std::convert::TryInto;\n\nuse std::fmt::Display;\n\nuse std::num::NonZeroU64;\n\nuse std::path::Path;\n\nuse url::Url;\n\n\n\nconst SPEC_VERSION: &str = \"1.0.0\";\n\n\n", "file_path": "tough/src/editor/mod.rs", "rank": 6, "score": 44284.13081179646 }, { "content": "use globset::{Glob, GlobMatcher};\n\nuse hex::ToHex;\n\nuse olpc_cjson::CanonicalFormatter;\n\nuse ring::digest::{digest, Context, SHA256};\n\nuse serde::de::Error as SerdeDeError;\n\nuse serde::{Deserialize, Deserializer, Serialize, Serializer};\n\nuse serde_json::Value;\n\nuse serde_plain::{derive_display_from_serialize, derive_fromstr_from_deserialize};\n\nuse snafu::ResultExt;\n\nuse std::collections::HashMap;\n\nuse std::fs::File;\n\nuse std::io::Read;\n\nuse std::num::NonZeroU64;\n\nuse std::ops::{Deref, DerefMut};\n\nuse std::path::Path;\n\nuse std::str::FromStr;\n\n\n\n/// The type of metadata role.\n\n#[derive(Debug, Clone, Copy, Deserialize, Serialize, PartialEq, Eq, Hash)]\n\n#[serde(rename_all = \"kebab-case\")]\n", "file_path": "tough/src/schema/mod.rs", "rank": 7, "score": 44283.780000704115 }, { "content": "/// for the specified role. To sign a `Targets` role from the `TargetsEditor` use `sign_targets_editor()`.\n\n/// This will clear out the targets editor and insert the newly signed targets in `signed_targets`.\n\n///\n\n/// To update an existing targets from a metadata file use `update_delegated_targets()`.\n\n///\n\n/// To add a new role from metadata to the `Targets` in `TargetsEditor` use `add_role()`.\n\n#[derive(Debug)]\n\npub struct RepositoryEditor {\n\n signed_root: SignedRole<Root>,\n\n\n\n snapshot_version: Option<NonZeroU64>,\n\n snapshot_expires: Option<DateTime<Utc>>,\n\n snapshot_extra: Option<HashMap<String, Value>>,\n\n\n\n timestamp_version: Option<NonZeroU64>,\n\n timestamp_expires: Option<DateTime<Utc>>,\n\n timestamp_extra: Option<HashMap<String, Value>>,\n\n\n\n targets_editor: Option<TargetsEditor>,\n\n\n", "file_path": "tough/src/editor/mod.rs", "rank": 8, "score": 44283.64306168742 }, { "content": " self.targets_editor_mut()?.clear_targets();\n\n Ok(self)\n\n }\n\n\n\n #[allow(clippy::too_many_arguments)]\n\n /// Delegate target with name as a `DelegatedRole` of the `Targets` in `targets_editor`\n\n /// This should be used if a role needs to be created by a user with `snapshot.json`,\n\n /// `timestamp.json`, and the new role's keys.\n\n pub fn delegate_role(\n\n &mut self,\n\n name: &str,\n\n key_source: &[Box<dyn KeySource>],\n\n paths: PathSet,\n\n threshold: NonZeroU64,\n\n expiration: DateTime<Utc>,\n\n version: NonZeroU64,\n\n ) -> Result<&mut Self> {\n\n // Create the new targets using targets editor\n\n let mut new_targets_editor = TargetsEditor::new(name);\n\n // Set the version and expiration\n", "file_path": "tough/src/editor/mod.rs", "rank": 9, "score": 44282.349004327145 }, { "content": "\n\n /// Determines when metadata should be considered expired and no longer trusted by clients.\n\n pub expires: DateTime<Utc>,\n\n\n\n /// The KEYID must be correct for the specified KEY. Clients MUST calculate each KEYID to verify\n\n /// this is correct for the associated key. Clients MUST ensure that for any KEYID represented\n\n /// in this key list and in other files, only one unique key has that KEYID.\n\n #[serde(deserialize_with = \"de::deserialize_keys\")]\n\n pub keys: HashMap<Decoded<Hex>, Key>,\n\n\n\n /// A list of roles, the keys associated with each role, and the threshold of signatures used\n\n /// for each role.\n\n pub roles: HashMap<RoleType, RoleKeys>,\n\n\n\n /// Extra arguments found during deserialization.\n\n ///\n\n /// We must store these to correctly verify signatures for this object.\n\n ///\n\n /// If you're instantiating this struct, you should make this `HashMap::empty()`.\n\n #[serde(flatten)]\n", "file_path": "tough/src/schema/mod.rs", "rank": 10, "score": 44281.09849022079 }, { "content": "/// `RepositoryEditor` contains the various bits of data needed to construct\n\n/// or edit a TUF repository.\n\n///\n\n/// A new repository may be started using the `new()` method.\n\n///\n\n/// An existing `tough::Repository` may be loaded and edited using the\n\n/// `from_repo()` method. When a repo is loaded in this way, versions and\n\n/// expirations are discarded. It is good practice to update these whenever\n\n/// a repo is changed.\n\n///\n\n/// Targets, versions, and expirations may be added to their respective roles\n\n/// via the provided \"setter\" methods. The final step in the process is the\n\n/// `sign()` method, which takes a given set of signing keys, builds each of\n\n/// the roles using the data provided, and signs the roles. This results in a\n\n/// `SignedRepository` which can be used to write the repo to disk.\n\n///\n\n/// The following should only be used in a repository that utilizes delegated targets\n\n/// `RepositoryEditor` uses a modal design to edit `Targets`. `TargetsEditor`\n\n/// is used to perform all actions on a specified `Targets`. To change the\n\n/// `Targets` being used call `change_delegated_targets()` to create a new `TargetsEditor`\n", "file_path": "tough/src/editor/mod.rs", "rank": 11, "score": 44280.3621665098 }, { "content": " /// If you're instantiating this struct, you should make this `HashMap::empty()`.\n\n #[serde(flatten)]\n\n pub _extra: HashMap<String, Value>,\n\n}\n\n\n\nimpl Target {\n\n /// Given a path, returns a Target struct\n\n pub fn from_path<P>(path: P) -> Result<Target>\n\n where\n\n P: AsRef<Path>,\n\n {\n\n // Ensure the given path is a file\n\n let path = path.as_ref();\n\n if !path.is_file() {\n\n return error::TargetNotAFileSnafu { path }.fail();\n\n }\n\n\n\n // Get the sha256 and length of the target\n\n let mut file = File::open(path).context(error::FileOpenSnafu { path })?;\n\n let mut digest = Context::new(&SHA256);\n", "file_path": "tough/src/schema/mod.rs", "rank": 12, "score": 44280.14594628418 }, { "content": " self.targets_editor_mut()?.remove_target(name);\n\n\n\n Ok(self)\n\n }\n\n\n\n /// Add a target to the repository using its path\n\n ///\n\n /// Note: This function builds a `Target` synchronously;\n\n /// no multithreading or parallelism is used. If you have a large number\n\n /// of targets to add, and require advanced performance, you may want to\n\n /// construct `Target`s directly in parallel and use `add_target()`.\n\n pub fn add_target_path<P>(&mut self, target_path: P) -> Result<&mut Self>\n\n where\n\n P: AsRef<Path>,\n\n {\n\n let (target_name, target) = RepositoryEditor::build_target(target_path)?;\n\n self.add_target(target_name, target)?;\n\n Ok(self)\n\n }\n\n\n", "file_path": "tough/src/editor/mod.rs", "rank": 13, "score": 44279.73234767735 }, { "content": " #[serde(deserialize_with = \"de::extra_skip_type\")]\n\n pub _extra: HashMap<String, Value>,\n\n}\n\n\n\n/// Represents the key IDs used for a role and the threshold of signatures required to validate it.\n\n/// TUF 4.3: A ROLE is one of \"root\", \"snapshot\", \"targets\", \"timestamp\", or \"mirrors\". A role for\n\n/// each of \"root\", \"snapshot\", \"timestamp\", and \"targets\" MUST be specified in the key list.\n\n/// The role of \"mirror\" is optional. If not specified, the mirror list will not need to be signed\n\n/// if mirror lists are being used. The THRESHOLD for a role is an integer of the number of keys of\n\n/// that role whose signatures are required in order to consider a file as being properly signed by\n\n/// that role.\n\n#[derive(Debug, Clone, Deserialize, Serialize, PartialEq)]\n\npub struct RoleKeys {\n\n /// The key IDs used for the role.\n\n pub keyids: Vec<Decoded<Hex>>,\n\n\n\n /// The threshold of signatures required to validate the role.\n\n pub threshold: NonZeroU64,\n\n\n\n /// Extra arguments found during deserialization.\n", "file_path": "tough/src/schema/mod.rs", "rank": 14, "score": 44279.369383047575 }, { "content": "\n\n /// Set the `Snapshot` expiration\n\n pub fn snapshot_expires(&mut self, snapshot_expires: DateTime<Utc>) -> &mut Self {\n\n self.snapshot_expires = Some(snapshot_expires);\n\n self\n\n }\n\n\n\n /// Set the `Targets` version\n\n pub fn targets_version(&mut self, targets_version: NonZeroU64) -> Result<&mut Self> {\n\n self.targets_editor_mut()?.version(targets_version);\n\n Ok(self)\n\n }\n\n\n\n /// Set the `Targets` expiration\n\n pub fn targets_expires(&mut self, targets_expires: DateTime<Utc>) -> Result<&mut Self> {\n\n self.targets_editor_mut()?.expires(targets_expires);\n\n Ok(self)\n\n }\n\n\n\n /// Set the `Timestamp` version\n", "file_path": "tough/src/editor/mod.rs", "rank": 15, "score": 44279.339409002176 }, { "content": " .context(error::DelegateMissingSnafu {\n\n name: role.to_string(),\n\n })?\n\n .clone();\n\n (KeyHolder::Delegations(parent), targets.signed)\n\n };\n\n self.targets_editor = Some(TargetsEditor::from_targets(role, targets, key_holder));\n\n\n\n Ok(self)\n\n }\n\n\n\n #[allow(clippy::too_many_lines)]\n\n /// Updates the metadata for the `Targets` role named `name`\n\n /// This method is used to load in a `Targets` metadata file located at\n\n /// `metadata_url` and update the repository's metadata for the role\n\n /// This method uses the result of `SignedDelegatedTargets::write()`\n\n /// Clears the current `targets_editor`\n\n pub fn update_delegated_targets(\n\n &mut self,\n\n name: &str,\n", "file_path": "tough/src/editor/mod.rs", "rank": 16, "score": 44279.20118289981 }, { "content": " name: name.to_string(),\n\n })?\n\n .targets = Some(role);\n\n }\n\n self.targets_editor = None;\n\n Ok(self)\n\n }\n\n\n\n /// Adds a role to the targets currently in `targets_editor`\n\n /// using a metadata file located at `metadata_url`/`name`.json\n\n /// `add_role()` uses `TargetsEditor::add_role()` to add a role from an existing metadata file.\n\n pub fn add_role(\n\n &mut self,\n\n name: &str,\n\n metadata_url: &str,\n\n paths: PathSet,\n\n threshold: NonZeroU64,\n\n keys: Option<HashMap<Decoded<Hex>, Key>>,\n\n ) -> Result<&mut Self> {\n\n let limits = self.limits.context(error::MissingLimitsSnafu)?;\n", "file_path": "tough/src/editor/mod.rs", "rank": 17, "score": 44279.17206201885 }, { "content": " serializer.serialize_str(self.value().as_ref())\n\n }\n\n}\n\n\n\nimpl<'de> Deserialize<'de> for PathPattern {\n\n fn deserialize<D>(deserializer: D) -> std::result::Result<Self, D::Error>\n\n where\n\n D: Deserializer<'de>,\n\n {\n\n let s = <String>::deserialize(deserializer)?;\n\n PathPattern::new(s).map_err(|e| D::Error::custom(format!(\"{}\", e)))\n\n }\n\n}\n\n\n\n/// The first characters found in the string representation of a sha256 digest. This can be used for\n\n/// randomly sharding a repository. See [`PathSet::PathHashDigest`] for the description of how this\n\n/// is used.\n\n#[derive(Clone, Debug, Eq, PartialEq, Ord, PartialOrd, Hash, Serialize, Deserialize)]\n\npub struct PathHashPrefix(String);\n\n\n", "file_path": "tough/src/schema/mod.rs", "rank": 18, "score": 44279.10089289374 }, { "content": "pub enum RoleType {\n\n /// The root role delegates trust to specific keys trusted for all other top-level roles used in\n\n /// the system.\n\n Root,\n\n /// The snapshot role signs a metadata file that provides information about the latest version\n\n /// of all targets metadata on the repository (the top-level targets role and all delegated\n\n /// roles).\n\n Snapshot,\n\n /// The targets role's signature indicates which target files are trusted by clients.\n\n Targets,\n\n /// The timestamp role is used to prevent an adversary from replaying an out-of-date signed\n\n /// metadata file whose signature has not yet expired.\n\n Timestamp,\n\n /// A delegated targets role\n\n DelegatedTargets,\n\n}\n\n\n\nderive_display_from_serialize!(RoleType);\n\nderive_fromstr_from_deserialize!(RoleType);\n\n\n", "file_path": "tough/src/schema/mod.rs", "rank": 19, "score": 44279.08693187073 }, { "content": " /// separator and does not start with a directory separator, akin to TARGETSPATH.\n\n #[serde(rename = \"paths\")]\n\n Paths(Vec<PathPattern>),\n\n\n\n /// The \"path_hash_prefixes\" list is used to succinctly describe a set of target paths.\n\n /// Specifically, each HEX_DIGEST in \"path_hash_prefixes\" describes a set of target paths;\n\n /// therefore, \"path_hash_prefixes\" is the union over each prefix of its set of target paths.\n\n /// The target paths must meet this condition: each target path, when hashed with the SHA-256\n\n /// hash function to produce a 64-byte hexadecimal digest (HEX_DIGEST), must share the same\n\n /// prefix as one of the prefixes in \"path_hash_prefixes\". This is useful to split a large\n\n /// number of targets into separate bins identified by consistent hashing.\n\n #[serde(rename = \"path_hash_prefixes\")]\n\n PathHashPrefixes(Vec<PathHashPrefix>),\n\n}\n\n\n\n/// A glob-like path pattern for matching delegated targets, e.g. `foo/bar/*`.\n\n///\n\n/// `PATHPATTERN` supports the Unix shell pattern matching convention for paths\n\n/// ([glob](https://man7.org/linux/man-pages/man7/glob.7.html)bing pathnames). Its format may either\n\n/// indicate a path to a single file, or to multiple files with the use of shell-style wildcards\n", "file_path": "tough/src/schema/mod.rs", "rank": 20, "score": 44279.03731853335 }, { "content": " const TYPE: RoleType = RoleType::Snapshot;\n\n\n\n fn expires(&self) -> DateTime<Utc> {\n\n self.expires\n\n }\n\n\n\n fn version(&self) -> NonZeroU64 {\n\n self.version\n\n }\n\n\n\n fn filename(&self, consistent_snapshot: bool) -> String {\n\n if consistent_snapshot {\n\n format!(\"{}.snapshot.json\", self.version())\n\n } else {\n\n \"snapshot.json\".to_string()\n\n }\n\n }\n\n}\n\n\n\n// =^..^= =^..^= =^..^= =^..^= =^..^= =^..^= =^..^= =^..^= =^..^= =^..^= =^..^=\n", "file_path": "tough/src/schema/mod.rs", "rank": 21, "score": 44278.97399559509 }, { "content": " delegated_targets\n\n }\n\n\n\n /// Link all current targets to `new_targets` metadata, returns a list of new `Targets` not included in the original `Targets`' delegated roles\n\n /// This is used to insert a set of updated `Targets` metadata without reloading the rest of the chain.\n\n pub fn update_targets(&self, new_targets: &mut Signed<Targets>) -> Vec<String> {\n\n let mut needed_roles = Vec::new();\n\n // Copy existing targets into proper places of new_targets\n\n if let Some(delegations) = &mut new_targets.signed.delegations {\n\n for mut role in &mut delegations.roles {\n\n // Check to see if `role.name` has already been loaded\n\n if let Ok(targets) = self.delegated_targets(&role.name) {\n\n // If it has been loaded, use it as the targets for the role\n\n role.targets = Some(targets.clone());\n\n } else {\n\n // If not make sure we keep track that it needs to be loaded\n\n needed_roles.push(role.name.clone());\n\n }\n\n }\n\n }\n", "file_path": "tough/src/schema/mod.rs", "rank": 22, "score": 44278.875095699404 }, { "content": " meta: HashMap::new(),\n\n _extra: HashMap::new(),\n\n }\n\n }\n\n}\n\n\n\nimpl Role for Timestamp {\n\n const TYPE: RoleType = RoleType::Timestamp;\n\n\n\n fn expires(&self) -> DateTime<Utc> {\n\n self.expires\n\n }\n\n\n\n fn version(&self) -> NonZeroU64 {\n\n self.version\n\n }\n\n\n\n fn filename(&self, _consistent_snapshot: bool) -> String {\n\n \"timestamp.json\".to_string()\n\n }\n\n}\n\n\n", "file_path": "tough/src/schema/mod.rs", "rank": 23, "score": 44278.84926837016 }, { "content": "\n\nimpl Role for DelegatedTargets {\n\n const TYPE: RoleType = RoleType::DelegatedTargets;\n\n\n\n fn expires(&self) -> DateTime<Utc> {\n\n self.targets.expires\n\n }\n\n\n\n fn version(&self) -> NonZeroU64 {\n\n self.targets.version\n\n }\n\n\n\n fn filename(&self, consistent_snapshot: bool) -> String {\n\n if consistent_snapshot {\n\n format!(\"{}.{}.json\", self.version(), encode_filename(&self.name))\n\n } else {\n\n format!(\"{}.json\", encode_filename(&self.name))\n\n }\n\n }\n\n\n", "file_path": "tough/src/schema/mod.rs", "rank": 24, "score": 44278.70894387141 }, { "content": " })\n\n }\n\n}\n\n\n\nimpl Targets {\n\n /// Create a new `Targets` object.\n\n pub fn new(spec_version: String, version: NonZeroU64, expires: DateTime<Utc>) -> Self {\n\n Targets {\n\n spec_version,\n\n version,\n\n expires,\n\n targets: HashMap::new(),\n\n _extra: HashMap::new(),\n\n delegations: Some(Delegations::new()),\n\n }\n\n }\n\n\n\n /// Given a target url, returns a reference to the Target struct or error if the target is\n\n /// unreachable.\n\n ///\n", "file_path": "tough/src/schema/mod.rs", "rank": 25, "score": 44278.66426986256 }, { "content": " terminating: false,\n\n targets: Some(Signed {\n\n signed: Targets {\n\n spec_version: \"\".to_string(),\n\n version: NonZeroU64::new(1).unwrap(),\n\n expires: Utc::now(),\n\n targets: hashmap! {\n\n TargetName::new(\"c.txt\").unwrap() => nothing.clone(),\n\n },\n\n delegations: None,\n\n _extra: Default::default(),\n\n },\n\n signatures: vec![],\n\n }),\n\n };\n\n let b_delegations = Delegations {\n\n keys: Default::default(),\n\n roles: vec![c_role],\n\n };\n\n let b_role = DelegatedRole {\n", "file_path": "tough/src/schema/mod.rs", "rank": 26, "score": 44278.62058794838 }, { "content": " let mut buf = [0; 8 * 1024];\n\n let mut length = 0;\n\n loop {\n\n match file.read(&mut buf).context(error::FileReadSnafu { path })? {\n\n 0 => break,\n\n n => {\n\n digest.update(&buf[..n]);\n\n length += n as u64;\n\n }\n\n }\n\n }\n\n\n\n Ok(Target {\n\n length,\n\n hashes: Hashes {\n\n sha256: Decoded::from(digest.finish().as_ref().to_vec()),\n\n _extra: HashMap::new(),\n\n },\n\n custom: HashMap::new(),\n\n _extra: HashMap::new(),\n", "file_path": "tough/src/schema/mod.rs", "rank": 27, "score": 44278.56333474743 }, { "content": "}\n\n\n\nimpl Signed<Targets> {\n\n /// Use a string and a `Signed<Targets>` to create a `Signed<DelegatedTargets>`\n\n pub fn delegated_targets(self, name: &str) -> Signed<DelegatedTargets> {\n\n Signed {\n\n signed: DelegatedTargets {\n\n name: name.to_string(),\n\n targets: self.signed,\n\n },\n\n signatures: self.signatures,\n\n }\n\n }\n\n}\n\n\n\n/// Delegations are found in a `targets.json` file.\n\n/// TUF 4.5: DELEGATIONS is an object whose format is the following:\n\n/// ```text\n\n/// { \"keys\" : {\n\n/// KEYID : KEY,\n", "file_path": "tough/src/schema/mod.rs", "rank": 28, "score": 44278.53746689401 }, { "content": " /// Given an object/key that impls Sign, return the corresponding\n\n /// key ID from Root\n\n pub fn key_id(&self, key_pair: &dyn Sign) -> Option<Decoded<Hex>> {\n\n for (key_id, key) in &self.keys {\n\n if key_pair.tuf_key() == *key {\n\n return Some(key_id.clone());\n\n }\n\n }\n\n None\n\n }\n\n}\n\n\n\nimpl Role for Root {\n\n const TYPE: RoleType = RoleType::Root;\n\n\n\n fn expires(&self) -> DateTime<Utc> {\n\n self.expires\n\n }\n\n\n\n fn version(&self) -> NonZeroU64 {\n", "file_path": "tough/src/schema/mod.rs", "rank": 29, "score": 44278.536071084694 }, { "content": " pub terminating: bool,\n\n\n\n /// The targets that are signed by this role.\n\n #[serde(skip)]\n\n pub targets: Option<Signed<Targets>>,\n\n}\n\n\n\n/// Specifies the target paths that a delegated role controls.\n\n#[derive(Debug, Clone, Deserialize, Serialize, PartialEq)]\n\npub enum PathSet {\n\n /// The \"paths\" list describes paths that the role is trusted to provide. Clients MUST check\n\n /// that a target is in one of the trusted paths of all roles in a delegation chain, not just in\n\n /// a trusted path of the role that describes the target file. PATHPATTERN can include shell-\n\n /// style wildcards and supports the Unix filename pattern matching convention. Its format may\n\n /// either indicate a path to a single file, or to multiple paths with the use of shell-style\n\n /// wildcards. For example, the path pattern \"targets/*.tgz\" would match file paths\n\n /// \"targets/foo.tgz\" and \"targets/bar.tgz\", but not \"targets/foo.txt\". Likewise, path pattern\n\n /// \"foo-version-?.tgz\" matches \"foo-version-2.tgz\" and \"foo-version-a.tgz\", but not\n\n /// \"foo-version-alpha.tgz\". To avoid surprising behavior when matching targets with\n\n /// PATHPATTERN, it is RECOMMENDED that PATHPATTERN uses the forward slash (/) as directory\n", "file_path": "tough/src/schema/mod.rs", "rank": 30, "score": 44278.48693825738 }, { "content": " keys: Default::default(),\n\n roles: vec![b_role],\n\n };\n\n let a = Targets {\n\n spec_version: \"\".to_string(),\n\n version: NonZeroU64::new(1).unwrap(),\n\n expires: Utc::now(),\n\n targets: hashmap! {\n\n TargetName::new(\"a.txt\").unwrap() => nothing.clone(),\n\n },\n\n delegations: Some(a_delegations),\n\n _extra: Default::default(),\n\n };\n\n\n\n // Assert that targets_iter is recursive and thus has a.txt, b.txt and c.txt\n\n assert!(a\n\n .targets_iter()\n\n .map(|(key, _)| key)\n\n .find(|&item| item.raw() == \"a.txt\")\n\n .is_some());\n", "file_path": "tough/src/schema/mod.rs", "rank": 31, "score": 44278.47505471563 }, { "content": " /// We must store these to correctly verify signatures for this object.\n\n ///\n\n /// If you're instantiating this struct, you should make this `HashMap::empty()`.\n\n #[serde(flatten)]\n\n pub _extra: HashMap<String, Value>,\n\n}\n\n\n\nimpl Snapshot {\n\n /// Create a new `Snapshot` object.\n\n pub fn new(spec_version: String, version: NonZeroU64, expires: DateTime<Utc>) -> Self {\n\n Snapshot {\n\n spec_version,\n\n version,\n\n expires,\n\n meta: HashMap::new(),\n\n _extra: HashMap::new(),\n\n }\n\n }\n\n}\n\nimpl Role for Snapshot {\n", "file_path": "tough/src/schema/mod.rs", "rank": 32, "score": 44278.45514839023 }, { "content": " name: \"b-role\".to_string(),\n\n keyids: vec![],\n\n threshold: NonZeroU64::new(1).unwrap(),\n\n paths: PathSet::Paths(vec![PathPattern::new(\"*\").unwrap()]),\n\n terminating: false,\n\n targets: Some(Signed {\n\n signed: Targets {\n\n spec_version: \"\".to_string(),\n\n version: NonZeroU64::new(1).unwrap(),\n\n expires: Utc::now(),\n\n targets: hashmap! {\n\n TargetName::new(\"b.txt\").unwrap() => nothing.clone(),\n\n },\n\n delegations: Some(b_delegations),\n\n _extra: Default::default(),\n\n },\n\n signatures: vec![],\n\n }),\n\n };\n\n let a_delegations = Delegations {\n", "file_path": "tough/src/schema/mod.rs", "rank": 33, "score": 44278.39667928836 }, { "content": "\n\n needed_roles\n\n }\n\n\n\n /// Calls `find_target` on each target (recursively provided by `targets_iter`). This\n\n /// proves that the target is either owned by us, or correctly matches through some hierarchy of\n\n /// [`PathSets`] below us. When called on the top level [`Targets`] of a repository, this proves\n\n /// that the ownership of each target is valid.\n\n pub(crate) fn validate(&self) -> Result<()> {\n\n for (target_name, _) in self.targets_iter() {\n\n self.find_target(target_name)?;\n\n }\n\n Ok(())\n\n }\n\n}\n\n\n\nimpl Role for Targets {\n\n const TYPE: RoleType = RoleType::Targets;\n\n\n\n fn expires(&self) -> DateTime<Utc> {\n", "file_path": "tough/src/schema/mod.rs", "rank": 34, "score": 44278.39667928836 }, { "content": " /// An integer that is greater than 0. Clients MUST NOT replace a metadata file with a version\n\n /// number less than the one currently trusted.\n\n pub version: NonZeroU64,\n\n\n\n /// Extra arguments found during deserialization.\n\n ///\n\n /// We must store these to correctly verify signatures for this object.\n\n ///\n\n /// If you're instantiating this struct, you should make this `HashMap::empty()`.\n\n #[serde(flatten)]\n\n pub _extra: HashMap<String, Value>,\n\n}\n\n\n\nimpl Timestamp {\n\n /// Creates a new `Timestamp` object.\n\n pub fn new(spec_version: String, version: NonZeroU64, expires: DateTime<Utc>) -> Self {\n\n Timestamp {\n\n spec_version,\n\n version,\n\n expires,\n", "file_path": "tough/src/schema/mod.rs", "rank": 35, "score": 44278.24937505292 }, { "content": " pub roles: Vec<DelegatedRole>,\n\n}\n\n\n\n/// Each role delegated in a targets file is considered a delegated role\n\n#[derive(Debug, Clone, Deserialize, Serialize, PartialEq)]\n\npub struct DelegatedRole {\n\n /// The name of the delegated role. For example, \"projects\".\n\n pub name: String,\n\n\n\n /// The key IDs used by this role.\n\n pub keyids: Vec<Decoded<Hex>>,\n\n\n\n /// The threshold of signatures required to validate the role.\n\n pub threshold: NonZeroU64,\n\n\n\n /// The paths governed by this role.\n\n #[serde(flatten)]\n\n pub paths: PathSet,\n\n\n\n /// Indicates whether subsequent delegations should be considered.\n", "file_path": "tough/src/schema/mod.rs", "rank": 36, "score": 44278.17235175489 }, { "content": " let target_path = target_path.as_ref();\n\n\n\n // Get the file name as a string\n\n let target_name = TargetName::new(\n\n target_path\n\n .file_name()\n\n .context(error::NoFileNameSnafu { path: target_path })?\n\n .to_str()\n\n .context(error::PathUtf8Snafu { path: target_path })?,\n\n )?;\n\n\n\n // Build a Target from the path given. If it is not a file, this will fail\n\n let target = Target::from_path(target_path)\n\n .context(error::TargetFromPathSnafu { path: target_path })?;\n\n\n\n Ok((target_name, target))\n\n }\n\n\n\n /// Remove all targets from this repo\n\n pub fn clear_targets(&mut self) -> Result<&mut Self> {\n", "file_path": "tough/src/editor/mod.rs", "rank": 37, "score": 44278.11265186676 }, { "content": " .context(error::FileParseJsonSnafu { path: root_path })?;\n\n\n\n // Quick check that root is signed by enough key IDs\n\n for (roletype, rolekeys) in &root.signed.roles {\n\n if rolekeys.threshold.get() > rolekeys.keyids.len() as u64 {\n\n return Err(error::Error::UnstableRoot {\n\n role: *roletype,\n\n threshold: rolekeys.threshold.get(),\n\n actual: rolekeys.keyids.len(),\n\n });\n\n }\n\n }\n\n\n\n let mut digest = [0; SHA256_OUTPUT_LEN];\n\n digest.copy_from_slice(ring::digest::digest(&SHA256, &root_buf).as_ref());\n\n\n\n let signed_root = SignedRole {\n\n signed: root,\n\n buffer: root_buf,\n\n sha256: digest,\n", "file_path": "tough/src/editor/mod.rs", "rank": 38, "score": 44278.11265186676 }, { "content": " pub spec_version: String,\n\n\n\n /// An integer that is greater than 0. Clients MUST NOT replace a metadata file with a version\n\n /// number less than the one currently trusted.\n\n pub version: NonZeroU64,\n\n\n\n /// Determines when metadata should be considered expired and no longer trusted by clients.\n\n pub expires: DateTime<Utc>,\n\n\n\n /// Each key of the TARGETS object is a TARGETPATH. A TARGETPATH is a path to a file that is\n\n /// relative to a mirror's base URL of targets.\n\n pub targets: HashMap<TargetName, Target>,\n\n\n\n /// Delegations describes subsets of the targets for which responsibility is delegated to\n\n /// another role.\n\n #[serde(skip_serializing_if = \"Option::is_none\")]\n\n pub delegations: Option<Delegations>,\n\n\n\n /// Extra arguments found during deserialization.\n\n ///\n", "file_path": "tough/src/schema/mod.rs", "rank": 39, "score": 44278.09719418185 }, { "content": " self.signed_targets\n\n .as_mut()\n\n .context(error::NoTargetsSnafu)?\n\n .signed\n\n .delegated_role_mut(&name)\n\n .context(error::DelegateMissingSnafu { name })?\n\n .targets = Some(targets);\n\n }\n\n }\n\n self.targets_editor = None;\n\n Ok(self)\n\n }\n\n\n\n /// Changes the targets refered to in `targets_editor` to role\n\n /// All `Targets` related calls will now be called on the `Targets` role named `role`\n\n /// Throws error if the `targets_editor` was not cleared using `sign_targets_editor()`\n\n /// Clones the desired targets from `signed_targets` and creates a `TargetsEditor` for it\n\n pub fn change_delegated_targets(&mut self, role: &str) -> Result<&mut Self> {\n\n if self.targets_editor.is_some() {\n\n return Err(error::Error::TargetsEditorSome);\n", "file_path": "tough/src/editor/mod.rs", "rank": 40, "score": 44277.991293881314 }, { "content": "\n\n /// An integer that is greater than 0. Clients MUST NOT replace a metadata file with a version\n\n /// number less than the one currently trusted.\n\n pub version: NonZeroU64,\n\n\n\n /// Determines when metadata should be considered expired and no longer trusted by clients.\n\n pub expires: DateTime<Utc>,\n\n\n\n /// A list of what the TUF spec calls 'METAFILES' (`SnapshotMeta` objects). The TUF spec\n\n /// describes the hash key in 4.4: METAPATH is the file path of the metadata on the repository\n\n /// relative to the metadata base URL. For snapshot.json, these are top-level targets metadata\n\n /// and delegated targets metadata.\n\n pub meta: HashMap<String, SnapshotMeta>,\n\n\n\n /// Extra arguments found during deserialization.\n\n ///\n\n /// We must store these to correctly verify signatures for this object.\n\n ///\n\n /// If you're instantiating this struct, you should make this `HashMap::empty()`.\n\n #[serde(flatten)]\n", "file_path": "tough/src/schema/mod.rs", "rank": 41, "score": 44277.942833410576 }, { "content": " pub fn timestamp_version(&mut self, timestamp_version: NonZeroU64) -> &mut Self {\n\n self.timestamp_version = Some(timestamp_version);\n\n self\n\n }\n\n\n\n /// Set the `Timestamp` expiration\n\n pub fn timestamp_expires(&mut self, timestamp_expires: DateTime<Utc>) -> &mut Self {\n\n self.timestamp_expires = Some(timestamp_expires);\n\n self\n\n }\n\n\n\n /// Takes the current Targets from `targets_editor` and inserts the role to its proper place in `signed_targets`\n\n /// Sets `targets_editor` to None\n\n /// Must be called before `change_delegated_targets()`\n\n pub fn sign_targets_editor(&mut self, keys: &[Box<dyn KeySource>]) -> Result<&mut Self> {\n\n if let Some(targets_editor) = self.targets_editor.as_mut() {\n\n let (name, targets) = targets_editor.create_signed(keys)?.targets();\n\n if name == \"targets\" {\n\n self.signed_targets = Some(targets);\n\n } else {\n", "file_path": "tough/src/editor/mod.rs", "rank": 42, "score": 44277.92817223712 }, { "content": " pub length: u64,\n\n\n\n /// HASHES is a dictionary that specifies one or more hashes, including the cryptographic hash\n\n /// function. For example: `{ \"sha256\": HASH, ... }`. HASH is the hexdigest of the cryptographic\n\n /// function computed on the target file.\n\n pub hashes: Hashes,\n\n\n\n /// If defined, the elements and values of \"custom\" will be made available to the client\n\n /// application. The information in \"custom\" is opaque to the framework and can include version\n\n /// numbers, dependencies, requirements, and any other data that the application wants to\n\n /// include to describe the file at TARGETPATH. The application may use this information to\n\n /// guide download decisions.\n\n #[serde(default)]\n\n #[serde(skip_serializing_if = \"HashMap::is_empty\")]\n\n pub custom: HashMap<String, Value>,\n\n\n\n /// Extra arguments found during deserialization.\n\n ///\n\n /// We must store these to correctly verify signatures for this object.\n\n ///\n", "file_path": "tough/src/schema/mod.rs", "rank": 43, "score": 44277.885671459706 }, { "content": "/// unaware of interference with obtaining updates.\n\n#[derive(Debug, Clone, Deserialize, Serialize, PartialEq)]\n\n#[serde(tag = \"_type\")]\n\n#[serde(rename = \"timestamp\")]\n\npub struct Timestamp {\n\n /// A string that contains the version number of the TUF specification. Its format follows the\n\n /// Semantic Versioning 2.0.0 (semver) specification.\n\n pub spec_version: String,\n\n\n\n /// An integer that is greater than 0. Clients MUST NOT replace a metadata file with a version\n\n /// number less than the one currently trusted.\n\n pub version: NonZeroU64,\n\n\n\n /// Determines when metadata should be considered expired and no longer trusted by clients.\n\n pub expires: DateTime<Utc>,\n\n\n\n /// METAFILES is the same as described for the snapshot.json file. In the case of the\n\n /// timestamp.json file, this MUST only include a description of the snapshot.json file.\n\n pub meta: HashMap<String, TimestampMeta>,\n\n\n", "file_path": "tough/src/schema/mod.rs", "rank": 44, "score": 44277.88498078468 }, { "content": " /// The signed top level targets, will be None if no top level targets have been signed\n\n signed_targets: Option<Signed<Targets>>,\n\n\n\n transport: Option<Box<dyn Transport>>,\n\n limits: Option<Limits>,\n\n}\n\n\n\nimpl RepositoryEditor {\n\n /// Create a new, bare `RepositoryEditor`\n\n pub fn new<P>(root_path: P) -> Result<Self>\n\n where\n\n P: AsRef<Path>,\n\n {\n\n // Read and parse the root.json. Without a good root, it doesn't\n\n // make sense to continue\n\n let root_path = root_path.as_ref();\n\n let root_buf =\n\n std::fs::read(root_path).context(error::FileReadSnafu { path: root_path })?;\n\n let root_buf_len = root_buf.len() as u64;\n\n let root = serde_json::from_slice::<Signed<Root>>(&root_buf)\n", "file_path": "tough/src/editor/mod.rs", "rank": 45, "score": 44277.83855342138 }, { "content": "/// (`*` or `?`). To avoid surprising behavior when matching targets with `PATHPATTERN` it is\n\n/// RECOMMENDED that `PATHPATTERN` uses the forward slash (`/`) as directory separator and does\n\n/// not start with a directory separator, as is also recommended for `TARGETPATH`. A path\n\n/// separator in a path SHOULD NOT be matched by a wildcard in the `PATHPATTERN`.\n\n///\n\n/// Some example `PATHPATTERN`s and expected matches:\n\n/// * a `PATHPATTERN` of `\"targets/*.tgz\"` would match file paths `\"targets/foo.tgz\"` and\n\n/// `\"targets/bar.tgz\"`, but not `\"targets/foo.txt\"`.\n\n/// * a `PATHPATTERN` of `\"foo-version-?.tgz\"` matches `\"foo-version-2.tgz\"` and\n\n/// `\"foo-version-a.tgz\"`, but not `\"foo-version-alpha.tgz\"`.\n\n/// * a `PATHPATTERN` of `\"*.tgz\"` would match `\"foo.tgz\"` and `\"bar.tgz\"`,\n\n/// but not `\"targets/foo.tgz\"`\n\n/// * a `PATHPATTERN` of `\"foo.tgz\"` would match only `\"foo.tgz\"`\n\n#[derive(Clone, Debug)]\n\npub struct PathPattern {\n\n value: String,\n\n glob: GlobMatcher,\n\n}\n\n\n\nimpl PathPattern {\n", "file_path": "tough/src/schema/mod.rs", "rank": 46, "score": 44277.759522965316 }, { "content": "/// }\n\n/// },\n\n/// ```\n\n#[derive(Debug, Clone, Deserialize, Serialize, PartialEq)]\n\npub struct SnapshotMeta {\n\n /// LENGTH is the integer length in bytes of the metadata file at METAPATH. It is OPTIONAL and\n\n /// can be omitted to reduce the snapshot metadata file size. In that case the client MUST use a\n\n /// custom download limit for the listed metadata.\n\n #[serde(skip_serializing_if = \"Option::is_none\")]\n\n pub length: Option<u64>,\n\n\n\n /// HASHES is a dictionary that specifies one or more hashes of the metadata file at METAPATH,\n\n /// including their cryptographic hash function. For example: `{ \"sha256\": HASH, ... }`. HASHES\n\n /// is OPTIONAL and can be omitted to reduce the snapshot metadata file size. In that case the\n\n /// repository MUST guarantee that VERSION alone unambiguously identifies the metadata at\n\n /// METAPATH.\n\n #[serde(skip_serializing_if = \"Option::is_none\")]\n\n pub hashes: Option<Hashes>,\n\n\n\n /// An integer that is greater than 0. Clients MUST NOT replace a metadata file with a version\n", "file_path": "tough/src/schema/mod.rs", "rank": 47, "score": 44277.70663808753 }, { "content": " given: targets.signed.spec_version,\n\n supported: SPEC_VERSION\n\n }\n\n );\n\n // Save the existing targets\n\n self.signed_targets = Some(targets.clone());\n\n // Create a targets editor so that targets can be updated\n\n self.targets_editor = Some(TargetsEditor::from_targets(\n\n \"targets\",\n\n targets.signed,\n\n KeyHolder::Root(self.signed_root.signed.signed.clone()),\n\n ));\n\n Ok(self)\n\n }\n\n\n\n /// Add an existing `Snapshot` to the repository. Only the `_extra` data\n\n /// is preserved\n\n pub fn snapshot(&mut self, snapshot: Snapshot) -> Result<&mut Self> {\n\n ensure!(\n\n snapshot.spec_version == SPEC_VERSION,\n", "file_path": "tough/src/editor/mod.rs", "rank": 48, "score": 44274.730277923096 }, { "content": " ) -> Result<Snapshot> {\n\n let version = self.snapshot_version.context(error::MissingSnafu {\n\n field: \"snapshot version\",\n\n })?;\n\n let expires = self.snapshot_expires.context(error::MissingSnafu {\n\n field: \"snapshot expiration\",\n\n })?;\n\n let _extra = self.snapshot_extra.clone().unwrap_or_else(HashMap::new);\n\n\n\n let mut snapshot = Snapshot::new(SPEC_VERSION.to_string(), version, expires);\n\n\n\n // Snapshot stores metadata about targets and root\n\n let targets_meta = Self::snapshot_meta(signed_targets);\n\n snapshot\n\n .meta\n\n .insert(\"targets.json\".to_owned(), targets_meta);\n\n\n\n if let Some(signed_delegated_targets) = signed_delegated_targets.as_ref() {\n\n for delegated_targets in &signed_delegated_targets.roles {\n\n let meta = Self::snapshot_meta(delegated_targets);\n", "file_path": "tough/src/editor/mod.rs", "rank": 49, "score": 44274.730277923096 }, { "content": " iter = Box::new(iter.chain(targets.signed.targets_iter()));\n\n }\n\n }\n\n }\n\n iter\n\n }\n\n\n\n /// Recursively clears all targets\n\n pub fn clear_targets(&mut self) {\n\n self.targets = HashMap::new();\n\n if let Some(delegations) = &mut self.delegations {\n\n for delegated_role in &mut delegations.roles {\n\n if let Some(targets) = &mut delegated_role.targets {\n\n targets.signed.clear_targets();\n\n }\n\n }\n\n }\n\n }\n\n\n\n /// Add a target to targets\n", "file_path": "tough/src/schema/mod.rs", "rank": 50, "score": 44274.730277923096 }, { "content": " self.expires\n\n }\n\n\n\n fn version(&self) -> NonZeroU64 {\n\n self.version\n\n }\n\n\n\n fn filename(&self, consistent_snapshot: bool) -> String {\n\n if consistent_snapshot {\n\n format!(\"{}.targets.json\", self.version())\n\n } else {\n\n \"targets.json\".to_string()\n\n }\n\n }\n\n}\n\n\n\n/// Wrapper for `Targets` so that a `Targets` role can be given a name\n\n#[derive(Debug, Clone, Deserialize, Serialize, PartialEq)]\n\npub struct DelegatedTargets {\n\n /// The name of the role\n", "file_path": "tough/src/schema/mod.rs", "rank": 51, "score": 44274.730277923096 }, { "content": "/// TUF 4.3: The root.json file is signed by the root role's keys. It indicates which keys are\n\n/// authorized for all top-level roles, including the root role itself. Revocation and replacement\n\n/// of top-level role keys, including for the root role, is done by changing the keys listed for the\n\n/// roles in this file.\n\n#[derive(Debug, Clone, Deserialize, Serialize, PartialEq)]\n\n#[serde(tag = \"_type\")]\n\n#[serde(rename = \"root\")]\n\npub struct Root {\n\n /// A string that contains the version number of the TUF specification. Its format follows the\n\n /// Semantic Versioning 2.0.0 (semver) specification.\n\n pub spec_version: String,\n\n\n\n /// A boolean indicating whether the repository supports consistent snapshots. When consistent\n\n /// snapshots is `true`, targets and certain metadata filenames are prefixed with either a\n\n /// a version number or digest.\n\n pub consistent_snapshot: bool,\n\n\n\n /// An integer that is greater than 0. Clients MUST NOT replace a metadata file with a version\n\n /// number less than the one currently trusted.\n\n pub version: NonZeroU64,\n", "file_path": "tough/src/schema/mod.rs", "rank": 52, "score": 44274.730277923096 }, { "content": " pub fn add_target(&mut self, name: TargetName, target: Target) {\n\n self.targets.insert(name, target);\n\n }\n\n\n\n /// Remove a target from targets\n\n pub fn remove_target(&mut self, name: &TargetName) -> Option<Target> {\n\n self.targets.remove(name)\n\n }\n\n\n\n /// Returns the `&Signed<Targets>` for `name`\n\n pub fn delegated_targets(&self, name: &str) -> Result<&Signed<Targets>> {\n\n self.delegated_role(name)?\n\n .targets\n\n .as_ref()\n\n .ok_or(error::Error::NoTargets)\n\n }\n\n\n\n /// Returns a mutable `Signed<Targets>` for `name`\n\n pub fn delegated_targets_mut(&mut self, name: &str) -> Result<&mut Signed<Targets>> {\n\n self.delegated_role_mut(name)?\n", "file_path": "tough/src/schema/mod.rs", "rank": 53, "score": 44274.730277923096 }, { "content": " ///\n\n /// We must store these to correctly verify signatures for this object.\n\n ///\n\n /// If you're instantiating this struct, you should make this `HashMap::empty()`.\n\n #[serde(flatten)]\n\n pub _extra: HashMap<String, Value>,\n\n}\n\n\n\nimpl Root {\n\n /// An iterator over the keys for a given role.\n\n pub fn keys(&self, role: RoleType) -> impl Iterator<Item = &Key> {\n\n KeysIter {\n\n keyids_iter: match self.roles.get(&role) {\n\n Some(role_keys) => role_keys.keyids.iter(),\n\n None => [].iter(),\n\n },\n\n keys: &self.keys,\n\n }\n\n }\n\n\n", "file_path": "tough/src/schema/mod.rs", "rank": 54, "score": 44274.730277923096 }, { "content": " Ok(self)\n\n }\n\n\n\n /// Returns a mutable reference to the targets editor if it exists\n\n fn targets_editor_mut(&mut self) -> Result<&mut TargetsEditor> {\n\n self.targets_editor.as_mut().ok_or(error::Error::NoTargets)\n\n }\n\n\n\n /// Add a `Target` to the repository\n\n pub fn add_target<T, E>(&mut self, name: T, target: Target) -> Result<&mut Self>\n\n where\n\n T: TryInto<TargetName, Error = E>,\n\n E: Display,\n\n {\n\n self.targets_editor_mut()?.add_target(name, target)?;\n\n Ok(self)\n\n }\n\n\n\n /// Remove a `Target` from the repository\n\n pub fn remove_target(&mut self, name: &TargetName) -> Result<&mut Self> {\n", "file_path": "tough/src/editor/mod.rs", "rank": 55, "score": 44274.730277923096 }, { "content": " let encoded_filename = format!(\"{}.json\", encoded_name);\n\n let role_url = metadata_base_url\n\n .join(&encoded_filename)\n\n .with_context(|_| error::JoinUrlEncodedSnafu {\n\n original: &name,\n\n encoded: encoded_name,\n\n filename: encoded_filename,\n\n url: metadata_base_url.clone(),\n\n })?;\n\n let reader = Box::new(fetch_max_size(\n\n transport.as_ref(),\n\n role_url,\n\n limits.max_targets_size,\n\n \"max targets limit\",\n\n )?);\n\n // Load new role metadata as Signed<Targets>\n\n let new_role: Signed<crate::schema::Targets> = serde_json::from_reader(reader)\n\n .context(error::ParseMetadataSnafu {\n\n role: RoleType::Targets,\n\n })?;\n", "file_path": "tough/src/editor/mod.rs", "rank": 56, "score": 44274.730277923096 }, { "content": " } else if let Ok(role) = role\n\n .targets\n\n .as_mut()\n\n .ok_or(error::Error::NoTargets)?\n\n .signed\n\n .delegated_role_mut(name)\n\n {\n\n return Ok(role);\n\n }\n\n }\n\n Err(error::Error::RoleNotFound {\n\n name: name.to_string(),\n\n })\n\n }\n\n\n\n ///Returns a vec of all rolenames\n\n pub fn role_names(&self) -> Vec<&String> {\n\n let mut roles = Vec::new();\n\n if let Some(delelegations) = &self.delegations {\n\n for role in &delelegations.roles {\n", "file_path": "tough/src/schema/mod.rs", "rank": 57, "score": 44274.730277923096 }, { "content": " }),\n\n length: Some(role.length),\n\n version: role.signed.signed.version(),\n\n _extra: HashMap::new(),\n\n }\n\n }\n\n\n\n /// Build the `Timestamp` struct\n\n fn build_timestamp(&self, signed_snapshot: &SignedRole<Snapshot>) -> Result<Timestamp> {\n\n let version = self.timestamp_version.context(error::MissingSnafu {\n\n field: \"timestamp version\",\n\n })?;\n\n let expires = self.timestamp_expires.context(error::MissingSnafu {\n\n field: \"timestamp expiration\",\n\n })?;\n\n let _extra = self.timestamp_extra.clone().unwrap_or_else(HashMap::new);\n\n let mut timestamp = Timestamp::new(SPEC_VERSION.to_string(), version, expires);\n\n\n\n // Timestamp stores metadata about snapshot\n\n let snapshot_meta = Self::timestamp_meta(signed_snapshot);\n", "file_path": "tough/src/editor/mod.rs", "rank": 58, "score": 44274.730277923096 }, { "content": " metadata_url: &str,\n\n ) -> Result<&mut Self> {\n\n let limits = self.limits.context(error::MissingLimitsSnafu)?;\n\n let transport = self\n\n .transport\n\n .as_ref()\n\n .context(error::MissingTransportSnafu)?;\n\n let targets = &mut self\n\n .signed_targets\n\n .as_mut()\n\n .context(error::NoTargetsSnafu)?\n\n .signed;\n\n let metadata_base_url = parse_url(metadata_url)?;\n\n // path to updated metadata\n\n let encoded_name = encode_filename(name);\n\n let encoded_filename = format!(\"{}.json\", encoded_name);\n\n let role_url = metadata_base_url\n\n .join(&encoded_filename)\n\n .with_context(|_| error::JoinUrlEncodedSnafu {\n\n original: name,\n", "file_path": "tough/src/editor/mod.rs", "rank": 59, "score": 44274.730277923096 }, { "content": " ///\n\n /// While `RepositoryEditor`s fields are all `Option`s, this step requires,\n\n /// at the very least, that the \"version\" and \"expiration\" field is set for\n\n /// each role; e.g. `targets_version`, `targets_expires`, etc.\n\n pub fn sign(mut self, keys: &[Box<dyn KeySource>]) -> Result<SignedRepository> {\n\n let rng = SystemRandom::new();\n\n let root = KeyHolder::Root(self.signed_root.signed.signed.clone());\n\n // Sign the targets editor if able to with the provided keys\n\n self.sign_targets_editor(keys)?;\n\n let targets = self.signed_targets.clone().context(error::NoTargetsSnafu)?;\n\n let delegated_targets = targets.signed.signed_delegated_targets();\n\n let signed_targets = SignedRole::from_signed(targets)?;\n\n\n\n let signed_delegated_targets = if delegated_targets.is_empty() {\n\n // If we don't have any delegated targets, there is no reason to create\n\n // a `SignedDelegatedTargets`\n\n None\n\n } else {\n\n // If we have delegated targets\n\n let mut roles = Vec::new();\n", "file_path": "tough/src/editor/mod.rs", "rank": 60, "score": 44274.730277923096 }, { "content": "impl PathHashPrefix {\n\n /// Create a new, valid `PathPattern`.\n\n pub fn new<S: Into<String>>(value: S) -> Result<Self> {\n\n // In case we choose to reject some of these in the future, we return a result. For now this\n\n // will always succeed.\n\n Ok(PathHashPrefix(value.into()))\n\n }\n\n\n\n /// Get the inner value of this `PathPattern` as a string.\n\n pub fn value(&self) -> &str {\n\n &self.0\n\n }\n\n\n\n fn matches_target_name(&self, target_name: &TargetName) -> bool {\n\n let target_name_digest =\n\n digest(&SHA256, target_name.resolved().as_bytes()).encode_hex::<String>();\n\n target_name_digest.starts_with(self.value())\n\n }\n\n}\n\n\n", "file_path": "tough/src/schema/mod.rs", "rank": 61, "score": 44274.730277923096 }, { "content": " timestamp\n\n .meta\n\n .insert(\"snapshot.json\".to_owned(), snapshot_meta);\n\n timestamp._extra = _extra;\n\n\n\n Ok(timestamp)\n\n }\n\n\n\n /// Build a `TimestampMeta` struct from a given `SignedRole<R>`. This metadata\n\n /// includes the sha256 and length of the signed role.\n\n fn timestamp_meta<R>(role: &SignedRole<R>) -> TimestampMeta\n\n where\n\n R: Role,\n\n {\n\n TimestampMeta {\n\n hashes: Hashes {\n\n sha256: role.sha256.to_vec().into(),\n\n _extra: HashMap::new(),\n\n },\n\n length: role.length,\n\n version: role.signed.signed.version(),\n\n _extra: HashMap::new(),\n\n }\n\n }\n\n}\n\n\n", "file_path": "tough/src/editor/mod.rs", "rank": 62, "score": 44274.730277923096 }, { "content": " signed_targets\n\n .signed\n\n .signed\n\n .validate()\n\n .context(error::InvalidPathSnafu)?;\n\n\n\n Ok(SignedRepository {\n\n root: self.signed_root,\n\n targets: signed_targets,\n\n snapshot: signed_snapshot,\n\n timestamp: signed_timestamp,\n\n delegated_targets: signed_delegated_targets,\n\n })\n\n }\n\n\n\n /// Add an existing `Targets` struct to the repository.\n\n pub fn targets(&mut self, targets: Signed<Targets>) -> Result<&mut Self> {\n\n ensure!(\n\n targets.signed.spec_version == SPEC_VERSION,\n\n error::SpecVersionSnafu {\n", "file_path": "tough/src/editor/mod.rs", "rank": 63, "score": 44274.730277923096 }, { "content": "\n\n Self::PathHashPrefixes(path_prefixes) => {\n\n for prefix in path_prefixes {\n\n if prefix.matches_target_name(target_name) {\n\n return true;\n\n }\n\n }\n\n }\n\n }\n\n false\n\n }\n\n}\n\n\n\nimpl Delegations {\n\n /// Creates a new Delegations with no keys or roles\n\n pub fn new() -> Self {\n\n Delegations {\n\n keys: HashMap::new(),\n\n roles: Vec::new(),\n\n }\n", "file_path": "tough/src/schema/mod.rs", "rank": 64, "score": 44274.730277923096 }, { "content": " /// Create a new, valid `PathPattern`. This will fail if we cannot parse the value as a glob. It is important that\n\n /// our implementation stop if it encounters a glob it cannot parse so that we do not load repositories where we\n\n /// cannot enforce delegate ownership.\n\n pub fn new<S: Into<String>>(value: S) -> Result<Self> {\n\n let value = value.into();\n\n let glob = Glob::new(&value)\n\n .context(error::GlobSnafu { pattern: &value })?\n\n .compile_matcher();\n\n Ok(Self { value, glob })\n\n }\n\n\n\n /// Get the inner value of this `PathPattern` as a string.\n\n pub fn value(&self) -> &str {\n\n &self.value\n\n }\n\n\n\n fn matches_target_name(&self, target_name: &TargetName) -> bool {\n\n self.glob.is_match(target_name.resolved())\n\n }\n\n}\n", "file_path": "tough/src/schema/mod.rs", "rank": 65, "score": 44274.730277923096 }, { "content": " // verify the role\n\n key_holder.verify_role(&new_role, &name)?;\n\n // add the new role\n\n delegations\n\n .roles\n\n .iter_mut()\n\n .find(|delegated_role| delegated_role.name == name)\n\n .context(error::DelegateNotFoundSnafu { name: name.clone() })?\n\n .targets = Some(new_role.clone());\n\n }\n\n // Add our new role in place of the old one\n\n if name == \"targets\" {\n\n self.signed_targets = Some(role);\n\n } else {\n\n self.signed_targets\n\n .as_mut()\n\n .context(error::NoTargetsSnafu)?\n\n .signed\n\n .delegated_role_mut(name)\n\n .context(error::DelegateMissingSnafu {\n", "file_path": "tough/src/editor/mod.rs", "rank": 66, "score": 44274.730277923096 }, { "content": " error::VersionMismatchSnafu {\n\n role: RoleType::Targets,\n\n fetched: role.signed.version,\n\n expected: current_targets.version\n\n }\n\n );\n\n // get a list of roles that we don't have metadata for yet\n\n // and copy current_targets delegated targets to role\n\n let new_roles = current_targets.update_targets(&mut role);\n\n let delegations = role\n\n .signed\n\n .delegations\n\n .as_mut()\n\n .context(error::NoDelegationsSnafu)?;\n\n // the new targets will be the keyholder for any of its newly delegated roles, so create a keyholder\n\n let key_holder = KeyHolder::Delegations(delegations.clone());\n\n // load the new roles\n\n for name in new_roles {\n\n // path to new metadata\n\n let encoded_name = encode_filename(&name);\n", "file_path": "tough/src/editor/mod.rs", "rank": 67, "score": 44274.730277923096 }, { "content": " }\n\n let targets = &mut self\n\n .signed_targets\n\n .as_mut()\n\n .context(error::NoTargetsSnafu)?\n\n .signed;\n\n let (key_holder, targets) = if role == \"targets\" {\n\n (\n\n KeyHolder::Root(self.signed_root.signed.signed.clone()),\n\n targets.clone(),\n\n )\n\n } else {\n\n let parent = targets\n\n .parent_of(role)\n\n .context(error::DelegateMissingSnafu {\n\n name: role.to_string(),\n\n })?\n\n .clone();\n\n let targets = targets\n\n .delegated_targets(role)\n", "file_path": "tough/src/editor/mod.rs", "rank": 68, "score": 44274.730277923096 }, { "content": " snapshot.meta.insert(\n\n format!(\"{}.json\", delegated_targets.signed.signed.name),\n\n meta,\n\n );\n\n }\n\n }\n\n\n\n Ok(snapshot)\n\n }\n\n\n\n /// Build a `SnapshotMeta` struct from a given `SignedRole<R>`. This metadata\n\n /// includes the sha256 and length of the signed role.\n\n fn snapshot_meta<R>(role: &SignedRole<R>) -> SnapshotMeta\n\n where\n\n R: Role,\n\n {\n\n SnapshotMeta {\n\n hashes: Some(Hashes {\n\n sha256: role.sha256.to_vec().into(),\n\n _extra: HashMap::new(),\n", "file_path": "tough/src/editor/mod.rs", "rank": 69, "score": 44274.730277923096 }, { "content": " #[serde(skip)]\n\n pub name: String,\n\n /// The targets representing the role metadata\n\n #[serde(flatten)]\n\n pub targets: Targets,\n\n}\n\n\n\nimpl Deref for DelegatedTargets {\n\n type Target = Targets;\n\n\n\n fn deref(&self) -> &Targets {\n\n &self.targets\n\n }\n\n}\n\n\n\nimpl DerefMut for DelegatedTargets {\n\n fn deref_mut(&mut self) -> &mut Targets {\n\n &mut self.targets\n\n }\n\n}\n", "file_path": "tough/src/schema/mod.rs", "rank": 70, "score": 44274.730277923096 }, { "content": " .targets\n\n .as_mut()\n\n .ok_or(error::Error::NoTargets)\n\n }\n\n\n\n /// Returns the `&DelegatedRole` for `name`\n\n pub fn delegated_role(&self, name: &str) -> Result<&DelegatedRole> {\n\n for role in &self\n\n .delegations\n\n .as_ref()\n\n .ok_or(error::Error::NoDelegations)?\n\n .roles\n\n {\n\n if role.name == name {\n\n return Ok(role);\n\n } else if let Ok(role) = role\n\n .targets\n\n .as_ref()\n\n .ok_or(error::Error::NoTargets)?\n\n .signed\n", "file_path": "tough/src/schema/mod.rs", "rank": 71, "score": 44274.730277923096 }, { "content": "/// A role identifier\n\n#[derive(Debug, Clone)]\n\npub enum RoleId {\n\n /// Top level roles are identified by a RoleType\n\n StandardRole(RoleType),\n\n /// A delegated role is identified by a String\n\n DelegatedRole(String),\n\n}\n\n\n\n/// Common trait implemented by all roles.\n", "file_path": "tough/src/schema/mod.rs", "rank": 72, "score": 44274.730277923096 }, { "content": "impl FromStr for PathHashPrefix {\n\n type Err = Error;\n\n\n\n fn from_str(s: &str) -> Result<Self> {\n\n PathHashPrefix::new(s)\n\n }\n\n}\n\n\n\nimpl PathSet {\n\n /// Given a `target_name`, returns whether or not this `PathSet` contains a pattern or hash\n\n /// prefix that matches.\n\n fn matches_target_name(&self, target_name: &TargetName) -> bool {\n\n match self {\n\n Self::Paths(paths) => {\n\n for path in paths {\n\n if path.matches_target_name(target_name) {\n\n return true;\n\n }\n\n }\n\n }\n", "file_path": "tough/src/schema/mod.rs", "rank": 73, "score": 44274.730277923096 }, { "content": "\n\nimpl FromStr for PathPattern {\n\n type Err = Error;\n\n\n\n fn from_str(s: &str) -> Result<Self> {\n\n PathPattern::new(s)\n\n }\n\n}\n\n\n\nimpl PartialEq for PathPattern {\n\n fn eq(&self, other: &Self) -> bool {\n\n PartialEq::eq(&self.value, &other.value)\n\n }\n\n}\n\n\n\nimpl Serialize for PathPattern {\n\n fn serialize<S>(&self, serializer: S) -> std::result::Result<S::Ok, S::Error>\n\n where\n\n S: Serializer,\n\n {\n", "file_path": "tough/src/schema/mod.rs", "rank": 74, "score": 44274.730277923096 }, { "content": " length: root_buf_len,\n\n };\n\n\n\n let mut editor = TargetsEditor::new(\"targets\");\n\n editor.key_holder = Some(KeyHolder::Root(signed_root.signed.signed.clone()));\n\n\n\n Ok(RepositoryEditor {\n\n signed_root,\n\n targets_editor: Some(editor),\n\n snapshot_version: None,\n\n snapshot_expires: None,\n\n snapshot_extra: None,\n\n timestamp_version: None,\n\n timestamp_expires: None,\n\n timestamp_extra: None,\n\n signed_targets: None,\n\n transport: None,\n\n limits: None,\n\n })\n\n }\n", "file_path": "tough/src/editor/mod.rs", "rank": 75, "score": 44274.730277923096 }, { "content": " /// Add a list of target paths to the repository\n\n ///\n\n /// See the note on `add_target_path()` regarding performance.\n\n pub fn add_target_paths<P>(&mut self, targets: Vec<P>) -> Result<&mut Self>\n\n where\n\n P: AsRef<Path>,\n\n {\n\n for target in targets {\n\n let (target_name, target) = RepositoryEditor::build_target(target)?;\n\n self.add_target(target_name, target)?;\n\n }\n\n\n\n Ok(self)\n\n }\n\n\n\n /// Builds a target struct for the given path\n\n pub fn build_target<P>(target_path: P) -> Result<(TargetName, Target)>\n\n where\n\n P: AsRef<Path>,\n\n {\n", "file_path": "tough/src/editor/mod.rs", "rank": 76, "score": 44274.730277923096 }, { "content": " #[serde(deserialize_with = \"de::extra_skip_type\")]\n\n pub _extra: HashMap<String, Value>,\n\n}\n\n\n\n/// Represents a metadata file in a `snapshot.json` file.\n\n/// TUF 4.4: METAFILES is an object whose format is the following:\n\n/// ```text\n\n/// { METAPATH : {\n\n/// \"version\" : VERSION,\n\n/// (\"length\" : LENGTH, |\n\n/// \"hashes\" : HASHES) }\n\n/// , ...\n\n/// }\n\n/// ```\n\n/// e.g.\n\n/// ```json\n\n/// \"project1.json\": {\n\n/// \"version\": 1,\n\n/// \"hashes\": {\n\n/// \"sha256\": \"f592d072e1193688a686267e8e10d7257b4ebfcf28133350dae88362d82a0c8a\"\n", "file_path": "tough/src/schema/mod.rs", "rank": 77, "score": 44274.730277923096 }, { "content": " error::SpecVersionSnafu {\n\n given: snapshot.spec_version,\n\n supported: SPEC_VERSION\n\n }\n\n );\n\n self.snapshot_extra = Some(snapshot._extra);\n\n Ok(self)\n\n }\n\n\n\n /// Add an existing `Timestamp` to the repository. Only the `_extra` data\n\n /// is preserved\n\n pub fn timestamp(&mut self, timestamp: Timestamp) -> Result<&mut Self> {\n\n ensure!(\n\n timestamp.spec_version == SPEC_VERSION,\n\n error::SpecVersionSnafu {\n\n given: timestamp.spec_version,\n\n supported: SPEC_VERSION\n\n }\n\n );\n\n self.timestamp_extra = Some(timestamp._extra);\n", "file_path": "tough/src/editor/mod.rs", "rank": 78, "score": 44274.730277923096 }, { "content": " new_targets_editor.version(version).expires(expiration);\n\n // Sign the new targets\n\n let new_targets = new_targets_editor.create_signed(key_source)?;\n\n // Find the keyids for key_source\n\n let mut keyids = Vec::new();\n\n let mut key_pairs = HashMap::new();\n\n for source in key_source {\n\n let key_pair = source\n\n .as_sign()\n\n .context(error::KeyPairFromKeySourceSnafu)?\n\n .tuf_key();\n\n keyids.push(\n\n key_pair\n\n .key_id()\n\n .context(error::JsonSerializationSnafu {})?,\n\n );\n\n key_pairs.insert(\n\n key_pair\n\n .key_id()\n\n .context(error::JsonSerializationSnafu {})?,\n", "file_path": "tough/src/editor/mod.rs", "rank": 79, "score": 44274.730277923096 }, { "content": " fn role_id(&self) -> RoleId {\n\n if self.name == \"targets\" {\n\n RoleId::StandardRole(RoleType::Targets)\n\n } else {\n\n RoleId::DelegatedRole(self.name.clone())\n\n }\n\n }\n\n}\n\n\n\nimpl Signed<DelegatedTargets> {\n\n /// Convert a `Signed<DelegatedTargets>` to the string representing the role and its `Signed<Targets>`\n\n pub fn targets(self) -> (String, Signed<Targets>) {\n\n (\n\n self.signed.name,\n\n Signed {\n\n signed: self.signed.targets,\n\n signatures: self.signatures,\n\n },\n\n )\n\n }\n", "file_path": "tough/src/schema/mod.rs", "rank": 80, "score": 44274.730277923096 }, { "content": " /// [More info on canonical JSON](http://wiki.laptop.org/go/Canonical_JSON)\n\n fn canonical_form(&self) -> Result<Vec<u8>> {\n\n let mut data = Vec::new();\n\n let mut ser = serde_json::Serializer::with_formatter(&mut data, CanonicalFormatter::new());\n\n self.serialize(&mut ser)\n\n .context(error::JsonSerializationSnafu { what: \"role\" })?;\n\n Ok(data)\n\n }\n\n}\n\n\n\n/// A signed metadata object.\n\n#[derive(Debug, Clone, Deserialize, Serialize, PartialEq)]\n\npub struct Signed<T> {\n\n /// The role that is signed.\n\n pub signed: T,\n\n /// A list of signatures and their key IDs.\n\n pub signatures: Vec<Signature>,\n\n}\n\n\n\n/// A signature and the key ID that made it.\n", "file_path": "tough/src/schema/mod.rs", "rank": 81, "score": 44274.730277923096 }, { "content": " error::TargetNotFoundSnafu {\n\n name: target_name.clone(),\n\n }\n\n .fail()\n\n }\n\n\n\n /// Returns a hashmap of all targets and all delegated targets recursively\n\n pub fn targets_map(&self) -> HashMap<TargetName, &Target> {\n\n self.targets_iter()\n\n .map(|(target_name, target)| (target_name.clone(), target))\n\n .collect()\n\n }\n\n\n\n /// Returns an iterator of all targets and all delegated targets recursively\n\n pub fn targets_iter(&self) -> impl Iterator<Item = (&TargetName, &Target)> + '_ {\n\n let mut iter: Box<dyn Iterator<Item = (&TargetName, &Target)>> =\n\n Box::new(self.targets.iter());\n\n if let Some(delegations) = &self.delegations {\n\n for role in &delegations.roles {\n\n if let Some(targets) = &role.targets {\n", "file_path": "tough/src/schema/mod.rs", "rank": 82, "score": 44274.730277923096 }, { "content": " )\n\n } else {\n\n let parent = targets\n\n .parent_of(name)\n\n .context(error::DelegateMissingSnafu {\n\n name: name.to_string(),\n\n })?\n\n .clone();\n\n let targets =\n\n targets\n\n .delegated_targets_mut(name)\n\n .context(error::DelegateMissingSnafu {\n\n name: name.to_string(),\n\n })?;\n\n (KeyHolder::Delegations(parent), &mut targets.signed)\n\n };\n\n parent.verify_role(&role, name)?;\n\n // Make sure the version isn't downgraded\n\n ensure!(\n\n role.signed.version >= current_targets.version,\n", "file_path": "tough/src/editor/mod.rs", "rank": 83, "score": 44274.730277923096 }, { "content": " }\n\n }\n\n }\n\n }\n\n Err(error::Error::RoleNotFound {\n\n name: name.to_string(),\n\n })\n\n }\n\n\n\n /// Returns a vec of all targets roles delegated by this role\n\n pub fn signed_delegated_targets(&self) -> Vec<Signed<DelegatedTargets>> {\n\n let mut delegated_targets = Vec::new();\n\n if let Some(delegations) = &self.delegations {\n\n for role in &delegations.roles {\n\n if let Some(targets) = &role.targets {\n\n delegated_targets.push(targets.clone().delegated_targets(&role.name));\n\n delegated_targets.extend(targets.signed.signed_delegated_targets());\n\n }\n\n }\n\n }\n", "file_path": "tough/src/schema/mod.rs", "rank": 84, "score": 44274.730277923096 }, { "content": " }\n\n\n\n /// Determines if target passes pathset specific matching\n\n pub fn target_is_delegated(&self, target: &TargetName) -> bool {\n\n for role in &self.roles {\n\n if role.paths.matches_target_name(target) {\n\n return true;\n\n }\n\n }\n\n false\n\n }\n\n\n\n /// Given an object/key that impls Sign, return the corresponding\n\n /// key ID from Delegation\n\n pub fn key_id(&self, key_pair: &dyn Sign) -> Option<Decoded<Hex>> {\n\n for (key_id, key) in &self.keys {\n\n if key_pair.tuf_key() == *key {\n\n return Some(key_id.clone());\n\n }\n\n }\n", "file_path": "tough/src/schema/mod.rs", "rank": 85, "score": 44274.730277923096 }, { "content": " .delegated_role(name)\n\n {\n\n return Ok(role);\n\n }\n\n }\n\n Err(error::Error::RoleNotFound {\n\n name: name.to_string(),\n\n })\n\n }\n\n\n\n /// Returns a mutable `DelegatedRole` for `name`\n\n pub fn delegated_role_mut(&mut self, name: &str) -> Result<&mut DelegatedRole> {\n\n for role in &mut self\n\n .delegations\n\n .as_mut()\n\n .ok_or(error::Error::NoDelegations)?\n\n .roles\n\n {\n\n if role.name == name {\n\n return Ok(role);\n", "file_path": "tough/src/schema/mod.rs", "rank": 86, "score": 44274.730277923096 }, { "content": "\n\n /// Given a `tough::Repository` and the path to a valid root.json, create a\n\n /// `RepositoryEditor`. This `RepositoryEditor` will include all of the targets\n\n /// and bits of _extra metadata from the roles included. It will not, however,\n\n /// include the versions or expirations and the user is expected to set them.\n\n pub fn from_repo<P>(root_path: P, repo: Repository) -> Result<RepositoryEditor>\n\n where\n\n P: AsRef<Path>,\n\n {\n\n let mut editor = RepositoryEditor::new(root_path)?;\n\n editor.targets(repo.targets)?;\n\n editor.snapshot(repo.snapshot.signed)?;\n\n editor.timestamp(repo.timestamp.signed)?;\n\n editor.transport = Some(repo.transport.clone());\n\n editor.limits = Some(repo.limits);\n\n Ok(editor)\n\n }\n\n\n\n /// Builds and signs each required role and returns a complete signed set\n\n /// of TUF repository metadata.\n", "file_path": "tough/src/editor/mod.rs", "rank": 87, "score": 44274.730277923096 }, { "content": " encoded: encoded_name,\n\n filename: encoded_filename,\n\n url: metadata_base_url.clone(),\n\n })?;\n\n let reader = Box::new(fetch_max_size(\n\n transport.as_ref(),\n\n role_url,\n\n limits.max_targets_size,\n\n \"max targets limit\",\n\n )?);\n\n // Load incoming role metadata as Signed<Targets>\n\n let mut role: Signed<crate::schema::Targets> =\n\n serde_json::from_reader(reader).context(error::ParseMetadataSnafu {\n\n role: RoleType::Targets,\n\n })?;\n\n //verify role with the parent delegation\n\n let (parent, current_targets) = if name == \"targets\" {\n\n (\n\n KeyHolder::Root(self.signed_root.signed.signed.clone()),\n\n targets,\n", "file_path": "tough/src/editor/mod.rs", "rank": 88, "score": 44274.730277923096 }, { "content": " self.version\n\n }\n\n\n\n fn filename(&self, _consistent_snapshot: bool) -> String {\n\n format!(\"{}.root.json\", self.version())\n\n }\n\n}\n\n\n\n// =^..^= =^..^= =^..^= =^..^= =^..^= =^..^= =^..^= =^..^= =^..^= =^..^= =^..^=\n\n\n\n/// TUF 4.4 The snapshot.json file is signed by the snapshot role. It MUST list the version numbers\n\n/// of the top-level targets metadata and all delegated targets metadata. It MAY also list their\n\n/// lengths and file hashes.\n\n#[derive(Debug, Clone, Deserialize, Serialize, PartialEq)]\n\n#[serde(tag = \"_type\")]\n\n#[serde(rename = \"snapshot\")]\n\npub struct Snapshot {\n\n /// A string that contains the version number of the TUF specification. Its format follows the\n\n /// Semantic Versioning 2.0.0 (semver) specification.\n\n pub spec_version: String,\n", "file_path": "tough/src/schema/mod.rs", "rank": 89, "score": 44274.730277923096 }, { "content": " roles.push(&role.name);\n\n if let Some(targets) = &role.targets {\n\n roles.append(&mut targets.signed.role_names());\n\n }\n\n }\n\n }\n\n\n\n roles\n\n }\n\n\n\n /// Returns a reference to the parent delegation of `name`\n\n pub fn parent_of(&self, name: &str) -> Result<&Delegations> {\n\n if let Some(delegations) = &self.delegations {\n\n for role in &delegations.roles {\n\n if role.name == name {\n\n return Ok(delegations);\n\n }\n\n if let Some(targets) = &role.targets {\n\n if let Ok(delegation) = targets.signed.parent_of(name) {\n\n return Ok(delegation);\n", "file_path": "tough/src/schema/mod.rs", "rank": 90, "score": 44274.730277923096 }, { "content": " key_pair,\n\n );\n\n }\n\n // Add the new role to targets_editor\n\n self.targets_editor_mut()?.delegate_role(\n\n new_targets,\n\n paths,\n\n key_pairs,\n\n keyids,\n\n threshold,\n\n )?;\n\n\n\n Ok(self)\n\n }\n\n\n\n /// Set the `Snapshot` version\n\n pub fn snapshot_version(&mut self, snapshot_version: NonZeroU64) -> &mut Self {\n\n self.snapshot_version = Some(snapshot_version);\n\n self\n\n }\n", "file_path": "tough/src/editor/mod.rs", "rank": 91, "score": 44274.730277923096 }, { "content": " /// We must store these to correctly verify signatures for this object.\n\n ///\n\n /// If you're instantiating this struct, you should make this `HashMap::empty()`.\n\n #[serde(flatten)]\n\n #[serde(deserialize_with = \"de::extra_skip_type\")]\n\n pub _extra: HashMap<String, Value>,\n\n}\n\n\n\n/// TUF 4.5: TARGETS is an object whose format is the following:\n\n/// ```text\n\n/// { TARGETPATH : {\n\n/// \"length\" : LENGTH,\n\n/// \"hashes\" : HASHES,\n\n/// (\"custom\" : { ... }) }\n\n/// , ...\n\n/// }\n\n/// ```\n\n#[derive(Debug, Clone, Deserialize, Serialize, PartialEq)]\n\npub struct Target {\n\n /// LENGTH is the integer length in bytes of the target file at TARGETPATH.\n", "file_path": "tough/src/schema/mod.rs", "rank": 92, "score": 44274.730277923096 }, { "content": "#[derive(Debug, Clone, Deserialize, Serialize, PartialEq)]\n\npub struct Signature {\n\n /// The key ID (listed in root.json) that made this signature.\n\n pub keyid: Decoded<Hex>,\n\n /// A hex-encoded signature of the canonical JSON form of a role.\n\n pub sig: Decoded<Hex>,\n\n}\n\n\n\n/// A `KeyHolder` is metadata that is responsible for verifying the signatures of a role.\n\n/// `KeyHolder` contains either a `Delegations` of a `Targets` or a `Root`\n\n#[derive(Debug, Clone)]\n\npub enum KeyHolder {\n\n /// Delegations verify delegated targets\n\n Delegations(Delegations),\n\n /// Root verifies the top level targets, snapshot, timestamp, and root\n\n Root(Root),\n\n}\n\n\n\n// =^..^= =^..^= =^..^= =^..^= =^..^= =^..^= =^..^= =^..^= =^..^= =^..^= =^..^=\n\n\n", "file_path": "tough/src/schema/mod.rs", "rank": 93, "score": 44274.730277923096 }, { "content": " let transport = self\n\n .transport\n\n .as_ref()\n\n .context(error::MissingTransportSnafu)?\n\n .clone();\n\n self.targets_editor_mut()?.limits(limits);\n\n self.targets_editor_mut()?.transport(transport.clone());\n\n self.targets_editor_mut()?\n\n .add_role(name, metadata_url, paths, threshold, keys)?;\n\n\n\n Ok(self)\n\n }\n\n\n\n // =^..^= =^..^= =^..^= =^..^= =^..^= =^..^= =^..^= =^..^= =^..^= =^..^=\n\n\n\n /// Build the `Snapshot` struct\n\n fn build_snapshot(\n\n &self,\n\n signed_targets: &SignedRole<Targets>,\n\n signed_delegated_targets: &Option<SignedDelegatedTargets>,\n", "file_path": "tough/src/editor/mod.rs", "rank": 94, "score": 44274.730277923096 }, { "content": " for role in delegated_targets {\n\n // Create a `SignedRole<DelegatedTargets>` for each delegated targets\n\n roles.push(SignedRole::from_signed(role)?);\n\n }\n\n // SignedDelegatedTargets is a wrapper for a set of `SignedRole<DelegatedTargets>`\n\n Some(SignedDelegatedTargets {\n\n roles,\n\n consistent_snapshot: self.signed_root.signed.signed.consistent_snapshot,\n\n })\n\n };\n\n\n\n let signed_snapshot = self\n\n .build_snapshot(&signed_targets, &signed_delegated_targets)\n\n .and_then(|snapshot| SignedRole::new(snapshot, &root, keys, &rng))?;\n\n let signed_timestamp = self\n\n .build_timestamp(&signed_snapshot)\n\n .and_then(|timestamp| SignedRole::new(timestamp, &root, keys, &rng))?;\n\n\n\n // This validation can only be done from the top level targets.json role. This check verifies\n\n // that each target's delegate hierarchy is a match (i.e. its delegate ownership is valid).\n", "file_path": "tough/src/editor/mod.rs", "rank": 95, "score": 44274.730277923096 }, { "content": "\n\n/// Represents a `targets.json` file.\n\n/// TUF 4.5:\n\n/// The \"signed\" portion of targets.json is as follows:\n\n/// ```text\n\n/// { \"_type\" : \"targets\",\n\n/// \"spec_version\" : SPEC_VERSION,\n\n/// \"version\" : VERSION,\n\n/// \"expires\" : EXPIRES,\n\n/// \"targets\" : TARGETS,\n\n/// (\"delegations\" : DELEGATIONS)\n\n/// }\n\n/// ```\n\n///\n\n#[derive(Debug, Clone, Deserialize, Serialize, PartialEq)]\n\n#[serde(tag = \"_type\")]\n\n#[serde(rename = \"targets\")]\n\npub struct Targets {\n\n /// A string that contains the version number of the TUF specification. Its format follows the\n\n /// Semantic Versioning 2.0.0 (semver) specification.\n", "file_path": "tough/src/schema/mod.rs", "rank": 96, "score": 44274.730277923096 }, { "content": " /// **Caution**: does not imply that delegations in this struct or any child are valid.\n\n ///\n\n pub fn find_target(&self, target_name: &TargetName) -> Result<&Target> {\n\n if let Some(target) = self.targets.get(target_name) {\n\n return Ok(target);\n\n }\n\n if let Some(delegations) = &self.delegations {\n\n for role in &delegations.roles {\n\n // If the target cannot match this DelegatedRole, then we do not want to recurse and\n\n // check any of its child roles either.\n\n if !role.paths.matches_target_name(target_name) {\n\n continue;\n\n }\n\n if let Some(targets) = &role.targets {\n\n if let Ok(target) = targets.signed.find_target(target_name) {\n\n return Ok(target);\n\n }\n\n }\n\n }\n\n }\n", "file_path": "tough/src/schema/mod.rs", "rank": 97, "score": 44274.730277923096 }, { "content": " /// number less than the one currently trusted.\n\n pub version: NonZeroU64,\n\n\n\n /// Extra arguments found during deserialization.\n\n ///\n\n /// We must store these to correctly verify signatures for this object.\n\n ///\n\n /// If you're instantiating this struct, you should make this `HashMap::empty()`.\n\n #[serde(flatten)]\n\n pub _extra: HashMap<String, Value>,\n\n}\n\n\n\n/// Represents the hash dictionary in a `snapshot.json` file.\n\n#[derive(Debug, Clone, Deserialize, Serialize, PartialEq)]\n\npub struct Hashes {\n\n /// The SHA 256 digest of a metadata file.\n\n pub sha256: Decoded<Hex>,\n\n\n\n /// Extra arguments found during deserialization.\n\n ///\n", "file_path": "tough/src/schema/mod.rs", "rank": 98, "score": 44274.730277923096 }, { "content": "/// ... },\n\n/// \"roles\" : [{\n\n/// \"name\": ROLENAME,\n\n/// \"keyids\" : [ KEYID, ... ] ,\n\n/// \"threshold\" : THRESHOLD,\n\n/// (\"path_hash_prefixes\" : [ HEX_DIGEST, ... ] |\n\n/// \"paths\" : [ PATHPATTERN, ... ]),\n\n/// \"terminating\": TERMINATING,\n\n/// }, ... ]\n\n/// }\n\n/// ```\n\n#[derive(Debug, Clone, Deserialize, Serialize, PartialEq, Default)]\n\npub struct Delegations {\n\n /// Lists the public keys to verify signatures of delegated targets roles. Revocation and\n\n /// replacement of delegated targets roles keys is done by changing the keys in this field in\n\n /// the delegating role's metadata.\n\n #[serde(deserialize_with = \"de::deserialize_keys\")]\n\n pub keys: HashMap<Decoded<Hex>, Key>,\n\n\n\n /// The list of delegated roles.\n", "file_path": "tough/src/schema/mod.rs", "rank": 99, "score": 44274.730277923096 } ]
Rust
src/core/value.rs
aesedepece/scriptful
37f6ff8361077ac63ab861273ba75b4f0571706d
#[derive(Clone, Debug, PartialOrd)] pub enum Value { Boolean(bool), Float(f64), Integer(i128), String(&'static str), } impl core::ops::Not for Value { type Output = Self; fn not(self) -> Self::Output { use Value::*; match self { Boolean(x) => Boolean(!x), Float(x) => Float(-x), Integer(x) => Integer(-x), _ => panic!("Type of {:?} cannot be negated", self), } } } #[allow(clippy::suspicious_arithmetic_impl)] impl core::ops::Add for Value { type Output = Self; fn add(self, rhs: Self) -> Self::Output { use Value::*; match (self, rhs) { (Boolean(a), Boolean(b)) => Boolean(a || b), (Float(a), Float(b)) => Float(a + b), (Float(a), Integer(b)) => Float(a + b as f64), (Integer(a), Integer(b)) => Integer(a + b), (Integer(a), Float(b)) => Float(a as f64 + b), (a, b) => panic!("Types of {:?} and {:?} cannot be added together", a, b), } } } #[allow(clippy::suspicious_arithmetic_impl)] impl core::ops::Mul for Value { type Output = Self; fn mul(self, rhs: Self) -> Self::Output { use Value::*; match (self, rhs) { (Boolean(a), Boolean(b)) => Boolean(a && b), (Float(a), Float(b)) => Float(a * b), (Float(a), Integer(b)) => Float(a * b as f64), (Integer(a), Integer(b)) => Integer(a * b), (Integer(a), Float(b)) => Float(a as f64 * b), (a, b) => panic!("Types of {:?} and {:?} cannot be multiplied together", a, b), } } } impl core::ops::Sub for Value { type Output = Self; fn sub(self, rhs: Self) -> Self::Output { self + !rhs } } impl core::cmp::PartialEq for Value { fn eq(&self, other: &Self) -> bool { use Value::*; match (self, other) { (Boolean(a), Boolean(b)) => a == b, (Float(a), Float(b)) => (a - b) * (a - b) < 0.000_000_000_000_000_000_1, (Float(a), Integer(b)) => { (a - *b as f64) * (a - *b as f64) < 0.000_000_000_000_000_000_1 } (Integer(a), Integer(b)) => a == b, (Integer(a), Float(b)) => { (*a as f64 - b) * (*a as f64 - *b) < 0.000_000_000_000_000_000_1 } (String(a), String(b)) => a == b, _ => false, } } } #[cfg(test)] mod tests { use crate::core::value::Value::*; #[test] fn test_negation() { assert_eq!(!Boolean(true), Boolean(false)); assert_eq!(!Boolean(false), Boolean(true)); assert_eq!(!Float(0.), Float(0.)); assert_eq!(!Float(1.1), Float(-1.1)); assert_eq!(!Integer(0), Integer(0)); assert_eq!(!Integer(1), Integer(-1)); } #[test] fn test_addition() { assert_eq!(Boolean(false) + Boolean(false), Boolean(false)); assert_eq!(Boolean(false) + Boolean(true), Boolean(true)); assert_eq!(Boolean(true) + Boolean(false), Boolean(true)); assert_eq!(Boolean(true) + Boolean(true), Boolean(true)); assert_eq!(Float(1.1) + Float(2.2), Float(3.3)); assert_eq!(Float(1.1) + Float(-2.2), Float(-1.1)); assert_eq!(Float(1.1) + Integer(2), Float(3.1)); assert_eq!(Float(1.1) + Integer(-2), Float(-0.9)); assert_eq!(Integer(1) + Integer(2), Integer(3)); assert_eq!(Integer(1) + Integer(-2), Integer(-1)); assert_eq!(Integer(1) + Float(2.2), Float(3.2)); assert_eq!(Integer(1) + Float(-2.1), Float(-1.1)); } #[test] fn test_subtraction() { assert_eq!(Boolean(false) - Boolean(false), Boolean(true)); assert_eq!(Boolean(false) - Boolean(true), Boolean(false)); assert_eq!(Boolean(true) - Boolean(false), Boolean(true)); assert_eq!(Boolean(true) - Boolean(true), Boolean(true)); assert_eq!(Float(1.1) - Float(2.2), Float(-1.1)); assert_eq!(Float(1.1) - Float(-2.2), Float(3.3)); assert_eq!(Float(1.1) - Integer(2), Float(-0.9)); assert_eq!(Float(1.1) - Integer(-2), Float(3.1)); assert_eq!(Integer(1) - Integer(2), Integer(-1)); assert_eq!(Integer(1) - Integer(-2), Integer(3)); assert_eq!(Integer(1) - Float(2.2), Float(-1.2)); assert_eq!(Integer(1) - Float(-2.2), Float(3.2)); } #[test] fn test_multiplication() { assert_eq!(Boolean(false) * Boolean(false), Boolean(false)); assert_eq!(Boolean(false) * Boolean(true), Boolean(false)); assert_eq!(Boolean(true) * Boolean(false), Boolean(false)); assert_eq!(Boolean(true) * Boolean(true), Boolean(true)); assert_eq!(Float(1.1) * Float(2.2), Float(2.42)); assert_eq!(Float(1.1) * Float(-2.2), Float(-2.42)); assert_eq!(Float(1.1) * Integer(2), Float(2.2)); assert_eq!(Float(1.1) * Integer(-2), Float(-2.2)); assert_eq!(Integer(1) * Integer(2), Integer(2)); assert_eq!(Integer(1) * Integer(-2), Integer(-2)); assert_eq!(Integer(1) * Float(2.2), Float(2.2)); assert_eq!(Integer(1) * Float(-2.2), Float(-2.2)); } #[test] fn test_comparison() { assert_eq!(Boolean(false) == Boolean(false), true); assert_eq!(Boolean(false) == Boolean(true), false); assert_eq!(Boolean(true) == Boolean(false), false); assert_eq!(Boolean(true) == Boolean(true), true); assert_eq!(Float(1.1) == Float(1.1), true); assert_eq!(Float(1.1) == Float(2.2), false); assert_eq!(Float(-1.1) == Float(-1.1), true); assert_eq!(Float(-1.1) == Float(-2.2), false); assert_eq!(Float(1.1) == Float(-1.1), false); assert_eq!(Float(1.) == Integer(1), true); assert_eq!(Float(-1.) == Integer(-1), true); assert_eq!(Integer(1) == Integer(1), true); assert_eq!(Integer(1) == Integer(2), false); assert_eq!(Integer(-1) == Integer(-1), true); assert_eq!(Integer(-1) == Integer(-2), false); assert_eq!(Integer(1) == Integer(-1), false); assert_eq!(Integer(1) == Float(1.), true); assert_eq!(Integer(-1) == Float(-1.), true); } }
#[derive(Clone, Debug, PartialOrd)] pub enum Value { Boolean(bool), Float(f64), Integer(i128), String(&'static str), } impl core::ops::Not for Value { type Output = Self; fn not(self) -> Self::Output { use Value::*; match self { Boolean(x) => Boolean(!x), Float(x) => Float(-x), Integer(x) => Integer(-x), _ => panic!("Type of {:?} cannot be negated", self), } } } #[allow(clippy::suspicious_arithmetic_impl)] impl core::ops::Add for Value { type Output = Self; fn add(self, rhs: Self) -> Self::Output { use Value::*; match (self, rhs) { (Boolean(a), Boolean(b)) => Boolean(a || b), (Float(a), Float(b)) => Float(a + b), (Float(a), Integer(b)) => Float(a + b as f64), (Integer(a), Integer(b)) => Integer(a + b), (Integer(a), Float(b)) => Float(a as f64 + b), (a, b) => panic!("Types of {:?} and {:?} cannot be added together", a, b), } } } #[allow(clippy::suspicious_arithmetic_impl)] impl core::ops::Mul for Value { type Output = Self; fn mul(self, rhs: Self) -> Self::Output { use Value::*; match (self, rhs) { (Boolean(a), Boolean(b)) => Boolean(a && b), (Float(a), Float(b)) => Float(a * b), (Float(a), Integer(b)) => Float(a * b as f64), (Integer(a), Integer(b)) => Integer(a * b), (Integer(a), Float(b)) => Float(a as f64 * b), (a, b) => panic!("Types of {:?} and {:?} cannot be multiplied together", a, b), } } } impl core::ops::Sub for Value { type Output = Self; fn sub(self, rhs: Self) -> Self::Output { self + !rhs } } impl core::cmp::PartialEq for Value { fn eq(&self, other: &Self) -> bool { use Value::*; match (self, other) { (Boolean(a), Boolean(b)) => a == b, (Float(a), Float(b)) => (a - b) * (a - b) < 0.000_000_000_000_000_000_1, (Float(a), Integer(b)) => { (a - *b as f64) * (a - *b as f64) < 0.000_000_000_000_000_000_1 } (Integer(a), Integer(b)) => a == b, (Integer(a), Float(b)) => { (*a as f64 - b) * (*a as f64 - *b) < 0.000_000_000_000_000_000_1 } (String(a), String(b)) => a == b, _ => false, } } } #[cfg(test)] mod tests { use crate::core::value::Value::*; #[test] fn test_negation() { assert_eq!(!Boolean(true), Boolean(false)); assert_eq!(!Boolean(false), Boolean(true)); assert_eq!(!Float(0.), Float(0.)); assert_eq!(!Float(1.1), Float(-1.1)); assert_eq!(!Integer(0), Integer(0)); assert_eq!(!Integer(1), Integer(-1)); } #[test] fn test_addition() { assert_eq!(Boolean(false) + Boolean(false), Boolean(false)); assert_eq!(Boolean(false) + Boolean(true), Boolean(true)); assert_eq!(Boolean(true) + Boolea
at(2.2), Float(3.3)); assert_eq!(Float(1.1) + Float(-2.2), Float(-1.1)); assert_eq!(Float(1.1) + Integer(2), Float(3.1)); assert_eq!(Float(1.1) + Integer(-2), Float(-0.9)); assert_eq!(Integer(1) + Integer(2), Integer(3)); assert_eq!(Integer(1) + Integer(-2), Integer(-1)); assert_eq!(Integer(1) + Float(2.2), Float(3.2)); assert_eq!(Integer(1) + Float(-2.1), Float(-1.1)); } #[test] fn test_subtraction() { assert_eq!(Boolean(false) - Boolean(false), Boolean(true)); assert_eq!(Boolean(false) - Boolean(true), Boolean(false)); assert_eq!(Boolean(true) - Boolean(false), Boolean(true)); assert_eq!(Boolean(true) - Boolean(true), Boolean(true)); assert_eq!(Float(1.1) - Float(2.2), Float(-1.1)); assert_eq!(Float(1.1) - Float(-2.2), Float(3.3)); assert_eq!(Float(1.1) - Integer(2), Float(-0.9)); assert_eq!(Float(1.1) - Integer(-2), Float(3.1)); assert_eq!(Integer(1) - Integer(2), Integer(-1)); assert_eq!(Integer(1) - Integer(-2), Integer(3)); assert_eq!(Integer(1) - Float(2.2), Float(-1.2)); assert_eq!(Integer(1) - Float(-2.2), Float(3.2)); } #[test] fn test_multiplication() { assert_eq!(Boolean(false) * Boolean(false), Boolean(false)); assert_eq!(Boolean(false) * Boolean(true), Boolean(false)); assert_eq!(Boolean(true) * Boolean(false), Boolean(false)); assert_eq!(Boolean(true) * Boolean(true), Boolean(true)); assert_eq!(Float(1.1) * Float(2.2), Float(2.42)); assert_eq!(Float(1.1) * Float(-2.2), Float(-2.42)); assert_eq!(Float(1.1) * Integer(2), Float(2.2)); assert_eq!(Float(1.1) * Integer(-2), Float(-2.2)); assert_eq!(Integer(1) * Integer(2), Integer(2)); assert_eq!(Integer(1) * Integer(-2), Integer(-2)); assert_eq!(Integer(1) * Float(2.2), Float(2.2)); assert_eq!(Integer(1) * Float(-2.2), Float(-2.2)); } #[test] fn test_comparison() { assert_eq!(Boolean(false) == Boolean(false), true); assert_eq!(Boolean(false) == Boolean(true), false); assert_eq!(Boolean(true) == Boolean(false), false); assert_eq!(Boolean(true) == Boolean(true), true); assert_eq!(Float(1.1) == Float(1.1), true); assert_eq!(Float(1.1) == Float(2.2), false); assert_eq!(Float(-1.1) == Float(-1.1), true); assert_eq!(Float(-1.1) == Float(-2.2), false); assert_eq!(Float(1.1) == Float(-1.1), false); assert_eq!(Float(1.) == Integer(1), true); assert_eq!(Float(-1.) == Integer(-1), true); assert_eq!(Integer(1) == Integer(1), true); assert_eq!(Integer(1) == Integer(2), false); assert_eq!(Integer(-1) == Integer(-1), true); assert_eq!(Integer(-1) == Integer(-2), false); assert_eq!(Integer(1) == Integer(-1), false); assert_eq!(Integer(1) == Float(1.), true); assert_eq!(Integer(-1) == Float(-1.), true); } }
n(false), Boolean(true)); assert_eq!(Boolean(true) + Boolean(true), Boolean(true)); assert_eq!(Float(1.1) + Flo
function_block-random_span
[ { "content": "/// The main function that tells which creatures evolute and devolute into which other creatures.\n\npub fn pokemon_op_sys(stack: &mut Stack<Creature>, operator: &Command) {\n\n use Creature::*;\n\n let last_creature = stack.pop();\n\n match operator {\n\n Command::Evolute => stack.push(match last_creature {\n\n Bulbasaur => Ivysaur,\n\n Ivysaur => Venusaur,\n\n Charmander => Charmaleon,\n\n Charmaleon => Charizard,\n\n Squirtle => Wartortle,\n\n Wartortle => Blastoise,\n\n any_other => any_other,\n\n }),\n\n Command::Devolute => stack.push(match last_creature {\n\n Ivysaur => Bulbasaur,\n\n Venusaur => Ivysaur,\n\n Charmaleon => Charmander,\n\n Charizard => Charmaleon,\n\n Wartortle => Squirtle,\n\n Blastoise => Wartortle,\n", "file_path": "src/op_systems/pokemon.rs", "rank": 0, "score": 34711.98871387154 }, { "content": "/// A simple operator system that decides how each of the variants of [`MathOperator`][MathOperator]\n\n/// trigger push and pulls on the [`Stack`][Stack] inside a [`Machine`][Machine].\n\n///\n\n/// [MathOperator]: enum.MathOperator.html\n\n/// [Stack]: ../../core/stack/struct.Stack.html\n\n/// [Machine]: ../../core/machine/struct.Machine.html\n\npub fn simple_math_op_sys(stack: &mut Stack, operator: &MathOperator) {\n\n use crate::core::value::Value::*;\n\n\n\n match operator {\n\n MathOperator::Add => {\n\n let a = stack.pop();\n\n let b = stack.pop();\n\n stack.push(a + b);\n\n }\n\n MathOperator::Equal => {\n\n let a = stack.pop();\n\n let b = stack.pop();\n\n stack.push(Boolean(a == b));\n\n }\n\n MathOperator::Mul => {\n\n let a = stack.pop();\n\n let b = stack.pop();\n\n stack.push(a * b);\n\n }\n\n MathOperator::Not => {\n", "file_path": "src/op_systems/simple_math.rs", "rank": 1, "score": 33449.01898294396 }, { "content": "pub mod item;\n\npub mod machine;\n\npub mod stack;\n\npub mod value;\n\n\n\n/// A simple alias for referring an ordered sequence of [`Item`][Item]s of definite length.\n\n///\n\n/// [Item]: item\n\npub type Script<Op, Val> = [item::Item<Op, Val>];\n", "file_path": "src/core/mod.rs", "rank": 2, "score": 22210.19090991893 }, { "content": "pub mod pokemon;\n\npub mod simple_math;\n", "file_path": "src/op_systems/mod.rs", "rank": 13, "score": 21056.257017720032 }, { "content": " Val: core::fmt::Debug + core::cmp::PartialEq,\n\n{\n\n fn eq(&self, other: &Self) -> bool {\n\n match (self, other) {\n\n (Self::Operator(op), Self::Operator(other_op)) => op == other_op,\n\n (Self::Value(value), Self::Value(other_value)) => value == other_value,\n\n _ => false,\n\n }\n\n }\n\n}\n\n\n\n#[cfg(test)]\n\nmod tests {\n\n use crate::core::item::Item::{self, *};\n\n use crate::core::value::Value::*;\n\n\n\n #[test]\n\n fn test_eq() {\n\n let op_item1: Item<u8> = Operator(u8::default());\n\n let op_item2: Item<u8> = Operator(u8::default());\n", "file_path": "src/core/item.rs", "rank": 14, "score": 16.595153682363456 }, { "content": " ///\n\n /// ```rust\n\n /// use scriptful::prelude::*;\n\n /// use scriptful::core::value::Value::*;\n\n ///\n\n /// let value = Integer(i128::default());\n\n /// let mut stack = Stack::default();\n\n /// stack.push(value.clone());\n\n /// let topmost = stack.topmost();\n\n ///\n\n /// assert_eq!(topmost, Some(&value));\n\n /// ```\n\n pub fn topmost(&self) -> Option<&Val> {\n\n self.main.last()\n\n }\n\n}\n\n\n\nimpl<Val> core::default::Default for Stack<Val>\n\nwhere\n\n Val: core::fmt::Debug,\n\n{\n\n fn default() -> Self {\n\n Self {\n\n main: SmallVec::new(),\n\n alt: SmallVec::new(),\n\n }\n\n }\n\n}\n", "file_path": "src/core/stack.rs", "rank": 15, "score": 11.31418320668554 }, { "content": "\n\n#![no_std]\n\n#![doc(html_playground_url = \"https://play.rust-lang.org/\")]\n\n\n\n/// The core of this library.\n\n///\n\n/// Provides all the [`Item`][Item], [`Stack`][Stack], [`Machine`][Machine] and [`Value`][Value] goodness.\n\n///\n\n/// [Item]: item/\n\n/// [Stack]: stack/\n\n/// [Machine]: machine/\n\n/// [Value]: value/\n\npub mod core;\n\n/// Some ready-to-use operator systems that may be useful for _someone_, _somewhere_, _somewhen_.\n\npub mod op_systems;\n\n\n\n/// Re-exports the most frequently used parts of this library so that they can be used more conveniently.\n\npub mod prelude {\n\n pub use crate::core::{item::Item, machine::Machine, stack::Stack, Script};\n\n}\n", "file_path": "src/lib.rs", "rank": 16, "score": 9.723423247312152 }, { "content": " let x = stack.pop();\n\n stack.push(!x);\n\n }\n\n MathOperator::Sub => {\n\n let a = stack.pop();\n\n let b = stack.pop();\n\n stack.push(a - b);\n\n }\n\n }\n\n}\n\n\n\n#[cfg(test)]\n\nmod tests {\n\n use crate::core::value::Value::*;\n\n use crate::op_systems::simple_math::{simple_math_op_sys, MathOperator};\n\n use crate::prelude::Item::*;\n\n use crate::prelude::*;\n\n\n\n #[test]\n\n fn test_one_plus_one_equals_two() {\n", "file_path": "src/op_systems/simple_math.rs", "rank": 17, "score": 9.034196870713485 }, { "content": "/// The `alt` sub-stack is therefore limited for usage as a sort of _clipboard_ for values.\n\n///\n\n/// [LIFO]: https://en.wikipedia.org/wiki/Stack_(abstract_data_type)\n\n/// [pop_into_alt]: #method.pop_into_alt\n\n/// [push_from_alt]: #method.push_from_alt\n\n#[derive(Debug)]\n\npub struct Stack<Val = Value>\n\nwhere\n\n Val: core::fmt::Debug,\n\n{\n\n main: SmallVec<[Val; 64]>,\n\n alt: SmallVec<[Val; 8]>,\n\n}\n\n\n\nimpl<Val> Stack<Val>\n\nwhere\n\n Val: core::fmt::Debug,\n\n{\n\n /// Returns the number of values in the `main` sub-stack, also referred to as its 'length'.\n\n ///\n", "file_path": "src/core/stack.rs", "rank": 18, "score": 8.921470138266711 }, { "content": "## Quick example\n\n\n\n```rust\n\nuse scriptful::prelude::*;\n\nuse scriptful::core::value::Value::*;\n\n\n\n// You can define your own operators.\n\n#[derive(Debug, PartialEq, Eq)]\n\nenum MyOperator {\n\n Add,\n\n Equal,\n\n Sub,\n\n}\n\n\n\n// An operator system decides what to do with the stack when each operator is applied on it.\n\nfn my_operator_system(stack: &mut Stack, operator: &MyOperator) {\n\n match operator {\n\n MyOperator::Add => {\n\n let a = stack.pop();\n\n let b = stack.pop();\n\n stack.push(a + b);\n\n }\n\n MyOperator::Equal => {\n\n let a = stack.pop();\n\n let b = stack.pop();\n\n stack.push(Boolean(a == b));\n\n }\n\n MyOperator::Sub => {\n\n let a = stack.pop();\n\n let b = stack.pop();\n\n stack.push(a - b);\n\n }\n\n }\n\n}\n\n\n\n// Instantiate the machine with a reference to your operator system.\n\nlet mut machine = Machine::new(&my_operator_system);\n\n\n\n// Run a script that simply adds 1 and 2.\n\nlet result = machine.run_script(&[\n\n Item::Value(Integer(1)),\n\n Item::Value(Integer(2)),\n\n Item::Operator(MyOperator::Add),\n\n]);\n\n\n\n// The result should unsurprisingly be 3.\n\nassert_eq!(result, Some(&Integer(3)));\n\n```\n\n\n\n## Known limitations\n\n\n\n- [Stacks][Stack] are currently implemented using a fixed-length, actually stack-allocated vectors using [smallvec].\n\nThus the `main` sub-stack is limited to 64 values, and the `alt` sub-stack can only hold up to 8.\n\n- _Beware of unwraps!_ This is a proof-of-concept and it is modelled to panic upon errors.\n\nMaking the library safe for production usage is in the near horizon though.\n\n- The possible value types that can be pushed into the [Stack] is not generic nor customizable.\n\nSuch feature will only be added if someone actually requests it.\n\n\n\n## License\n\n\n\nScriptful is distributed under the terms of both the MIT license and the Apache License (Version 2.0).\n\n\n\nSee [LICENSE-APACHE] and [LICENSE-MIT], and [COPYRIGHT] for details.\n\n\n\n[Forth]: https://en.wikipedia.org/wiki/Forth_(programming_language)\n\n[BitcoinScript]: https://en.bitcoin.it/wiki/Script\n\n[LIFO]: https://en.wikipedia.org/wiki/Stack_(abstract_data_type)\n\n[Stack]: https://docs.rs/scriptful/latest/scriptful/core/stack/struct.Stack.html\n\n[Item]: https://docs.rs/scriptful/latest/scriptful/core/item/enum.Item.html\n\n[Operator system]: https://docs.rs/scriptful/latest/scriptful/op_systems/\n\n[Script]: https://docs.rs/scriptful/latest/scriptful/core/type.Script.html\n\n[Machine]: https://docs.rs/scriptful/latest/scriptful/core/machine/struct.Machine.html\n\n[smallvec]: https://crates.io/crates/smallvec\n\n[Value]: core/value/enum.Value.html\n\n[enum]: https://doc.rust-lang.org/std/keyword.enum.html\n\n[LICENSE-APACHE]: LICENSE-APACHE\n\n[LICENSE-MIT]: LICENSE-MIT\n", "file_path": "README.md", "rank": 19, "score": 8.546242347165723 }, { "content": "use crate::prelude::*;\n\n\n\n/// A convenient wrapper around [`Stack`][Stack] providing multiple operation methods, i.e.\n\n/// xecuting scripts by evaluating operators and pushing values into the stack.\n\n///\n\n/// This is the preferred way to interact with [`Stack`s][Stack], as they do not support operators,\n\n/// [`Item`s][Item], and other abstractions.\n\n///\n\n/// [Stack]: ../stack/struct.Stack.html\n\n/// [Item]: ../item/enum.Item.html\n\npub struct Machine<'a, Op, Val>\n\nwhere\n\n Val: core::fmt::Debug + core::cmp::PartialEq,\n\n{\n\n op_sys: &'a dyn Fn(&mut Stack<Val>, &Op),\n\n stack: Stack<Val>,\n\n}\n\n\n\nimpl<'a, Op, Val> Machine<'a, Op, Val>\n\nwhere\n", "file_path": "src/core/machine.rs", "rank": 20, "score": 8.431456289977337 }, { "content": " any_other => any_other,\n\n }),\n\n Command::Close => {}\n\n }\n\n}\n\n\n\n#[cfg(test)]\n\nmod tests {\n\n use crate::op_systems::pokemon::{pokemon_op_sys, Command::*, Creature::*};\n\n use crate::prelude::*;\n\n\n\n #[test]\n\n fn test_evolution() {\n\n // Let's create an evolution machine\n\n let mut machine = Machine::new(&pokemon_op_sys);\n\n\n\n // You have a Charmander\n\n let my_creature = Charmander;\n\n\n\n // Put the Charmander into the machine\n", "file_path": "src/op_systems/pokemon.rs", "rank": 21, "score": 7.137685749696166 }, { "content": "use crate::core::value::Value;\n\n\n\n/// An `Item` is each one of the entities that conform a [`Script`][Script].\n\n///\n\n/// In other words, a [`Script`][Script] is no more than an array of `Item`s in the likes of\n\n/// `[Item<Op, Val>]`.\n\n///\n\n/// `Ìtem` does not implement any methods other than implementations of some traits from the\n\n/// [`core`][core] crate.\n\n///\n\n/// [Script]: ../type.Script.html\n\n/// [core]: https://doc.rust-lang.org/nightly/core/\n\n#[derive(Debug)]\n\npub enum Item<Op, Val = Value>\n\nwhere\n\n Op: core::fmt::Debug + core::cmp::Eq,\n\n Val: core::fmt::Debug + core::cmp::PartialEq,\n\n{\n\n /// An operator code, either a variant of an user-defined [`enum`][enum] containing different\n\n /// operator identifiers, or any of the ones found in the [`op_systems`][op_systems] module.\n", "file_path": "src/core/item.rs", "rank": 22, "score": 6.694371148578853 }, { "content": " pub fn operate(&mut self, item: &Item<Op, Val>) -> Option<&Val> {\n\n match item {\n\n Item::Operator(operator) => (self.op_sys)(&mut self.stack, operator),\n\n Item::Value(value) => self.stack.push((*value).clone()),\n\n }\n\n\n\n self.stack.topmost()\n\n }\n\n\n\n /// Evaluates a [`Script`][Script] in the context of a `Machine`.\n\n ///\n\n /// # Panics\n\n ///\n\n /// Operating on a `Machine` that has an empty [`Stack`][Stack] can cause a panic if any of the\n\n /// [`Item`s][Item] in the [`Script`][Script] is an operator that tries to pop from it.\n\n ///\n\n /// # Examples\n\n ///\n\n /// ```rust\n\n /// use scriptful::prelude::*;\n", "file_path": "src/core/machine.rs", "rank": 23, "score": 6.665420470509204 }, { "content": "# ![Scriptful](logo.png)\n\n\n\n[![Build Status](https://travis-ci.com/aesedepece/scriptful.svg?branch=master)](https://travis-ci.com/aesedepece/scriptful)\n\n[![Crate](https://img.shields.io/crates/v/scriptful.svg)](https://crates.io/crates/scriptful)\n\n[![Docs](https://docs.rs/scriptful/badge.svg)](https://docs.rs/scriptful)\n\n![License](https://img.shields.io/crates/l/scriptful.svg)\n\n\n\n___Scriptful_ is a minimalist `no_std` stack machine for interpreting scripts written with domain specific interpreted languages.__\n\n\n\nThis library is heavily inspired by the [Forth] programming language and [Script][BitcoinScript] (the scripting language in Bitcoin).\n\n\n\n## General design\n\n\n\nThe whole library is built around these concepts:\n\n\n\n- __[Stack]__: an ordered sequence of values that can be operated in a [LIFO]-alike way.\n\n- __[Item]__: either a `Value` (a piece of data to be pushed into the stack) or an `Operator` (the descriptor for an action that operates on the topmost items in the stack).\n\n- __Type system__: an [`enum`][enum] whose variants are all the possible data types allowed in a [`Stack`][Stack].\n\n- __[Operator system]__: a function that decides how each operator will mutate a given stack.\n\n- __[Script]__: an ordered sequence of items (values and operators) that can be passed to an operator system for operating on a given stack.\n\n- __[Machine]__: a convenient wrapper around a stack that enables multiple modes of operation.\n\n\n\nUsing this library is as easy as:\n\n\n\n1. Defining your own set of operators, or using any of the ones that come bundled in the [`op_systems`][Operator system] module.\n\n2. Defining your own type system, or using the [`Value`][Value] type system that comes bundled in the [`core::value`][Value] module.\n\n3. Defining your own [operator system][Operator system] function, or using any of the ones that come bundled in the [`op_systems`][Operator system] module.\n\n4. Instantiating a [machine][Machine] with a reference to your operator system.\n\n5. Composing a [script][Script] and running it in the machine.\n\n\n", "file_path": "README.md", "rank": 24, "score": 6.636600267342091 }, { "content": "use crate::prelude::*;\n\n\n\n/// Frequently used mathematical operators.\n\n#[derive(Debug, PartialEq, Eq)]\n\npub enum MathOperator {\n\n /// Addition of two numbers (`a + b`).\n\n Add,\n\n /// Equivalence of two numbers (`a == b`).\n\n Equal,\n\n /// Multiplication of two numbers (`a * b`)\n\n Mul,\n\n /// Negation of one number (`-a`).\n\n Not,\n\n /// Subtraction of two numbers (`a - b`).\n\n Sub,\n\n}\n\n\n\n/// A simple operator system that decides how each of the variants of [`MathOperator`][MathOperator]\n\n/// trigger push and pulls on the [`Stack`][Stack] inside a [`Machine`][Machine].\n\n///\n\n/// [MathOperator]: enum.MathOperator.html\n\n/// [Stack]: ../../core/stack/struct.Stack.html\n\n/// [Machine]: ../../core/machine/struct.Machine.html\n", "file_path": "src/op_systems/simple_math.rs", "rank": 25, "score": 6.347745515817769 }, { "content": " ///\n\n /// # Panics\n\n /// Panics if there are no values left in the `main` stack.\n\n ///\n\n /// # Examples\n\n ///\n\n /// ```rust\n\n /// use scriptful::prelude::*;\n\n /// use scriptful::core::value::Value::*;\n\n ///\n\n /// let value = Integer(i128::default());\n\n /// let mut stack = Stack::default();\n\n /// stack.push(value.clone());\n\n /// let popped = stack.pop();\n\n ///\n\n /// assert_eq!(value, popped);\n\n /// ```\n\n pub fn pop(&mut self) -> Val {\n\n self.main.pop().unwrap()\n\n }\n", "file_path": "src/core/stack.rs", "rank": 26, "score": 6.277073262977257 }, { "content": " /// // Make sure the stack is initialized to be empty.\n\n /// assert_eq!(machine.stack_length(), 0);\n\n /// ```\n\n pub fn new(op_sys: &'a dyn Fn(&mut Stack<Val>, &Op)) -> Self {\n\n Self {\n\n op_sys,\n\n stack: Stack::<Val>::default(),\n\n }\n\n }\n\n\n\n /// The simplest way to make a `Machine` evaluate a single [`Item`][Item], be it a `Value` or\n\n /// `Operator`.\n\n ///\n\n /// Note that the preferred way to evaluate multiple [`Item`s][Item] at once is through the\n\n /// [`run_script`][run_script] method, which instead of single [`Item`s][Item] takes a\n\n /// [`Script`][Script], i.e. an array of [`Item`s][Item].\n\n ///\n\n /// # Panics\n\n ///\n\n /// Operating on a `Machine` that has an empty [`Stack`][Stack] can cause a panic if the\n", "file_path": "src/core/machine.rs", "rank": 27, "score": 6.243159116875114 }, { "content": " /// [Script]: ../type.Script.html\n\n /// [Stack]: ../stack/struct.Stack.html\n\n /// [Item]: ../item/enum.Item.html\n\n pub fn run_script(&mut self, script: &Script<Op, Val>) -> Option<&Val> {\n\n for item in script {\n\n self.operate(item);\n\n }\n\n\n\n self.stack.topmost()\n\n }\n\n\n\n /// Returns the number of [`Value`s][Value] currently in the [`Stack`][Stack].\n\n ///\n\n /// # Examples\n\n ///\n\n /// ```rust\n\n /// use scriptful::prelude::*;\n\n /// use scriptful::core::value::Value::*;\n\n /// use scriptful::op_systems::simple_math::*;\n\n ///\n", "file_path": "src/core/machine.rs", "rank": 28, "score": 6.127665344434986 }, { "content": "\n\n /// Similar to [`pop`][pop], but instead of returning the popped value, it pushes it to the `alt` sub-stack.\n\n ///\n\n /// # Panics\n\n /// Panics if there are no values left in the `main` stack.\n\n ///\n\n /// [pop]: #method.pop\n\n pub fn pop_into_alt(&mut self) {\n\n self.alt.push(self.main.pop().unwrap())\n\n }\n\n\n\n /// Puts a value on top of the stack.\n\n ///\n\n /// # Examples\n\n ///\n\n /// ```rust\n\n /// use scriptful::prelude::*;\n\n /// use scriptful::core::value::Value::*;\n\n ///\n\n /// let value = Integer(i128::default());\n", "file_path": "src/core/stack.rs", "rank": 29, "score": 6.110256721041773 }, { "content": " /// # Examples\n\n ///\n\n /// ```rust\n\n /// use scriptful::prelude::*;\n\n /// use scriptful::core::value::Value::*;\n\n ///\n\n /// let mut stack = Stack::default();\n\n /// assert_eq!(stack.length(), 0);\n\n ///\n\n /// stack.push(Integer(i128::default()));\n\n /// assert_eq!(stack.length(), 1);\n\n ///\n\n /// stack.pop();\n\n /// assert_eq!(stack.length(), 0);\n\n /// ```\n\n pub fn length(&self) -> usize {\n\n self.main.len()\n\n }\n\n\n\n /// Removes the topmost value in the `main` sub-stack and returns it.\n", "file_path": "src/core/stack.rs", "rank": 30, "score": 5.885989153578513 }, { "content": "//! 3. Defining your own [operator system][Operator system] function, or using any of the ones that come bundled in the [`op_systems`][Operator system] module.\n\n//! 4. Instantiating a [machine][Machine] with a reference to your operator system.\n\n//! 5. Composing a [script][Script] and running it in the machine.\n\n//!\n\n//! # Quick example\n\n//!\n\n//! ```rust\n\n//! use scriptful::prelude::*;\n\n//! use scriptful::core::value::Value::*;\n\n//!\n\n//! // You can define your own operators.\n\n//! #[derive(Debug, PartialEq, Eq)]\n\n//! enum MyOperator {\n\n//! Add,\n\n//! Equal,\n\n//! Sub,\n\n//! }\n\n//!\n\n//! // An operator system decides what to do with the stack when each operator is applied on it.\n\n//! fn my_operator_system(stack: &mut Stack, operator: &MyOperator) {\n", "file_path": "src/lib.rs", "rank": 31, "score": 5.423434736389365 }, { "content": "//! A sample stack machine that showcases how to use custom operators on custom types, and at the\n\n//! same time, doubles as an example of how to implement a state machine.\n\n//!\n\n//! Put any [`Creature`][Creature] into the machine, enter one of the [`Command`s][Command], and\n\n//! watch your creature either evolute or devolute!\n\n//!\n\n//! [Creature]: enum.Creature.html\n\n//! [Command]: enum.Command.html\n\n\n\nuse crate::prelude::*;\n\n\n\n/// Simply the first nine Pokémon.\n\n#[derive(Clone, Debug, PartialEq)]\n\npub enum Creature {\n\n Bulbasaur,\n\n Ivysaur,\n\n Venusaur,\n\n Charmander,\n\n Charmaleon,\n\n Charizard,\n", "file_path": "src/op_systems/pokemon.rs", "rank": 32, "score": 5.218439699053574 }, { "content": "//! ___Scriptful_ is a minimalist `no_std` stack machine for interpreting scripts written using domain specific interpreted languages.__\n\n//!\n\n//! This library is heavily inspired by the [Forth] programming language and [Script][BitcoinScript]\n\n//! (the scripting language in Bitcoin).\n\n//!\n\n//! # General design\n\n//!\n\n//! The whole library is built around these concepts:\n\n//!\n\n//! - __[Stack]__: an ordered sequence of values that can be operated in a [LIFO]-alike way.\n\n//! - __[Item]__: either a `Value` (a piece of data to be pushed into the stack) or an `Operator` (the descriptor for an action that operates on the topmost items in the stack).\n\n//! - __Type system__: an [`enum`][enum] whose variants are all the possible data types allowed in a [`Stack`][Stack].\n\n//! - __[Operator system]__: a function that decides how each operator will mutate a given stack.\n\n//! - __[Script]__: an ordered sequence of items (values and operators) that can be passed to an operator system for operating on a given stack.\n\n//! - __[Machine]__: a convenient wrapper around a stack that enables multiple modes of operation.\n\n//!\n\n//! Using this library is as easy as:\n\n//!\n\n//! 1. Defining your own set of operators, or using any of the ones that come bundled in the [`op_systems`][Operator system] module.\n\n//! 2. Defining your own type system, or using the [`Value`][Value] type system that comes bundled in the [`core::value`][Value] module.\n", "file_path": "src/lib.rs", "rank": 33, "score": 5.201951344310807 }, { "content": " ///\n\n /// [enum]: https://doc.rust-lang.org/std/keyword.enum.html\n\n /// [op_systems]: ../../op_systems/\n\n Operator(Op),\n\n /// A value, either a variant of an user-defined [`enum`][enum] representing a type system, or\n\n /// an instance of any of the variants of [`Value`][Value], i.e. [`Boolean`][Boolean],\n\n /// [`Float`][Float], [`Integer`][Integer] or [`String`][String].\n\n ///\n\n /// [enum]: https://doc.rust-lang.org/std/keyword.enum.html\n\n /// [Value]: ../value/enum.Value.html\n\n /// [Boolean]: ../value/enum.Value.html#variant.Boolean\n\n /// [Float]: ../value/enum.Value.html#variant.Float\n\n /// [Integer]: ../value/enum.Value.html#variant.Integer\n\n /// [String]: ../value/enum.Value.html#variant.String\n\n Value(Val),\n\n}\n\n\n\nimpl<Op, Val> PartialEq for Item<Op, Val>\n\nwhere\n\n Op: core::fmt::Debug + core::cmp::Eq,\n", "file_path": "src/core/item.rs", "rank": 34, "score": 5.172574591452339 }, { "content": "//! An ordered sequence of values that can be operated in a [LIFO]-alike way.\n\n//!\n\n//! This module provides the [`Stack`][Stack] struct which in turn is the core of the [`Machine`][Machine] abstraction.\n\n//!\n\n//! For more details on [`Stack`][Stack], how it works and which methods does it provide, please go to the [`struct Stack` documentation][Stack].\n\n//!\n\n//! [LIFO]: https://en.wikipedia.org/wiki/Stack_(abstract_data_type)\n\n//! [Stack]: core/stack/struct.Stack.html\n\n//! [Script]: core/type.Script.html\n\n//! [Machine]: core/machine/\n\n\n\nuse crate::core::value::Value;\n\nuse smallvec::SmallVec;\n\n\n\n/// An ordered sequence of values that can be operated in a [LIFO]-alike way.\n\n///\n\n/// Every `Stack` actually comprises two sequences of values: the `main` sub-stack and the `alt` sub-stack.\n\n///\n\n/// As its name indicates, the `main` sub-stack is the one you operate by default.\n\n/// That is, the `alt` sub-stack cannot be operated directly — you can only move values between both sub-stacks with the [`pop_into_alt`][pop_into_alt] and [`push_from_alt`][push_from_alt] methods.\n", "file_path": "src/core/stack.rs", "rank": 35, "score": 4.770073792675788 }, { "content": " }\n\n}\n\n\n\n/// Debugging of `Machine` only shows the internal [`Stack`][Stack], but not the operator system.\n\n///\n\n/// The explanation for this is straightforward: how do you print a dynamic reference to a function?\n\n///\n\n/// [Stack]: ../stack/struct.Stack.html\n\nimpl<'a, Op, Val> core::fmt::Debug for Machine<'a, Op, Val>\n\nwhere\n\n Val: core::fmt::Debug + core::cmp::PartialEq,\n\n{\n\n fn fmt(&self, f: &mut core::fmt::Formatter) -> Result<(), core::fmt::Error> {\n\n write!(f, \"{:?}\", self.stack)\n\n }\n\n}\n", "file_path": "src/core/machine.rs", "rank": 36, "score": 4.470164000250923 }, { "content": " /// [`Item`][Item] is an operator that tries to pop from it.\n\n ///\n\n /// # Examples\n\n ///\n\n /// ```rust\n\n /// use scriptful::prelude::*;\n\n /// use scriptful::core::value::Value::*;\n\n /// use scriptful::op_systems::simple_math::*;\n\n ///\n\n /// // Instantiate the machine with a reference to your operator system, or any of the ones in\n\n /// // the `op_systems` module. \n\n /// let mut machine = Machine::new(&simple_math_op_sys);\n\n ///\n\n /// // Operating a `Value::Integer(1)` should simply push it into the stack.\n\n /// let result = machine.operate(&Item::Value(Integer(1)));\n\n /// // Make sure the value gets pushed.\n\n /// assert_eq!(result, Some(&Integer(1)));\n\n /// // The length of the stack should be 1.\n\n /// assert_eq!(machine.stack_length(), 1);\n\n ///\n", "file_path": "src/core/machine.rs", "rank": 37, "score": 4.3797018614610135 }, { "content": " /// let mut stack = Stack::default();\n\n /// stack.push(value.clone());\n\n /// let topmost = stack.topmost();\n\n ///\n\n /// assert_eq!(topmost, Some(&value));\n\n /// ```\n\n pub fn push(&mut self, item: Val) {\n\n self.main.push(item)\n\n }\n\n\n\n /// Similar to [`push`][push], but instead of receiving the value to be pushed as an argument, it pops it from the `alt` sub-stack.\n\n ///\n\n /// [push]: #method.push\n\n pub fn push_from_alt(&mut self) {\n\n self.main.push(self.alt.pop().unwrap())\n\n }\n\n\n\n /// Returns a reference to the last value in the `main` sub-stack.\n\n ///\n\n /// # Examples\n", "file_path": "src/core/stack.rs", "rank": 38, "score": 4.297072276638024 }, { "content": " /// use scriptful::core::value::Value::*;\n\n /// use scriptful::op_systems::simple_math::*;\n\n ///\n\n /// // Instantiate the machine with a reference to your operator system, or any of the ones in\n\n /// // the `op_systems` module.\n\n /// let mut machine = Machine::new(&simple_math_op_sys);\n\n ///\n\n /// // Run a script that simply adds 1 and 2.\n\n /// let result = machine.run_script(&[\n\n /// Item::Value(Integer(1)),\n\n /// Item::Value(Integer(2)),\n\n /// Item::Operator(MathOperator::Add),\n\n /// ]);\n\n ///\n\n /// // The result should unsurprisingly be 3.\n\n /// assert_eq!(result, Some(&Integer(3)));\n\n /// // The final length of the stack should be 1.\n\n /// assert_eq!(machine.stack_length(), 1);\n\n /// ```\n\n ///\n", "file_path": "src/core/machine.rs", "rank": 39, "score": 4.033196246236581 }, { "content": " /// // Instantiate the machine with a reference to your operator system, or any of the ones in\n\n /// // the `op_systems` module.\n\n /// let mut machine = Machine::new(&simple_math_op_sys);\n\n ///\n\n /// // Run a script that simply pushes 4 values into the stack.\n\n /// machine.run_script(&[\n\n /// Item::Value(Boolean(true)),\n\n /// Item::Value(Float(3.141592)),\n\n /// Item::Value(Integer(1337)),\n\n /// Item::Value(String(\"foo\"))\n\n /// ]);\n\n ///\n\n /// // The final length of the stack should be 4.\n\n /// assert_eq!(machine.stack_length(), 4);\n\n /// ```\n\n ///\n\n /// [Value]: ../value/enum.Value.html\n\n /// [Stack]: ../stack/struct.Stack.html\n\n pub fn stack_length(&self) -> usize {\n\n self.stack.length()\n", "file_path": "src/core/machine.rs", "rank": 40, "score": 3.884564041335205 }, { "content": " Op: core::fmt::Debug + core::cmp::Eq,\n\n Val: core::fmt::Debug + core::cmp::PartialEq + core::clone::Clone,\n\n{\n\n /// A simple factory that helps constructing a `Machine` around a existing operator system, be\n\n /// it user defined or any of the ones in the [`op_systems`][op_systems] module.\n\n ///\n\n /// This method initializes the internal stack to be empty.\n\n ///\n\n /// [op_systems]: ../../op_systems/\n\n ///\n\n /// # Examples\n\n ///\n\n /// ```rust\n\n /// use scriptful::prelude::*;\n\n /// use scriptful::op_systems::simple_math::simple_math_op_sys;\n\n ///\n\n /// // Instantiate the machine with a reference to your operator system, or any of the ones in\n\n /// // the `op_systems` module.\n\n /// let machine = Machine::new(&simple_math_op_sys);\n\n ///\n", "file_path": "src/core/machine.rs", "rank": 41, "score": 3.8469822877485838 }, { "content": "\n\n assert_eq!(op_item1, op_item2);\n\n\n\n let val_item1: Item<u8> = Value(Integer(i128::default()));\n\n let val_item2: Item<u8> = Value(Integer(i128::default()));\n\n\n\n assert_eq!(val_item1, val_item2);\n\n }\n\n\n\n #[test]\n\n fn test_ne() {\n\n let op_item1: Item<u8> = Operator(u8::default());\n\n let op_item2: Item<u8> = Operator(u8::default() + 1);\n\n\n\n assert_ne!(op_item1, op_item2);\n\n\n\n let val_item1: Item<u8> = Value(Integer(i128::default()));\n\n let val_item2: Item<u8> = Value(Integer(i128::default() + 1));\n\n\n\n assert_ne!(val_item1, val_item2);\n\n\n\n assert_ne!(op_item1, val_item1);\n\n assert_ne!(op_item1, val_item2);\n\n assert_ne!(op_item2, val_item1);\n\n assert_ne!(op_item2, val_item2);\n\n }\n\n}\n", "file_path": "src/core/item.rs", "rank": 42, "score": 3.7256198714753452 }, { "content": "//! let mut machine = Machine::new(&my_operator_system);\n\n//!\n\n//! // Run a script that simply adds 1 and 2.\n\n//! let result = machine.run_script(&[\n\n//! Item::Value(Integer(1)),\n\n//! Item::Value(Integer(2)),\n\n//! Item::Operator(MyOperator::Add),\n\n//! ]);\n\n//!\n\n//! // The result should unsurprisingly be 3.\n\n//! assert_eq!(result, Some(&Integer(3)));\n\n//! ```\n\n//!\n\n//! # Known limitations\n\n//!\n\n//! - [Stacks][Stack] are currently implemented using a fixed-length, actually stack-allocated vectors using [smallvec].\n\n//! Thus the `main` sub-stack is limited to 64 values, and the `alt` sub-stack can only hold up to 8.\n\n//! - _Beware of unwraps!_ This is a proof-of-concept and it is modelled to panic upon errors.\n\n//! Making the library safe for production usage is in the near horizon though.\n\n//!\n", "file_path": "src/lib.rs", "rank": 43, "score": 3.655694652077673 }, { "content": " Squirtle,\n\n Wartortle,\n\n Blastoise,\n\n}\n\n\n\n/// The different commands that an evolution / devolution machine can understand.\n\n#[derive(Debug, PartialEq, Eq)]\n\npub enum Command {\n\n /// Evolute a creature into the next stage in its evolution chart.\n\n Evolute,\n\n /// Revert a creature back to its previous stage in its evolution chart.\n\n Devolute,\n\n /// Finish operating the evolution / devolution machine.\n\n Close,\n\n}\n\n\n\n/// The main function that tells which creatures evolute and devolute into which other creatures.\n", "file_path": "src/op_systems/pokemon.rs", "rank": 44, "score": 3.428142949016409 }, { "content": " /// // Operating a `Value::Integer(2)` should simply push it into the stack.\n\n /// let result = machine.operate(&Item::Value(Integer(2)));\n\n /// // Make sure the value gets pushed.\n\n /// assert_eq!(result, Some(&Integer(2)));\n\n /// // The length of the stack should be 2.\n\n /// assert_eq!(machine.stack_length(), 2);\n\n ///\n\n /// // Operating an `MathOperator::Add` should pop the two topmost values in the stack, add them\n\n /// // together, and push the result back into the stack.\n\n /// let result = machine.operate(&Item::Operator(MathOperator::Add));\n\n /// // Make sure the result is 3.\n\n /// assert_eq!(result, Some(&Integer(3)));\n\n /// // The final length of the stack should be 1 again.\n\n /// assert_eq!(machine.stack_length(), 1);\n\n /// ```\n\n ///\n\n /// [Item]: ../item/enum.Item.html\n\n /// [run_script]: #method.run_script\n\n /// [Script]: ../type.Script.html\n\n /// [Stack]: ../stack/struct.Stack.html\n", "file_path": "src/core/machine.rs", "rank": 45, "score": 3.3576387550616955 }, { "content": "//! # License\n\n//!\n\n//! Scriptful is distributed under the terms of both the MIT license and the Apache License (Version 2.0).\n\n//!\n\n//! See [LICENSE-APACHE] and [LICENSE-MIT], and [COPYRIGHT] for details.\n\n//!\n\n//! [Forth]: https://en.wikipedia.org/wiki/Forth_(programming_language)\n\n//! [BitcoinScript]: https://en.bitcoin.it/wiki/Script\n\n//! [LIFO]: https://en.wikipedia.org/wiki/Stack_(abstract_data_type)\n\n//! [Stack]: core/stack/struct.Stack.html\n\n//! [Item]: core/item/enum.Item.html\n\n//! [Operator system]: op_systems/\n\n//! [Script]: core/type.Script.html\n\n//! [Machine]: core/machine/struct.Machine.html\n\n//! [Value]: core/value/enum.Value.html\n\n//! [enum]: https://doc.rust-lang.org/std/keyword.enum.html\n\n//! [LICENSE-APACHE]: https://github.com/aesedepece/scriptful/blob/master/LICENSE-APACHE\n\n//! [LICENSE-MIT]: https://github.com/aesedepece/scriptful/blob/master/LICENSE-MIT\n\n//! [COPYRIGHT]: https://github.com/aesedepece/scriptful/blob/master/COPYRIGHT\n\n//! [smallvec]: https://crates.io/crates/smallvec\n", "file_path": "src/lib.rs", "rank": 46, "score": 2.7006973311120106 }, { "content": "\n\n // What if we try to evolute Charizard?\n\n let result = machine.operate(&Item::Operator(Evolute)).unwrap();\n\n\n\n // Good try... but it should still be a Charizard\n\n assert_eq!(result, &Charizard);\n\n\n\n // Ok, we already got Charizard, let's just close the machine and make sure we don't leave\n\n // any creature behind\n\n machine.operate(&Item::Operator(Close));\n\n assert_eq!(machine.stack_length(), 0);\n\n }\n\n\n\n #[test]\n\n fn test_devolution() {\n\n // Let's create a devolution machine\n\n let mut machine = Machine::new(&pokemon_op_sys);\n\n\n\n // This time you have a Blastoise\n\n let my_creature = Blastoise;\n", "file_path": "src/op_systems/pokemon.rs", "rank": 47, "score": 2.298468195149985 }, { "content": " let machine = &mut Machine::new(&simple_math_op_sys);\n\n\n\n let result = machine\n\n .run_script(&[\n\n Value(Integer(1)),\n\n Value(Integer(1)),\n\n Operator(MathOperator::Add),\n\n Value(Integer(2)),\n\n Operator(MathOperator::Equal),\n\n ])\n\n .unwrap();\n\n\n\n assert_eq!(result, &Boolean(true));\n\n }\n\n}\n", "file_path": "src/op_systems/simple_math.rs", "rank": 48, "score": 2.1858462402996643 }, { "content": "//! match operator {\n\n//! MyOperator::Add => {\n\n//! let a = stack.pop();\n\n//! let b = stack.pop();\n\n//! stack.push(a + b);\n\n//! }\n\n//! MyOperator::Equal => {\n\n//! let a = stack.pop();\n\n//! let b = stack.pop();\n\n//! stack.push(Boolean(a == b));\n\n//! }\n\n//! MyOperator::Sub => {\n\n//! let a = stack.pop();\n\n//! let b = stack.pop();\n\n//! stack.push(a - b);\n\n//! }\n\n//! }\n\n//! }\n\n//!\n\n//! // Instantiate the machine with a reference to your operator system.\n", "file_path": "src/lib.rs", "rank": 49, "score": 2.0494903530173065 }, { "content": "\n\n // Put the Blastoise into the machine\n\n let result = machine.operate(&Item::Value(my_creature)).unwrap();\n\n\n\n // There should obviously be a Blastoise in the machine\n\n assert_eq!(result, &Blastoise);\n\n // And there should be nothing else in the machine\n\n assert_eq!(machine.stack_length(), 1);\n\n\n\n // Let's make it devolute!\n\n let result = machine.operate(&Item::Operator(Devolute)).unwrap();\n\n\n\n // Blastoise should have turned into Wartortle!\n\n assert_eq!(result, &Wartortle);\n\n // And again there should be only 1 creature in the machine\n\n assert_eq!(machine.stack_length(), 1);\n\n\n\n // Let's devolute it again\n\n let result = machine.operate(&Item::Operator(Devolute)).unwrap();\n\n\n", "file_path": "src/op_systems/pokemon.rs", "rank": 50, "score": 1.2154172185129104 }, { "content": " let result = machine.operate(&Item::Value(my_creature)).unwrap();\n\n\n\n // There should obviously be a Charmander in the machine\n\n assert_eq!(result, &Charmander);\n\n // And there should be nothing else in the machine\n\n assert_eq!(machine.stack_length(), 1);\n\n\n\n // Let's make it evolute!\n\n let result = machine.operate(&Item::Operator(Evolute)).unwrap();\n\n\n\n // Charmander should have turned into Charmaleon!\n\n assert_eq!(result, &Charmaleon);\n\n // And again there should be only 1 creature in the machine\n\n assert_eq!(machine.stack_length(), 1);\n\n\n\n // Let's evolute it again\n\n let result = machine.operate(&Item::Operator(Evolute)).unwrap();\n\n\n\n // Meet our blazing Charizard!\n\n assert_eq!(result, &Charizard);\n", "file_path": "src/op_systems/pokemon.rs", "rank": 51, "score": 1.1781812511540508 } ]
Rust
src/emac0/mmctxim.rs
tirust/msp432e4
479d52cb87a757f77406e1f314ea8acfba70f675
#[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::MMCTXIM { #[doc = r"Modifies the contents of the register"] #[inline(always)] pub fn modify<F>(&self, f: F) where for<'w> F: FnOnce(&R, &'w mut W) -> &'w mut W, { let bits = self.register.get(); self.register.set(f(&R { bits }, &mut W { bits }).bits); } #[doc = r"Reads the contents of the register"] #[inline(always)] pub fn read(&self) -> R { R { bits: self.register.get(), } } #[doc = r"Writes to the register"] #[inline(always)] pub fn write<F>(&self, f: F) where F: FnOnce(&mut W) -> &mut W, { self.register.set( f(&mut W { bits: Self::reset_value(), }) .bits, ); } #[doc = r"Reset value of the register"] #[inline(always)] pub const fn reset_value() -> u32 { 0 } #[doc = r"Writes the reset value to the register"] #[inline(always)] pub fn reset(&self) { self.register.set(Self::reset_value()) } } #[doc = r"Value of the field"] pub struct EMAC_MMCTXIM_GBFR { bits: bool, } impl EMAC_MMCTXIM_GBFR { #[doc = r"Value of the field as raw bits"] #[inline(always)] pub fn bit(&self) -> bool { self.bits } #[doc = r"Returns `true` if the bit is clear (0)"] #[inline(always)] pub fn bit_is_clear(&self) -> bool { !self.bit() } #[doc = r"Returns `true` if the bit is set (1)"] #[inline(always)] pub fn bit_is_set(&self) -> bool { self.bit() } } #[doc = r"Proxy"] pub struct _EMAC_MMCTXIM_GBFW<'a> { w: &'a mut W, } impl<'a> _EMAC_MMCTXIM_GBFW<'a> { #[doc = r"Sets the field bit"] #[inline(always)] pub fn set_bit(self) -> &'a mut W { self.bit(true) } #[doc = r"Clears the field bit"] #[inline(always)] pub fn clear_bit(self) -> &'a mut W { self.bit(false) } #[doc = r"Writes raw bits to the field"] #[inline(always)] pub fn bit(self, value: bool) -> &'a mut W { self.w.bits &= !(1 << 1); self.w.bits |= ((value as u32) & 1) << 1; self.w } } #[doc = r"Value of the field"] pub struct EMAC_MMCTXIM_SCOLLGFR { bits: bool, } impl EMAC_MMCTXIM_SCOLLGFR { #[doc = r"Value of the field as raw bits"] #[inline(always)] pub fn bit(&self) -> bool { self.bits } #[doc = r"Returns `true` if the bit is clear (0)"] #[inline(always)] pub fn bit_is_clear(&self) -> bool { !self.bit() } #[doc = r"Returns `true` if the bit is set (1)"] #[inline(always)] pub fn bit_is_set(&self) -> bool { self.bit() } } #[doc = r"Proxy"] pub struct _EMAC_MMCTXIM_SCOLLGFW<'a> { w: &'a mut W, } impl<'a> _EMAC_MMCTXIM_SCOLLGFW<'a> { #[doc = r"Sets the field bit"] #[inline(always)] pub fn set_bit(self) -> &'a mut W { self.bit(true) } #[doc = r"Clears the field bit"] #[inline(always)] pub fn clear_bit(self) -> &'a mut W { self.bit(false) } #[doc = r"Writes raw bits to the field"] #[inline(always)] pub fn bit(self, value: bool) -> &'a mut W { self.w.bits &= !(1 << 14); self.w.bits |= ((value as u32) & 1) << 14; self.w } } #[doc = r"Value of the field"] pub struct EMAC_MMCTXIM_MCOLLGFR { bits: bool, } impl EMAC_MMCTXIM_MCOLLGFR { #[doc = r"Value of the field as raw bits"] #[inline(always)] pub fn bit(&self) -> bool { self.bits } #[doc = r"Returns `true` if the bit is clear (0)"] #[inline(always)] pub fn bit_is_clear(&self) -> bool { !self.bit() } #[doc = r"Returns `true` if the bit is set (1)"] #[inline(always)] pub fn bit_is_set(&self) -> bool { self.bit() } } #[doc = r"Proxy"] pub struct _EMAC_MMCTXIM_MCOLLGFW<'a> { w: &'a mut W, } impl<'a> _EMAC_MMCTXIM_MCOLLGFW<'a> { #[doc = r"Sets the field bit"] #[inline(always)] pub fn set_bit(self) -> &'a mut W { self.bit(true) } #[doc = r"Clears the field bit"] #[inline(always)] pub fn clear_bit(self) -> &'a mut W { self.bit(false) } #[doc = r"Writes raw bits to the field"] #[inline(always)] pub fn bit(self, value: bool) -> &'a mut W { self.w.bits &= !(1 << 15); self.w.bits |= ((value as u32) & 1) << 15; self.w } } #[doc = r"Value of the field"] pub struct EMAC_MMCTXIM_OCTCNTR { bits: bool, } impl EMAC_MMCTXIM_OCTCNTR { #[doc = r"Value of the field as raw bits"] #[inline(always)] pub fn bit(&self) -> bool { self.bits } #[doc = r"Returns `true` if the bit is clear (0)"] #[inline(always)] pub fn bit_is_clear(&self) -> bool { !self.bit() } #[doc = r"Returns `true` if the bit is set (1)"] #[inline(always)] pub fn bit_is_set(&self) -> bool { self.bit() } } #[doc = r"Proxy"] pub struct _EMAC_MMCTXIM_OCTCNTW<'a> { w: &'a mut W, } impl<'a> _EMAC_MMCTXIM_OCTCNTW<'a> { #[doc = r"Sets the field bit"] #[inline(always)] pub fn set_bit(self) -> &'a mut W { self.bit(true) } #[doc = r"Clears the field bit"] #[inline(always)] pub fn clear_bit(self) -> &'a mut W { self.bit(false) } #[doc = r"Writes raw bits to the field"] #[inline(always)] pub fn bit(self, value: bool) -> &'a mut W { self.w.bits &= !(1 << 20); self.w.bits |= ((value as u32) & 1) << 20; self.w } } impl R { #[doc = r"Value of the register as raw bits"] #[inline(always)] pub fn bits(&self) -> u32 { self.bits } #[doc = "Bit 1 - MMC Transmit Good Bad Frame Counter Interrupt Mask"] #[inline(always)] pub fn emac_mmctxim_gbf(&self) -> EMAC_MMCTXIM_GBFR { let bits = ((self.bits >> 1) & 1) != 0; EMAC_MMCTXIM_GBFR { bits } } #[doc = "Bit 14 - MMC Transmit Single Collision Good Frame Counter Interrupt Mask"] #[inline(always)] pub fn emac_mmctxim_scollgf(&self) -> EMAC_MMCTXIM_SCOLLGFR { let bits = ((self.bits >> 14) & 1) != 0; EMAC_MMCTXIM_SCOLLGFR { bits } } #[doc = "Bit 15 - MMC Transmit Multiple Collision Good Frame Counter Interrupt Mask"] #[inline(always)] pub fn emac_mmctxim_mcollgf(&self) -> EMAC_MMCTXIM_MCOLLGFR { let bits = ((self.bits >> 15) & 1) != 0; EMAC_MMCTXIM_MCOLLGFR { bits } } #[doc = "Bit 20 - MMC Transmit Good Octet Counter Interrupt Mask"] #[inline(always)] pub fn emac_mmctxim_octcnt(&self) -> EMAC_MMCTXIM_OCTCNTR { let bits = ((self.bits >> 20) & 1) != 0; EMAC_MMCTXIM_OCTCNTR { bits } } } impl W { #[doc = r"Writes raw bits to the register"] #[inline(always)] pub unsafe fn bits(&mut self, bits: u32) -> &mut Self { self.bits = bits; self } #[doc = "Bit 1 - MMC Transmit Good Bad Frame Counter Interrupt Mask"] #[inline(always)] pub fn emac_mmctxim_gbf(&mut self) -> _EMAC_MMCTXIM_GBFW { _EMAC_MMCTXIM_GBFW { w: self } } #[doc = "Bit 14 - MMC Transmit Single Collision Good Frame Counter Interrupt Mask"] #[inline(always)] pub fn emac_mmctxim_scollgf(&mut self) -> _EMAC_MMCTXIM_SCOLLGFW { _EMAC_MMCTXIM_SCOLLGFW { w: self } } #[doc = "Bit 15 - MMC Transmit Multiple Collision Good Frame Counter Interrupt Mask"] #[inline(always)] pub fn emac_mmctxim_mcollgf(&mut self) -> _EMAC_MMCTXIM_MCOLLGFW { _EMAC_MMCTXIM_MCOLLGFW { w: self } } #[doc = "Bit 20 - MMC Transmit Good Octet Counter Interrupt Mask"] #[inline(always)] pub fn emac_mmctxim_octcnt(&mut self) -> _EMAC_MMCTXIM_OCTCNTW { _EMAC_MMCTXIM_OCTCNTW { w: self } } }
#[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::MMCTXIM { #[doc = r"Modifies the contents of the register"] #[inline(always)]
#[doc = r"Reads the contents of the register"] #[inline(always)] pub fn read(&self) -> R { R { bits: self.register.get(), } } #[doc = r"Writes to the register"] #[inline(always)] pub fn write<F>(&self, f: F) where F: FnOnce(&mut W) -> &mut W, { self.register.set( f(&mut W { bits: Self::reset_value(), }) .bits, ); } #[doc = r"Reset value of the register"] #[inline(always)] pub const fn reset_value() -> u32 { 0 } #[doc = r"Writes the reset value to the register"] #[inline(always)] pub fn reset(&self) { self.register.set(Self::reset_value()) } } #[doc = r"Value of the field"] pub struct EMAC_MMCTXIM_GBFR { bits: bool, } impl EMAC_MMCTXIM_GBFR { #[doc = r"Value of the field as raw bits"] #[inline(always)] pub fn bit(&self) -> bool { self.bits } #[doc = r"Returns `true` if the bit is clear (0)"] #[inline(always)] pub fn bit_is_clear(&self) -> bool { !self.bit() } #[doc = r"Returns `true` if the bit is set (1)"] #[inline(always)] pub fn bit_is_set(&self) -> bool { self.bit() } } #[doc = r"Proxy"] pub struct _EMAC_MMCTXIM_GBFW<'a> { w: &'a mut W, } impl<'a> _EMAC_MMCTXIM_GBFW<'a> { #[doc = r"Sets the field bit"] #[inline(always)] pub fn set_bit(self) -> &'a mut W { self.bit(true) } #[doc = r"Clears the field bit"] #[inline(always)] pub fn clear_bit(self) -> &'a mut W { self.bit(false) } #[doc = r"Writes raw bits to the field"] #[inline(always)] pub fn bit(self, value: bool) -> &'a mut W { self.w.bits &= !(1 << 1); self.w.bits |= ((value as u32) & 1) << 1; self.w } } #[doc = r"Value of the field"] pub struct EMAC_MMCTXIM_SCOLLGFR { bits: bool, } impl EMAC_MMCTXIM_SCOLLGFR { #[doc = r"Value of the field as raw bits"] #[inline(always)] pub fn bit(&self) -> bool { self.bits } #[doc = r"Returns `true` if the bit is clear (0)"] #[inline(always)] pub fn bit_is_clear(&self) -> bool { !self.bit() } #[doc = r"Returns `true` if the bit is set (1)"] #[inline(always)] pub fn bit_is_set(&self) -> bool { self.bit() } } #[doc = r"Proxy"] pub struct _EMAC_MMCTXIM_SCOLLGFW<'a> { w: &'a mut W, } impl<'a> _EMAC_MMCTXIM_SCOLLGFW<'a> { #[doc = r"Sets the field bit"] #[inline(always)] pub fn set_bit(self) -> &'a mut W { self.bit(true) } #[doc = r"Clears the field bit"] #[inline(always)] pub fn clear_bit(self) -> &'a mut W { self.bit(false) } #[doc = r"Writes raw bits to the field"] #[inline(always)] pub fn bit(self, value: bool) -> &'a mut W { self.w.bits &= !(1 << 14); self.w.bits |= ((value as u32) & 1) << 14; self.w } } #[doc = r"Value of the field"] pub struct EMAC_MMCTXIM_MCOLLGFR { bits: bool, } impl EMAC_MMCTXIM_MCOLLGFR { #[doc = r"Value of the field as raw bits"] #[inline(always)] pub fn bit(&self) -> bool { self.bits } #[doc = r"Returns `true` if the bit is clear (0)"] #[inline(always)] pub fn bit_is_clear(&self) -> bool { !self.bit() } #[doc = r"Returns `true` if the bit is set (1)"] #[inline(always)] pub fn bit_is_set(&self) -> bool { self.bit() } } #[doc = r"Proxy"] pub struct _EMAC_MMCTXIM_MCOLLGFW<'a> { w: &'a mut W, } impl<'a> _EMAC_MMCTXIM_MCOLLGFW<'a> { #[doc = r"Sets the field bit"] #[inline(always)] pub fn set_bit(self) -> &'a mut W { self.bit(true) } #[doc = r"Clears the field bit"] #[inline(always)] pub fn clear_bit(self) -> &'a mut W { self.bit(false) } #[doc = r"Writes raw bits to the field"] #[inline(always)] pub fn bit(self, value: bool) -> &'a mut W { self.w.bits &= !(1 << 15); self.w.bits |= ((value as u32) & 1) << 15; self.w } } #[doc = r"Value of the field"] pub struct EMAC_MMCTXIM_OCTCNTR { bits: bool, } impl EMAC_MMCTXIM_OCTCNTR { #[doc = r"Value of the field as raw bits"] #[inline(always)] pub fn bit(&self) -> bool { self.bits } #[doc = r"Returns `true` if the bit is clear (0)"] #[inline(always)] pub fn bit_is_clear(&self) -> bool { !self.bit() } #[doc = r"Returns `true` if the bit is set (1)"] #[inline(always)] pub fn bit_is_set(&self) -> bool { self.bit() } } #[doc = r"Proxy"] pub struct _EMAC_MMCTXIM_OCTCNTW<'a> { w: &'a mut W, } impl<'a> _EMAC_MMCTXIM_OCTCNTW<'a> { #[doc = r"Sets the field bit"] #[inline(always)] pub fn set_bit(self) -> &'a mut W { self.bit(true) } #[doc = r"Clears the field bit"] #[inline(always)] pub fn clear_bit(self) -> &'a mut W { self.bit(false) } #[doc = r"Writes raw bits to the field"] #[inline(always)] pub fn bit(self, value: bool) -> &'a mut W { self.w.bits &= !(1 << 20); self.w.bits |= ((value as u32) & 1) << 20; self.w } } impl R { #[doc = r"Value of the register as raw bits"] #[inline(always)] pub fn bits(&self) -> u32 { self.bits } #[doc = "Bit 1 - MMC Transmit Good Bad Frame Counter Interrupt Mask"] #[inline(always)] pub fn emac_mmctxim_gbf(&self) -> EMAC_MMCTXIM_GBFR { let bits = ((self.bits >> 1) & 1) != 0; EMAC_MMCTXIM_GBFR { bits } } #[doc = "Bit 14 - MMC Transmit Single Collision Good Frame Counter Interrupt Mask"] #[inline(always)] pub fn emac_mmctxim_scollgf(&self) -> EMAC_MMCTXIM_SCOLLGFR { let bits = ((self.bits >> 14) & 1) != 0; EMAC_MMCTXIM_SCOLLGFR { bits } } #[doc = "Bit 15 - MMC Transmit Multiple Collision Good Frame Counter Interrupt Mask"] #[inline(always)] pub fn emac_mmctxim_mcollgf(&self) -> EMAC_MMCTXIM_MCOLLGFR { let bits = ((self.bits >> 15) & 1) != 0; EMAC_MMCTXIM_MCOLLGFR { bits } } #[doc = "Bit 20 - MMC Transmit Good Octet Counter Interrupt Mask"] #[inline(always)] pub fn emac_mmctxim_octcnt(&self) -> EMAC_MMCTXIM_OCTCNTR { let bits = ((self.bits >> 20) & 1) != 0; EMAC_MMCTXIM_OCTCNTR { bits } } } impl W { #[doc = r"Writes raw bits to the register"] #[inline(always)] pub unsafe fn bits(&mut self, bits: u32) -> &mut Self { self.bits = bits; self } #[doc = "Bit 1 - MMC Transmit Good Bad Frame Counter Interrupt Mask"] #[inline(always)] pub fn emac_mmctxim_gbf(&mut self) -> _EMAC_MMCTXIM_GBFW { _EMAC_MMCTXIM_GBFW { w: self } } #[doc = "Bit 14 - MMC Transmit Single Collision Good Frame Counter Interrupt Mask"] #[inline(always)] pub fn emac_mmctxim_scollgf(&mut self) -> _EMAC_MMCTXIM_SCOLLGFW { _EMAC_MMCTXIM_SCOLLGFW { w: self } } #[doc = "Bit 15 - MMC Transmit Multiple Collision Good Frame Counter Interrupt Mask"] #[inline(always)] pub fn emac_mmctxim_mcollgf(&mut self) -> _EMAC_MMCTXIM_MCOLLGFW { _EMAC_MMCTXIM_MCOLLGFW { w: self } } #[doc = "Bit 20 - MMC Transmit Good Octet Counter Interrupt Mask"] #[inline(always)] pub fn emac_mmctxim_octcnt(&mut self) -> _EMAC_MMCTXIM_OCTCNTW { _EMAC_MMCTXIM_OCTCNTW { w: self } } }
pub fn modify<F>(&self, f: F) where for<'w> F: FnOnce(&R, &'w mut W) -> &'w mut W, { let bits = self.register.get(); self.register.set(f(&R { bits }, &mut W { bits }).bits); }
function_block-full_function
[ { "content": "#[doc = r\"Value read from the register\"]\n\npub struct R {\n\n bits: u32,\n\n}\n\n#[doc = r\"Value to write to the register\"]\n\npub struct W {\n\n bits: u32,\n\n}\n\nimpl super::BIT {\n\n #[doc = r\"Modifies the contents of the register\"]\n\n #[inline(always)]\n\n pub fn modify<F>(&self, f: F)\n\n where\n\n for<'w> F: FnOnce(&R, &'w mut W) -> &'w mut W,\n\n {\n\n let bits = self.register.get();\n\n self.register.set(f(&R { bits }, &mut W { bits }).bits);\n\n }\n\n #[doc = r\"Reads the contents of the register\"]\n\n #[inline(always)]\n", "file_path": "src/can0/bit_.rs", "rank": 0, "score": 61984.516309050734 }, { "content": " pub fn read(&self) -> R {\n\n R {\n\n bits: self.register.get(),\n\n }\n\n }\n\n #[doc = r\"Writes to the register\"]\n\n #[inline(always)]\n\n pub fn write<F>(&self, f: F)\n\n where\n\n F: FnOnce(&mut W) -> &mut W,\n\n {\n\n self.register.set(\n\n f(&mut W {\n\n bits: Self::reset_value(),\n\n })\n\n .bits,\n\n );\n\n }\n\n #[doc = r\"Reset value of the register\"]\n\n #[inline(always)]\n", "file_path": "src/can0/bit_.rs", "rank": 1, "score": 61966.285465677654 }, { "content": "}\n\nimpl CAN_BIT_TSEG1R {\n\n #[doc = r\"Value of the field as raw bits\"]\n\n #[inline(always)]\n\n pub fn bits(&self) -> u8 {\n\n self.bits\n\n }\n\n}\n\n#[doc = r\"Proxy\"]\n\npub struct _CAN_BIT_TSEG1W<'a> {\n\n w: &'a mut W,\n\n}\n\nimpl<'a> _CAN_BIT_TSEG1W<'a> {\n\n #[doc = r\"Writes raw bits to the field\"]\n\n #[inline(always)]\n\n pub unsafe fn bits(self, value: u8) -> &'a mut W {\n\n self.w.bits &= !(15 << 8);\n\n self.w.bits |= ((value as u32) & 15) << 8;\n\n self.w\n\n }\n", "file_path": "src/can0/bit_.rs", "rank": 2, "score": 61956.00083763663 }, { "content": "#[doc = r\"Proxy\"]\n\npub struct _CAN_BIT_BRPW<'a> {\n\n w: &'a mut W,\n\n}\n\nimpl<'a> _CAN_BIT_BRPW<'a> {\n\n #[doc = r\"Writes raw bits to the field\"]\n\n #[inline(always)]\n\n pub unsafe fn bits(self, value: u8) -> &'a mut W {\n\n self.w.bits &= !(63 << 0);\n\n self.w.bits |= ((value as u32) & 63) << 0;\n\n self.w\n\n }\n\n}\n\n#[doc = r\"Value of the field\"]\n\npub struct CAN_BIT_SJWR {\n\n bits: u8,\n\n}\n\nimpl CAN_BIT_SJWR {\n\n #[doc = r\"Value of the field as raw bits\"]\n\n #[inline(always)]\n", "file_path": "src/can0/bit_.rs", "rank": 3, "score": 61955.49464698807 }, { "content": " pub const fn reset_value() -> u32 {\n\n 0\n\n }\n\n #[doc = r\"Writes the reset value to the register\"]\n\n #[inline(always)]\n\n pub fn reset(&self) {\n\n self.register.set(Self::reset_value())\n\n }\n\n}\n\n#[doc = r\"Value of the field\"]\n\npub struct CAN_BIT_BRPR {\n\n bits: u8,\n\n}\n\nimpl CAN_BIT_BRPR {\n\n #[doc = r\"Value of the field as raw bits\"]\n\n #[inline(always)]\n\n pub fn bits(&self) -> u8 {\n\n self.bits\n\n }\n\n}\n", "file_path": "src/can0/bit_.rs", "rank": 4, "score": 61955.33371326577 }, { "content": " let bits = ((self.bits >> 6) & 3) as u8;\n\n CAN_BIT_SJWR { bits }\n\n }\n\n #[doc = \"Bits 8:11 - Time Segment Before Sample Point\"]\n\n #[inline(always)]\n\n pub fn can_bit_tseg1(&self) -> CAN_BIT_TSEG1R {\n\n let bits = ((self.bits >> 8) & 15) as u8;\n\n CAN_BIT_TSEG1R { bits }\n\n }\n\n #[doc = \"Bits 12:14 - Time Segment after Sample Point\"]\n\n #[inline(always)]\n\n pub fn can_bit_tseg2(&self) -> CAN_BIT_TSEG2R {\n\n let bits = ((self.bits >> 12) & 7) as u8;\n\n CAN_BIT_TSEG2R { bits }\n\n }\n\n}\n\nimpl W {\n\n #[doc = r\"Writes raw bits to the register\"]\n\n #[inline(always)]\n\n pub unsafe fn bits(&mut self, bits: u32) -> &mut Self {\n", "file_path": "src/can0/bit_.rs", "rank": 5, "score": 61955.3004904712 }, { "content": " pub fn bits(&self) -> u8 {\n\n self.bits\n\n }\n\n}\n\n#[doc = r\"Proxy\"]\n\npub struct _CAN_BIT_SJWW<'a> {\n\n w: &'a mut W,\n\n}\n\nimpl<'a> _CAN_BIT_SJWW<'a> {\n\n #[doc = r\"Writes raw bits to the field\"]\n\n #[inline(always)]\n\n pub unsafe fn bits(self, value: u8) -> &'a mut W {\n\n self.w.bits &= !(3 << 6);\n\n self.w.bits |= ((value as u32) & 3) << 6;\n\n self.w\n\n }\n\n}\n\n#[doc = r\"Value of the field\"]\n\npub struct CAN_BIT_TSEG1R {\n\n bits: u8,\n", "file_path": "src/can0/bit_.rs", "rank": 6, "score": 61955.11633100571 }, { "content": " self.w.bits &= !(7 << 12);\n\n self.w.bits |= ((value as u32) & 7) << 12;\n\n self.w\n\n }\n\n}\n\nimpl R {\n\n #[doc = r\"Value of the register as raw bits\"]\n\n #[inline(always)]\n\n pub fn bits(&self) -> u32 {\n\n self.bits\n\n }\n\n #[doc = \"Bits 0:5 - Baud Rate Prescaler\"]\n\n #[inline(always)]\n\n pub fn can_bit_brp(&self) -> CAN_BIT_BRPR {\n\n let bits = ((self.bits >> 0) & 63) as u8;\n\n CAN_BIT_BRPR { bits }\n\n }\n\n #[doc = \"Bits 6:7 - (Re)Synchronization Jump Width\"]\n\n #[inline(always)]\n\n pub fn can_bit_sjw(&self) -> CAN_BIT_SJWR {\n", "file_path": "src/can0/bit_.rs", "rank": 7, "score": 61954.46481891685 }, { "content": "}\n\n#[doc = r\"Value of the field\"]\n\npub struct CAN_BIT_TSEG2R {\n\n bits: u8,\n\n}\n\nimpl CAN_BIT_TSEG2R {\n\n #[doc = r\"Value of the field as raw bits\"]\n\n #[inline(always)]\n\n pub fn bits(&self) -> u8 {\n\n self.bits\n\n }\n\n}\n\n#[doc = r\"Proxy\"]\n\npub struct _CAN_BIT_TSEG2W<'a> {\n\n w: &'a mut W,\n\n}\n\nimpl<'a> _CAN_BIT_TSEG2W<'a> {\n\n #[doc = r\"Writes raw bits to the field\"]\n\n #[inline(always)]\n\n pub unsafe fn bits(self, value: u8) -> &'a mut W {\n", "file_path": "src/can0/bit_.rs", "rank": 8, "score": 61950.68242075026 }, { "content": " self.bits = bits;\n\n self\n\n }\n\n #[doc = \"Bits 0:5 - Baud Rate Prescaler\"]\n\n #[inline(always)]\n\n pub fn can_bit_brp(&mut self) -> _CAN_BIT_BRPW {\n\n _CAN_BIT_BRPW { w: self }\n\n }\n\n #[doc = \"Bits 6:7 - (Re)Synchronization Jump Width\"]\n\n #[inline(always)]\n\n pub fn can_bit_sjw(&mut self) -> _CAN_BIT_SJWW {\n\n _CAN_BIT_SJWW { w: self }\n\n }\n\n #[doc = \"Bits 8:11 - Time Segment Before Sample Point\"]\n\n #[inline(always)]\n\n pub fn can_bit_tseg1(&mut self) -> _CAN_BIT_TSEG1W {\n\n _CAN_BIT_TSEG1W { w: self }\n\n }\n\n #[doc = \"Bits 12:14 - Time Segment after Sample Point\"]\n\n #[inline(always)]\n\n pub fn can_bit_tseg2(&mut self) -> _CAN_BIT_TSEG2W {\n\n _CAN_BIT_TSEG2W { w: self }\n\n }\n\n}\n", "file_path": "src/can0/bit_.rs", "rank": 9, "score": 61933.73730791687 }, { "content": "#[doc = r\"Value read from the register\"]\n\npub struct R {\n\n bits: u32,\n\n}\n\n#[doc = r\"Value to write to the register\"]\n\npub struct W {\n\n bits: u32,\n\n}\n\nimpl super::IS {\n\n #[doc = r\"Modifies the contents of the register\"]\n\n #[inline(always)]\n\n pub fn modify<F>(&self, f: F)\n\n where\n\n for<'w> F: FnOnce(&R, &'w mut W) -> &'w mut W,\n\n {\n\n let bits = self.register.get();\n\n self.register.set(f(&R { bits }, &mut W { bits }).bits);\n\n }\n\n #[doc = r\"Reads the contents of the register\"]\n\n #[inline(always)]\n", "file_path": "src/gpioa/is.rs", "rank": 10, "score": 60.671003763796236 }, { "content": "#[doc = r\"Value read from the register\"]\n\npub struct R {\n\n bits: u32,\n\n}\n\n#[doc = r\"Value to write to the register\"]\n\npub struct W {\n\n bits: u32,\n\n}\n\nimpl super::SSEMUX1 {\n\n #[doc = r\"Modifies the contents of the register\"]\n\n #[inline(always)]\n\n pub fn modify<F>(&self, f: F)\n\n where\n\n for<'w> F: FnOnce(&R, &'w mut W) -> &'w mut W,\n\n {\n\n let bits = self.register.get();\n\n self.register.set(f(&R { bits }, &mut W { bits }).bits);\n\n }\n\n #[doc = r\"Reads the contents of the register\"]\n\n #[inline(always)]\n", "file_path": "src/adc0/ssemux1.rs", "rank": 11, "score": 60.46770973237478 }, { "content": "#[doc = r\"Value read from the register\"]\n\npub struct R {\n\n bits: u32,\n\n}\n\n#[doc = r\"Value to write to the register\"]\n\npub struct W {\n\n bits: u32,\n\n}\n\nimpl super::_0_FLTSRC0 {\n\n #[doc = r\"Modifies the contents of the register\"]\n\n #[inline(always)]\n\n pub fn modify<F>(&self, f: F)\n\n where\n\n for<'w> F: FnOnce(&R, &'w mut W) -> &'w mut W,\n\n {\n\n let bits = self.register.get();\n\n self.register.set(f(&R { bits }, &mut W { bits }).bits);\n\n }\n\n #[doc = r\"Reads the contents of the register\"]\n\n #[inline(always)]\n", "file_path": "src/pwm0/_0_fltsrc0.rs", "rank": 12, "score": 60.46770973237478 }, { "content": "#[doc = r\"Value read from the register\"]\n\npub struct R {\n\n bits: u32,\n\n}\n\n#[doc = r\"Value to write to the register\"]\n\npub struct W {\n\n bits: u32,\n\n}\n\nimpl super::READFIFO0 {\n\n #[doc = r\"Modifies the contents of the register\"]\n\n #[inline(always)]\n\n pub fn modify<F>(&self, f: F)\n\n where\n\n for<'w> F: FnOnce(&R, &'w mut W) -> &'w mut W,\n\n {\n\n let bits = self.register.get();\n\n self.register.set(f(&R { bits }, &mut W { bits }).bits);\n\n }\n\n #[doc = r\"Reads the contents of the register\"]\n\n #[inline(always)]\n", "file_path": "src/epi0/readfifo0.rs", "rank": 13, "score": 60.46770973237478 }, { "content": "#[doc = r\"Value read from the register\"]\n\npub struct R {\n\n bits: u32,\n\n}\n\n#[doc = r\"Value to write to the register\"]\n\npub struct W {\n\n bits: u32,\n\n}\n\nimpl super::_0_GENA {\n\n #[doc = r\"Modifies the contents of the register\"]\n\n #[inline(always)]\n\n pub fn modify<F>(&self, f: F)\n\n where\n\n for<'w> F: FnOnce(&R, &'w mut W) -> &'w mut W,\n\n {\n\n let bits = self.register.get();\n\n self.register.set(f(&R { bits }, &mut W { bits }).bits);\n\n }\n\n #[doc = r\"Reads the contents of the register\"]\n\n #[inline(always)]\n", "file_path": "src/pwm0/_0_gena.rs", "rank": 14, "score": 60.46770973237478 }, { "content": "#[doc = r\"Value read from the register\"]\n\npub struct R {\n\n bits: u32,\n\n}\n\n#[doc = r\"Value to write to the register\"]\n\npub struct W {\n\n bits: u32,\n\n}\n\nimpl super::_0_RIS {\n\n #[doc = r\"Modifies the contents of the register\"]\n\n #[inline(always)]\n\n pub fn modify<F>(&self, f: F)\n\n where\n\n for<'w> F: FnOnce(&R, &'w mut W) -> &'w mut W,\n\n {\n\n let bits = self.register.get();\n\n self.register.set(f(&R { bits }, &mut W { bits }).bits);\n\n }\n\n #[doc = r\"Reads the contents of the register\"]\n\n #[inline(always)]\n", "file_path": "src/pwm0/_0_ris.rs", "rank": 15, "score": 60.46770973237478 }, { "content": "#[doc = r\"Value read from the register\"]\n\npub struct R {\n\n bits: u32,\n\n}\n\n#[doc = r\"Value to write to the register\"]\n\npub struct W {\n\n bits: u32,\n\n}\n\nimpl super::NWDA1 {\n\n #[doc = r\"Modifies the contents of the register\"]\n\n #[inline(always)]\n\n pub fn modify<F>(&self, f: F)\n\n where\n\n for<'w> F: FnOnce(&R, &'w mut W) -> &'w mut W,\n\n {\n\n let bits = self.register.get();\n\n self.register.set(f(&R { bits }, &mut W { bits }).bits);\n\n }\n\n #[doc = r\"Reads the contents of the register\"]\n\n #[inline(always)]\n", "file_path": "src/can0/nwda1.rs", "rank": 16, "score": 60.46770973237478 }, { "content": "#[doc = r\"Value read from the register\"]\n\npub struct R {\n\n bits: u32,\n\n}\n\n#[doc = r\"Value to write to the register\"]\n\npub struct W {\n\n bits: u32,\n\n}\n\nimpl super::HB16TIME {\n\n #[doc = r\"Modifies the contents of the register\"]\n\n #[inline(always)]\n\n pub fn modify<F>(&self, f: F)\n\n where\n\n for<'w> F: FnOnce(&R, &'w mut W) -> &'w mut W,\n\n {\n\n let bits = self.register.get();\n\n self.register.set(f(&R { bits }, &mut W { bits }).bits);\n\n }\n\n #[doc = r\"Reads the contents of the register\"]\n\n #[inline(always)]\n", "file_path": "src/epi0/hb16time.rs", "rank": 17, "score": 60.46770973237478 }, { "content": "#[doc = r\"Value read from the register\"]\n\npub struct R {\n\n bits: u32,\n\n}\n\n#[doc = r\"Value to write to the register\"]\n\npub struct W {\n\n bits: u32,\n\n}\n\nimpl super::HB16TIME4 {\n\n #[doc = r\"Modifies the contents of the register\"]\n\n #[inline(always)]\n\n pub fn modify<F>(&self, f: F)\n\n where\n\n for<'w> F: FnOnce(&R, &'w mut W) -> &'w mut W,\n\n {\n\n let bits = self.register.get();\n\n self.register.set(f(&R { bits }, &mut W { bits }).bits);\n\n }\n\n #[doc = r\"Reads the contents of the register\"]\n\n #[inline(always)]\n", "file_path": "src/epi0/hb16time4.rs", "rank": 18, "score": 60.46770973237478 }, { "content": "#[doc = r\"Value read from the register\"]\n\npub struct R {\n\n bits: u32,\n\n}\n\n#[doc = r\"Value to write to the register\"]\n\npub struct W {\n\n bits: u32,\n\n}\n\nimpl super::USERREG0 {\n\n #[doc = r\"Modifies the contents of the register\"]\n\n #[inline(always)]\n\n pub fn modify<F>(&self, f: F)\n\n where\n\n for<'w> F: FnOnce(&R, &'w mut W) -> &'w mut W,\n\n {\n\n let bits = self.register.get();\n\n self.register.set(f(&R { bits }, &mut W { bits }).bits);\n\n }\n\n #[doc = r\"Reads the contents of the register\"]\n\n #[inline(always)]\n", "file_path": "src/flash_ctrl/userreg0.rs", "rank": 19, "score": 60.46770973237478 }, { "content": "#[doc = r\"Value read from the register\"]\n\npub struct R {\n\n bits: u32,\n\n}\n\n#[doc = r\"Value to write to the register\"]\n\npub struct W {\n\n bits: u32,\n\n}\n\nimpl super::RSIZE1 {\n\n #[doc = r\"Modifies the contents of the register\"]\n\n #[inline(always)]\n\n pub fn modify<F>(&self, f: F)\n\n where\n\n for<'w> F: FnOnce(&R, &'w mut W) -> &'w mut W,\n\n {\n\n let bits = self.register.get();\n\n self.register.set(f(&R { bits }, &mut W { bits }).bits);\n\n }\n\n #[doc = r\"Reads the contents of the register\"]\n\n #[inline(always)]\n", "file_path": "src/epi0/rsize1.rs", "rank": 20, "score": 60.46770973237478 }, { "content": "#[doc = r\"Value read from the register\"]\n\npub struct R {\n\n bits: u32,\n\n}\n\n#[doc = r\"Value to write to the register\"]\n\npub struct W {\n\n bits: u32,\n\n}\n\nimpl super::FCMISC {\n\n #[doc = r\"Modifies the contents of the register\"]\n\n #[inline(always)]\n\n pub fn modify<F>(&self, f: F)\n\n where\n\n for<'w> F: FnOnce(&R, &'w mut W) -> &'w mut W,\n\n {\n\n let bits = self.register.get();\n\n self.register.set(f(&R { bits }, &mut W { bits }).bits);\n\n }\n\n #[doc = r\"Reads the contents of the register\"]\n\n #[inline(always)]\n", "file_path": "src/flash_ctrl/fcmisc.rs", "rank": 21, "score": 60.46770973237478 }, { "content": "#[doc = r\"Value read from the register\"]\n\npub struct R {\n\n bits: u32,\n\n}\n\n#[doc = r\"Value to write to the register\"]\n\npub struct W {\n\n bits: u32,\n\n}\n\nimpl super::KEY1_0 {\n\n #[doc = r\"Modifies the contents of the register\"]\n\n #[inline(always)]\n\n pub fn modify<F>(&self, f: F)\n\n where\n\n for<'w> F: FnOnce(&R, &'w mut W) -> &'w mut W,\n\n {\n\n let bits = self.register.get();\n\n self.register.set(f(&R { bits }, &mut W { bits }).bits);\n\n }\n\n #[doc = r\"Reads the contents of the register\"]\n\n #[inline(always)]\n", "file_path": "src/aes/key1_0.rs", "rank": 22, "score": 60.46770973237478 }, { "content": "#[doc = r\"Value read from the register\"]\n\npub struct R {\n\n bits: u32,\n\n}\n\n#[doc = r\"Value to write to the register\"]\n\npub struct W {\n\n bits: u32,\n\n}\n\nimpl super::RXCNTCRCERR {\n\n #[doc = r\"Modifies the contents of the register\"]\n\n #[inline(always)]\n\n pub fn modify<F>(&self, f: F)\n\n where\n\n for<'w> F: FnOnce(&R, &'w mut W) -> &'w mut W,\n\n {\n\n let bits = self.register.get();\n\n self.register.set(f(&R { bits }, &mut W { bits }).bits);\n\n }\n\n #[doc = r\"Reads the contents of the register\"]\n\n #[inline(always)]\n", "file_path": "src/emac0/rxcntcrcerr.rs", "rank": 23, "score": 60.46770973237478 }, { "content": "#[doc = r\"Value read from the register\"]\n\npub struct R {\n\n bits: u32,\n\n}\n\n#[doc = r\"Value to write to the register\"]\n\npub struct W {\n\n bits: u32,\n\n}\n\nimpl super::HASHTBLL {\n\n #[doc = r\"Modifies the contents of the register\"]\n\n #[inline(always)]\n\n pub fn modify<F>(&self, f: F)\n\n where\n\n for<'w> F: FnOnce(&R, &'w mut W) -> &'w mut W,\n\n {\n\n let bits = self.register.get();\n\n self.register.set(f(&R { bits }, &mut W { bits }).bits);\n\n }\n\n #[doc = r\"Reads the contents of the register\"]\n\n #[inline(always)]\n", "file_path": "src/emac0/hashtbll.rs", "rank": 24, "score": 60.46770973237478 }, { "content": "#[doc = r\"Value read from the register\"]\n\npub struct R {\n\n bits: u32,\n\n}\n\n#[doc = r\"Value to write to the register\"]\n\npub struct W {\n\n bits: u32,\n\n}\n\nimpl super::PP {\n\n #[doc = r\"Modifies the contents of the register\"]\n\n #[inline(always)]\n\n pub fn modify<F>(&self, f: F)\n\n where\n\n for<'w> F: FnOnce(&R, &'w mut W) -> &'w mut W,\n\n {\n\n let bits = self.register.get();\n\n self.register.set(f(&R { bits }, &mut W { bits }).bits);\n\n }\n\n #[doc = r\"Reads the contents of the register\"]\n\n #[inline(always)]\n", "file_path": "src/eeprom/pp.rs", "rank": 25, "score": 60.46770973237478 }, { "content": "#[doc = r\"Value read from the register\"]\n\npub struct R {\n\n bits: u32,\n\n}\n\n#[doc = r\"Value to write to the register\"]\n\npub struct W {\n\n bits: u32,\n\n}\n\nimpl super::FMPRE0 {\n\n #[doc = r\"Modifies the contents of the register\"]\n\n #[inline(always)]\n\n pub fn modify<F>(&self, f: F)\n\n where\n\n for<'w> F: FnOnce(&R, &'w mut W) -> &'w mut W,\n\n {\n\n let bits = self.register.get();\n\n self.register.set(f(&R { bits }, &mut W { bits }).bits);\n\n }\n\n #[doc = r\"Reads the contents of the register\"]\n\n #[inline(always)]\n", "file_path": "src/flash_ctrl/fmpre0.rs", "rank": 26, "score": 60.46770973237478 }, { "content": "#[doc = r\"Value read from the register\"]\n\npub struct R {\n\n bits: u32,\n\n}\n\n#[doc = r\"Value to write to the register\"]\n\npub struct W {\n\n bits: u32,\n\n}\n\nimpl super::FMPRE6 {\n\n #[doc = r\"Modifies the contents of the register\"]\n\n #[inline(always)]\n\n pub fn modify<F>(&self, f: F)\n\n where\n\n for<'w> F: FnOnce(&R, &'w mut W) -> &'w mut W,\n\n {\n\n let bits = self.register.get();\n\n self.register.set(f(&R { bits }, &mut W { bits }).bits);\n\n }\n\n #[doc = r\"Reads the contents of the register\"]\n\n #[inline(always)]\n", "file_path": "src/flash_ctrl/fmpre6.rs", "rank": 27, "score": 60.467709732374786 }, { "content": "#[doc = r\"Value read from the register\"]\n\npub struct R {\n\n bits: u32,\n\n}\n\n#[doc = r\"Value to write to the register\"]\n\npub struct W {\n\n bits: u32,\n\n}\n\nimpl super::SSOP1 {\n\n #[doc = r\"Modifies the contents of the register\"]\n\n #[inline(always)]\n\n pub fn modify<F>(&self, f: F)\n\n where\n\n for<'w> F: FnOnce(&R, &'w mut W) -> &'w mut W,\n\n {\n\n let bits = self.register.get();\n\n self.register.set(f(&R { bits }, &mut W { bits }).bits);\n\n }\n\n #[doc = r\"Reads the contents of the register\"]\n\n #[inline(always)]\n", "file_path": "src/adc0/ssop1.rs", "rank": 28, "score": 60.46770973237478 }, { "content": "#[doc = r\"Value read from the register\"]\n\npub struct R {\n\n bits: u32,\n\n}\n\n#[doc = r\"Value to write to the register\"]\n\npub struct W {\n\n bits: u32,\n\n}\n\nimpl super::SIMR {\n\n #[doc = r\"Modifies the contents of the register\"]\n\n #[inline(always)]\n\n pub fn modify<F>(&self, f: F)\n\n where\n\n for<'w> F: FnOnce(&R, &'w mut W) -> &'w mut W,\n\n {\n\n let bits = self.register.get();\n\n self.register.set(f(&R { bits }, &mut W { bits }).bits);\n\n }\n\n #[doc = r\"Reads the contents of the register\"]\n\n #[inline(always)]\n", "file_path": "src/i2c0/simr.rs", "rank": 29, "score": 60.46770973237478 }, { "content": "#[doc = r\"Value read from the register\"]\n\npub struct R {\n\n bits: u32,\n\n}\n\n#[doc = r\"Value to write to the register\"]\n\npub struct W {\n\n bits: u32,\n\n}\n\nimpl super::KEY2_3 {\n\n #[doc = r\"Modifies the contents of the register\"]\n\n #[inline(always)]\n\n pub fn modify<F>(&self, f: F)\n\n where\n\n for<'w> F: FnOnce(&R, &'w mut W) -> &'w mut W,\n\n {\n\n let bits = self.register.get();\n\n self.register.set(f(&R { bits }, &mut W { bits }).bits);\n\n }\n\n #[doc = r\"Reads the contents of the register\"]\n\n #[inline(always)]\n", "file_path": "src/aes/key2_3.rs", "rank": 30, "score": 60.46770973237478 }, { "content": "#[doc = r\"Value read from the register\"]\n\npub struct R {\n\n bits: u32,\n\n}\n\n#[doc = r\"Value to write to the register\"]\n\npub struct W {\n\n bits: u32,\n\n}\n\nimpl super::HB8TIME4 {\n\n #[doc = r\"Modifies the contents of the register\"]\n\n #[inline(always)]\n\n pub fn modify<F>(&self, f: F)\n\n where\n\n for<'w> F: FnOnce(&R, &'w mut W) -> &'w mut W,\n\n {\n\n let bits = self.register.get();\n\n self.register.set(f(&R { bits }, &mut W { bits }).bits);\n\n }\n\n #[doc = r\"Reads the contents of the register\"]\n\n #[inline(always)]\n", "file_path": "src/epi0/hb8time4.rs", "rank": 31, "score": 60.46770973237478 }, { "content": "#[doc = r\"Value read from the register\"]\n\npub struct R {\n\n bits: u32,\n\n}\n\n#[doc = r\"Value to write to the register\"]\n\npub struct W {\n\n bits: u32,\n\n}\n\nimpl super::FMPPE4 {\n\n #[doc = r\"Modifies the contents of the register\"]\n\n #[inline(always)]\n\n pub fn modify<F>(&self, f: F)\n\n where\n\n for<'w> F: FnOnce(&R, &'w mut W) -> &'w mut W,\n\n {\n\n let bits = self.register.get();\n\n self.register.set(f(&R { bits }, &mut W { bits }).bits);\n\n }\n\n #[doc = r\"Reads the contents of the register\"]\n\n #[inline(always)]\n", "file_path": "src/flash_ctrl/fmppe4.rs", "rank": 32, "score": 60.46770973237478 }, { "content": "#[doc = r\"Value read from the register\"]\n\npub struct R {\n\n bits: u32,\n\n}\n\n#[doc = r\"Value to write to the register\"]\n\npub struct W {\n\n bits: u32,\n\n}\n\nimpl super::FMPRE4 {\n\n #[doc = r\"Modifies the contents of the register\"]\n\n #[inline(always)]\n\n pub fn modify<F>(&self, f: F)\n\n where\n\n for<'w> F: FnOnce(&R, &'w mut W) -> &'w mut W,\n\n {\n\n let bits = self.register.get();\n\n self.register.set(f(&R { bits }, &mut W { bits }).bits);\n\n }\n\n #[doc = r\"Reads the contents of the register\"]\n\n #[inline(always)]\n", "file_path": "src/flash_ctrl/fmpre4.rs", "rank": 33, "score": 60.467709732374786 }, { "content": "#[doc = r\"Value read from the register\"]\n\npub struct R {\n\n bits: u32,\n\n}\n\n#[doc = r\"Value to write to the register\"]\n\npub struct W {\n\n bits: u32,\n\n}\n\nimpl super::DATA_IN_1 {\n\n #[doc = r\"Modifies the contents of the register\"]\n\n #[inline(always)]\n\n pub fn modify<F>(&self, f: F)\n\n where\n\n for<'w> F: FnOnce(&R, &'w mut W) -> &'w mut W,\n\n {\n\n let bits = self.register.get();\n\n self.register.set(f(&R { bits }, &mut W { bits }).bits);\n\n }\n\n #[doc = r\"Reads the contents of the register\"]\n\n #[inline(always)]\n", "file_path": "src/aes/data_in_1.rs", "rank": 34, "score": 60.46770973237478 }, { "content": "#[doc = r\"Value read from the register\"]\n\npub struct R {\n\n bits: u32,\n\n}\n\n#[doc = r\"Value to write to the register\"]\n\npub struct W {\n\n bits: u32,\n\n}\n\nimpl super::ADDR0L {\n\n #[doc = r\"Modifies the contents of the register\"]\n\n #[inline(always)]\n\n pub fn modify<F>(&self, f: F)\n\n where\n\n for<'w> F: FnOnce(&R, &'w mut W) -> &'w mut W,\n\n {\n\n let bits = self.register.get();\n\n self.register.set(f(&R { bits }, &mut W { bits }).bits);\n\n }\n\n #[doc = r\"Reads the contents of the register\"]\n\n #[inline(always)]\n", "file_path": "src/emac0/addr0l.rs", "rank": 35, "score": 60.46770973237478 }, { "content": "#[doc = r\"Value read from the register\"]\n\npub struct R {\n\n bits: u32,\n\n}\n\n#[doc = r\"Value to write to the register\"]\n\npub struct W {\n\n bits: u32,\n\n}\n\nimpl super::_0_CTL {\n\n #[doc = r\"Modifies the contents of the register\"]\n\n #[inline(always)]\n\n pub fn modify<F>(&self, f: F)\n\n where\n\n for<'w> F: FnOnce(&R, &'w mut W) -> &'w mut W,\n\n {\n\n let bits = self.register.get();\n\n self.register.set(f(&R { bits }, &mut W { bits }).bits);\n\n }\n\n #[doc = r\"Reads the contents of the register\"]\n\n #[inline(always)]\n", "file_path": "src/pwm0/_0_ctl.rs", "rank": 36, "score": 60.46770973237478 }, { "content": "#[doc = r\"Value read from the register\"]\n\npub struct R {\n\n bits: u32,\n\n}\n\n#[doc = r\"Value to write to the register\"]\n\npub struct W {\n\n bits: u32,\n\n}\n\nimpl super::FMPRE12 {\n\n #[doc = r\"Modifies the contents of the register\"]\n\n #[inline(always)]\n\n pub fn modify<F>(&self, f: F)\n\n where\n\n for<'w> F: FnOnce(&R, &'w mut W) -> &'w mut W,\n\n {\n\n let bits = self.register.get();\n\n self.register.set(f(&R { bits }, &mut W { bits }).bits);\n\n }\n\n #[doc = r\"Reads the contents of the register\"]\n\n #[inline(always)]\n", "file_path": "src/flash_ctrl/fmpre12.rs", "rank": 37, "score": 60.46770973237478 }, { "content": "#[doc = r\"Value read from the register\"]\n\npub struct R {\n\n bits: u32,\n\n}\n\n#[doc = r\"Value to write to the register\"]\n\npub struct W {\n\n bits: u32,\n\n}\n\nimpl super::IO {\n\n #[doc = r\"Modifies the contents of the register\"]\n\n #[inline(always)]\n\n pub fn modify<F>(&self, f: F)\n\n where\n\n for<'w> F: FnOnce(&R, &'w mut W) -> &'w mut W,\n\n {\n\n let bits = self.register.get();\n\n self.register.set(f(&R { bits }, &mut W { bits }).bits);\n\n }\n\n #[doc = r\"Reads the contents of the register\"]\n\n #[inline(always)]\n", "file_path": "src/hib/io.rs", "rank": 38, "score": 60.46770973237478 }, { "content": "#[doc = r\"Value read from the register\"]\n\npub struct R {\n\n bits: u32,\n\n}\n\n#[doc = r\"Value to write to the register\"]\n\npub struct W {\n\n bits: u32,\n\n}\n\nimpl super::MBMON {\n\n #[doc = r\"Modifies the contents of the register\"]\n\n #[inline(always)]\n\n pub fn modify<F>(&self, f: F)\n\n where\n\n for<'w> F: FnOnce(&R, &'w mut W) -> &'w mut W,\n\n {\n\n let bits = self.register.get();\n\n self.register.set(f(&R { bits }, &mut W { bits }).bits);\n\n }\n\n #[doc = r\"Reads the contents of the register\"]\n\n #[inline(always)]\n", "file_path": "src/i2c0/mbmon.rs", "rank": 39, "score": 60.46770973237478 }, { "content": "#[doc = r\"Value read from the register\"]\n\npub struct R {\n\n bits: u32,\n\n}\n\n#[doc = r\"Value to write to the register\"]\n\npub struct W {\n\n bits: u32,\n\n}\n\nimpl super::SSMUX0 {\n\n #[doc = r\"Modifies the contents of the register\"]\n\n #[inline(always)]\n\n pub fn modify<F>(&self, f: F)\n\n where\n\n for<'w> F: FnOnce(&R, &'w mut W) -> &'w mut W,\n\n {\n\n let bits = self.register.get();\n\n self.register.set(f(&R { bits }, &mut W { bits }).bits);\n\n }\n\n #[doc = r\"Reads the contents of the register\"]\n\n #[inline(always)]\n", "file_path": "src/adc0/ssmux0.rs", "rank": 40, "score": 60.46770973237478 }, { "content": "#[doc = r\"Value read from the register\"]\n\npub struct R {\n\n bits: u32,\n\n}\n\n#[doc = r\"Value to write to the register\"]\n\npub struct W {\n\n bits: u32,\n\n}\n\nimpl super::IV_IN_3 {\n\n #[doc = r\"Modifies the contents of the register\"]\n\n #[inline(always)]\n\n pub fn modify<F>(&self, f: F)\n\n where\n\n for<'w> F: FnOnce(&R, &'w mut W) -> &'w mut W,\n\n {\n\n let bits = self.register.get();\n\n self.register.set(f(&R { bits }, &mut W { bits }).bits);\n\n }\n\n #[doc = r\"Reads the contents of the register\"]\n\n #[inline(always)]\n", "file_path": "src/aes/iv_in_3.rs", "rank": 41, "score": 60.46770973237478 }, { "content": "#[doc = r\"Value read from the register\"]\n\npub struct R {\n\n bits: u32,\n\n}\n\n#[doc = r\"Value to write to the register\"]\n\npub struct W {\n\n bits: u32,\n\n}\n\nimpl super::DR4R {\n\n #[doc = r\"Modifies the contents of the register\"]\n\n #[inline(always)]\n\n pub fn modify<F>(&self, f: F)\n\n where\n\n for<'w> F: FnOnce(&R, &'w mut W) -> &'w mut W,\n\n {\n\n let bits = self.register.get();\n\n self.register.set(f(&R { bits }, &mut W { bits }).bits);\n\n }\n\n #[doc = r\"Reads the contents of the register\"]\n\n #[inline(always)]\n", "file_path": "src/gpioa/dr4r.rs", "rank": 42, "score": 60.46770973237478 }, { "content": "#[doc = r\"Value read from the register\"]\n\npub struct R {\n\n bits: u32,\n\n}\n\n#[doc = r\"Value to write to the register\"]\n\npub struct W {\n\n bits: u32,\n\n}\n\nimpl super::IF2ARB1 {\n\n #[doc = r\"Modifies the contents of the register\"]\n\n #[inline(always)]\n\n pub fn modify<F>(&self, f: F)\n\n where\n\n for<'w> F: FnOnce(&R, &'w mut W) -> &'w mut W,\n\n {\n\n let bits = self.register.get();\n\n self.register.set(f(&R { bits }, &mut W { bits }).bits);\n\n }\n\n #[doc = r\"Reads the contents of the register\"]\n\n #[inline(always)]\n", "file_path": "src/can0/if2arb1.rs", "rank": 43, "score": 60.46770973237478 }, { "content": "#[doc = r\"Value read from the register\"]\n\npub struct R {\n\n bits: u32,\n\n}\n\n#[doc = r\"Value to write to the register\"]\n\npub struct W {\n\n bits: u32,\n\n}\n\nimpl super::CALM0 {\n\n #[doc = r\"Modifies the contents of the register\"]\n\n #[inline(always)]\n\n pub fn modify<F>(&self, f: F)\n\n where\n\n for<'w> F: FnOnce(&R, &'w mut W) -> &'w mut W,\n\n {\n\n let bits = self.register.get();\n\n self.register.set(f(&R { bits }, &mut W { bits }).bits);\n\n }\n\n #[doc = r\"Reads the contents of the register\"]\n\n #[inline(always)]\n", "file_path": "src/hib/calm0.rs", "rank": 44, "score": 60.46770973237478 }, { "content": "#[doc = r\"Value read from the register\"]\n\npub struct R {\n\n bits: u32,\n\n}\n\n#[doc = r\"Value to write to the register\"]\n\npub struct W {\n\n bits: u32,\n\n}\n\nimpl super::ADCCTL {\n\n #[doc = r\"Modifies the contents of the register\"]\n\n #[inline(always)]\n\n pub fn modify<F>(&self, f: F)\n\n where\n\n for<'w> F: FnOnce(&R, &'w mut W) -> &'w mut W,\n\n {\n\n let bits = self.register.get();\n\n self.register.set(f(&R { bits }, &mut W { bits }).bits);\n\n }\n\n #[doc = r\"Reads the contents of the register\"]\n\n #[inline(always)]\n", "file_path": "src/gpioa/adcctl.rs", "rank": 45, "score": 60.46770973237478 }, { "content": "#[doc = r\"Value read from the register\"]\n\npub struct R {\n\n bits: u32,\n\n}\n\n#[doc = r\"Value to write to the register\"]\n\npub struct W {\n\n bits: u32,\n\n}\n\nimpl super::IF1DB1 {\n\n #[doc = r\"Modifies the contents of the register\"]\n\n #[inline(always)]\n\n pub fn modify<F>(&self, f: F)\n\n where\n\n for<'w> F: FnOnce(&R, &'w mut W) -> &'w mut W,\n\n {\n\n let bits = self.register.get();\n\n self.register.set(f(&R { bits }, &mut W { bits }).bits);\n\n }\n\n #[doc = r\"Reads the contents of the register\"]\n\n #[inline(always)]\n", "file_path": "src/can0/if1db1.rs", "rank": 46, "score": 60.46770973237478 }, { "content": "#[doc = r\"Value read from the register\"]\n\npub struct R {\n\n bits: u32,\n\n}\n\n#[doc = r\"Value to write to the register\"]\n\npub struct W {\n\n bits: u32,\n\n}\n\nimpl super::PP {\n\n #[doc = r\"Modifies the contents of the register\"]\n\n #[inline(always)]\n\n pub fn modify<F>(&self, f: F)\n\n where\n\n for<'w> F: FnOnce(&R, &'w mut W) -> &'w mut W,\n\n {\n\n let bits = self.register.get();\n\n self.register.set(f(&R { bits }, &mut W { bits }).bits);\n\n }\n\n #[doc = r\"Reads the contents of the register\"]\n\n #[inline(always)]\n", "file_path": "src/flash_ctrl/pp.rs", "rank": 47, "score": 60.46770973237478 }, { "content": "#[doc = r\"Value read from the register\"]\n\npub struct R {\n\n bits: u32,\n\n}\n\n#[doc = r\"Value to write to the register\"]\n\npub struct W {\n\n bits: u32,\n\n}\n\nimpl super::_0_MINFLTPER {\n\n #[doc = r\"Modifies the contents of the register\"]\n\n #[inline(always)]\n\n pub fn modify<F>(&self, f: F)\n\n where\n\n for<'w> F: FnOnce(&R, &'w mut W) -> &'w mut W,\n\n {\n\n let bits = self.register.get();\n\n self.register.set(f(&R { bits }, &mut W { bits }).bits);\n\n }\n\n #[doc = r\"Reads the contents of the register\"]\n\n #[inline(always)]\n", "file_path": "src/pwm0/_0_minfltper.rs", "rank": 48, "score": 60.46770973237478 }, { "content": "#[doc = r\"Value read from the register\"]\n\npub struct R {\n\n bits: u32,\n\n}\n\n#[doc = r\"Value to write to the register\"]\n\npub struct W {\n\n bits: u32,\n\n}\n\nimpl super::SDRAMCFG {\n\n #[doc = r\"Modifies the contents of the register\"]\n\n #[inline(always)]\n\n pub fn modify<F>(&self, f: F)\n\n where\n\n for<'w> F: FnOnce(&R, &'w mut W) -> &'w mut W,\n\n {\n\n let bits = self.register.get();\n\n self.register.set(f(&R { bits }, &mut W { bits }).bits);\n\n }\n\n #[doc = r\"Reads the contents of the register\"]\n\n #[inline(always)]\n", "file_path": "src/epi0/sdramcfg.rs", "rank": 49, "score": 60.46770973237478 }, { "content": "#[doc = r\"Value read from the register\"]\n\npub struct R {\n\n bits: u32,\n\n}\n\n#[doc = r\"Value to write to the register\"]\n\npub struct W {\n\n bits: u32,\n\n}\n\nimpl super::SDR {\n\n #[doc = r\"Modifies the contents of the register\"]\n\n #[inline(always)]\n\n pub fn modify<F>(&self, f: F)\n\n where\n\n for<'w> F: FnOnce(&R, &'w mut W) -> &'w mut W,\n\n {\n\n let bits = self.register.get();\n\n self.register.set(f(&R { bits }, &mut W { bits }).bits);\n\n }\n\n #[doc = r\"Reads the contents of the register\"]\n\n #[inline(always)]\n", "file_path": "src/i2c0/sdr.rs", "rank": 50, "score": 60.46770973237478 }, { "content": "#[doc = r\"Value read from the register\"]\n\npub struct R {\n\n bits: u32,\n\n}\n\n#[doc = r\"Value to write to the register\"]\n\npub struct W {\n\n bits: u32,\n\n}\n\nimpl super::IRQENABLE {\n\n #[doc = r\"Modifies the contents of the register\"]\n\n #[inline(always)]\n\n pub fn modify<F>(&self, f: F)\n\n where\n\n for<'w> F: FnOnce(&R, &'w mut W) -> &'w mut W,\n\n {\n\n let bits = self.register.get();\n\n self.register.set(f(&R { bits }, &mut W { bits }).bits);\n\n }\n\n #[doc = r\"Reads the contents of the register\"]\n\n #[inline(always)]\n", "file_path": "src/aes/irqenable.rs", "rank": 51, "score": 60.46770973237478 }, { "content": "#[doc = r\"Value read from the register\"]\n\npub struct R {\n\n bits: u32,\n\n}\n\n#[doc = r\"Value to write to the register\"]\n\npub struct W {\n\n bits: u32,\n\n}\n\nimpl super::IF1DB2 {\n\n #[doc = r\"Modifies the contents of the register\"]\n\n #[inline(always)]\n\n pub fn modify<F>(&self, f: F)\n\n where\n\n for<'w> F: FnOnce(&R, &'w mut W) -> &'w mut W,\n\n {\n\n let bits = self.register.get();\n\n self.register.set(f(&R { bits }, &mut W { bits }).bits);\n\n }\n\n #[doc = r\"Reads the contents of the register\"]\n\n #[inline(always)]\n", "file_path": "src/can0/if1db2.rs", "rank": 52, "score": 60.46770973237478 }, { "content": "#[doc = r\"Value read from the register\"]\n\npub struct R {\n\n bits: u32,\n\n}\n\n#[doc = r\"Value to write to the register\"]\n\npub struct W {\n\n bits: u32,\n\n}\n\nimpl super::MMCCTRL {\n\n #[doc = r\"Modifies the contents of the register\"]\n\n #[inline(always)]\n\n pub fn modify<F>(&self, f: F)\n\n where\n\n for<'w> F: FnOnce(&R, &'w mut W) -> &'w mut W,\n\n {\n\n let bits = self.register.get();\n\n self.register.set(f(&R { bits }, &mut W { bits }).bits);\n\n }\n\n #[doc = r\"Reads the contents of the register\"]\n\n #[inline(always)]\n", "file_path": "src/emac0/mmcctrl.rs", "rank": 53, "score": 60.46770973237478 }, { "content": "#[doc = r\"Value read from the register\"]\n\npub struct R {\n\n bits: u32,\n\n}\n\n#[doc = r\"Value to write to the register\"]\n\npub struct W {\n\n bits: u32,\n\n}\n\nimpl super::HB16CFG {\n\n #[doc = r\"Modifies the contents of the register\"]\n\n #[inline(always)]\n\n pub fn modify<F>(&self, f: F)\n\n where\n\n for<'w> F: FnOnce(&R, &'w mut W) -> &'w mut W,\n\n {\n\n let bits = self.register.get();\n\n self.register.set(f(&R { bits }, &mut W { bits }).bits);\n\n }\n\n #[doc = r\"Reads the contents of the register\"]\n\n #[inline(always)]\n", "file_path": "src/epi0/hb16cfg.rs", "rank": 54, "score": 60.46770973237478 }, { "content": "#[doc = r\"Value read from the register\"]\n\npub struct R {\n\n bits: u32,\n\n}\n\n#[doc = r\"Value to write to the register\"]\n\npub struct W {\n\n bits: u32,\n\n}\n\nimpl super::IF2DA1 {\n\n #[doc = r\"Modifies the contents of the register\"]\n\n #[inline(always)]\n\n pub fn modify<F>(&self, f: F)\n\n where\n\n for<'w> F: FnOnce(&R, &'w mut W) -> &'w mut W,\n\n {\n\n let bits = self.register.get();\n\n self.register.set(f(&R { bits }, &mut W { bits }).bits);\n\n }\n\n #[doc = r\"Reads the contents of the register\"]\n\n #[inline(always)]\n", "file_path": "src/can0/if2da1.rs", "rank": 55, "score": 60.46770973237478 }, { "content": "#[doc = r\"Value read from the register\"]\n\npub struct R {\n\n bits: u32,\n\n}\n\n#[doc = r\"Value to write to the register\"]\n\npub struct W {\n\n bits: u32,\n\n}\n\nimpl super::ADDR0H {\n\n #[doc = r\"Modifies the contents of the register\"]\n\n #[inline(always)]\n\n pub fn modify<F>(&self, f: F)\n\n where\n\n for<'w> F: FnOnce(&R, &'w mut W) -> &'w mut W,\n\n {\n\n let bits = self.register.get();\n\n self.register.set(f(&R { bits }, &mut W { bits }).bits);\n\n }\n\n #[doc = r\"Reads the contents of the register\"]\n\n #[inline(always)]\n", "file_path": "src/emac0/addr0h.rs", "rank": 56, "score": 60.46770973237478 }, { "content": "#[doc = r\"Value read from the register\"]\n\npub struct R {\n\n bits: u32,\n\n}\n\n#[doc = r\"Value to write to the register\"]\n\npub struct W {\n\n bits: u32,\n\n}\n\nimpl super::FMPRE13 {\n\n #[doc = r\"Modifies the contents of the register\"]\n\n #[inline(always)]\n\n pub fn modify<F>(&self, f: F)\n\n where\n\n for<'w> F: FnOnce(&R, &'w mut W) -> &'w mut W,\n\n {\n\n let bits = self.register.get();\n\n self.register.set(f(&R { bits }, &mut W { bits }).bits);\n\n }\n\n #[doc = r\"Reads the contents of the register\"]\n\n #[inline(always)]\n", "file_path": "src/flash_ctrl/fmpre13.rs", "rank": 57, "score": 60.46770973237478 }, { "content": "#[doc = r\"Value read from the register\"]\n\npub struct R {\n\n bits: u32,\n\n}\n\n#[doc = r\"Value to write to the register\"]\n\npub struct W {\n\n bits: u32,\n\n}\n\nimpl super::STATUS {\n\n #[doc = r\"Modifies the contents of the register\"]\n\n #[inline(always)]\n\n pub fn modify<F>(&self, f: F)\n\n where\n\n for<'w> F: FnOnce(&R, &'w mut W) -> &'w mut W,\n\n {\n\n let bits = self.register.get();\n\n self.register.set(f(&R { bits }, &mut W { bits }).bits);\n\n }\n\n #[doc = r\"Reads the contents of the register\"]\n\n #[inline(always)]\n", "file_path": "src/pwm0/status.rs", "rank": 58, "score": 60.46770973237478 }, { "content": "#[doc = r\"Value read from the register\"]\n\npub struct R {\n\n bits: u32,\n\n}\n\n#[doc = r\"Value to write to the register\"]\n\npub struct W {\n\n bits: u32,\n\n}\n\nimpl super::HB16CFG4 {\n\n #[doc = r\"Modifies the contents of the register\"]\n\n #[inline(always)]\n\n pub fn modify<F>(&self, f: F)\n\n where\n\n for<'w> F: FnOnce(&R, &'w mut W) -> &'w mut W,\n\n {\n\n let bits = self.register.get();\n\n self.register.set(f(&R { bits }, &mut W { bits }).bits);\n\n }\n\n #[doc = r\"Reads the contents of the register\"]\n\n #[inline(always)]\n", "file_path": "src/epi0/hb16cfg4.rs", "rank": 59, "score": 60.46770973237478 }, { "content": "#[doc = r\"Value read from the register\"]\n\npub struct R {\n\n bits: u32,\n\n}\n\n#[doc = r\"Value to write to the register\"]\n\npub struct W {\n\n bits: u32,\n\n}\n\nimpl super::IEV {\n\n #[doc = r\"Modifies the contents of the register\"]\n\n #[inline(always)]\n\n pub fn modify<F>(&self, f: F)\n\n where\n\n for<'w> F: FnOnce(&R, &'w mut W) -> &'w mut W,\n\n {\n\n let bits = self.register.get();\n\n self.register.set(f(&R { bits }, &mut W { bits }).bits);\n\n }\n\n #[doc = r\"Reads the contents of the register\"]\n\n #[inline(always)]\n", "file_path": "src/gpioa/iev.rs", "rank": 60, "score": 60.46770973237478 }, { "content": "#[doc = r\"Value read from the register\"]\n\npub struct R {\n\n bits: u32,\n\n}\n\n#[doc = r\"Value to write to the register\"]\n\npub struct W {\n\n bits: u32,\n\n}\n\nimpl super::ACREFCTL {\n\n #[doc = r\"Modifies the contents of the register\"]\n\n #[inline(always)]\n\n pub fn modify<F>(&self, f: F)\n\n where\n\n for<'w> F: FnOnce(&R, &'w mut W) -> &'w mut W,\n\n {\n\n let bits = self.register.get();\n\n self.register.set(f(&R { bits }, &mut W { bits }).bits);\n\n }\n\n #[doc = r\"Reads the contents of the register\"]\n\n #[inline(always)]\n", "file_path": "src/comp/acrefctl.rs", "rank": 61, "score": 60.46770973237478 }, { "content": "#[doc = r\"Value read from the register\"]\n\npub struct R {\n\n bits: u32,\n\n}\n\n#[doc = r\"Value to write to the register\"]\n\npub struct W {\n\n bits: u32,\n\n}\n\nimpl super::EEHIDE1 {\n\n #[doc = r\"Modifies the contents of the register\"]\n\n #[inline(always)]\n\n pub fn modify<F>(&self, f: F)\n\n where\n\n for<'w> F: FnOnce(&R, &'w mut W) -> &'w mut W,\n\n {\n\n let bits = self.register.get();\n\n self.register.set(f(&R { bits }, &mut W { bits }).bits);\n\n }\n\n #[doc = r\"Reads the contents of the register\"]\n\n #[inline(always)]\n", "file_path": "src/eeprom/eehide1.rs", "rank": 62, "score": 60.46770973237478 }, { "content": "#[doc = r\"Value read from the register\"]\n\npub struct R {\n\n bits: u32,\n\n}\n\n#[doc = r\"Value to write to the register\"]\n\npub struct W {\n\n bits: u32,\n\n}\n\nimpl super::FMPPE6 {\n\n #[doc = r\"Modifies the contents of the register\"]\n\n #[inline(always)]\n\n pub fn modify<F>(&self, f: F)\n\n where\n\n for<'w> F: FnOnce(&R, &'w mut W) -> &'w mut W,\n\n {\n\n let bits = self.register.get();\n\n self.register.set(f(&R { bits }, &mut W { bits }).bits);\n\n }\n\n #[doc = r\"Reads the contents of the register\"]\n\n #[inline(always)]\n", "file_path": "src/flash_ctrl/fmppe6.rs", "rank": 63, "score": 60.46770973237478 }, { "content": "#[doc = r\"Value read from the register\"]\n\npub struct R {\n\n bits: u32,\n\n}\n\n#[doc = r\"Value to write to the register\"]\n\npub struct W {\n\n bits: u32,\n\n}\n\nimpl super::FMPPE10 {\n\n #[doc = r\"Modifies the contents of the register\"]\n\n #[inline(always)]\n\n pub fn modify<F>(&self, f: F)\n\n where\n\n for<'w> F: FnOnce(&R, &'w mut W) -> &'w mut W,\n\n {\n\n let bits = self.register.get();\n\n self.register.set(f(&R { bits }, &mut W { bits }).bits);\n\n }\n\n #[doc = r\"Reads the contents of the register\"]\n\n #[inline(always)]\n", "file_path": "src/flash_ctrl/fmppe10.rs", "rank": 64, "score": 60.46770973237478 }, { "content": "#[doc = r\"Value read from the register\"]\n\npub struct R {\n\n bits: u32,\n\n}\n\n#[doc = r\"Value to write to the register\"]\n\npub struct W {\n\n bits: u32,\n\n}\n\nimpl super::_0_ISC {\n\n #[doc = r\"Modifies the contents of the register\"]\n\n #[inline(always)]\n\n pub fn modify<F>(&self, f: F)\n\n where\n\n for<'w> F: FnOnce(&R, &'w mut W) -> &'w mut W,\n\n {\n\n let bits = self.register.get();\n\n self.register.set(f(&R { bits }, &mut W { bits }).bits);\n\n }\n\n #[doc = r\"Reads the contents of the register\"]\n\n #[inline(always)]\n", "file_path": "src/pwm0/_0_isc.rs", "rank": 65, "score": 60.46770973237478 }, { "content": "#[doc = r\"Value read from the register\"]\n\npub struct R {\n\n bits: u32,\n\n}\n\n#[doc = r\"Value to write to the register\"]\n\npub struct W {\n\n bits: u32,\n\n}\n\nimpl super::DATA {\n\n #[doc = r\"Modifies the contents of the register\"]\n\n #[inline(always)]\n\n pub fn modify<F>(&self, f: F)\n\n where\n\n for<'w> F: FnOnce(&R, &'w mut W) -> &'w mut W,\n\n {\n\n let bits = self.register.get();\n\n self.register.set(f(&R { bits }, &mut W { bits }).bits);\n\n }\n\n #[doc = r\"Reads the contents of the register\"]\n\n #[inline(always)]\n", "file_path": "src/gpioa/data.rs", "rank": 66, "score": 60.467709732374786 }, { "content": "#[doc = r\"Value read from the register\"]\n\npub struct R {\n\n bits: u32,\n\n}\n\n#[doc = r\"Value to write to the register\"]\n\npub struct W {\n\n bits: u32,\n\n}\n\nimpl super::KEY1_4 {\n\n #[doc = r\"Modifies the contents of the register\"]\n\n #[inline(always)]\n\n pub fn modify<F>(&self, f: F)\n\n where\n\n for<'w> F: FnOnce(&R, &'w mut W) -> &'w mut W,\n\n {\n\n let bits = self.register.get();\n\n self.register.set(f(&R { bits }, &mut W { bits }).bits);\n\n }\n\n #[doc = r\"Reads the contents of the register\"]\n\n #[inline(always)]\n", "file_path": "src/aes/key1_4.rs", "rank": 67, "score": 60.46770973237478 }, { "content": "#[doc = r\"Value read from the register\"]\n\npub struct R {\n\n bits: u32,\n\n}\n\n#[doc = r\"Value to write to the register\"]\n\npub struct W {\n\n bits: u32,\n\n}\n\nimpl super::DATA_IN_0 {\n\n #[doc = r\"Modifies the contents of the register\"]\n\n #[inline(always)]\n\n pub fn modify<F>(&self, f: F)\n\n where\n\n for<'w> F: FnOnce(&R, &'w mut W) -> &'w mut W,\n\n {\n\n let bits = self.register.get();\n\n self.register.set(f(&R { bits }, &mut W { bits }).bits);\n\n }\n\n #[doc = r\"Reads the contents of the register\"]\n\n #[inline(always)]\n", "file_path": "src/aes/data_in_0.rs", "rank": 68, "score": 60.46770973237478 }, { "content": "#[doc = r\"Value read from the register\"]\n\npub struct R {\n\n bits: u32,\n\n}\n\n#[doc = r\"Value to write to the register\"]\n\npub struct W {\n\n bits: u32,\n\n}\n\nimpl super::ACSTAT0 {\n\n #[doc = r\"Modifies the contents of the register\"]\n\n #[inline(always)]\n\n pub fn modify<F>(&self, f: F)\n\n where\n\n for<'w> F: FnOnce(&R, &'w mut W) -> &'w mut W,\n\n {\n\n let bits = self.register.get();\n\n self.register.set(f(&R { bits }, &mut W { bits }).bits);\n\n }\n\n #[doc = r\"Reads the contents of the register\"]\n\n #[inline(always)]\n", "file_path": "src/comp/acstat0.rs", "rank": 69, "score": 60.46770973237478 }, { "content": "#[doc = r\"Value read from the register\"]\n\npub struct R {\n\n bits: u32,\n\n}\n\n#[doc = r\"Value to write to the register\"]\n\npub struct W {\n\n bits: u32,\n\n}\n\nimpl super::HOSTXBA {\n\n #[doc = r\"Modifies the contents of the register\"]\n\n #[inline(always)]\n\n pub fn modify<F>(&self, f: F)\n\n where\n\n for<'w> F: FnOnce(&R, &'w mut W) -> &'w mut W,\n\n {\n\n let bits = self.register.get();\n\n self.register.set(f(&R { bits }, &mut W { bits }).bits);\n\n }\n\n #[doc = r\"Reads the contents of the register\"]\n\n #[inline(always)]\n", "file_path": "src/emac0/hostxba.rs", "rank": 70, "score": 60.46770973237478 }, { "content": "#[doc = r\"Value read from the register\"]\n\npub struct R {\n\n bits: u32,\n\n}\n\n#[doc = r\"Value to write to the register\"]\n\npub struct W {\n\n bits: u32,\n\n}\n\nimpl super::FMPRE3 {\n\n #[doc = r\"Modifies the contents of the register\"]\n\n #[inline(always)]\n\n pub fn modify<F>(&self, f: F)\n\n where\n\n for<'w> F: FnOnce(&R, &'w mut W) -> &'w mut W,\n\n {\n\n let bits = self.register.get();\n\n self.register.set(f(&R { bits }, &mut W { bits }).bits);\n\n }\n\n #[doc = r\"Reads the contents of the register\"]\n\n #[inline(always)]\n", "file_path": "src/flash_ctrl/fmpre3.rs", "rank": 71, "score": 60.46770973237478 }, { "content": "#[doc = r\"Value read from the register\"]\n\npub struct R {\n\n bits: u32,\n\n}\n\n#[doc = r\"Value to write to the register\"]\n\npub struct W {\n\n bits: u32,\n\n}\n\nimpl super::KEY2_4 {\n\n #[doc = r\"Modifies the contents of the register\"]\n\n #[inline(always)]\n\n pub fn modify<F>(&self, f: F)\n\n where\n\n for<'w> F: FnOnce(&R, &'w mut W) -> &'w mut W,\n\n {\n\n let bits = self.register.get();\n\n self.register.set(f(&R { bits }, &mut W { bits }).bits);\n\n }\n\n #[doc = r\"Reads the contents of the register\"]\n\n #[inline(always)]\n", "file_path": "src/aes/key2_4.rs", "rank": 72, "score": 60.46770973237478 }, { "content": "#[doc = r\"Value read from the register\"]\n\npub struct R {\n\n bits: u32,\n\n}\n\n#[doc = r\"Value to write to the register\"]\n\npub struct W {\n\n bits: u32,\n\n}\n\nimpl super::SSIZE {\n\n #[doc = r\"Modifies the contents of the register\"]\n\n #[inline(always)]\n\n pub fn modify<F>(&self, f: F)\n\n where\n\n for<'w> F: FnOnce(&R, &'w mut W) -> &'w mut W,\n\n {\n\n let bits = self.register.get();\n\n self.register.set(f(&R { bits }, &mut W { bits }).bits);\n\n }\n\n #[doc = r\"Reads the contents of the register\"]\n\n #[inline(always)]\n", "file_path": "src/flash_ctrl/ssize.rs", "rank": 73, "score": 60.46770973237478 }, { "content": "#[doc = r\"Value read from the register\"]\n\npub struct R {\n\n bits: u32,\n\n}\n\n#[doc = r\"Value to write to the register\"]\n\npub struct W {\n\n bits: u32,\n\n}\n\nimpl super::FMPPE5 {\n\n #[doc = r\"Modifies the contents of the register\"]\n\n #[inline(always)]\n\n pub fn modify<F>(&self, f: F)\n\n where\n\n for<'w> F: FnOnce(&R, &'w mut W) -> &'w mut W,\n\n {\n\n let bits = self.register.get();\n\n self.register.set(f(&R { bits }, &mut W { bits }).bits);\n\n }\n\n #[doc = r\"Reads the contents of the register\"]\n\n #[inline(always)]\n", "file_path": "src/flash_ctrl/fmppe5.rs", "rank": 74, "score": 60.46770973237478 }, { "content": "#[doc = r\"Value read from the register\"]\n\npub struct R {\n\n bits: u32,\n\n}\n\n#[doc = r\"Value to write to the register\"]\n\npub struct W {\n\n bits: u32,\n\n}\n\nimpl super::SLR {\n\n #[doc = r\"Modifies the contents of the register\"]\n\n #[inline(always)]\n\n pub fn modify<F>(&self, f: F)\n\n where\n\n for<'w> F: FnOnce(&R, &'w mut W) -> &'w mut W,\n\n {\n\n let bits = self.register.get();\n\n self.register.set(f(&R { bits }, &mut W { bits }).bits);\n\n }\n\n #[doc = r\"Reads the contents of the register\"]\n\n #[inline(always)]\n", "file_path": "src/gpioa/slr.rs", "rank": 75, "score": 60.46770973237478 }, { "content": "#[doc = r\"Value read from the register\"]\n\npub struct R {\n\n bits: u32,\n\n}\n\n#[doc = r\"Value to write to the register\"]\n\npub struct W {\n\n bits: u32,\n\n}\n\nimpl super::DIRTYBITS {\n\n #[doc = r\"Modifies the contents of the register\"]\n\n #[inline(always)]\n\n pub fn modify<F>(&self, f: F)\n\n where\n\n for<'w> F: FnOnce(&R, &'w mut W) -> &'w mut W,\n\n {\n\n let bits = self.register.get();\n\n self.register.set(f(&R { bits }, &mut W { bits }).bits);\n\n }\n\n #[doc = r\"Reads the contents of the register\"]\n\n #[inline(always)]\n", "file_path": "src/aes/dirtybits.rs", "rank": 76, "score": 60.46770973237478 }, { "content": "#[doc = r\"Value read from the register\"]\n\npub struct R {\n\n bits: u32,\n\n}\n\n#[doc = r\"Value to write to the register\"]\n\npub struct W {\n\n bits: u32,\n\n}\n\nimpl super::BAUD2 {\n\n #[doc = r\"Modifies the contents of the register\"]\n\n #[inline(always)]\n\n pub fn modify<F>(&self, f: F)\n\n where\n\n for<'w> F: FnOnce(&R, &'w mut W) -> &'w mut W,\n\n {\n\n let bits = self.register.get();\n\n self.register.set(f(&R { bits }, &mut W { bits }).bits);\n\n }\n\n #[doc = r\"Reads the contents of the register\"]\n\n #[inline(always)]\n", "file_path": "src/epi0/baud2.rs", "rank": 77, "score": 60.46770973237478 }, { "content": "#[doc = r\"Value read from the register\"]\n\npub struct R {\n\n bits: u32,\n\n}\n\n#[doc = r\"Value to write to the register\"]\n\npub struct W {\n\n bits: u32,\n\n}\n\nimpl super::FMPPE13 {\n\n #[doc = r\"Modifies the contents of the register\"]\n\n #[inline(always)]\n\n pub fn modify<F>(&self, f: F)\n\n where\n\n for<'w> F: FnOnce(&R, &'w mut W) -> &'w mut W,\n\n {\n\n let bits = self.register.get();\n\n self.register.set(f(&R { bits }, &mut W { bits }).bits);\n\n }\n\n #[doc = r\"Reads the contents of the register\"]\n\n #[inline(always)]\n", "file_path": "src/flash_ctrl/fmppe13.rs", "rank": 78, "score": 60.46770973237478 }, { "content": "#[doc = r\"Value read from the register\"]\n\npub struct R {\n\n bits: u32,\n\n}\n\n#[doc = r\"Value to write to the register\"]\n\npub struct W {\n\n bits: u32,\n\n}\n\nimpl super::_1_ISC {\n\n #[doc = r\"Modifies the contents of the register\"]\n\n #[inline(always)]\n\n pub fn modify<F>(&self, f: F)\n\n where\n\n for<'w> F: FnOnce(&R, &'w mut W) -> &'w mut W,\n\n {\n\n let bits = self.register.get();\n\n self.register.set(f(&R { bits }, &mut W { bits }).bits);\n\n }\n\n #[doc = r\"Reads the contents of the register\"]\n\n #[inline(always)]\n", "file_path": "src/pwm0/_1_isc.rs", "rank": 79, "score": 60.46770973237478 }, { "content": "#[doc = r\"Value read from the register\"]\n\npub struct R {\n\n bits: u32,\n\n}\n\n#[doc = r\"Value to write to the register\"]\n\npub struct W {\n\n bits: u32,\n\n}\n\nimpl super::TPLOG0 {\n\n #[doc = r\"Modifies the contents of the register\"]\n\n #[inline(always)]\n\n pub fn modify<F>(&self, f: F)\n\n where\n\n for<'w> F: FnOnce(&R, &'w mut W) -> &'w mut W,\n\n {\n\n let bits = self.register.get();\n\n self.register.set(f(&R { bits }, &mut W { bits }).bits);\n\n }\n\n #[doc = r\"Reads the contents of the register\"]\n\n #[inline(always)]\n", "file_path": "src/hib/tplog0.rs", "rank": 80, "score": 60.46770973237478 }, { "content": "#[doc = r\"Value read from the register\"]\n\npub struct R {\n\n bits: u32,\n\n}\n\n#[doc = r\"Value to write to the register\"]\n\npub struct W {\n\n bits: u32,\n\n}\n\nimpl super::SSOP3 {\n\n #[doc = r\"Modifies the contents of the register\"]\n\n #[inline(always)]\n\n pub fn modify<F>(&self, f: F)\n\n where\n\n for<'w> F: FnOnce(&R, &'w mut W) -> &'w mut W,\n\n {\n\n let bits = self.register.get();\n\n self.register.set(f(&R { bits }, &mut W { bits }).bits);\n\n }\n\n #[doc = r\"Reads the contents of the register\"]\n\n #[inline(always)]\n", "file_path": "src/adc0/ssop3.rs", "rank": 81, "score": 60.46770973237478 }, { "content": "#[doc = r\"Value read from the register\"]\n\npub struct R {\n\n bits: u32,\n\n}\n\n#[doc = r\"Value to write to the register\"]\n\npub struct W {\n\n bits: u32,\n\n}\n\nimpl super::BRPE {\n\n #[doc = r\"Modifies the contents of the register\"]\n\n #[inline(always)]\n\n pub fn modify<F>(&self, f: F)\n\n where\n\n for<'w> F: FnOnce(&R, &'w mut W) -> &'w mut W,\n\n {\n\n let bits = self.register.get();\n\n self.register.set(f(&R { bits }, &mut W { bits }).bits);\n\n }\n\n #[doc = r\"Reads the contents of the register\"]\n\n #[inline(always)]\n", "file_path": "src/can0/brpe.rs", "rank": 82, "score": 60.46770973237478 }, { "content": "#[doc = r\"Value read from the register\"]\n\npub struct R {\n\n bits: u32,\n\n}\n\n#[doc = r\"Value to write to the register\"]\n\npub struct W {\n\n bits: u32,\n\n}\n\nimpl super::MSG2VAL {\n\n #[doc = r\"Modifies the contents of the register\"]\n\n #[inline(always)]\n\n pub fn modify<F>(&self, f: F)\n\n where\n\n for<'w> F: FnOnce(&R, &'w mut W) -> &'w mut W,\n\n {\n\n let bits = self.register.get();\n\n self.register.set(f(&R { bits }, &mut W { bits }).bits);\n\n }\n\n #[doc = r\"Reads the contents of the register\"]\n\n #[inline(always)]\n", "file_path": "src/can0/msg2val.rs", "rank": 83, "score": 60.46770973237478 }, { "content": "#[doc = r\"Value read from the register\"]\n\npub struct R {\n\n bits: u32,\n\n}\n\n#[doc = r\"Value to write to the register\"]\n\npub struct W {\n\n bits: u32,\n\n}\n\nimpl super::REVISION {\n\n #[doc = r\"Modifies the contents of the register\"]\n\n #[inline(always)]\n\n pub fn modify<F>(&self, f: F)\n\n where\n\n for<'w> F: FnOnce(&R, &'w mut W) -> &'w mut W,\n\n {\n\n let bits = self.register.get();\n\n self.register.set(f(&R { bits }, &mut W { bits }).bits);\n\n }\n\n #[doc = r\"Reads the contents of the register\"]\n\n #[inline(always)]\n", "file_path": "src/aes/revision.rs", "rank": 84, "score": 60.46770973237478 }, { "content": "#[doc = r\"Value read from the register\"]\n\npub struct R {\n\n bits: u32,\n\n}\n\n#[doc = r\"Value to write to the register\"]\n\npub struct W {\n\n bits: u32,\n\n}\n\nimpl super::REVISION {\n\n #[doc = r\"Modifies the contents of the register\"]\n\n #[inline(always)]\n\n pub fn modify<F>(&self, f: F)\n\n where\n\n for<'w> F: FnOnce(&R, &'w mut W) -> &'w mut W,\n\n {\n\n let bits = self.register.get();\n\n self.register.set(f(&R { bits }, &mut W { bits }).bits);\n\n }\n\n #[doc = r\"Reads the contents of the register\"]\n\n #[inline(always)]\n", "file_path": "src/des/revision.rs", "rank": 85, "score": 60.46770973237478 }, { "content": "#[doc = r\"Value read from the register\"]\n\npub struct R {\n\n bits: u32,\n\n}\n\n#[doc = r\"Value to write to the register\"]\n\npub struct W {\n\n bits: u32,\n\n}\n\nimpl super::VLNINCREP {\n\n #[doc = r\"Modifies the contents of the register\"]\n\n #[inline(always)]\n\n pub fn modify<F>(&self, f: F)\n\n where\n\n for<'w> F: FnOnce(&R, &'w mut W) -> &'w mut W,\n\n {\n\n let bits = self.register.get();\n\n self.register.set(f(&R { bits }, &mut W { bits }).bits);\n\n }\n\n #[doc = r\"Reads the contents of the register\"]\n\n #[inline(always)]\n", "file_path": "src/emac0/vlnincrep.rs", "rank": 86, "score": 60.46770973237478 }, { "content": "#[doc = r\"Value read from the register\"]\n\npub struct R {\n\n bits: u32,\n\n}\n\n#[doc = r\"Value to write to the register\"]\n\npub struct W {\n\n bits: u32,\n\n}\n\nimpl super::FMPPE0 {\n\n #[doc = r\"Modifies the contents of the register\"]\n\n #[inline(always)]\n\n pub fn modify<F>(&self, f: F)\n\n where\n\n for<'w> F: FnOnce(&R, &'w mut W) -> &'w mut W,\n\n {\n\n let bits = self.register.get();\n\n self.register.set(f(&R { bits }, &mut W { bits }).bits);\n\n }\n\n #[doc = r\"Reads the contents of the register\"]\n\n #[inline(always)]\n", "file_path": "src/flash_ctrl/fmppe0.rs", "rank": 87, "score": 60.46770973237478 }, { "content": "#[doc = r\"Value read from the register\"]\n\npub struct R {\n\n bits: u32,\n\n}\n\n#[doc = r\"Value to write to the register\"]\n\npub struct W {\n\n bits: u32,\n\n}\n\nimpl super::EEPASS2 {\n\n #[doc = r\"Modifies the contents of the register\"]\n\n #[inline(always)]\n\n pub fn modify<F>(&self, f: F)\n\n where\n\n for<'w> F: FnOnce(&R, &'w mut W) -> &'w mut W,\n\n {\n\n let bits = self.register.get();\n\n self.register.set(f(&R { bits }, &mut W { bits }).bits);\n\n }\n\n #[doc = r\"Reads the contents of the register\"]\n\n #[inline(always)]\n", "file_path": "src/eeprom/eepass2.rs", "rank": 88, "score": 60.46770973237478 }, { "content": "#[doc = r\"Value read from the register\"]\n\npub struct R {\n\n bits: u32,\n\n}\n\n#[doc = r\"Value to write to the register\"]\n\npub struct W {\n\n bits: u32,\n\n}\n\nimpl super::SSCTL3 {\n\n #[doc = r\"Modifies the contents of the register\"]\n\n #[inline(always)]\n\n pub fn modify<F>(&self, f: F)\n\n where\n\n for<'w> F: FnOnce(&R, &'w mut W) -> &'w mut W,\n\n {\n\n let bits = self.register.get();\n\n self.register.set(f(&R { bits }, &mut W { bits }).bits);\n\n }\n\n #[doc = r\"Reads the contents of the register\"]\n\n #[inline(always)]\n", "file_path": "src/adc0/ssctl3.rs", "rank": 89, "score": 60.46770973237478 }, { "content": "#[doc = r\"Value read from the register\"]\n\npub struct R {\n\n bits: u32,\n\n}\n\n#[doc = r\"Value to write to the register\"]\n\npub struct W {\n\n bits: u32,\n\n}\n\nimpl super::MBCNT {\n\n #[doc = r\"Modifies the contents of the register\"]\n\n #[inline(always)]\n\n pub fn modify<F>(&self, f: F)\n\n where\n\n for<'w> F: FnOnce(&R, &'w mut W) -> &'w mut W,\n\n {\n\n let bits = self.register.get();\n\n self.register.set(f(&R { bits }, &mut W { bits }).bits);\n\n }\n\n #[doc = r\"Reads the contents of the register\"]\n\n #[inline(always)]\n", "file_path": "src/i2c0/mbcnt.rs", "rank": 90, "score": 60.46770973237478 }, { "content": "#[doc = r\"Value read from the register\"]\n\npub struct R {\n\n bits: u32,\n\n}\n\n#[doc = r\"Value to write to the register\"]\n\npub struct W {\n\n bits: u32,\n\n}\n\nimpl super::CALM1 {\n\n #[doc = r\"Modifies the contents of the register\"]\n\n #[inline(always)]\n\n pub fn modify<F>(&self, f: F)\n\n where\n\n for<'w> F: FnOnce(&R, &'w mut W) -> &'w mut W,\n\n {\n\n let bits = self.register.get();\n\n self.register.set(f(&R { bits }, &mut W { bits }).bits);\n\n }\n\n #[doc = r\"Reads the contents of the register\"]\n\n #[inline(always)]\n", "file_path": "src/hib/calm1.rs", "rank": 91, "score": 60.46770973237478 }, { "content": "#[doc = r\"Value read from the register\"]\n\npub struct R {\n\n bits: u32,\n\n}\n\n#[doc = r\"Value to write to the register\"]\n\npub struct W {\n\n bits: u32,\n\n}\n\nimpl super::TIMNANOU {\n\n #[doc = r\"Modifies the contents of the register\"]\n\n #[inline(always)]\n\n pub fn modify<F>(&self, f: F)\n\n where\n\n for<'w> F: FnOnce(&R, &'w mut W) -> &'w mut W,\n\n {\n\n let bits = self.register.get();\n\n self.register.set(f(&R { bits }, &mut W { bits }).bits);\n\n }\n\n #[doc = r\"Reads the contents of the register\"]\n\n #[inline(always)]\n", "file_path": "src/emac0/timnanou.rs", "rank": 92, "score": 60.46770973237478 }, { "content": "#[doc = r\"Value read from the register\"]\n\npub struct R {\n\n bits: u32,\n\n}\n\n#[doc = r\"Value to write to the register\"]\n\npub struct W {\n\n bits: u32,\n\n}\n\nimpl super::ADDRMAP {\n\n #[doc = r\"Modifies the contents of the register\"]\n\n #[inline(always)]\n\n pub fn modify<F>(&self, f: F)\n\n where\n\n for<'w> F: FnOnce(&R, &'w mut W) -> &'w mut W,\n\n {\n\n let bits = self.register.get();\n\n self.register.set(f(&R { bits }, &mut W { bits }).bits);\n\n }\n\n #[doc = r\"Reads the contents of the register\"]\n\n #[inline(always)]\n", "file_path": "src/epi0/addrmap.rs", "rank": 93, "score": 60.46770973237478 }, { "content": "#[doc = r\"Value read from the register\"]\n\npub struct R {\n\n bits: u32,\n\n}\n\n#[doc = r\"Value to write to the register\"]\n\npub struct W {\n\n bits: u32,\n\n}\n\nimpl super::SSEMUX3 {\n\n #[doc = r\"Modifies the contents of the register\"]\n\n #[inline(always)]\n\n pub fn modify<F>(&self, f: F)\n\n where\n\n for<'w> F: FnOnce(&R, &'w mut W) -> &'w mut W,\n\n {\n\n let bits = self.register.get();\n\n self.register.set(f(&R { bits }, &mut W { bits }).bits);\n\n }\n\n #[doc = r\"Reads the contents of the register\"]\n\n #[inline(always)]\n", "file_path": "src/adc0/ssemux3.rs", "rank": 94, "score": 60.46770973237478 }, { "content": "#[doc = r\"Value read from the register\"]\n\npub struct R {\n\n bits: u32,\n\n}\n\n#[doc = r\"Value to write to the register\"]\n\npub struct W {\n\n bits: u32,\n\n}\n\nimpl super::FMPPE15 {\n\n #[doc = r\"Modifies the contents of the register\"]\n\n #[inline(always)]\n\n pub fn modify<F>(&self, f: F)\n\n where\n\n for<'w> F: FnOnce(&R, &'w mut W) -> &'w mut W,\n\n {\n\n let bits = self.register.get();\n\n self.register.set(f(&R { bits }, &mut W { bits }).bits);\n\n }\n\n #[doc = r\"Reads the contents of the register\"]\n\n #[inline(always)]\n", "file_path": "src/flash_ctrl/fmppe15.rs", "rank": 95, "score": 60.467709732374786 }, { "content": "#[doc = r\"Value read from the register\"]\n\npub struct R {\n\n bits: u32,\n\n}\n\n#[doc = r\"Value to write to the register\"]\n\npub struct W {\n\n bits: u32,\n\n}\n\nimpl super::SSTSH2 {\n\n #[doc = r\"Modifies the contents of the register\"]\n\n #[inline(always)]\n\n pub fn modify<F>(&self, f: F)\n\n where\n\n for<'w> F: FnOnce(&R, &'w mut W) -> &'w mut W,\n\n {\n\n let bits = self.register.get();\n\n self.register.set(f(&R { bits }, &mut W { bits }).bits);\n\n }\n\n #[doc = r\"Reads the contents of the register\"]\n\n #[inline(always)]\n", "file_path": "src/adc0/sstsh2.rs", "rank": 96, "score": 60.46770973237478 }, { "content": "#[doc = r\"Value read from the register\"]\n\npub struct R {\n\n bits: u32,\n\n}\n\n#[doc = r\"Value to write to the register\"]\n\npub struct W {\n\n bits: u32,\n\n}\n\nimpl super::SSOP2 {\n\n #[doc = r\"Modifies the contents of the register\"]\n\n #[inline(always)]\n\n pub fn modify<F>(&self, f: F)\n\n where\n\n for<'w> F: FnOnce(&R, &'w mut W) -> &'w mut W,\n\n {\n\n let bits = self.register.get();\n\n self.register.set(f(&R { bits }, &mut W { bits }).bits);\n\n }\n\n #[doc = r\"Reads the contents of the register\"]\n\n #[inline(always)]\n", "file_path": "src/adc0/ssop2.rs", "rank": 97, "score": 60.46770973237478 }, { "content": "#[doc = r\"Value read from the register\"]\n\npub struct R {\n\n bits: u32,\n\n}\n\n#[doc = r\"Value to write to the register\"]\n\npub struct W {\n\n bits: u32,\n\n}\n\nimpl super::IF1ARB2 {\n\n #[doc = r\"Modifies the contents of the register\"]\n\n #[inline(always)]\n\n pub fn modify<F>(&self, f: F)\n\n where\n\n for<'w> F: FnOnce(&R, &'w mut W) -> &'w mut W,\n\n {\n\n let bits = self.register.get();\n\n self.register.set(f(&R { bits }, &mut W { bits }).bits);\n\n }\n\n #[doc = r\"Reads the contents of the register\"]\n\n #[inline(always)]\n", "file_path": "src/can0/if1arb2.rs", "rank": 98, "score": 60.46770973237478 }, { "content": "#[doc = r\"Value read from the register\"]\n\npub struct R {\n\n bits: u32,\n\n}\n\n#[doc = r\"Value to write to the register\"]\n\npub struct W {\n\n bits: u32,\n\n}\n\nimpl super::HB8CFG2 {\n\n #[doc = r\"Modifies the contents of the register\"]\n\n #[inline(always)]\n\n pub fn modify<F>(&self, f: F)\n\n where\n\n for<'w> F: FnOnce(&R, &'w mut W) -> &'w mut W,\n\n {\n\n let bits = self.register.get();\n\n self.register.set(f(&R { bits }, &mut W { bits }).bits);\n\n }\n\n #[doc = r\"Reads the contents of the register\"]\n\n #[inline(always)]\n", "file_path": "src/epi0/hb8cfg2.rs", "rank": 99, "score": 60.46770973237478 } ]
Rust
src/lib.rs
antialize/sql-parse
37ef1b698af74ab5952f7866512b81e0fbbb9deb
#![no_std] #![forbid(unsafe_code)] extern crate alloc; use alloc::vec::Vec; use lexer::Token; use parser::Parser; mod alter; mod create; mod data_type; mod delete; mod drop; mod expression; mod identifier; mod insert_replace; mod issue; mod keywords; mod lexer; mod parser; mod select; mod span; mod sstring; mod statement; mod update; pub use data_type::{DataType, DataTypeProperty, Type}; pub use identifier::Identifier; pub use issue::{Issue, Level}; pub use span::{OptSpanned, Span, Spanned}; pub use sstring::SString; pub use statement::{Statement, Union, UnionType, UnionWith}; pub use alter::{ AlterSpecification, AlterTable, ForeignKeyOn, ForeignKeyOnAction, ForeignKeyOnType, IndexCol, IndexOption, IndexType, }; pub use create::{ CreateAlgorithm, CreateDefinition, CreateFunction, CreateOption, CreateTable, CreateTrigger, CreateView, TableOption, }; pub use delete::{Delete, DeleteFlag}; pub use drop::{ DropDatabase, DropEvent, DropFunction, DropProcedure, DropServer, DropTable, DropTrigger, DropView, }; pub use expression::{ BinaryOperator, Expression, Function, IdentifierPart, Is, UnaryOperator, When, }; pub use insert_replace::{InsertReplace, InsertReplaceFlag, InsertReplaceType}; pub use select::{JoinSpecification, JoinType, Select, SelectFlag, TableReference}; pub use update::{Update, UpdateFlag}; #[derive(Clone, Debug)] pub enum SQLDialect { MariaDB, PostgreSQL, } impl SQLDialect { fn is_postgresql(&self) -> bool { matches!(self, SQLDialect::PostgreSQL) } } #[derive(Clone, Debug)] pub enum SQLArguments { None, Percent, QuestionMark, } #[derive(Clone, Debug)] pub struct ParseOptions { dialect: SQLDialect, arguments: SQLArguments, warn_unquoted_identifiers: bool, warn_none_capital_keywords: bool, list_hack: bool, } impl Default for ParseOptions { fn default() -> Self { Self { dialect: SQLDialect::MariaDB, arguments: SQLArguments::None, warn_none_capital_keywords: false, warn_unquoted_identifiers: false, list_hack: false, } } } impl ParseOptions { pub fn new() -> Self { Default::default() } pub fn dialect(self, dialect: SQLDialect) -> Self { Self { dialect, ..self } } pub fn arguments(self, arguments: SQLArguments) -> Self { Self { arguments, ..self } } pub fn warn_unquoted_identifiers(self, warn_unquoted_identifiers: bool) -> Self { Self { warn_unquoted_identifiers, ..self } } pub fn warn_none_capital_keywords(self, warn_none_capital_keywords: bool) -> Self { Self { warn_none_capital_keywords, ..self } } pub fn list_hack(self, list_hack: bool) -> Self { Self { list_hack, ..self } } } #[macro_export] macro_rules! issue_ice { ( $spanned:expr ) => {{ Issue::err( alloc::format!("Internal compiler error in {}:{}", file!(), line!()), $spanned, ) }}; } #[macro_export] macro_rules! issue_todo { ( $spanned:expr ) => {{ Issue::err( alloc::format!("Not yet implemented {}:{}", file!(), line!()), $spanned, ) }}; } pub fn parse_statements<'a>( src: &'a str, issues: &mut Vec<Issue>, options: &ParseOptions, ) -> Vec<Statement<'a>> { let mut parser = Parser::new(src, issues, options); statement::parse_statements(&mut parser) } pub fn parse_statement<'a>( src: &'a str, issues: &mut Vec<Issue>, options: &ParseOptions, ) -> Option<Statement<'a>> { let mut parser = Parser::new(src, issues, options); match statement::parse_statement(&mut parser) { Ok(Some(v)) => { if parser.token != Token::Eof { parser.expected_error("Unexpected token after statement") } Some(v) } Ok(None) => { parser.expected_error("Statement"); None } Err(_) => None, } }
#![no_std] #![forbid(unsafe_code)] extern crate alloc; use alloc::vec::Vec; use lexer::Token; use parser::Parser; mod alter; mod create; mod data_type; mod delete; mod drop; mod expression; mod identifier; mod insert_replace; mod issue; mod keywords; mod lexer; mod parser; mod select; mod span; mod sstring; mod statement; mod update; pub use data_type::{DataType, DataTypeProperty, Type}; pub use identifier::Identifier; pub use issue::{Issue, Level}; pub use span::{OptSpanned, Span, Spanned}; pub use sstring::SString; pub use statement::{Statement, Union, UnionType, UnionWith}; pub use alter::{ AlterSpecification, AlterTable, ForeignKeyOn, ForeignKeyOnAction, ForeignKeyOnType, IndexCol, IndexOption, IndexType, }; pub use create::{ CreateAlgorithm, CreateDefinition, CreateFunction, CreateOption, CreateTable, CreateTrigger, CreateView, TableOption, }; pub use delete::{Delete, DeleteFlag}; pub use drop::{ DropDatabase, DropEvent, DropFunction, DropProcedure, DropServer, DropTable, DropTrigger, DropView, }; pub use expression::{ BinaryOperator, Expression, Function, IdentifierPart, Is, UnaryOperator, When, }; pub use insert_replace::{InsertReplace, InsertReplaceFlag, InsertReplaceType}; pub use select::{JoinSpecification, JoinType, Select, SelectFlag, TableReference}; pub use update::{Update, UpdateFlag}; #[derive(Clone, Debug)] pub enum SQLDialect { MariaDB, PostgreSQL, } impl SQLDialect { fn is_postgresql(&self) -> bool { matches!(self, SQLDialect::PostgreSQL) } } #[derive(Clone, Debug)] pub enum SQLArguments { None, Percent, QuestionMark, } #[derive(Clone, Debug)] pub struct ParseOptions { dialect: SQLDialect, arguments: SQLArguments, warn_unquoted_identifiers: bool, warn_none_capital_keywords: bool, list_hack: bool, } impl Default for ParseOptions { fn default() -> Self { Self { dialect: SQLDialect::MariaDB, arguments: SQLArguments::None, warn_none_capital_keywords: false, warn_unquoted_identifiers: false, list_hack: false, } } } impl ParseOptions { pub fn new() -> Self { Default::default() } pub fn dialect(self, dialect: SQLDialect) -> Self { Self { dialect, ..self } } pub fn arguments(self, arguments: SQLArguments) -> Self { Self { arguments, ..self } } pub fn warn_unquoted_identifiers(self, warn_unquoted_identifiers: bool) -> Self { Self { warn_unquoted_identifiers, ..self } } pub fn warn_none_capital_keywords(self, warn_none_capital_keywords: bool) -> Self { Self { warn_none_capital_keywords, ..self } } pub fn list_hack(self, list_hack: bool) -> Self { Self { list_hack, ..self } } } #[macro_export] macro_rules! issue_ice { ( $spanned:expr ) => {{ Issue::err( alloc::format!("Internal compiler error in {}:{}", file!(), line!()), $spanned, ) }}; } #[macro_export] macro_rules! issue_todo { ( $spanned:expr ) => {{ Issue::err( alloc::format!("Not yet implemented {}:{}", file!(), line!()), $spanned, ) }}; } pub fn parse_statements<'a>( src: &'a str, issues: &mut Vec<Issue>, options: &ParseOptions, ) -> Vec<Statement<'a>> { let mut parser = Parser::new(src, issues, options); statement::parse_statements(&mut parser) } pub fn parse_statement<'a>( src: &'a str, issues: &mut Vec<Issue>, options: &ParseOptions, ) -> Option<Statement<'a>> { let mut parser = Parser::new(src, issues, options); match statement::parse_statement(&mut parser) { Ok(Some(v)) => {
if parser.token != Token::Eof { parser.expected_error("Unexpected token after statement") } Some(v) } Ok(None) => { parser.expected_error("Statement"); None } Err(_) => None, } }
function_block-function_prefix_line
[ { "content": "fn parse_width(parser: &mut Parser<'_, '_>) -> Result<Option<(usize, Span)>, ParseError> {\n\n if !matches!(parser.token, Token::LParen) {\n\n return Ok(None);\n\n }\n\n parser.consume_token(Token::LParen)?;\n\n let value = parser.recovered(\")\", &|t| t == &Token::RParen, |parser| parser.consume_int())?;\n\n parser.consume_token(Token::RParen)?;\n\n Ok(Some(value))\n\n}\n\n\n", "file_path": "src/data_type.rs", "rank": 0, "score": 208341.21819404088 }, { "content": "fn parse_commit<'a, 'b>(parser: &mut Parser<'a, 'b>) -> Result<Span, ParseError> {\n\n parser.consume_keyword(Keyword::COMMIT)\n\n}\n\n\n", "file_path": "src/statement.rs", "rank": 1, "score": 191217.49748470992 }, { "content": "fn parse_end<'a, 'b>(parser: &mut Parser<'a, 'b>) -> Result<Span, ParseError> {\n\n parser.consume_keyword(Keyword::END)\n\n}\n\n\n", "file_path": "src/statement.rs", "rank": 2, "score": 191217.49748470995 }, { "content": "fn parse_begin<'a, 'b>(parser: &mut Parser<'a, 'b>) -> Result<Span, ParseError> {\n\n parser.consume_keyword(Keyword::BEGIN)\n\n}\n\n\n", "file_path": "src/statement.rs", "rank": 3, "score": 191217.49748470995 }, { "content": "fn parse_width_req(parser: &mut Parser<'_, '_>) -> Result<(usize, Span), ParseError> {\n\n if !matches!(parser.token, Token::LParen) {\n\n return parser.expected_failure(\"'('\");\n\n }\n\n Ok(parse_width(parser)?.expect(\"width\"))\n\n}\n\n\n", "file_path": "src/data_type.rs", "rank": 4, "score": 178308.23372226843 }, { "content": "fn parse_start<'a, 'b>(parser: &mut Parser<'a, 'b>) -> Result<Statement<'a>, ParseError> {\n\n Ok(Statement::StartTransaction(parser.consume_keywords(&[\n\n Keyword::START,\n\n Keyword::TRANSACTION,\n\n ])?))\n\n}\n\n\n", "file_path": "src/statement.rs", "rank": 5, "score": 178066.87038241804 }, { "content": "fn parse_block<'a, 'b>(parser: &mut Parser<'a, 'b>) -> Result<Vec<Statement<'a>>, ParseError> {\n\n parser.consume_keyword(Keyword::BEGIN)?;\n\n let mut ans = Vec::new();\n\n parser.recovered(\n\n \"'END'\",\n\n &|e| matches!(e, Token::Ident(_, Keyword::END)),\n\n |parser| parse_statement_list(parser, &mut ans),\n\n )?;\n\n parser.consume_keyword(Keyword::END)?;\n\n Ok(ans)\n\n}\n\n\n\n/// Condition in if statement\n\n#[derive(Clone, Debug)]\n\npub struct IfCondition<'a> {\n\n /// Span of \"ELSEIF\" if specified\n\n pub elseif_span: Option<Span>,\n\n /// Expression that must be true for `then` to be executed\n\n pub search_condition: Expression<'a>,\n\n /// Span of \"THEN\"\n", "file_path": "src/statement.rs", "rank": 6, "score": 171801.25267395657 }, { "content": "fn parse_cols<'a, 'b>(parser: &mut Parser<'a, 'b>) -> Result<Vec<Identifier<'a>>, ParseError> {\n\n parser.consume_token(Token::LParen)?;\n\n let mut ans = Vec::new();\n\n parser.recovered(\"')'\", &|t| t == &Token::RParen, |parser| {\n\n loop {\n\n ans.push(parser.consume_plain_identifier()?);\n\n if parser.skip_token(Token::Comma).is_none() {\n\n break;\n\n }\n\n }\n\n Ok(())\n\n })?;\n\n parser.consume_token(Token::RParen)?;\n\n Ok(ans)\n\n}\n\n\n", "file_path": "src/alter.rs", "rank": 7, "score": 171594.3037493506 }, { "content": "fn parse_if<'a, 'b>(parser: &mut Parser<'a, 'b>) -> Result<If<'a>, ParseError> {\n\n let if_span = parser.consume_keyword(Keyword::IF)?;\n\n let mut conditions = Vec::new();\n\n let mut else_ = None;\n\n parser.recovered(\n\n \"'END'\",\n\n &|e| matches!(e, Token::Ident(_, Keyword::END)),\n\n |parser| {\n\n let search_condition = parse_expression(parser, false)?;\n\n let then_span = parser.consume_keyword(Keyword::THEN)?;\n\n let mut then = Vec::new();\n\n parse_statement_list(parser, &mut then)?;\n\n conditions.push(IfCondition {\n\n elseif_span: None,\n\n search_condition,\n\n then_span,\n\n then,\n\n });\n\n while let Some(elseif_span) = parser.skip_keyword(Keyword::ELSEIF) {\n\n let search_condition = parse_expression(parser, false)?;\n", "file_path": "src/statement.rs", "rank": 8, "score": 166298.26797800948 }, { "content": "fn parse_set<'a, 'b>(parser: &mut Parser<'a, 'b>) -> Result<Set<'a>, ParseError> {\n\n let set_span = parser.consume_keyword(Keyword::SET)?;\n\n let mut values = Vec::new();\n\n loop {\n\n let name = parser.consume_plain_identifier()?;\n\n parser.consume_token(Token::Eq)?;\n\n let val = parse_expression(parser, false)?;\n\n values.push((name, val));\n\n if parser.skip_token(Token::Comma).is_none() {\n\n break;\n\n }\n\n }\n\n Ok(Set { set_span, values })\n\n}\n\n\n", "file_path": "src/statement.rs", "rank": 9, "score": 156137.74219213956 }, { "content": "fn parse_index_cols<'a, 'b>(parser: &mut Parser<'a, 'b>) -> Result<Vec<IndexCol<'a>>, ParseError> {\n\n parser.consume_token(Token::LParen)?;\n\n let mut ans = Vec::new();\n\n parser.recovered(\"')'\", &|t| t == &Token::RParen, |parser| {\n\n loop {\n\n let name = parser.consume_plain_identifier()?;\n\n let size = if parser.skip_token(Token::LParen).is_some() {\n\n let size = parser.recovered(\"')'\", &|t| t == &Token::RParen, |parser| {\n\n parser.consume_int()\n\n })?;\n\n parser.consume_token(Token::RParen)?;\n\n Some(size)\n\n } else {\n\n None\n\n };\n\n\n\n // TODO [ASC | DESC]\n\n\n\n ans.push(IndexCol { name, size });\n\n if parser.skip_token(Token::Comma).is_none() {\n\n break;\n\n }\n\n }\n\n Ok(())\n\n })?;\n\n parser.consume_token(Token::RParen)?;\n\n Ok(ans)\n\n}\n\n\n", "file_path": "src/alter.rs", "rank": 10, "score": 153783.17283097625 }, { "content": "fn parse_create_function<'a, 'b>(\n\n parser: &mut Parser<'a, 'b>,\n\n create_span: Span,\n\n create_options: Vec<CreateOption<'a>>,\n\n) -> Result<Statement<'a>, ParseError> {\n\n let function_span = parser.consume_keyword(Keyword::FUNCTION)?;\n\n\n\n let if_not_exists = if let Some(if_) = parser.skip_keyword(Keyword::IF) {\n\n Some(\n\n parser\n\n .consume_keywords(&[Keyword::NOT, Keyword::EXISTS])?\n\n .join_span(&if_),\n\n )\n\n } else {\n\n None\n\n };\n\n\n\n let name = parser.consume_plain_identifier()?;\n\n let mut params = Vec::new();\n\n parser.consume_token(Token::LParen)?;\n", "file_path": "src/create.rs", "rank": 13, "score": 112590.36418452059 }, { "content": "fn parse_function<'a, 'b>(\n\n parser: &mut Parser<'a, 'b>,\n\n t: Token<'a>,\n\n span: Span,\n\n) -> Result<Expression<'a>, ParseError> {\n\n parser.consume_token(Token::LParen)?;\n\n let func = match &t {\n\n // https://mariadb.com/kb/en/string-functions/\n\n Token::Ident(_, Keyword::ASCII) => Function::Ascii,\n\n Token::Ident(_, Keyword::BIN) => Function::Bin,\n\n Token::Ident(_, Keyword::BIT_LENGTH) => Function::BitLength,\n\n Token::Ident(_, Keyword::CHAR_LENGTH) => Function::CharacterLength,\n\n Token::Ident(_, Keyword::CHARACTER_LENGTH) => Function::CharacterLength,\n\n Token::Ident(_, Keyword::CHR) => Function::Chr,\n\n Token::Ident(_, Keyword::CONCAT) => Function::Concat,\n\n Token::Ident(_, Keyword::CONCAT_WS) => Function::ConcatWs,\n\n Token::Ident(_, Keyword::ELT) => Function::Elt,\n\n Token::Ident(_, Keyword::EXPORT_SET) => Function::ExportSet,\n\n Token::Ident(_, Keyword::EXTRACTVALUE) => Function::ExtractValue,\n\n Token::Ident(_, Keyword::FIELD) => Function::Field,\n", "file_path": "src/expression.rs", "rank": 14, "score": 107682.51526389488 }, { "content": "fn parse_index_options<'a, 'b>(\n\n parser: &mut Parser<'a, 'b>,\n\n out: &mut Vec<IndexOption<'a>>,\n\n) -> Result<(), ParseError> {\n\n loop {\n\n match &parser.token {\n\n Token::Ident(_, Keyword::USING) => parse_index_type(parser, out)?,\n\n Token::Ident(_, Keyword::COMMENT) => {\n\n parser.consume_keyword(Keyword::COMMENT)?;\n\n out.push(IndexOption::Comment(parser.consume_string()?))\n\n }\n\n _ => break,\n\n }\n\n }\n\n Ok(())\n\n}\n\n\n", "file_path": "src/alter.rs", "rank": 15, "score": 102823.89373907175 }, { "content": "fn parse_index_type<'a, 'b>(\n\n parser: &mut Parser<'a, 'b>,\n\n out: &mut Vec<IndexOption<'a>>,\n\n) -> Result<(), ParseError> {\n\n parser.consume_keyword(Keyword::USING)?;\n\n out.push(match &parser.token {\n\n Token::Ident(_, Keyword::BTREE) => {\n\n IndexOption::IndexTypeBTree(parser.consume_keyword(Keyword::BTREE)?)\n\n }\n\n Token::Ident(_, Keyword::HASH) => {\n\n IndexOption::IndexTypeHash(parser.consume_keyword(Keyword::HASH)?)\n\n }\n\n Token::Ident(_, Keyword::RTREE) => {\n\n IndexOption::IndexTypeRTree(parser.consume_keyword(Keyword::RTREE)?)\n\n }\n\n _ => parser.expected_failure(\"'BTREE', 'RTREE' or 'HASH'\")?,\n\n });\n\n Ok(())\n\n}\n\n\n", "file_path": "src/alter.rs", "rank": 16, "score": 102590.51782065982 }, { "content": "/// Compute byte span of an ast fragment\n\npub trait Spanned {\n\n /// Compute byte span of an ast fragment\n\n fn span(&self) -> Span;\n\n\n\n /// Compute the minimal span containing both self and other\n\n fn join_span(&self, other: &impl OptSpanned) -> Span {\n\n let l = self.span();\n\n if let Some(r) = other.opt_span() {\n\n usize::min(l.start, r.start)..usize::max(l.end, r.end)\n\n } else {\n\n l\n\n }\n\n }\n\n}\n\n\n\nimpl<T: Spanned> OptSpanned for T {\n\n fn opt_span(&self) -> Option<Span> {\n\n Some(self.span())\n\n }\n\n}\n", "file_path": "src/span.rs", "rank": 17, "score": 97182.6750266588 }, { "content": "fn parse_enum_set_values<'a, 'b>(\n\n parser: &mut Parser<'a, 'b>,\n\n) -> Result<Vec<SString<'a>>, ParseError> {\n\n parser.consume_token(Token::LParen)?;\n\n let mut ans = Vec::new();\n\n parser.recovered(\")\", &|t| t == &Token::RParen, |parser| {\n\n loop {\n\n ans.push(parser.consume_string()?);\n\n match &parser.token {\n\n Token::Comma => {\n\n parser.consume_token(Token::Comma)?;\n\n }\n\n Token::RParen => break,\n\n _ => parser.expected_failure(\"',' or ')'\")?,\n\n }\n\n }\n\n Ok(())\n\n })?;\n\n parser.consume_token(Token::RParen)?;\n\n Ok(ans)\n", "file_path": "src/data_type.rs", "rank": 18, "score": 93938.47873770152 }, { "content": "pub trait OptSpanned {\n\n /// Compute an optional byte span of an ast fragment\n\n fn opt_span(&self) -> Option<Span>;\n\n\n\n /// Compute the minimal span containing both self and other\n\n /// if either is missing return the other\n\n fn opt_join_span(&self, other: &impl OptSpanned) -> Option<Span> {\n\n if let Some(l) = self.opt_span() {\n\n Some(l.join_span(other))\n\n } else {\n\n other.opt_span()\n\n }\n\n }\n\n}\n\n\n", "file_path": "src/span.rs", "rank": 19, "score": 93720.17868059299 }, { "content": "struct Reducer<'a> {\n\n stack: Vec<ReduceMember<'a>>,\n\n}\n\n\n\nimpl<'a> Reducer<'a> {\n\n fn reduce(&mut self, priority: usize) -> Result<(), &'static str> {\n\n let mut e = match self.stack.pop() {\n\n Some(ReduceMember::Expression(e)) => e,\n\n _ => {\n\n return Err(\"Expected expression before here\");\n\n }\n\n };\n\n loop {\n\n let v = self.stack.pop();\n\n match v {\n\n None => break,\n\n Some(ReduceMember::Expression(_)) => return Err(\"ICE Reduce stack error 1\"),\n\n Some(ReduceMember::Unary(op, span)) if op.priority() > priority => {\n\n self.stack.push(ReduceMember::Unary(op, span));\n\n break;\n", "file_path": "src/expression.rs", "rank": 20, "score": 91142.05279874815 }, { "content": "#[derive(Debug)]\n\nenum ReduceMember<'a> {\n\n Expression(Expression<'a>),\n\n Binary(BinaryOperator, Span),\n\n Unary(UnaryOperator, Span),\n\n}\n\n\n", "file_path": "src/expression.rs", "rank": 21, "score": 87104.19846126612 }, { "content": "fn parse_alter_table<'a, 'b>(\n\n parser: &mut Parser<'a, 'b>,\n\n alter_span: Span,\n\n online: Option<Span>,\n\n ignore: Option<Span>,\n\n) -> Result<AlterTable<'a>, ParseError> {\n\n let table_span = parser.consume_keyword(Keyword::TABLE)?;\n\n let if_exists = if let Some(span) = parser.skip_keyword(Keyword::IF) {\n\n Some(parser.consume_keyword(Keyword::EXISTS)?.join_span(&span))\n\n } else {\n\n None\n\n };\n\n let table = parser.consume_plain_identifier()?;\n\n let d = parser.delimiter.clone();\n\n let mut alter_specifications = Vec::new();\n\n parser.recovered(d.name(), &|t| t == &d, |parser| {\n\n loop {\n\n alter_specifications.push(match parser.token {\n\n Token::Ident(_, Keyword::ADD) => parse_add_alter_specification(parser)?,\n\n Token::Ident(_, Keyword::MODIFY) => {\n", "file_path": "src/alter.rs", "rank": 22, "score": 83871.29853700192 }, { "content": "fn parse_statement_list<'a, 'b>(\n\n parser: &mut Parser<'a, 'b>,\n\n out: &mut Vec<Statement<'a>>,\n\n) -> Result<(), ParseError> {\n\n let old_delimiter = core::mem::replace(&mut parser.delimiter, Token::SemiColon);\n\n let r = parse_statement_list_inner(parser, out);\n\n parser.delimiter = old_delimiter;\n\n r\n\n}\n\n\n", "file_path": "src/statement.rs", "rank": 23, "score": 83760.73571582646 }, { "content": "fn parse_create_table<'a, 'b>(\n\n parser: &mut Parser<'a, 'b>,\n\n create_span: Span,\n\n create_options: Vec<CreateOption<'a>>,\n\n) -> Result<Statement<'a>, ParseError> {\n\n let table_span = parser.consume_keyword(Keyword::TABLE)?;\n\n\n\n let mut identifier = Identifier::new(\"\", 0..0);\n\n let mut if_not_exists = None;\n\n\n\n parser.recovered(\"'('\", &|t| t == &Token::LParen, |parser| {\n\n if let Some(if_) = parser.skip_keyword(Keyword::IF) {\n\n if_not_exists = Some(\n\n if_.start\n\n ..parser\n\n .consume_keywords(&[Keyword::NOT, Keyword::EXISTS])?\n\n .end,\n\n );\n\n }\n\n identifier = parser.consume_plain_identifier()?;\n", "file_path": "src/create.rs", "rank": 24, "score": 83467.4806705895 }, { "content": "fn parse_create_trigger<'a, 'b>(\n\n parser: &mut Parser<'a, 'b>,\n\n create_span: Span,\n\n create_options: Vec<CreateOption<'a>>,\n\n) -> Result<Statement<'a>, ParseError> {\n\n let trigger_span = parser.consume_keyword(Keyword::TRIGGER)?;\n\n\n\n let if_not_exists = if let Some(if_) = parser.skip_keyword(Keyword::IF) {\n\n Some(\n\n parser\n\n .consume_keywords(&[Keyword::NOT, Keyword::EXISTS])?\n\n .join_span(&if_),\n\n )\n\n } else {\n\n None\n\n };\n\n\n\n let name = parser.consume_plain_identifier()?;\n\n\n\n let trigger_time = match &parser.token {\n", "file_path": "src/create.rs", "rank": 25, "score": 83467.4806705895 }, { "content": "fn parse_create_index<'a, 'b>(\n\n parser: &mut Parser<'a, 'b>,\n\n create_span: Span,\n\n create_options: Vec<CreateOption<'a>>,\n\n) -> Result<Statement<'a>, ParseError> {\n\n let index_span = parser.consume_keyword(Keyword::INDEX)?;\n\n let index_name = parser.consume_plain_identifier()?;\n\n let on_span = parser.consume_keyword(Keyword::ON)?;\n\n let table_name = parser.consume_plain_identifier()?;\n\n let mut index_options = Vec::new();\n\n if let Some(using_span) = parser.skip_keyword(Keyword::USING) {\n\n let gist_span = parser.consume_keyword(Keyword::GIST)?;\n\n index_options.push(CreateIndexOption::UsingGist(\n\n gist_span.join_span(&using_span),\n\n ));\n\n }\n\n let l_paren_span = parser.consume_token(Token::LParen)?;\n\n let column_name = parser.consume_plain_identifier()?;\n\n let r_paren_span = parser.consume_token(Token::RParen)?;\n\n Ok(Statement::CreateIndex(CreateIndex {\n", "file_path": "src/create.rs", "rank": 26, "score": 83467.4806705895 }, { "content": "fn parse_create_view<'a, 'b>(\n\n parser: &mut Parser<'a, 'b>,\n\n create_span: Span,\n\n create_options: Vec<CreateOption<'a>>,\n\n) -> Result<Statement<'a>, ParseError> {\n\n let view_span = parser.consume_keyword(Keyword::VIEW)?;\n\n\n\n let if_not_exists = if let Some(if_) = parser.skip_keyword(Keyword::IF) {\n\n Some(\n\n parser\n\n .consume_keywords(&[Keyword::NOT, Keyword::EXISTS])?\n\n .join_span(&if_),\n\n )\n\n } else {\n\n None\n\n };\n\n\n\n let name = parser.consume_plain_identifier()?;\n\n // TODO (column_list)\n\n\n", "file_path": "src/create.rs", "rank": 27, "score": 83467.4806705895 }, { "content": "fn parse_add_alter_specification<'a, 'b>(\n\n parser: &mut Parser<'a, 'b>,\n\n) -> Result<AlterSpecification<'a>, ParseError> {\n\n let add_span = parser.consume_keyword(Keyword::ADD)?;\n\n let constraint = if let Some(span) = parser.skip_keyword(Keyword::CONSTRAINT) {\n\n let v = match &parser.token {\n\n Token::Ident(_, kw) if !kw.reserved() => Some(parser.consume_plain_identifier()?),\n\n _ => None,\n\n };\n\n Some((span, v))\n\n } else {\n\n None\n\n };\n\n match &parser.token {\n\n Token::Ident(_, Keyword::FOREIGN) => {\n\n let foregin_key_span = parser.consume_keywords(&[Keyword::FOREIGN, Keyword::KEY])?;\n\n let if_not_exists = if let Some(s) = parser.skip_keyword(Keyword::IF) {\n\n Some(\n\n parser\n\n .consume_keywords(&[Keyword::NOT, Keyword::EXISTS])?\n", "file_path": "src/alter.rs", "rank": 28, "score": 80743.3062609692 }, { "content": "fn parse_statement_list_inner<'a, 'b>(\n\n parser: &mut Parser<'a, 'b>,\n\n out: &mut Vec<Statement<'a>>,\n\n) -> Result<(), ParseError> {\n\n loop {\n\n while parser.skip_token(Token::SemiColon).is_some() {}\n\n let mut stdin = false;\n\n match parse_statement(parser)? {\n\n Some(v) => {\n\n stdin = v.reads_from_stdin();\n\n out.push(v);\n\n }\n\n None => break,\n\n }\n\n if !matches!(parser.token, Token::SemiColon) {\n\n break;\n\n }\n\n if stdin {\n\n let (s, span) = parser.read_from_stdin_and_next();\n\n out.push(Statement::Stdin(s, span));\n\n } else {\n\n parser.consume_token(Token::SemiColon)?;\n\n }\n\n }\n\n Ok(())\n\n}\n\n\n", "file_path": "src/statement.rs", "rank": 29, "score": 80636.65092553181 }, { "content": " level: Level::Error,\n\n message: message.into(),\n\n span: span.span(),\n\n fragments: Vec::new(),\n\n }\n\n }\n\n\n\n /// Construct a warning with given message and span\n\n pub fn warn(message: impl Into<String>, span: &impl Spanned) -> Self {\n\n Issue {\n\n level: Level::Warning,\n\n message: message.into(),\n\n span: span.span(),\n\n fragments: Vec::new(),\n\n }\n\n }\n\n\n\n /// Add a fragment with the given message and span\n\n pub fn frag(mut self, message: impl Into<String>, span: &impl Spanned) -> Self {\n\n self.fragments.push((message.into(), span.span()));\n\n self\n\n }\n\n}\n", "file_path": "src/issue.rs", "rank": 30, "score": 41054.796836646005 }, { "content": " Error,\n\n}\n\n\n\n/// An issue encountered during parsing, or later stages\n\n#[derive(Clone, PartialEq, Eq, Debug)]\n\npub struct Issue {\n\n /// The level of the issue\n\n pub level: Level,\n\n /// The primary message of the issue\n\n pub message: String,\n\n /// The span to attach the primary message to\n\n pub span: Span,\n\n /// List of secondary messages and spans\n\n pub fragments: Vec<(String, Span)>,\n\n}\n\n\n\nimpl Issue {\n\n /// Construct an error with given message and span\n\n pub fn err(message: impl Into<String>, span: &impl Spanned) -> Self {\n\n Issue {\n", "file_path": "src/issue.rs", "rank": 31, "score": 41054.000317656544 }, { "content": " pub value: Cow<'a, str>,\n\n /// The span the string originated from\n\n pub span: Span,\n\n}\n\n\n\nimpl<'a> SString<'a> {\n\n /// Construct new SString with given value an span\n\n pub fn new(value: Cow<'a, str>, span: Span) -> Self {\n\n Self { value, span }\n\n }\n\n\n\n /// Return the str value\n\n pub fn as_str(&self) -> &str {\n\n self.value.as_ref()\n\n }\n\n}\n\n\n\nimpl<'a> core::ops::Deref for SString<'a> {\n\n type Target = str;\n\n\n", "file_path": "src/sstring.rs", "rank": 32, "score": 41048.755769885756 }, { "content": "// Licensed under the Apache License, Version 2.0 (the \"License\");\n\n// you may not use this file except in compliance with the License.\n\n// You may obtain a copy of the License at\n\n//\n\n// http://www.apache.org/licenses/LICENSE-2.0\n\n//\n\n// Unless required by applicable law or agreed to in writing, software\n\n// distributed under the License is distributed on an \"AS IS\" BASIS,\n\n// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n\n// See the License for the specific language governing permissions and\n\n// limitations under the License.\n\n\n\nuse alloc::{string::String, vec::Vec};\n\n\n\nuse crate::{Span, Spanned};\n\n\n\n/// Level of an issues\n\n#[derive(Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Debug)]\n\npub enum Level {\n\n Warning,\n", "file_path": "src/issue.rs", "rank": 33, "score": 41046.53128873284 }, { "content": "// Licensed under the Apache License, Version 2.0 (the \"License\");\n\n// you may not use this file except in compliance with the License.\n\n// You may obtain a copy of the License at\n\n//\n\n// http://www.apache.org/licenses/LICENSE-2.0\n\n//\n\n// Unless required by applicable law or agreed to in writing, software\n\n// distributed under the License is distributed on an \"AS IS\" BASIS,\n\n// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n\n// See the License for the specific language governing permissions and\n\n// limitations under the License.\n\n\n\nuse alloc::borrow::Cow;\n\n\n\nuse crate::{Span, Spanned};\n\n\n\n/// A string with attached span\n\n#[derive(Clone, Debug)]\n\npub struct SString<'a> {\n\n /// The underlying string\n", "file_path": "src/sstring.rs", "rank": 34, "score": 41042.45147566208 }, { "content": " /// Span of the value\n\n pub span: Span,\n\n}\n\n\n\nimpl<'a> Identifier<'a> {\n\n /// Produce new identifier given value and span\n\n pub fn new(value: &'a str, span: Span) -> Self {\n\n Identifier { value, span }\n\n }\n\n\n\n /// Get the string representation of the identifier\n\n pub fn as_str(&self) -> &'a str {\n\n self.value\n\n }\n\n}\n\n\n\nimpl<'a> core::ops::Deref for Identifier<'a> {\n\n type Target = str;\n\n\n\n fn deref(&self) -> &'a Self::Target {\n", "file_path": "src/identifier.rs", "rank": 35, "score": 41040.107927817604 }, { "content": " fn deref(&self) -> &Self::Target {\n\n self.value.deref()\n\n }\n\n}\n\n\n\nimpl<'a> Spanned for SString<'a> {\n\n fn span(&self) -> Span {\n\n self.span.span()\n\n }\n\n}\n", "file_path": "src/sstring.rs", "rank": 36, "score": 41036.65536159018 }, { "content": "// Licensed under the Apache License, Version 2.0 (the \"License\");\n\n// you may not use this file except in compliance with the License.\n\n// You may obtain a copy of the License at\n\n//\n\n// http://www.apache.org/licenses/LICENSE-2.0\n\n//\n\n// Unless required by applicable law or agreed to in writing, software\n\n// distributed under the License is distributed on an \"AS IS\" BASIS,\n\n// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n\n// See the License for the specific language governing permissions and\n\n// limitations under the License.\n\n\n\nuse crate::{Span, Spanned};\n\n\n\n/// Simple identifier in code\n\n/// it derefs to its string value\n\n#[derive(Clone, Debug)]\n\npub struct Identifier<'a> {\n\n /// Identifier string\n\n pub value: &'a str,\n", "file_path": "src/identifier.rs", "rank": 37, "score": 41032.54956284002 }, { "content": " self.value\n\n }\n\n}\n\n\n\nimpl<'a> Spanned for Identifier<'a> {\n\n fn span(&self) -> Span {\n\n self.span.span()\n\n }\n\n}\n", "file_path": "src/identifier.rs", "rank": 38, "score": 41023.793087313185 }, { "content": "\n\n/// Representation of replace Statement\n\n///\n\n/// ```\n\n/// # use sql_parse::{SQLDialect, SQLArguments, ParseOptions, parse_statement, Update, Statement};\n\n/// # let options = ParseOptions::new().dialect(SQLDialect::MariaDB);\n\n/// # let mut issues = Vec::new();\n\n/// #\n\n/// let sql = \"UPDATE tab1, tab2 SET tab1.column1 = value1, tab1.column2 = value2 WHERE tab1.id = tab2.id\";\n\n/// let stmt = parse_statement(sql, &mut issues, &options);\n\n///\n\n/// # assert!(issues.is_empty());\n\n/// #\n\n/// let u: Update = match stmt {\n\n/// Some(Statement::Update(u)) => u,\n\n/// _ => panic!(\"We should get an update statement\")\n\n/// };\n\n///\n\n/// println!(\"{:#?}\", u.where_.unwrap())\n\n/// ```\n", "file_path": "src/update.rs", "rank": 39, "score": 40992.20378761315 }, { "content": "#[derive(Clone, Debug)]\n\npub struct Update<'a> {\n\n /// Span of \"UPDATE\"\n\n pub update_span: Span,\n\n /// Flags specified after \"UPDATE\"\n\n pub flags: Vec<UpdateFlag>,\n\n /// List of tables to update\n\n pub tables: Vec<TableReference<'a>>,\n\n /// Span of \"SET\"\n\n pub set_span: Span,\n\n /// List of key,value pairs to set\n\n pub set: Vec<(Vec<Identifier<'a>>, Expression<'a>)>,\n\n /// Where expression and span of \"WHERE\" if specified\n\n pub where_: Option<(Expression<'a>, Span)>,\n\n}\n\n\n\nimpl<'a> Spanned for Update<'a> {\n\n fn span(&self) -> Span {\n\n let mut set_span = None;\n\n for (a, b) in &self.set {\n", "file_path": "src/update.rs", "rank": 40, "score": 40989.97536961816 }, { "content": " set_span = set_span.opt_join_span(a).opt_join_span(b)\n\n }\n\n\n\n self.update_span\n\n .join_span(&self.flags)\n\n .join_span(&self.tables)\n\n .join_span(&self.set_span)\n\n .join_span(&set_span)\n\n .join_span(&self.where_)\n\n }\n\n}\n\n\n\npub(crate) fn parse_update<'a, 'b>(parser: &mut Parser<'a, 'b>) -> Result<Update<'a>, ParseError> {\n\n let update_span = parser.consume_keyword(Keyword::UPDATE)?;\n\n let mut flags = Vec::new();\n\n\n\n loop {\n\n match &parser.token {\n\n Token::Ident(_, Keyword::LOW_PRIORITY) => flags.push(UpdateFlag::LowPriority(\n\n parser.consume_keyword(Keyword::LOW_PRIORITY)?,\n", "file_path": "src/update.rs", "rank": 41, "score": 40989.45055701117 }, { "content": " )),\n\n Token::Ident(_, Keyword::IGNORE) => {\n\n flags.push(UpdateFlag::Ignore(parser.consume_keyword(Keyword::IGNORE)?))\n\n }\n\n _ => break,\n\n }\n\n }\n\n\n\n let mut tables = Vec::new();\n\n loop {\n\n tables.push(parse_table_reference(parser)?);\n\n if parser.skip_token(Token::Comma).is_none() {\n\n break;\n\n }\n\n }\n\n\n\n let set_span = parser.consume_keyword(Keyword::SET)?;\n\n let mut set = Vec::new();\n\n loop {\n\n let mut col = vec![parser.consume_plain_identifier()?];\n", "file_path": "src/update.rs", "rank": 42, "score": 40984.343991546324 }, { "content": " select::{parse_table_reference, TableReference},\n\n span::OptSpanned,\n\n Identifier, Span, Spanned,\n\n};\n\n\n\n/// Flags specified after \"UPDATE\"\n\n#[derive(Clone, Debug)]\n\npub enum UpdateFlag {\n\n LowPriority(Span),\n\n Ignore(Span),\n\n}\n\n\n\nimpl Spanned for UpdateFlag {\n\n fn span(&self) -> Span {\n\n match &self {\n\n UpdateFlag::LowPriority(v) => v.span(),\n\n UpdateFlag::Ignore(v) => v.span(),\n\n }\n\n }\n\n}\n", "file_path": "src/update.rs", "rank": 43, "score": 40983.99431236928 }, { "content": " while parser.skip_token(Token::Period).is_some() {\n\n col.push(parser.consume_plain_identifier()?);\n\n }\n\n parser.consume_token(Token::Eq)?;\n\n let val = parse_expression(parser, false)?;\n\n set.push((col, val));\n\n if parser.skip_token(Token::Comma).is_none() {\n\n break;\n\n }\n\n }\n\n\n\n let where_ = if let Some(span) = parser.skip_keyword(Keyword::WHERE) {\n\n Some((parse_expression(parser, false)?, span))\n\n } else {\n\n None\n\n };\n\n\n\n Ok(Update {\n\n flags,\n\n update_span,\n", "file_path": "src/update.rs", "rank": 44, "score": 40983.5555238569 }, { "content": "// Licensed under the Apache License, Version 2.0 (the \"License\");\n\n// you may not use this file except in compliance with the License.\n\n// You may obtain a copy of the License at\n\n//\n\n// http://www.apache.org/licenses/LICENSE-2.0\n\n//\n\n// Unless required by applicable law or agreed to in writing, software\n\n// distributed under the License is distributed on an \"AS IS\" BASIS,\n\n// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n\n// See the License for the specific language governing permissions and\n\n// limitations under the License.\n\n\n\nuse alloc::vec;\n\nuse alloc::vec::Vec;\n\n\n\nuse crate::{\n\n expression::{parse_expression, Expression},\n\n keywords::Keyword,\n\n lexer::Token,\n\n parser::{ParseError, Parser},\n", "file_path": "src/update.rs", "rank": 45, "score": 40982.62925083446 }, { "content": " /// Where expression and Span of \"WHERE\" if specified\n\n pub where_: Option<(Expression<'a>, Span)>,\n\n}\n\n\n\nimpl<'a> Spanned for Delete<'a> {\n\n fn span(&self) -> Span {\n\n self.delete_span\n\n .join_span(&self.flags)\n\n .join_span(&self.from_span)\n\n .join_span(&self.tables)\n\n .join_span(&self.using)\n\n .join_span(&self.where_)\n\n }\n\n}\n\n\n\npub(crate) fn parse_delete<'a, 'b>(parser: &mut Parser<'a, 'b>) -> Result<Delete<'a>, ParseError> {\n\n let delete_span = parser.consume_keyword(Keyword::DELETE)?;\n\n let mut flags = Vec::new();\n\n\n\n loop {\n", "file_path": "src/delete.rs", "rank": 46, "score": 40974.12988742594 }, { "content": "}\n\n\n\n/// Represent a delete statement\n\n/// ```\n\n/// # use sql_parse::{SQLDialect, SQLArguments, ParseOptions, parse_statements, Delete, Statement};\n\n/// # let options = ParseOptions::new().dialect(SQLDialect::MariaDB);\n\n/// # let mut issues = Vec::new();\n\n/// #\n\n/// let sql = \"DELETE FROM t1 WHERE c1 IN (SELECT b.c1 FROM t1 b WHERE b.c2=0);\";\n\n///\n\n/// let mut stmts = parse_statements(sql, &mut issues, &options);\n\n///\n\n/// # assert!(issues.is_empty());\n\n/// #\n\n/// let delete: Delete = match stmts.pop() {\n\n/// Some(Statement::Delete(d)) => d,\n\n/// _ => panic!(\"We should get a delete statement\")\n\n/// };\n\n///\n\n/// assert!(delete.tables[0][0].as_str() == \"t1\");\n", "file_path": "src/delete.rs", "rank": 47, "score": 40971.63063680334 }, { "content": " tables,\n\n set_span,\n\n set,\n\n where_,\n\n })\n\n}\n\n\n\n// UPDATE [LOW_PRIORITY] [IGNORE] table_references\n\n// SET col1={expr1|DEFAULT} [, col2={expr2|DEFAULT}] ...\n\n// [WHERE where_condition]\n", "file_path": "src/update.rs", "rank": 48, "score": 40969.81345136107 }, { "content": "/// println!(\"{:#?}\", delete.where_);\n\n///\n\n/// let sql = \"DELETE `t1` FROM `t1` LEFT JOIN `t2` ON `t1`.`t2_id`=`t2`.`id` WHERE `t2`.`key`='my_key';\";\n\n///\n\n/// let mut stmts = parse_statements(sql, &mut issues, &options);\n\n///\n\n/// # assert!(issues.is_empty());\n\n/// ```\n\n#[derive(Clone, Debug)]\n\npub struct Delete<'a> {\n\n /// Span of \"DELETE\"\n\n pub delete_span: Span,\n\n /// Flags following \"DELETE\"\n\n pub flags: Vec<DeleteFlag>,\n\n /// Span of \"FROM\"\n\n pub from_span: Span,\n\n /// Tables to do deletes on\n\n pub tables: Vec<Vec<Identifier<'a>>>,\n\n /// Table to use in where clause in multi table delete\n\n pub using: Vec<TableReference<'a>>,\n", "file_path": "src/delete.rs", "rank": 49, "score": 40963.58628414499 }, { "content": " parser.issues.push(Issue::err(\n\n \"Using not allowed in delete with table names before FROM\",\n\n &using_span,\n\n ));\n\n }\n\n loop {\n\n using.push(parse_table_reference(parser)?);\n\n if parser.skip_token(Token::Comma).is_none() {\n\n break;\n\n }\n\n }\n\n }\n\n\n\n let where_ = if let Some(span) = parser.skip_keyword(Keyword::WHERE) {\n\n Some((parse_expression(parser, false)?, span))\n\n } else {\n\n None\n\n };\n\n //TODO [ORDER BY ...]\n\n //TODO LIMIT row_count]\n", "file_path": "src/delete.rs", "rank": 50, "score": 40961.05354875768 }, { "content": " match &parser.token {\n\n Token::Ident(_, Keyword::LOW_PRIORITY) => flags.push(DeleteFlag::LowPriority(\n\n parser.consume_keyword(Keyword::LOW_PRIORITY)?,\n\n )),\n\n Token::Ident(_, Keyword::QUICK) => {\n\n flags.push(DeleteFlag::Quick(parser.consume_keyword(Keyword::QUICK)?))\n\n }\n\n Token::Ident(_, Keyword::IGNORE) => {\n\n flags.push(DeleteFlag::Ignore(parser.consume_keyword(Keyword::IGNORE)?))\n\n }\n\n _ => break,\n\n }\n\n }\n\n\n\n let mut tables = Vec::new();\n\n let mut using = Vec::new();\n\n let from_span = if let Some(from_span) = parser.skip_keyword(Keyword::FROM) {\n\n loop {\n\n let mut table = vec![parser.consume_plain_identifier()?];\n\n loop {\n", "file_path": "src/delete.rs", "rank": 51, "score": 40960.76991408214 }, { "content": " select::parse_table_reference,\n\n Identifier, Issue, Span, Spanned, TableReference,\n\n};\n\n\n\n/// Flags for deletion\n\n#[derive(Clone, Debug)]\n\npub enum DeleteFlag {\n\n LowPriority(Span),\n\n Quick(Span),\n\n Ignore(Span),\n\n}\n\n\n\nimpl Spanned for DeleteFlag {\n\n fn span(&self) -> Span {\n\n match &self {\n\n DeleteFlag::LowPriority(v) => v.span(),\n\n DeleteFlag::Quick(v) => v.span(),\n\n DeleteFlag::Ignore(v) => v.span(),\n\n }\n\n }\n", "file_path": "src/delete.rs", "rank": 52, "score": 40960.04335133959 }, { "content": "// Licensed under the Apache License, Version 2.0 (the \"License\");\n\n// you may not use this file except in compliance with the License.\n\n// You may obtain a copy of the License at\n\n//\n\n// http://www.apache.org/licenses/LICENSE-2.0\n\n//\n\n// Unless required by applicable law or agreed to in writing, software\n\n// distributed under the License is distributed on an \"AS IS\" BASIS,\n\n// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n\n// See the License for the specific language governing permissions and\n\n// limitations under the License.\n\n\n\nuse alloc::vec;\n\nuse alloc::vec::Vec;\n\n\n\nuse crate::{\n\n expression::{parse_expression, Expression},\n\n keywords::Keyword,\n\n lexer::Token,\n\n parser::{ParseError, Parser},\n", "file_path": "src/delete.rs", "rank": 53, "score": 40956.38321081218 }, { "content": " tables.push(table);\n\n if parser.skip_token(Token::Comma).is_none() {\n\n break;\n\n }\n\n }\n\n let from_span = parser.consume_keyword(Keyword::FROM)?;\n\n loop {\n\n using.push(parse_table_reference(parser)?);\n\n if parser.skip_token(Token::Comma).is_none() {\n\n break;\n\n }\n\n }\n\n from_span\n\n };\n\n\n\n //TODO [PARTITION (partition_list)]\n\n //TODO [FOR PORTION OF period FROM expr1 TO expr2]\n\n\n\n if let Some(using_span) = parser.skip_keyword(Keyword::USING) {\n\n if !using.is_empty() {\n", "file_path": "src/delete.rs", "rank": 54, "score": 40952.708342630554 }, { "content": " if parser.skip_token(Token::Period).is_none() {\n\n break;\n\n }\n\n table.push(parser.consume_plain_identifier()?);\n\n }\n\n tables.push(table);\n\n if parser.skip_token(Token::Comma).is_none() {\n\n break;\n\n }\n\n }\n\n from_span\n\n } else {\n\n loop {\n\n let mut table = vec![parser.consume_plain_identifier()?];\n\n loop {\n\n if parser.skip_token(Token::Period).is_none() {\n\n break;\n\n }\n\n table.push(parser.consume_plain_identifier()?);\n\n }\n", "file_path": "src/delete.rs", "rank": 55, "score": 40950.06312936278 }, { "content": " //TODO [RETURNING select_expr\n\n //TODO [, select_expr ...]]\n\n\n\n Ok(Delete {\n\n flags,\n\n delete_span,\n\n tables,\n\n using,\n\n from_span,\n\n where_,\n\n })\n\n}\n", "file_path": "src/delete.rs", "rank": 56, "score": 40949.14801458655 }, { "content": "\n\nimpl Spanned for Span {\n\n fn span(&self) -> Span {\n\n self.clone()\n\n }\n\n}\n\n\n\nimpl<T: Spanned> Spanned for Box<T> {\n\n fn span(&self) -> Span {\n\n self.as_ref().span()\n\n }\n\n}\n\n\n\nimpl<T: OptSpanned> OptSpanned for Option<T> {\n\n fn opt_span(&self) -> Option<Span> {\n\n match &self {\n\n Some(v) => v.opt_span(),\n\n None => None,\n\n }\n\n }\n", "file_path": "src/span.rs", "rank": 57, "score": 40912.61517111704 }, { "content": " self.1.span()\n\n }\n\n}\n\n\n\nimpl<S: Spanned> Spanned for (bool, S) {\n\n fn span(&self) -> Span {\n\n self.1.span()\n\n }\n\n}\n\n\n\nimpl<'a, S: Spanned> Spanned for (&'a str, S) {\n\n fn span(&self) -> Span {\n\n self.1.span()\n\n }\n\n}\n\n\n\nimpl<'a, S: Spanned> Spanned for (alloc::borrow::Cow<'a, str>, S) {\n\n fn span(&self) -> Span {\n\n self.1.span()\n\n }\n", "file_path": "src/span.rs", "rank": 58, "score": 40912.36062853346 }, { "content": "}\n\n\n\nimpl<T: OptSpanned> OptSpanned for Vec<T> {\n\n fn opt_span(&self) -> Option<Span> {\n\n self.iter().fold(None, |a, b| a.opt_join_span(b))\n\n }\n\n}\n\n\n\nimpl<T: OptSpanned> OptSpanned for [T] {\n\n fn opt_span(&self) -> Option<Span> {\n\n self.iter().fold(None, |a, b| a.opt_join_span(b))\n\n }\n\n}\n\n\n\nimpl<S: Spanned> Spanned for (usize, S) {\n\n fn span(&self) -> Span {\n\n self.1.span()\n\n }\n\n}\n\n\n", "file_path": "src/span.rs", "rank": 59, "score": 40908.995757086486 }, { "content": "// Licensed under the Apache License, Version 2.0 (the \"License\");\n\n// you may not use this file except in compliance with the License.\n\n// You may obtain a copy of the License at\n\n//\n\n// http://www.apache.org/licenses/LICENSE-2.0\n\n//\n\n// Unless required by applicable law or agreed to in writing, software\n\n// distributed under the License is distributed on an \"AS IS\" BASIS,\n\n// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n\n// See the License for the specific language governing permissions and\n\n// limitations under the License.\n\n\n\nuse alloc::{boxed::Box, vec::Vec};\n\n\n\n/// Byte span of ast fragment\n\npub type Span = core::ops::Range<usize>;\n\n\n\n/// Compute an optional byte span of an ast fragment\n\n\n", "file_path": "src/span.rs", "rank": 60, "score": 40907.771662316045 }, { "content": "impl<S: Spanned> Spanned for (usize, usize, S) {\n\n fn span(&self) -> Span {\n\n self.2.span()\n\n }\n\n}\n\n\n\nimpl<S: Spanned> Spanned for (u32, S) {\n\n fn span(&self) -> Span {\n\n self.1.span()\n\n }\n\n}\n\n\n\nimpl<S: Spanned> Spanned for (u64, S) {\n\n fn span(&self) -> Span {\n\n self.1.span()\n\n }\n\n}\n\n\n\nimpl<S: Spanned> Spanned for (f64, S) {\n\n fn span(&self) -> Span {\n", "file_path": "src/span.rs", "rank": 61, "score": 40902.42343384666 }, { "content": "}\n\n\n\nimpl<S: Spanned, O: OptSpanned> Spanned for (S, O) {\n\n fn span(&self) -> Span {\n\n self.0.join_span(&self.1)\n\n }\n\n}\n\n\n\nimpl<T1: Spanned, T2: OptSpanned, T3: OptSpanned> Spanned for (T1, T2, T3) {\n\n fn span(&self) -> Span {\n\n self.0.join_span(&self.1).join_span(&self.2)\n\n }\n\n}\n", "file_path": "src/span.rs", "rank": 62, "score": 40901.675469704074 }, { "content": "impl<'a> Spanned for DropEvent<'a> {\n\n fn span(&self) -> Span {\n\n self.drop_span\n\n .join_span(&self.event_span)\n\n .join_span(&self.if_exists)\n\n .join_span(&self.event)\n\n }\n\n}\n\n\n\n/// Represent a drop function statement\n\n/// ```\n\n/// # use sql_parse::{SQLDialect, SQLArguments, ParseOptions, parse_statements, DropFunction, Statement};\n\n/// # let options = ParseOptions::new().dialect(SQLDialect::MariaDB);\n\n/// # let mut issues = Vec::new();\n\n/// #\n\n/// let sql = \"DROP FUNCTION myfunc;\";\n\n///\n\n/// let mut stmts = parse_statements(sql, &mut issues, &options);\n\n///\n\n/// # assert!(issues.is_empty());\n", "file_path": "src/drop.rs", "rank": 63, "score": 40760.2268647621 }, { "content": "impl<'a> Spanned for DropFunction<'a> {\n\n fn span(&self) -> Span {\n\n self.drop_span\n\n .join_span(&self.function_span)\n\n .join_span(&self.if_exists)\n\n .join_span(&self.function)\n\n }\n\n}\n\n\n\n/// Represent a drop procedure statement\n\n/// ```\n\n/// # use sql_parse::{SQLDialect, SQLArguments, ParseOptions, parse_statements, DropProcedure, Statement};\n\n/// # let options = ParseOptions::new().dialect(SQLDialect::MariaDB);\n\n/// # let mut issues = Vec::new();\n\n/// #\n\n/// let sql = \"DROP PROCEDURE myproc;\";\n\n///\n\n/// let mut stmts = parse_statements(sql, &mut issues, &options);\n\n///\n\n/// # assert!(issues.is_empty());\n", "file_path": "src/drop.rs", "rank": 64, "score": 40759.214282398774 }, { "content": " .join_span(&self.table_span)\n\n .join_span(&self.if_exists)\n\n .join_span(&self.tables)\n\n }\n\n}\n\n\n\n/// Represent a drop view statement\n\n/// ```\n\n/// # use sql_parse::{SQLDialect, SQLArguments, ParseOptions, parse_statements, DropView, Statement};\n\n/// # let options = ParseOptions::new().dialect(SQLDialect::MariaDB);\n\n/// # let mut issues = Vec::new();\n\n/// #\n\n/// let sql = \"DROP VIEW `Employees`, `Customers`;\";\n\n///\n\n/// let mut stmts = parse_statements(sql, &mut issues, &options);\n\n///\n\n/// # assert!(issues.is_empty());\n\n/// #\n\n/// let delete: DropView = match stmts.pop() {\n\n/// Some(Statement::DropView(d)) => d,\n", "file_path": "src/drop.rs", "rank": 65, "score": 40758.381082757995 }, { "content": "\n\n/// Represent a drop table statement\n\n/// ```\n\n/// # use sql_parse::{SQLDialect, SQLArguments, ParseOptions, parse_statements, DropTable, Statement};\n\n/// # let options = ParseOptions::new().dialect(SQLDialect::MariaDB);\n\n/// # let mut issues = Vec::new();\n\n/// #\n\n/// let sql = \"DROP TABLE `Employees`, `Customers`;\";\n\n///\n\n/// let mut stmts = parse_statements(sql, &mut issues, &options);\n\n///\n\n/// # assert!(issues.is_empty());\n\n/// #\n\n/// let delete: DropTable = match stmts.pop() {\n\n/// Some(Statement::DropTable(d)) => d,\n\n/// _ => panic!(\"We should get a drop table statement\")\n\n/// };\n\n///\n\n/// assert!(delete.tables.get(0).unwrap().as_str() == \"Employees\");\n\n/// ```\n", "file_path": "src/drop.rs", "rank": 66, "score": 40757.99475926427 }, { "content": " } else {\n\n None\n\n };\n\n let mut tables = Vec::new();\n\n loop {\n\n tables.push(parser.consume_plain_identifier()?);\n\n if parser.skip_token(Token::Comma).is_none() {\n\n break;\n\n }\n\n }\n\n let cascade = if parser.options.dialect.is_postgresql() {\n\n parser.skip_keyword(Keyword::CASCADE)\n\n } else {\n\n None\n\n };\n\n Ok(Statement::DropTable(DropTable {\n\n drop_span,\n\n temporary,\n\n table_span,\n\n if_exists,\n", "file_path": "src/drop.rs", "rank": 67, "score": 40757.098817843806 }, { "content": "impl<'a> Spanned for DropDatabase<'a> {\n\n fn span(&self) -> Span {\n\n self.drop_span\n\n .join_span(&self.database_span)\n\n .join_span(&self.if_exists)\n\n .join_span(&self.database)\n\n }\n\n}\n\n\n\n/// Represent a drop event statement\n\n/// ```\n\n/// # use sql_parse::{SQLDialect, SQLArguments, ParseOptions, parse_statements, DropEvent, Statement};\n\n/// # let options = ParseOptions::new().dialect(SQLDialect::MariaDB);\n\n/// # let mut issues = Vec::new();\n\n/// #\n\n/// let sql = \"DROP EVENT myevent;\";\n\n///\n\n/// let mut stmts = parse_statements(sql, &mut issues, &options);\n\n///\n\n/// # assert!(issues.is_empty());\n", "file_path": "src/drop.rs", "rank": 68, "score": 40756.97166356836 }, { "content": "impl<'a> Spanned for DropProcedure<'a> {\n\n fn span(&self) -> Span {\n\n self.drop_span\n\n .join_span(&self.procedure_span)\n\n .join_span(&self.if_exists)\n\n .join_span(&self.procedure)\n\n }\n\n}\n\n\n\n/// Represent a drop server statement\n\n/// ```\n\n/// # use sql_parse::{SQLDialect, SQLArguments, ParseOptions, parse_statements, DropServer, Statement};\n\n/// # let options = ParseOptions::new().dialect(SQLDialect::MariaDB);\n\n/// # let mut issues = Vec::new();\n\n/// #\n\n/// let sql = \"DROP SERVER myserver;\";\n\n///\n\n/// let mut stmts = parse_statements(sql, &mut issues, &options);\n\n///\n\n/// # assert!(issues.is_empty());\n", "file_path": "src/drop.rs", "rank": 69, "score": 40756.97166356836 }, { "content": "impl<'a> Spanned for DropServer<'a> {\n\n fn span(&self) -> Span {\n\n self.drop_span\n\n .join_span(&self.server_span)\n\n .join_span(&self.if_exists)\n\n .join_span(&self.server)\n\n }\n\n}\n\n\n\n/// Represent a drop trigger statement\n\n/// ```\n\n/// # use sql_parse::{SQLDialect, SQLArguments, ParseOptions, parse_statements, DropTrigger, Statement};\n\n/// # let options = ParseOptions::new().dialect(SQLDialect::MariaDB);\n\n/// # let mut issues = Vec::new();\n\n/// #\n\n/// let sql = \"DROP TRIGGER IF EXISTS `foo`.`mytrigger`;\";\n\n///\n\n/// let mut stmts = parse_statements(sql, &mut issues, &options);\n\n///\n\n/// # assert!(issues.is_empty());\n", "file_path": "src/drop.rs", "rank": 70, "score": 40756.62226314387 }, { "content": " fn span(&self) -> Span {\n\n self.drop_span\n\n .join_span(&self.temporary)\n\n .join_span(&self.view_span)\n\n .join_span(&self.if_exists)\n\n .join_span(&self.views)\n\n }\n\n}\n\n\n\n/// Represent a drop database statement\n\n/// ```\n\n/// # use sql_parse::{SQLDialect, SQLArguments, ParseOptions, parse_statements, DropDatabase, Statement};\n\n/// # let options = ParseOptions::new().dialect(SQLDialect::MariaDB);\n\n/// # let mut issues = Vec::new();\n\n/// #\n\n/// let sql = \"DROP DATABASE mydb;\";\n\n///\n\n/// let mut stmts = parse_statements(sql, &mut issues, &options);\n\n///\n\n/// # assert!(issues.is_empty());\n", "file_path": "src/drop.rs", "rank": 71, "score": 40754.68333383526 }, { "content": "/// #\n\n/// let s: DropFunction = match stmts.pop() {\n\n/// Some(Statement::DropFunction(s)) => s,\n\n/// _ => panic!(\"We should get a drop function statement\")\n\n/// };\n\n///\n\n/// assert!(s.function.as_str() == \"myfunc\");\n\n/// ```\n\n#[derive(Debug, Clone)]\n\npub struct DropFunction<'a> {\n\n /// Span of \"DROP\"\n\n pub drop_span: Span,\n\n /// Span of \"FUNCTION\"\n\n pub function_span: Span,\n\n /// Span of \"IF EXISTS\" if specified\n\n pub if_exists: Option<Span>,\n\n /// Function to drop\n\n pub function: Identifier<'a>,\n\n}\n\n\n", "file_path": "src/drop.rs", "rank": 72, "score": 40753.63218965286 }, { "content": "}\n\npub(crate) struct Lexer<'a> {\n\n src: &'a str,\n\n chars: core::iter::Peekable<core::str::CharIndices<'a>>,\n\n}\n\n\n\nimpl<'a> Lexer<'a> {\n\n pub fn new(src: &'a str) -> Self {\n\n Self {\n\n src,\n\n chars: src.char_indices().peekable(),\n\n }\n\n }\n\n\n\n fn s(&self, span: Span) -> &'a str {\n\n core::str::from_utf8(&self.src.as_bytes()[span]).unwrap()\n\n }\n\n\n\n fn simple_literal(&mut self, start: usize) -> Token<'a> {\n\n let end = loop {\n", "file_path": "src/lexer.rs", "rank": 73, "score": 40753.51249749818 }, { "content": "}\n\n\n\nimpl<'a> Spanned for DropTrigger<'a> {\n\n fn span(&self) -> Span {\n\n self.drop_span\n\n .join_span(&self.trigger_span)\n\n .join_span(&self.if_exists)\n\n .join_span(&self.schema)\n\n .join_span(&self.trigger)\n\n }\n\n}\n\n\n\npub(crate) fn parse_drop<'a, 'b>(parser: &mut Parser<'a, 'b>) -> Result<Statement<'a>, ParseError> {\n\n let drop_span = parser.consume_keyword(Keyword::DROP)?;\n\n let temporary = parser.skip_keyword(Keyword::TEMPORARY);\n\n match &parser.token {\n\n Token::Ident(_, Keyword::TABLE) => {\n\n let table_span = parser.consume_keyword(Keyword::TABLE)?;\n\n let if_exists = if let Some(span) = parser.skip_keyword(Keyword::IF) {\n\n Some(parser.consume_keyword(Keyword::EXISTS)?.join_span(&span))\n", "file_path": "src/drop.rs", "rank": 74, "score": 40751.382800900516 }, { "content": "/// _ => panic!(\"We should get a drop table statement\")\n\n/// };\n\n///\n\n/// assert!(delete.views.get(0).unwrap().as_str() == \"Employees\");\n\n/// ```\n\n#[derive(Debug, Clone)]\n\npub struct DropView<'a> {\n\n /// Span of \"DROP\"\n\n pub drop_span: Span,\n\n /// Span of \"TEMPORARY\" if specified\n\n pub temporary: Option<Span>,\n\n /// Span of \"VIEW\"\n\n pub view_span: Span,\n\n /// Span of \"IF EXISTS\"\n\n pub if_exists: Option<Span>,\n\n /// List of views to drop\n\n pub views: Vec<Identifier<'a>>,\n\n}\n\n\n\nimpl<'a> Spanned for DropView<'a> {\n", "file_path": "src/drop.rs", "rank": 75, "score": 40750.511875070435 }, { "content": "/// #\n\n/// let s: DropTrigger = match stmts.pop() {\n\n/// Some(Statement::DropTrigger(s)) => s,\n\n/// _ => panic!(\"We should get a drop trigger statement\")\n\n/// };\n\n///\n\n/// assert!(s.trigger.as_str() == \"mytrigger\");\n\n/// ```\n\n#[derive(Debug, Clone)]\n\npub struct DropTrigger<'a> {\n\n /// Span of \"DROP\"\n\n pub drop_span: Span,\n\n /// Span of \"TRIGGER\"\n\n pub trigger_span: Span,\n\n /// Span of \"IF EXISTS\" if specified\n\n pub if_exists: Option<Span>,\n\n /// Schema identifier if specified\n\n pub schema: Option<Identifier<'a>>,\n\n /// Trigger to drop\n\n pub trigger: Identifier<'a>,\n", "file_path": "src/drop.rs", "rank": 76, "score": 40750.41476948488 }, { "content": "/// #\n\n/// let s: DropServer = match stmts.pop() {\n\n/// Some(Statement::DropServer(s)) => s,\n\n/// _ => panic!(\"We should get a drop server statement\")\n\n/// };\n\n///\n\n/// assert!(s.server.as_str() == \"myserver\");\n\n/// ```\n\n#[derive(Debug, Clone)]\n\npub struct DropServer<'a> {\n\n /// Span of \"DROP\"\n\n pub drop_span: Span,\n\n /// Span of \"SERVER\"\n\n pub server_span: Span,\n\n /// Span of \"IF EXISTS\" if specified\n\n pub if_exists: Option<Span>,\n\n /// Server to drop\n\n pub server: Identifier<'a>,\n\n}\n\n\n", "file_path": "src/drop.rs", "rank": 77, "score": 40748.91352866726 }, { "content": "/// #\n\n/// let s: DropProcedure = match stmts.pop() {\n\n/// Some(Statement::DropProcedure(s)) => s,\n\n/// _ => panic!(\"We should get a drop procedure statement\")\n\n/// };\n\n///\n\n/// assert!(s.procedure.as_str() == \"myproc\");\n\n/// ```\n\n#[derive(Debug, Clone)]\n\npub struct DropProcedure<'a> {\n\n /// Span of \"DROP\"\n\n pub drop_span: Span,\n\n /// Span of \"PROCEDURE\"\n\n pub procedure_span: Span,\n\n /// Span of \"IF EXISTS\" if specified\n\n pub if_exists: Option<Span>,\n\n /// Procedure to drop\n\n pub procedure: Identifier<'a>,\n\n}\n\n\n", "file_path": "src/drop.rs", "rank": 78, "score": 40748.91352866726 }, { "content": "/// #\n\n/// let s: DropEvent = match stmts.pop() {\n\n/// Some(Statement::DropEvent(s)) => s,\n\n/// _ => panic!(\"We should get a drop event statement\")\n\n/// };\n\n///\n\n/// assert!(s.event.as_str() == \"myevent\");\n\n/// ```\n\n#[derive(Debug, Clone)]\n\npub struct DropEvent<'a> {\n\n /// Span of \"DROP\"\n\n pub drop_span: Span,\n\n /// Span of \"EVENT\"\n\n pub event_span: Span,\n\n /// Span of \"IF EXISTS\" if specified\n\n pub if_exists: Option<Span>,\n\n /// Event to drop\n\n pub event: Identifier<'a>,\n\n}\n\n\n", "file_path": "src/drop.rs", "rank": 79, "score": 40748.91352866726 }, { "content": "/// #\n\n/// let s: DropDatabase = match stmts.pop() {\n\n/// Some(Statement::DropDatabase(s)) => s,\n\n/// _ => panic!(\"We should get a drop database statement\")\n\n/// };\n\n///\n\n/// assert!(s.database.as_str() == \"mydb\");\n\n/// ```\n\n#[derive(Debug, Clone)]\n\npub struct DropDatabase<'a> {\n\n /// Span of \"DROP\"\n\n pub drop_span: Span,\n\n /// Span of \"DATABASE\"\n\n pub database_span: Span,\n\n /// Span of \"IF EXISTS\" if specified\n\n pub if_exists: Option<Span>,\n\n /// Name of database to drop\n\n pub database: Identifier<'a>,\n\n}\n\n\n", "file_path": "src/drop.rs", "rank": 80, "score": 40748.73911723157 }, { "content": " let if_exists = if let Some(span) = parser.skip_keyword(Keyword::IF) {\n\n Some(parser.consume_keyword(Keyword::EXISTS)?.join_span(&span))\n\n } else {\n\n None\n\n };\n\n let function = parser.consume_plain_identifier()?;\n\n Ok(Statement::DropFunction(DropFunction {\n\n drop_span,\n\n function_span,\n\n if_exists,\n\n function,\n\n }))\n\n }\n\n Token::Ident(_, Keyword::INDEX) => {\n\n // DROP INDEX [IF EXISTS] index_name ON tbl_name\n\n parser.todo(file!(), line!())\n\n }\n\n Token::Ident(_, Keyword::PROCEDURE) => {\n\n // TODO complain about temporary\n\n let procedure_span = parser.consume_keyword(Keyword::PROCEDURE)?;\n", "file_path": "src/drop.rs", "rank": 81, "score": 40748.525643037676 }, { "content": " };\n\n let mut views = Vec::new();\n\n loop {\n\n views.push(parser.consume_plain_identifier()?);\n\n if parser.skip_token(Token::Comma).is_none() {\n\n break;\n\n }\n\n }\n\n // TODO [RESTRICT | CASCADE]\n\n Ok(Statement::DropView(DropView {\n\n drop_span,\n\n temporary,\n\n view_span,\n\n if_exists,\n\n views,\n\n }))\n\n }\n\n Token::Ident(_, Keyword::USER) => {\n\n // DROP USER [IF EXISTS] user_name [, user_name] ..\n\n parser.todo(file!(), line!())\n\n }\n\n _ => parser.expected_failure(\"droppable\"),\n\n }\n\n}\n", "file_path": "src/drop.rs", "rank": 82, "score": 40747.21914198874 }, { "content": "// Licensed under the Apache License, Version 2.0 (the \"License\");\n\n// you may not use this file except in compliance with the License.\n\n// You may obtain a copy of the License at\n\n//\n\n// http://www.apache.org/licenses/LICENSE-2.0\n\n//\n\n// Unless required by applicable law or agreed to in writing, software\n\n// distributed under the License is distributed on an \"AS IS\" BASIS,\n\n// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n\n// See the License for the specific language governing permissions and\n\n// limitations under the License.\n\n\n\nuse alloc::vec::Vec;\n\n\n\nuse crate::{\n\n keywords::Keyword,\n\n lexer::Token,\n\n parser::{ParseError, Parser},\n\n Identifier, Span, Spanned, Statement,\n\n};\n", "file_path": "src/drop.rs", "rank": 83, "score": 40746.973729394245 }, { "content": " }\n\n Token::Ident(_, Keyword::EVENT) => {\n\n // TODO complain about temporary\n\n let event_span = parser.consume_keyword(Keyword::EVENT)?;\n\n let if_exists = if let Some(span) = parser.skip_keyword(Keyword::IF) {\n\n Some(parser.consume_keyword(Keyword::EXISTS)?.join_span(&span))\n\n } else {\n\n None\n\n };\n\n let event = parser.consume_plain_identifier()?;\n\n Ok(Statement::DropEvent(DropEvent {\n\n drop_span,\n\n event_span,\n\n if_exists,\n\n event,\n\n }))\n\n }\n\n Token::Ident(_, Keyword::FUNCTION) => {\n\n // TODO complain about temporary\n\n let function_span = parser.consume_keyword(Keyword::FUNCTION)?;\n", "file_path": "src/drop.rs", "rank": 84, "score": 40746.24037822047 }, { "content": " let n1 = parser.consume_plain_identifier()?;\n\n let (schema, trigger) = if parser.skip_token(Token::Period).is_some() {\n\n (Some(n1), parser.consume_plain_identifier()?)\n\n } else {\n\n (None, n1)\n\n };\n\n Ok(Statement::DropTrigger(DropTrigger {\n\n drop_span,\n\n trigger_span,\n\n if_exists,\n\n schema,\n\n trigger,\n\n }))\n\n }\n\n Token::Ident(_, Keyword::VIEW) => {\n\n let view_span = parser.consume_keyword(Keyword::VIEW)?;\n\n let if_exists = if let Some(span) = parser.skip_keyword(Keyword::IF) {\n\n Some(parser.consume_keyword(Keyword::EXISTS)?.join_span(&span))\n\n } else {\n\n None\n", "file_path": "src/drop.rs", "rank": 85, "score": 40744.89502021147 }, { "content": " let if_exists = if let Some(span) = parser.skip_keyword(Keyword::IF) {\n\n Some(parser.consume_keyword(Keyword::EXISTS)?.join_span(&span))\n\n } else {\n\n None\n\n };\n\n let procedure = parser.consume_plain_identifier()?;\n\n Ok(Statement::DropProcedure(DropProcedure {\n\n drop_span,\n\n procedure_span,\n\n if_exists,\n\n procedure,\n\n }))\n\n }\n\n Token::Ident(_, Keyword::SEQUENCE) => {\n\n // DROP [TEMPORARY] SEQUENCE [IF EXISTS] [/*COMMENT TO SAVE*/] sequence_name [, sequence_name] ...\n\n parser.todo(file!(), line!())\n\n }\n\n Token::Ident(_, Keyword::SERVER) => {\n\n // TODO complain about temporary\n\n let server_span = parser.consume_keyword(Keyword::SERVER)?;\n", "file_path": "src/drop.rs", "rank": 86, "score": 40744.84529002258 }, { "content": " let if_exists = if let Some(span) = parser.skip_keyword(Keyword::IF) {\n\n Some(parser.consume_keyword(Keyword::EXISTS)?.join_span(&span))\n\n } else {\n\n None\n\n };\n\n let server = parser.consume_plain_identifier()?;\n\n Ok(Statement::DropServer(DropServer {\n\n drop_span,\n\n server_span,\n\n if_exists,\n\n server,\n\n }))\n\n }\n\n Token::Ident(_, Keyword::TRIGGER) => {\n\n let trigger_span = parser.consume_keyword(Keyword::TRIGGER)?;\n\n let if_exists = if let Some(span) = parser.skip_keyword(Keyword::IF) {\n\n Some(parser.consume_keyword(Keyword::EXISTS)?.join_span(&span))\n\n } else {\n\n None\n\n };\n", "file_path": "src/drop.rs", "rank": 87, "score": 40744.53097961359 }, { "content": "#[derive(Debug, Clone)]\n\npub struct DropTable<'a> {\n\n /// Span of \"DROP\"\n\n pub drop_span: Span,\n\n /// Span of \"TEMPORARY\" if specified\n\n pub temporary: Option<Span>,\n\n /// Span of \"TABLE\"\n\n pub table_span: Span,\n\n /// Span of \"IF EXISTS\" if specified\n\n pub if_exists: Option<Span>,\n\n /// List of tables to drops\n\n pub tables: Vec<Identifier<'a>>,\n\n /// Span of \"CASCADE\" if specified\n\n pub cascade: Option<Span>,\n\n}\n\n\n\nimpl<'a> Spanned for DropTable<'a> {\n\n fn span(&self) -> Span {\n\n self.drop_span\n\n .join_span(&self.temporary)\n", "file_path": "src/drop.rs", "rank": 88, "score": 40743.7981295113 }, { "content": " tables,\n\n cascade,\n\n }))\n\n }\n\n Token::Ident(_, kw @ Keyword::DATABASE | kw @ Keyword::SCHEMA) => {\n\n // TODO complain about temporary\n\n let kw = *kw;\n\n let database_span = parser.consume_keyword(kw)?;\n\n let if_exists = if let Some(span) = parser.skip_keyword(Keyword::IF) {\n\n Some(parser.consume_keyword(Keyword::EXISTS)?.join_span(&span))\n\n } else {\n\n None\n\n };\n\n let database = parser.consume_plain_identifier()?;\n\n Ok(Statement::DropDatabase(DropDatabase {\n\n drop_span,\n\n database_span,\n\n if_exists,\n\n database,\n\n }))\n", "file_path": "src/drop.rs", "rank": 89, "score": 40743.09144624854 }, { "content": " match self.chars.peek() {\n\n Some((_, '_' | 'a'..='z' | 'A'..='Z' | '0'..='9')) => {\n\n self.chars.next();\n\n }\n\n Some((i, _)) => break *i,\n\n None => break self.src.len(),\n\n }\n\n };\n\n let s = self.s(start..end);\n\n let ss = s.to_ascii_uppercase();\n\n Token::Ident(s, ss.as_str().into())\n\n }\n\n\n\n /// Simulate reading from standard input after a statement like `COPY ... FROM STDIN;`.\n\n /// First skips space characters and optionally one NL.\n\n /// Then consumes until NL '\\' '.' NL is encountered, or until EOF.\n\n /// The trailing '\\' '.' NL is consumed but not returned.\n\n pub fn read_from_stdin(&mut self) -> (&'a str, Span) {\n\n // Skip optional spaces.\n\n while self\n", "file_path": "src/lexer.rs", "rank": 90, "score": 40742.33950170209 }, { "content": " }\n\n}\n\n\n\nimpl<'a> Iterator for Lexer<'a> {\n\n type Item = (Token<'a>, Span);\n\n\n\n fn next(&mut self) -> Option<Self::Item> {\n\n Some(self.next_token())\n\n }\n\n}\n", "file_path": "src/lexer.rs", "rank": 91, "score": 40740.74097210104 }, { "content": " }\n\n // Data ends at EOF without NL '\\' '.' [NL].\n\n let span = start..self.src.len();\n\n return (self.s(span.clone()), span);\n\n }\n\n\n\n pub fn next_token(&mut self) -> (Token<'a>, Span) {\n\n loop {\n\n let (start, c) = match self.chars.next() {\n\n Some(v) => v,\n\n None => {\n\n return (Token::Eof, self.src.len()..self.src.len());\n\n }\n\n };\n\n let t = match c {\n\n ' ' | '\\t' | '\\n' | '\\r' => continue,\n\n '?' => Token::QuestionMark,\n\n ';' => Token::SemiColon,\n\n '\\\\' => Token::Backslash,\n\n '[' => Token::LBracket,\n", "file_path": "src/lexer.rs", "rank": 92, "score": 40738.421991903655 }, { "content": "// Licensed under the Apache License, Version 2.0 (the \"License\");\n\n// you may not use this file except in compliance with the License.\n\n// You may obtain a copy of the License at\n\n//\n\n// http://www.apache.org/licenses/LICENSE-2.0\n\n//\n\n// Unless required by applicable law or agreed to in writing, software\n\n// distributed under the License is distributed on an \"AS IS\" BASIS,\n\n// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n\n// See the License for the specific language governing permissions and\n\n// limitations under the License.\n\n\n\nuse crate::{keywords::Keyword, Span};\n\n\n\n/// SQL Token enumeration\n\n#[derive(Debug, Clone, PartialEq, Eq, Hash)]\n\npub(crate) enum Token<'a> {\n\n Ampersand,\n\n At,\n\n Backslash,\n", "file_path": "src/lexer.rs", "rank": 93, "score": 40736.549026913024 }, { "content": " Spaceship,\n\n Tilde,\n\n Eof,\n\n PercentS,\n\n}\n\n\n\nimpl<'a> Token<'a> {\n\n pub(crate) fn name(&self) -> &'static str {\n\n match self {\n\n Token::Ampersand => \"'&'\",\n\n Token::At => \"'@'\",\n\n Token::Backslash => \"'\\\\'\",\n\n Token::Caret => \"'^'\",\n\n Token::Colon => \"':'\",\n\n Token::Comma => \"','\",\n\n Token::Div => \"'/'\",\n\n Token::DoubleColon => \"'::'\",\n\n Token::DoubleExclamationMark => \"'!!'\",\n\n Token::DoublePipe => \"'||'\",\n\n Token::DoubleAmpersand => \"'&&'\",\n", "file_path": "src/lexer.rs", "rank": 94, "score": 40735.32753923577 }, { "content": " .chars\n\n .peek()\n\n .filter(|(_, c)| *c != '\\n' && c.is_ascii_whitespace())\n\n .is_some()\n\n {\n\n self.chars.next().unwrap();\n\n }\n\n let start = match self.chars.peek() {\n\n Some((i, '\\n')) => i + 1,\n\n Some((i, _)) => *i,\n\n None => {\n\n let span = self.src.len()..self.src.len();\n\n return (self.s(span.clone()), span);\n\n }\n\n };\n\n while let Some((i, c)) = self.chars.next() {\n\n if c != '\\n' {\n\n continue;\n\n }\n\n if !matches!(self.chars.peek(), Some((_, '\\\\'))) {\n", "file_path": "src/lexer.rs", "rank": 95, "score": 40734.05802328818 }, { "content": " }\n\n None => break Token::Float(self.s(start..self.src.len())),\n\n }\n\n },\n\n _ => Token::Period,\n\n },\n\n _ => Token::Invalid,\n\n };\n\n\n\n let end = match self.chars.peek() {\n\n Some((i, _)) => *i,\n\n None => self.src.len(),\n\n };\n\n return (t, start..end);\n\n\n\n // // string\n\n\n\n // '\\'' => {\n\n // let value = self.tokenize_single_quoted_string(chars)?;\n\n // Ok(Some(Token::SingleQuotedString { value, span }))\n", "file_path": "src/lexer.rs", "rank": 96, "score": 40732.27692406213 }, { "content": " None => break Token::Float(self.s(start..self.src.len())),\n\n }\n\n };\n\n }\n\n Some((i, _)) => {\n\n let i = *i;\n\n break Token::Integer(self.s(start..i));\n\n }\n\n None => break Token::Integer(self.s(start..self.src.len())),\n\n }\n\n },\n\n '.' => match self.chars.peek() {\n\n Some((_, '0'..='9')) => loop {\n\n match self.chars.peek() {\n\n Some((_, '0'..='9')) => {\n\n self.chars.next();\n\n }\n\n Some((i, _)) => {\n\n let i = *i;\n\n break Token::Float(self.s(start..i));\n", "file_path": "src/lexer.rs", "rank": 97, "score": 40730.68342538552 }, { "content": " self.chars.peek(),\n\n Some((_, '_' | 'a'..='z' | 'A'..='Z' | '0'..='9' | '-'))\n\n ) {\n\n self.chars.next();\n\n }\n\n match self.chars.peek() {\n\n Some((i, '`')) => {\n\n let i = *i;\n\n self.chars.next();\n\n Token::Ident(self.s(start + 1..i), Keyword::QUOTED_IDENTIFIER)\n\n }\n\n _ => Token::Invalid,\n\n }\n\n }\n\n '\\'' => loop {\n\n match self.chars.next() {\n\n Some((_, '\\\\')) => {\n\n self.chars.next();\n\n }\n\n Some((i, '\\'')) => match self.chars.peek() {\n", "file_path": "src/lexer.rs", "rank": 98, "score": 40729.27199163194 }, { "content": " continue;\n\n }\n\n self.chars.next().unwrap();\n\n if !matches!(self.chars.peek(), Some((_, '.'))) {\n\n continue;\n\n }\n\n self.chars.next().unwrap();\n\n if matches!(self.chars.peek(), Some((_, '\\n'))) {\n\n // Data ends with NL '\\' '.' NL.\n\n self.chars.next().unwrap();\n\n } else if !matches!(self.chars.peek(), None) {\n\n continue;\n\n } else {\n\n // Data ends with NL '\\' '.' without an extra NL,\n\n // which is fine.\n\n }\n\n // `i` is the character index of the first '\\n',\n\n // so the data ends at character index i + 1.\n\n let span = start..(i + 1);\n\n return (self.s(span.clone()), span);\n", "file_path": "src/lexer.rs", "rank": 99, "score": 40729.21919525132 } ]
Rust
implementations/rust/ockam/signature_ps/src/signature.rs
psinghal20/ockam
55c2787eb2392c919156c6dded9f31a5249541e1
use crate::{PublicKey, SecretKey}; use blake2::{Blake2b, VarBlake2b}; use bls12_381_plus::{ multi_miller_loop, ExpandMsgXmd, G1Affine, G1Projective, G2Affine, G2Prepared, G2Projective, Scalar, }; use core::convert::TryFrom; use digest::{Update, VariableOutput}; use group::{Curve, Group}; use serde::{ de::{Error as DError, SeqAccess, Visitor}, ser::SerializeTuple, Deserialize, Deserializer, Serialize, Serializer, }; use signature_core::{constants::*, error::Error, lib::*, util::*}; use subtle::{Choice, CtOption}; #[derive(Debug, Copy, Clone, Eq, PartialEq)] pub struct Signature { pub(crate) sigma_1: G1Projective, pub(crate) sigma_2: G1Projective, pub(crate) m_tick: Scalar, } impl Serialize for Signature { fn serialize<S>(&self, s: S) -> Result<S::Ok, S::Error> where S: Serializer, { let bytes = self.to_bytes(); let mut seq = s.serialize_tuple(bytes.len())?; for b in &bytes { seq.serialize_element(b)?; } seq.end() } } impl<'de> Deserialize<'de> for Signature { fn deserialize<D>(d: D) -> Result<Signature, D::Error> where D: Deserializer<'de>, { struct ArrayVisitor; impl<'de> Visitor<'de> for ArrayVisitor { type Value = Signature; fn expecting(&self, f: &mut fmt::Formatter) -> fmt::Result { write!(f, "expected byte array") } fn visit_seq<A>(self, mut seq: A) -> Result<Signature, A::Error> where A: SeqAccess<'de>, { let mut arr = [0u8; Signature::BYTES]; for i in 0..arr.len() { arr[i] = seq .next_element()? .ok_or_else(|| DError::invalid_length(i, &self))?; } let res = Signature::from_bytes(&arr); if res.is_some().unwrap_u8() == 1 { Ok(res.unwrap()) } else { Err(DError::invalid_value( serde::de::Unexpected::Bytes(&arr), &self, )) } } } d.deserialize_tuple(Signature::BYTES, ArrayVisitor) } } impl Default for Signature { fn default() -> Self { Self { sigma_1: G1Projective::identity(), sigma_2: G1Projective::identity(), m_tick: Scalar::zero(), } } } impl Signature { pub const BYTES: usize = 128; const DST: &'static [u8] = b"PS_SIG_BLS12381G1_XMD:BLAKE2B_SSWU_RO_"; pub fn new<M>(sk: &SecretKey, msgs: M) -> Result<Self, Error> where M: AsRef<[Message]>, { let msgs = msgs.as_ref(); if sk.y.len() < msgs.len() { return Err(Error::new(1, "secret key is not big enough")); } if sk.is_invalid() { return Err(Error::new(1, "invalid secret key")); } let mut hasher = VarBlake2b::new(48).unwrap(); for m in msgs { hasher.update(m.to_bytes()); } let mut out = [0u8; 48]; hasher.finalize_variable(|r| { out.copy_from_slice(r); }); let m_tick = Scalar::from_okm(&out); let sigma_1 = G1Projective::hash::<ExpandMsgXmd<Blake2b>>(&m_tick.to_bytes()[..], Self::DST); let mut exp = sk.x + sk.w * m_tick; for i in 0..msgs.len() { exp += sk.y[i] * msgs[i].0; } let sigma_2 = sigma_1 * exp; Ok(Self { sigma_1, sigma_2, m_tick, }) } pub fn verify<M>(&self, pk: &PublicKey, msgs: M) -> Choice where M: AsRef<[Message]>, { let msgs = msgs.as_ref(); if pk.y.len() < msgs.len() { return Choice::from(0); } if pk.is_invalid().unwrap_u8() == 1 { return Choice::from(0); } let mut points = Vec::<G2Projective, U130>::new(); let mut scalars = Vec::<Scalar, U130>::new(); points.push(pk.x).expect(ALLOC_MSG); scalars.push(Scalar::one()).expect(ALLOC_MSG); points.push(pk.w).expect(ALLOC_MSG); scalars.push(self.m_tick).expect(ALLOC_MSG); for i in 0..msgs.len() { points.push(pk.y[i]).expect(ALLOC_MSG); scalars.push(msgs[i].0).expect(ALLOC_MSG); } let y_m = G2Projective::sum_of_products_in_place(points.as_ref(), scalars.as_mut()); multi_miller_loop(&[ ( &self.sigma_1.to_affine(), &G2Prepared::from(y_m.to_affine()), ), ( &self.sigma_2.to_affine(), &G2Prepared::from(-G2Affine::generator()), ), ]) .final_exponentiation() .is_identity() } pub fn to_bytes(&self) -> [u8; Self::BYTES] { let mut bytes = [0u8; Self::BYTES]; bytes[..48].copy_from_slice(&self.sigma_1.to_affine().to_compressed()); bytes[48..96].copy_from_slice(&self.sigma_2.to_affine().to_compressed()); bytes[96..128].copy_from_slice(&scalar_to_bytes(self.m_tick)); bytes } pub fn from_bytes(data: &[u8; Self::BYTES]) -> CtOption<Self> { let s1 = G1Affine::from_compressed(slicer!(data, 0, 48, COMMITMENT_BYTES)) .map(|p| G1Projective::from(p)); let s2 = G1Affine::from_compressed(slicer!(data, 48, 96, COMMITMENT_BYTES)) .map(|p| G1Projective::from(p)); let m_t = scalar_from_bytes(slicer!(data, 96, 128, FIELD_BYTES)); s1.and_then(|sigma_1| { s2.and_then(|sigma_2| { m_t.and_then(|m_tick| { CtOption::new( Signature { sigma_1, sigma_2, m_tick, }, Choice::from(1), ) }) }) }) } }
use crate::{PublicKey, SecretKey}; use blake2::{Blake2b, VarBlake2b}; use bls12_381_plus::{ multi_miller_loop, ExpandMsgXmd, G1Affine, G1Projective, G2Affine, G2Prepared, G2Projective, Scalar, }; use core::convert::TryFrom; use digest::{Update, VariableOutput}; use group::{Curve, Group}; use serde::{ de::{Error as DError, SeqAccess, Visitor}, ser::SerializeTuple, Deserialize, Deserializer, Serialize, Serializer, }; use signature_core::{constants::*, error::Error, lib::*, util::*}; use subtle::{Choice, CtOption}; #[derive(Debug, Copy, Clone, Eq, PartialEq)] pub struct Signature { pub(crate) sigma_1: G1Projective, pub(crate) sigma_2: G1Projective, pub(crate) m_tick: Scalar, } impl Serialize for Signature {
} impl<'de> Deserialize<'de> for Signature { fn deserialize<D>(d: D) -> Result<Signature, D::Error> where D: Deserializer<'de>, { struct ArrayVisitor; impl<'de> Visitor<'de> for ArrayVisitor { type Value = Signature; fn expecting(&self, f: &mut fmt::Formatter) -> fmt::Result { write!(f, "expected byte array") } fn visit_seq<A>(self, mut seq: A) -> Result<Signature, A::Error> where A: SeqAccess<'de>, { let mut arr = [0u8; Signature::BYTES]; for i in 0..arr.len() { arr[i] = seq .next_element()? .ok_or_else(|| DError::invalid_length(i, &self))?; } let res = Signature::from_bytes(&arr); if res.is_some().unwrap_u8() == 1 { Ok(res.unwrap()) } else { Err(DError::invalid_value( serde::de::Unexpected::Bytes(&arr), &self, )) } } } d.deserialize_tuple(Signature::BYTES, ArrayVisitor) } } impl Default for Signature { fn default() -> Self { Self { sigma_1: G1Projective::identity(), sigma_2: G1Projective::identity(), m_tick: Scalar::zero(), } } } impl Signature { pub const BYTES: usize = 128; const DST: &'static [u8] = b"PS_SIG_BLS12381G1_XMD:BLAKE2B_SSWU_RO_"; pub fn new<M>(sk: &SecretKey, msgs: M) -> Result<Self, Error> where M: AsRef<[Message]>, { let msgs = msgs.as_ref(); if sk.y.len() < msgs.len() { return Err(Error::new(1, "secret key is not big enough")); } if sk.is_invalid() { return Err(Error::new(1, "invalid secret key")); } let mut hasher = VarBlake2b::new(48).unwrap(); for m in msgs { hasher.update(m.to_bytes()); } let mut out = [0u8; 48]; hasher.finalize_variable(|r| { out.copy_from_slice(r); }); let m_tick = Scalar::from_okm(&out); let sigma_1 = G1Projective::hash::<ExpandMsgXmd<Blake2b>>(&m_tick.to_bytes()[..], Self::DST); let mut exp = sk.x + sk.w * m_tick; for i in 0..msgs.len() { exp += sk.y[i] * msgs[i].0; } let sigma_2 = sigma_1 * exp; Ok(Self { sigma_1, sigma_2, m_tick, }) } pub fn verify<M>(&self, pk: &PublicKey, msgs: M) -> Choice where M: AsRef<[Message]>, { let msgs = msgs.as_ref(); if pk.y.len() < msgs.len() { return Choice::from(0); } if pk.is_invalid().unwrap_u8() == 1 { return Choice::from(0); } let mut points = Vec::<G2Projective, U130>::new(); let mut scalars = Vec::<Scalar, U130>::new(); points.push(pk.x).expect(ALLOC_MSG); scalars.push(Scalar::one()).expect(ALLOC_MSG); points.push(pk.w).expect(ALLOC_MSG); scalars.push(self.m_tick).expect(ALLOC_MSG); for i in 0..msgs.len() { points.push(pk.y[i]).expect(ALLOC_MSG); scalars.push(msgs[i].0).expect(ALLOC_MSG); } let y_m = G2Projective::sum_of_products_in_place(points.as_ref(), scalars.as_mut()); multi_miller_loop(&[ ( &self.sigma_1.to_affine(), &G2Prepared::from(y_m.to_affine()), ), ( &self.sigma_2.to_affine(), &G2Prepared::from(-G2Affine::generator()), ), ]) .final_exponentiation() .is_identity() } pub fn to_bytes(&self) -> [u8; Self::BYTES] { let mut bytes = [0u8; Self::BYTES]; bytes[..48].copy_from_slice(&self.sigma_1.to_affine().to_compressed()); bytes[48..96].copy_from_slice(&self.sigma_2.to_affine().to_compressed()); bytes[96..128].copy_from_slice(&scalar_to_bytes(self.m_tick)); bytes } pub fn from_bytes(data: &[u8; Self::BYTES]) -> CtOption<Self> { let s1 = G1Affine::from_compressed(slicer!(data, 0, 48, COMMITMENT_BYTES)) .map(|p| G1Projective::from(p)); let s2 = G1Affine::from_compressed(slicer!(data, 48, 96, COMMITMENT_BYTES)) .map(|p| G1Projective::from(p)); let m_t = scalar_from_bytes(slicer!(data, 96, 128, FIELD_BYTES)); s1.and_then(|sigma_1| { s2.and_then(|sigma_2| { m_t.and_then(|m_tick| { CtOption::new( Signature { sigma_1, sigma_2, m_tick, }, Choice::from(1), ) }) }) }) } }
fn serialize<S>(&self, s: S) -> Result<S::Ok, S::Error> where S: Serializer, { let bytes = self.to_bytes(); let mut seq = s.serialize_tuple(bytes.len())?; for b in &bytes { seq.serialize_element(b)?; } seq.end() }
function_block-full_function
[ { "content": "/// Convert a big endian byte sequence to a Scalar\n\npub fn scalar_from_bytes(bytes: &[u8; 32]) -> CtOption<Scalar> {\n\n let mut t = [0u8; 32];\n\n t.copy_from_slice(bytes);\n\n t.reverse();\n\n Scalar::from_bytes(&t)\n\n}\n\n\n", "file_path": "implementations/rust/ockam/signature_core/src/util.rs", "rank": 0, "score": 233299.63104240925 }, { "content": "/// Converts a scalar to big endian bytes\n\npub fn scalar_to_bytes(s: Scalar) -> [u8; 32] {\n\n let mut bytes = s.to_bytes();\n\n // Make big endian\n\n bytes.reverse();\n\n bytes\n\n}\n\n\n", "file_path": "implementations/rust/ockam/signature_core/src/util.rs", "rank": 1, "score": 230605.61151242253 }, { "content": "/// Hashes a byte sequence to a Scalar\n\npub fn hash_to_scalar<B: AsRef<[u8]>>(data: B) -> Scalar {\n\n const BYTES: usize = 48;\n\n let mut res = [0u8; BYTES];\n\n let mut hasher = VarBlake2b::new(BYTES).unwrap();\n\n hasher.update(data.as_ref());\n\n hasher.finalize_variable(|out| {\n\n res.copy_from_slice(out);\n\n });\n\n Scalar::from_okm(&res)\n\n}\n\n\n", "file_path": "implementations/rust/ockam/signature_core/src/util.rs", "rank": 2, "score": 214038.0827802776 }, { "content": "/// Compute multi-exponeniation which for elliptic curves is the sum of products\n\n/// using Pippenger's method\n\npub fn sum_of_products(points: &[G1Projective], scalars: &mut [Scalar]) -> G1Projective {\n\n G1Projective::sum_of_products_in_place(points, scalars)\n\n}\n", "file_path": "implementations/rust/ockam/signature_core/src/util.rs", "rank": 3, "score": 208895.72587374336 }, { "content": "/// An internal vector serializer\n\npub trait VecSerializer<'de>: Sized {\n\n /// Serialize the custom type and size\n\n fn serialize<S>(&self, ser: S) -> Result<S::Ok, S::Error>\n\n where\n\n S: Serializer;\n\n /// Deserialize the custom type and size\n\n fn deserialize<D>(des: D) -> Result<Self, D::Error>\n\n where\n\n D: Deserializer<'de>;\n\n}\n\n\n\nimpl<'de, T, N> VecSerializer<'de> for Vec<T, N>\n\nwhere\n\n T: Default + Copy + Serialize + Deserialize<'de>,\n\n N: ArrayLength<T>,\n\n{\n\n fn serialize<S>(&self, ser: S) -> Result<S::Ok, S::Error>\n\n where\n\n S: Serializer,\n\n {\n", "file_path": "implementations/rust/ockam/signature_core/src/util.rs", "rank": 4, "score": 206839.95077214658 }, { "content": "pub fn block_on<T>(future: impl Future<Output = T> + 'static + Send) -> T\n\nwhere\n\n T: Send + 'static,\n\n{\n\n executor::block_on(future)\n\n}\n", "file_path": "implementations/rust/ockam/ockam_node_no_std/src/lib.rs", "rank": 5, "score": 146051.87092540873 }, { "content": "pub fn read_byte_string<'de, D>(deserializer: D) -> Result<String, D::Error>\n\nwhere\n\n D: Deserializer<'de>,\n\n{\n\n struct ByteStringVisitor;\n\n\n\n impl<'de> Visitor<'de> for ByteStringVisitor {\n\n type Value = String;\n\n\n\n fn expecting(&self, formatter: &mut fmt::Formatter) -> fmt::Result {\n\n formatter.write_str(\"expected array of attributes\")\n\n }\n\n\n\n fn visit_str<E>(self, s: &str) -> Result<String, E>\n\n where\n\n E: DError,\n\n {\n\n Ok(String::from(s))\n\n }\n\n }\n\n\n\n deserializer.deserialize_str(ByteStringVisitor)\n\n}\n", "file_path": "implementations/rust/ockam/ockam/src/credential/util.rs", "rank": 6, "score": 137032.91754120737 }, { "content": "pub fn read_attributes<'de, D>(deserializer: D) -> Result<Vec<CredentialAttributeSchema>, D::Error>\n\nwhere\n\n D: Deserializer<'de>,\n\n{\n\n struct BufferAttributeVisitor;\n\n\n\n impl<'de> Visitor<'de> for BufferAttributeVisitor {\n\n type Value = Vec<CredentialAttributeSchema>;\n\n\n\n fn expecting(&self, formatter: &mut fmt::Formatter) -> fmt::Result {\n\n formatter.write_str(\"expected array of attributes\")\n\n }\n\n\n\n fn visit_seq<A>(self, mut s: A) -> Result<Vec<CredentialAttributeSchema>, A::Error>\n\n where\n\n A: SeqAccess<'de>,\n\n {\n\n let _l = if let Some(l) = s.size_hint() { l } else { 0 };\n\n let mut buf = Vec::new();\n\n while let Some(a) = s.next_element()? {\n", "file_path": "implementations/rust/ockam/ockam/src/credential/util.rs", "rank": 7, "score": 132605.21563638584 }, { "content": "pub fn sha256(vault: &mut impl Hasher) {\n\n let res = vault.sha256(b\"a\");\n\n assert!(res.is_ok());\n\n let digest = res.unwrap();\n\n assert_eq!(\n\n encode(digest),\n\n \"ca978112ca1bbdcafac231b39a23dc4da786eff8147c4e72b9807785afee48bb\"\n\n );\n\n}\n\n\n", "file_path": "implementations/rust/ockam/ockam_vault_test_suite/src/hasher_impl.rs", "rank": 8, "score": 131397.10088678217 }, { "content": "pub fn new_secret_keys(vault: &mut impl SecretVault) {\n\n let types = [(SecretType::Curve25519, 32), (SecretType::Buffer, 24)];\n\n for (t, s) in &types {\n\n let attributes = SecretAttributes::new(*t, SecretPersistence::Ephemeral, *s);\n\n let res = vault.secret_generate(attributes);\n\n assert!(res.is_ok());\n\n let sk_ctx = res.unwrap();\n\n let sk = vault.secret_export(&sk_ctx).unwrap();\n\n assert_eq!(sk.as_ref().len(), *s);\n\n vault.secret_destroy(sk_ctx).unwrap();\n\n }\n\n}\n\n\n", "file_path": "implementations/rust/ockam/ockam_vault_test_suite/src/secret_impl.rs", "rank": 9, "score": 127751.42367265391 }, { "content": "pub fn secret_attributes_get(vault: &mut impl SecretVault) {\n\n let attributes = SecretAttributes::new(\n\n SecretType::Curve25519,\n\n SecretPersistence::Ephemeral,\n\n CURVE25519_SECRET_LENGTH,\n\n );\n\n\n\n let secret = vault.secret_generate(attributes).unwrap();\n\n assert_eq!(vault.secret_attributes_get(&secret).unwrap(), attributes);\n\n\n\n let attributes = SecretAttributes::new(SecretType::Buffer, SecretPersistence::Ephemeral, 24);\n\n\n\n let secret = vault.secret_generate(attributes).unwrap();\n\n assert_eq!(vault.secret_attributes_get(&secret).unwrap(), attributes);\n\n}\n", "file_path": "implementations/rust/ockam/ockam_vault_test_suite/src/secret_impl.rs", "rank": 10, "score": 127751.42367265391 }, { "content": "pub fn new_public_keys(vault: &mut impl SecretVault) {\n\n let attributes = SecretAttributes::new(\n\n SecretType::Curve25519,\n\n SecretPersistence::Ephemeral,\n\n CURVE25519_SECRET_LENGTH,\n\n );\n\n\n\n let res = vault.secret_generate(attributes);\n\n assert!(res.is_ok());\n\n let p256_ctx_1 = res.unwrap();\n\n\n\n let res = vault.secret_public_key_get(&p256_ctx_1);\n\n assert!(res.is_ok());\n\n let pk_1 = res.unwrap();\n\n assert_eq!(pk_1.as_ref().len(), CURVE25519_PUBLIC_LENGTH);\n\n\n\n let res = vault.secret_generate(attributes);\n\n assert!(res.is_ok());\n\n let c25519_ctx_1 = res.unwrap();\n\n let res = vault.secret_public_key_get(&c25519_ctx_1);\n\n assert!(res.is_ok());\n\n let pk_1 = res.unwrap();\n\n assert_eq!(pk_1.as_ref().len(), CURVE25519_PUBLIC_LENGTH);\n\n}\n\n\n", "file_path": "implementations/rust/ockam/ockam_vault_test_suite/src/secret_impl.rs", "rank": 11, "score": 127751.42367265391 }, { "content": "pub fn secret_import_export(vault: &mut impl SecretVault) {\n\n let attributes = SecretAttributes::new(\n\n SecretType::Curve25519,\n\n SecretPersistence::Ephemeral,\n\n CURVE25519_SECRET_LENGTH,\n\n );\n\n\n\n let secret_str = \"98d589b0dce92c9e2442b3093718138940bff71323f20b9d158218b89c3cec6e\";\n\n\n\n let secret = vault\n\n .secret_import(decode(secret_str).unwrap().as_slice(), attributes)\n\n .unwrap();\n\n\n\n assert_eq!(secret.index(), 1);\n\n assert_eq!(\n\n encode(vault.secret_export(&secret).unwrap().as_ref()),\n\n secret_str\n\n );\n\n\n\n let attributes = SecretAttributes::new(SecretType::Buffer, SecretPersistence::Ephemeral, 24);\n", "file_path": "implementations/rust/ockam/ockam_vault_test_suite/src/secret_impl.rs", "rank": 12, "score": 127751.42367265391 }, { "content": "pub fn hkdf(vault: &mut (impl Hasher + SecretVault)) {\n\n let salt_value = b\"hkdf_test\";\n\n let attributes = SecretAttributes::new(\n\n SecretType::Buffer,\n\n SecretPersistence::Ephemeral,\n\n salt_value.len(),\n\n );\n\n let salt = vault.secret_import(&salt_value[..], attributes).unwrap();\n\n\n\n let ikm_value = b\"a\";\n\n let attributes = SecretAttributes::new(\n\n SecretType::Buffer,\n\n SecretPersistence::Ephemeral,\n\n ikm_value.len(),\n\n );\n\n let ikm = vault.secret_import(&ikm_value[..], attributes).unwrap();\n\n\n\n let attributes = SecretAttributes::new(SecretType::Buffer, SecretPersistence::Ephemeral, 24);\n\n\n\n let res = vault.hkdf_sha256(&salt, b\"\", Some(&ikm), vec![attributes]);\n\n assert!(res.is_ok());\n\n let digest = res.unwrap();\n\n assert_eq!(digest.len(), 1);\n\n let digest = vault.secret_export(&digest[0]).unwrap();\n\n assert_eq!(\n\n encode(digest.as_ref()),\n\n \"921ab9f260544b71941dbac2ca2d42c417aa07b53e055a8f\"\n\n );\n\n}\n", "file_path": "implementations/rust/ockam/ockam_vault_test_suite/src/hasher_impl.rs", "rank": 13, "score": 126021.38537750355 }, { "content": "pub fn encryption(vault: &mut (impl SymmetricVault + SecretVault)) {\n\n let message = b\"Ockam Test Message\";\n\n let nonce = b\"TestingNonce\";\n\n let aad = b\"Extra payload data\";\n\n let attributes = SecretAttributes::new(\n\n SecretType::Aes,\n\n SecretPersistence::Ephemeral,\n\n AES128_SECRET_LENGTH,\n\n );\n\n\n\n let ctx = &vault.secret_generate(attributes).unwrap();\n\n let res = vault.aead_aes_gcm_encrypt(ctx, message.as_ref(), nonce.as_ref(), aad.as_ref());\n\n assert!(res.is_ok());\n\n let mut ciphertext = res.unwrap();\n\n let res = vault.aead_aes_gcm_decrypt(ctx, ciphertext.as_slice(), nonce.as_ref(), aad.as_ref());\n\n assert!(res.is_ok());\n\n let plaintext = res.unwrap();\n\n assert_eq!(plaintext, message.to_vec());\n\n ciphertext[0] ^= 0xb4;\n\n ciphertext[1] ^= 0xdc;\n\n let res = vault.aead_aes_gcm_decrypt(ctx, ciphertext.as_slice(), nonce.as_ref(), aad.as_ref());\n\n assert!(res.is_err());\n\n}\n", "file_path": "implementations/rust/ockam/ockam_vault_test_suite/src/symmetric_impl.rs", "rank": 14, "score": 124837.35723485022 }, { "content": "/// Traits required for a Vault implementation suitable for use in a Profile\n\npub trait ProfileVault:\n\n SecretVault + SecureChannelVault + KeyIdVault + Hasher + Signer + Verifier + Clone + Send + 'static\n\n{\n\n}\n\n\n\nimpl<D> ProfileVault for D where\n\n D: SecretVault\n\n + SecureChannelVault\n\n + KeyIdVault\n\n + Hasher\n\n + Signer\n\n + Verifier\n\n + Clone\n\n + Send\n\n + 'static\n\n{\n\n}\n\n\n\n/// Profile is an abstraction responsible for keeping, verifying and modifying\n\n/// user's data (mainly - public keys). It is used to create new keys, rotate and revoke them.\n", "file_path": "implementations/rust/ockam/ockam_entity/src/lib.rs", "rank": 15, "score": 123367.06588174327 }, { "content": "pub fn compute_key_id_for_public_key(vault: &mut impl KeyIdVault) {\n\n let public =\n\n decode(\"68858ea1ea4e1ade755df7fb6904056b291d9781eb5489932f46e32f12dd192a\").unwrap();\n\n let public = PublicKey::new(public.to_vec());\n\n\n\n let key_id = vault.compute_key_id_for_public_key(&public).unwrap();\n\n\n\n assert_eq!(\n\n key_id,\n\n \"732af49a0b47c820c0a4cac428d6cb80c1fa70622f4a51708163dd87931bc942\"\n\n );\n\n}\n\n\n", "file_path": "implementations/rust/ockam/ockam_vault_test_suite/src/key_id_impl.rs", "rank": 16, "score": 123299.95355277046 }, { "content": "pub fn sign(vault: &mut (impl Signer + Verifier + SecretVault)) {\n\n let secret = vault\n\n .secret_generate(SecretAttributes::new(\n\n SecretType::Curve25519,\n\n SecretPersistence::Ephemeral,\n\n CURVE25519_SECRET_LENGTH,\n\n ))\n\n .unwrap();\n\n let res = vault.sign(&secret, b\"hello world!\");\n\n assert!(res.is_ok());\n\n let pubkey = vault.secret_public_key_get(&secret).unwrap();\n\n let signature = res.unwrap();\n\n let res = vault.verify(&signature, &pubkey, b\"hello world!\").unwrap();\n\n assert!(res);\n\n}\n", "file_path": "implementations/rust/ockam/ockam_vault_test_suite/src/signer_impl.rs", "rank": 17, "score": 122422.0502327068 }, { "content": "pub fn ec_diffie_hellman_curve25519(vault: &mut (impl AsymmetricVault + SecretVault)) {\n\n let attributes = SecretAttributes::new(\n\n SecretType::Curve25519,\n\n SecretPersistence::Ephemeral,\n\n CURVE25519_SECRET_LENGTH,\n\n );\n\n let sk_ctx_1 = vault.secret_generate(attributes).unwrap();\n\n let sk_ctx_2 = vault.secret_generate(attributes).unwrap();\n\n let pk_1 = vault.secret_public_key_get(&sk_ctx_1).unwrap();\n\n let pk_2 = vault.secret_public_key_get(&sk_ctx_2).unwrap();\n\n\n\n let res1 = vault.ec_diffie_hellman(&sk_ctx_1, &pk_2);\n\n assert!(res1.is_ok());\n\n let _ss1 = res1.unwrap();\n\n\n\n let res2 = vault.ec_diffie_hellman(&sk_ctx_2, &pk_1);\n\n assert!(res2.is_ok());\n\n let _ss2 = res2.unwrap();\n\n // TODO: Check result against test vector\n\n}\n", "file_path": "implementations/rust/ockam/ockam_vault_test_suite/src/asymmetric_impl.rs", "rank": 18, "score": 121458.21707883678 }, { "content": "/// Vault with X3DH required functionality\n\npub trait X3dhVault:\n\n SecretVault + Signer + Verifier + AsymmetricVault + SymmetricVault + Hasher + Clone + Send + 'static\n\n{\n\n}\n\n\n\nimpl<D> X3dhVault for D where\n\n D: SecretVault\n\n + Signer\n\n + Verifier\n\n + AsymmetricVault\n\n + SymmetricVault\n\n + Hasher\n\n + Clone\n\n + Send\n\n + 'static\n\n{\n\n}\n\n\n\n#[cfg(test)]\n\nmod tests {\n", "file_path": "implementations/rust/ockam/ockam_key_exchange_x3dh/src/lib.rs", "rank": 19, "score": 120105.62790938737 }, { "content": "/// A trait implemented by both Initiator and Responder peers.\n\npub trait KeyExchanger {\n\n /// Generate request that should be sent to the other party.\n\n fn generate_request(&mut self, payload: &[u8]) -> Result<Vec<u8>>;\n\n /// Handle response from other party and return payload.\n\n fn handle_response(&mut self, response: &[u8]) -> Result<Vec<u8>>;\n\n /// Returns true if the key exchange process is complete.\n\n fn is_complete(&self) -> bool;\n\n /// Return the data and keys needed for channels. Key exchange must be completed prior to calling this function.\n\n fn finalize(self) -> Result<CompletedKeyExchange>;\n\n}\n\n\n", "file_path": "implementations/rust/ockam/ockam_key_exchange_core/src/lib.rs", "rank": 20, "score": 120105.62790938737 }, { "content": "/// Vault with XX required functionality\n\npub trait XXVault:\n\n SecretVault + Hasher + AsymmetricVault + SymmetricVault + Clone + Send + 'static\n\n{\n\n}\n\n\n\nimpl<D> XXVault for D where\n\n D: SecretVault + Hasher + AsymmetricVault + SymmetricVault + Clone + Send + 'static\n\n{\n\n}\n\n\n\nmod initiator;\n\nmod state;\n\npub use initiator::*;\n\nmod responder;\n\npub use responder::*;\n\nmod new_key_exchanger;\n\npub use new_key_exchanger::*;\n\nuse ockam_vault_core::{AsymmetricVault, Hasher, SecretVault, SymmetricVault};\n\n\n\n#[cfg(test)]\n", "file_path": "implementations/rust/ockam/ockam_key_exchange_xx/src/lib.rs", "rank": 21, "score": 120105.62790938737 }, { "content": "pub fn get_secret_by_key_id(vault: &mut (impl KeyIdVault + SecretVault)) {\n\n let attributes = SecretAttributes::new(\n\n SecretType::Curve25519,\n\n SecretPersistence::Ephemeral,\n\n CURVE25519_SECRET_LENGTH,\n\n );\n\n\n\n let secret = vault.secret_generate(attributes).unwrap();\n\n let public = vault.secret_public_key_get(&secret).unwrap();\n\n\n\n let key_id = vault.compute_key_id_for_public_key(&public).unwrap();\n\n let secret2 = vault.get_secret_by_key_id(&key_id).unwrap();\n\n\n\n assert_eq!(secret.index(), secret2.index());\n\n}\n", "file_path": "implementations/rust/ockam/ockam_vault_test_suite/src/key_id_impl.rs", "rank": 22, "score": 119338.92053064772 }, { "content": "/// Vault with XX required functionality\n\npub trait SecureChannelVault: SymmetricVault + Clone + Send + 'static {}\n\n\n\nimpl<D> SecureChannelVault for D where D: SymmetricVault + Clone + Send + 'static {}\n\n\n", "file_path": "implementations/rust/ockam/ockam_channel/src/traits.rs", "rank": 23, "score": 119130.20620567421 }, { "content": "/// A creator of both initiator and responder peers of a key exchange.\n\npub trait NewKeyExchanger {\n\n /// Initiator\n\n type Initiator: KeyExchanger + Send + 'static;\n\n /// Responder\n\n type Responder: KeyExchanger + Send + 'static;\n\n\n\n /// Create a new Key Exchanger with the initiator role\n\n fn initiator(&self) -> Result<Self::Initiator>;\n\n /// Create a new Key Exchanger with the responder role\n\n fn responder(&self) -> Result<Self::Responder>;\n\n}\n\n\n\n/// The state of a completed key exchange.\n\n#[derive(Debug, Zeroize)]\n\npub struct CompletedKeyExchange {\n\n h: [u8; 32],\n\n encrypt_key: Secret,\n\n decrypt_key: Secret,\n\n}\n\n\n", "file_path": "implementations/rust/ockam/ockam_key_exchange_core/src/lib.rs", "rank": 24, "score": 118558.16530728468 }, { "content": "pub fn example_schema() -> CredentialSchema {\n\n CredentialSchema {\n\n id: \"file:///truck-schema-20210227-1_0_0\".to_string(),\n\n label: \"Truck Management\".to_string(),\n\n description: \"A Demoable schema\".to_string(),\n\n attributes: vec![\n\n CredentialAttributeSchema {\n\n label: SECRET_ID.to_string(),\n\n description: \"A unique identifier for maintenance worker. \".to_string(),\n\n attribute_type: CredentialAttributeType::Blob,\n\n unknown: true,\n\n },\n\n CredentialAttributeSchema {\n\n label: \"can_access\".to_string(),\n\n description: \"Can worker access the truck maintenance codes?\".to_string(),\n\n attribute_type: CredentialAttributeType::Number,\n\n unknown: false,\n\n },\n\n ],\n\n }\n", "file_path": "implementations/rust/ockam/ockam_examples/example_projects/credentials/src/lib.rs", "rank": 25, "score": 111653.80564651037 }, { "content": "pub fn default_issuer_address() -> String {\n\n format!(\"127.0.0.1:{}\", DEFAULT_ISSUER_PORT)\n\n}\n\n\n", "file_path": "implementations/rust/ockam/ockam_examples/example_projects/credentials/src/lib.rs", "rank": 26, "score": 111653.80564651037 }, { "content": "struct ProofCommittedBuilderCache<B, C, P, S>\n\nwhere\n\n B: Clone + Copy + Debug + Default + ConstantTimeEq + PartialEq + Eq + Curve<AffineRepr = C>,\n\n C: GroupEncoding + Debug,\n\n P: ArrayLength<B> + NonZero + Clone,\n\n S: ArrayLength<Scalar> + NonZero + Clone,\n\n{\n\n commitment: B,\n\n points: Vec<B, P>,\n\n scalars: Vec<Scalar, S>,\n\n}\n\n\n\nimpl<B, C, P, S> Default for ProofCommittedBuilderCache<B, C, P, S>\n\nwhere\n\n B: Clone + Copy + Debug + Default + ConstantTimeEq + PartialEq + Eq + Curve<AffineRepr = C>,\n\n C: GroupEncoding + Debug,\n\n P: ArrayLength<B> + NonZero + Clone,\n\n S: ArrayLength<Scalar> + NonZero + Clone,\n\n{\n\n fn default() -> Self {\n", "file_path": "implementations/rust/ockam/signature_core/src/proof_committed_builder.rs", "rank": 27, "score": 103443.18795060721 }, { "content": "use crate::lib::*;\n\nuse blake2::VarBlake2b;\n\nuse bls12_381_plus::{G1Projective, Scalar};\n\nuse digest::{Update, VariableOutput};\n\nuse heapless::ArrayLength;\n\nuse serde::{\n\n de::{Error as DError, SeqAccess, Visitor},\n\n ser::SerializeSeq,\n\n Deserialize, Deserializer, Serialize, Serializer,\n\n};\n\nuse subtle::CtOption;\n\n\n\n/// Convert slice to a fixed array\n\n#[macro_export]\n\nmacro_rules! slicer {\n\n ($d:expr, $b:expr, $e:expr, $s:expr) => {\n\n &<[u8; $s]>::try_from(&$d[$b..$e]).unwrap()\n\n };\n\n}\n\n\n\n/// An internal vector serializer\n", "file_path": "implementations/rust/ockam/signature_core/src/util.rs", "rank": 28, "score": 101979.93341921852 }, { "content": "\n\n impl<'de, T, N> Visitor<'de> for TVisitor<T, N>\n\n where\n\n T: Default + Copy + Deserialize<'de>,\n\n N: ArrayLength<T>,\n\n {\n\n type Value = Vec<T, N>;\n\n\n\n fn expecting(&self, f: &mut fmt::Formatter) -> fmt::Result {\n\n f.write_str(\"expected array\")\n\n }\n\n\n\n fn visit_seq<A>(self, mut arr: A) -> Result<Vec<T, N>, A::Error>\n\n where\n\n A: SeqAccess<'de>,\n\n {\n\n let mut buf = Vec::new();\n\n for i in 0..N::to_usize() {\n\n buf.push(\n\n arr.next_element()?\n", "file_path": "implementations/rust/ockam/signature_core/src/util.rs", "rank": 29, "score": 101964.25470567906 }, { "content": " let l = if self.is_empty() {\n\n None\n\n } else {\n\n Some(self.len())\n\n };\n\n let mut iter = ser.serialize_seq(l)?;\n\n for i in self {\n\n iter.serialize_element(i)?;\n\n }\n\n iter.end()\n\n }\n\n\n\n fn deserialize<D>(des: D) -> Result<Vec<T, N>, D::Error>\n\n where\n\n D: Deserializer<'de>,\n\n {\n\n struct TVisitor<T, N> {\n\n element: PhantomData<T>,\n\n size: PhantomData<N>,\n\n }\n", "file_path": "implementations/rust/ockam/signature_core/src/util.rs", "rank": 30, "score": 101962.84939187964 }, { "content": " .ok_or_else(|| DError::invalid_length(i, &self))?,\n\n )\n\n .map_err(|_| DError::invalid_length(i, &self))?;\n\n }\n\n Ok(buf)\n\n }\n\n }\n\n\n\n let visitor = TVisitor {\n\n element: PhantomData,\n\n size: PhantomData,\n\n };\n\n des.deserialize_seq(visitor)\n\n }\n\n}\n\n\n", "file_path": "implementations/rust/ockam/signature_core/src/util.rs", "rank": 31, "score": 101958.40633472707 }, { "content": "//! A crate for common methods used by short group signatures\n\n\n\n#![no_std]\n\n#![deny(\n\n missing_docs,\n\n trivial_casts,\n\n trivial_numeric_casts,\n\n unsafe_code,\n\n unused_import_braces,\n\n unused_qualifications,\n\n warnings\n\n)]\n\n\n\n/// Common methods for signature schemes\n\n#[macro_use]\n\npub mod util;\n\n\n\n/// The errors generated by short group signatures\n\n#[macro_use]\n\npub mod error;\n", "file_path": "implementations/rust/ockam/signature_core/src/lib.rs", "rank": 32, "score": 101746.81802922768 }, { "content": "pub mod proof_message;\n\n\n\n/// The kind of hidden message in a proof\n\npub mod hidden_message;\n\n\n\n/// The blinding factor when hiding messages during signing\n\npub mod signature_blinding;\n\n\n\n/// A facade around the various collections and primitives needed\n\n/// when using no alloc, alloc only, or std modes\n\npub mod lib {\n\n pub use core::cell::{Cell, RefCell};\n\n pub use core::clone::{self, Clone};\n\n pub use core::convert::{self, From, Into};\n\n pub use core::default::{self, Default};\n\n pub use core::fmt::{self, Debug, Display};\n\n pub use core::marker::{self, PhantomData};\n\n pub use core::num::Wrapping;\n\n pub use core::ops::{Deref, DerefMut, Range};\n\n pub use core::option::{self, Option};\n", "file_path": "implementations/rust/ockam/signature_core/src/lib.rs", "rank": 33, "score": 101744.52235175214 }, { "content": " pub use core::result::{self, Result};\n\n pub use core::{cmp, iter, mem, num, slice, str};\n\n pub use core::{f32, f64};\n\n pub use core::{i16, i32, i64, i8, isize};\n\n pub use core::{u16, u32, u64, u8, usize};\n\n\n\n pub use heapless::consts::*;\n\n pub use heapless::ArrayLength;\n\n pub use heapless::String;\n\n pub use heapless::Vec;\n\n\n\n pub use super::challenge::Challenge;\n\n pub use super::commitment::Commitment;\n\n pub use super::hidden_message::HiddenMessage;\n\n pub use super::message::Message;\n\n pub use super::nonce::Nonce;\n\n pub use super::proof_committed_builder::ProofCommittedBuilder;\n\n pub use super::proof_message::ProofMessage;\n\n pub use super::signature_blinding::SignatureBlinding;\n\n pub use super::util::{sum_of_products, VecSerializer};\n\n pub use hashbrown::{HashMap, HashSet};\n\n}\n", "file_path": "implementations/rust/ockam/signature_core/src/lib.rs", "rank": 34, "score": 101743.65985997609 }, { "content": "/// The Proof of knowledge of signature proof\n\npub use pok_signature_proof::*;\n\n/// The proving methods\n\npub use prover::*;\n\n/// The Pointcheval Saunders public key\n\npub use public_key::*;\n\n/// The Pointcheval Saunders secret key\n\npub use secret_key::*;\n\n/// The Pointcheval Saunders signature\n\npub use signature::*;\n\n/// The verifier methods for validating proofs\n\npub use verifier::*;\n\n\n\n#[cfg(test)]\n\npub struct MockRng(rand_xorshift::XorShiftRng);\n\n\n\n#[cfg(test)]\n\nimpl rand_core::SeedableRng for MockRng {\n\n type Seed = [u8; 16];\n\n\n", "file_path": "implementations/rust/ockam/signature_ps/src/lib.rs", "rank": 35, "score": 101742.4776281177 }, { "content": "mod signature;\n\nmod signature_vt;\n\n\n\npub use aggregate_signature::*;\n\npub use aggregate_signature_vt::*;\n\npub use multi_public_key::*;\n\npub use multi_public_key_vt::*;\n\npub use multi_signature::*;\n\npub use multi_signature_vt::*;\n\npub use proof_of_possession::*;\n\npub use proof_of_possession_vt::*;\n\npub use public_key::*;\n\npub use public_key_vt::*;\n\npub use secret_key::*;\n\npub use signature::*;\n\npub use signature_vt::*;\n\n\n\n#[cfg(test)]\n\npub struct MockRng(rand_xorshift::XorShiftRng);\n\n\n", "file_path": "implementations/rust/ockam/signature_bls/src/lib.rs", "rank": 36, "score": 101740.17095546954 }, { "content": "mod issuer;\n\nmod message_generator;\n\nmod pok_signature;\n\nmod pok_signature_proof;\n\nmod prover;\n\nmod public_key;\n\nmod secret_key;\n\nmod signature;\n\nmod verifier;\n\n\n\n/// A PS blind signature\n\npub use blind_signature::*;\n\n/// The blind signature context\n\npub use blind_signature_context::*;\n\n/// The issuer methods\n\npub use issuer::*;\n\n/// The generators used for blind signature computation\n\npub use message_generator::*;\n\n/// The Proof of knowledge of signature proof initial phase\n\npub use pok_signature::*;\n", "file_path": "implementations/rust/ockam/signature_ps/src/lib.rs", "rank": 37, "score": 101739.3021327786 }, { "content": "\n\n/// The methods and structs for proving in zero-knowledge\n\npub mod proof_committed_builder;\n\n\n\n/// The constant values across the signatures\n\npub mod constants;\n\n\n\n/// The challenge values\n\npub mod challenge;\n\n\n\n/// Messages that can be signed\n\npub mod message;\n\n\n\n/// Nonce values for zero-knowledge proofs\n\npub mod nonce;\n\n\n\n/// Commitment for proofs and blinded values\n\npub mod commitment;\n\n\n\n/// Indicates which messages are hidden or revealed in proofs\n", "file_path": "implementations/rust/ockam/signature_core/src/lib.rs", "rank": 38, "score": 101730.983819746 }, { "content": "//! This crate implements the Pointcheval Saunders signature\n\n//! as described in <https://eprint.iacr.org/2015/525.pdf>\n\n//! and <https://eprint.iacr.org/2017/1197.pdf>\n\n\n\n#![no_std]\n\n#![deny(\n\n missing_docs,\n\n trivial_casts,\n\n trivial_numeric_casts,\n\n unsafe_code,\n\n unused_import_braces,\n\n unused_qualifications,\n\n warnings\n\n)]\n\n\n\n#[macro_use]\n\nextern crate signature_core;\n\n\n\nmod blind_signature;\n\nmod blind_signature_context;\n", "file_path": "implementations/rust/ockam/signature_ps/src/lib.rs", "rank": 39, "score": 101730.68137341447 }, { "content": "//! This crate implements BLS signatures according to the IETF draft v4\n\n//!\n\n//! for the Proof of Possession Cipher Suite\n\n//!\n\n//! Since BLS signatures can use either G1 or G2 fields, there are two types of\n\n//! public keys and signatures. Normal and Variant (suffix'd with Vt).\n\n//!\n\n//! Normal puts signatures in G1 and pubic keys in G2.\n\n//! Variant is the reverse.\n\n//!\n\n//! This crate has been designed to be compliant with no-std by avoiding allocations\n\n//!\n\n//! but provides some optimizations when an allocator exists for verifying\n\n//! aggregated signatures.\n\n\n\n#![no_std]\n\n#![deny(\n\n missing_docs,\n\n trivial_casts,\n\n trivial_numeric_casts,\n", "file_path": "implementations/rust/ockam/signature_bls/src/lib.rs", "rank": 40, "score": 101730.46269368859 }, { "content": " unsafe_code,\n\n unused_import_braces,\n\n unused_qualifications,\n\n warnings\n\n)]\n\n\n\n#[cfg(feature = \"alloc\")]\n\nextern crate alloc;\n\n\n\nmod aggregate_signature;\n\nmod aggregate_signature_vt;\n\nmod multi_public_key;\n\nmod multi_public_key_vt;\n\nmod multi_signature;\n\nmod multi_signature_vt;\n\nmod proof_of_possession;\n\nmod proof_of_possession_vt;\n\nmod public_key;\n\nmod public_key_vt;\n\nmod secret_key;\n", "file_path": "implementations/rust/ockam/signature_bls/src/lib.rs", "rank": 41, "score": 101726.69379897349 }, { "content": "#[cfg(test)]\n\nimpl rand_core::SeedableRng for MockRng {\n\n type Seed = [u8; 16];\n\n\n\n fn from_seed(seed: Self::Seed) -> Self {\n\n Self(rand_xorshift::XorShiftRng::from_seed(seed))\n\n }\n\n}\n\n\n\n#[cfg(test)]\n\nimpl rand_core::CryptoRng for MockRng {}\n\n\n\n#[cfg(test)]\n\nimpl rand_core::RngCore for MockRng {\n\n fn next_u32(&mut self) -> u32 {\n\n self.0.next_u32()\n\n }\n\n\n\n fn next_u64(&mut self) -> u64 {\n\n self.0.next_u64()\n", "file_path": "implementations/rust/ockam/signature_bls/src/lib.rs", "rank": 42, "score": 101726.22658875109 }, { "content": " fn from_seed(seed: Self::Seed) -> Self {\n\n Self(rand_xorshift::XorShiftRng::from_seed(seed))\n\n }\n\n}\n\n\n\n#[cfg(test)]\n\nimpl rand_core::CryptoRng for MockRng {}\n\n\n\n#[cfg(test)]\n\nimpl rand_core::RngCore for MockRng {\n\n fn next_u32(&mut self) -> u32 {\n\n self.0.next_u32()\n\n }\n\n\n\n fn next_u64(&mut self) -> u64 {\n\n self.0.next_u64()\n\n }\n\n\n\n fn fill_bytes(&mut self, dest: &mut [u8]) {\n\n self.0.fill_bytes(dest)\n\n }\n\n\n\n fn try_fill_bytes(&mut self, dest: &mut [u8]) -> Result<(), rand_core::Error> {\n\n self.0.try_fill_bytes(dest)\n\n }\n\n}\n", "file_path": "implementations/rust/ockam/signature_ps/src/lib.rs", "rank": 43, "score": 101725.47044693858 }, { "content": " }\n\n\n\n fn fill_bytes(&mut self, dest: &mut [u8]) {\n\n self.0.fill_bytes(dest)\n\n }\n\n\n\n fn try_fill_bytes(&mut self, dest: &mut [u8]) -> Result<(), rand_core::Error> {\n\n self.0.try_fill_bytes(dest)\n\n }\n\n}\n", "file_path": "implementations/rust/ockam/signature_bls/src/lib.rs", "rank": 44, "score": 101720.67648835162 }, { "content": "fn generate_secret_key(count: usize, mut rng: impl RngCore + CryptoRng) -> Option<SecretKey> {\n\n if count == 0 || count > 128 {\n\n return None;\n\n }\n\n let w = Scalar::random(&mut rng);\n\n let x = Scalar::random(&mut rng);\n\n let mut y = Vec::new();\n\n for _ in 0..count {\n\n if let Err(_) = y.push(Scalar::random(&mut rng)) {\n\n return None;\n\n }\n\n }\n\n\n\n Some(SecretKey { w, x, y })\n\n}\n", "file_path": "implementations/rust/ockam/signature_ps/src/secret_key.rs", "rank": 45, "score": 100623.0534290281 }, { "content": "#[cfg(test)]\n\npub struct MockRng(rand_xorshift::XorShiftRng);\n\n\n\n#[cfg(test)]\n\nimpl rand_core::SeedableRng for MockRng {\n\n type Seed = [u8; 16];\n\n\n\n fn from_seed(seed: Self::Seed) -> Self {\n\n Self(rand_xorshift::XorShiftRng::from_seed(seed))\n\n }\n\n}\n\n\n\n#[cfg(test)]\n\nimpl rand_core::CryptoRng for MockRng {}\n\n\n\n#[cfg(test)]\n\nimpl rand_core::RngCore for MockRng {\n\n fn next_u32(&mut self) -> u32 {\n\n self.0.next_u32()\n\n }\n", "file_path": "implementations/rust/ockam/signature_bbs_plus/src/util.rs", "rank": 46, "score": 100120.39124003495 }, { "content": "\n\n fn next_u64(&mut self) -> u64 {\n\n self.0.next_u64()\n\n }\n\n\n\n fn fill_bytes(&mut self, dest: &mut [u8]) {\n\n self.0.fill_bytes(dest)\n\n }\n\n\n\n fn try_fill_bytes(&mut self, dest: &mut [u8]) -> Result<(), rand_core::Error> {\n\n self.0.try_fill_bytes(dest)\n\n }\n\n}\n", "file_path": "implementations/rust/ockam/signature_bbs_plus/src/util.rs", "rank": 47, "score": 100111.20311466232 }, { "content": "mod blind_signature;\n\nmod blind_signature_context;\n\nmod issuer;\n\nmod message_generator;\n\nmod pok_signature;\n\nmod pok_signature_proof;\n\nmod prover;\n\nmod signature;\n\nmod verifier;\n\n\n\npub use blind_signature::*;\n\npub use blind_signature_context::*;\n\npub use issuer::*;\n\npub use message_generator::*;\n\npub use pok_signature::*;\n\npub use pok_signature_proof::*;\n\npub use prover::*;\n\npub use signature::*;\n\npub use signature_bls::{ProofOfPossession, PublicKey, SecretKey, Signature as BlsSignature};\n\n#[cfg(test)]\n\npub use util::MockRng;\n\npub use verifier::*;\n", "file_path": "implementations/rust/ockam/signature_bbs_plus/src/lib.rs", "rank": 48, "score": 99911.31578138885 }, { "content": "//!\n\n#![no_std]\n\n#![deny(\n\n missing_docs,\n\n trivial_casts,\n\n trivial_numeric_casts,\n\n unsafe_code,\n\n unused_import_braces,\n\n unused_qualifications,\n\n warnings\n\n)]\n\n\n\n#[macro_use]\n\nextern crate signature_core;\n\n\n\n/// The maximum number of messages that can be signed by this crate\n\npub const MAX_MSGS: usize = 128;\n\n\n\n#[macro_use]\n\nmod util;\n", "file_path": "implementations/rust/ockam/signature_bbs_plus/src/lib.rs", "rank": 49, "score": 99906.45844354336 }, { "content": "#[proc_macro_attribute]\n\npub fn node(_args: TokenStream, item: TokenStream) -> TokenStream {\n\n // Parse the item that #[ockam::node] is defined on.\n\n // Expect that this item is a function and fail if it isn't a function\n\n let mut input_function = parse_macro_input!(item as ItemFn);\n\n\n\n // Fail if the function is not declared async\n\n if input_function.sig.asyncness.is_none() {\n\n let message = \"a function with attribute '#[ockam::node]' must be declared as 'async'\";\n\n let token = input_function.sig.fn_token;\n\n return Error::new_spanned(token, message).to_compile_error().into();\n\n }\n\n\n\n // Fail if the function does not have exactly one argument\n\n if input_function.sig.inputs.len() != 1 {\n\n let message = \"a function with '#[ockam::node]' must have exactly one argument\";\n\n let token = input_function.sig.fn_token;\n\n return Error::new_spanned(token, message).to_compile_error().into();\n\n }\n\n\n\n // Verify that the type of the passed argument is Context\n", "file_path": "implementations/rust/ockam/ockam_node_attribute/src/lib.rs", "rank": 50, "score": 99147.92691018012 }, { "content": "pub fn on<S: ToString>(host: S, port: usize) -> String {\n\n format!(\"{}:{}\", host.to_string(), port)\n\n}\n\n\n", "file_path": "implementations/rust/ockam/ockam_examples/example_projects/credentials/src/lib.rs", "rank": 51, "score": 96928.27555472519 }, { "content": "pub fn issuer_on_or_default<S: ToString>(host: Option<S>) -> String {\n\n if let Some(host) = host {\n\n let host = host.to_string();\n\n if let Some(_) = host.find(\":\") {\n\n host.parse().unwrap()\n\n } else {\n\n on(host, DEFAULT_ISSUER_PORT)\n\n }\n\n } else {\n\n default_issuer_address()\n\n }\n\n}\n\n\n\nuse ockam::{CredentialAttributeSchema, CredentialAttributeType, CredentialSchema, SECRET_ID};\n\nuse rand::{Error, SeedableRng};\n\n\n", "file_path": "implementations/rust/ockam/ockam_examples/example_projects/credentials/src/lib.rs", "rank": 52, "score": 96664.18477523183 }, { "content": "#[proc_macro_attribute]\n\npub fn vault_test(_attr: TokenStream, item: TokenStream) -> TokenStream {\n\n let original_fn = parse_macro_input!(item as ItemFn);\n\n let original_fn_ident = original_fn.sig.ident;\n\n let import_test = TokenStream::from_str(\n\n format!(\n\n \"use ockam_vault_test_suite::{};\",\n\n original_fn_ident.to_string()\n\n )\n\n .as_str(),\n\n )\n\n .unwrap();\n\n let import_test: Stmt = syn::parse(import_test).expect(\"B\");\n\n let run_test =\n\n TokenStream::from_str(format!(\"{}(&mut vault);\", original_fn_ident.to_string()).as_str())\n\n .unwrap();\n\n let run_test: Stmt = syn::parse(run_test).expect(\"B\");\n\n\n\n let output_function = quote! {\n\n #[test]\n\n fn #original_fn_ident() {\n\n #import_test\n\n let mut vault = new_vault();\n\n #run_test\n\n }\n\n };\n\n\n\n TokenStream::from(output_function)\n\n}\n\n\n", "file_path": "implementations/rust/ockam/ockam_vault_test_attribute/src/lib.rs", "rank": 53, "score": 96627.93286050444 }, { "content": "#[proc_macro_attribute]\n\npub fn vault_test_sync(_attr: TokenStream, item: TokenStream) -> TokenStream {\n\n let original_fn = parse_macro_input!(item as ItemFn);\n\n let original_fn_ident = original_fn.sig.ident;\n\n let import_test = TokenStream::from_str(\n\n format!(\n\n \"use ockam_vault_test_suite::{};\",\n\n original_fn_ident.to_string()\n\n )\n\n .as_str(),\n\n )\n\n .unwrap();\n\n let import_test: Stmt = syn::parse(import_test).expect(\"B\");\n\n let run_test =\n\n TokenStream::from_str(format!(\"{}(&mut vault);\", original_fn_ident.to_string()).as_str())\n\n .unwrap();\n\n let run_test: Stmt = syn::parse(run_test).expect(\"B\");\n\n\n\n let output_function = quote! {\n\n #[test]\n\n fn #original_fn_ident() {\n", "file_path": "implementations/rust/ockam/ockam_vault_test_attribute/src/lib.rs", "rank": 54, "score": 95423.10559331634 }, { "content": "#[doc(hidden)]\n\npub fn block_future<'r, F>(rt: &'r Runtime, f: F) -> <F as Future>::Output\n\nwhere\n\n F: Future + Send,\n\n F::Output: Send,\n\n{\n\n task::block_in_place(move || {\n\n let local = task::LocalSet::new();\n\n local.block_on(&rt, f)\n\n })\n\n}\n", "file_path": "implementations/rust/ockam/ockam_node/src/lib.rs", "rank": 55, "score": 95403.92839999561 }, { "content": "#[allow(clippy::ptr_arg)]\n\npub fn write_byte_string<S>(v: &String, s: S) -> Result<S::Ok, S::Error>\n\nwhere\n\n S: Serializer,\n\n{\n\n s.serialize_str(v.as_str())\n\n}\n\n\n", "file_path": "implementations/rust/ockam/ockam/src/credential/util.rs", "rank": 56, "score": 93567.16554259954 }, { "content": "#[allow(clippy::ptr_arg)]\n\npub fn write_attributes<S>(v: &Vec<CredentialAttributeSchema>, s: S) -> Result<S::Ok, S::Error>\n\nwhere\n\n S: Serializer,\n\n{\n\n let l = if v.is_empty() { None } else { Some(v.len()) };\n\n\n\n let mut iter = s.serialize_seq(l)?;\n\n for i in v {\n\n iter.serialize_element(i)?;\n\n }\n\n iter.end()\n\n}\n\n\n", "file_path": "implementations/rust/ockam/ockam/src/credential/util.rs", "rank": 57, "score": 90541.0586441797 }, { "content": "struct Responder;\n\n\n\n#[async_trait::async_trait]\n\nimpl Worker for Responder {\n\n type Context = Context;\n\n type Message = String;\n\n\n\n async fn handle_message(&mut self, ctx: &mut Context, msg: Routed<String>) -> Result<()> {\n\n info!(\"Responder: {}\", msg);\n\n debug!(\"Replying back to {}\", &msg.return_route());\n\n ctx.send(msg.return_route(), msg.body()).await?;\n\n Ok(())\n\n }\n\n}\n\n\n", "file_path": "implementations/rust/ockam/ockam_transport_websocket/examples/server.rs", "rank": 58, "score": 81575.38451734144 }, { "content": "#[ockam::node]\n\nstruct A {}\n", "file_path": "implementations/rust/ockam/ockam/tests/node_attribute/fails_if_item_is_not_a_function.rs", "rank": 59, "score": 80716.24879363437 }, { "content": "#[derive(StructOpt)]\n\nstruct Args {\n\n #[structopt(long, short = \"i\")]\n\n issuer: Option<String>,\n\n}\n\n\n\n#[ockam::node]\n\nasync fn main(ctx: Context) -> Result<()> {\n\n let args: Args = Args::from_args();\n\n\n\n // Demo hack to get a reference from Holder to Verifier\n\n let verifier = format!(\"127.0.0.1:{}\", DEFAULT_VERIFIER_PORT);\n\n let issuer = issuer_on_or_default(args.issuer);\n\n\n\n let rng = CredentialRng::from_entropy();\n\n let holder = CredentialHolder::new(rng);\n\n\n\n ctx.start_worker(\n\n \"holder\",\n\n Holder {\n\n holder,\n", "file_path": "implementations/rust/ockam/ockam_examples/example_projects/credentials/src/holder.rs", "rank": 60, "score": 79892.04889530946 }, { "content": "#[derive(StructOpt)]\n\nstruct Args {\n\n #[structopt(long, short = \"i\")]\n\n issuer: Option<String>,\n\n\n\n #[structopt(long, short)]\n\n port: Option<usize>,\n\n}\n\n\n\n#[ockam::node]\n\nasync fn main(ctx: Context) -> Result<()> {\n\n let args: Args = Args::from_args();\n\n let port = args.port.unwrap_or(DEFAULT_VERIFIER_PORT);\n\n\n\n let local_tcp = format!(\"0.0.0.0:{}\", port);\n\n\n\n let issuer = issuer_on_or_default(args.issuer);\n\n\n\n let tcp = TcpTransport::create(&ctx).await?;\n\n tcp.listen(local_tcp).await?;\n\n tcp.connect(&issuer).await?;\n", "file_path": "implementations/rust/ockam/ockam_examples/example_projects/credentials/src/verifier.rs", "rank": 61, "score": 79892.04889530946 }, { "content": "#[derive(StructOpt)]\n\nstruct Args {\n\n #[structopt(long, short = \"k\")]\n\n signing_key: Option<String>,\n\n\n\n #[structopt(long, short)]\n\n port: Option<usize>,\n\n}\n\n\n\n#[ockam::node]\n\nasync fn main(ctx: Context) -> Result<()> {\n\n let args: Args = Args::from_args();\n\n let port = args.port.unwrap_or(DEFAULT_ISSUER_PORT);\n\n\n\n let tcp = TcpTransport::create(&ctx).await?;\n\n tcp.listen(format!(\"0.0.0.0:{}\", port)).await?;\n\n\n\n let credential_issuer = if let Some(signing_key) = args.signing_key {\n\n CredentialIssuer::with_signing_key_hex(signing_key).unwrap()\n\n } else {\n\n let rng = rand::thread_rng();\n", "file_path": "implementations/rust/ockam/ockam_examples/example_projects/credentials/src/issuer.rs", "rank": 62, "score": 79892.04889530946 }, { "content": "struct Holder {\n\n holder: CredentialHolder,\n\n issuer: String,\n\n verifier: String,\n\n issuer_pubkey: Option<PublicKeyBytes>,\n\n frag1: Option<CredentialFragment1>,\n\n credential: Option<Credential>,\n\n offer_id: Option<OfferIdBytes>,\n\n}\n\n\n\n#[ockam::worker]\n\nimpl Worker for Holder {\n\n type Message = CredentialMessage;\n\n type Context = Context;\n\n\n\n async fn initialize(&mut self, ctx: &mut Self::Context) -> Result<()> {\n\n let issuer = &self.issuer;\n\n let verifier = &self.verifier;\n\n\n\n let tcp = TcpTransport::create(&ctx).await?;\n", "file_path": "implementations/rust/ockam/ockam_examples/example_projects/credentials/src/holder.rs", "rank": 63, "score": 79886.4773824932 }, { "content": "struct Verifier {\n\n issuer: String,\n\n issuer_pubkey: Option<PublicKeyBytes>,\n\n}\n\n\n\n#[ockam::worker]\n\nimpl Worker for Verifier {\n\n type Message = CredentialMessage;\n\n type Context = Context;\n\n\n\n async fn initialize(&mut self, ctx: &mut Self::Context) -> Result<()> {\n\n let issuer = &self.issuer;\n\n\n\n println!(\"Verifier starting. Discovering Issuer\");\n\n\n\n // Send a New Credential Connection message\n\n ctx.send(\n\n Route::new().append_t(TCP, issuer).append(\"issuer\"),\n\n CredentialMessage::CredentialConnection,\n\n )\n", "file_path": "implementations/rust/ockam/ockam_examples/example_projects/credentials/src/verifier.rs", "rank": 64, "score": 79886.4773824932 }, { "content": "#[derive(Debug, Clone)]\n\nstruct Service {\n\n schema: CredentialSchema,\n\n bundle: EstablishmentBundle,\n\n}\n\n\n", "file_path": "implementations/rust/ockam/ockam_examples/example_projects/okta/truck/src/main.rs", "rank": 65, "score": 79090.00678488414 }, { "content": "struct Button {\n\n pin: Pin<Input<PullUp>>,\n\n // not right, not pretty\n\n gpiote: hal::gpiote::Gpiote,\n\n}\n\n\n\nimpl Button {\n\n fn new(gpiote: hal::gpiote::Gpiote, button: Pin<Input<PullUp>>) -> Self {\n\n Self {\n\n pin: button,\n\n gpiote,\n\n }\n\n }\n\n\n\n #[allow(unused)]\n\n fn enable_interrupt(&self) {\n\n self.gpiote\n\n .channel0()\n\n .input_pin(&self.pin)\n\n .hi_to_lo()\n", "file_path": "implementations/rust/ockam/ockam_examples/WIP/IOT/ARM/nRF52840/src/main.rs", "rank": 66, "score": 79084.59011933411 }, { "content": "struct MyWorker;\n\n\n\n#[ockam::worker]\n\nimpl Worker for MyWorker {\n\n type Context = Context;\n\n type Message = Any;\n\n\n\n async fn handle_message(&mut self, ctx: &mut Context, msg: Routed<Any>) -> Result<()> {\n\n println!(\"TransportMessage onward: {:?}\", msg.onward_route());\n\n println!(\"TransportMessage return: {:?}\", msg.return_route());\n\n println!(\"TransportMessage payload: {:?}\", msg.payload());\n\n\n\n ctx.stop().await\n\n }\n\n}\n\n\n\n#[ockam::node]\n\nasync fn main(ctx: Context) -> Result<()> {\n\n ctx.start_worker(\"worker.middleware\", MyWorker).await?;\n\n\n\n ctx.send(\"worker.middleware\", \"Hello World!\".to_string())\n\n .await?;\n\n\n\n Ok(())\n\n}\n", "file_path": "implementations/rust/ockam/ockam_examples/example_projects/worker/examples/worker_no_peeling.rs", "rank": 67, "score": 79084.59011933411 }, { "content": "struct Led {\n\n inner: Pin<Output<PushPull>>,\n\n}\n\n\n\nimpl Led {\n\n fn new(pin: Pin<Output<PushPull>>) -> Self {\n\n Self { inner: pin }\n\n }\n\n fn on(&mut self) {\n\n let _ = self.inner.set_low();\n\n }\n\n fn off(&mut self) {\n\n let _ = self.inner.set_high();\n\n }\n\n fn is_on(&self) -> bool {\n\n self.inner.is_set_low().unwrap_or_default()\n\n }\n\n fn toggle(&mut self) {\n\n if self.is_on() {\n\n self.off()\n\n } else {\n\n self.on()\n\n }\n\n }\n\n}\n\n\n", "file_path": "implementations/rust/ockam/ockam_examples/WIP/IOT/ARM/nRF52840/src/main.rs", "rank": 68, "score": 79084.59011933411 }, { "content": "#[derive(Default)]\n\nstruct MyWorker {\n\n parser: ProtocolParser<MyWorker>,\n\n stream: Option<String>,\n\n}\n\n\n", "file_path": "implementations/rust/ockam/ockam_examples/example_projects/worker/examples/worker_protocols.rs", "rank": 69, "score": 79084.59011933411 }, { "content": "struct Board {\n\n led1: Led,\n\n led2: Led,\n\n led3: Led,\n\n led4: Led,\n\n button1: Button,\n\n temp: hal::Temp,\n\n rtc: Rtc<RTC0>,\n\n}\n\n\n\nimpl Board {\n\n fn init() -> Self {\n\n rtt_init_print!(BlockIfFull, 16384);\n\n\n\n if log::max_level() == LevelFilter::Off {\n\n log::set_max_level(LevelFilter::Info)\n\n }\n\n log::set_logger(&rttlogger::RttLogger).unwrap();\n\n\n\n setup_heap();\n", "file_path": "implementations/rust/ockam/ockam_examples/WIP/IOT/ARM/nRF52840/src/main.rs", "rank": 70, "score": 79084.59011933411 }, { "content": "struct Nothing;\n\n\n\n#[ockam::worker]\n\nimpl Worker for Nothing {\n\n type Message = ();\n\n type Context = Context;\n\n\n\n async fn initialize(&mut self, _context: &mut Self::Context) -> Result<()> {\n\n println!(\"Worker that does nothing is starting\");\n\n Ok(())\n\n }\n\n}\n\n\n", "file_path": "implementations/rust/ockam/ockam_examples/example_projects/worker/examples/worker_initialize.rs", "rank": 71, "score": 79084.59011933411 }, { "content": "struct Square;\n\n\n", "file_path": "implementations/rust/ockam/ockam_examples/example_projects/worker/examples/worker_get_reply.rs", "rank": 72, "score": 78309.20467640771 }, { "content": "struct Printer;\n\n\n\n// Types that are Serialize + Deserialize are automatically Message\n", "file_path": "implementations/rust/ockam/ockam_examples/example_projects/worker/examples/worker_send_message.rs", "rank": 73, "score": 78309.20467640771 }, { "content": "struct Echo;\n\n\n\n#[ockam::worker]\n\nimpl Worker for Echo {\n\n type Message = Message;\n\n type Context = Context;\n\n\n\n async fn handle_message(&mut self, ctx: &mut Context, _: Routed<Message>) -> Result<()> {\n\n println!(\"[ECHO]: Received message: sending one Bad, then one Good\");\n\n ctx.send(\"io.ockam.picky\", Message::Bad).await?;\n\n ctx.send(\"io.ockam.picky\", Message::Good).await?;\n\n Ok(())\n\n }\n\n}\n\n\n\n#[ockam::node]\n\nasync fn main(app: Context) -> Result<()> {\n\n app.start_worker(\"io.ockam.picky\", Picky).await?;\n\n app.start_worker(\"io.ockam.echo\", Echo).await?;\n\n\n\n app.send(\"io.ockam.picky\", Message::Good).await?;\n\n\n\n Ok(())\n\n}\n", "file_path": "implementations/rust/ockam/ockam_examples/example_projects/worker/examples/worker_cancel_reply.rs", "rank": 74, "score": 78309.20467640771 }, { "content": "struct Responder;\n\n\n\n#[ockam::worker]\n\nimpl Worker for Responder {\n\n type Context = Context;\n\n type Message = String;\n\n\n\n async fn handle_message(&mut self, ctx: &mut Context, msg: Routed<String>) -> Result<()> {\n\n info!(\"Responder: {}\", msg);\n\n ctx.send(msg.return_route(), msg.body()).await?;\n\n Ok(())\n\n }\n\n}\n\n\n", "file_path": "implementations/rust/ockam/ockam_examples/example_projects/tcp/examples/network_echo_server.rs", "rank": 75, "score": 78309.20467640771 }, { "content": "struct OneHertz;\n\n\n\nimpl OneHertz {\n\n /// Flag can hold the _token of button toggle_\n\n /// which can be consumed by exactly one entity.\n\n fn notify_flag() -> &'static Flag {\n\n static FLAG: Flag = Flag::new();\n\n &FLAG\n\n }\n\n\n\n /// Create a new `button press future`.\n\n pub fn new() -> Self {\n\n Self\n\n }\n\n}\n\n\n\nimpl Future for OneHertz {\n\n type Output = ();\n\n fn poll(self: core::pin::Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Self::Output> {\n\n if Self::notify_flag().check(cx.waker()) {\n\n Poll::Ready(())\n\n } else {\n\n Poll::Pending\n\n }\n\n }\n\n}\n\n\n", "file_path": "implementations/rust/ockam/ockam_examples/WIP/IOT/ARM/nRF52840/src/main.rs", "rank": 76, "score": 78309.20467640771 }, { "content": "struct StatefulWorker {\n\n inner: usize,\n\n}\n\n\n", "file_path": "implementations/rust/ockam/ockam_examples/example_projects/worker/examples/worker_stateful.rs", "rank": 77, "score": 78309.20467640771 }, { "content": "struct Echo;\n\n\n", "file_path": "implementations/rust/ockam/ockam_examples/example_projects/worker/examples/worker_receive_match.rs", "rank": 78, "score": 78309.20467640771 }, { "content": "/// Not re-entrant, only one instance at a time will be triggered\n\n// since the first one consumes the shared flag\n\nstruct ButtonPress;\n\n\n\nimpl ButtonPress {\n\n /// Flag can hold the _token of button toggle_\n\n /// which can be consumed by exactly one entity.\n\n fn notify_flag() -> &'static Flag {\n\n static FLAG: Flag = Flag::new();\n\n &FLAG\n\n }\n\n /// Create a new `button press future`.\n\n pub fn new() -> Self {\n\n Self\n\n }\n\n}\n\n\n\nimpl Future for ButtonPress {\n\n type Output = ();\n\n fn poll(self: core::pin::Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Self::Output> {\n\n if Self::notify_flag().check(cx.waker()) {\n\n Poll::Ready(())\n\n } else {\n\n Poll::Pending\n\n }\n\n }\n\n}\n", "file_path": "implementations/rust/ockam/ockam_examples/WIP/IOT/ARM/nRF52840/src/main.rs", "rank": 79, "score": 78309.20467640771 }, { "content": "/// This worker requests more data and is very picky about what data it accepts.\n\nstruct Picky;\n\n\n\n#[ockam::worker]\n\nimpl Worker for Picky {\n\n type Message = Message;\n\n type Context = Context;\n\n\n\n async fn handle_message(&mut self, ctx: &mut Context, msg: Routed<Message>) -> Result<()> {\n\n match *msg {\n\n Message::Good => {\n\n println!(\"[PICKY]: I got a good message! I want another one\");\n\n ctx.send(\"io.ockam.echo\", Message::Good).await?;\n\n\n\n loop {\n\n let msg = ctx.receive::<Message>().await.unwrap();\n\n if msg == Message::Bad {\n\n println!(\"[PICKY]: Ignoring bad message\");\n\n msg.cancel().await;\n\n } else {\n\n println!(\"[PICKY]: Yay, another good message!\");\n", "file_path": "implementations/rust/ockam/ockam_examples/example_projects/worker/examples/worker_cancel_reply.rs", "rank": 80, "score": 78309.20467640771 }, { "content": "struct MyRouter;\n\n\n\n#[ockam::worker]\n\nimpl Worker for MyRouter {\n\n type Context = Context;\n\n type Message = Any;\n\n\n\n /// This handle function takes any incoming message and forwards\n\n /// it to the next hop in the route\n\n async fn handle_message(&mut self, ctx: &mut Context, msg: Routed<Any>) -> Result<()> {\n\n println!(\"Received: {}\", msg);\n\n let mut msg = msg.into_transport_message();\n\n msg.onward_route.step()?;\n\n msg.return_route.modify().prepend(ctx.address());\n\n ctx.forward(msg).await\n\n }\n\n}\n\n\n", "file_path": "implementations/rust/ockam/ockam_examples/example_projects/worker/examples/worker_local_routing.rs", "rank": 81, "score": 78309.20467640771 }, { "content": "#[derive(Default)]\n\nstruct MyWorker {\n\n parser: ProtocolParser<MyWorker>,\n\n stream: Option<String>,\n\n peer: String,\n\n}\n\n\n\nimpl MyWorker {\n\n fn new(peer: String) -> Self {\n\n Self {\n\n peer,\n\n ..Default::default()\n\n }\n\n }\n\n}\n\n\n", "file_path": "implementations/rust/ockam/ockam_examples/example_projects/tcp/examples/hub_stream_protocol.rs", "rank": 82, "score": 78309.20467640771 }, { "content": "struct Echo;\n\n\n\n#[ockam::worker]\n\nimpl Worker for Echo {\n\n type Context = Context;\n\n type Message = String;\n\n\n\n async fn handle_message(&mut self, ctx: &mut Context, msg: Routed<String>) -> Result<()> {\n\n println!(\"Received: '{}'\", msg);\n\n ctx.send(msg.return_route(), msg.body()).await\n\n }\n\n}\n\n\n\n#[ockam::node]\n\nasync fn main(mut ctx: Context) -> Result<()> {\n\n ctx.start_worker(\"router\", MyRouter).await?;\n\n ctx.start_worker(\"client\", Echo).await?;\n\n\n\n ctx.send(\n\n Route::new().append(\"router\").append(\"client\"),\n", "file_path": "implementations/rust/ockam/ockam_examples/example_projects/worker/examples/worker_local_routing.rs", "rank": 83, "score": 78309.20467640771 }, { "content": "#[derive(Debug)]\n\nstruct StateData {\n\n id: usize,\n\n state: [u8; 16],\n\n stream: TcpStream,\n\n}\n\n\n\n// /// Groups to check against\n\n// /// Enroller => 00g26qjjaQlo67l4s5d6\n\n// const OKTA_GROUPS: [&str; 1] = [\"00g26qjjaQlo67l4s5d6\"];\n\n\n", "file_path": "implementations/rust/ockam/ockam_examples/example_projects/okta/management_service/src/main.rs", "rank": 84, "score": 77559.02861060677 }, { "content": "#[derive(Default)]\n\nstruct Router {\n\n routes: BTreeMap<Address, Address>,\n\n}\n\n\n\n#[ockam::worker]\n\nimpl Worker for Router {\n\n // Routers must handle `RouterMessage` provided by ockam_core, to\n\n // create a consistent interface across all router implementations\n\n type Message = RouterMessage;\n\n type Context = Context;\n\n\n\n async fn initialize(&mut self, _: &mut Context) -> Result<()> {\n\n info!(\"Starting router...\");\n\n Ok(())\n\n }\n\n\n\n async fn handle_message(\n\n &mut self,\n\n ctx: &mut Context,\n\n msg: Routed<RouterMessage>,\n", "file_path": "implementations/rust/ockam/ockam_examples/example_projects/worker/examples/WIP/worker_simple_router.rs", "rank": 85, "score": 77559.02861060677 }, { "content": "#[derive(Debug)]\n\nstruct OktaData {\n\n state: BTreeMap<[u8; 16], StateData>,\n\n ids: BTreeMap<usize, [u8; 16]>,\n\n redirect_uri: String\n\n}\n\n\n\nimpl Default for OktaData {\n\n fn default() -> Self {\n\n Self {\n\n state: BTreeMap::new(),\n\n ids : BTreeMap::new(),\n\n redirect_uri: String::new()\n\n }\n\n }\n\n}\n\n\n", "file_path": "implementations/rust/ockam/ockam_examples/example_projects/okta/management_service/src/main.rs", "rank": 86, "score": 77559.02861060677 }, { "content": "struct RingWorker {\n\n ctr: usize,\n\n next: Option<Address>,\n\n}\n\n\n\n#[ockam::worker]\n\nimpl Worker for RingWorker {\n\n type Context = Context;\n\n type Message = RingMessage;\n\n\n\n async fn handle_message(\n\n &mut self,\n\n context: &mut Self::Context,\n\n msg: Routed<Self::Message>,\n\n ) -> Result<()> {\n\n self.ctr += 1;\n\n if self.ctr <= 1024 {\n\n context\n\n .send(self.next.as_ref().unwrap().clone(), msg.body())\n\n .await?;\n", "file_path": "implementations/rust/ockam/ockam_examples/example_projects/worker/examples/worker_ring_benchmark.rs", "rank": 87, "score": 77559.02861060677 }, { "content": "struct Player {\n\n friend: Option<Address>,\n\n count: u8,\n\n}\n\n\n\nimpl Player {\n\n fn new() -> Self {\n\n Self {\n\n friend: None,\n\n count: 0,\n\n }\n\n }\n\n\n\n fn friend(&self) -> Address {\n\n self.friend.clone().unwrap()\n\n }\n\n}\n\n\n", "file_path": "implementations/rust/ockam/ockam_examples/example_projects/node/examples/create_ping_pong_node.rs", "rank": 88, "score": 77559.02861060677 }, { "content": "/// A connoisseur of strings\n\nstruct Consumer;\n\n\n\n#[ockam::worker]\n\nimpl Worker for Consumer {\n\n type Message = String;\n\n type Context = Context;\n\n\n\n async fn initialize(&mut self, ctx: &mut Context) -> Result<()> {\n\n info!(\"Starting consumer '{}'...\", ctx.address());\n\n\n\n // Register this consumer with the router by its accept scope\n\n // (which is used in a look-up table in the router to forward\n\n // messages), as well as its own address.\n\n //\n\n // The accept scope is address type `10`, with a prefix and\n\n // its own address. Messages sent to this address will be\n\n // sent to the 10-type router, which will then forward them.\n\n ctx.send(\n\n \"simple.router\",\n\n RouterMessage::Register {\n", "file_path": "implementations/rust/ockam/ockam_examples/example_projects/worker/examples/WIP/worker_simple_router.rs", "rank": 89, "score": 77559.02861060677 }, { "content": "/// A worker who isn't always available. It registers itself with the\n\n/// hub forwarding service to never miss a message.\n\nstruct ProxiedWorker {\n\n /// The hub's address\n\n peer: String,\n\n}\n\n\n\n#[ockam::worker]\n\nimpl Worker for ProxiedWorker {\n\n type Context = Context;\n\n type Message = String;\n\n\n\n async fn initialize(&mut self, ctx: &mut Context) -> Result<()> {\n\n // Register this service with the hub's forwarding service\n\n ctx.send(\n\n Route::new()\n\n .append_t(TCP, &self.peer)\n\n .append(\"forwarding_service\"),\n\n String::from(\"register\"),\n\n )\n\n .await\n\n }\n", "file_path": "implementations/rust/ockam/ockam_examples/example_projects/tcp/examples/relay_echo_server.rs", "rank": 90, "score": 77559.02861060677 }, { "content": "#[derive(Debug, Deserialize)]\n\nstruct OktaIntrospectResponse {\n\n active: bool,\n\n aud: Option<String>,\n\n client_id: Option<String>,\n\n device_id: Option<String>,\n\n exp: Option<usize>,\n\n iat: Option<usize>,\n\n iss: Option<String>,\n\n jti: Option<String>,\n\n nbf: Option<usize>,\n\n scope: Option<String>,\n\n sub: Option<String>,\n\n token_type: Option<String>,\n\n uid: Option<String>,\n\n username: Option<String>\n\n}\n\n\n\nimpl OktaIntrospectResponse {\n\n //pub fn id(&self) -> String {\n\n // self.uid.clone().unwrap_or(String::new())\n", "file_path": "implementations/rust/ockam/ockam_examples/example_projects/okta/management_service/src/main.rs", "rank": 91, "score": 76838.34651450359 }, { "content": "#[derive(Debug, Deserialize)]\n\nstruct OktaTokenResponse {\n\n access_token: String,\n\n token_type: String,\n\n expires_in: usize,\n\n scope: String,\n\n refresh_token: Option<String>,\n\n id_token: String\n\n}\n\n\n", "file_path": "implementations/rust/ockam/ockam_examples/example_projects/okta/management_service/src/main.rs", "rank": 92, "score": 76838.34651450359 }, { "content": "struct MultiAddressWorker;\n\n\n\n#[ockam::worker]\n\nimpl Worker for MultiAddressWorker {\n\n type Message = String;\n\n type Context = Context;\n\n\n\n async fn initialize(&mut self, ctx: &mut Self::Context) -> Result<()> {\n\n println!(\"Worker main address: '{}'\", ctx.address());\n\n Ok(())\n\n }\n\n\n\n async fn handle_message(&mut self, ctx: &mut Context, msg: Routed<String>) -> Result<()> {\n\n println!(\"Addr '{}' received: '{}'\", ctx.address(), msg);\n\n Ok(())\n\n }\n\n}\n\n\n\n#[ockam::node]\n\nasync fn main(mut ctx: Context) -> Result<()> {\n", "file_path": "implementations/rust/ockam/ockam_examples/example_projects/worker/examples/worker_multi_address.rs", "rank": 93, "score": 76832.85217449353 }, { "content": "#[derive(Debug, Deserialize)]\n\nstruct OktaOpenIdResponse {\n\n code: String,\n\n state: String\n\n}\n\n\n\nimpl Default for OktaOpenIdResponse {\n\n fn default() -> Self {\n\n Self { code: String::new(), state: String::new() }\n\n }\n\n}\n\n\n", "file_path": "implementations/rust/ockam/ockam_examples/example_projects/okta/management_service/src/main.rs", "rank": 94, "score": 76135.03614644261 }, { "content": "/// Profile identity.\n\npub trait ProfileIdentity {\n\n /// Return unique [`Profile`] identifier, which is equal to sha256 of the root public key\n\n fn identifier(&self) -> Result<ProfileIdentifier>;\n\n}\n\n\n", "file_path": "implementations/rust/ockam/ockam_entity/src/traits.rs", "rank": 95, "score": 74964.14205717367 }, { "content": "/// Profile authentication support.\n\npub trait ProfileAuth {\n\n /// Generate an authentication proof based on the given channel_state\n\n fn generate_authentication_proof(&mut self, channel_state: &[u8]) -> Result<Vec<u8>>;\n\n\n\n /// Verify an authentication proof based on the given channel state, proof and profile.\n\n fn verify_authentication_proof(\n\n &mut self,\n\n channel_state: &[u8],\n\n responder_contact_id: &ProfileIdentifier,\n\n proof: &[u8],\n\n ) -> Result<bool>;\n\n}\n\n\n", "file_path": "implementations/rust/ockam/ockam_entity/src/traits.rs", "rank": 96, "score": 74964.14205717367 }, { "content": "/// Profile secret management.\n\npub trait ProfileSecrets {\n\n /// Create new key. Key is uniquely identified by label in [`KeyAttributes`]\n\n fn create_key(\n\n &mut self,\n\n key_attributes: KeyAttributes,\n\n attributes: Option<ProfileEventAttributes>,\n\n ) -> Result<()>;\n\n\n\n /// Rotate existing key. Key is uniquely identified by label in [`KeyAttributes`]\n\n fn rotate_key(\n\n &mut self,\n\n key_attributes: KeyAttributes,\n\n attributes: Option<ProfileEventAttributes>,\n\n ) -> Result<()>;\n\n\n\n /// Get [`Secret`] key. Key is uniquely identified by label in [`KeyAttributes`]\n\n fn get_secret_key(&mut self, key_attributes: &KeyAttributes) -> Result<Secret>;\n\n\n\n /// Get [`PublicKey`]. Key is uniquely identified by label in [`KeyAttributes`]\n\n fn get_public_key(&self, key_attributes: &KeyAttributes) -> Result<PublicKey>;\n\n\n\n /// Get the root [`Secret`]\n\n fn get_root_secret(&mut self) -> Result<Secret>;\n\n}\n\n\n\n/// A trait that represents the two endpoints of a secure channel.\n", "file_path": "implementations/rust/ockam/ockam_entity/src/traits.rs", "rank": 97, "score": 74964.14205717367 }, { "content": "/// Profile contact management.\n\npub trait ProfileContacts {\n\n /// Return all known to this profile [`Contact`]s\n\n fn contacts(&self) -> Result<ContactsDb>;\n\n /// Convert [`Profile`] to [`Contact`]\n\n fn to_contact(&self) -> Result<Contact>;\n\n /// Serialize [`Profile`] to [`Contact`] in binary form for storing/transferring over the network\n\n fn serialize_to_contact(&self) -> Result<Vec<u8>>;\n\n /// Return [`Contact`] with given [`ProfileIdentifier`]\n\n fn get_contact(&self, id: &ProfileIdentifier) -> Result<Option<Contact>>;\n\n /// Verify cryptographically whole event chain. Also verify sequence correctness\n\n fn verify_contact(&mut self, contact: &Contact) -> Result<bool>;\n\n /// Verify and add new [`Contact`] to [`Profile`]'s Contact list\n\n fn verify_and_add_contact(&mut self, contact: Contact) -> Result<bool>;\n\n /// Verify and update known [`Contact`] with new [`ProfileChangeEvent`]s\n\n fn verify_and_update_contact(\n\n &mut self,\n\n profile_id: &ProfileIdentifier,\n\n change_events: Vec<ProfileChangeEvent>,\n\n ) -> Result<bool>;\n\n}\n\n\n", "file_path": "implementations/rust/ockam/ockam_entity/src/traits.rs", "rank": 98, "score": 74964.14205717367 }, { "content": "/// Profile verified change history.\n\npub trait ProfileChanges {\n\n /// Return change history chain\n\n fn change_events(&self) -> Result<Vec<ProfileChangeEvent>>;\n\n /// Add a change event.\n\n fn update_no_verification(&mut self, change_event: ProfileChangeEvent) -> Result<()>;\n\n /// Verify the whole change event chain\n\n fn verify(&mut self) -> Result<bool>;\n\n}\n\n\n", "file_path": "implementations/rust/ockam/ockam_entity/src/traits.rs", "rank": 99, "score": 74964.14205717367 } ]
Rust
crates/history/src/browser.rs
kolloch/gloo
07e7dfa9c67d74c871f82fca54a1d7b5a0b9fce7
use std::any::Any; use std::borrow::Cow; use std::cell::RefCell; use std::fmt; use std::rc::Rc; use gloo_events::EventListener; use gloo_utils::window; #[cfg(feature = "query")] use serde::Serialize; use wasm_bindgen::{JsValue, UnwrapThrowExt}; use web_sys::Url; #[cfg(feature = "query")] use crate::error::HistoryResult; use crate::history::History; use crate::listener::HistoryListener; use crate::location::Location; use crate::state::{HistoryState, StateMap}; use crate::utils::WeakCallback; #[derive(Clone)] pub struct BrowserHistory { inner: web_sys::History, states: Rc<RefCell<StateMap>>, callbacks: Rc<RefCell<Vec<WeakCallback>>>, } impl fmt::Debug for BrowserHistory { fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { f.debug_struct("BrowserHistory").finish() } } impl PartialEq for BrowserHistory { fn eq(&self, _rhs: &Self) -> bool { true } } impl History for BrowserHistory { fn len(&self) -> usize { self.inner.length().expect_throw("failed to get length.") as usize } fn go(&self, delta: isize) { self.inner .go_with_delta(delta as i32) .expect_throw("failed to call go.") } fn push<'a>(&self, route: impl Into<Cow<'a, str>>) { let url = route.into(); self.inner .push_state_with_url(&Self::create_history_state().1, "", Some(&url)) .expect_throw("failed to push state."); self.notify_callbacks(); } fn replace<'a>(&self, route: impl Into<Cow<'a, str>>) { let url = route.into(); self.inner .replace_state_with_url(&Self::create_history_state().1, "", Some(&url)) .expect_throw("failed to replace history."); self.notify_callbacks(); } fn push_with_state<'a, T>(&self, route: impl Into<Cow<'a, str>>, state: T) where T: 'static, { let url = route.into(); let (id, history_state) = Self::create_history_state(); let mut states = self.states.borrow_mut(); states.insert(id, Rc::new(state) as Rc<dyn Any>); self.inner .push_state_with_url(&history_state, "", Some(&url)) .expect_throw("failed to push state."); self.notify_callbacks(); } fn replace_with_state<'a, T>(&self, route: impl Into<Cow<'a, str>>, state: T) where T: 'static, { let url = route.into(); let (id, history_state) = Self::create_history_state(); let mut states = self.states.borrow_mut(); states.insert(id, Rc::new(state) as Rc<dyn Any>); self.inner .replace_state_with_url(&history_state, "", Some(&url)) .expect_throw("failed to replace state."); self.notify_callbacks(); } #[cfg(feature = "query")] fn push_with_query<'a, Q>(&self, route: impl Into<Cow<'a, str>>, query: Q) -> HistoryResult<()> where Q: Serialize, { let route = route.into(); let query = serde_urlencoded::to_string(query)?; let url = Self::combine_url(&route, &query); self.inner .push_state_with_url(&Self::create_history_state().1, "", Some(&url)) .expect_throw("failed to push history."); self.notify_callbacks(); Ok(()) } #[cfg(feature = "query")] fn replace_with_query<'a, Q>( &self, route: impl Into<Cow<'a, str>>, query: Q, ) -> HistoryResult<()> where Q: Serialize, { let route = route.into(); let query = serde_urlencoded::to_string(query)?; let url = Self::combine_url(&route, &query); self.inner .replace_state_with_url(&Self::create_history_state().1, "", Some(&url)) .expect_throw("failed to replace history."); self.notify_callbacks(); Ok(()) } #[cfg(all(feature = "query"))] fn push_with_query_and_state<'a, Q, T>( &self, route: impl Into<Cow<'a, str>>, query: Q, state: T, ) -> HistoryResult<()> where Q: Serialize, T: 'static, { let (id, history_state) = Self::create_history_state(); let mut states = self.states.borrow_mut(); states.insert(id, Rc::new(state) as Rc<dyn Any>); let route = route.into(); let query = serde_urlencoded::to_string(query)?; let url = Self::combine_url(&route, &query); self.inner .push_state_with_url(&history_state, "", Some(&url)) .expect_throw("failed to push history."); self.notify_callbacks(); Ok(()) } #[cfg(all(feature = "query"))] fn replace_with_query_and_state<'a, Q, T>( &self, route: impl Into<Cow<'a, str>>, query: Q, state: T, ) -> HistoryResult<()> where Q: Serialize, T: 'static, { let (id, history_state) = Self::create_history_state(); let mut states = self.states.borrow_mut(); states.insert(id, Rc::new(state) as Rc<dyn Any>); let route = route.into(); let query = serde_urlencoded::to_string(query)?; let url = Self::combine_url(&route, &query); self.inner .replace_state_with_url(&history_state, "", Some(&url)) .expect_throw("failed to replace history."); self.notify_callbacks(); Ok(()) } fn listen<CB>(&self, callback: CB) -> HistoryListener where CB: Fn() + 'static, { let cb = Rc::new(callback) as Rc<dyn Fn()>; self.callbacks.borrow_mut().push(Rc::downgrade(&cb)); HistoryListener { _listener: cb } } fn location(&self) -> Location { let loc = window().location(); let history_state = self.inner.state().expect_throw("failed to get state"); let history_state = serde_wasm_bindgen::from_value::<HistoryState>(history_state).ok(); let id = history_state.map(|m| m.id()); let states = self.states.borrow(); Location { path: loc.pathname().expect_throw("failed to get pathname").into(), query_str: loc .search() .expect_throw("failed to get location query.") .into(), hash: loc .hash() .expect_throw("failed to get location hash.") .into(), state: id.and_then(|m| states.get(&m).cloned()), id, } } } impl Default for BrowserHistory { fn default() -> Self { thread_local! { static BROWSER_HISTORY: RefCell<Option<BrowserHistory>> = RefCell::default(); static LISTENER: RefCell<Option<EventListener>> = RefCell::default(); } BROWSER_HISTORY.with(|m| { let mut m = m.borrow_mut(); match *m { Some(ref m) => m.clone(), None => { let window = window(); let inner = window .history() .expect_throw("Failed to create browser history. Are you using a browser?"); let callbacks = Rc::default(); let history = Self { inner, callbacks, states: Rc::default(), }; { let history = history.clone(); LISTENER.with(move |m| { let mut listener = m.borrow_mut(); *listener = Some(EventListener::new(&window, "popstate", move |_| { history.notify_callbacks(); })); }); } *m = Some(history.clone()); history } } }) } } impl BrowserHistory { pub fn new() -> Self { Self::default() } fn notify_callbacks(&self) { crate::utils::notify_callbacks(self.callbacks.clone()); } fn create_history_state() -> (u32, JsValue) { let history_state = HistoryState::new(); ( history_state.id(), serde_wasm_bindgen::to_value(&history_state) .expect_throw("fails to create history state."), ) } pub(crate) fn combine_url(route: &str, query: &str) -> String { let href = window() .location() .href() .expect_throw("Failed to read location href"); let url = Url::new_with_base(route, &href).expect_throw("current url is not valid."); url.set_search(query); url.href() } }
use std::any::Any; use std::borrow::Cow; use std::cell::RefCell; use std::fmt; use std::rc::Rc; use gloo_events::EventListener; use gloo_utils::window; #[cfg(feature = "query")] use serde::Serialize; use wasm_bindgen::{JsValue, UnwrapThrowExt}; use web_sys::Url; #[cfg(feature = "query")] use crate::error::HistoryResult; use crate::history::History; use crate::listener::HistoryListener; use crate::location::Location; use crate::state::{HistoryState, StateMap}; use crate::utils::WeakCallback; #[derive(Clone)] pub struct BrowserHistory { inner: web_sys::History, states: Rc<RefCell<StateMap>>, callbacks: Rc<RefCell<Vec<WeakCallback>>>, } impl fmt::Debug for BrowserHistory { fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { f.debug_struct("BrowserHistory").finish() } } impl PartialEq for BrowserHistory { fn eq(&self, _rhs: &Self) -> bool { true } } impl History for BrowserHistory { fn len(&self) -> usize { self.inner.length().expect_throw("failed to get length.") as usize } fn go(&self, delta: isize) { self.inner .go_with_delta(delta as i32) .expect_throw("failed to call go.") } fn push<'a>(&self, route: impl Into<Cow<'a, str>>) { let url = route.into(); self.inner .push_state_with_url(&Self::create_history_state().1, "", Some(&url)) .expect_throw("failed to push state."); self.notify_callbacks(); } fn replace<'a>(&self, route: impl Into<Cow<'a, str>>) { let url = route.into(); self.inner .replace_state_with_url(&Self::create_history_state().1, "", Some(&url)) .expect_throw("failed to replace history."); self.notify_callbacks(); } fn push_with_state<'a, T>(&self, route: impl Into<Cow<'a, str>>, state: T) where T: 'static, { let url = route.into(); let (id, history_state) = Self::create_history_state(); let mut states = self.states.borrow_mut(); states.insert(id, Rc::new(state) as Rc<dyn Any>); self.inner .push_state_with_url(&history_state, "", Some(&url)) .expect_throw("failed to push state."); self.notify_callbacks(); } fn replace_with_state<'a, T>(&self, route: impl Into<Cow<'a, str>>, state: T) where T: 'static, { let url = route.into(); let (id, history_state) = Self::create_history_state();
.into(), hash: loc .hash() .expect_throw("failed to get location hash.") .into(), state: id.and_then(|m| states.get(&m).cloned()), id, } } } impl Default for BrowserHistory { fn default() -> Self { thread_local! { static BROWSER_HISTORY: RefCell<Option<BrowserHistory>> = RefCell::default(); static LISTENER: RefCell<Option<EventListener>> = RefCell::default(); } BROWSER_HISTORY.with(|m| { let mut m = m.borrow_mut(); match *m { Some(ref m) => m.clone(), None => { let window = window(); let inner = window .history() .expect_throw("Failed to create browser history. Are you using a browser?"); let callbacks = Rc::default(); let history = Self { inner, callbacks, states: Rc::default(), }; { let history = history.clone(); LISTENER.with(move |m| { let mut listener = m.borrow_mut(); *listener = Some(EventListener::new(&window, "popstate", move |_| { history.notify_callbacks(); })); }); } *m = Some(history.clone()); history } } }) } } impl BrowserHistory { pub fn new() -> Self { Self::default() } fn notify_callbacks(&self) { crate::utils::notify_callbacks(self.callbacks.clone()); } fn create_history_state() -> (u32, JsValue) { let history_state = HistoryState::new(); ( history_state.id(), serde_wasm_bindgen::to_value(&history_state) .expect_throw("fails to create history state."), ) } pub(crate) fn combine_url(route: &str, query: &str) -> String { let href = window() .location() .href() .expect_throw("Failed to read location href"); let url = Url::new_with_base(route, &href).expect_throw("current url is not valid."); url.set_search(query); url.href() } }
let mut states = self.states.borrow_mut(); states.insert(id, Rc::new(state) as Rc<dyn Any>); self.inner .replace_state_with_url(&history_state, "", Some(&url)) .expect_throw("failed to replace state."); self.notify_callbacks(); } #[cfg(feature = "query")] fn push_with_query<'a, Q>(&self, route: impl Into<Cow<'a, str>>, query: Q) -> HistoryResult<()> where Q: Serialize, { let route = route.into(); let query = serde_urlencoded::to_string(query)?; let url = Self::combine_url(&route, &query); self.inner .push_state_with_url(&Self::create_history_state().1, "", Some(&url)) .expect_throw("failed to push history."); self.notify_callbacks(); Ok(()) } #[cfg(feature = "query")] fn replace_with_query<'a, Q>( &self, route: impl Into<Cow<'a, str>>, query: Q, ) -> HistoryResult<()> where Q: Serialize, { let route = route.into(); let query = serde_urlencoded::to_string(query)?; let url = Self::combine_url(&route, &query); self.inner .replace_state_with_url(&Self::create_history_state().1, "", Some(&url)) .expect_throw("failed to replace history."); self.notify_callbacks(); Ok(()) } #[cfg(all(feature = "query"))] fn push_with_query_and_state<'a, Q, T>( &self, route: impl Into<Cow<'a, str>>, query: Q, state: T, ) -> HistoryResult<()> where Q: Serialize, T: 'static, { let (id, history_state) = Self::create_history_state(); let mut states = self.states.borrow_mut(); states.insert(id, Rc::new(state) as Rc<dyn Any>); let route = route.into(); let query = serde_urlencoded::to_string(query)?; let url = Self::combine_url(&route, &query); self.inner .push_state_with_url(&history_state, "", Some(&url)) .expect_throw("failed to push history."); self.notify_callbacks(); Ok(()) } #[cfg(all(feature = "query"))] fn replace_with_query_and_state<'a, Q, T>( &self, route: impl Into<Cow<'a, str>>, query: Q, state: T, ) -> HistoryResult<()> where Q: Serialize, T: 'static, { let (id, history_state) = Self::create_history_state(); let mut states = self.states.borrow_mut(); states.insert(id, Rc::new(state) as Rc<dyn Any>); let route = route.into(); let query = serde_urlencoded::to_string(query)?; let url = Self::combine_url(&route, &query); self.inner .replace_state_with_url(&history_state, "", Some(&url)) .expect_throw("failed to replace history."); self.notify_callbacks(); Ok(()) } fn listen<CB>(&self, callback: CB) -> HistoryListener where CB: Fn() + 'static, { let cb = Rc::new(callback) as Rc<dyn Fn()>; self.callbacks.borrow_mut().push(Rc::downgrade(&cb)); HistoryListener { _listener: cb } } fn location(&self) -> Location { let loc = window().location(); let history_state = self.inner.state().expect_throw("failed to get state"); let history_state = serde_wasm_bindgen::from_value::<HistoryState>(history_state).ok(); let id = history_state.map(|m| m.id()); let states = self.states.borrow(); Location { path: loc.pathname().expect_throw("failed to get pathname").into(), query_str: loc .search() .expect_throw("failed to get location query.")
random
[ { "content": "/// Calls the confirm function.\n\n///\n\n/// [MDN Documentation](https://developer.mozilla.org/en-US/docs/Web/API/Window/confirm)\n\npub fn confirm(message: &str) -> bool {\n\n window().confirm_with_message(message).unwrap_throw()\n\n}\n\n\n", "file_path": "crates/dialogs/src/lib.rs", "rank": 0, "score": 180666.1095771002 }, { "content": "/// Calls browser's `requestAnimationFrame`. It is cancelled when the handler is dropped.\n\n///\n\n/// [MDN Documentation](https://developer.mozilla.org/en-US/docs/Web/API/Window/requestAnimationFrame)\n\npub fn request_animation_frame<F>(callback_once: F) -> AnimationFrame\n\nwhere\n\n F: FnOnce(f64) + 'static,\n\n{\n\n let callback_wrapper = Rc::new(RefCell::new(Some(CallbackWrapper(Box::new(callback_once)))));\n\n let callback: Closure<dyn Fn(JsValue)> = {\n\n let callback_wrapper = Rc::clone(&callback_wrapper);\n\n Closure::wrap(Box::new(move |v: JsValue| {\n\n let time: f64 = v.as_f64().unwrap_or(0.0);\n\n let callback = callback_wrapper.borrow_mut().take().unwrap().0;\n\n callback(time);\n\n }))\n\n };\n\n\n\n let render_id = web_sys::window()\n\n .unwrap_throw()\n\n .request_animation_frame(callback.as_ref().unchecked_ref())\n\n .unwrap_throw();\n\n\n\n AnimationFrame {\n\n render_id,\n\n _closure: callback,\n\n callback_wrapper,\n\n }\n\n}\n", "file_path": "crates/render/src/lib.rs", "rank": 1, "score": 164914.6424617811 }, { "content": "struct CallbackWrapper(Box<dyn FnOnce(f64) + 'static>);\n\nimpl fmt::Debug for CallbackWrapper {\n\n fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {\n\n f.write_str(\"CallbackWrapper\")\n\n }\n\n}\n\n\n\nimpl Drop for AnimationFrame {\n\n fn drop(&mut self) {\n\n if self.callback_wrapper.borrow_mut().is_some() {\n\n web_sys::window()\n\n .unwrap_throw()\n\n .cancel_animation_frame(self.render_id)\n\n .unwrap_throw()\n\n }\n\n }\n\n}\n\n\n", "file_path": "crates/render/src/lib.rs", "rank": 2, "score": 142327.81549151216 }, { "content": "/// Calls the alert function.\n\n///\n\n/// [MDN Documentation](https://developer.mozilla.org/en-US/docs/Web/API/Window/alert)\n\npub fn alert(message: &str) {\n\n window().alert_with_message(message).unwrap_throw()\n\n}\n\n\n", "file_path": "crates/dialogs/src/lib.rs", "rank": 3, "score": 141195.97246102302 }, { "content": "/// Calls the `prompt` function.\n\n///\n\n/// A default value can be supplied which will be returned if the user doesn't input anything.\n\n/// This function will return `None` if the value of `default` is `None` and the user cancels\n\n/// the operation.\n\n///\n\n/// [MDN Documentation](https://developer.mozilla.org/en-US/docs/Web/API/Window/prompt)\n\npub fn prompt(message: &str, default: Option<&str>) -> Option<String> {\n\n match default {\n\n Some(default) => window()\n\n .prompt_with_message_and_default(message, default)\n\n .expect_throw(\"can't read input\"),\n\n None => window()\n\n .prompt_with_message(message)\n\n .expect_throw(\"can't read input\"),\n\n }\n\n}\n\n\n", "file_path": "crates/dialogs/src/lib.rs", "rank": 4, "score": 129977.75314503058 }, { "content": "/// Convenience function to access the web_sys history.\n\npub fn history() -> web_sys::History {\n\n window().history().expect_throw(\"Can't find history\")\n\n}\n", "file_path": "crates/utils/src/lib.rs", "rank": 5, "score": 129004.44092407016 }, { "content": "#[test]\n\nfn get() {\n\n let key = \"key\";\n\n let value = \"value\";\n\n LocalStorage::set(key, value).unwrap();\n\n\n\n let obtained_value: String = LocalStorage::get(key).unwrap();\n\n\n\n assert_eq!(value, obtained_value)\n\n}\n\n\n", "file_path": "crates/storage/tests/local_storage.rs", "rank": 6, "score": 111040.69064785002 }, { "content": "#[test]\n\nfn get() {\n\n let key = \"key\";\n\n let value = \"value\";\n\n SessionStorage::set(key, value).unwrap();\n\n\n\n let obtained_value: String = SessionStorage::get(key).unwrap();\n\n\n\n assert_eq!(value, obtained_value)\n\n}\n\n\n", "file_path": "crates/storage/tests/session_storage.rs", "rank": 7, "score": 111040.69064785002 }, { "content": "/// A trait to provide [`History`] access.\n\n///\n\n/// # Warning\n\n///\n\n/// The behaviour of this trait is not well-defined when you mix multiple history kinds in the same application\n\n/// or use `window().history()` to update session history.\n\npub trait History: Clone + PartialEq {\n\n /// Returns the number of elements in [`History`].\n\n fn len(&self) -> usize;\n\n\n\n /// Returns true if the current [`History`] is empty.\n\n fn is_empty(&self) -> bool {\n\n self.len() == 0\n\n }\n\n\n\n /// Moves back 1 page in [`History`].\n\n fn back(&self) {\n\n self.go(-1);\n\n }\n\n\n\n /// Moves forward 1 page in [`History`].\n\n fn forward(&self) {\n\n self.go(1);\n\n }\n\n\n\n /// Loads a specific page in [`History`] with a `delta` relative to current page.\n", "file_path": "crates/history/src/history.rs", "rank": 8, "score": 106869.26461623405 }, { "content": "#[wasm_bindgen(start)]\n\npub fn main() {\n\n console_error_panic_hook::set_once();\n\n\n\n let document = web_sys::window().unwrap_throw().document().unwrap_throw();\n\n\n\n let el = document.get_element_by_id(\"clock\").unwrap_throw();\n\n\n\n // render the date, then set it to re-render every second.\n\n render_date(&el);\n\n\n\n spawn_local(async move {\n\n IntervalStream::new(1_000).for_each(|_| {\n\n render_date(&el);\n\n ready(())\n\n }).await;\n\n });\n\n}\n\n\n", "file_path": "examples/clock/src/lib.rs", "rank": 9, "score": 103608.97746477152 }, { "content": "#[test]\n\nfn history_works() {\n\n let history = MemoryHistory::new();\n\n assert_eq!(history.location().path(), \"/\");\n\n\n\n history.push(\"/path-a\");\n\n assert_eq!(history.location().path(), \"/path-a\");\n\n\n\n history.replace(\"/path-b\");\n\n assert_eq!(history.location().path(), \"/path-b\");\n\n\n\n history.back();\n\n assert_eq!(history.location().path(), \"/\");\n\n\n\n history.forward();\n\n assert_eq!(history.location().path(), \"/path-b\");\n\n}\n", "file_path": "crates/history/tests/memory_history.rs", "rank": 10, "score": 97067.66880462 }, { "content": "/// Declares the behavior of the worker.\n\npub trait Worker: Sized + 'static {\n\n /// Reach capability of the worker.\n\n type Reach: Discoverer<Worker = Self>;\n\n /// Type of an input message.\n\n type Message;\n\n /// Incoming message type.\n\n type Input;\n\n /// Outgoing message type.\n\n type Output;\n\n\n\n /// Creates an instance of an worker.\n\n fn create(link: WorkerLink<Self>) -> Self;\n\n\n\n /// This method called on every update message.\n\n fn update(&mut self, msg: Self::Message);\n\n\n\n /// This method called on when a new bridge created.\n\n fn connected(&mut self, _id: HandlerId) {}\n\n\n\n /// This method called on every incoming message.\n", "file_path": "crates/worker/src/lib.rs", "rank": 11, "score": 95442.72055035766 }, { "content": "/// This trait allows registering or getting the address of a worker.\n\npub trait Bridged: Worker + Sized + 'static {\n\n /// Creates a messaging bridge between a worker and the component.\n\n fn bridge(callback: Callback<Self::Output>) -> Box<dyn Bridge<Self>>;\n\n}\n\n\n\nimpl<T> Bridged for T\n\nwhere\n\n T: Worker,\n\n <T as Worker>::Reach: Discoverer<Worker = T>,\n\n{\n\n fn bridge(callback: Callback<Self::Output>) -> Box<dyn Bridge<Self>> {\n\n Self::Reach::spawn_or_join(Some(callback))\n\n }\n\n}\n", "file_path": "crates/worker/src/lib.rs", "rank": 12, "score": 90691.42886115557 }, { "content": "/// This trait allows the creation of a dispatcher to an existing worker that will not send replies when messages are sent.\n\npub trait Dispatched: Worker + Sized + 'static {\n\n /// Creates a dispatcher to the worker that will not send messages back.\n\n ///\n\n /// # Note\n\n /// Dispatchers don't have `HandlerId`s and therefore `Worker::handle` will be supplied `None`\n\n /// for the `id` parameter, and `connected` and `disconnected` will not be called.\n\n ///\n\n /// # Important\n\n /// Because the Workers using Context or Public reaches use the number of existing bridges to\n\n /// keep track of if the worker itself should exist, creating dispatchers will not guarantee that\n\n /// an Worker will exist to service requests sent from Dispatchers. You **must** keep at least one\n\n /// bridge around if you wish to use a dispatcher. If you are using workers in a write-only manner,\n\n /// then it is suggested that you create a bridge that handles no-op responses as high up in the\n\n /// component hierarchy as possible - oftentimes the root component for simplicity's sake.\n\n fn dispatcher() -> Dispatcher<Self>;\n\n}\n\n\n", "file_path": "crates/worker/src/pool.rs", "rank": 13, "score": 90687.3075795956 }, { "content": "/// Convenience function to avoid repeating expect logic.\n\npub fn window() -> web_sys::Window {\n\n web_sys::window().expect_throw(\"Can't find the global Window\")\n\n}\n\n\n", "file_path": "crates/utils/src/lib.rs", "rank": 14, "score": 90476.05310959605 }, { "content": "/// Convenience function to access the web_sys DOM document.\n\npub fn document() -> web_sys::Document {\n\n window().document().expect_throw(\"Can't find document\")\n\n}\n\n\n", "file_path": "crates/utils/src/lib.rs", "rank": 15, "score": 90476.05310959605 }, { "content": "#[derive(Debug)]\n\nstruct LocationStack {\n\n prev: Vec<Location>,\n\n next: VecDeque<Location>,\n\n current: Location,\n\n}\n\n\n\nimpl LocationStack {\n\n fn current(&self) -> Location {\n\n self.current.clone()\n\n }\n\n\n\n fn len(&self) -> usize {\n\n self.prev.len() + self.next.len() + 1\n\n }\n\n\n\n fn go(&mut self, delta: isize) {\n\n match delta.cmp(&0) {\n\n // Go forward.\n\n Ordering::Greater => {\n\n for _i in 0..delta {\n", "file_path": "crates/history/src/memory.rs", "rank": 16, "score": 88952.98272152623 }, { "content": "/// Convenience function to access `document.body`.\n\npub fn body() -> web_sys::HtmlElement {\n\n document().body().expect_throw(\"Can't find document body\")\n\n}\n\n\n", "file_path": "crates/utils/src/lib.rs", "rank": 17, "score": 88637.4493104663 }, { "content": "/// Convenience function to access `document.documentElement`.\n\npub fn document_element() -> web_sys::Element {\n\n document()\n\n .document_element()\n\n .expect_throw(\"Can't find document element\")\n\n}\n\n\n", "file_path": "crates/utils/src/lib.rs", "rank": 18, "score": 88637.4493104663 }, { "content": "/// Convenience function to access the head element.\n\npub fn head() -> web_sys::HtmlHeadElement {\n\n document()\n\n .head()\n\n .expect_throw(\"Can't find the head element\")\n\n}\n\n\n", "file_path": "crates/utils/src/lib.rs", "rank": 19, "score": 86908.79873581596 }, { "content": "#[test]\n\nfn get_all() {\n\n LocalStorage::set(\"key1\", \"value\").unwrap();\n\n LocalStorage::set(\"key2\", \"value\").unwrap();\n\n\n\n let data: Data = LocalStorage::get_all().unwrap();\n\n assert_eq!(data.key1, \"value\");\n\n assert_eq!(data.key2, \"value\");\n\n}\n\n\n", "file_path": "crates/storage/tests/local_storage.rs", "rank": 20, "score": 86754.1002123873 }, { "content": "#[test]\n\nfn get_all() {\n\n SessionStorage::set(\"key1\", \"value\").unwrap();\n\n SessionStorage::set(\"key2\", \"value\").unwrap();\n\n\n\n let data: Data = SessionStorage::get_all().unwrap();\n\n assert_eq!(data.key1, \"value\");\n\n assert_eq!(data.key2, \"value\");\n\n}\n\n\n", "file_path": "crates/storage/tests/session_storage.rs", "rank": 21, "score": 86754.1002123873 }, { "content": "/// Waits until the specified duration has elapsed.\n\n///\n\n/// # Panics\n\n///\n\n/// This function will panic if the specified [`Duration`] cannot be casted into a u32 in\n\n/// milliseconds.\n\n///\n\n/// # Example\n\n///\n\n/// ```compile_fail\n\n/// use std::time::Duration;\n\n/// use gloo_timers::future::sleep;\n\n///\n\n/// sleep(Duration::from_secs(1)).await;\n\n/// ```\n\npub fn sleep(dur: Duration) -> TimeoutFuture {\n\n let millis = u32::try_from(dur.as_millis())\n\n .expect_throw(\"failed to cast the duration into a u32 with Duration::as_millis.\");\n\n\n\n TimeoutFuture::new(millis)\n\n}\n\n\n\nimpl Future for TimeoutFuture {\n\n type Output = ();\n\n\n\n fn poll(mut self: Pin<&mut Self>, cx: &mut Context) -> Poll<Self::Output> {\n\n Future::poll(Pin::new(&mut self.rx), cx).map(|t| t.unwrap_throw())\n\n }\n\n}\n\n/// A scheduled interval as a `Stream`.\n\n///\n\n/// See `IntervalStream::new` for scheduling new intervals.\n\n///\n\n/// Once scheduled, if you want to stop the interval from continuing to fire,\n\n/// you can `drop` the stream.\n", "file_path": "crates/timers/src/future.rs", "rank": 22, "score": 86075.00594256764 }, { "content": "struct WorkerState<W> {\n\n worker: Option<W>,\n\n // TODO: Use worker field to control create message this flag\n\n destroyed: bool,\n\n}\n\n\n\nimpl<W> WorkerState<W> {\n\n fn new() -> Self {\n\n WorkerState {\n\n worker: None,\n\n destroyed: false,\n\n }\n\n }\n\n}\n\n\n\n/// Internal Worker lifecycle events\n\n#[derive(Debug)]\n\npub(crate) enum WorkerLifecycleEvent<W: Worker> {\n\n /// Request to create link\n\n Create(WorkerLink<W>),\n", "file_path": "crates/worker/src/link.rs", "rank": 23, "score": 85444.13429510366 }, { "content": "#[test]\n\nfn set_and_length() {\n\n LocalStorage::clear();\n\n assert_eq!(LocalStorage::length(), 0);\n\n LocalStorage::set(\"key\", \"value\").unwrap();\n\n assert_eq!(LocalStorage::length(), 1);\n\n LocalStorage::clear();\n\n assert_eq!(LocalStorage::length(), 0);\n\n}\n", "file_path": "crates/storage/tests/local_storage.rs", "rank": 24, "score": 84531.49626668936 }, { "content": "#[test]\n\nfn set_and_length() {\n\n SessionStorage::clear();\n\n assert_eq!(SessionStorage::length(), 0);\n\n SessionStorage::set(\"key\", \"value\").unwrap();\n\n assert_eq!(SessionStorage::length(), 1);\n\n SessionStorage::clear();\n\n assert_eq!(SessionStorage::length(), 0);\n\n}\n", "file_path": "crates/storage/tests/session_storage.rs", "rank": 25, "score": 84531.49626668936 }, { "content": "#[derive(Debug, Clone, Serialize, Deserialize)]\n\nenum HistoryStateKind {\n\n #[serde(rename = \"gloo_history_state\")]\n\n Gloo,\n\n}\n\n\n\n/// The state used by browser history to store history id.\n\n#[derive(Debug, Clone, Serialize, Deserialize)]\n\npub(crate) struct HistoryState {\n\n id: u32,\n\n kind: HistoryStateKind,\n\n}\n\n\n\nimpl HistoryState {\n\n pub fn new() -> HistoryState {\n\n Self {\n\n id: get_id(),\n\n kind: HistoryStateKind::Gloo,\n\n }\n\n }\n\n\n\n pub fn id(&self) -> u32 {\n\n self.id\n\n }\n\n}\n\n\n\npub(crate) type StateMap = HashMap<u32, Rc<dyn Any>>;\n", "file_path": "crates/history/src/state.rs", "rank": 26, "score": 82207.03776151231 }, { "content": "fn worker_self() -> DedicatedWorkerGlobalScope {\n\n JsValue::from(js_sys::global()).into()\n\n}\n\n\n", "file_path": "crates/worker/src/worker/mod.rs", "rank": 27, "score": 74611.07562315019 }, { "content": "use std::any::Any;\n\nuse std::collections::HashMap;\n\nuse std::rc::Rc;\n\n\n\nuse serde::{Deserialize, Serialize};\n\n\n\nuse crate::utils::get_id;\n\n\n\n/// A constant to prevent state collision.\n\n#[derive(Debug, Clone, Serialize, Deserialize)]\n", "file_path": "crates/history/src/state.rs", "rank": 28, "score": 70224.89524776483 }, { "content": "#[derive(Deserialize)]\n\nstruct Data {\n\n key1: String,\n\n key2: String,\n\n}\n\n\n", "file_path": "crates/storage/tests/local_storage.rs", "rank": 29, "score": 57009.610470126594 }, { "content": "#[derive(Deserialize)]\n\nstruct Data {\n\n key1: String,\n\n key2: String,\n\n}\n\n\n", "file_path": "crates/storage/tests/session_storage.rs", "rank": 30, "score": 57009.610470126594 }, { "content": "#[derive(Clone)]\n\nstruct Sender<A> {\n\n sender: mpsc::UnboundedSender<Result<A, JsValue>>,\n\n}\n\n\n\nimpl<A> Sender<A> {\n\n fn send<F>(&self, f: F)\n\n where\n\n F: FnOnce() -> Result<A, JsValue>,\n\n {\n\n self.sender.unbounded_send(f()).unwrap_throw();\n\n }\n\n}\n\n\n\nasync fn mpsc<A, F>(f: F) -> Result<Vec<A>, JsValue>\n\nwhere\n\n F: FnOnce(Sender<A>),\n\n{\n\n let (sender, receiver) = mpsc::unbounded();\n\n f(Sender { sender });\n\n receiver.try_collect().await\n", "file_path": "crates/events/tests/web.rs", "rank": 31, "score": 55588.449183676326 }, { "content": "#[wasm_bindgen_test]\n\nfn forget() {\n\n let target = window()\n\n .unwrap_throw()\n\n .document()\n\n .unwrap_throw()\n\n .create_element(\"div\")\n\n .unwrap_throw();\n\n\n\n let handler = EventListener::new(&target, \"click\", move |_| {});\n\n\n\n handler.forget();\n\n}\n\n\n\n#[wasm_bindgen_test]\n\nasync fn dynamic_registration() {\n\n let results = mpsc(|sender| {\n\n let body = body();\n\n\n\n let handler1 = EventListener::new(&body, \"click\", {\n\n let sender = sender.clone();\n", "file_path": "crates/events/tests/web.rs", "rank": 32, "score": 54622.51171706252 }, { "content": "#[wasm_bindgen_test]\n\nfn modified_since() {\n\n use chrono::Utc;\n\n use std::time::{Duration, SystemTime};\n\n\n\n let file = File::new(\"test.txt\", \"\");\n\n let now: SystemTime = Utc::now().into();\n\n // Check the file was created less than 1ms ago. This should be plenty of time.\n\n assert!(\n\n file.last_modified_time()\n\n .checked_sub(Duration::from_millis(1))\n\n .unwrap()\n\n < now.into()\n\n );\n\n}\n\n\n\n#[cfg(feature = \"futures\")]\n\n#[wasm_bindgen_test]\n\nasync fn text_future() {\n\n let blob = Blob::new(\"hello\");\n\n\n", "file_path": "crates/file/tests/web.rs", "rank": 33, "score": 53423.683172439225 }, { "content": "#[wasm_bindgen_test]\n\nfn png_file() {\n\n let file = File::new_with_options(\"img.png\", PNG_FILE, Some(\"image/png\"), None);\n\n assert_eq!(file.name(), \"img.png\");\n\n assert_eq!(file.raw_mime_type(), \"image/png\");\n\n}\n\n\n", "file_path": "crates/file/tests/web.rs", "rank": 34, "score": 53423.683172439225 }, { "content": "/// Trait which provides implementations for managing storage in the browser.\n\npub trait Storage {\n\n /// Get the raw [`web_sys::Storage`] instance\n\n fn raw() -> web_sys::Storage;\n\n\n\n /// Get the value for the specified key\n\n fn get<T>(key: impl AsRef<str>) -> Result<T>\n\n where\n\n T: for<'de> Deserialize<'de>,\n\n {\n\n let key = key.as_ref();\n\n let item = Self::raw()\n\n .get_item(key)\n\n .expect_throw(\"unreachable: get_item does not throw an exception\")\n\n .ok_or_else(|| StorageError::KeyNotFound(key.to_string()))?;\n\n let item = serde_json::from_str(&item)?;\n\n Ok(item)\n\n }\n\n\n\n /// Get all the stored keys and their values\n\n fn get_all<T>() -> Result<T>\n", "file_path": "crates/storage/src/lib.rs", "rank": 35, "score": 52462.8192179891 }, { "content": " pub trait Sealed {}\n\n}\n\nuse sealed::Sealed;\n\n\n", "file_path": "crates/file/src/blob.rs", "rank": 36, "score": 52462.8192179891 }, { "content": "#[doc(hidden)]\n\npub trait Discoverer {\n\n type Worker: Worker;\n\n\n\n /// Spawns an worker and returns `Bridge` implementation.\n\n fn spawn_or_join(\n\n _callback: Option<Callback<<Self::Worker as Worker>::Output>>,\n\n ) -> Box<dyn Bridge<Self::Worker>>;\n\n}\n\n\n", "file_path": "crates/worker/src/lib.rs", "rank": 37, "score": 52462.8192179891 }, { "content": "#[doc(hidden)]\n\npub trait Dispatchable {}\n\n\n\nimpl<T> Dispatched for T\n\nwhere\n\n T: Worker,\n\n <T as Worker>::Reach: Discoverer<Worker = T>,\n\n <T as Worker>::Reach: Dispatchable,\n\n{\n\n fn dispatcher() -> Dispatcher<T> {\n\n Dispatcher(Self::Reach::spawn_or_join(None))\n\n }\n\n}\n", "file_path": "crates/worker/src/pool.rs", "rank": 38, "score": 52462.8192179891 }, { "content": "fn worker_new(\n\n name_of_resource: &str,\n\n resource_is_relative: bool,\n\n is_module: bool,\n\n) -> web_sys::Worker {\n\n let origin = gloo_utils::document()\n\n .location()\n\n .unwrap_throw()\n\n .origin()\n\n .unwrap_throw();\n\n let pathname = gloo_utils::window().location().pathname().unwrap_throw();\n\n\n\n let prefix = if resource_is_relative {\n\n pathname\n\n .rfind(|c| c == '/')\n\n .map(|i| &pathname[..i])\n\n .unwrap_or_default()\n\n } else {\n\n \"\"\n\n };\n", "file_path": "crates/worker/src/worker/mod.rs", "rank": 39, "score": 52306.28743183292 }, { "content": "struct RemoteWorker<W>\n\nwhere\n\n W: Worker,\n\n <W as Worker>::Input: Serialize + for<'de> Deserialize<'de>,\n\n <W as Worker>::Output: Serialize + for<'de> Deserialize<'de>,\n\n{\n\n worker: web_sys::Worker,\n\n slab: SharedOutputSlab<W>,\n\n}\n\n\n\nimpl<W> RemoteWorker<W>\n\nwhere\n\n W: Worker,\n\n <W as Worker>::Input: Serialize + for<'de> Deserialize<'de>,\n\n <W as Worker>::Output: Serialize + for<'de> Deserialize<'de>,\n\n{\n\n pub fn new(worker: web_sys::Worker, slab: SharedOutputSlab<W>) -> Self {\n\n RemoteWorker { worker, slab }\n\n }\n\n\n", "file_path": "crates/worker/src/worker/public.rs", "rank": 40, "score": 52189.80700154302 }, { "content": "/// Message packager, based on serde::Serialize/Deserialize\n\npub trait Packed {\n\n /// Pack serializable message into Vec<u8>\n\n fn pack(&self) -> Vec<u8>;\n\n /// Unpack deserializable message of byte slice\n\n fn unpack(data: &[u8]) -> Self;\n\n}\n\n\n\nimpl<T: Serialize + for<'de> Deserialize<'de>> Packed for T {\n\n fn pack(&self) -> Vec<u8> {\n\n bincode::serialize(&self).expect(\"can't serialize an worker message\")\n\n }\n\n\n\n fn unpack(data: &[u8]) -> Self {\n\n bincode::deserialize(data).expect(\"can't deserialize an worker message\")\n\n }\n\n}\n\n\n\n/// Serializable messages to worker\n", "file_path": "crates/worker/src/worker/mod.rs", "rank": 41, "score": 51340.59360323283 }, { "content": "#[wasm_bindgen_test]\n\nfn scoped_timer_returns_value() {\n\n let value = Timer::scope(\"foo\", || true);\n\n\n\n assert!(value);\n\n}\n", "file_path": "crates/console/tests/web.rs", "rank": 42, "score": 51262.2998145879 }, { "content": "/// A trait to enable public workers being registered in a web worker.\n\npub trait PublicWorker {\n\n /// Executes an worker in the current environment.\n\n /// Uses in `main` function of a worker.\n\n fn register();\n\n}\n\n\n\nimpl<W> PublicWorker for W\n\nwhere\n\n W: Worker<Reach = Public<W>>,\n\n <W as Worker>::Input: Serialize + for<'de> Deserialize<'de>,\n\n <W as Worker>::Output: Serialize + for<'de> Deserialize<'de>,\n\n{\n\n fn register() {\n\n let scope = WorkerScope::<W>::new();\n\n let responder = WorkerResponder;\n\n let link = WorkerLink::connect(&scope, responder);\n\n let upd = WorkerLifecycleEvent::Create(link);\n\n scope.send(upd);\n\n let handler = move |data: Vec<u8>| {\n\n let msg = ToWorker::<W::Input>::unpack(&data);\n", "file_path": "crates/worker/src/worker/public.rs", "rank": 43, "score": 50292.093413922106 }, { "content": "/// A trait to enable private workers being registered in a web worker.\n\npub trait PrivateWorker {\n\n /// Executes an worker in the current environment.\n\n /// Uses in `main` function of a worker.\n\n fn register();\n\n}\n\n\n\nimpl<W> PrivateWorker for W\n\nwhere\n\n W: Worker<Reach = Private<W>>,\n\n <W as Worker>::Input: Serialize + for<'de> Deserialize<'de>,\n\n <W as Worker>::Output: Serialize + for<'de> Deserialize<'de>,\n\n{\n\n fn register() {\n\n let scope = WorkerScope::<W>::new();\n\n let responder = WorkerResponder;\n\n let link = WorkerLink::connect(&scope, responder);\n\n let upd = WorkerLifecycleEvent::Create(link);\n\n scope.send(upd);\n\n let handler = move |data: Vec<u8>| {\n\n let msg = ToWorker::<W::Input>::unpack(&data);\n", "file_path": "crates/worker/src/worker/private.rs", "rank": 44, "score": 50292.093413922106 }, { "content": "struct WorkerRunnable<W: Worker> {\n\n state: Shared<WorkerState<W>>,\n\n event: WorkerLifecycleEvent<W>,\n\n}\n\n\n\nimpl<W> WorkerRunnable<W>\n\nwhere\n\n W: Worker,\n\n{\n\n fn run(self) {\n\n let mut state = self.state.borrow_mut();\n\n if state.destroyed {\n\n return;\n\n }\n\n match self.event {\n\n WorkerLifecycleEvent::Create(link) => {\n\n state.worker = Some(W::create(link));\n\n }\n\n WorkerLifecycleEvent::Message(msg) => {\n\n state\n", "file_path": "crates/worker/src/link.rs", "rank": 45, "score": 50082.24467520838 }, { "content": "fn body() -> HtmlElement {\n\n window()\n\n .unwrap_throw()\n\n .document()\n\n .unwrap_throw()\n\n .body()\n\n .unwrap_throw()\n\n}\n\n\n", "file_path": "crates/events/tests/web.rs", "rank": 46, "score": 50028.76250617613 }, { "content": "/// This trait is used to overload the `Blob::new_with_options` function, allowing a variety of\n\n/// types to be used to create a `Blob`. Ignore this, and use &\\[u8], &str, etc to create a `Blob`.\n\n///\n\n/// The trait is sealed: it can only be implemented by types in this\n\n/// crate, as this crate relies on invariants regarding the `JsValue` returned from `into_jsvalue`.\n\npub trait BlobContents: Sealed {\n\n /// # Safety\n\n ///\n\n /// For `&[u8]` and `&str`, the returned `Uint8Array` must be modified,\n\n /// and must not be kept past the lifetime of the original slice.\n\n unsafe fn into_jsvalue(self) -> JsValue;\n\n}\n\n\n\nimpl<'a> Sealed for &'a str {}\n\nimpl<'a> BlobContents for &'a str {\n\n unsafe fn into_jsvalue(self) -> JsValue {\n\n // Converting a Rust string to a JS string re-encodes it from UTF-8 to UTF-16,\n\n // and `Blob` re-encodes JS strings from UTF-16 to UTF-8.\n\n // So, it's better to just pass the original bytes of the Rust string to `Blob`\n\n // and avoid the round trip through UTF-16.\n\n self.as_bytes().into_jsvalue()\n\n }\n\n}\n\n\n\nimpl<'a> Sealed for &'a [u8] {}\n", "file_path": "crates/file/src/blob.rs", "rank": 47, "score": 48359.42991705952 }, { "content": "#[inline]\n\nfn window() -> web_sys::Window {\n\n web_sys::window().expect_throw(\"can't access window\")\n\n}\n", "file_path": "crates/dialogs/src/lib.rs", "rank": 48, "score": 47162.234541208694 }, { "content": "/// Bridge to a specific kind of worker.\n\npub trait Bridge<W: Worker> {\n\n /// Send a message to an worker.\n\n fn send(&mut self, msg: W::Input);\n\n}\n\n\n", "file_path": "crates/worker/src/lib.rs", "rank": 49, "score": 46764.72435751133 }, { "content": "/// JavaScript only has `f64`, which has a maximum accurate integer size of`2^53 - 1`. So we use\n\n/// this to safely convert from larger integers to `f64`. See\n\n/// [Number.MAX_SAFE_INTEGER](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Number/MAX_SAFE_INTEGER)\n\nfn safe_u64_to_f64(number: u64) -> f64 {\n\n // Max integer stably representable by f64\n\n if number > (js_sys::Number::MAX_SAFE_INTEGER as u64) {\n\n throw_str(\"a rust number was too large and could not be represented in JavaScript\");\n\n }\n\n number as f64\n\n}\n\n\n", "file_path": "crates/file/src/blob.rs", "rank": 50, "score": 43778.65732601471 }, { "content": "/// Render the date with the `:` flashing on and off every second into `el`.\n\nfn render_date(el: &web_sys::Element) {\n\n // print the current date\n\n let date = chrono::Local::now();\n\n\n\n let format_str = if date.second() % 2 == 0 {\n\n \"%Y-%m-%d %H %M\"\n\n } else {\n\n \"%Y-%m-%d %H:%M\"\n\n };\n\n\n\n let date_str = date.format(format_str).to_string();\n\n\n\n // Set the contents of `el` to our date string\n\n el.set_text_content(Some(&date_str));\n\n}\n", "file_path": "examples/clock/src/lib.rs", "rank": 51, "score": 43775.81825694331 }, { "content": "/// Like safe_u64_to_f64, but additionally checks that the number is an integer.\n\nfn safe_f64_to_u64(number: f64) -> u64 {\n\n // Max integer stably representable by f64\n\n if number > js_sys::Number::MAX_SAFE_INTEGER {\n\n throw_str(\"a rust number was too large and could not be represented in JavaScript\");\n\n }\n\n\n\n if number.fract() != 0.0 {\n\n throw_str(\n\n \"a number could not be converted to an integer because it was not a whole number\",\n\n );\n\n }\n\n number as u64\n\n}\n", "file_path": "crates/file/src/blob.rs", "rank": 52, "score": 43775.81825694331 }, { "content": "fn safe_u128_to_f64(number: u128) -> f64 {\n\n // Max integer stably representable by f64\n\n const MAX_SAFE_INTEGER: u128 = js_sys::Number::MAX_SAFE_INTEGER as u128; // (2^53 - 1)\n\n if number > MAX_SAFE_INTEGER {\n\n throw_str(\"a rust number was too large and could not be represented in JavaScript\");\n\n }\n\n number as f64\n\n}\n\n\n", "file_path": "crates/file/src/blob.rs", "rank": 53, "score": 43775.81825694331 }, { "content": " ///\n\n /// See: <https://developer.mozilla.org/en-US/docs/Web/API/History/go>\n\n fn go(&self, delta: isize);\n\n\n\n /// Pushes a route entry with [`None`] being the state.\n\n fn push<'a>(&self, route: impl Into<Cow<'a, str>>);\n\n\n\n /// Replaces the current history entry with provided route and [`None`] state.\n\n fn replace<'a>(&self, route: impl Into<Cow<'a, str>>);\n\n\n\n /// Pushes a route entry with state.\n\n fn push_with_state<'a, T>(&self, route: impl Into<Cow<'a, str>>, state: T)\n\n where\n\n T: 'static;\n\n\n\n /// Replaces the current history entry with provided route and state.\n\n fn replace_with_state<'a, T>(&self, route: impl Into<Cow<'a, str>>, state: T)\n\n where\n\n T: 'static;\n\n\n", "file_path": "crates/history/src/history.rs", "rank": 54, "score": 43133.140673016875 }, { "content": " route: impl Into<Cow<'a, str>>,\n\n query: Q,\n\n state: T,\n\n ) -> HistoryResult<()>\n\n where\n\n Q: Serialize,\n\n T: 'static;\n\n\n\n /// Same as `.replace_with_state()` but affix the queries to the end of the route.\n\n #[cfg(all(feature = \"query\"))]\n\n fn replace_with_query_and_state<'a, Q, T>(\n\n &self,\n\n route: impl Into<Cow<'a, str>>,\n\n query: Q,\n\n state: T,\n\n ) -> HistoryResult<()>\n\n where\n\n Q: Serialize,\n\n T: 'static;\n\n\n", "file_path": "crates/history/src/history.rs", "rank": 55, "score": 43124.76444433221 }, { "content": " /// Same as `.push()` but affix the queries to the end of the route.\n\n #[cfg(feature = \"query\")]\n\n fn push_with_query<'a, Q>(&self, route: impl Into<Cow<'a, str>>, query: Q) -> HistoryResult<()>\n\n where\n\n Q: Serialize;\n\n\n\n /// Same as `.replace()` but affix the queries to the end of the route.\n\n #[cfg(feature = \"query\")]\n\n fn replace_with_query<'a, Q>(\n\n &self,\n\n route: impl Into<Cow<'a, str>>,\n\n query: Q,\n\n ) -> HistoryResult<()>\n\n where\n\n Q: Serialize;\n\n\n\n /// Same as `.push_with_state()` but affix the queries to the end of the route.\n\n #[cfg(all(feature = \"query\"))]\n\n fn push_with_query_and_state<'a, Q, T>(\n\n &self,\n", "file_path": "crates/history/src/history.rs", "rank": 56, "score": 43124.052011857304 }, { "content": " /// Creates a Listener that will be notified when current state changes.\n\n ///\n\n /// This method returns a [`HistoryListener`] that will automatically unregister the callback\n\n /// when dropped.\n\n fn listen<CB>(&self, callback: CB) -> HistoryListener\n\n where\n\n CB: Fn() + 'static;\n\n\n\n /// Returns current [`Location`].\n\n fn location(&self) -> Location;\n\n}\n", "file_path": "crates/history/src/history.rs", "rank": 57, "score": 43109.755366828154 }, { "content": "use std::borrow::Cow;\n\n\n\n#[cfg(feature = \"query\")]\n\nuse serde::Serialize;\n\n\n\n#[cfg(feature = \"query\")]\n\nuse crate::error::HistoryResult;\n\nuse crate::listener::HistoryListener;\n\nuse crate::location::Location;\n\n\n\n/// A trait to provide [`History`] access.\n\n///\n\n/// # Warning\n\n///\n\n/// The behaviour of this trait is not well-defined when you mix multiple history kinds in the same application\n\n/// or use `window().history()` to update session history.\n", "file_path": "crates/history/src/history.rs", "rank": 58, "score": 43105.285845838545 }, { "content": "fn parse_message(event: MessageEvent) -> Message {\n\n if let Ok(array_buffer) = event.data().dyn_into::<js_sys::ArrayBuffer>() {\n\n let array = js_sys::Uint8Array::new(&array_buffer);\n\n Message::Bytes(array.to_vec())\n\n } else if let Ok(txt) = event.data().dyn_into::<js_sys::JsString>() {\n\n Message::Text(String::from(&txt))\n\n } else {\n\n unreachable!(\"message event, received Unknown: {:?}\", event.data());\n\n }\n\n}\n\n\n\nimpl Sink<Message> for WebSocket {\n\n type Error = WebSocketError;\n\n\n\n fn poll_ready(self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Result<(), Self::Error>> {\n\n let ready_state = self.ws.ready_state();\n\n if ready_state == 0 {\n\n *self.sink_waker.borrow_mut() = Some(cx.waker().clone());\n\n Poll::Pending\n\n } else {\n", "file_path": "crates/net/src/websocket/futures.rs", "rank": 59, "score": 42913.35693753951 }, { "content": "use std::time::Duration;\n\n\n\nuse gloo_timers::future::sleep;\n\nuse wasm_bindgen_test::{wasm_bindgen_test as test, wasm_bindgen_test_configure};\n\n\n\nuse gloo_history::{BrowserHistory, History};\n\n\n\nwasm_bindgen_test_configure!(run_in_browser);\n\n\n\n#[test]\n\nasync fn history_works() {\n\n let history = BrowserHistory::new();\n\n assert_eq!(history.location().path(), \"/\");\n\n\n\n history.push(\"/path-a\");\n\n assert_eq!(history.location().path(), \"/path-a\");\n\n\n\n history.replace(\"/path-b\");\n\n assert_eq!(history.location().path(), \"/path-b\");\n\n\n\n history.back();\n\n sleep(Duration::from_millis(100)).await;\n\n assert_eq!(history.location().path(), \"/\");\n\n\n\n history.forward();\n\n sleep(Duration::from_millis(100)).await;\n\n assert_eq!(history.location().path(), \"/path-b\");\n\n}\n", "file_path": "crates/history/tests/browser_history.rs", "rank": 60, "score": 42106.800005743564 }, { "content": "use std::time::Duration;\n\n\n\nuse gloo_timers::future::sleep;\n\nuse wasm_bindgen_test::{wasm_bindgen_test as test, wasm_bindgen_test_configure};\n\n\n\nuse gloo_history::{HashHistory, History};\n\nuse gloo_utils::window;\n\n\n\nwasm_bindgen_test_configure!(run_in_browser);\n\n\n\n#[test]\n\nasync fn history_works() {\n\n let history = HashHistory::new();\n\n assert_eq!(history.location().path(), \"/\");\n\n assert_eq!(window().location().pathname().unwrap(), \"/\");\n\n assert_eq!(window().location().hash().unwrap(), \"#/\");\n\n\n\n history.push(\"/path-a\");\n\n assert_eq!(history.location().path(), \"/path-a\");\n\n assert_eq!(window().location().pathname().unwrap(), \"/\");\n", "file_path": "crates/history/tests/hash_history.rs", "rank": 61, "score": 42105.0175873688 }, { "content": "use wasm_bindgen_test::{wasm_bindgen_test as test, wasm_bindgen_test_configure};\n\n\n\nuse gloo_history::{History, MemoryHistory};\n\n\n\nwasm_bindgen_test_configure!(run_in_browser);\n\n\n\n#[test]\n", "file_path": "crates/history/tests/memory_history.rs", "rank": 62, "score": 42102.52835986284 }, { "content": " assert_eq!(window().location().hash().unwrap(), \"#/path-a\");\n\n\n\n history.replace(\"/path-b\");\n\n assert_eq!(history.location().path(), \"/path-b\");\n\n assert_eq!(window().location().pathname().unwrap(), \"/\");\n\n assert_eq!(window().location().hash().unwrap(), \"#/path-b\");\n\n\n\n history.back();\n\n sleep(Duration::from_millis(100)).await;\n\n assert_eq!(history.location().path(), \"/\");\n\n assert_eq!(window().location().pathname().unwrap(), \"/\");\n\n assert_eq!(window().location().hash().unwrap(), \"#/\");\n\n\n\n history.forward();\n\n sleep(Duration::from_millis(100)).await;\n\n assert_eq!(history.location().path(), \"/path-b\");\n\n assert_eq!(window().location().pathname().unwrap(), \"/\");\n\n assert_eq!(window().location().hash().unwrap(), \"#/path-b\");\n\n}\n", "file_path": "crates/history/tests/hash_history.rs", "rank": 63, "score": 42100.54679092915 }, { "content": "fn is<A>(actual: A, expected: A) -> Result<(), JsValue>\n\nwhere\n\n A: PartialEq + std::fmt::Debug,\n\n{\n\n if expected == actual {\n\n Ok(())\n\n } else {\n\n Err(Error::new(&format!(\n\n \"Expected:\\n {:#?}\\nBut got:\\n {:#?}\",\n\n expected, actual\n\n ))\n\n .into())\n\n }\n\n}\n\n\n", "file_path": "crates/events/tests/web.rs", "rank": 64, "score": 40714.252809966085 }, { "content": " assert_eq!(\n\n history.location().query::<Query>().unwrap(),\n\n Query {\n\n a: \"something\".to_string(),\n\n b: 123,\n\n }\n\n );\n\n\n\n history.push_with_state(\n\n \"/path-c\",\n\n State {\n\n i: \"something\".to_string(),\n\n ii: 123,\n\n },\n\n );\n\n\n\n assert_eq!(history.location().path(), \"/path-c\");\n\n assert_eq!(\n\n history.location().state::<State>().unwrap(),\n\n Rc::new(State {\n\n i: \"something\".to_string(),\n\n ii: 123,\n\n })\n\n );\n\n }\n\n}\n", "file_path": "crates/history/tests/browser_history_feat_serialize.rs", "rank": 65, "score": 40246.91660273482 }, { "content": " history.forward();\n\n assert_eq!(history.location().path(), \"/path-b\");\n\n\n\n history\n\n .push_with_query(\n\n \"/path\",\n\n Query {\n\n a: \"something\".to_string(),\n\n b: 123,\n\n },\n\n )\n\n .unwrap();\n\n\n\n assert_eq!(history.location().path(), \"/path\");\n\n assert_eq!(history.location().query_str(), \"?a=something&b=123\");\n\n assert_eq!(\n\n history.location().query::<Query>().unwrap(),\n\n Query {\n\n a: \"something\".to_string(),\n\n b: 123,\n", "file_path": "crates/history/tests/memory_history_feat_serialize.rs", "rank": 66, "score": 40245.72198436644 }, { "content": " history.back();\n\n sleep(Duration::from_millis(100)).await;\n\n assert_eq!(history.location().path(), \"/\");\n\n\n\n history.forward();\n\n sleep(Duration::from_millis(100)).await;\n\n assert_eq!(history.location().path(), \"/path-b\");\n\n\n\n history\n\n .push_with_query(\n\n \"/path\",\n\n Query {\n\n a: \"something\".to_string(),\n\n b: 123,\n\n },\n\n )\n\n .unwrap();\n\n\n\n assert_eq!(history.location().path(), \"/path\");\n\n assert_eq!(history.location().query_str(), \"?a=something&b=123\");\n", "file_path": "crates/history/tests/browser_history_feat_serialize.rs", "rank": 67, "score": 40244.780389048006 }, { "content": " b: u64,\n\n }\n\n\n\n #[derive(Debug, Serialize, Deserialize, PartialEq)]\n\n struct State {\n\n i: String,\n\n ii: u64,\n\n }\n\n\n\n #[test]\n\n async fn history_serialize_works() {\n\n let history = BrowserHistory::new();\n\n assert_eq!(history.location().path(), \"/\");\n\n\n\n history.push(\"/path-a\");\n\n assert_eq!(history.location().path(), \"/path-a\");\n\n\n\n history.replace(\"/path-b\");\n\n assert_eq!(history.location().path(), \"/path-b\");\n\n\n", "file_path": "crates/history/tests/browser_history_feat_serialize.rs", "rank": 68, "score": 40243.51346570599 }, { "content": " #[derive(Debug, Serialize, Deserialize, PartialEq)]\n\n struct State {\n\n i: String,\n\n ii: u64,\n\n }\n\n\n\n #[test]\n\n fn history_serialize_works() {\n\n let history = MemoryHistory::new();\n\n assert_eq!(history.location().path(), \"/\");\n\n\n\n history.push(\"/path-a\");\n\n assert_eq!(history.location().path(), \"/path-a\");\n\n\n\n history.replace(\"/path-b\");\n\n assert_eq!(history.location().path(), \"/path-b\");\n\n\n\n history.back();\n\n assert_eq!(history.location().path(), \"/\");\n\n\n", "file_path": "crates/history/tests/memory_history_feat_serialize.rs", "rank": 69, "score": 40243.24050831918 }, { "content": " }\n\n );\n\n\n\n history.push_with_state(\n\n \"/path-c\",\n\n State {\n\n i: \"something\".to_string(),\n\n ii: 123,\n\n },\n\n );\n\n\n\n assert_eq!(history.location().path(), \"/path-c\");\n\n assert_eq!(\n\n history.location().state::<State>().unwrap(),\n\n Rc::new(State {\n\n i: \"something\".to_string(),\n\n ii: 123,\n\n })\n\n );\n\n }\n\n}\n", "file_path": "crates/history/tests/memory_history_feat_serialize.rs", "rank": 70, "score": 40242.90422746073 }, { "content": "use wasm_bindgen_test::wasm_bindgen_test_configure;\n\n\n\nwasm_bindgen_test_configure!(run_in_browser);\n\n\n\n#[cfg(all(feature = \"query\"))]\n\nmod feat_serialize {\n\n use wasm_bindgen_test::wasm_bindgen_test as test;\n\n\n\n use std::rc::Rc;\n\n\n\n use serde::{Deserialize, Serialize};\n\n\n\n use gloo_history::{History, MemoryHistory};\n\n\n\n #[derive(Debug, Serialize, Deserialize, PartialEq)]\n\n struct Query {\n\n a: String,\n\n b: u64,\n\n }\n\n\n", "file_path": "crates/history/tests/memory_history_feat_serialize.rs", "rank": 71, "score": 40242.18966569349 }, { "content": "use wasm_bindgen_test::wasm_bindgen_test_configure;\n\n\n\nwasm_bindgen_test_configure!(run_in_browser);\n\n\n\n#[cfg(all(feature = \"query\"))]\n\nmod feat_serialize {\n\n use wasm_bindgen_test::wasm_bindgen_test as test;\n\n\n\n use std::rc::Rc;\n\n use std::time::Duration;\n\n\n\n use serde::{Deserialize, Serialize};\n\n\n\n use gloo_history::{BrowserHistory, History};\n\n\n\n use gloo_timers::future::sleep;\n\n\n\n #[derive(Debug, Serialize, Deserialize, PartialEq)]\n\n struct Query {\n\n a: String,\n", "file_path": "crates/history/tests/browser_history_feat_serialize.rs", "rank": 72, "score": 40242.07894639395 }, { "content": " );\n\n\n\n history.push_with_state(\n\n \"/path-c\",\n\n State {\n\n i: \"something\".to_string(),\n\n ii: 123,\n\n },\n\n );\n\n\n\n assert_eq!(history.location().path(), \"/path-c\");\n\n assert_eq!(window().location().pathname().unwrap(), \"/\");\n\n assert_eq!(window().location().hash().unwrap(), \"#/path-c\");\n\n assert_eq!(\n\n history.location().state::<State>().unwrap(),\n\n Rc::new(State {\n\n i: \"something\".to_string(),\n\n ii: 123,\n\n })\n\n );\n\n }\n\n}\n", "file_path": "crates/history/tests/hash_history_feat_serialize.rs", "rank": 73, "score": 40242.043204330526 }, { "content": "use wasm_bindgen_test::wasm_bindgen_test_configure;\n\n\n\nwasm_bindgen_test_configure!(run_in_browser);\n\n\n\n#[cfg(all(feature = \"query\"))]\n\nmod feat_serialize {\n\n use wasm_bindgen_test::wasm_bindgen_test as test;\n\n\n\n use std::rc::Rc;\n\n use std::time::Duration;\n\n\n\n use serde::{Deserialize, Serialize};\n\n\n\n use gloo_history::{HashHistory, History};\n\n\n\n use gloo_timers::future::sleep;\n\n use gloo_utils::window;\n\n\n\n #[derive(Debug, Serialize, Deserialize, PartialEq)]\n\n struct Query {\n", "file_path": "crates/history/tests/hash_history_feat_serialize.rs", "rank": 74, "score": 40242.04422814888 }, { "content": " Query {\n\n a: \"something\".to_string(),\n\n b: 123,\n\n },\n\n )\n\n .unwrap();\n\n\n\n assert_eq!(history.location().path(), \"/path\");\n\n assert_eq!(history.location().query_str(), \"?a=something&b=123\");\n\n assert_eq!(window().location().pathname().unwrap(), \"/\");\n\n assert_eq!(\n\n window().location().hash().unwrap(),\n\n \"#/path?a=something&b=123\"\n\n );\n\n assert_eq!(\n\n history.location().query::<Query>().unwrap(),\n\n Query {\n\n a: \"something\".to_string(),\n\n b: 123,\n\n }\n", "file_path": "crates/history/tests/hash_history_feat_serialize.rs", "rank": 75, "score": 40241.9377892375 }, { "content": " history.replace(\"/path-b\");\n\n assert_eq!(history.location().path(), \"/path-b\");\n\n assert_eq!(window().location().pathname().unwrap(), \"/\");\n\n assert_eq!(window().location().hash().unwrap(), \"#/path-b\");\n\n\n\n history.back();\n\n sleep(Duration::from_millis(100)).await;\n\n assert_eq!(history.location().path(), \"/\");\n\n assert_eq!(window().location().pathname().unwrap(), \"/\");\n\n assert_eq!(window().location().hash().unwrap(), \"#/\");\n\n\n\n history.forward();\n\n sleep(Duration::from_millis(100)).await;\n\n assert_eq!(history.location().path(), \"/path-b\");\n\n assert_eq!(window().location().pathname().unwrap(), \"/\");\n\n assert_eq!(window().location().hash().unwrap(), \"#/path-b\");\n\n\n\n history\n\n .push_with_query(\n\n \"/path\",\n", "file_path": "crates/history/tests/hash_history_feat_serialize.rs", "rank": 76, "score": 40241.29968201991 }, { "content": " a: String,\n\n b: u64,\n\n }\n\n\n\n #[derive(Debug, Serialize, Deserialize, PartialEq)]\n\n struct State {\n\n i: String,\n\n ii: u64,\n\n }\n\n\n\n #[test]\n\n async fn history_serialize_works() {\n\n let history = HashHistory::new();\n\n assert_eq!(history.location().path(), \"/\");\n\n\n\n history.push(\"/path-a\");\n\n assert_eq!(history.location().path(), \"/path-a\");\n\n assert_eq!(window().location().pathname().unwrap(), \"/\");\n\n assert_eq!(window().location().hash().unwrap(), \"#/path-a\");\n\n\n", "file_path": "crates/history/tests/hash_history_feat_serialize.rs", "rank": 77, "score": 40240.21657065013 }, { "content": "}\n\n\n\nimpl Interval {\n\n /// Schedule an interval to invoke `callback` every `millis` milliseconds.\n\n ///\n\n /// # Example\n\n ///\n\n /// ```no_run\n\n /// use gloo_timers::callback::Interval;\n\n ///\n\n /// let interval = Interval::new(1_000, move || {\n\n /// // Do something...\n\n /// });\n\n /// ```\n\n pub fn new<F>(millis: u32, callback: F) -> Interval\n\n where\n\n F: 'static + FnMut(),\n\n {\n\n let closure = Closure::wrap(Box::new(callback) as Box<dyn FnMut()>);\n\n\n", "file_path": "crates/timers/src/callback.rs", "rank": 78, "score": 35746.95858596572 }, { "content": "\n\n/// A scheduled interval.\n\n///\n\n/// See `Interval::new` for scheduling new intervals.\n\n///\n\n/// Once scheduled, you can either `cancel` so that it ceases to fire or `forget`\n\n/// it so that it is un-cancel-able.\n\n#[derive(Debug)]\n\n#[must_use = \"intervals cancel on drop; either call `forget` or `drop` explicitly\"]\n\npub struct Interval {\n\n id: Option<i32>,\n\n closure: Option<Closure<dyn FnMut()>>,\n\n}\n\n\n\nimpl Drop for Interval {\n\n fn drop(&mut self) {\n\n if let Some(id) = self.id {\n\n clear_interval(id);\n\n }\n\n }\n", "file_path": "crates/timers/src/callback.rs", "rank": 79, "score": 35746.74200032119 }, { "content": "\n\n/// A scheduled timeout.\n\n///\n\n/// See `Timeout::new` for scheduling new timeouts.\n\n///\n\n/// Once scheduled, you can either `cancel` so that it doesn't run or `forget`\n\n/// it so that it is un-cancel-able.\n\n#[derive(Debug)]\n\n#[must_use = \"timeouts cancel on drop; either call `forget` or `drop` explicitly\"]\n\npub struct Timeout {\n\n id: Option<i32>,\n\n closure: Option<Closure<dyn FnMut()>>,\n\n}\n\n\n\nimpl Drop for Timeout {\n\n fn drop(&mut self) {\n\n if let Some(id) = self.id {\n\n clear_timeout(id);\n\n }\n\n }\n", "file_path": "crates/timers/src/callback.rs", "rank": 80, "score": 35746.74200032119 }, { "content": " match self {\n\n Self::Browser(m) => m.replace_with_query(route, query),\n\n Self::Hash(m) => m.replace_with_query(route, query),\n\n Self::Memory(m) => m.replace_with_query(route, query),\n\n }\n\n }\n\n\n\n #[cfg(all(feature = \"query\"))]\n\n fn push_with_query_and_state<'a, Q, T>(\n\n &self,\n\n route: impl Into<Cow<'a, str>>,\n\n query: Q,\n\n state: T,\n\n ) -> HistoryResult<()>\n\n where\n\n Q: Serialize,\n\n T: 'static,\n\n {\n\n match self {\n\n Self::Browser(m) => m.push_with_query_and_state(route, query, state),\n", "file_path": "crates/history/src/any.rs", "rank": 81, "score": 35746.715944059426 }, { "content": " ///\n\n /// ```no_run\n\n /// use gloo_timers::callback::Timeout;\n\n ///\n\n /// // We definitely want to do stuff, and aren't going to ever cancel this\n\n /// // timeout.\n\n /// Timeout::new(1_000, || {\n\n /// // Do stuff...\n\n /// }).forget();\n\n /// ```\n\n pub fn forget(mut self) -> i32 {\n\n let id = self.id.take().unwrap_throw();\n\n self.closure.take().unwrap_throw().forget();\n\n id\n\n }\n\n\n\n /// Cancel this timeout so that the callback is not invoked after the time\n\n /// is up.\n\n ///\n\n /// The scheduled callback is returned.\n", "file_path": "crates/timers/src/callback.rs", "rank": 82, "score": 35746.634887747176 }, { "content": " Self::Hash(m) => m.push_with_query_and_state(route, query, state),\n\n Self::Memory(m) => m.push_with_query_and_state(route, query, state),\n\n }\n\n }\n\n\n\n #[cfg(all(feature = \"query\"))]\n\n fn replace_with_query_and_state<'a, Q, T>(\n\n &self,\n\n route: impl Into<Cow<'a, str>>,\n\n query: Q,\n\n state: T,\n\n ) -> HistoryResult<()>\n\n where\n\n Q: Serialize,\n\n T: 'static,\n\n {\n\n match self {\n\n Self::Browser(m) => m.replace_with_query_and_state(route, query, state),\n\n Self::Hash(m) => m.replace_with_query_and_state(route, query, state),\n\n Self::Memory(m) => m.replace_with_query_and_state(route, query, state),\n", "file_path": "crates/history/src/any.rs", "rank": 83, "score": 35746.356558604 }, { "content": " /// ```no_run\n\n /// use gloo_timers::callback::Interval;\n\n ///\n\n /// // We want to do stuff every second, indefinitely.\n\n /// Interval::new(1_000, || {\n\n /// // Do stuff...\n\n /// }).forget();\n\n /// ```\n\n pub fn forget(mut self) -> i32 {\n\n let id = self.id.take().unwrap_throw();\n\n self.closure.take().unwrap_throw().forget();\n\n id\n\n }\n\n\n\n /// Cancel this interval so that the callback is no longer periodically\n\n /// invoked.\n\n ///\n\n /// The scheduled callback is returned.\n\n ///\n\n /// # Example\n", "file_path": "crates/timers/src/callback.rs", "rank": 84, "score": 35743.90834574693 }, { "content": "}\n\n\n\nimpl Timeout {\n\n /// Schedule a timeout to invoke `callback` in `millis` milliseconds from\n\n /// now.\n\n ///\n\n /// # Example\n\n ///\n\n /// ```no_run\n\n /// use gloo_timers::callback::Timeout;\n\n ///\n\n /// let timeout = Timeout::new(1_000, move || {\n\n /// // Do something...\n\n /// });\n\n /// ```\n\n pub fn new<F>(millis: u32, callback: F) -> Timeout\n\n where\n\n F: 'static + FnOnce(),\n\n {\n\n let closure = Closure::once(callback);\n", "file_path": "crates/timers/src/callback.rs", "rank": 85, "score": 35743.61045311883 }, { "content": " T: 'static,\n\n {\n\n match self {\n\n Self::Browser(m) => m.push_with_state(route, state),\n\n Self::Hash(m) => m.push_with_state(route, state),\n\n Self::Memory(m) => m.push_with_state(route, state),\n\n }\n\n }\n\n\n\n fn replace_with_state<'a, T>(&self, route: impl Into<Cow<'a, str>>, state: T)\n\n where\n\n T: 'static,\n\n {\n\n match self {\n\n Self::Browser(m) => m.replace_with_state(route, state),\n\n Self::Hash(m) => m.replace_with_state(route, state),\n\n Self::Memory(m) => m.replace_with_state(route, state),\n\n }\n\n }\n\n\n", "file_path": "crates/history/src/any.rs", "rank": 86, "score": 35742.16003628318 }, { "content": " ///\n\n /// ```no_run\n\n /// use gloo_timers::callback::Interval;\n\n ///\n\n /// let interval = Interval::new(1_000, || {\n\n /// // Do stuff...\n\n /// });\n\n ///\n\n /// // If we don't want this interval to run anymore, then cancel it.\n\n /// if nevermind() {\n\n /// interval.cancel();\n\n /// }\n\n /// # fn nevermind() -> bool { true }\n\n /// ```\n\n pub fn cancel(mut self) -> Closure<dyn FnMut()> {\n\n self.closure.take().unwrap_throw()\n\n }\n\n}\n", "file_path": "crates/timers/src/callback.rs", "rank": 87, "score": 35742.07431310451 }, { "content": " ///\n\n /// # Example\n\n ///\n\n /// ```no_run\n\n /// use gloo_timers::callback::Timeout;\n\n ///\n\n /// let timeout = Timeout::new(1_000, || {\n\n /// // Do stuff...\n\n /// });\n\n ///\n\n /// // If actually we didn't want to set a timer, then cancel it.\n\n /// if nevermind() {\n\n /// timeout.cancel();\n\n /// }\n\n /// # fn nevermind() -> bool { true }\n\n /// ```\n\n pub fn cancel(mut self) -> Closure<dyn FnMut()> {\n\n self.closure.take().unwrap_throw()\n\n }\n\n}\n", "file_path": "crates/timers/src/callback.rs", "rank": 88, "score": 35741.671304222866 }, { "content": " #[cfg(feature = \"query\")]\n\n fn push_with_query<'a, Q>(&self, route: impl Into<Cow<'a, str>>, query: Q) -> HistoryResult<()>\n\n where\n\n Q: Serialize,\n\n {\n\n match self {\n\n Self::Browser(m) => m.push_with_query(route, query),\n\n Self::Hash(m) => m.push_with_query(route, query),\n\n Self::Memory(m) => m.push_with_query(route, query),\n\n }\n\n }\n\n #[cfg(feature = \"query\")]\n\n fn replace_with_query<'a, Q>(\n\n &self,\n\n route: impl Into<Cow<'a, str>>,\n\n query: Q,\n\n ) -> HistoryResult<()>\n\n where\n\n Q: Serialize,\n\n {\n", "file_path": "crates/history/src/any.rs", "rank": 89, "score": 35741.48121288631 }, { "content": " }\n\n\n\n fn push<'a>(&self, route: impl Into<Cow<'a, str>>) {\n\n match self {\n\n Self::Browser(m) => m.push(route),\n\n Self::Hash(m) => m.push(route),\n\n Self::Memory(m) => m.push(route),\n\n }\n\n }\n\n\n\n fn replace<'a>(&self, route: impl Into<Cow<'a, str>>) {\n\n match self {\n\n Self::Browser(m) => m.replace(route),\n\n Self::Hash(m) => m.replace(route),\n\n Self::Memory(m) => m.replace(route),\n\n }\n\n }\n\n\n\n fn push_with_state<'a, T>(&self, route: impl Into<Cow<'a, str>>, state: T)\n\n where\n", "file_path": "crates/history/src/any.rs", "rank": 90, "score": 35741.164042912606 }, { "content": " Hash(HashHistory),\n\n /// A Memory History\n\n Memory(MemoryHistory),\n\n}\n\n\n\nimpl History for AnyHistory {\n\n fn len(&self) -> usize {\n\n match self {\n\n Self::Browser(m) => m.len(),\n\n Self::Hash(m) => m.len(),\n\n Self::Memory(m) => m.len(),\n\n }\n\n }\n\n\n\n fn go(&self, delta: isize) {\n\n match self {\n\n Self::Browser(m) => m.go(delta),\n\n Self::Hash(m) => m.go(delta),\n\n Self::Memory(m) => m.go(delta),\n\n }\n", "file_path": "crates/history/src/any.rs", "rank": 91, "score": 35737.64917940936 }, { "content": " let id = set_interval(\n\n closure.as_ref().unchecked_ref::<js_sys::Function>(),\n\n millis as i32,\n\n )\n\n .unwrap_throw();\n\n\n\n Interval {\n\n id: Some(id),\n\n closure: Some(closure),\n\n }\n\n }\n\n\n\n /// Make this interval uncancel-able.\n\n ///\n\n /// Returns the identifier returned by the original `setInterval` call, and\n\n /// therefore you can still cancel the interval by calling `clearInterval`\n\n /// directly (perhaps via `web_sys::clear_interval_with_handle`).\n\n ///\n\n /// # Example\n\n ///\n", "file_path": "crates/timers/src/callback.rs", "rank": 92, "score": 35730.501660437716 }, { "content": "\n\n let id = set_timeout(\n\n closure.as_ref().unchecked_ref::<js_sys::Function>(),\n\n millis as i32,\n\n )\n\n .unwrap_throw();\n\n\n\n Timeout {\n\n id: Some(id),\n\n closure: Some(closure),\n\n }\n\n }\n\n\n\n /// Make this timeout uncancel-able.\n\n ///\n\n /// Returns the identifier returned by the original `setTimeout` call, and\n\n /// therefore you can still cancel the timeout by calling `clearTimeout`\n\n /// directly (perhaps via `web_sys::clear_timeout_with_handle`).\n\n ///\n\n /// # Example\n", "file_path": "crates/timers/src/callback.rs", "rank": 93, "score": 35730.501660437716 }, { "content": "//! Callback-style timer APIs.\n\n\n\nuse js_sys::Function;\n\nuse wasm_bindgen::prelude::*;\n\nuse wasm_bindgen::{JsCast, JsValue};\n\n\n\n#[wasm_bindgen]\n\nextern \"C\" {\n\n #[wasm_bindgen(js_name = \"setTimeout\", catch)]\n\n fn set_timeout(handler: &Function, timeout: i32) -> Result<i32, JsValue>;\n\n\n\n #[wasm_bindgen(js_name = \"setInterval\", catch)]\n\n fn set_interval(handler: &Function, timeout: i32) -> Result<i32, JsValue>;\n\n\n\n #[wasm_bindgen(js_name = \"clearTimeout\")]\n\n fn clear_timeout(handle: i32);\n\n\n\n #[wasm_bindgen(js_name = \"clearInterval\")]\n\n fn clear_interval(handle: i32);\n\n}\n", "file_path": "crates/timers/src/callback.rs", "rank": 94, "score": 35730.177563002304 }, { "content": " }\n\n }\n\n\n\n fn listen<CB>(&self, callback: CB) -> HistoryListener\n\n where\n\n CB: Fn() + 'static,\n\n {\n\n match self {\n\n Self::Browser(m) => m.listen(callback),\n\n Self::Hash(m) => m.listen(callback),\n\n Self::Memory(m) => m.listen(callback),\n\n }\n\n }\n\n\n\n fn location(&self) -> Location {\n\n match self {\n\n Self::Browser(m) => m.location(),\n\n Self::Hash(m) => m.location(),\n\n Self::Memory(m) => m.location(),\n\n }\n", "file_path": "crates/history/src/any.rs", "rank": 95, "score": 35728.43140416142 }, { "content": "use std::borrow::Cow;\n\n\n\n#[cfg(feature = \"query\")]\n\nuse serde::Serialize;\n\n\n\nuse crate::browser::BrowserHistory;\n\n#[cfg(feature = \"query\")]\n\nuse crate::error::HistoryResult;\n\nuse crate::hash::HashHistory;\n\nuse crate::history::History;\n\nuse crate::listener::HistoryListener;\n\nuse crate::location::Location;\n\nuse crate::memory::MemoryHistory;\n\n\n\n/// A [`History`] that provides a universial API to the underlying history type.\n\n#[derive(Clone, PartialEq, Debug)]\n\npub enum AnyHistory {\n\n /// A Browser History.\n\n Browser(BrowserHistory),\n\n /// A Hash History\n", "file_path": "crates/history/src/any.rs", "rank": 96, "score": 35725.210055003525 }, { "content": " }\n\n}\n\n\n\nimpl From<BrowserHistory> for AnyHistory {\n\n fn from(m: BrowserHistory) -> AnyHistory {\n\n AnyHistory::Browser(m)\n\n }\n\n}\n\n\n\nimpl From<HashHistory> for AnyHistory {\n\n fn from(m: HashHistory) -> AnyHistory {\n\n AnyHistory::Hash(m)\n\n }\n\n}\n\n\n\nimpl From<MemoryHistory> for AnyHistory {\n\n fn from(m: MemoryHistory) -> AnyHistory {\n\n AnyHistory::Memory(m)\n\n }\n\n}\n", "file_path": "crates/history/src/any.rs", "rank": 97, "score": 35719.71852378425 }, { "content": "fn send_to_remote<W>(worker: &web_sys::Worker, msg: ToWorker<W::Input>)\n\nwhere\n\n W: Worker,\n\n <W as Worker>::Input: Serialize + for<'de> Deserialize<'de>,\n\n <W as Worker>::Output: Serialize + for<'de> Deserialize<'de>,\n\n{\n\n let msg = msg.pack();\n\n worker.post_message_vec(msg);\n\n}\n", "file_path": "crates/worker/src/worker/mod.rs", "rank": 98, "score": 34611.11019835299 } ]
Rust
src/transformers/dominance.rs
EclecticGriffin/Bril-Toolkit
a72ce7a7d2ca235ec9e544a713638df408d1828c
use super::cfg::{Node, Block}; use crate::serde_structs::structs::{Instr, Label}; use std::rc::{Rc, Weak}; use std::collections::{HashMap, HashSet}; use crate::analysis::dehydrated::{set_intersection, set_union}; use std::collections::VecDeque; fn reverse_post_order(root: &Rc<Node>) -> Vec<Rc<Node>> { let mut process_queue = Vec::<Rc<Node>>::new(); let mut exit_queue = Vec::<Rc<Node>>::new(); process_queue.push(root.clone()); while let Some(current) = process_queue.last() { let successors = current.successor_refs(); if successors.is_empty() { exit_queue.push(process_queue.pop().unwrap()); } else { let not_processed: Vec<&Rc<Node>> = successors.iter().filter(|x| !exit_queue.contains(x) && *x != current).collect(); if not_processed.is_empty() { exit_queue.push(process_queue.pop().unwrap()); } else if not_processed.iter().all(|x| process_queue.contains(x)) { exit_queue.push(process_queue.pop().unwrap()); } else { for item in not_processed.into_iter() { if !process_queue.contains(item) { process_queue.push(item.clone()); } } } } } exit_queue.reverse(); exit_queue } pub fn determine_dominators(nodes: &[Rc<Node>]) -> HashMap<Label, HashSet<Label>> { let mut label_map = HashMap::<Label, HashSet<Label>>::new(); let ordering = reverse_post_order(&nodes[0]); { let mut dom_set = HashSet::<Label>::new(); for node in ordering.iter() { dom_set.insert(node.label()); } for node in ordering.iter(){ label_map.insert(node.label(), dom_set.clone()); } } let mut changed = true; while changed { changed = false; for node in ordering.iter() { let preds = node.predecessor_labels(); let sets: Vec<&HashSet<Label>> = preds.into_iter().map(|x| {&label_map[&x]}).collect(); let intersect = set_intersection(sets); let mut current = HashSet::<Label>::with_capacity(1); current.insert(node.label()); let new_value = set_union(vec! [&intersect, &current ]); if new_value != label_map[&node.label()] { changed = true; label_map.insert(node.label(), new_value); } } } label_map } pub struct DominanceTree { nodes: HashMap<Label, Rc<Node>>, dominated_map: HashMap<Label, HashSet<Label>>, dom_tree: HashMap<Label, Vec<Label>>, root_label: Label } impl DominanceTree { pub fn new(nodes: &[Rc<Node>]) -> Self { let mut node_map = HashMap::<Label, Rc<Node>>::new(); for node in nodes { node_map.insert(node.label(), node.clone()); } let (dom_tree, dominated_map) = construct_dominance_tree(nodes); DominanceTree { nodes: node_map, dom_tree, dominated_map, root_label: nodes[0].label() } } pub fn lookup_node(&self, label: &Label) -> &Rc<Node> { &self.nodes[label] } pub fn root_node(&self) -> &Rc<Node> { self.lookup_node(&self.root_label) } pub fn get_children(&self, label: &Label) -> Vec<Rc<Node>> { self.dom_tree[label].iter() .map(|x| {self.lookup_node(x)}) .cloned() .collect() } pub fn compute_frontier(&self, target_label: &Label) -> Vec<Label> { let mut processing_queue: Vec<Label> = self.lookup_node(target_label).successor_labels(); let mut frontier = Vec::<Label>::new(); let mut processed: HashSet<Label> = HashSet::new(); processed.insert(*target_label); while let Some(current) = processing_queue.pop() { if self.dominated_map[&current].contains(target_label) { processed.insert(current); for successor_label in self.lookup_node(&current).successor_labels() { if !processed.contains(&successor_label) { processing_queue.push(successor_label); } else if successor_label == *target_label && !frontier.contains(target_label) { frontier.push(successor_label); } } } else { frontier.push(current); } } frontier } } fn construct_dominance_tree(nodes: &[Rc<Node>]) -> (HashMap<Label, Vec<Label>>, HashMap<Label, HashSet<Label>>){ let dominance_map = determine_dominators(nodes); let mut label_map = HashMap::<Label, Rc<Node>>::new(); let mut immediate_dominance_map = HashMap::<Label, Vec<Label>>::new(); for node in nodes { label_map.insert(node.label(), node.clone()); immediate_dominance_map.insert(node.label(), Vec::new()); } for node in nodes { for successor_label in node.successor_refs().iter().map(|x| x.label()) { if dominance_map[&successor_label].contains(&node.label()) && node.label() != successor_label { immediate_dominance_map.get_mut(&node.label()).unwrap().push(successor_label); } } } (immediate_dominance_map, dominance_map) }
use super::cfg::{Node, Block}; use crate::serde_structs::structs::{Instr, Label}; use std::rc::{Rc, Weak}; use std::collections::{HashMap, HashSet}; use crate::analysis::dehydrated::{set_intersection, set_union}; use std::collections::VecDeque; fn reverse_post_order(root: &Rc<Node>) -> Vec<Rc<Node>> { let mut process_queue = Vec::<Rc<Node>>::new(); let mut exit_queue = Vec::<Rc<Node>>::new(); process_queue.push(root.clone()); while let Some(current) = process_queue.last() { let successors = current.successor_refs(); if successors.is_empty() { exit_queue.push(process_queue.pop().unwrap()); } else { let not_processed: Vec<&Rc<Node>> = successors.iter().filter(|x| !exit_queue.contains(x) && *x != current).collect(); if not_processed.is_empty() { exit_queue.push(process_queue.pop().unwrap()); } else if not_processed.iter().all(|x| process_queue.contains(x)) { exit_queue.push(process_queue.pop().unwrap()); } else { for item in not_processed.into_iter() { if !process_queue.contains(item) { process_queue.push(item.clone()); } } } } } exit_queue.reverse(); exit_queue } pub fn determine_dominators(nodes: &[Rc<Node>]) -> HashMap<Label, HashSet<Label>> { let mut label_map = HashMap::<Label, HashSet<Label>>::new(); le
pub struct DominanceTree { nodes: HashMap<Label, Rc<Node>>, dominated_map: HashMap<Label, HashSet<Label>>, dom_tree: HashMap<Label, Vec<Label>>, root_label: Label } impl DominanceTree { pub fn new(nodes: &[Rc<Node>]) -> Self { let mut node_map = HashMap::<Label, Rc<Node>>::new(); for node in nodes { node_map.insert(node.label(), node.clone()); } let (dom_tree, dominated_map) = construct_dominance_tree(nodes); DominanceTree { nodes: node_map, dom_tree, dominated_map, root_label: nodes[0].label() } } pub fn lookup_node(&self, label: &Label) -> &Rc<Node> { &self.nodes[label] } pub fn root_node(&self) -> &Rc<Node> { self.lookup_node(&self.root_label) } pub fn get_children(&self, label: &Label) -> Vec<Rc<Node>> { self.dom_tree[label].iter() .map(|x| {self.lookup_node(x)}) .cloned() .collect() } pub fn compute_frontier(&self, target_label: &Label) -> Vec<Label> { let mut processing_queue: Vec<Label> = self.lookup_node(target_label).successor_labels(); let mut frontier = Vec::<Label>::new(); let mut processed: HashSet<Label> = HashSet::new(); processed.insert(*target_label); while let Some(current) = processing_queue.pop() { if self.dominated_map[&current].contains(target_label) { processed.insert(current); for successor_label in self.lookup_node(&current).successor_labels() { if !processed.contains(&successor_label) { processing_queue.push(successor_label); } else if successor_label == *target_label && !frontier.contains(target_label) { frontier.push(successor_label); } } } else { frontier.push(current); } } frontier } } fn construct_dominance_tree(nodes: &[Rc<Node>]) -> (HashMap<Label, Vec<Label>>, HashMap<Label, HashSet<Label>>){ let dominance_map = determine_dominators(nodes); let mut label_map = HashMap::<Label, Rc<Node>>::new(); let mut immediate_dominance_map = HashMap::<Label, Vec<Label>>::new(); for node in nodes { label_map.insert(node.label(), node.clone()); immediate_dominance_map.insert(node.label(), Vec::new()); } for node in nodes { for successor_label in node.successor_refs().iter().map(|x| x.label()) { if dominance_map[&successor_label].contains(&node.label()) && node.label() != successor_label { immediate_dominance_map.get_mut(&node.label()).unwrap().push(successor_label); } } } (immediate_dominance_map, dominance_map) }
t ordering = reverse_post_order(&nodes[0]); { let mut dom_set = HashSet::<Label>::new(); for node in ordering.iter() { dom_set.insert(node.label()); } for node in ordering.iter(){ label_map.insert(node.label(), dom_set.clone()); } } let mut changed = true; while changed { changed = false; for node in ordering.iter() { let preds = node.predecessor_labels(); let sets: Vec<&HashSet<Label>> = preds.into_iter().map(|x| {&label_map[&x]}).collect(); let intersect = set_intersection(sets); let mut current = HashSet::<Label>::with_capacity(1); current.insert(node.label()); let new_value = set_union(vec! [&intersect, &current ]); if new_value != label_map[&node.label()] { changed = true; label_map.insert(node.label(), new_value); } } } label_map }
function_block-function_prefixed
[ { "content": "pub fn connect_basic_blocks(blocks: &mut Vec<Rc<Node>>) {\n\n let map = construct_label_lookup(blocks);\n\n let mut second_iter = blocks.iter();\n\n second_iter.next();\n\n\n\n for (current, node) in blocks.iter().zip(second_iter) {\n\n connect_block(current, node, &map)\n\n }\n\n\n\n connect_terminal_block(blocks.last().unwrap(), &map);\n\n let mut replacement_map: HashMap<Label, Weak<Node>> = HashMap::new();\n\n\n\n for node in blocks.iter() {\n\n if let Some(Link::Fallthrough(x)) = &*node.out.borrow() {\n\n if node.block_label().is_some() && node.contents.borrow().0.len() == 1 {\n\n replacement_map.insert(node.label(), x.clone());\n\n }\n\n }\n\n }\n\n let mut update: Vec<(Label,Label)> = Vec::new();\n", "file_path": "src/transformers/cfg.rs", "rank": 0, "score": 140082.00633168936 }, { "content": "pub fn construct_basic_blocks(instrs: Vec<Instr>) -> Vec<Block> {\n\n let mut output = Vec::<Block>::new();\n\n let mut cur_block = Vec::<Instr>::new();\n\n for instr in instrs.into_iter() {\n\n if instr.is_label() {\n\n if !cur_block.is_empty() {\n\n output.push(Block::new(cur_block));\n\n }\n\n cur_block = vec![instr];\n\n } else if instr.is_terminator() {\n\n cur_block.push(instr);\n\n output.push(Block::new(cur_block));\n\n cur_block = Vec::<Instr>::new();\n\n } else {\n\n cur_block.push(instr);\n\n }\n\n }\n\n if !cur_block.is_empty() {\n\n output.push(Block::new(cur_block));\n\n }\n\n output\n\n}\n\n\n", "file_path": "src/transformers/cfg.rs", "rank": 2, "score": 119143.84992008278 }, { "content": "pub fn run_lvn(instrs: &mut Vec<Instr>) {\n\n // eprintln!(\"{:?}\", instrs);\n\n force_unique_names(instrs);\n\n // for instr in instrs.iter(){\n\n // eprintln!(\"{}\", instr);\n\n // }\n\n // eprintln!(\"\\n\\n\\n\");\n\n\n\n let mut tbl = Table::new();\n\n\n\n for instr in instrs.iter_mut() {\n\n tbl.rewrite(instr)\n\n }\n\n}\n\n\n", "file_path": "src/transformers/lvn.rs", "rank": 3, "score": 117333.66538358995 }, { "content": "pub fn trivial_global_dce(nodes: &mut Vec<Instr>) {\n\n let mut repeat = true;\n\n\n\n while repeat {\n\n let mut used = HashSet::<Var>::new();\n\n let mut defined = HashSet::<Var>::new();\n\n\n\n for instr in nodes.iter() {\n\n match instr {\n\n Instr::Const { dest, .. } => { defined.insert(*dest); }\n\n Instr::Value { dest, args,.. } => {\n\n defined.insert(*dest);\n\n for arg in args.iter() {\n\n used.insert(*arg);\n\n }}\n\n Instr::Effect { args,.. } => {\n\n for arg in args.iter() {\n\n used.insert(*arg);\n\n }\n\n }\n", "file_path": "src/transformers/dce.rs", "rank": 4, "score": 115010.1280644535 }, { "content": "pub fn from_ssa(nodes: &mut Vec<Rc<Node>>) {\n\n let mut label_map: HashMap<Label, Rc<Node>> = HashMap::new();\n\n\n\n for node in nodes.iter() {\n\n node.clear_predecessors();\n\n label_map.insert(node.label(), node.clone());\n\n }\n\n\n\n let mut new_nodes: Vec<Rc<Node>> = Vec::new();\n\n let mut fix_list: Vec<(Label, Rc<Node>)> = Vec::new();\n\n\n\n let mut new_nodes_map: HashMap<(Label, Label), Rc<Node>> = HashMap::new();\n\n\n\n for node in nodes.iter_mut() {\n\n let block = &mut *node.contents.borrow_mut();\n\n // let mut correction_list: Vec<> = vec! [];\n\n\n\n for instr in block.0.iter_mut() {\n\n if let Instr::Value {op: Op::Phi, args, labels, dest, r_type,..} = instr {\n\n for (var, label) in args.iter().zip(labels.iter()) {\n", "file_path": "src/transformers/ssa.rs", "rank": 5, "score": 114413.26340482442 }, { "content": "pub fn to_ssa(nodes: &mut Vec<Rc<Node>>, headers: &[FnHeaders]) {\n\n for node in nodes.iter() {\n\n node.normalize()\n\n }\n\n let (dom_tree, mut def_map) = insert_phi_nodes(&mut nodes[..], headers);\n\n\n\n let mut stack = RenameStack::new(def_map.keys(), headers);\n\n let header_vars: Vec<Var> = headers.iter().map(|x|x.name).collect();\n\n\n\n rename(&mut nodes[0], &dom_tree, &mut stack, &header_vars[..])\n\n}\n\n\n", "file_path": "src/transformers/ssa.rs", "rank": 6, "score": 111616.18398884322 }, { "content": "pub fn repair_predecessor_links(nodes: &mut Vec<Rc<Node>>) {\n\n let mut label_map: HashMap<Label, Rc<Node>> = HashMap::new();\n\n\n\n for node in nodes.iter() {\n\n match &*node.out.borrow() {\n\n Some(x) => {\n\n match x {\n\n Link::Fallthrough(successor)\n\n | Link::Jump(successor) => {\n\n successor.upgrade().unwrap().predecessors.borrow_mut().push(Rc::downgrade(node));\n\n }\n\n Link::Branch { true_branch, false_branch } => {\n\n true_branch.upgrade().unwrap().predecessors.borrow_mut().push(Rc::downgrade(node));\n\n false_branch.upgrade().unwrap().predecessors.borrow_mut().push(Rc::downgrade(node));\n\n }\n\n _ => {}\n\n }\n\n }\n\n None => {}\n\n }\n", "file_path": "src/transformers/cfg.rs", "rank": 7, "score": 109920.45159782642 }, { "content": "pub fn construct_cfg_nodes(instrs: Vec<Block>) -> Vec<Rc<Node>> {\n\n instrs.into_iter().map(|x|{Rc::new(\n\n Node::from_block(x)\n\n )}).collect()\n\n}\n\n\n", "file_path": "src/transformers/cfg.rs", "rank": 8, "score": 105626.97804034779 }, { "content": "pub fn remove_inaccessible_blocks(blocks: Vec<Rc<Node>>) -> Vec<Rc<Node>> {\n\n let _root = Rc::downgrade(&blocks[0]);\n\n (blocks).into_iter().filter(|x| {Rc::weak_count(x) > x.successor_count()}).collect()\n\n}\n", "file_path": "src/transformers/orphan.rs", "rank": 10, "score": 95235.26518840363 }, { "content": "fn construct_label_lookup(blocks: &[Rc<Node>]) -> LabelMap {\n\n let mut map = LabelMap::new();\n\n for node in blocks.iter() {\n\n if node.is_labeled() {\n\n map.insert(node.block_label().unwrap(), Rc::clone(node));\n\n }\n\n }\n\n map\n\n}\n\n\n", "file_path": "src/transformers/cfg.rs", "rank": 11, "score": 90871.37218910517 }, { "content": "fn connect_terminal_block( last_block: &Rc<Node>, map: &LabelMap) {\n\n let instrs = &last_block.contents.borrow();\n\n let last = instrs.last();\n\n\n\n match last {\n\n Instr::Value { op, labels, .. } | Instr::Effect { op, labels, .. } => match op {\n\n Op::Jmp => {\n\n let target = &labels[0];\n\n let target_ref = map.get(&target).unwrap_or_else(|| {\n\n panic!(\n\n \"Unable to locate label {}\",\n\n namer().get_string(&(target.0))\n\n )\n\n });\n\n last_block\n\n .out\n\n .replace(Some(Link::Jump(Rc::downgrade(target_ref))));\n\n let mut vec_cell = target_ref.predecessors.borrow_mut();\n\n vec_cell.push(Rc::downgrade(last_block));\n\n return;\n", "file_path": "src/transformers/cfg.rs", "rank": 12, "score": 85608.65402599331 }, { "content": "pub fn local_dce(node: &Node) {\n\n let mut block = node.contents.borrow_mut();\n\n let tmp = std::mem::replace(&mut block.0, Vec::new());\n\n block.0 = trivial_local_dce(tmp);\n\n}\n\n\n\n\n", "file_path": "src/transformers/dce.rs", "rank": 13, "score": 85142.05851105647 }, { "content": "// based entirely on how stdin is handled\n\npub fn namer() -> NameReader {\n\n static mut NAMEREADER: *const NameReader = 0 as *const NameReader;\n\n static ONCE: Once = Once::new();\n\n\n\n unsafe {\n\n ONCE.call_once(|| {\n\n let reader = NameReader::new();\n\n NAMEREADER = transmute(Box::new(reader)); // !!!!\n\n });\n\n (*NAMEREADER).clone()\n\n }\n\n}\n", "file_path": "src/serde_structs/names/name_mapper.rs", "rank": 14, "score": 84539.82956455866 }, { "content": "fn identify_definitions(nodes: &[Rc<Node>], headers: &[FnHeaders]) -> HashMap<Var, (HashSet<Label>, Type)> {\n\n let mut var_map: HashMap<Var, (HashSet<Label>, Type)> = HashMap::new();\n\n {\n\n let contents: &mut Block = &mut nodes[0].contents.borrow_mut();\n\n\n\n for header in headers {\n\n let mut set = HashSet::<Label>::with_capacity(1);\n\n set.insert(nodes[0].label());\n\n var_map.insert(header.name, (set, header.r_type.clone()));\n\n contents.0.insert(1, Instr::Value {\n\n op: Op::Id,\n\n dest: header.name,\n\n r_type: header.r_type.clone(),\n\n args: vec! [header.name],\n\n funcs: Vec::new(),\n\n labels: Vec::new(),\n\n\n\n })\n\n }\n\n}\n", "file_path": "src/transformers/ssa.rs", "rank": 15, "score": 82315.24075241585 }, { "content": "fn force_unique_names(instrs: &mut Vec<Instr>) {\n\n let name_reader = namer();\n\n let mut new_mapping = HashMap::<Var, Vec<(RangeInclusive<usize>, Var)>>::new();\n\n let mut prev_defn = HashMap::<Var, usize>::new();\n\n\n\n for (idx, instr) in instrs.iter().enumerate() {\n\n match instr {\n\n Instr::Const { dest, .. } | Instr::Value { dest, .. } => {\n\n if prev_defn.contains_key(dest) && new_mapping.contains_key(dest) {\n\n let prior_marker = prev_defn.remove(dest).unwrap();\n\n let fresh = name_reader.fresh(&dest.0);\n\n\n\n new_mapping\n\n .get_mut(dest)\n\n .unwrap()\n\n .push((prior_marker..=idx, Var(fresh)));\n\n prev_defn.insert(*dest, idx);\n\n } else if prev_defn.contains_key(dest) {\n\n let prior_marker = prev_defn.remove(dest).unwrap();\n\n let fresh = name_reader.fresh(&dest.0);\n", "file_path": "src/transformers/lvn.rs", "rank": 16, "score": 80049.4631554822 }, { "content": "fn apply_transformations(mut prog: Program, conf: ConfigOptions) -> Program {\n\n\n\n if conf.g_tdce {\n\n // eprintln!(\"Applying trivial global dce\");\n\n for fun in prog.functions.iter_mut() {\n\n fun.g_tcde()\n\n }\n\n }\n\n\n\n if conf.lvn.run_lvn() || conf.l_tdce || conf.orphan_block || conf.to_ssa\n\n || conf.from_ssa {\n\n let mut cfg = prog.determine_cfg();\n\n // for fun in cfg.functions.iter() {\n\n // eprintln!(\"{:?}\", fun)\n\n // }\n\n // eprintln!(\"\\n\\n\\n\\n\\n\");\n\n if conf.orphan_block {\n\n // eprintln!(\"Applying orphan block removal\");\n\n for fun in cfg.functions.iter_mut() {\n\n fun.drop_orphan_blocks()\n", "file_path": "src/main.rs", "rank": 17, "score": 74386.07931981288 }, { "content": "fn rename(node: &mut Rc<Node>, dom_tree: &DominanceTree, stack: &mut RenameStack, headers: &[Var]) {\n\n stack.increase_layer();\n\n {\n\n let contents: &mut Block = &mut node.contents.borrow_mut();\n\n let block = &mut contents.0;\n\n for instr in block.iter_mut() {\n\n match instr {\n\n // Constants will only define a new name\n\n Instr::Const { dest, .. } => {\n\n let new_name = Var(namer().fresh(&dest.0));\n\n stack.push_var(dest, new_name);\n\n *dest = new_name;\n\n\n\n }\n\n // Phi instrs we only update the new name, not the args\n\n Instr::Value {\n\n op: Op::Phi, dest, ..\n\n } => {\n\n let new_name = Var(namer().fresh(&dest.0));\n\n stack.push_var(dest, new_name);\n", "file_path": "src/transformers/ssa.rs", "rank": 18, "score": 74222.69263955261 }, { "content": "fn connect_block(current: &Rc<Node>, node: &Rc<Node>, map: &LabelMap) {\n\n if current.out.borrow().is_some() {\n\n return;\n\n }\n\n\n\n let instrs = &current.contents.borrow();\n\n let last = instrs.last();\n\n let (op, labels) = match last {\n\n Instr::Value { op, labels, .. } | Instr::Effect { op, labels, .. } => (op, labels),\n\n _ => {\n\n current\n\n .out\n\n .replace(Some(Link::Fallthrough(Rc::downgrade(node))));\n\n let mut vec_cell = node.predecessors.borrow_mut();\n\n vec_cell.push(Rc::downgrade(current));\n\n\n\n return;\n\n }\n\n };\n\n match op {\n", "file_path": "src/transformers/cfg.rs", "rank": 19, "score": 72406.86883900533 }, { "content": "pub fn trivial_local_dce(instrs: Vec<Instr>) -> Vec<Instr> {\n\n\n\n let mut used = HashSet::<Var>::new();\n\n let mut defined = HashSet::<Var>::new();\n\n\n\n // this feels like a crime\n\n let mut i: Vec<Instr> = instrs.into_iter().rev().map(|x| -> (bool, Instr) {\n\n match x {\n\n Instr::Const {ref dest, .. } => {\n\n if used.contains(dest) {\n\n used.remove(dest);\n\n (true, x)\n\n } else if defined.contains(dest) {\n\n (false, x)\n\n } else {\n\n defined.insert(*dest);\n\n (true, x)\n\n }\n\n },\n\n Instr::Value {ref dest, ref args, ..} => {\n", "file_path": "src/transformers/dce.rs", "rank": 20, "score": 72229.20905395613 }, { "content": "fn transfer(input: &Data, instrs: &Block, idx: usize) -> Data {\n\n let mut out = Data::new();\n\n\n\n for instr in instrs.0.iter() {\n\n match instr {\n\n Instr::Const { dest, .. } | Instr::Value { dest, .. } => {\n\n let new = VarDef(*dest, idx);\n\n out.retain(|x| {x.0 != *dest});\n\n out.insert(new);\n\n }\n\n _ => {}\n\n }\n\n }\n\n input.union(&out).cloned().collect()\n\n}\n\n\n", "file_path": "src/analysis/reaching_defns.rs", "rank": 21, "score": 71559.09083893907 }, { "content": "fn transfer(input: &Data, instrs: &Block, _idx: usize) -> Data {\n\n let mut used_vars = Data::new();\n\n let mut killed = Data::new();\n\n\n\n for instr in instrs.0.iter() {\n\n match instr {\n\n Instr::Const { dest, ..} => {\n\n killed.insert(*dest);\n\n }\n\n Instr::Value { dest, args, .. } => {\n\n for arg in args.iter() {\n\n if !killed.contains(arg) {\n\n used_vars.insert(*arg);\n\n }\n\n }\n\n killed.insert(*dest);\n\n }\n\n Instr::Effect { args, ..} => {\n\n for arg in args.iter() {\n\n if !killed.contains(arg) {\n", "file_path": "src/analysis/live_vars.rs", "rank": 22, "score": 71559.09083893907 }, { "content": "pub fn reaching_definitions(nodes: &[Rc<Node>], initial: &[FnHeaders] ) -> Vec<AnalysisNode<Data>> {\n\n\n\n\n\n let fake_node = Node::dummy_block(\n\n RefCell::new(Block(initial.iter().map(|x| x.generate_dummy_instrs()).collect())),\n\n RefCell::new(Some(Link::Fallthrough(Rc::downgrade(&nodes[0])))),\n\n RefCell::new(Vec::new()),\n\n RefCell::new(None),\n\n );\n\n\n\n let mut input_nodes = Vec::<Rc<Node>>::new();\n\n input_nodes.push(Rc::new(fake_node));\n\n for node in nodes {\n\n input_nodes.push(node.clone())\n\n }\n\n\n\n {\n\n let mut fall = input_nodes[1].predecessors.borrow_mut();\n\n fall.push(Rc::downgrade(&input_nodes[0]));\n\n }\n\n\n\n worklist_solver(&input_nodes, Data::new(), transfer, set_union, Direction::Forward)\n\n}\n", "file_path": "src/analysis/reaching_defns.rs", "rank": 23, "score": 70230.65554019007 }, { "content": "pub fn live_variables(nodes: &[Rc<Node>]) -> Vec<AnalysisNode<Data>> {\n\n worklist_solver(nodes, Data::new(), transfer, set_union, Direction::Backward)\n\n}\n", "file_path": "src/analysis/live_vars.rs", "rank": 24, "score": 67936.20702937536 }, { "content": "pub fn worklist_solver<D, T, M>(nodes: &[Rc<Node>], initial_value: D, transfer_fn: T,\n\n merge_fn: M, direction: Direction) -> Vec<AnalysisNode<D>>\n\n where T:Fn(&D, &Block, usize) -> D, M:Fn(Vec<&D>) -> D, D: Clone + PartialEq + Debug {\n\n let mut analysis_nodes = Vec::<AnalysisNode<D>>::new();\n\n\n\n for (idx, node) in nodes.iter().enumerate() {\n\n node.idx.replace(Some(idx));\n\n }\n\n\n\n for (idx, node) in nodes.iter().enumerate() {\n\n analysis_nodes.push(AnalysisNode {\n\n in_data: initial_value.clone(),\n\n out_data: initial_value.clone(),\n\n program_node: Rc::clone(node),\n\n predecessors: Vec::new(),\n\n successors: Vec::new()\n\n });\n\n let pred_ref = node.predecessors.borrow();\n\n let preds: Vec<usize> = pred_ref.iter().map(|x| -> usize {\n\n let upgraded = x.upgrade().unwrap();\n", "file_path": "src/analysis/dataflow_core.rs", "rank": 25, "score": 65847.6495359871 }, { "content": "fn main() {\n\n let matches = App::new(\"Bril Toolkit\").version(\"0.1\")\n\n .author(\"Griffin Berlstein <[email protected]>\")\n\n .about(\"A toolkit for bril transformations\")\n\n .subcommand(\n\n SubCommand::with_name(\"transform\")\n\n .version(\"0.1\")\n\n .author(\"Griffin Berlstein <[email protected]>\")\n\n .about(\"Apply transformations to a bril program\")\n\n .arg(Arg::with_name(\"optimizations\")\n\n .short(\"o\")\n\n .long(\"optimizations\")\n\n .multiple(true)\n\n .takes_value(true)\n\n .possible_values(&transformers::config::ALLOWED_VALUES)\n\n ))\n\n .subcommand(\n\n SubCommand::with_name(\"analyze\")\n\n .version(\"0.1\")\n\n .author(\"Griffin Berlstein <[email protected]>\")\n", "file_path": "src/main.rs", "rank": 26, "score": 51995.16827982105 }, { "content": "type LabelMap = HashMap<Label, Rc<Node>>;\n\n\n\n#[derive(Debug, Default)]\n\npub struct Block(pub Vec<Instr>);\n\n\n\nimpl Block {\n\n pub fn new(input: Vec<Instr>) -> Self {\n\n Block(input)\n\n }\n\n\n\n pub fn is_empty(&self) -> bool {\n\n self.0.is_empty()\n\n }\n\n\n\n pub fn label(&self) -> Option<Label> {\n\n self.0.get(0)?.extract_label()\n\n }\n\n\n\n pub fn last(&self) -> &Instr {\n\n self.0.last().unwrap()\n", "file_path": "src/transformers/cfg.rs", "rank": 27, "score": 50705.67463959863 }, { "content": "fn insert_phi_nodes(\n\n nodes: &mut [Rc<Node>], headers: &[FnHeaders]\n\n) -> (DominanceTree, HashMap<Var, (HashSet<Label>, Type)>) {\n\n\n\n let mut def_map = identify_definitions(nodes, headers);\n\n let dom_tree = DominanceTree::new(nodes);\n\n // eprintln!(\"dom tree computed\");\n\n\n\n for (var, (defs, r_type)) in def_map.iter_mut() {\n\n let mut queue: VecDeque<Label> = defs.iter().cloned().collect();\n\n let def_len = queue.len();\n\n\n\n if queue.len() != 1 {\n\n // eprintln!(\">>>> checking defs of {} total {}\", var, def_len);\n\n while let Some(block_label) = queue.pop_front() {\n\n // eprintln!(\"queue length {}\", queue.len());\n\n // eprintln!(\"frontier for {} is {:?} \", block_label, dom_tree.compute_frontier(&block_label));\n\n for block in dom_tree.compute_frontier(&block_label) {\n\n // eprintln!(\"frontier for {} contains {}\", block_label, block);\n\n\n", "file_path": "src/transformers/ssa.rs", "rank": 28, "score": 48312.56198512516 }, { "content": "type LinkTarget = Weak<Node>;\n", "file_path": "src/transformers/cfg.rs", "rank": 29, "score": 47933.477283751665 }, { "content": "fn get_stdin() -> String {\n\n let stdin = io::stdin();\n\n let mut buffer = String::new();\n\n let mut handle = stdin.lock();\n\n\n\n\n\n match handle.read_to_string(&mut buffer) {\n\n Ok(_) => {}\n\n Err(error) => {\n\n eprint!(\"Encountered error {}\", error);\n\n exit(1)\n\n }\n\n }\n\n buffer\n\n}\n\n\n", "file_path": "src/main.rs", "rank": 30, "score": 47569.603815347196 }, { "content": "type Data = HashSet<Var>;\n\n\n", "file_path": "src/analysis/live_vars.rs", "rank": 32, "score": 21725.50140033064 }, { "content": "type Data = HashSet<VarDef>;\n\n\n\n#[derive(Hash, Clone, Eq, PartialEq, Debug)]\n\npub struct VarDef(pub Var, pub usize);\n\n\n\nimpl Display for VarDef {\n\n fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {\n\n write!(f, \"{}_{}\", self.0, self.1)\n\n }\n\n}\n\n\n\n\n\n\n", "file_path": "src/analysis/reaching_defns.rs", "rank": 33, "score": 21725.50140033064 }, { "content": "type Data = HashSet<Value>;\n\n\n", "file_path": "src/analysis/cprop.rs", "rank": 34, "score": 21725.50140033064 }, { "content": " self.predecessors.borrow().iter().map(|x| Weak::upgrade(x).unwrap().label()).collect()\n\n }\n\n\n\n pub fn successor_labels(&self) -> Vec<Label> {\n\n self.successor_refs().iter().map(|x| x.label()).collect()\n\n }\n\n\n\n pub fn block_label(&self) -> Option<Label>{\n\n self.contents.borrow().label()\n\n }\n\n\n\n pub fn is_labeled(&self) -> bool {\n\n self.contents.borrow().label().is_some()\n\n }\n\n\n\n pub fn normalize(&self) {\n\n if self.block_label().is_none() {\n\n let block: &mut Block = &mut self.contents.borrow_mut();\n\n block.0.insert(0, Instr::Label {label: self.label})\n\n }\n", "file_path": "src/transformers/cfg.rs", "rank": 35, "score": 17.732023873394112 }, { "content": " let block = &mut *self.contents.borrow_mut();\n\n block.0.push(instr);\n\n }\n\n\n\n pub fn replace_link(&self, old: Label, new_ref: Weak<Node>, new_label: Label) {\n\n let out: &mut Option<Link> = &mut self.out.borrow_mut();\n\n if out.is_none() {\n\n panic!(\"replace on unlinked block\");\n\n }\n\n let block = &mut *self.contents.borrow_mut();\n\n\n\n if let Some(Link::Fallthrough(_)) = out {\n\n out.replace(Link::Jump(new_ref));\n\n block.0.push(Instr::Effect{\n\n op: Op::Jmp,\n\n labels: vec! [new_label],\n\n args: Vec::new(),\n\n funcs: Vec::new(),\n\n })\n\n } else if let Instr::Effect { op, labels, .. } = block.0.last_mut().unwrap() {\n", "file_path": "src/transformers/cfg.rs", "rank": 36, "score": 13.124225927765544 }, { "content": "use super::cfg::{Block, Node, Link};\n\nuse super::dominance::DominanceTree;\n\nuse crate::serde_structs::namer;\n\nuse crate::serde_structs::structs::{Instr, Label, Op, Type, Var, FnHeaders};\n\nuse std::collections::{HashMap, HashSet, VecDeque};\n\nuse std::ops::{Index, IndexMut};\n\nuse std::rc::{Rc, Weak};\n\n\n", "file_path": "src/transformers/ssa.rs", "rank": 37, "score": 12.674733113404782 }, { "content": " pub fn dummy_block(\n\n contents: RefCell<Block>,\n\n out: RefCell<Option<Link>>,\n\n predecessors: RefCell<Vec<Weak<Node>>>,\n\n idx: RefCell<Option<usize>>) -> Self {\n\n\n\n Node {\n\n contents,\n\n out,\n\n predecessors,\n\n idx,\n\n label: namer().fresh_label()\n\n }\n\n }\n\n\n\n pub fn label(&self) -> Label{\n\n self.label\n\n }\n\n\n\n pub fn predecessor_labels(&self) -> Vec<Label> {\n", "file_path": "src/transformers/cfg.rs", "rank": 38, "score": 11.60814583278696 }, { "content": " pub fn empty_block() -> Rc<Self> {\n\n let mut new = Node {\n\n contents: RefCell::<Block>::default(),\n\n out: RefCell::<Option<Link>>::default(),\n\n predecessors: RefCell::<Vec<Weak<Node>>>::default(),\n\n idx: RefCell::<Option<usize>>::default(),\n\n label: namer().fresh_label()\n\n };\n\n new.normalize();\n\n Rc::new(new)\n\n }\n\n\n\n pub fn new(input: Vec<Instr>) -> Node{\n\n Node::from_block(Block::new(input))\n\n }\n\n\n\n pub fn clear_predecessors(&self) {\n\n self.predecessors.replace(Vec::new());\n\n }\n\n\n", "file_path": "src/transformers/cfg.rs", "rank": 39, "score": 11.32242117004622 }, { "content": " None if headers.contains(arg) => *arg,\n\n _ => panic!(\"Unknown variable {}\", arg),\n\n }\n\n }\n\n }\n\n _ => {}\n\n }\n\n }\n\n }\n\n\n\n for successor in node.successor_refs() {\n\n // eprintln!(\"updating successors\");\n\n let contents: &mut Block = &mut successor.contents.borrow_mut();\n\n let block = &mut contents.0;\n\n for instr in block.iter_mut() {\n\n if let Instr::Value { op: op @ Op::Phi, args, dest, labels, ..} = instr {\n\n let mut index:usize = 0;\n\n let mut found = false;\n\n for (idx, arg) in args.iter().enumerate() {\n\n if stack.contains(arg) {\n", "file_path": "src/transformers/ssa.rs", "rank": 40, "score": 11.25194338020661 }, { "content": "mod basic_types;\n\nmod functions;\n\nmod program;\n\nmod names;\n\nmod operations;\n\nmod instructions;\n\n\n\npub use names::namer;\n\n\n\npub mod structs {\n\n // Collects the internal structures\n\n pub use super::basic_types::{Literal, Type};\n\n pub use super::names::{FnName, Var, Label};\n\n pub use super::program::{Program, CFGProgram};\n\n pub use super::instructions::Instr;\n\n pub use super::operations::Op;\n\n pub use super::functions::{CFGFunction, Function, FnHeaders};\n\n}\n", "file_path": "src/serde_structs/mod.rs", "rank": 41, "score": 11.17062884317795 }, { "content": " if let Some(Link::Branch { false_branch, ..} ) = out {\n\n *false_branch = new_ref;\n\n } else {\n\n panic!(\"Branch Link missing\")\n\n }\n\n } else {\n\n panic!(\"Malformed {} {:?}\",old, labels)\n\n }\n\n },\n\n _ => {}\n\n }\n\n } else {\n\n panic!(\"??????\")\n\n }\n\n }\n\n\n\n\n\n\n\n pub fn add_jump(&self, target: Weak<Node>, label: Label) {\n\n let out: &mut Option<Link> = &mut self.out.borrow_mut();\n", "file_path": "src/transformers/cfg.rs", "rank": 43, "score": 10.76859722470493 }, { "content": " name: FnName,\n\n #[serde(default = \"Vec::new\")]\n\n args: Vec<FnHeaders>,\n\n\n\n #[serde(rename = \"type\")]\n\n #[serde(skip_serializing_if = \"Option::is_none\")]\n\n r_type: Option<Type>,\n\n\n\n instrs: Vec<Instr>,\n\n}\n\n\n\nimpl Function {\n\n\n\n pub fn g_tcde(&mut self) {\n\n trivial_global_dce(&mut self.instrs)\n\n }\n\n\n\n pub fn make_cfg(self) -> CFGFunction {\n\n\n\n let mut blocks = construct_cfg_nodes(construct_basic_blocks(self.instrs));\n", "file_path": "src/serde_structs/functions.rs", "rank": 44, "score": 10.575435322579265 }, { "content": "\n\n connect_basic_blocks(&mut blocks);\n\n\n\n CFGFunction {\n\n name: self.name,\n\n args: self.args,\n\n r_type: self.r_type,\n\n blocks\n\n }\n\n }\n\n}\n\n\n\n#[derive(Debug)]\n\npub struct CFGFunction {\n\n name: FnName,\n\n args: Vec<FnHeaders>,\n\n\n\n r_type: Option<Type>,\n\n\n\n blocks: Vec<Rc<Node>>,\n", "file_path": "src/serde_structs/functions.rs", "rank": 45, "score": 10.559574036549572 }, { "content": "use std::fmt::{self, Display};\n\nuse serde::{self, Deserialize, Serialize};\n\n\n\nuse super::names::{FnName, Label, namer, Var};\n\nuse super::basic_types::{Literal, Type};\n\nuse super::operations::Op;\n\n\n\n#[derive(Serialize, Deserialize, Debug)]\n\n#[serde(untagged)]\n\npub enum Instr {\n\n #[serde(rename = \"label\")]\n\n Label { label: Label },\n\n Const {\n\n op: Op,\n\n dest: Var,\n\n #[serde(rename = \"type\")]\n\n r_type: Type,\n\n value: Literal,\n\n },\n\n Value {\n", "file_path": "src/serde_structs/instructions.rs", "rank": 46, "score": 10.276475964003858 }, { "content": "mod dataflow_core;\n\npub mod reaching_defns;\n\npub mod live_vars;\n\nmod cprop;\n\n\n\nmod prelude {\n\n pub use super::dataflow_core::{worklist_solver, AnalysisNode, Direction};\n\n pub use crate::transformers::cfg::{Node, Block};\n\n pub use crate::serde_structs::structs::{Instr, Var, FnHeaders};\n\n pub use std::rc::Rc;\n\n pub use std::fmt::Display;\n\n}\n\n\n\npub const ALLOWED_VALUES: &[&str] = &[\"reaching_defns\", \"live\"];\n\n\n\npub use reaching_defns::reaching_definitions;\n\npub use live_vars::live_variables;\n\n\n\n// just add types!\n\npub mod dehydrated {\n", "file_path": "src/analysis/mod.rs", "rank": 47, "score": 10.069874869737479 }, { "content": " }\n\n\n\n pub fn successor_refs(&self) -> Vec<Rc<Node>> {\n\n let successor: &Option<Link> = &self.out.borrow();\n\n\n\n match successor {\n\n Some(link) => {\n\n match link {\n\n Link::Ret => Vec::new(),\n\n Link::Exit => Vec::new(),\n\n Link::Fallthrough(weak) => Weak::upgrade(weak).map_or(Vec::new(), |s| { vec! [s] }),\n\n Link::Jump(weak) => Weak::upgrade(weak).map_or(Vec::new(), |s| { vec! [s] }),\n\n Link::Branch { true_branch, false_branch } => {\n\n let mut true_br = Weak::upgrade(true_branch).map_or(Vec::new(), |s| { vec! [s] });\n\n let mut false_br = Weak::upgrade(false_branch).map_or(Vec::new(), |s| { vec! [s] });\n\n true_br.append(&mut false_br);\n\n true_br\n\n }\n\n }\n\n }\n", "file_path": "src/transformers/cfg.rs", "rank": 48, "score": 9.997183193119705 }, { "content": "use serde::{self, Deserialize, Serialize};\n\nuse super::name_mapper::{namer,Name};\n\nuse std::fmt::{Display, Debug};\n\n\n\n#[derive(Serialize, Deserialize, Clone, Copy, PartialEq, Eq, Hash, Ord, PartialOrd)]\n\npub struct Var(pub Name);\n\n\n\n#[derive(Serialize, Deserialize, Clone, Copy, PartialEq, Eq, Hash, Ord, PartialOrd)]\n\npub struct Label(pub Name);\n\n\n\n#[derive(Serialize, Deserialize, Clone, Copy, PartialEq, Eq, Hash, Ord, PartialOrd)]\n\npub struct FnName(pub Name);\n\n\n\n\n\nimpl Debug for Var {\n\n fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {\n\n write!(f, \"<Var: {} [{}]>\", namer().get_string(&self.0), &(self.0).0)\n\n }\n\n}\n\n\n", "file_path": "src/serde_structs/names/wrapper_names.rs", "rank": 50, "score": 9.594413260768583 }, { "content": " let node = dom_tree.lookup_node(&block);\n\n let contents: &mut Block = &mut node.contents.borrow_mut();\n\n if contents.len() != 1 {\n\n let mut found = false;\n\n for instr in contents.0.iter_mut() {\n\n if let Instr::Value {\n\n op: Op::Phi,\n\n dest,\n\n labels,\n\n args,\n\n ..\n\n } = instr\n\n {\n\n if dest == var {\n\n args.push(*var);\n\n labels.push(block_label);\n\n found = true;\n\n break\n\n }\n\n }\n", "file_path": "src/transformers/ssa.rs", "rank": 51, "score": 9.59353499402716 }, { "content": " }\n\n\n\n pub fn apply_basic_dce(&mut self) {\n\n for block in self.blocks.iter_mut() {\n\n local_dce(block);\n\n }\n\n }\n\n pub fn apply_lvn(&mut self) {\n\n for blk in self.blocks.iter() {\n\n let node = blk.as_ref();\n\n let contents = &mut node.contents.borrow_mut().0;\n\n run_lvn(contents)\n\n }\n\n }\n\n\n\n pub fn reaching_defns(&self) {\n\n let analysis_nodes = analysis::reaching_definitions(&self.blocks, &self.args);\n\n\n\n println!(\"\\n\\nRunning reaching definitions analysis on {}\\n\", self.name);\n\n for (index, node) in analysis_nodes.into_iter().enumerate() {\n", "file_path": "src/serde_structs/functions.rs", "rank": 52, "score": 9.516166187386192 }, { "content": "impl Display for Block {\n\n fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {\n\n match self.label() {\n\n Some(l) => {\n\n write!(f, \"{}\", l)\n\n }\n\n None => {\n\n write!(f, \"unlabeled\")\n\n }\n\n }\n\n }\n\n}\n\n\n\nimpl IntoIterator for Block {\n\n type Item = Instr;\n\n\n\n type IntoIter = std::vec::IntoIter<Instr>;\n\n\n\n fn into_iter(self) -> Self::IntoIter {\n\n self.0.into_iter()\n", "file_path": "src/transformers/cfg.rs", "rank": 53, "score": 9.492395266458868 }, { "content": " use std::hash::Hash;\n\n use std::collections::HashSet;\n\n\n\n pub fn set_union<T: Eq + Hash + Clone>(input: Vec<&HashSet<T>>) -> HashSet<T> {\n\n let mut out = HashSet::new();\n\n for set in input {\n\n out = out.union(set).cloned().collect()\n\n }\n\n out\n\n }\n\n\n\n pub fn set_intersection<T: Eq + Hash + Clone>(input: Vec<&HashSet<T>>) -> HashSet<T> {\n\n let mut out = HashSet::<T>::new();\n\n\n\n if !input.is_empty() {\n\n for item in input[0].iter() {\n\n if input.iter().all(|x| x.contains(item)) {\n\n out.insert(item.clone());\n\n }\n\n }\n\n }\n\n out\n\n }\n\n}\n", "file_path": "src/analysis/mod.rs", "rank": 54, "score": 9.411071988622261 }, { "content": "use crate::transformers::cfg::{Node, Block, Link};\n\nuse std::rc::Rc;\n\nuse std::fmt::Debug;\n\nuse std::collections::HashSet;\n\n\n\n#[derive(Debug)]\n\npub struct AnalysisNode<D> {\n\n pub in_data: D,\n\n pub out_data: D,\n\n pub program_node: Rc<Node>,\n\n predecessors: Vec<usize>,\n\n successors: Vec<usize>\n\n}\n\n\n\n// This is silly and used only to enforce a particular\n\n// print order for testing purposes\n\nimpl<T: Clone> AnalysisNode<HashSet<T>> {\n\n pub fn in_data_as_vec(&self) -> Vec<T>{\n\n self.in_data.iter().cloned().collect()\n\n }\n", "file_path": "src/analysis/dataflow_core.rs", "rank": 55, "score": 9.39754051536455 }, { "content": " }\n\n}\n\n\n\nimpl Display for Node {\n\n fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {\n\n if let Some(label) = &self.block_label() {\n\n writeln!(f, \"Block {}:\", namer().get_string(&label.0))?;\n\n } else {\n\n writeln!(f, \"Block (unlabeled):\")?;\n\n }\n\n for line in self.contents.borrow_mut().iter() {\n\n writeln!(f,\" {}\", line)?;\n\n }\n\n if let Some(x) = self.out.borrow().as_ref() {\n\n write!(f, \" Connected to: {}\", x)\n\n } else {\n\n write!(f, \" not connected?\")\n\n }\n\n }\n\n}\n", "file_path": "src/transformers/cfg.rs", "rank": 56, "score": 9.169964343648179 }, { "content": " None => Vec::new()\n\n }\n\n }\n\n\n\n pub fn prune_missing_predecessors(&self) {\n\n let preds: &mut Vec<Weak<Node>> = &mut self.predecessors.borrow_mut();\n\n preds.retain(|x| {\n\n x.upgrade().is_some()\n\n });\n\n }\n\n\n\n pub fn insert_id(&self, var: Var, dest: Var, r_type: Type) {\n\n let instr = Instr::Value {\n\n op: Op::Id,\n\n dest: dest,\n\n r_type: r_type,\n\n args: vec![var],\n\n funcs: Vec::new(),\n\n labels: Vec::new(),\n\n };\n", "file_path": "src/transformers/cfg.rs", "rank": 57, "score": 9.15590957697653 }, { "content": " }\n\n\n\n pub fn to_ssa(&mut self) {\n\n to_ssa(&mut self.blocks, &self.args[..])\n\n }\n\n\n\n pub fn from_ssa(&mut self) {\n\n from_ssa(&mut self.blocks)\n\n }\n\n}\n\n\n\nimpl Display for CFGFunction {\n\n fn fmt(&self, f: & mut fmt::Formatter<'_>) -> fmt::Result {\n\n let namer = namer();\n\n writeln!(f, \"== Function: {} ==\", namer.get_string(&self.name.0))?;\n\n writeln!(f, \"args: {:?}\", &self.args)?;\n\n if let Some(x) = &self.r_type {\n\n writeln!(f, \"returns {}\", x)?;\n\n }\n\n for node in self.blocks.iter() {\n\n writeln!(f, \"\\n{}\", node)?;\n\n }\n\n Ok(())\n\n }\n\n}\n", "file_path": "src/serde_structs/functions.rs", "rank": 58, "score": 9.119206557705272 }, { "content": " // The phi node is not valid along this path. Remove\n\n *op = Op::Nop;\n\n *args = vec! [];\n\n *labels = vec! [];\n\n }\n\n\n\n\n\n }\n\n\n\n\n\n }\n\n }\n\n }\n\n\n\n for mut child in dom_tree.get_children(&node.label()) {\n\n rename(&mut child, dom_tree, stack, headers);\n\n }\n\n\n\n let contents: &mut Block = &mut node.contents.borrow_mut();\n\n let block = &mut contents.0;\n", "file_path": "src/transformers/ssa.rs", "rank": 59, "score": 9.084496343872488 }, { "content": "use std::fmt::{self, Display};\n\nuse serde::{self, Deserialize, Serialize};\n\nuse super::names::{FnName, namer, Var};\n\nuse super::basic_types::{Type, Literal};\n\nuse super::instructions::Instr;\n\nuse super::operations::Op;\n\nuse super::super::transformers::cfg::Node;\n\nuse super::super::transformers::cfg::{connect_basic_blocks, construct_basic_blocks, construct_cfg_nodes};\n\nuse super::super::transformers::orphan::remove_inaccessible_blocks;\n\nuse super::super::transformers::dce::{trivial_global_dce,local_dce};\n\nuse super::super::transformers::lvn::run_lvn;\n\nuse super::super::transformers::ssa::{to_ssa, from_ssa};\n\n\n\nuse std::rc::Rc;\n\nuse crate::analysis;\n\nuse crate::analysis::reaching_defns::VarDef;\n\n\n\nuse std::mem::replace;\n\n#[derive(Serialize, Deserialize, Debug)]\n\npub struct FnHeaders {\n", "file_path": "src/serde_structs/functions.rs", "rank": 60, "score": 9.027802013328955 }, { "content": "\n\n #[serde(default = \"Vec::new\")]\n\n funcs: Vec<FnName>,\n\n\n\n #[serde(default = \"Vec::new\")]\n\n labels: Vec<Label>,\n\n },\n\n}\n\n\n\nimpl Instr {\n\n pub fn is_label(&self) -> bool {\n\n if let Instr::Label { .. } = &self {\n\n true\n\n } else {\n\n false\n\n }\n\n }\n\n\n\n pub fn is_terminator(&self) -> bool {\n\n match self {\n", "file_path": "src/serde_structs/instructions.rs", "rank": 62, "score": 8.962878142173981 }, { "content": "}\n\n\n\nimpl CFGFunction {\n\n pub fn make_serializeable(self) -> Function {\n\n Function {\n\n name: self.name,\n\n args: self.args,\n\n r_type: self.r_type,\n\n instrs: self.blocks.into_iter().map(|x| Rc::try_unwrap(x).unwrap().make_serializeable()).flatten().collect()\n\n }\n\n }\n\n\n\n pub fn drop_orphan_blocks(&mut self) {\n\n let tmp = replace(&mut self.blocks, Vec::new());\n\n\n\n self.blocks = remove_inaccessible_blocks(tmp);\n\n\n\n for block in self.blocks.iter() {\n\n block.prune_missing_predecessors()\n\n }\n", "file_path": "src/serde_structs/functions.rs", "rank": 63, "score": 8.855361509869919 }, { "content": " pub idx: RefCell<Option<usize>>, // this is bad and I am bad\n\n label: Label\n\n}\n\n\n\nimpl Node {\n\n pub fn from_block(input: Block) -> Node {\n\n if input.is_empty() {\n\n panic!(\"Tried to create an empty block????\\n\")\n\n }\n\n\n\n let label = input.label().unwrap_or(namer().fresh_label());\n\n Node {\n\n contents: RefCell::new(input),\n\n out: RefCell::new(None),\n\n predecessors: RefCell::new(Vec::new()),\n\n idx: RefCell::new(None),\n\n label\n\n }\n\n }\n\n\n", "file_path": "src/transformers/cfg.rs", "rank": 64, "score": 8.818165771877336 }, { "content": "\n\n for block in nodes {\n\n let instrs: &Block = &block.contents.borrow();\n\n for instr in instrs.0.iter() {\n\n match instr {\n\n Instr::Const { dest, r_type, .. } | Instr::Value { dest, r_type, .. } => {\n\n let contains: bool = var_map.contains_key(dest);\n\n\n\n if contains {\n\n var_map.get_mut(dest).unwrap().0.insert(block.label());\n\n } else {\n\n let mut set = HashSet::<Label>::with_capacity(1);\n\n set.insert(block.label());\n\n var_map.insert(*dest, (set, r_type.clone()));\n\n }\n\n }\n\n _ => {}\n\n }\n\n }\n\n }\n\n var_map\n\n}\n\n\n", "file_path": "src/transformers/ssa.rs", "rank": 65, "score": 8.607950773816853 }, { "content": "\n\nimpl Debug for Label {\n\n fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {\n\n write!(f, \"<Label: {} [{}]>\", namer().get_string(&self.0), &self.0)\n\n }\n\n}\n\n\n\nimpl Debug for FnName {\n\n fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {\n\n write!(f, \"<FnName: {} [{}]>\", namer().get_string(&self.0), &self.0)\n\n }\n\n}\n\n\n\nimpl Display for Var {\n\n fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {\n\n write!(f, \"{}\", &self.0)\n\n }\n\n}\n\n\n\nimpl Display for Label {\n", "file_path": "src/serde_structs/names/wrapper_names.rs", "rank": 66, "score": 8.342268060177759 }, { "content": " pub fn fresh_label(&self) -> Label {\n\n let map = &mut *self.mapper.as_ref().lock().unwrap();\n\n Label(map.gen_fresh_name(&String::from(\"tmp_label\")))\n\n }\n\n // pub fn remove_and_return_string(&self, name: &Name) -> String {\n\n // (*self.mapper.as_ref().lock().unwrap()).remove_and_return_string(name)\n\n // }\n\n\n\n}\n\n\n", "file_path": "src/serde_structs/names/name_mapper.rs", "rank": 67, "score": 8.285143350327013 }, { "content": " if out.is_some() {\n\n panic!(\"Tried to add jump on linked node\")\n\n }\n\n let block = &mut *self.contents.borrow_mut();\n\n\n\n if let Some(Instr::Effect {op, .. }) = block.0.last() {\n\n if *op == Op::Jmp || *op == Op::Br || *op == Op::Ret {\n\n panic!(\"Adding jump to block that already contains a terminal instr\");\n\n }\n\n }\n\n\n\n block.0.push(Instr::Effect {\n\n op: Op::Jmp,\n\n args: Vec::new(),\n\n funcs: Vec::new(),\n\n labels: vec! [label],\n\n });\n\n out.replace(Link::Jump(target));\n\n }\n\n\n\n}\n\n\n\nimpl PartialEq for Node {\n\n fn eq(&self, other: &Self) -> bool {\n\n self.label() == other.label()\n\n }\n\n}\n\n\n\n\n", "file_path": "src/transformers/cfg.rs", "rank": 68, "score": 8.264823888602198 }, { "content": "use bimap::BiHashMap;\n\nuse std::sync::{Arc, Mutex, Once};\n\nuse std::mem::transmute;\n\n\n\nuse serde::de::{self, Deserializer, Deserialize, Visitor};\n\nuse serde::{Serialize, Serializer};\n\nuse std::fmt::{self, Display};\n\nuse super::wrapper_names::Label;\n\n\n\n#[derive(PartialEq, Eq, Hash, Clone, Copy, Debug, Ord, PartialOrd)]\n\npub struct Name(pub u64);\n\n\n\nimpl Display for Name {\n\n fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {\n\n write!(f, \"{}\", namer().get_string(&self))\n\n }\n\n}\n\n\n\nimpl<'de> Deserialize<'de> for Name {\n\n fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>\n", "file_path": "src/serde_structs/names/name_mapper.rs", "rank": 69, "score": 8.140631979647935 }, { "content": " analysis_nodes[block_idx].predecessors.iter().map(|x| -> &D {\n\n &analysis_nodes[*x].out_data\n\n }).collect()\n\n } else {\n\n analysis_nodes[block_idx].successors.iter().map(|x| -> &D {\n\n &analysis_nodes[*x].in_data\n\n }).collect()\n\n };\n\n\n\n if let Direction::Forward = direction {\n\n analysis_nodes[block_idx].in_data = merge_fn(merge_list)\n\n } else {\n\n analysis_nodes[block_idx].out_data = merge_fn(merge_list)\n\n }\n\n\n\n {\n\n // going directly to the\n\n let block:&Block = &nodes[block_idx].contents.borrow();\n\n if let Direction::Forward = direction {\n\n analysis_nodes[block_idx].out_data = transfer_fn(&analysis_nodes[block_idx].in_data, block, block_idx);\n", "file_path": "src/analysis/dataflow_core.rs", "rank": 70, "score": 8.008852899623978 }, { "content": "use super::super::serde_structs::structs::{Label, Instr, Op, Var, Type};\n\nuse super::super::serde_structs::namer;\n\nuse std::collections::HashMap;\n\nuse std::rc::{Rc, Weak};\n\nuse std::{cell::RefCell, fmt, fmt::Display};\n\nuse std::iter::Iterator;\n\n\n\n\n\n\n", "file_path": "src/transformers/cfg.rs", "rank": 71, "score": 7.84655088005613 }, { "content": " vec! [borrowed_true.unwrap(), borrowed_false.unwrap()]\n\n }\n\n };\n\n analysis_nodes[idx].successors = successors;\n\n }\n\n }\n\n\n\n // Now the analysis nodes are fully set up and we no longer need to refer\n\n // to the program blocks for the graph\n\n\n\n let mut worklist: Vec<usize> = (0..analysis_nodes.len()).collect();\n\n\n\n while let Some(block_idx) = worklist.pop() {\n\n let old: D = if let Direction::Forward = direction {\n\n std::mem::replace(&mut analysis_nodes[block_idx].out_data, initial_value.clone())\n\n } else {\n\n std::mem::replace(&mut analysis_nodes[block_idx].in_data, initial_value.clone())\n\n };\n\n\n\n let merge_list: Vec<&D> = if let Direction::Forward = direction {\n", "file_path": "src/analysis/dataflow_core.rs", "rank": 72, "score": 7.651682665102578 }, { "content": " }\n\n}\n\n\n\n#[derive(Debug)]\n\npub enum Link {\n\n Ret,\n\n Exit,\n\n Fallthrough(LinkTarget),\n\n Jump(LinkTarget),\n\n Branch {\n\n true_branch: LinkTarget,\n\n false_branch: LinkTarget,\n\n },\n\n}\n\n\n\n#[derive(Debug)]\n\npub struct Node {\n\n pub contents: RefCell<Block>,\n\n pub out: RefCell<Option<Link>>,\n\n pub predecessors: RefCell<Vec<Weak<Node>>>,\n", "file_path": "src/transformers/cfg.rs", "rank": 73, "score": 7.351462510319953 }, { "content": " index = idx;\n\n found = true;\n\n break\n\n }\n\n }\n\n if !found {\n\n // eprintln!(\"adding arg to phi node for {}\", dest);\n\n args.push(stack.get_top(dest).unwrap());\n\n labels.push(node.label())\n\n // panic!(\"No arg to rename? {:?} {} {}\", args, dest, successor.label())\n\n } else {\n\n // eprintln!(\"rewriting phi node\");\n\n // eprintln!(\"args len {}, idx {}\", args.len(), index);\n\n let var = args.get_mut(index).unwrap();\n\n\n\n if let Some(renamed) = stack.get_top(var){\n\n *var = renamed;\n\n let label = labels.get_mut(index).unwrap();\n\n *label = node.label();\n\n } else {\n", "file_path": "src/transformers/ssa.rs", "rank": 74, "score": 7.345004277033068 }, { "content": " } else {\n\n analysis_nodes[block_idx].in_data = transfer_fn(&analysis_nodes[block_idx].out_data, block, block_idx);\n\n }\n\n }\n\n\n\n let updates_required = if let Direction::Forward = direction {\n\n analysis_nodes[block_idx].out_data != old\n\n } else {\n\n analysis_nodes[block_idx].in_data != old\n\n };\n\n\n\n if updates_required {\n\n if let Direction::Forward = direction {\n\n for index in analysis_nodes[block_idx].successors.iter() {\n\n worklist.push(*index)\n\n }\n\n } else {\n\n for index in analysis_nodes[block_idx].predecessors.iter() {\n\n worklist.push(*index)\n\n }\n", "file_path": "src/analysis/dataflow_core.rs", "rank": 75, "score": 7.068884985467292 }, { "content": "use std::fmt::{self, Display};\n\nuse serde::{self, Deserialize, Serialize};\n\n\n\n#[derive(Serialize, Deserialize, Debug, PartialEq, Eq, Copy, Clone)]\n\n#[serde(rename_all = \"lowercase\")]\n\npub enum Op {\n\n Const,\n\n // Arith\n\n Add,\n\n Mul,\n\n Sub,\n\n Div,\n\n // Comparison\n\n Eq,\n\n Lt,\n\n Gt,\n\n Le,\n\n Ge,\n\n // Logic\n\n Not,\n", "file_path": "src/serde_structs/operations.rs", "rank": 76, "score": 7.033411754674238 }, { "content": "mod name_mapper;\n\nmod wrapper_names;\n\n\n\npub use name_mapper::namer;\n\npub use wrapper_names::*;\n", "file_path": "src/serde_structs/names/mod.rs", "rank": 77, "score": 6.905009005875654 }, { "content": " Instr::Label { .. } => true,\n\n Instr::Const { .. } => false,\n\n Instr::Effect { op: operation, .. } | Instr::Value { op: operation, .. } => {\n\n operation.is_terminator()\n\n }\n\n }\n\n }\n\n\n\n pub fn extract_label(&self) -> Option<Label> {\n\n if let Instr::Label {label} = &self {\n\n Some(*label)\n\n } else {\n\n None\n\n }\n\n }\n\n}\n\n\n\n// impl Label {\n\n// pub fn make_instr(self) -> Instr {\n\n// Instr::Label {label: self}\n", "file_path": "src/serde_structs/instructions.rs", "rank": 78, "score": 6.838050388197324 }, { "content": "\n\n\n\n\n\nimpl Display for Link {\n\n fn fmt(&self, f: & mut fmt::Formatter<'_>) -> fmt::Result {\n\n let namer = namer();\n\n match &self {\n\n Link::Ret => {\n\n write!(f, \"<RETURN>\")\n\n }\n\n Link::Exit => {\n\n write!(f, \"<EXIT>\")\n\n }\n\n Link::Fallthrough(val) => {\n\n let val = val.upgrade();\n\n if let Some(val) = val {\n\n match val.block_label() {\n\n Some(label) => {\n\n write!(f, \"<FALLTHROUGH: .{}>\", namer.get_string(&label.0))\n\n }\n", "file_path": "src/transformers/cfg.rs", "rank": 79, "score": 6.832949217257261 }, { "content": " // TODO: Figure out how to get rid of this\n\n for instr in block.iter_mut() {\n\n if let Instr::Value {op: op @ Op::Phi, args, labels, ..} = instr{\n\n // eprintln!(\"{:?}\", args);\n\n while !args.is_empty() && stack.contains(args.last().unwrap()) {\n\n args.pop();\n\n labels.pop();\n\n }\n\n if args.is_empty() {\n\n *op = Op::Nop;\n\n }\n\n }\n\n }\n\n\n\n block.retain(|x| if let Instr::Value { op:Op::Nop, ..} = x {\n\n false\n\n } else{\n\n true\n\n });\n\n\n\n stack.decrease_layer();\n\n\n\n}\n\n\n", "file_path": "src/transformers/ssa.rs", "rank": 81, "score": 6.699414898599249 }, { "content": " pub name: Var,\n\n #[serde(rename = \"type\")]\n\n pub r_type: Type,\n\n}\n\n\n\nimpl FnHeaders {\n\n // Only should be used for dataflow analysis\n\n pub fn generate_dummy_instrs(&self) -> Instr {\n\n Instr::Const { op: Op::Const, dest: self.name, r_type: self.r_type.clone(),\n\n value: match self.r_type {\n\n Type::Int => {Literal::Int(0)}\n\n Type::Bool => {Literal::Bool(false)}\n\n Type::Ptr(_) => {todo!()}\n\n Type::Float => {Literal::Float(0.0)}\n\n }}\n\n }\n\n}\n\n\n\n#[derive(Serialize, Deserialize, Debug)]\n\npub struct Function {\n", "file_path": "src/serde_structs/functions.rs", "rank": 83, "score": 6.523320151609575 }, { "content": "\n\n let new_node = new_nodes_map.entry((node.label(), *label)).or_insert(Node::empty_block());\n\n new_node.insert_id(*var, *dest, r_type.clone());\n\n // if *label != node.label() {\n\n // label_map.get_mut(label).unwrap().replace_link(node.label(), Rc::downgrade(&new_node), new_node.label());\n\n // new_nodes.push(new_node);\n\n // } else {\n\n // fix_list.push((*label, new_node));\n\n // }\n\n }\n\n }\n\n }\n\n }\n\n\n\n for ((to, from), new_node) in new_nodes_map.drain() {\n\n {\n\n let target = &label_map[&to];\n\n new_node.add_jump(Rc::downgrade(target), target.label());\n\n }\n\n label_map[&from].replace_link(to,\n", "file_path": "src/transformers/ssa.rs", "rank": 84, "score": 6.5007693197828695 }, { "content": " Rc::downgrade(&new_node),\n\n new_node.label());\n\n nodes.push(new_node);\n\n }\n\n\n\n // for (label, new_node) in fix_list {\n\n // // eprintln!(\"{} {}\", label, new_node.label());\n\n // label_map.get_mut(&label).unwrap().replace_link(label, Rc::downgrade(&new_node), new_node.label());\n\n // new_nodes.push(new_node);\n\n // }\n\n\n\n nodes.append(&mut new_nodes);\n\n\n\n let len = nodes.len();\n\n\n\n for (idx,node) in nodes.iter_mut().enumerate() {\n\n node.contents.borrow_mut().0.retain(|x| {\n\n if let Instr::Value {op:Op::Phi, ..} = x {\n\n false\n\n } else {\n", "file_path": "src/transformers/ssa.rs", "rank": 85, "score": 6.43621658204022 }, { "content": "use serde::{self, Deserialize, Serialize};\n\nuse super::functions::{CFGFunction, Function};\n\n\n\n#[derive(Serialize, Deserialize, Debug)]\n\npub struct Program {\n\n pub functions: Vec<Function>,\n\n}\n\n\n\npub struct CFGProgram {\n\n pub functions: Vec<CFGFunction>\n\n}\n\n\n\nimpl Program {\n\n pub fn determine_cfg(self) -> CFGProgram {\n\n CFGProgram {\n\n functions: self.functions.into_iter().map(|f| f.make_cfg()).collect()\n\n }\n\n }\n\n\n\n}\n", "file_path": "src/serde_structs/program.rs", "rank": 86, "score": 6.240929182888148 }, { "content": " None => {\n\n // Is this possible???\n\n write!(f, \"<FALLTHROUGH: Unlabeled Block>\")\n\n }\n\n }\n\n } else {\n\n write!(f, \"?? LOST CONNECTION ??\")\n\n }\n\n }\n\n Link::Jump(val) => {\n\n let val = val.upgrade();\n\n if let Some(val) = val {\n\n if let Some(label) = val.block_label() {\n\n write!(f, \"<JUMP: .{}>\", namer.get_string(&label.0))?\n\n }\n\n Ok(())\n\n } else {\n\n write!(f, \"?? LOST CONNECTION ??\")\n\n }\n\n }\n", "file_path": "src/transformers/cfg.rs", "rank": 87, "score": 6.200700832909172 }, { "content": " true_branch: Rc::downgrade(true_target),\n\n false_branch: Rc::downgrade(false_target),\n\n }));\n\n let mut vec_cell = true_target.predecessors.borrow_mut();\n\n vec_cell.push(Rc::downgrade(last_block));\n\n\n\n let mut vec_cell = false_target.predecessors.borrow_mut();\n\n vec_cell.push(Rc::downgrade(last_block));\n\n return;\n\n }\n\n Op::Ret => {\n\n last_block.out.replace(Some(Link::Ret));\n\n return;\n\n }\n\n _ => {}\n\n },\n\n _ => {}\n\n };\n\n\n\n last_block.out.replace(Some(Link::Exit));\n\n}\n\n\n", "file_path": "src/transformers/cfg.rs", "rank": 88, "score": 6.195915308513465 }, { "content": " fun.apply_lvn();\n\n fun.apply_basic_dce()\n\n }\n\n }\n\n\n\n if conf.to_ssa {\n\n for fun in cfg.functions.iter_mut() {\n\n if !conf.orphan_block{\n\n fun.drop_orphan_blocks()\n\n }\n\n fun.to_ssa()\n\n }\n\n }\n\n\n\n if conf.from_ssa {\n\n for fun in cfg.functions.iter_mut() {\n\n fun.from_ssa()\n\n }\n\n }\n\n\n", "file_path": "src/main.rs", "rank": 90, "score": 6.0099057003437535 }, { "content": " Link::Branch { true_branch, false_branch } => {\n\n let val = true_branch.upgrade();\n\n if let Some(val) = val {\n\n if let Some(label) = val.block_label() {\n\n write!(f, \"<BR TRUE: .{}>\", namer.get_string(&label.0))?;\n\n }\n\n } else {\n\n write!(f, \"<BR TRUE:?? LOST CONNECTION ??>\")?;\n\n }\n\n\n\n write!(f, \" \")?;\n\n let val = false_branch.upgrade();\n\n if let Some(val) = val {\n\n if let Some(label) = val.block_label(){\n\n write!(f, \"<BR FALSE: .{}>\", namer.get_string(&label.0))\n\n } else {\n\n Ok(())\n\n }\n\n } else {\n\n write!(f, \"<BR FALSE:?? LOST CONNECTION ??>\")\n\n }\n\n\n\n }\n\n }\n\n }\n\n}\n", "file_path": "src/transformers/cfg.rs", "rank": 91, "score": 5.978337591847777 }, { "content": " }\n\n\n\n pub fn len(&self) -> usize {\n\n self.0.len()\n\n }\n\n\n\n fn make_serializeable(self) -> Vec<Instr> {\n\n self.0\n\n }\n\n\n\n fn iter(&self) -> std::slice::Iter<Instr> {\n\n self.0.iter()\n\n }\n\n\n\n fn iter_mut(&mut self) -> std::slice::IterMut<Instr> {\n\n self.0.iter_mut()\n\n }\n\n\n\n}\n\n\n", "file_path": "src/transformers/cfg.rs", "rank": 92, "score": 5.910533248288957 }, { "content": " LVNChoice::Bool(_) => false\n\n }\n\n }\n\n\n\n pub fn run_normal(&self) -> bool {\n\n match self {\n\n LVNChoice::Solo => false,\n\n LVNChoice::Bool(b) => *b\n\n }\n\n }\n\n}\n\n\n\npub struct ConfigOptions {\n\n pub orphan_block: bool,\n\n pub l_tdce: bool,\n\n pub g_tdce: bool,\n\n pub to_ssa: bool,\n\n pub from_ssa: bool,\n\n pub lvn: LVNChoice\n\n}\n", "file_path": "src/transformers/config.rs", "rank": 93, "score": 5.8493508624869435 }, { "content": " Op::Jmp => {\n\n let target = &labels[0];\n\n let target_ref = map.get(&target).unwrap_or_else(|| {\n\n panic!(\n\n \"Unable to locate label {}\",\n\n namer().get_string(&(target.0))\n\n )\n\n });\n\n current.out.replace(Some(Link::Jump(Rc::downgrade(target_ref))));\n\n let mut vec_cell = target_ref.predecessors.borrow_mut();\n\n vec_cell.push(Rc::downgrade(current));\n\n }\n\n Op::Br => {\n\n let true_label = &labels[0];\n\n let false_label = &labels[1];\n\n\n\n let true_target = map.get(&true_label).unwrap_or_else(|| {\n\n panic!(\n\n \"Unable to locate label {}\",\n\n namer().get_string(&(true_label.0))\n", "file_path": "src/transformers/cfg.rs", "rank": 94, "score": 5.775533759796595 }, { "content": "use std::collections::HashMap;\n\nuse clap::Values;\n\npub const ALLOWED_VALUES: &[&str] = &[\"all\", \"g_tdce\", \"l_tdce\", \"lvn\", \"orph\", \"solo_lvn\", \"to_ssa\", \"from_ssa\"];\n\n\n\npub enum LVNChoice {\n\n Solo,\n\n Bool(bool)\n\n}\n\n\n\nimpl LVNChoice {\n\n pub fn run_lvn(&self) -> bool {\n\n match self {\n\n LVNChoice::Solo => true,\n\n LVNChoice::Bool(b) => *b\n\n }\n\n }\n\n\n\n pub fn run_solo(&self) -> bool {\n\n match self {\n\n LVNChoice::Solo => true,\n", "file_path": "src/transformers/config.rs", "rank": 95, "score": 5.775092532665026 }, { "content": " }\n\n Op::Br => {\n\n let true_label = &labels[0];\n\n let false_label = &labels[1];\n\n\n\n let true_target = map.get(&true_label).unwrap_or_else(|| {\n\n panic!(\n\n \"Unable to locate label {}\",\n\n namer().get_string(&(true_label.0))\n\n )\n\n });\n\n\n\n let false_target = map.get(&false_label).unwrap_or_else(|| {\n\n panic!(\n\n \"Unable to locate label {}\",\n\n namer().get_string(&(false_label.0))\n\n )\n\n });\n\n\n\n last_block.out.replace(Some(Link::Branch {\n", "file_path": "src/transformers/cfg.rs", "rank": 96, "score": 5.690184971645172 }, { "content": " }\n\n\n\n if found {\n\n continue;\n\n }\n\n }\n\n\n\n let new = Instr::Value {\n\n op: Op::Phi,\n\n dest: *var,\n\n r_type: r_type.clone(),\n\n args: vec![*var],\n\n funcs: vec![],\n\n labels: vec![block_label],\n\n };\n\n // eprintln!(\"Inserting phi node for {} in {}\", var, node.label());\n\n contents.0.insert(1, new);\n\n defs.insert(node.label());\n\n\n\n\n", "file_path": "src/transformers/ssa.rs", "rank": 97, "score": 5.65467748620078 }, { "content": " update.push((node.label(), *label));\n\n break\n\n }\n\n }\n\n }\n\n }\n\n\n\n for (node, target) in update {\n\n let new_ref = &replacement_map[&target];\n\n let new_label= new_ref.upgrade().unwrap().label();\n\n map[&node].replace_link(target, new_ref.clone(), new_label)\n\n }\n\n\n\n repair_predecessor_links(blocks);\n\n\n\n }\n\n\n", "file_path": "src/transformers/cfg.rs", "rank": 98, "score": 5.651029888093646 }, { "content": "use std::fmt::{self,Display};\n\nuse std::ops::{Add, Mul, Div, Sub, BitAnd, BitOr, Not};\n\n\n\nuse serde::{self, Deserialize, Serialize};\n\n\n\n\n\n#[derive(Serialize, Deserialize, Debug, Clone)]\n\n#[serde(rename_all = \"lowercase\")]\n\npub enum Type {\n\n Int,\n\n Bool,\n\n Ptr(Box<Type>),\n\n Float,\n\n}\n\n\n\n#[derive(Serialize, Deserialize, Debug, Clone)]\n\n#[serde(untagged)]\n\npub enum Literal {\n\n Int(i64),\n\n Bool(bool),\n", "file_path": "src/serde_structs/basic_types.rs", "rank": 99, "score": 5.64965920689975 } ]
Rust
main/src/main.rs
kirch7/shaat
1479561bc3d8329940f693c7708e7cfa71a3fcc9
#[macro_use] extern crate actix; extern crate actix_web; extern crate cookie; extern crate crypto; #[macro_use] extern crate diesel; extern crate env_logger; extern crate futures; #[macro_use] extern crate juniper; #[macro_use] extern crate lazy_static; extern crate listenfd; extern crate messages; extern crate r2d2; #[macro_use] extern crate serde_derive; extern crate serde; extern crate serde_json; extern crate static_cache; extern crate time; use actix::{Addr, Arbiter, Syn, SyncArbiter}; use actix_web::middleware::Logger; use actix_web::{http::Method, App, HttpResponse}; use diesel::r2d2::ConnectionManager; use diesel::SqliteConnection; use std::sync::Arc; mod auth; mod db; mod graphql; mod messajes; mod statiq; mod users; mod ws; use auth::{CookieIdentityPolicy, IdentityService}; fn main() -> Result<(), Box<dyn std::error::Error>> { ::std::env::set_var("RUST_LOG", "actix_web=info"); let addr = get_envvar("SHAAT_ADDR").ok_or("SHAAT_ADDR must be set")?; let db_addr = get_envvar("SHAAT_DB").ok_or("SHAAT_DB must be set")?; let _ = get_envvar("SHAAT_STATIC").ok_or("SHAAT_STATIC must be set")?; env_logger::init(); println!("loading users"); users::load(&db_addr).unwrap(); println!("loading messages"); messajes::load(&db_addr).unwrap(); println!("Okay"); println!("http://{}", addr); let sys = actix::System::new("shaat"); let a_server: Addr<Syn, _> = Arbiter::start(|_| ws::ChatServer::default()); let db_manager = ConnectionManager::<SqliteConnection>::new(db_addr); let db_pool = r2d2::Pool::builder().build(db_manager)?; let db_server = SyncArbiter::start(1, move || db::DbExecutor(db_pool.clone())); let schema = Arc::new(graphql::create_schema()); let graphql_addr = SyncArbiter::start(1, move || graphql::GraphQLExecutor::new(schema.clone())); let http_server = actix_web::server::new(move || { let ws_state = ws::WsChatSessionState { addr: a_server.clone(), username: String::default(), }; let db_state = db::State { db: db_server.clone(), }; let graphql_state = graphql::AppState { executor: graphql_addr.clone(), }; vec![ App::new() .middleware(Logger::default()) .prefix("/static") .resource("/{filename}", |r| r.f(statiq::handle_static)) .boxed(), App::with_state((ws_state, db_state, graphql_state)) .middleware(Logger::default()) .middleware(IdentityService::new( CookieIdentityPolicy::new(&[0; 32]) .name("shaat-auth") .secure(false), )) .resource("/ws/", |r| r.get().f(ws::handle_ws)) .resource("/graphql", |r| { r.method(Method::POST).with(graphql::graphql) }) .resource("/graphiql", |r| r.method(Method::GET).f(graphql::graphiql)) .resource("/login", |r| { r.method(Method::POST).with(auth::handle_login_post); r.method(Method::GET).f(auth::handle_login_get); }) .resource("/logout", |r| r.f(auth::handle_logout)) .resource("/", |r| r.f(auth::handle_index)) .boxed(), ] }); let mut manager = listenfd::ListenFd::from_env(); let http_server = if let Some(li) = manager.take_tcp_listener(0).map_err(|e| e.to_string())? { http_server.listen(li) } else { http_server.bind(addr).map_err(|e| e.to_string())? }; http_server.start(); let _ = sys.run(); Ok(()) } #[inline] fn get_envvar(key: &str) -> Option<String> { std::env::vars() .find(|(key_, _value)| key_ == key) .map(|(_key, value)| value) } #[inline] fn bad_request() -> HttpResponse { HttpResponse::BadRequest().finish() }
#[macro_use] extern crate actix; extern crate actix_web; extern crate cookie; extern crate crypto; #[macro_use] extern crate diesel; extern crate env_logger; extern crate futures; #[macro_use] extern crate juniper; #[macro_use] extern crate lazy_static; extern crate listenfd; extern crate messages; extern crate r2d2; #[macro_use] extern crate serde_derive; extern crate serde; extern crate serde_json; extern crate static_cache; extern crate time; use actix::{Addr, Arbiter, Syn, SyncArbiter}; use actix_web::middleware::Logger; use actix_web::{http::Method, App, HttpResponse}; use diesel::r2d2::ConnectionManager; use diesel::SqliteConnection; use std::sync::Arc; mod auth; mod db; mod graphql; mod messajes; mod statiq; mod users; mod ws; use auth::{CookieIdentityPolicy, IdentityService}; fn main() -> Result<(), Box<dyn std::error::Error>> { ::std::env::set_var("RUST_LOG", "actix_web=info"); let addr = get_envvar("SHAAT_ADDR").ok_or("SHAAT_ADDR must be set")?; let db_addr = get_envvar("SHAAT_DB").ok_or("SHAAT_DB must be set")?; let _ = get_envvar("SHAAT_STATIC").ok_or("SHAAT_STATIC must be set")?; env_logger::init(); println!("loading users"); users::load(&db_addr).unwrap(); println!("loading messages"); messajes::load(&db_addr).unwrap(); println!("Okay"); println!("http://{}", addr); let sys = actix::System::new("shaat"); let a_server: Addr<Syn, _> = Arbiter::start(|_| ws::ChatServer::default()); let db_manager = ConnectionManager::<SqliteConnection>::new(db_addr); let db_pool = r2d2::Pool::builder().build(db_manager)?; let db_server = SyncArbiter::start(1, move || db::DbExecutor(db_pool.clone())); let schema = Arc::new(graphql::create_schema()); let graphql_addr = SyncArbiter::start(1, move || graphql::GraphQLExecutor::new(schema.clone())); let http_server = actix_web::server::new(move || { let ws_state = ws::WsChatSessionState { addr: a_server.clone(), username: String::default(), }; let db_state = db::State { db: db_server.clone(), };
#[inline] fn get_envvar(key: &str) -> Option<String> { std::env::vars() .find(|(key_, _value)| key_ == key) .map(|(_key, value)| value) } #[inline] fn bad_request() -> HttpResponse { HttpResponse::BadRequest().finish() }
let graphql_state = graphql::AppState { executor: graphql_addr.clone(), }; vec![ App::new() .middleware(Logger::default()) .prefix("/static") .resource("/{filename}", |r| r.f(statiq::handle_static)) .boxed(), App::with_state((ws_state, db_state, graphql_state)) .middleware(Logger::default()) .middleware(IdentityService::new( CookieIdentityPolicy::new(&[0; 32]) .name("shaat-auth") .secure(false), )) .resource("/ws/", |r| r.get().f(ws::handle_ws)) .resource("/graphql", |r| { r.method(Method::POST).with(graphql::graphql) }) .resource("/graphiql", |r| r.method(Method::GET).f(graphql::graphiql)) .resource("/login", |r| { r.method(Method::POST).with(auth::handle_login_post); r.method(Method::GET).f(auth::handle_login_get); }) .resource("/logout", |r| r.f(auth::handle_logout)) .resource("/", |r| r.f(auth::handle_index)) .boxed(), ] }); let mut manager = listenfd::ListenFd::from_env(); let http_server = if let Some(li) = manager.take_tcp_listener(0).map_err(|e| e.to_string())? { http_server.listen(li) } else { http_server.bind(addr).map_err(|e| e.to_string())? }; http_server.start(); let _ = sys.run(); Ok(()) }
function_block-function_prefix_line
[ { "content": "pub fn load(db: &str) -> Result<(), ()> {\n\n let db = SqliteConnection::establish(db).unwrap();\n\n\n\n let mut users = USERS.write().unwrap();\n\n ::db::schema::users::dsl::users\n\n .load::<::db::models::User>(&db)\n\n .map_err(|_| ())?\n\n .iter()\n\n .map(|user| User {\n\n username: user.username.clone(),\n\n color: user.color.clone(),\n\n password: user.password.clone(),\n\n })\n\n .for_each(|user| {\n\n let _ = users.insert(user.username.clone(), user);\n\n });\n\n\n\n Ok(())\n\n}\n", "file_path": "main/src/users/mod.rs", "rank": 0, "score": 165547.95603954262 }, { "content": "pub fn load(db: &str) -> Result<(), ()> {\n\n use db::schema::messages::dsl::{id, messages};\n\n\n\n let db = SqliteConnection::establish(db).unwrap();\n\n\n\n messages\n\n .order(id.asc())\n\n .load::<::db::models::Message>(&db)\n\n .map_err(|_| ())?\n\n .iter()\n\n .map(|ref m| Message {\n\n username: m.username.clone(),\n\n message: m.message.clone().into_bytes(),\n\n })\n\n .for_each(|m| {\n\n let _ = MESSAGES.insert_message(m);\n\n });\n\n\n\n Ok(())\n\n}\n", "file_path": "main/src/messajes.rs", "rank": 1, "score": 149134.03832870812 }, { "content": "pub fn graphql(\n\n (req, data): (\n\n HttpRequest<(WsChatSessionState, ::db::State, ::graphql::AppState)>,\n\n Json<GraphQLData>,\n\n ),\n\n) -> FutureResponse<HttpResponse> {\n\n req.state()\n\n .2\n\n .executor\n\n .send(data.0)\n\n .from_err()\n\n .and_then(|res| match res {\n\n Ok(user) => Ok(HttpResponse::Ok()\n\n .content_type(\"application/json\")\n\n .body(user)),\n\n Err(_) => Ok(HttpResponse::InternalServerError().into()),\n\n })\n\n .responder()\n\n}\n\n\n\nimpl Handler<GraphQLData> for GraphQLExecutor {\n\n type Result = Result<String, Error>;\n\n\n\n fn handle(&mut self, msg: GraphQLData, _: &mut Self::Context) -> Self::Result {\n\n let res = msg.0.execute(&self.schema, &());\n\n let res_text = serde_json::to_string(&res)?;\n\n Ok(res_text)\n\n }\n\n}\n", "file_path": "main/src/graphql/mod.rs", "rank": 2, "score": 134532.86430794373 }, { "content": "pub fn create_schema() -> Schema {\n\n Schema::new(QueryRoot, ())\n\n}\n", "file_path": "main/src/graphql/schema.rs", "rank": 3, "score": 129579.50079365767 }, { "content": "#[derive(GraphQLObject)]\n\n#[graphql(description = \"A user for shaat\")]\n\nstruct User {\n\n username: String,\n\n color: String,\n\n}\n\n\n", "file_path": "main/src/graphql/schema.rs", "rank": 4, "score": 117773.08223755713 }, { "content": "fn send_to(\n\n req: HttpRequest<(WsChatSessionState, ::db::State, ::graphql::AppState)>,\n\n to: &'static str,\n\n) -> Box<Future<Item = HttpResponse, Error = Error>> {\n\n let fut = req\n\n .concat2()\n\n .from_err()\n\n .and_then(move |_| Ok(HttpResponse::Found().header(\"location\", to).finish()));\n\n Box::new(fut)\n\n}\n", "file_path": "main/src/auth/mod.rs", "rank": 5, "score": 111380.89878596214 }, { "content": "pub fn handle_ws(\n\n req: HttpRequest<(WsChatSessionState, ::db::State, ::graphql::AppState)>,\n\n) -> Result<HttpResponse, actix_web::Error> {\n\n let username = {\n\n let req = req.clone();\n\n match req.identity() {\n\n Some(username) => username.into(),\n\n None => {\n\n return Ok(::bad_request());\n\n }\n\n }\n\n };\n\n ws::start(req, WsChatSession::new(username))\n\n}\n", "file_path": "main/src/ws/mod.rs", "rank": 6, "score": 110348.57890349146 }, { "content": "pub fn register_message(\n\n username: &str,\n\n message: &[u8],\n\n db: &Addr<Syn, DbExecutor>,\n\n) -> Result<(), ()> {\n\n match (*MESSAGES).insert_message(Message {\n\n message: message.to_owned(),\n\n username: username.to_owned(),\n\n }) {\n\n Ok(id) => {\n\n let message = message.to_owned();\n\n let _insertion = db\n\n .send(::db::InsertMessage(::db::models::Message {\n\n id,\n\n message: String::from_utf8(message).unwrap(),\n\n username: username.to_owned(),\n\n }))\n\n .wait();\n\n\n\n Ok(())\n\n }\n\n Err(_) => Err(()),\n\n }\n\n}\n\n\n", "file_path": "main/src/messajes.rs", "rank": 7, "score": 108126.32424805788 }, { "content": "pub fn graphiql(\n\n req: HttpRequest<(WsChatSessionState, ::db::State, AppState)>,\n\n) -> Result<HttpResponse, Error> {\n\n use actix_web::HttpMessage;\n\n\n\n let host = req\n\n .headers()\n\n .get(\"host\")\n\n .map(|e| e.to_str().unwrap_or(\"\"))\n\n .unwrap_or(\"\");\n\n let html = graphiql_source(&format!(\"//{}/graphql\", host));\n\n Ok(HttpResponse::Ok()\n\n .content_type(\"text/html; charset=utf-8\")\n\n .body(html))\n\n}\n\n\n", "file_path": "main/src/graphql/mod.rs", "rank": 8, "score": 106391.40045791218 }, { "content": "pub fn handle_index(\n\n req: HttpRequest<(WsChatSessionState, ::db::State, ::graphql::AppState)>,\n\n) -> Box<Future<Item = HttpResponse, Error = Error>> {\n\n let in_users = {\n\n let id = &req.identity();\n\n if id.is_none() {\n\n false\n\n } else {\n\n (*::users::USERS.read().unwrap()).contains_key(id.unwrap())\n\n }\n\n };\n\n if in_users {\n\n let fut = req\n\n .concat2()\n\n .from_err()\n\n .and_then(|_| Ok(super::statiq::handle_html(\"index.html\")));\n\n Box::new(fut)\n\n } else {\n\n let fut = req\n\n .concat2()\n\n .from_err()\n\n .and_then(|_| Ok(HttpResponse::Found().header(\"location\", \"/login\").finish()));\n\n Box::new(fut)\n\n }\n\n}\n\n\n", "file_path": "main/src/auth/mod.rs", "rank": 10, "score": 101896.96692928512 }, { "content": "pub fn handle_logout(\n\n mut req: HttpRequest<(WsChatSessionState, ::db::State, ::graphql::AppState)>,\n\n) -> HttpResponse {\n\n req.forget();\n\n HttpResponse::Found().header(\"location\", \"/\").finish()\n\n}\n\n\n", "file_path": "main/src/auth/mod.rs", "rank": 11, "score": 101896.96692928512 }, { "content": "#[inline]\n\nfn get_html(subname: &str) -> Result<Vec<u8>, String> {\n\n let filename = (*STATIC_PATH).clone() + \"/\" + subname;\n\n CACHE.get(&PathBuf::from(filename))\n\n}\n\n\n", "file_path": "main/src/statiq.rs", "rank": 12, "score": 98998.50185941572 }, { "content": "pub fn handle_login_post(\n\n (req, form): (\n\n HttpRequest<(WsChatSessionState, ::db::State, ::graphql::AppState)>,\n\n Form<Login>,\n\n ),\n\n) -> Box<Future<Item = HttpResponse, Error = Error>> {\n\n let already_logged = {\n\n let id = &req.identity();\n\n id.is_some()\n\n };\n\n\n\n if already_logged {\n\n send_to(req, \"/\")\n\n } else {\n\n let mut req3 = req.clone();\n\n\n\n req.concat2()\n\n .from_err()\n\n .and_then(move |_| {\n\n let mut s = String::default();\n", "file_path": "main/src/auth/mod.rs", "rank": 13, "score": 98637.21602490812 }, { "content": "pub fn handle_login_get(\n\n req: HttpRequest<(WsChatSessionState, ::db::State, ::graphql::AppState)>,\n\n) -> Box<Future<Item = HttpResponse, Error = Error>> {\n\n let already_logged = {\n\n let id = &req.identity();\n\n if id.is_none() {\n\n false\n\n } else {\n\n (*::users::USERS.read().unwrap()).contains_key(id.unwrap())\n\n }\n\n };\n\n if already_logged {\n\n send_to(req, \"/\")\n\n } else {\n\n req.concat2()\n\n .from_err()\n\n .and_then(move |_| Ok(::statiq::handle_html(\"login.html\")))\n\n .responder()\n\n }\n\n}\n\n\n", "file_path": "main/src/auth/mod.rs", "rank": 14, "score": 98637.21602490812 }, { "content": "fn hash(input: &str) -> String {\n\n let mut hasher = Sha3::sha3_256();\n\n hasher.input_str(input);\n\n hasher.result_str()\n\n}\n\n\n", "file_path": "main/src/auth/mod.rs", "rank": 15, "score": 95535.26208481823 }, { "content": "#[derive(GraphQLObject)]\n\n#[graphql(description = \"A shaat message\")]\n\nstruct Message {\n\n username: String,\n\n message: String,\n\n}\n\n\n\npub struct QueryRoot;\n\n\n\ngraphql_object!(QueryRoot: () |&self| {\n\n field user(&executor, username: String) -> FieldResult<User> {\n\n let users = ::users::USERS\n\n .read()\n\n .unwrap();\n\n match users.get(&username) {\n\n Some(user) => Ok(User {\n\n username: user.username.clone(),\n\n color: user.color.clone(),\n\n }),\n\n None => Err(FieldError::new(\n\n \"User not found\",\n\n graphql_value!({ \"some error\": \"User not found\" })\n", "file_path": "main/src/graphql/schema.rs", "rank": 16, "score": 94977.11259218342 }, { "content": "pub fn handle_insert_on_html(\n\n filename: &str,\n\n insertions: &HashMap<String, String>,\n\n) -> HttpResponse {\n\n let content0 = get_html(&filename);\n\n\n\n if content0.is_ok() {\n\n let mime = \"text/html\";\n\n let content = String::from_utf8(content0.unwrap()).unwrap();\n\n let mut out_content = Vec::default();\n\n for line in content.lines() {\n\n let line0 = line.trim();\n\n if line0.starts_with(\"<!--\") && line0.ends_with(\"-->\") {\n\n let key = line0\n\n .replace(\"<!--\", \"\")\n\n .replace(\"-->\", \"\")\n\n .trim()\n\n .to_string();\n\n let value = insertions\n\n .get(&key)\n", "file_path": "main/src/statiq.rs", "rank": 17, "score": 80888.44164742087 }, { "content": "use juniper::RootNode;\n\nuse juniper::{FieldError, FieldResult};\n\nuse messages::{Id, MessageGuard};\n\n\n\n#[derive(GraphQLObject)]\n\n#[graphql(description = \"A user for shaat\")]\n", "file_path": "main/src/graphql/schema.rs", "rank": 18, "score": 72743.82203433556 }, { "content": " )),\n\n }\n\n }\n\n\n\n field message(&executor, last_n: String) -> FieldResult<Vec<Message>> {\n\n let last_n = last_n.parse::<Id>();\n\n if last_n.is_err() || last_n.clone().unwrap() < 0 {\n\n Err(FieldError::new(\n\n \"Invalid id\",\n\n graphql_value!({ \"some error\": \"Invalid id\" })\n\n ))\n\n } else {\n\n let messages: Vec<_> = ::messajes::MESSAGES\n\n .get_latest(last_n.unwrap())\n\n .iter()\n\n .map(|m| Message {\n\n username: m.username.clone(),\n\n message: String::from_utf8(m.message.clone()).unwrap(),\n\n })\n\n .collect();\n\n Ok(messages)\n\n }\n\n }\n\n});\n\n\n\npub type Schema = RootNode<'static, QueryRoot, ()>;\n\n\n", "file_path": "main/src/graphql/schema.rs", "rank": 19, "score": 72739.5242636118 }, { "content": "table! {\n\n users (username) {\n\n username -> Text,\n\n color -> Text,\n\n password -> Text,\n\n }\n\n}\n\n\n\ntable! {\n\n messages (id) {\n\n id -> BigInt,\n\n username -> Text,\n\n message -> Text,\n\n }\n\n}\n", "file_path": "main/src/db/schema.rs", "rank": 20, "score": 72478.97865302811 }, { "content": "use std::collections::HashMap;\n\nuse std::sync::{Arc, RwLock};\n\n\n\nuse diesel::{Connection, RunQueryDsl, SqliteConnection};\n\n\n\nlazy_static! {\n\n pub static ref USERS: Arc<RwLock<HashMap<String, User>>> = Arc::default();\n\n}\n\n\n\npub struct User {\n\n pub username: String,\n\n pub color: String,\n\n pub password: String,\n\n}\n\n\n", "file_path": "main/src/users/mod.rs", "rank": 21, "score": 71587.83117004794 }, { "content": "use actix::{Actor, Addr, Handler, Message, Syn, SyncContext};\n\nuse actix_web::{AsyncResponder, Error, FutureResponse, HttpRequest, HttpResponse, Json};\n\nuse futures::Future;\n\nuse juniper::http::{graphiql::graphiql_source, GraphQLRequest};\n\nuse serde_json;\n\nuse std::sync::Arc;\n\nuse ws::WsChatSessionState;\n\n\n\nmod schema;\n\npub use self::schema::create_schema;\n\n\n\n#[derive(Serialize, Deserialize)]\n\npub struct GraphQLData(GraphQLRequest);\n\n\n\nimpl Message for GraphQLData {\n\n type Result = Result<String, Error>;\n\n}\n\n\n\npub struct AppState {\n\n pub executor: Addr<Syn, GraphQLExecutor>,\n", "file_path": "main/src/graphql/mod.rs", "rank": 22, "score": 71303.7200867824 }, { "content": "}\n\n\n\npub struct GraphQLExecutor {\n\n schema: Arc<schema::Schema>,\n\n}\n\n\n\nimpl GraphQLExecutor {\n\n pub fn new(schema: Arc<schema::Schema>) -> GraphQLExecutor {\n\n GraphQLExecutor { schema }\n\n }\n\n}\n\n\n\nimpl Actor for GraphQLExecutor {\n\n type Context = SyncContext<Self>;\n\n}\n\n\n", "file_path": "main/src/graphql/mod.rs", "rank": 23, "score": 71284.95867787123 }, { "content": "// Copyright 2018 Cássio Kirch.\n\n\n\n// Originally licensed under Apache License.\n\n// https://github.com/actix/examples/tree/master/cookie-session\n\n// With modifications made by the Shaat project author(s).\n\n\n\nuse std::rc::Rc;\n\n\n\nuse cookie::{Cookie, CookieJar, Key};\n\nuse futures::future::{err as FutErr, ok as FutOk, FutureResult};\n\nuse futures::Future;\n\nuse time::Duration;\n\n\n\nuse actix_web::http::header::{self, HeaderValue};\n\nuse actix_web::middleware::{Middleware, Response, Started};\n\nuse actix_web::{Error, HttpRequest, HttpResponse};\n\n\n\n/// Trait provides identity service for the request.\n", "file_path": "main/src/auth/cookies.rs", "rank": 24, "score": 71231.85160797428 }, { "content": "\n\n fn set_cookie(&self, resp: &mut HttpResponse, id: Option<String>) -> Result<(), Error> {\n\n let some = id.is_some();\n\n {\n\n let id = id.unwrap_or_else(String::new);\n\n let mut cookie = Cookie::new(self.name.clone(), id);\n\n cookie.set_path(self.path.clone());\n\n cookie.set_secure(self.secure);\n\n cookie.set_http_only(true);\n\n\n\n if let Some(ref domain) = self.domain {\n\n cookie.set_domain(domain.clone());\n\n }\n\n\n\n if let Some(max_age) = self.max_age {\n\n cookie.set_max_age(max_age);\n\n }\n\n\n\n let mut jar = CookieJar::new();\n\n if some {\n", "file_path": "main/src/auth/cookies.rs", "rank": 25, "score": 71228.95102044208 }, { "content": "\n\nimpl<S> IdentityPolicy<S> for CookieIdentityPolicy {\n\n type Identity = CookieIdentity;\n\n type Future = FutureResult<CookieIdentity, Error>;\n\n\n\n fn from_request(&self, req: &mut HttpRequest<S>) -> Self::Future {\n\n let identity = self.0.load(req);\n\n FutOk(CookieIdentity {\n\n identity,\n\n changed: false,\n\n inner: Rc::clone(&self.0),\n\n })\n\n }\n\n}\n", "file_path": "main/src/auth/cookies.rs", "rank": 26, "score": 71226.15509861808 }, { "content": " pub fn new(key: &[u8]) -> CookieIdentityPolicy {\n\n CookieIdentityPolicy(Rc::new(CookieIdentityInner::new(key)))\n\n }\n\n\n\n /// Sets the `path` field in the session cookie being built.\n\n #[allow(dead_code)]\n\n pub fn path<S: Into<String>>(mut self, value: S) -> CookieIdentityPolicy {\n\n Rc::get_mut(&mut self.0).unwrap().path = value.into();\n\n self\n\n }\n\n\n\n /// Sets the `name` field in the session cookie being built.\n\n pub fn name<S: Into<String>>(mut self, value: S) -> CookieIdentityPolicy {\n\n Rc::get_mut(&mut self.0).unwrap().name = value.into();\n\n self\n\n }\n\n\n\n /// Sets the `domain` field in the session cookie being built.\n\n #[allow(dead_code)]\n\n pub fn domain<S: Into<String>>(mut self, value: S) -> CookieIdentityPolicy {\n", "file_path": "main/src/auth/cookies.rs", "rank": 27, "score": 71225.70634420539 }, { "content": " });\n\n Ok(Started::Future(Box::new(fut)))\n\n }\n\n\n\n fn response(&self, req: &mut HttpRequest<S>, resp: HttpResponse) -> Result<Response, Error> {\n\n if let Some(mut id) = req.extensions_mut().remove::<IdentityBox>() {\n\n id.0.write(resp)\n\n } else {\n\n Ok(Response::Done(resp))\n\n }\n\n }\n\n}\n\n\n\n/// Identity that uses private cookies as identity storage\n\npub struct CookieIdentity {\n\n changed: bool,\n\n identity: Option<String>,\n\n inner: Rc<CookieIdentityInner>,\n\n}\n\n\n", "file_path": "main/src/auth/cookies.rs", "rank": 28, "score": 71225.47051242868 }, { "content": " Rc::get_mut(&mut self.0).unwrap().domain = Some(value.into());\n\n self\n\n }\n\n\n\n /// Sets the `secure` field in the session cookie being built.\n\n ///\n\n /// If the `secure` field is set, a cookie will only be transmitted when the\n\n /// connection is secure - i.e. `https`\n\n pub fn secure(mut self, value: bool) -> CookieIdentityPolicy {\n\n Rc::get_mut(&mut self.0).unwrap().secure = value;\n\n self\n\n }\n\n\n\n /// Sets the `max-age` field in the session cookie being built.\n\n #[allow(dead_code)]\n\n pub fn max_age(mut self, value: Duration) -> CookieIdentityPolicy {\n\n Rc::get_mut(&mut self.0).unwrap().max_age = Some(value);\n\n self\n\n }\n\n}\n", "file_path": "main/src/auth/cookies.rs", "rank": 29, "score": 71225.2463971078 }, { "content": "impl Identity for CookieIdentity {\n\n fn identity(&self) -> Option<&str> {\n\n self.identity.as_ref().map(|s| s.as_ref())\n\n }\n\n\n\n fn remember(&mut self, value: String) {\n\n self.changed = true;\n\n self.identity = Some(value);\n\n }\n\n\n\n fn forget(&mut self) {\n\n self.changed = true;\n\n self.identity = None;\n\n }\n\n\n\n fn write(&mut self, mut resp: HttpResponse) -> Result<Response, Error> {\n\n if self.changed {\n\n let _ = self.inner.set_cookie(&mut resp, self.identity.take());\n\n }\n\n Ok(Response::Done(resp))\n\n }\n\n}\n\n\n", "file_path": "main/src/auth/cookies.rs", "rank": 30, "score": 71223.89518594992 }, { "content": " jar.add_original(cookie.clone());\n\n\n\n let cookie_opt = jar.private(&self.key).get(&self.name);\n\n if let Some(cookie) = cookie_opt {\n\n return Some(cookie.value().into());\n\n }\n\n }\n\n }\n\n }\n\n None\n\n }\n\n}\n\n\n\n/// Use cookies for request identity.\n\npub struct CookieIdentityPolicy(Rc<CookieIdentityInner>);\n\n\n\nimpl CookieIdentityPolicy {\n\n /// Construct new `CookieIdentityPolicy` instance.\n\n ///\n\n /// Panics if key length is less than 32 bytes.\n", "file_path": "main/src/auth/cookies.rs", "rank": 31, "score": 71223.66012023273 }, { "content": " jar.private(&self.key).add(cookie);\n\n } else {\n\n jar.add_original(cookie.clone());\n\n jar.private(&self.key).remove(cookie);\n\n }\n\n\n\n for cookie in jar.delta() {\n\n let val = HeaderValue::from_str(&cookie.to_string())?;\n\n resp.headers_mut().append(header::SET_COOKIE, val);\n\n }\n\n }\n\n\n\n Ok(())\n\n }\n\n\n\n fn load<S>(&self, req: &mut HttpRequest<S>) -> Option<String> {\n\n if let Ok(cookies) = req.cookies() {\n\n for cookie in cookies {\n\n if cookie.name() == self.name {\n\n let mut jar = CookieJar::new();\n", "file_path": "main/src/auth/cookies.rs", "rank": 32, "score": 71223.60824835098 }, { "content": "\n\n fn remember(&mut self, identity: String) {\n\n if let Some(id) = self.extensions_mut().get_mut::<IdentityBox>() {\n\n return id.0.remember(identity);\n\n }\n\n }\n\n\n\n fn forget(&mut self) {\n\n if let Some(id) = self.extensions_mut().get_mut::<IdentityBox>() {\n\n return id.0.forget();\n\n }\n\n }\n\n}\n\n\n", "file_path": "main/src/auth/cookies.rs", "rank": 33, "score": 71218.46776459031 }, { "content": "use actix::{Actor, Addr, Handler, Message, Syn, SyncContext};\n\n\n\nuse actix_web;\n\n\n\nuse diesel::r2d2::{ConnectionManager, Pool};\n\nuse diesel::{self, RunQueryDsl, SqliteConnection};\n\n\n\npub mod models;\n\npub mod schema;\n\n\n\npub struct DbExecutor(pub Pool<ConnectionManager<SqliteConnection>>);\n\n\n\n/// An state for actix\n\npub struct State {\n\n pub db: Addr<Syn, DbExecutor>,\n\n}\n\n\n\nimpl Actor for DbExecutor {\n\n type Context = SyncContext<Self>;\n\n}\n", "file_path": "main/src/db/mod.rs", "rank": 34, "score": 71043.79234466224 }, { "content": "\n\n let connection: &SqliteConnection = &self.0.get().unwrap();\n\n\n\n diesel::insert_into(users)\n\n .values(&new_user)\n\n .execute(connection)\n\n .map_err(|_| actix_web::error::ErrorInternalServerError(\"Error inserting person\"))?;\n\n\n\n Ok(user)\n\n }\n\n}\n\n\n\nimpl Handler<QueryMessage> for DbExecutor {\n\n type Result = Result<models::Message, actix_web::Error>;\n\n\n\n fn handle(&mut self, m: QueryMessage, _ctx: &mut Self::Context) -> Self::Result {\n\n use self::schema::messages::dsl::*;\n\n use diesel::QueryDsl;\n\n\n\n let connection: &SqliteConnection = &self.0.get().unwrap();\n", "file_path": "main/src/db/mod.rs", "rank": 35, "score": 71039.12907312036 }, { "content": " username: user.0.clone(),\n\n color: user.1.clone(),\n\n password: user.2.clone(),\n\n })\n\n .collect())\n\n }\n\n}\n\n\n\nimpl Handler<CreateUser> for DbExecutor {\n\n type Result = Result<models::User, actix_web::Error>;\n\n\n\n fn handle(&mut self, message: CreateUser, _ctx: &mut Self::Context) -> Self::Result {\n\n use self::schema::users::dsl::users;\n\n\n\n let user = message.0.clone();\n\n let new_user = models::NewUser {\n\n username: &user.username.clone(),\n\n color: &user.color.clone(),\n\n password: &user.password.clone(),\n\n };\n", "file_path": "main/src/db/mod.rs", "rank": 36, "score": 71039.06339341063 }, { "content": " \"Empty query result\",\n\n )))\n\n }\n\n}\n\n\n\nimpl Handler<QueryAllUsers> for DbExecutor {\n\n type Result = Result<Vec<models::User>, actix_web::Error>;\n\n\n\n fn handle(&mut self, _message: QueryAllUsers, _ctx: &mut Self::Context) -> Self::Result {\n\n use self::schema::users::dsl::*;\n\n use diesel::QueryDsl;\n\n\n\n let connection: &SqliteConnection = &self.0.get().unwrap();\n\n\n\n Ok(users\n\n .select((username, color, password))\n\n .load::<(String, String, String)>(connection)\n\n .map_err(|e| actix_web::error::ErrorInternalServerError(e.to_string()))?\n\n .iter()\n\n .map(|ref user| models::User {\n", "file_path": "main/src/db/mod.rs", "rank": 37, "score": 71038.93380102508 }, { "content": "\n\nimpl Handler<InsertMessage> for DbExecutor {\n\n type Result = Result<models::Message, actix_web::Error>;\n\n\n\n fn handle(&mut self, message: InsertMessage, _ctx: &mut Self::Context) -> Self::Result {\n\n use self::schema::messages::dsl::messages;\n\n\n\n let message = message.0.clone();\n\n let new_message = models::NewMessage {\n\n id: message.id,\n\n username: &message.username.clone(),\n\n message: &message.message.clone(),\n\n };\n\n\n\n let connection: &SqliteConnection = &self.0.get().unwrap();\n\n\n\n diesel::insert_into(messages)\n\n .values(&new_message)\n\n .execute(connection)\n\n .map_err(|_| actix_web::error::ErrorInternalServerError(\"Error inserting message\"))?;\n\n\n\n Ok(message)\n\n }\n\n}\n", "file_path": "main/src/db/mod.rs", "rank": 38, "score": 71037.18797301383 }, { "content": "impl Message for QueryUser {\n\n type Result = Result<models::User, actix_web::Error>;\n\n}\n\n\n\nimpl Message for QueryAllUsers {\n\n type Result = Result<Vec<models::User>, actix_web::Error>;\n\n}\n\n\n\nimpl Message for InsertMessage {\n\n type Result = Result<models::Message, actix_web::Error>;\n\n}\n\n\n\nimpl Message for QueryMessage {\n\n type Result = Result<models::Message, actix_web::Error>;\n\n}\n\n\n\nimpl Handler<QueryUser> for DbExecutor {\n\n type Result = Result<models::User, actix_web::Error>;\n\n\n\n fn handle(&mut self, message: QueryUser, _ctx: &mut Self::Context) -> Self::Result {\n", "file_path": "main/src/db/mod.rs", "rank": 39, "score": 71036.86894934531 }, { "content": " use self::schema::users::dsl::*;\n\n use diesel::QueryDsl;\n\n\n\n let connection: &SqliteConnection = &self.0.get().unwrap();\n\n\n\n let all_users = users\n\n .select((username, color, password))\n\n .load::<(String, String, String)>(connection)\n\n .map_err(|e| actix_web::error::ErrorInternalServerError(e.to_string()))?;\n\n all_users\n\n .iter()\n\n .find(|ref t| t.0 == message.0)\n\n .map(|user| {\n\n Ok(models::User {\n\n username: user.0.clone(),\n\n color: user.1.clone(),\n\n password: user.2.clone(),\n\n })\n\n })\n\n .unwrap_or_else(|| Err(actix_web::error::ErrorInternalServerError(\n", "file_path": "main/src/db/mod.rs", "rank": 40, "score": 71036.37766949245 }, { "content": "\n\n/// Structure to help new users insertion on database.\n\npub struct CreateUser(pub models::User);\n\n\n\n/// Structure to help query users by their names on database. pub\n\npub struct QueryUser(pub String);\n\n\n\n/// Structure to help query users by their names on database. pub\n\npub struct QueryAllUsers;\n\n\n\n/// Structure to help new users insertion on database.\n\npub struct InsertMessage(pub models::Message);\n\n\n\n/// Structure to help query users by their names on database.\n\npub struct QueryMessage(pub ::messages::Id);\n\n\n\nimpl Message for CreateUser {\n\n type Result = Result<models::User, actix_web::Error>;\n\n}\n\n\n", "file_path": "main/src/db/mod.rs", "rank": 41, "score": 71032.42666486031 }, { "content": "\n\n let all_messages = messages\n\n .select((id, username, message))\n\n .load::<(::messages::Id, String, String)>(connection)\n\n .map_err(|e| actix_web::error::ErrorInternalServerError(e.to_string()))?;\n\n all_messages\n\n .iter()\n\n .find(|ref tup| tup.0 == m.0)\n\n .map(|tuple| {\n\n Ok(models::Message {\n\n id: tuple.0,\n\n username: tuple.1.clone(),\n\n message: tuple.2.clone(),\n\n })\n\n })\n\n .unwrap_or_else(|| Err(actix_web::error::ErrorInternalServerError(\n\n \"Empty query result\",\n\n )))\n\n }\n\n}\n", "file_path": "main/src/db/mod.rs", "rank": 42, "score": 71031.86622422012 }, { "content": "use actix::{Recipient, Syn};\n\nuse actix_web::{self, ws, HttpRequest, HttpResponse};\n\n\n\npub use self::chat_server::ChatServer;\n\nuse self::session::WsChatSession;\n\npub use self::session::WsChatSessionState;\n\nuse auth::RequestIdentity;\n\n\n\nmod chat_server;\n\nmod session;\n\n\n\n#[derive(Message)]\n", "file_path": "main/src/ws/mod.rs", "rank": 43, "score": 70986.03800695947 }, { "content": "struct CookieIdentityInner {\n\n key: Key,\n\n name: String,\n\n path: String,\n\n domain: Option<String>,\n\n secure: bool,\n\n max_age: Option<Duration>,\n\n}\n\n\n\nimpl CookieIdentityInner {\n\n fn new(key: &[u8]) -> CookieIdentityInner {\n\n CookieIdentityInner {\n\n key: Key::from_master(key),\n\n name: \"actix-identity\".to_owned(),\n\n path: \"/\".to_owned(),\n\n domain: None,\n\n secure: true,\n\n max_age: None,\n\n }\n\n }\n", "file_path": "main/src/auth/cookies.rs", "rank": 44, "score": 70428.05894383743 }, { "content": "// Copyright 2018 Cássio Kirch.\n\n\n\nuse actix_web::{AsyncResponder, Error, Form, HttpRequest, HttpResponse};\n\nuse crypto::{digest::Digest, sha3::Sha3};\n\nuse futures::{Future, Stream};\n\nuse std::collections::HashMap;\n\n\n\nuse super::ws::WsChatSessionState;\n\n\n\nmod cookies;\n\npub use self::cookies::{CookieIdentityPolicy, IdentityService, RequestIdentity};\n\n\n\n#[derive(Debug, Deserialize)]\n\npub struct Login {\n\n username: Option<String>,\n\n password0: Option<String>,\n\n repassword: Option<String>,\n\n usercolor: Option<String>,\n\n}\n\n\n", "file_path": "main/src/auth/mod.rs", "rank": 45, "score": 70246.4883781979 }, { "content": " if !exists {\n\n let color = form.usercolor.clone().unwrap_or_else(|| \"#000000\".to_owned());\n\n let user_inner = ::db::models::User {\n\n username: username.clone().unwrap(),\n\n color: color.clone(),\n\n password: hash(&password0.clone().unwrap()),\n\n };\n\n match req3.state().1.db.send(::db::CreateUser(user_inner)).wait() {\n\n Err(e) => {\n\n s += &format!(\"{:?}\", e);\n\n }\n\n Ok(_) => {\n\n req3.remember(username.clone().unwrap());\n\n ::users::USERS.write().unwrap().insert(\n\n username.clone().unwrap(),\n\n ::users::User {\n\n username: username.unwrap().clone(),\n\n color,\n\n password: hash(&password0.unwrap().clone()),\n\n },\n", "file_path": "main/src/auth/mod.rs", "rank": 46, "score": 70240.6624329885 }, { "content": " if s.is_empty() {\n\n exists = {\n\n if password0.is_none() {\n\n s += \"No password. \";\n\n }\n\n ::users::USERS\n\n .read()\n\n .unwrap()\n\n .contains_key(&username.clone().unwrap())\n\n };\n\n if exists {\n\n if repassword.is_some() && repassword.unwrap() != \"\" {\n\n s += \"Re-register? \";\n\n }\n\n let password0 = password0.clone();\n\n if password0.is_some() {\n\n let password0 = hash(&password0.unwrap());\n\n let user = ::users::USERS.read().unwrap();\n\n let password = user\n\n .get(&username.clone().unwrap())\n", "file_path": "main/src/auth/mod.rs", "rank": 47, "score": 70237.65353017839 }, { "content": " );\n\n }\n\n };\n\n } else {\n\n req3.remember(username.clone().unwrap());\n\n }\n\n }\n\n\n\n if s.is_empty() {\n\n Ok(HttpResponse::Found().header(\"location\", \"/\").finish())\n\n } else {\n\n let mut hash = HashMap::default();\n\n hash.insert(\"ERRORMESSAGE\".into(), s);\n\n Ok(::statiq::handle_insert_on_html(\"login.html\", &hash))\n\n }\n\n })\n\n .responder()\n\n }\n\n}\n\n\n", "file_path": "main/src/auth/mod.rs", "rank": 48, "score": 70235.75485736993 }, { "content": "\n\n let username = form.username.clone();\n\n match &username {\n\n None => {\n\n s += \"undefined username. \";\n\n }\n\n Some(username) => {\n\n // Validating username.\n\n if username.len() < 2 {\n\n s += \"username too short. \";\n\n } else if username.len() > 12 {\n\n s += \"username too large. \";\n\n }\n\n }\n\n }\n\n\n\n let password0 = form.password0.clone();\n\n let repassword = form.repassword.clone();\n\n\n\n let mut exists = false;\n", "file_path": "main/src/auth/mod.rs", "rank": 49, "score": 70235.59207446176 }, { "content": " .unwrap()\n\n .password\n\n .clone();\n\n if password != password0 {\n\n s += \"Wrong password. \";\n\n }\n\n }\n\n } else {\n\n if repassword.is_none() {\n\n s += \"Enter password twice. \";\n\n }\n\n\n\n match &form.usercolor {\n\n None => {\n\n s += \"undefined usercolor. \";\n\n }\n\n Some(usercolor) => {\n\n // Validating color.\n\n if usercolor.len() != 7 {\n\n s += \"could not understand color. \";\n", "file_path": "main/src/auth/mod.rs", "rank": 50, "score": 70231.91970535317 }, { "content": " } else {\n\n for c in usercolor.chars() {\n\n if c == '#'\n\n || (c as u32 >= '0' as u32 && c as u32 <= '9' as u32)\n\n || (c as u32 >= 'a' as u32 && c as u32 <= 'f' as u32)\n\n || (c as u32 >= 'A' as u32 && c as u32 <= 'F' as u32)\n\n {\n\n continue;\n\n } else {\n\n s += \"could not understand color. \";\n\n break;\n\n }\n\n }\n\n }\n\n }\n\n }\n\n }\n\n }\n\n\n\n if s.is_empty() {\n", "file_path": "main/src/auth/mod.rs", "rank": 51, "score": 70231.91970535317 }, { "content": "pub fn handle_html(subname: &str) -> HttpResponse {\n\n let content = get_html(subname);\n\n if content.is_ok() {\n\n let mime = \"text/html\";\n\n HttpResponse::Ok().content_type(mime).body(content.unwrap())\n\n } else {\n\n bad_request()\n\n }\n\n}\n\n\n", "file_path": "main/src/statiq.rs", "rank": 52, "score": 69797.14607395613 }, { "content": "#[derive(Message)]\n\nstruct Disconnect {\n\n session_id: usize,\n\n}\n\n\n", "file_path": "main/src/ws/mod.rs", "rank": 53, "score": 67869.16998797687 }, { "content": "#[derive(Message)]\n\n#[rtype(usize)]\n\nstruct Connect {\n\n username: String,\n\n addr: Recipient<Syn, ::messajes::Message>,\n\n}\n\n\n", "file_path": "main/src/ws/mod.rs", "rank": 54, "score": 67869.04911803959 }, { "content": "pub fn handle_static(req: HttpRequest) -> HttpResponse {\n\n match req.match_info().get(\"filename\") {\n\n Some(filename) => {\n\n let ext = filename.split('.').last();\n\n if let Some(ext) = ext {\n\n let mime = match ext {\n\n \"js\" => \"application/javascript\",\n\n \"css\" => \"text/css\",\n\n _other => {\n\n eprintln!(\"{}\", ext);\n\n return bad_request();\n\n }\n\n };\n\n let filename = (*STATIC_PATH).clone() + \"/\" + filename;\n\n let content = CACHE.get(&PathBuf::from(filename));\n\n if content.is_ok() {\n\n HttpResponse::Ok().content_type(mime).body(content.unwrap())\n\n } else {\n\n eprintln!(\"cacaca\");\n\n bad_request()\n", "file_path": "main/src/statiq.rs", "rank": 55, "score": 67840.141521596 }, { "content": "/// Trait provides identity service for the request.\n\npub trait RequestIdentity {\n\n /// Return the claimed identity of the user associated request or\n\n /// ``None`` if no identity can be found associated with the request.\n\n fn identity(&self) -> Option<&str>;\n\n\n\n /// Remember identity.\n\n fn remember(&mut self, identity: String);\n\n\n\n /// This method is used to 'forget' the current identity on subsequent\n\n /// requests.\n\n fn forget(&mut self);\n\n}\n\n\n\nimpl<S> RequestIdentity for HttpRequest<S> {\n\n fn identity(&self) -> Option<&str> {\n\n if let Some(id) = self.extensions().get::<IdentityBox>() {\n\n return id.0.identity();\n\n }\n\n None\n\n }\n", "file_path": "main/src/auth/cookies.rs", "rank": 57, "score": 62625.71759832563 }, { "content": "/// An identity\n\npub trait Identity: 'static {\n\n fn identity(&self) -> Option<&str>;\n\n\n\n fn remember(&mut self, key: String);\n\n\n\n fn forget(&mut self);\n\n\n\n /// Write session to storage backend.\n\n fn write(&mut self, resp: HttpResponse) -> Result<Response, Error>;\n\n}\n\n\n", "file_path": "main/src/auth/cookies.rs", "rank": 58, "score": 62625.71759832563 }, { "content": "fn get_file_content(file: &File) -> io::Result<Vec<u8>> {\n\n let mut buf = BufReader::new(file);\n\n let mut v = Vec::default();\n\n buf.read_to_end(&mut v).map(|_| Ok(v))?\n\n}\n", "file_path": "libstatic/src/node.rs", "rank": 59, "score": 62573.44251462034 }, { "content": "struct IdentityBox(Box<Identity>);\n\n\n\n#[doc(hidden)]\n\nunsafe impl Send for IdentityBox {}\n\n#[doc(hidden)]\n\nunsafe impl Sync for IdentityBox {}\n\n\n\nimpl<S: 'static, T: IdentityPolicy<S>> Middleware<S> for IdentityService<T> {\n\n fn start(&self, req: &mut HttpRequest<S>) -> Result<Started, Error> {\n\n let mut req = req.clone();\n\n\n\n let fut = self\n\n .backend\n\n .from_request(&mut req)\n\n .then(move |res| match res {\n\n Ok(id) => {\n\n req.extensions_mut().insert(IdentityBox(Box::new(id)));\n\n FutOk(None)\n\n }\n\n Err(err) => FutErr(err),\n", "file_path": "main/src/auth/cookies.rs", "rank": 60, "score": 60204.42798611645 }, { "content": "/// Identity policy definition.\n\npub trait IdentityPolicy<S>: Sized + 'static {\n\n type Identity: Identity;\n\n type Future: Future<Item = Self::Identity, Error = Error>;\n\n\n\n /// Parse the session from request and load data from a service identity.\n\n fn from_request(&self, request: &mut HttpRequest<S>) -> Self::Future;\n\n}\n\n\n\n/// Middleware that implements identity service\n\npub struct IdentityService<T> {\n\n backend: T,\n\n}\n\n\n\nimpl<T> IdentityService<T> {\n\n /// Create new identity service with specified backend.\n\n pub fn new(backend: T) -> Self {\n\n IdentityService { backend }\n\n }\n\n}\n\n\n", "file_path": "main/src/auth/cookies.rs", "rank": 62, "score": 55883.21749299372 }, { "content": "// Copyright 2018 Cássio Kirch.\n\n\n\nuse actix::{Addr, Syn};\n\nuse db::DbExecutor;\n\nuse diesel::{Connection, ExpressionMethods, QueryDsl, RunQueryDsl, SqliteConnection};\n\nuse futures::Future;\n\nuse messages::{MessageGuard, Messages};\n\n\n\nlazy_static! {\n\n pub static ref MESSAGES: Messages<Message> = Messages::default();\n\n}\n\n\n\n#[derive(Clone, Default, Message)]\n\npub struct Message {\n\n pub message: Vec<u8>,\n\n pub username: String,\n\n}\n\n\n", "file_path": "main/src/messajes.rs", "rank": 63, "score": 48839.09318527344 }, { "content": "// Copyright 2018 Cássio Kirch.\n\n\n\nuse super::bad_request;\n\nuse actix_web::{HttpRequest, HttpResponse};\n\nuse std::collections::HashMap;\n\nuse std::path::PathBuf;\n\n\n", "file_path": "main/src/statiq.rs", "rank": 64, "score": 48567.15562779926 }, { "content": " }\n\n } else {\n\n bad_request()\n\n }\n\n }\n\n None => {\n\n bad_request()\n\n }\n\n }\n\n}\n", "file_path": "main/src/statiq.rs", "rank": 65, "score": 48561.88290898641 }, { "content": " .map(|value| value.as_str())\n\n .unwrap_or(\"\");\n\n out_content.extend(value.as_bytes());\n\n } else {\n\n out_content.extend(line.as_bytes());\n\n }\n\n out_content.extend(&[b'\\n']);\n\n }\n\n HttpResponse::Ok().content_type(mime).body(out_content)\n\n } else {\n\n bad_request()\n\n }\n\n}\n\n\n", "file_path": "main/src/statiq.rs", "rank": 66, "score": 48561.88290898641 }, { "content": "use super::schema::messages;\n\nuse super::schema::users;\n\n\n\n#[derive(Clone, Serialize, Queryable)]\n\npub struct User {\n\n pub username: String,\n\n pub color: String,\n\n pub password: String,\n\n}\n\n\n\n#[derive(Insertable)]\n\n#[table_name = \"users\"]\n\npub struct NewUser<'a> {\n\n pub username: &'a str,\n\n pub color: &'a str,\n\n pub password: &'a str,\n\n}\n\n\n\n#[derive(Clone, Serialize, Queryable)]\n\npub struct Message {\n", "file_path": "main/src/db/models.rs", "rank": 67, "score": 46044.20309269361 }, { "content": " pub id: ::messages::Id,\n\n pub username: String,\n\n pub message: String,\n\n}\n\n\n\n#[derive(Insertable)]\n\n#[table_name = \"messages\"]\n\npub struct NewMessage<'a> {\n\n pub id: ::messages::Id,\n\n pub username: &'a str,\n\n pub message: &'a str,\n\n}\n", "file_path": "main/src/db/models.rs", "rank": 68, "score": 46038.260635763756 }, { "content": "use super::ws;\n\nuse actix::{fut, ActorFuture, AsyncContext, ContextFutureSpawner, StreamHandler, WrapFuture};\n\nuse actix::{Actor, ActorContext, Addr, Handler, Running, Syn};\n\n\n\npub struct WsChatSessionState {\n\n pub addr: Addr<Syn, super::ChatServer>,\n\n pub username: String,\n\n}\n\n\n\npub struct WsChatSession {\n\n id: usize,\n\n username: String,\n\n}\n\n\n\nimpl WsChatSession {\n\n pub fn new(username: String) -> Self {\n\n WsChatSession {\n\n id: 0,\n\n username,\n\n }\n", "file_path": "main/src/ws/session.rs", "rank": 69, "score": 45996.327117772744 }, { "content": " }\n\n}\n\n\n\nimpl Actor for WsChatSession {\n\n type Context =\n\n ws::WebsocketContext<Self, (WsChatSessionState, ::db::State, ::graphql::AppState)>;\n\n\n\n fn started(&mut self, context: &mut Self::Context) {\n\n let address: Addr<Syn, _> = context.address();\n\n context\n\n .state()\n\n .0\n\n .addr\n\n .send(super::Connect {\n\n addr: address.recipient(),\n\n username: self.username.clone(),\n\n })\n\n .into_actor(self)\n\n .then(|response, actor, context| {\n\n match response {\n", "file_path": "main/src/ws/session.rs", "rank": 70, "score": 45993.25237751222 }, { "content": " }\n\n}\n\n\n\nimpl StreamHandler<ws::Message, ws::ProtocolError> for WsChatSession {\n\n fn handle(&mut self, msg: ws::Message, ctx: &mut Self::Context) {\n\n // process websocket messages\n\n match msg {\n\n ws::Message::Text(text) => {\n\n let text = text.trim();\n\n eprintln!(\"text: {:?}\", text);\n\n let text = text.as_bytes().to_vec();\n\n\n\n // Registering in server memory:\n\n let db = &ctx.state().1.db;\n\n\n\n ::messajes::register_message(&self.username, &text, db).unwrap_or(()); // todo: error handling\n\n\n\n // Send to all sessions:\n\n ctx.state().0.addr.do_send(::messajes::Message {\n\n username: self.username.clone(),\n", "file_path": "main/src/ws/session.rs", "rank": 71, "score": 45993.08676070909 }, { "content": " &mut self,\n\n message: ::messajes::Message,\n\n context: &mut Self::Context,\n\n ) -> Self::Result {\n\n let color = {\n\n match ::users::USERS.read().unwrap().get(&message.username) {\n\n Some(user) => user.color.clone(),\n\n None => \"#ffffff\".into(),\n\n }\n\n };\n\n let open = format!(\n\n \"<code style=\\\"color:{}\\\">{} </code>\",\n\n color, message.username\n\n );\n\n let mut m = open.into_bytes();\n\n let close = b\"<br/>\";\n\n m.extend_from_slice(&message.message);\n\n m.extend_from_slice(close);\n\n\n\n context.text(m);\n", "file_path": "main/src/ws/session.rs", "rank": 72, "score": 45990.56388697061 }, { "content": " Ok(response) => actor.id = response,\n\n _ => context.stop(),\n\n };\n\n fut::ok(())\n\n })\n\n .wait(context);\n\n }\n\n\n\n fn stopping(&mut self, context: &mut Self::Context) -> Running {\n\n context.state().0.addr.do_send(super::Disconnect {\n\n session_id: self.id,\n\n });\n\n Running::Stop\n\n }\n\n}\n\n\n\nimpl Handler<::messajes::Message> for WsChatSession {\n\n type Result = ();\n\n\n\n fn handle(\n", "file_path": "main/src/ws/session.rs", "rank": 73, "score": 45987.90721730806 }, { "content": " message: text,\n\n })\n\n }\n\n ws::Message::Binary(_) => {\n\n //// todo\n\n }\n\n ws::Message::Close(_) => {\n\n eprintln!(\"closing {}'s session\", self.username);\n\n ctx.stop();\n\n }\n\n _ => {\n\n eprintln!(\"other\");\n\n //// todo\n\n }\n\n };\n\n }\n\n}\n", "file_path": "main/src/ws/session.rs", "rank": 74, "score": 45987.74341466591 }, { "content": "\n\n fn handle(&mut self, message: super::Connect, _context: &mut Context<Self>) -> Self::Result {\n\n let id = self.get_new_id();\n\n let sessions = &mut self.sessions;\n\n let _ = sessions.insert(id, (message.username, message.addr));\n\n for (key, tuple) in sessions {\n\n println!(\"{}\\t{:?}\", key, tuple.0);\n\n }\n\n\n\n id\n\n }\n\n}\n\n\n\nimpl Handler<::messajes::Message> for ChatServer {\n\n type Result = ();\n\n\n\n fn handle(\n\n &mut self,\n\n message: ::messajes::Message,\n\n _context: &mut Context<Self>,\n\n ) -> Self::Result {\n\n self.send_message(&message);\n\n }\n\n}\n", "file_path": "main/src/ws/chat_server.rs", "rank": 75, "score": 43979.1763305677 }, { "content": "use actix::{Actor, Context, Handler, Recipient, Syn};\n\nuse std::collections::HashMap;\n\n\n\n#[derive(Default, Message)]\n\npub struct ChatServer {\n\n sessions: HashMap<usize, (String, Recipient<Syn, ::messajes::Message>)>,\n\n}\n\n\n\nimpl ChatServer {\n\n pub fn send_message(&self, message: &::messajes::Message) {\n\n self.sessions\n\n .iter()\n\n .map(|(_id, tuple)| &tuple.1)\n\n .for_each(|recipient| {\n\n let _ = recipient.do_send(message.clone()); //// todo: erro handling\n\n });\n\n }\n\n\n\n pub fn get_new_id(&mut self) -> usize {\n\n (0..)\n", "file_path": "main/src/ws/chat_server.rs", "rank": 76, "score": 43979.10558480178 }, { "content": " .filter(|id| !self.sessions.contains_key(&id))\n\n .nth(0)\n\n .unwrap()\n\n }\n\n}\n\n\n\nimpl Actor for ChatServer {\n\n type Context = Context<Self>;\n\n}\n\n\n\nimpl Handler<super::Disconnect> for ChatServer {\n\n type Result = ();\n\n\n\n fn handle(&mut self, message: super::Disconnect, _context: &mut Context<Self>) -> Self::Result {\n\n let _ = self.sessions.remove(&message.session_id);\n\n }\n\n}\n\n\n\nimpl Handler<super::Connect> for ChatServer {\n\n type Result = usize;\n", "file_path": "main/src/ws/chat_server.rs", "rank": 77, "score": 43973.169524262434 }, { "content": "type Cache = super::static_cache::HashCache;\n\n\n\nlazy_static! {\n\n static ref CACHE: Cache = Cache::default();\n\n static ref STATIC_PATH: String = super::get_envvar(\"SHAAT_STATIC\").unwrap();\n\n}\n\n\n", "file_path": "main/src/statiq.rs", "rank": 78, "score": 37715.96814556549 }, { "content": "const username = document\n", "file_path": "static/login.js", "rank": 84, "score": 24453.109871029756 }, { "content": "const socket = (() => {\n\n const socketAddr = (window.location.protocol == 'https:' && 'wss://' || 'ws://') + window.location.host + '/ws/';\n\n const socket = new WebSocket(socketAddr);\n\n\n\n //socket.onopen = event => { };\n\n \n\n const messages = document\n\n\t .getElementById('messages');\n\n\n\n socket.onmessage = message => {\n\n\tupdate(message.data);\n\n };\n\n \n\n socket.onerror = e => {\n\n\tconsole.log(e);\n\n };\n\n\n\n socket.onclose = e => {\n\n\tconsole.log(e);\n\n };\n\n return socket;\n\n\n\n function update(message) {\n\n\tconst deltaScroll = messages.scrollTopMax - messages.scrollTop;\n\n\tmessages.innerHTML += message;\n\n\tif (deltaScroll < 10)\n\n\t messages.scrollTop = messages.scrollTopMax;\n\n }\n", "file_path": "static/ws.js", "rank": 85, "score": 23800.335115172467 }, { "content": "pub trait MessageGuard: Default {\n\n type Message;\n\n\n\n fn insert_message<M>(&self, message: M) -> Result<Id, String>\n\n where\n\n Self::Message: From<M>;\n\n\n\n fn get_message_by_id(&self, id: Id) -> Result<Self::Message, String>;\n\n fn get_latest(&self, n: Id) -> Vec<Self::Message>;\n\n}\n\n\n\npub type Messages2<T> = btree2::Messages<T>;\n\npub type Messages<T> = btree::Messages<T>;\n", "file_path": "libmessages/src/lib.rs", "rank": 86, "score": 23378.731535494942 }, { "content": "const socket = (() => {\n\n const socketAddr = (window.location.protocol == 'https:' && 'wss://' || 'ws://') + window.location.host + '/ws/';\n\n const socket = new WebSocket(socketAddr);\n\n\n\n //socket.onopen = event => { };\n\n \n\n const messages = document\n\n\t .getElementById('messages');\n\n\n\n socket.onmessage = message => {\n\n\tupdate(message.data);\n\n };\n\n \n\n socket.onerror = e => {\n\n\tconsole.log(e);\n\n };\n\n\n\n socket.onclose = e => {\n\n\tconsole.log(e);\n\n };\n\n return socket;\n\n\n\n function update(message) {\n\n\tconst deltaScroll = messages.scrollTopMax - messages.scrollTop;\n\n\tmessages.innerHTML += message;\n\n\tif (deltaScroll < 10)\n\n\t messages.scrollTop = messages.scrollTopMax;\n\n }\n\n})();\n\n\n\n{\n\n const sendButton = document\n\n\t .getElementById('userinputsubmit');\n\n const messageField = document\n\n\t .getElementById('userinputtext');\n\n \n\n sendButton.onclick = () => {\n\n\tconst text = messageField.value;\n\n\tsocket\n\n\t .send(text);\n\n\tmessageField.value = '';\n\n\treturn false;\n\n };\n\n \n\n messageField.onkeyup = (key) => {\n\n\tif (key.keyCode === 13) // enter\n\n\t sendButton.click();\n\n };\n\n}\n", "file_path": "static/ws.js", "rank": 87, "score": 18402.491687097445 }, { "content": "// Removes message asking for JavaScript.\n\ndocument\n\n .getElementById(\"jsdisabled\")\n\n .parentNode\n\n .removeChild(jsdisabled);\n", "file_path": "static/main.js", "rank": 88, "score": 14172.164728472368 }, { "content": "// Copyright 2018 Cássio Kirch.\n\n\n\nuse super::{io, time};\n\nuse std::fs::File;\n\nuse std::io::{BufReader, Read};\n\n\n\npub struct Node {\n\n pub last_update: time::SystemTime,\n\n pub content: Result<Vec<u8>, String>,\n\n}\n\n\n\nimpl Node {\n\n pub fn must_update(&self, file: &File) -> Result<bool, String> {\n\n let metadata = file.metadata().map_err(|e| e.to_string())?;\n\n\n\n let modified = metadata.modified().map_err(|e| e.to_string())?;\n\n\n\n Ok(modified > self.last_update)\n\n }\n\n\n", "file_path": "libstatic/src/node.rs", "rank": 89, "score": 8.495167267474015 }, { "content": "// Copyright 2018 Cássio Kirch.\n\n\n\nuse std::collections::{BTreeMap, HashMap};\n\nuse std::fs::File;\n\nuse std::path::PathBuf;\n\nuse std::sync::{Arc, RwLock};\n\nuse std::{io, time};\n\n\n\nmod node;\n\n\n\n#[macro_use]\n\nmod macros {\n\n macro_rules! generate_cache {\n\n ($newname:ident, $map:tt) => {\n\n pub struct $newname {\n\n cache: Arc<RwLock<$map<PathBuf, Arc<RwLock<node::Node>>>>>,\n\n }\n\n impl $newname {\n\n pub fn get(&self, path: &PathBuf) -> Result<Vec<u8>, String> {\n\n let (content, node) = {\n", "file_path": "libstatic/src/lib.rs", "rank": 90, "score": 7.26729682232685 }, { "content": "// Copyright 2018 Cássio Kirch.\n\n\n\nuse super::{Id, MessageGuard};\n\nuse std::collections::BTreeMap;\n\nuse std::sync::{Arc, RwLock};\n\n\n", "file_path": "libmessages/src/btree.rs", "rank": 91, "score": 5.136896657955656 }, { "content": "// Copyright 2018 Cássio Kirch.\n\n\n\nuse super::{Id, MessageGuard};\n\nuse std::collections::BTreeMap;\n\nuse std::sync::{Arc, RwLock};\n\n\n", "file_path": "libmessages/src/btree2.rs", "rank": 92, "score": 5.136896657955656 }, { "content": " *last += 1;\n\n\n\n Ok(*last - 1)\n\n }\n\n\n\n fn get_message_by_id(&self, id: Id) -> Result<Self::Message, String> {\n\n let tree = &*self.tree.read().map_err(|e| e.to_string())?;\n\n let message = tree.get(&id);\n\n if message.is_some() {\n\n Ok((*message.unwrap()).clone())\n\n } else {\n\n Err(\"Message not found\".into())\n\n }\n\n }\n\n\n\n fn get_latest(&self, n: Id) -> Vec<Self::Message> {\n\n let (tree, last) = (self.tree.read().unwrap(), self.last_id.read().unwrap());\n\n let n = if n <= 0 { 32 } else { n };\n\n\n\n let n = if n > *last { *last } else { n };\n", "file_path": "libmessages/src/btree.rs", "rank": 93, "score": 4.584005085498097 }, { "content": " Messages::new(1024)\n\n }\n\n}\n\n\n\nimpl<T: Clone> MessageGuard for Messages<T> {\n\n type Message = T;\n\n\n\n fn insert_message<M>(&self, message: M) -> Result<Id, String>\n\n where\n\n Self::Message: From<M>,\n\n {\n\n let last = *self.last_inner_tree_id.read().unwrap();\n\n if last % *self.divisor == 0 {\n\n let mut out_tree = self.tree.write().unwrap();\n\n out_tree.insert(last, Arc::default());\n\n }\n\n\n\n let last_group = (last / *self.divisor) * *self.divisor;\n\n\n\n let outer_tree = self.tree.read().unwrap();\n", "file_path": "libmessages/src/btree2.rs", "rank": 94, "score": 4.477861215892761 }, { "content": " let mut inner_tree = outer_tree.get(&last_group).unwrap().write().unwrap();\n\n inner_tree.insert(last, message.into());\n\n let mut last = self.last_inner_tree_id.write().unwrap();\n\n *last += 1;\n\n\n\n Ok(*last - 1)\n\n }\n\n\n\n fn get_message_by_id(&self, id: Id) -> Result<Self::Message, String> {\n\n let group_id = (id / *self.divisor) * *self.divisor;\n\n let outer_tree = &*self.tree.read().map_err(|e| e.to_string())?;\n\n let inner_tree = outer_tree.get(&group_id);\n\n if inner_tree.is_none() {\n\n Err(\"Inner tree not found\".into())\n\n } else {\n\n let inner_tree = &*inner_tree.unwrap().read().map_err(|e| e.to_string())?;\n\n let message = inner_tree.get(&id);\n\n if message.is_some() {\n\n Ok(message.unwrap().clone())\n\n } else {\n", "file_path": "libmessages/src/btree2.rs", "rank": 95, "score": 3.7224270751907396 }, { "content": " let cache = self.cache.read().unwrap();\n\n let node = cache.get(path);\n\n match node {\n\n Some(node) => {\n\n let file = match File::open(path) {\n\n Ok(file) => file,\n\n Err(e) => {\n\n return Err(e.to_string());\n\n }\n\n };\n\n\n\n let must_update = {\n\n let node = node.read().unwrap();\n\n let must_update = node.must_update(&file);\n\n must_update.is_err() || must_update.unwrap()\n\n };\n\n return if must_update {\n\n let mut node = node.write().unwrap();\n\n node.update(&file);\n\n node.content.clone()\n", "file_path": "libstatic/src/lib.rs", "rank": 96, "score": 3.335642923392318 }, { "content": "// Copyright 2018 Cássio Kirch.\n\n\n\npub type Id = i64;\n\n\n\nmod btree;\n\nmod btree2;\n\n\n", "file_path": "libmessages/src/lib.rs", "rank": 97, "score": 3.327427763460488 }, { "content": "}\n\n\n\nimpl Default for Node {\n\n fn default() -> Self {\n\n Node {\n\n last_update: time::UNIX_EPOCH,\n\n content: Err(\"Still unset\".into()),\n\n }\n\n }\n\n}\n\n\n", "file_path": "libstatic/src/node.rs", "rank": 98, "score": 2.482598092745035 }, { "content": " }\n\n };\n\n }\n\n\n\n if n == 0 {\n\n if group_id > 0 {\n\n scan!(group_id - *self.divisor, group_id);\n\n }\n\n scan!(group_id, latest_id);\n\n } else if latest_id >= n {\n\n let first_message_id = latest_id - n;\n\n let first_group_id = (first_message_id / *self.divisor) * *self.divisor;\n\n scan!(first_message_id, first_group_id + *self.divisor);\n\n\n\n for group_count in (first_group_id + 1) / *self.divisor..group_id / *self.divisor {\n\n scan!(\n\n group_count * *self.divisor,\n\n group_count * *self.divisor + *self.divisor\n\n );\n\n }\n\n }\n\n v\n\n }\n\n}\n", "file_path": "libmessages/src/btree2.rs", "rank": 99, "score": 2.3531052204193044 } ]
Rust
src/test/instruction_tests/instr_vcvtps2uqq.rs
ftilde/rust-x86asm
f6584b8cfe8e75d978bf7b83a67c69444fd3f161
use instruction_def::*; use test::run_test; use Operand::*; use Reg::*; use RegScale::*; use RegType::*; use {BroadcastMode, Instruction, MaskReg, MergeMode, Mnemonic, OperandSize, Reg, RoundingMode}; #[test] fn vcvtps2uqq_1() { run_test( &Instruction { mnemonic: Mnemonic::VCVTPS2UQQ, operand1: Some(Direct(XMM2)), operand2: Some(Direct(XMM4)), operand3: None, operand4: None, lock: false, rounding_mode: None, merge_mode: Some(MergeMode::Zero), sae: false, mask: Some(MaskReg::K5), broadcast: None, }, &[98, 241, 125, 141, 121, 212], OperandSize::Dword, ) } #[test] fn vcvtps2uqq_2() { run_test( &Instruction { mnemonic: Mnemonic::VCVTPS2UQQ, operand1: Some(Direct(XMM6)), operand2: Some(IndirectScaledDisplaced( ECX, Four, 782247532, Some(OperandSize::Qword), None, )), operand3: None, operand4: None, lock: false, rounding_mode: None, merge_mode: Some(MergeMode::Zero), sae: false, mask: Some(MaskReg::K7), broadcast: None, }, &[98, 241, 125, 143, 121, 52, 141, 108, 38, 160, 46], OperandSize::Dword, ) } #[test] fn vcvtps2uqq_3() { run_test( &Instruction { mnemonic: Mnemonic::VCVTPS2UQQ, operand1: Some(Direct(XMM8)), operand2: Some(Direct(XMM27)), operand3: None, operand4: None, lock: false, rounding_mode: None, merge_mode: Some(MergeMode::Zero), sae: false, mask: Some(MaskReg::K6), broadcast: None, }, &[98, 17, 125, 142, 121, 195], OperandSize::Qword, ) } #[test] fn vcvtps2uqq_4() { run_test( &Instruction { mnemonic: Mnemonic::VCVTPS2UQQ, operand1: Some(Direct(XMM7)), operand2: Some(IndirectScaledIndexed( RDI, RSI, Two, Some(OperandSize::Qword), None, )), operand3: None, operand4: None, lock: false, rounding_mode: None, merge_mode: Some(MergeMode::Zero), sae: false, mask: Some(MaskReg::K1), broadcast: None, }, &[98, 241, 125, 137, 121, 60, 119], OperandSize::Qword, ) } #[test] fn vcvtps2uqq_5() { run_test( &Instruction { mnemonic: Mnemonic::VCVTPS2UQQ, operand1: Some(Direct(YMM4)), operand2: Some(Direct(XMM6)), operand3: None, operand4: None, lock: false, rounding_mode: None, merge_mode: Some(MergeMode::Zero), sae: false, mask: Some(MaskReg::K3), broadcast: None, }, &[98, 241, 125, 171, 121, 230], OperandSize::Dword, ) } #[test] fn vcvtps2uqq_6() { run_test( &Instruction { mnemonic: Mnemonic::VCVTPS2UQQ, operand1: Some(Direct(YMM0)), operand2: Some(IndirectScaledDisplaced( ESI, Four, 1742127559, Some(OperandSize::Xmmword), None, )), operand3: None, operand4: None, lock: false, rounding_mode: None, merge_mode: Some(MergeMode::Zero), sae: false, mask: Some(MaskReg::K2), broadcast: None, }, &[98, 241, 125, 170, 121, 4, 181, 199, 193, 214, 103], OperandSize::Dword, ) } #[test] fn vcvtps2uqq_7() { run_test( &Instruction { mnemonic: Mnemonic::VCVTPS2UQQ, operand1: Some(Direct(YMM12)), operand2: Some(Direct(XMM24)), operand3: None, operand4: None, lock: false, rounding_mode: None, merge_mode: Some(MergeMode::Zero), sae: false, mask: Some(MaskReg::K3), broadcast: None, }, &[98, 17, 125, 171, 121, 224], OperandSize::Qword, ) } #[test] fn vcvtps2uqq_8() { run_test( &Instruction { mnemonic: Mnemonic::VCVTPS2UQQ, operand1: Some(Direct(YMM21)), operand2: Some(IndirectScaledDisplaced( RAX, Eight, 796565832, Some(OperandSize::Xmmword), None, )), operand3: None, operand4: None, lock: false, rounding_mode: None, merge_mode: Some(MergeMode::Zero), sae: false, mask: Some(MaskReg::K5), broadcast: None, }, &[98, 225, 125, 173, 121, 44, 197, 72, 161, 122, 47], OperandSize::Qword, ) } #[test] fn vcvtps2uqq_9() { run_test( &Instruction { mnemonic: Mnemonic::VCVTPS2UQQ, operand1: Some(Direct(ZMM0)), operand2: Some(Direct(YMM5)), operand3: None, operand4: None, lock: false, rounding_mode: Some(RoundingMode::Zero), merge_mode: Some(MergeMode::Zero), sae: false, mask: Some(MaskReg::K3), broadcast: None, }, &[98, 241, 125, 251, 121, 197], OperandSize::Dword, ) } #[test] fn vcvtps2uqq_10() { run_test( &Instruction { mnemonic: Mnemonic::VCVTPS2UQQ, operand1: Some(Direct(ZMM5)), operand2: Some(IndirectDisplaced( EAX, 1019708652, Some(OperandSize::Ymmword), None, )), operand3: None, operand4: None, lock: false, rounding_mode: None, merge_mode: Some(MergeMode::Zero), sae: false, mask: Some(MaskReg::K2), broadcast: None, }, &[98, 241, 125, 202, 121, 168, 236, 132, 199, 60], OperandSize::Dword, ) } #[test] fn vcvtps2uqq_11() { run_test( &Instruction { mnemonic: Mnemonic::VCVTPS2UQQ, operand1: Some(Direct(ZMM27)), operand2: Some(Direct(YMM21)), operand3: None, operand4: None, lock: false, rounding_mode: Some(RoundingMode::Nearest), merge_mode: Some(MergeMode::Zero), sae: false, mask: Some(MaskReg::K6), broadcast: None, }, &[98, 33, 125, 158, 121, 221], OperandSize::Qword, ) } #[test] fn vcvtps2uqq_12() { run_test( &Instruction { mnemonic: Mnemonic::VCVTPS2UQQ, operand1: Some(Direct(ZMM25)), operand2: Some(IndirectDisplaced( RDI, 1515537008, Some(OperandSize::Ymmword), None, )), operand3: None, operand4: None, lock: false, rounding_mode: None, merge_mode: Some(MergeMode::Zero), sae: false, mask: Some(MaskReg::K3), broadcast: None, }, &[98, 97, 125, 203, 121, 143, 112, 66, 85, 90], OperandSize::Qword, ) }
use instruction_def::*; use test::run_test; use Operand::*; use Reg::*; use RegScale::*; use RegType::*; use {BroadcastMode, Instruction, MaskReg, MergeMode, Mnemonic, OperandSize, Reg, RoundingMode}; #[test] fn vcvtps2uqq_1() { run_test( &Instruction { mnemonic: Mnemonic::VCVTPS2UQQ, operand1: Some(Direct(XMM2)), operand2: Some(Direct(XMM4)), operand3: None, operand4: None, lock: false, rounding_mode: None, merge_mode: Some(MergeMode::Zero), sae: false, mask: Some(MaskReg::K5), broadcast: None, }, &[98, 241, 125, 141, 121, 212], OperandSize::Dword, ) } #[test] fn vcvtps2uqq_2() { run_test( &Instruction { mnemonic: Mnemonic::VCVTPS2UQQ, operand1: Some(Direct(XMM6)), operand2: Some(IndirectScaledDisplaced( ECX, Four, 782247532, Some(OperandSize::Qword), None, )), operand3: None, operand4: Non
nic::VCVTPS2UQQ, operand1: Some(Direct(ZMM25)), operand2: Some(IndirectDisplaced( RDI, 1515537008, Some(OperandSize::Ymmword), None, )), operand3: None, operand4: None, lock: false, rounding_mode: None, merge_mode: Some(MergeMode::Zero), sae: false, mask: Some(MaskReg::K3), broadcast: None, }, &[98, 97, 125, 203, 121, 143, 112, 66, 85, 90], OperandSize::Qword, ) }
e, lock: false, rounding_mode: None, merge_mode: Some(MergeMode::Zero), sae: false, mask: Some(MaskReg::K7), broadcast: None, }, &[98, 241, 125, 143, 121, 52, 141, 108, 38, 160, 46], OperandSize::Dword, ) } #[test] fn vcvtps2uqq_3() { run_test( &Instruction { mnemonic: Mnemonic::VCVTPS2UQQ, operand1: Some(Direct(XMM8)), operand2: Some(Direct(XMM27)), operand3: None, operand4: None, lock: false, rounding_mode: None, merge_mode: Some(MergeMode::Zero), sae: false, mask: Some(MaskReg::K6), broadcast: None, }, &[98, 17, 125, 142, 121, 195], OperandSize::Qword, ) } #[test] fn vcvtps2uqq_4() { run_test( &Instruction { mnemonic: Mnemonic::VCVTPS2UQQ, operand1: Some(Direct(XMM7)), operand2: Some(IndirectScaledIndexed( RDI, RSI, Two, Some(OperandSize::Qword), None, )), operand3: None, operand4: None, lock: false, rounding_mode: None, merge_mode: Some(MergeMode::Zero), sae: false, mask: Some(MaskReg::K1), broadcast: None, }, &[98, 241, 125, 137, 121, 60, 119], OperandSize::Qword, ) } #[test] fn vcvtps2uqq_5() { run_test( &Instruction { mnemonic: Mnemonic::VCVTPS2UQQ, operand1: Some(Direct(YMM4)), operand2: Some(Direct(XMM6)), operand3: None, operand4: None, lock: false, rounding_mode: None, merge_mode: Some(MergeMode::Zero), sae: false, mask: Some(MaskReg::K3), broadcast: None, }, &[98, 241, 125, 171, 121, 230], OperandSize::Dword, ) } #[test] fn vcvtps2uqq_6() { run_test( &Instruction { mnemonic: Mnemonic::VCVTPS2UQQ, operand1: Some(Direct(YMM0)), operand2: Some(IndirectScaledDisplaced( ESI, Four, 1742127559, Some(OperandSize::Xmmword), None, )), operand3: None, operand4: None, lock: false, rounding_mode: None, merge_mode: Some(MergeMode::Zero), sae: false, mask: Some(MaskReg::K2), broadcast: None, }, &[98, 241, 125, 170, 121, 4, 181, 199, 193, 214, 103], OperandSize::Dword, ) } #[test] fn vcvtps2uqq_7() { run_test( &Instruction { mnemonic: Mnemonic::VCVTPS2UQQ, operand1: Some(Direct(YMM12)), operand2: Some(Direct(XMM24)), operand3: None, operand4: None, lock: false, rounding_mode: None, merge_mode: Some(MergeMode::Zero), sae: false, mask: Some(MaskReg::K3), broadcast: None, }, &[98, 17, 125, 171, 121, 224], OperandSize::Qword, ) } #[test] fn vcvtps2uqq_8() { run_test( &Instruction { mnemonic: Mnemonic::VCVTPS2UQQ, operand1: Some(Direct(YMM21)), operand2: Some(IndirectScaledDisplaced( RAX, Eight, 796565832, Some(OperandSize::Xmmword), None, )), operand3: None, operand4: None, lock: false, rounding_mode: None, merge_mode: Some(MergeMode::Zero), sae: false, mask: Some(MaskReg::K5), broadcast: None, }, &[98, 225, 125, 173, 121, 44, 197, 72, 161, 122, 47], OperandSize::Qword, ) } #[test] fn vcvtps2uqq_9() { run_test( &Instruction { mnemonic: Mnemonic::VCVTPS2UQQ, operand1: Some(Direct(ZMM0)), operand2: Some(Direct(YMM5)), operand3: None, operand4: None, lock: false, rounding_mode: Some(RoundingMode::Zero), merge_mode: Some(MergeMode::Zero), sae: false, mask: Some(MaskReg::K3), broadcast: None, }, &[98, 241, 125, 251, 121, 197], OperandSize::Dword, ) } #[test] fn vcvtps2uqq_10() { run_test( &Instruction { mnemonic: Mnemonic::VCVTPS2UQQ, operand1: Some(Direct(ZMM5)), operand2: Some(IndirectDisplaced( EAX, 1019708652, Some(OperandSize::Ymmword), None, )), operand3: None, operand4: None, lock: false, rounding_mode: None, merge_mode: Some(MergeMode::Zero), sae: false, mask: Some(MaskReg::K2), broadcast: None, }, &[98, 241, 125, 202, 121, 168, 236, 132, 199, 60], OperandSize::Dword, ) } #[test] fn vcvtps2uqq_11() { run_test( &Instruction { mnemonic: Mnemonic::VCVTPS2UQQ, operand1: Some(Direct(ZMM27)), operand2: Some(Direct(YMM21)), operand3: None, operand4: None, lock: false, rounding_mode: Some(RoundingMode::Nearest), merge_mode: Some(MergeMode::Zero), sae: false, mask: Some(MaskReg::K6), broadcast: None, }, &[98, 33, 125, 158, 121, 221], OperandSize::Qword, ) } #[test] fn vcvtps2uqq_12() { run_test( &Instruction { mnemonic: Mnemo
random
[ { "content": "fn encode64_helper2(mnemonic: Mnemonic, operand1: Operand, operand2: Operand, expected: &Vec<u8>) {\n\n let instr = Instruction {\n\n mnemonic: mnemonic,\n\n operand1: Some(operand1),\n\n operand2: Some(operand2),\n\n operand3: None,\n\n operand4: None,\n\n ..Default::default()\n\n };\n\n encode64_helper(&instr, expected);\n\n}\n\n\n", "file_path": "src/test/mod.rs", "rank": 0, "score": 606330.1135968915 }, { "content": "fn encode32_helper2(mnemonic: Mnemonic, operand1: Operand, operand2: Operand, expected: &Vec<u8>) {\n\n let instr = Instruction {\n\n mnemonic: mnemonic,\n\n operand1: Some(operand1),\n\n operand2: Some(operand2),\n\n operand3: None,\n\n operand4: None,\n\n ..Default::default()\n\n };\n\n encode32_helper(&instr, expected);\n\n}\n\n\n", "file_path": "src/test/mod.rs", "rank": 1, "score": 606330.1135968915 }, { "content": "fn encode16_helper2(mnemonic: Mnemonic, operand1: Operand, operand2: Operand, expected: &Vec<u8>) {\n\n let instr = Instruction {\n\n mnemonic: mnemonic,\n\n operand1: Some(operand1),\n\n operand2: Some(operand2),\n\n operand3: None,\n\n operand4: None,\n\n ..Default::default()\n\n };\n\n encode16_helper(&instr, expected);\n\n}\n\n\n", "file_path": "src/test/mod.rs", "rank": 2, "score": 606330.1135968915 }, { "content": "#[test]\n\nfn operand_type_mask_reg() {\n\n decode_helper(\n\n &vec![0x62, 0xF1, 0xED, 0x28, 0xC2, 0xDB, 0x05],\n\n Mode::Long,\n\n &Instruction::new4(\n\n Mnemonic::VCMPPD,\n\n Operand::Direct(Reg::K3),\n\n Operand::Direct(Reg::YMM2),\n\n Operand::Direct(Reg::YMM3),\n\n Operand::Literal8(5),\n\n ),\n\n ); // VCMPPD K3, YMM2, YMM3, 5\n\n}\n\n\n", "file_path": "src/test/decode.rs", "rank": 3, "score": 446160.93751226546 }, { "content": "fn random_reg_of_size(size: OperandSize) -> Reg {\n\n match size {\n\n OperandSize::Byte => random_reg_8(),\n\n OperandSize::Word => random_reg_16(),\n\n OperandSize::Dword => random_reg_32(),\n\n OperandSize::Qword => random_reg_64(),\n\n _ => panic!(\"Invalid general register size: {:?}.\", size)\n\n }\n\n}\n\n\n", "file_path": "gen_defs/src/gen_tests.rs", "rank": 4, "score": 405074.69505944534 }, { "content": "fn random_reg_of_size_no_stack(size: OperandSize) -> Reg {\n\n match size {\n\n OperandSize::Byte => random_reg_8(),\n\n OperandSize::Word => random_reg_16_no_stack(),\n\n OperandSize::Dword => random_reg_32_no_stack(),\n\n OperandSize::Qword => random_reg_64_no_stack(),\n\n _ => panic!(\"Invalid general register size: {:?}.\", size)\n\n }\n\n}\n\n\n", "file_path": "gen_defs/src/gen_tests.rs", "rank": 5, "score": 400092.43049772026 }, { "content": "#[allow(dead_code)]\n\nfn encode32_helper1(mnemonic: Mnemonic, op1: Operand, expected: &Vec<u8>) {\n\n let instr = Instruction {\n\n mnemonic: mnemonic,\n\n operand1: Some(op1),\n\n operand2: None,\n\n operand3: None,\n\n operand4: None,\n\n ..Default::default()\n\n };\n\n encode32_helper(&instr, expected);\n\n}\n", "file_path": "src/test/mod.rs", "rank": 6, "score": 383637.69327454804 }, { "content": "#[test]\n\nfn operand_type_mask_or_mem_64() {\n\n decode_helper(\n\n &vec![0xC4, 0xE1, 0xF8, 0x90, 0xCA],\n\n Mode::Long,\n\n &Instruction::new2(\n\n Mnemonic::KMOVQ,\n\n Operand::Direct(Reg::K1),\n\n Operand::Direct(Reg::K2),\n\n ),\n\n ); // KMOVQ K1, K2\n\n decode_helper(\n\n &vec![0xC4, 0xE1, 0xF8, 0x90, 0x08],\n\n Mode::Long,\n\n &Instruction::new2(\n\n Mnemonic::KMOVQ,\n\n Operand::Direct(Reg::K1),\n\n Operand::Indirect(Reg::RAX, Some(OperandSize::Qword), None),\n\n ),\n\n ); // KMOVQ K1, QWORD PTR [RAX]\n\n}\n\n\n", "file_path": "src/test/decode.rs", "rank": 7, "score": 379029.60926208395 }, { "content": "#[test]\n\nfn operand_type_mask_or_mem_32() {\n\n decode_helper(\n\n &vec![0xC4, 0xE1, 0xF9, 0x90, 0xCA],\n\n Mode::Long,\n\n &Instruction::new2(\n\n Mnemonic::KMOVD,\n\n Operand::Direct(Reg::K1),\n\n Operand::Direct(Reg::K2),\n\n ),\n\n ); // KMOVD K1, K2\n\n decode_helper(\n\n &vec![0xC4, 0xE1, 0xF9, 0x90, 0x08],\n\n Mode::Long,\n\n &Instruction::new2(\n\n Mnemonic::KMOVD,\n\n Operand::Direct(Reg::K1),\n\n Operand::Indirect(Reg::RAX, Some(OperandSize::Dword), None),\n\n ),\n\n ); // KMOVD K1, DWORD PTR [RAX]\n\n}\n\n\n", "file_path": "src/test/decode.rs", "rank": 8, "score": 379029.609262084 }, { "content": "#[test]\n\nfn operand_type_mask_or_mem_16() {\n\n decode_helper(\n\n &vec![0xC5, 0xF8, 0x90, 0xCA],\n\n Mode::Long,\n\n &Instruction::new2(\n\n Mnemonic::KMOVW,\n\n Operand::Direct(Reg::K1),\n\n Operand::Direct(Reg::K2),\n\n ),\n\n ); // KMOVW K1, K2\n\n decode_helper(\n\n &vec![0xC5, 0xF8, 0x90, 0x08],\n\n Mode::Long,\n\n &Instruction::new2(\n\n Mnemonic::KMOVW,\n\n Operand::Direct(Reg::K1),\n\n Operand::Indirect(Reg::RAX, Some(OperandSize::Word), None),\n\n ),\n\n ); // KMOVW K1, BYTE PTR [RAX]\n\n}\n\n\n", "file_path": "src/test/decode.rs", "rank": 9, "score": 379029.609262084 }, { "content": "#[test]\n\nfn operand_type_mask_or_mem_8() {\n\n decode_helper(\n\n &vec![0xC5, 0xF9, 0x90, 0xCA],\n\n Mode::Long,\n\n &Instruction::new2(\n\n Mnemonic::KMOVB,\n\n Operand::Direct(Reg::K1),\n\n Operand::Direct(Reg::K2),\n\n ),\n\n ); // KMOVB K1, K2\n\n decode_helper(\n\n &vec![0xC5, 0xF9, 0x90, 0x08],\n\n Mode::Long,\n\n &Instruction::new2(\n\n Mnemonic::KMOVB,\n\n Operand::Direct(Reg::K1),\n\n Operand::Indirect(Reg::RAX, Some(OperandSize::Byte), None),\n\n ),\n\n ); // KMOVB K1, BYTE PTR [RAX]\n\n}\n\n\n", "file_path": "src/test/decode.rs", "rank": 10, "score": 379029.60926208395 }, { "content": "fn random_mask() -> MaskReg {\n\n random_of(&[MaskReg::K1, MaskReg::K2, MaskReg::K3, MaskReg::K4, MaskReg::K5, MaskReg::K6,\n\n MaskReg::K7])\n\n}\n\n\n\nnamed!(parse_as_output<Vec<u8>>, do_parse!(\n\n take_until_and_consume!(\"0:\\t\") >>\n\n bytes: flat_map!(\n\n take_until!(\"\\t\"),\n\n ws!(many1!(parse_u8_hex_str))\n\n ) >>\n\n (bytes)\n\n));\n\n\n\nnamed!(parse_u8_hex_str<u8>, map!(\n\n alphanumeric,\n\n |val| u8::from_str_radix(str::from_utf8(val).unwrap(), 16).unwrap()\n\n));\n\n\n\nimpl Display for Reg {\n", "file_path": "gen_defs/src/gen_tests.rs", "rank": 11, "score": 372693.5476501826 }, { "content": "fn random_mask_reg() -> Reg\n\n { random_of(&[Reg::K1, Reg::K2, Reg::K3, Reg::K4, Reg::K5, Reg::K6, Reg::K7]) }\n\n\n", "file_path": "gen_defs/src/gen_tests.rs", "rank": 12, "score": 372689.33923427993 }, { "content": "fn random_imm(size: OperandSize) -> Operand {\n\n let mut gen = rand::thread_rng();\n\n match size {\n\n OperandSize::Byte => Operand::Literal8(gen.gen_range::<u8>(0, 128)),\n\n OperandSize::Word => Operand::Literal16(\n\n gen.gen_range::<u16>(u8::max_value() as u16 + 1, i16::max_value() as u16)),\n\n OperandSize::Dword => Operand::Literal32(\n\n gen.gen_range::<u32>(u16::max_value() as u32 + 1, i32::max_value() as u32)),\n\n OperandSize::Qword => Operand::Literal64(\n\n gen.gen_range::<u64>(u32::max_value() as u64 + 1, i64::max_value() as u64)),\n\n OperandSize::Far16 => Operand::MemoryAndSegment16(rand::random(), rand::random()),\n\n OperandSize::Far32 => Operand::MemoryAndSegment32(rand::random(), rand::random()),\n\n _ => panic!(\"Invalid immediate value size: {:?}.\", size)\n\n }\n\n}\n\n\n", "file_path": "gen_defs/src/gen_tests.rs", "rank": 13, "score": 364239.84979508806 }, { "content": "fn random_reg(reg_type: RegType, size: OperandSize, addr_size: OperandSize, \n\n def: &InstructionDefinition) -> Reg {\n\n match reg_type {\n\n RegType::General => {\n\n match size {\n\n OperandSize::Byte => random_reg_8(),\n\n OperandSize::Word => random_reg_16(),\n\n OperandSize::Dword => random_reg_32(),\n\n OperandSize::Qword => random_reg_64(),\n\n OperandSize::Unsized => random_reg_of_size(addr_size),\n\n _ => panic!(\"Invalid general register size: {:?}.\", size)\n\n }\n\n },\n\n RegType::Avx => {\n\n let allow_all = if let Some(CompositePrefix::Evex {..}) = def.composite_prefix {\n\n addr_size == OperandSize::Qword } else { false };\n\n match size {\n\n OperandSize::Xmmword => random_xmm_reg(allow_all),\n\n OperandSize::Ymmword => random_ymm_reg(allow_all),\n\n OperandSize::Zmmword => random_zmm_reg(allow_all),\n", "file_path": "gen_defs/src/gen_tests.rs", "rank": 14, "score": 362089.76032153267 }, { "content": "fn random_fixed(fixed_op: FixedOperand) -> Operand {\n\n match fixed_op {\n\n FixedOperand::Reg(reg) => Operand::Direct(reg),\n\n FixedOperand::Constant(c) => Operand::Literal8(c as u8)\n\n }\n\n}\n\n\n", "file_path": "gen_defs/src/gen_tests.rs", "rank": 15, "score": 360428.80400271865 }, { "content": "fn run_test(instr: &Instruction, expected: &[u8], addr_size: OperandSize) {\n\n let mut buffer = Cursor::new(Vec::new());\n\n instr\n\n .encode(&mut buffer, Mode::from_size(addr_size).unwrap())\n\n .expect(\"Encoding failed\");\n\n if &buffer.get_ref()[..] != expected {\n\n println!(\"Test failed.\");\n\n print!(\"Output: [\");\n\n output_hex_array(buffer.get_ref());\n\n println!(\"]\");\n\n print!(\"Expected: [\");\n\n output_hex_array(expected);\n\n println!(\"]\");\n\n panic!(\n\n \"Failure. Mode: {:?}.\\nInstruction: {:?}.\\n\",\n\n addr_size, instr\n\n );\n\n }\n\n}\n\n\n", "file_path": "src/test/mod.rs", "rank": 16, "score": 358425.5942229312 }, { "content": "fn random_mib(size: OperandSize, addr_size: OperandSize) -> Operand {\n\n Operand::IndirectScaledIndexed(\n\n random_reg_of_size_no_stack(addr_size),\n\n random_reg_of_size_no_stack(addr_size),\n\n RegScale::One,\n\n Some(size), None)\n\n}\n\n\n", "file_path": "gen_defs/src/gen_tests.rs", "rank": 17, "score": 353851.0840731592 }, { "content": "fn random_mem(size: OperandSize, addr_size: OperandSize) -> Operand {\n\n if addr_size != OperandSize::Word {\n\n match rand::random::<u32>() % 5 { // Select addressing mode\n\n 0 => { // Indirect - [EAX]\n\n Operand::Indirect(\n\n random_reg_of_size_no_stack(addr_size),\n\n Some(size), None)\n\n },\n\n 1 => { // Indirect Displaced - [EAX+5]\n\n Operand::IndirectDisplaced(\n\n random_reg_of_size_no_stack(addr_size),\n\n (rand::random::<u32>() as u64) & 0x7FFFFFFF,\n\n Some(size), None)\n\n },\n\n 2 => { // Indirect Scaled Indexed - [EAX+EBX*2]\n\n Operand::IndirectScaledIndexed(\n\n random_reg_of_size_no_stack(addr_size),\n\n random_reg_of_size_no_stack(addr_size),\n\n random_reg_scale(),\n\n Some(size), None)\n", "file_path": "gen_defs/src/gen_tests.rs", "rank": 18, "score": 353851.0840731592 }, { "content": "fn write_operand<W: Write>(op: &Operand, instr_def: &InstructionDefinition, f: &mut W)\n\n -> io::Result<()> { \n\n match *op {\n\n Operand::Direct(reg) => write!(f, \"{}\", reg),\n\n Operand::Indirect(reg, size, seg) => \n\n write_indirect(f, Some(reg), None, None, None, size, seg, instr_def),\n\n Operand::IndirectDisplaced(reg, dsp, size, seg) =>\n\n write_indirect(f, Some(reg), None, None, Some(dsp), size, seg, instr_def),\n\n Operand::IndirectScaledIndexed(base, index, scale, size, seg) => \n\n write_indirect(f, Some(base), Some(index), Some(scale), None, size, seg, instr_def),\n\n Operand::IndirectScaledIndexedDisplaced(base, index, scale, dsp, size, seg) =>\n\n write_indirect(f, Some(base), Some(index), Some(scale), Some(dsp), size, seg,\n\n instr_def),\n\n Operand::IndirectScaledDisplaced(reg, scale, dsp, size, seg) =>\n\n write_indirect(f, Some(reg), None, Some(scale), Some(dsp), size, seg, instr_def),\n\n Operand::Memory(addr, size, seg) |\n\n Operand::Offset(addr, size, seg) => size_seg_helper(f, size, seg, |fmt| write!(fmt, \"[{}]\", addr)), // TODO Is this correct?\n\n Operand::Literal8(v) => write!(f, \"0x{:X}\", v),\n\n Operand::Literal16(v) => write!(f, \"0x{:X}\", v),\n\n Operand::Literal32(v) => write!(f, \"0x{:X}\", v),\n\n Operand::Literal64(v) => write!(f, \"0x{:X}\", v),\n\n Operand::MemoryAndSegment16(seg, addr) => write!(f, \"0x{:X}:0x{:X}\", seg, addr),\n\n Operand::MemoryAndSegment32(seg, addr) => write!(f, \"0x{:X}:0x{:X}\", seg, addr),\n\n }\n\n}\n\n\n", "file_path": "gen_defs/src/gen_tests.rs", "rank": 19, "score": 348761.8677862119 }, { "content": "fn random_ymm_reg(use_all: bool) -> Reg { \n\n if use_all { random_of(&[\n\n Reg::YMM0, Reg::YMM1, Reg::YMM2, Reg::YMM3, Reg::YMM4, Reg::YMM5, Reg::YMM6, Reg::YMM7,\n\n Reg::YMM8, Reg::YMM9, Reg::YMM10, Reg::YMM11, Reg::YMM12, Reg::YMM13, Reg::YMM14, Reg::YMM15,\n\n Reg::YMM16, Reg::YMM17, Reg::YMM18, Reg::YMM19, Reg::YMM20, Reg::YMM21, Reg::YMM22, Reg::YMM23,\n\n Reg::YMM24, Reg::YMM25, Reg::YMM26, Reg::YMM27, Reg::YMM28, Reg::YMM29, Reg::YMM30, Reg::YMM31\n\n ]) } else { random_of(&[\n\n Reg::YMM0, Reg::YMM1, Reg::YMM2, Reg::YMM3, Reg::YMM4, Reg::YMM5, Reg::YMM6, Reg::YMM7,\n\n ]) }\n\n}\n\n\n", "file_path": "gen_defs/src/gen_tests.rs", "rank": 20, "score": 348038.44714981 }, { "content": "fn random_xmm_reg(use_all: bool) -> Reg { \n\n if use_all { random_of(&[\n\n Reg::XMM0, Reg::XMM1, Reg::XMM2, Reg::XMM3, Reg::XMM4, Reg::XMM5, Reg::XMM6, Reg::XMM7,\n\n Reg::XMM8, Reg::XMM9, Reg::XMM10, Reg::XMM11, Reg::XMM12, Reg::XMM13, Reg::XMM14, Reg::XMM15,\n\n Reg::XMM16, Reg::XMM17, Reg::XMM18, Reg::XMM19, Reg::XMM20, Reg::XMM21, Reg::XMM22, Reg::XMM23,\n\n Reg::XMM24, Reg::XMM25, Reg::XMM26, Reg::XMM27, Reg::XMM28, Reg::XMM29, Reg::XMM30, Reg::XMM31\n\n ]) } else { random_of(&[\n\n Reg::XMM0, Reg::XMM1, Reg::XMM2, Reg::XMM3, Reg::XMM4, Reg::XMM5, Reg::XMM6, Reg::XMM7,\n\n ]) }\n\n}\n\n\n", "file_path": "gen_defs/src/gen_tests.rs", "rank": 21, "score": 348038.44714981 }, { "content": "fn random_zmm_reg(use_all: bool) -> Reg { \n\n if use_all { random_of(&[\n\n Reg::ZMM0, Reg::ZMM1, Reg::ZMM2, Reg::ZMM3, Reg::ZMM4, Reg::ZMM5, Reg::ZMM6, Reg::ZMM7,\n\n Reg::ZMM8, Reg::ZMM9, Reg::ZMM10, Reg::ZMM11, Reg::ZMM12, Reg::ZMM13, Reg::ZMM14, Reg::ZMM15,\n\n Reg::ZMM16, Reg::ZMM17, Reg::ZMM18, Reg::ZMM19, Reg::ZMM20, Reg::ZMM21, Reg::ZMM22, Reg::ZMM23,\n\n Reg::ZMM24, Reg::ZMM25, Reg::ZMM26, Reg::ZMM27, Reg::ZMM28, Reg::ZMM29, Reg::ZMM30, Reg::ZMM31\n\n ]) } else { random_of(&[\n\n Reg::ZMM0, Reg::ZMM1, Reg::ZMM2, Reg::ZMM3, Reg::ZMM4, Reg::ZMM5, Reg::ZMM6, Reg::ZMM7,\n\n ]) }\n\n}\n\n\n", "file_path": "gen_defs/src/gen_tests.rs", "rank": 22, "score": 348038.44714981 }, { "content": "fn make_operand_combinations(instr: &InstructionDefinition) -> Vec<Vec<OperandDefinition>> {\n\n let set_parts = instr.operands.iter().by_ref().filter_map(\n\n |maybe_op| maybe_op.as_ref().and_then(\n\n |op| if let OperandType::Set(ref items) = op.op_type {\n\n if instr.mnemonic.find(\"CVT\").is_none() {\n\n Some(items.clone())\n\n } else {\n\n Some(items.iter().filter(|i| if let OperandType::Bcst(_) = **i { false }\n\n else { true }).cloned().collect())\n\n }\n\n } else { None }\n\n )\n\n ).next();\n\n if let Some(parts) = set_parts { \n\n parts.iter().map(|part| instr.operands.iter().filter_map(\n\n |maybe_op| maybe_op.as_ref().map(|op| if let OperandType::Set(_) = op.op_type {\n\n OperandDefinition {\n\n encoding: op.encoding,\n\n access: op.access,\n\n size: op.size,\n\n op_type: part.clone()\n\n }\n\n } else { op.clone() }\n\n )).collect()).collect()\n\n } else {\n\n vec![instr.operands.iter().filter_map(|x| x.as_ref()).cloned().collect()]\n\n }\n\n}\n\n\n", "file_path": "gen_defs/src/gen_tests.rs", "rank": 23, "score": 328989.55420121795 }, { "content": "#[test]\n\nfn operand_type_v() {\n\n decode_helper(\n\n &vec![0x40],\n\n Mode::Real,\n\n &Instruction::new1(Mnemonic::INC, Operand::Direct(Reg::AX)),\n\n ); // INC AX\n\n decode_helper(\n\n &vec![0x66, 0x40],\n\n Mode::Real,\n\n &Instruction::new1(Mnemonic::INC, Operand::Direct(Reg::EAX)),\n\n ); // INC EAX\n\n decode_helper(\n\n &vec![0x66, 0x40],\n\n Mode::Protected,\n\n &Instruction::new1(Mnemonic::INC, Operand::Direct(Reg::AX)),\n\n ); // INC AX\n\n decode_helper(\n\n &vec![0x40],\n\n Mode::Protected,\n\n &Instruction::new1(Mnemonic::INC, Operand::Direct(Reg::EAX)),\n\n ); // INC EAX\n\n}\n\n\n", "file_path": "src/test/decode.rs", "rank": 24, "score": 322405.83004577464 }, { "content": "#[test]\n\nfn operand_type_q() {\n\n decode_helper(\n\n &vec![0xFF, 0x20],\n\n Mode::Long,\n\n &Instruction::new1(\n\n Mnemonic::JMP,\n\n Operand::Indirect(Reg::RAX, Some(OperandSize::Qword), None),\n\n ),\n\n ); // JMP QWORD PTR [RAX]\n\n}\n\n\n", "file_path": "src/test/decode.rs", "rank": 25, "score": 322405.83004577464 }, { "content": "#[test]\n\nfn operand_type_w() {\n\n decode_helper(\n\n &vec![0xC8, 0x05, 0x00, 0x06],\n\n Mode::Real,\n\n &Instruction::new2(\n\n Mnemonic::ENTER,\n\n Operand::Literal16(0x5),\n\n Operand::Literal8(0x06),\n\n ),\n\n ); // ENTER 5, 6\n\n decode_helper(\n\n &vec![0xC8, 0x05, 0x00, 0x06],\n\n Mode::Protected,\n\n &Instruction::new2(\n\n Mnemonic::ENTER,\n\n Operand::Literal16(0x5),\n\n Operand::Literal8(0x06),\n\n ),\n\n ); // ENTER 5, 6\n\n decode_helper(\n\n &vec![0xC8, 0x05, 0x00, 0x06],\n\n Mode::Long,\n\n &Instruction::new2(\n\n Mnemonic::ENTER,\n\n Operand::Literal16(0x5),\n\n Operand::Literal8(0x06),\n\n ),\n\n ); // ENTER 5, 6\n\n}\n\n\n", "file_path": "src/test/decode.rs", "rank": 26, "score": 322405.83004577464 }, { "content": "#[test]\n\nfn operand_type_p() {\n\n decode_helper(\n\n &vec![0x9A, 0xAB, 0x89, 0x67, 0x45, 0x23, 0x01],\n\n Mode::Protected,\n\n &Instruction::new1(\n\n Mnemonic::CALL,\n\n Operand::MemoryAndSegment32(0x0123, 0x456789AB),\n\n ),\n\n ); // CALL 0x0123:0x456789AB\n\n decode_helper(\n\n &vec![0x66, 0x9A, 0x67, 0x45, 0x23, 0x01],\n\n Mode::Protected,\n\n &Instruction::new1(Mnemonic::CALL, Operand::MemoryAndSegment16(0x0123, 0x4567)),\n\n ); // CALL 0x0123:0x4567\n\n decode_helper(\n\n &vec![0x9A, 0x67, 0x45, 0x23, 0x01],\n\n Mode::Real,\n\n &Instruction::new1(Mnemonic::CALL, Operand::MemoryAndSegment16(0x0123, 0x4567)),\n\n ); // CALL 0x0123:0x4567\n\n}\n\n\n", "file_path": "src/test/decode.rs", "rank": 27, "score": 322405.83004577464 }, { "content": "#[test]\n\nfn operand_type_b() {\n\n decode_helper(\n\n &vec![0xC4, 0xE3, 0x79, 0x32, 0xCA, 0x05],\n\n Mode::Protected,\n\n &Instruction::new3(\n\n Mnemonic::KSHIFTLB,\n\n Operand::Direct(Reg::K1),\n\n Operand::Direct(Reg::K2),\n\n Operand::Literal8(5),\n\n ),\n\n ); // KSHIFTLB K1, K2, 5\n\n}\n\n\n", "file_path": "src/test/decode.rs", "rank": 28, "score": 322405.83004577464 }, { "content": "#[test]\n\nfn operand_type_a() {\n\n decode_helper(\n\n &vec![0x66, 0x62, 0x00],\n\n Mode::Protected,\n\n &Instruction::new2(\n\n Mnemonic::BOUND,\n\n Operand::Direct(Reg::AX),\n\n Operand::Indirect(Reg::EAX, Some(OperandSize::Unsized), None),\n\n ),\n\n ); // BOUND AX, [EAX]\n\n decode_helper(\n\n &vec![0x62, 0x00],\n\n Mode::Protected,\n\n &Instruction::new2(\n\n Mnemonic::BOUND,\n\n Operand::Direct(Reg::EAX),\n\n Operand::Indirect(Reg::EAX, Some(OperandSize::Unsized), None),\n\n ),\n\n ); // BOUND EAX, [EAX]\n\n}\n\n\n", "file_path": "src/test/decode.rs", "rank": 29, "score": 322405.83004577464 }, { "content": "#[test]\n\nfn operand_type_d() {\n\n decode_helper(\n\n &vec![0x0F, 0x6E, 0xD0],\n\n Mode::Protected,\n\n &Instruction::new2(\n\n Mnemonic::MOVD,\n\n Operand::Direct(Reg::MM2),\n\n Operand::Direct(Reg::EAX),\n\n ),\n\n ); // MOVD MM2, EAX\n\n}\n\n\n", "file_path": "src/test/decode.rs", "rank": 30, "score": 322405.83004577464 }, { "content": "#[test]\n\nfn addressing_mode_masked_mask_reg() {\n\n decode_helper(\n\n &vec![0x62, 0xF1, 0x6D, 0x2B, 0x74, 0xD3],\n\n Mode::Long,\n\n &Instruction {\n\n mnemonic: Mnemonic::VPCMPEQB,\n\n operand1: Some(Operand::Direct(Reg::K2)),\n\n operand2: Some(Operand::Direct(Reg::YMM2)),\n\n operand3: Some(Operand::Direct(Reg::YMM3)),\n\n mask: Some(MaskReg::K3),\n\n merge_mode: Some(MergeMode::Merge),\n\n ..Default::default()\n\n },\n\n ); // VPCMPEQB K2 {K3}, YMM2, YMM3\n\n}\n\n\n", "file_path": "src/test/decode.rs", "rank": 31, "score": 322402.04090135463 }, { "content": "fn build_test_operand(instr: &mut Instruction, instr_def: &InstructionDefinition,\n\n def: &OperandDefinition, addr_size: OperandSize) -> Operand {\n\n match def.op_type {\n\n OperandType::Reg(reg_type) =>\n\n Operand::Direct(random_reg(reg_type, def.size, addr_size, instr_def)),\n\n OperandType::Mem(size) => random_mem(size.unwrap_or(def.size), addr_size),\n\n OperandType::Imm => random_imm(def.size),\n\n OperandType::Offset => Operand::Offset(rand_value_of_size(def.size), Some(def.size), None),\n\n OperandType::Rel(op_size) => random_imm(op_size), // TODO Is this correct?\n\n OperandType::Mib => random_mib(def.size, addr_size),\n\n OperandType::Bcst(bcst_size) => random_mem(bcst_size, addr_size),\n\n OperandType::Fixed(fixed_op) => random_fixed(fixed_op),\n\n OperandType::Constant => unimplemented!(), // TODO What is this?\n\n _ => unreachable!() // Set(_) should be split apart already\n\n }\n\n}\n\n\n", "file_path": "gen_defs/src/gen_tests.rs", "rank": 32, "score": 320714.5979397588 }, { "content": "fn make_rm(size: OperandSize, reg_type: RegType) -> InstructionToken {\n\n let vec = vec![InstructionToken::Reg(reg_type, size), InstructionToken::Mem(size)];\n\n InstructionToken::Set(vec)\n\n}\n\n\n", "file_path": "gen_defs/src/main.rs", "rank": 33, "score": 318056.8734751269 }, { "content": "// Test decoding of the operand size prefix.\n\nfn operand_size_prefix() {\n\n decode_helper(\n\n &vec![0xC5, 0xE9, 0x58, 0x08],\n\n Mode::Protected,\n\n &Instruction::new3(\n\n Mnemonic::VADDPD,\n\n Operand::Direct(Reg::XMM1),\n\n Operand::Direct(Reg::XMM2),\n\n Operand::Indirect(Reg::EAX, Some(OperandSize::Xmmword), None),\n\n ),\n\n ); // VADDPD XMM1, XMM2, [EAX]\n\n}\n\n\n\n#[test]\n", "file_path": "src/test/decode.rs", "rank": 34, "score": 317057.37213678606 }, { "content": "#[test]\n\nfn operand_type_psq() {\n\n decode_helper(\n\n &vec![0x0F, 0x2C, 0xCA],\n\n Mode::Protected,\n\n &Instruction::new2(\n\n Mnemonic::CVTTPS2PI,\n\n Operand::Direct(Reg::MM1),\n\n Operand::Direct(Reg::XMM2),\n\n ),\n\n ); // CVTTPS2PI MM1, XMM2\n\n decode_helper(\n\n &vec![0x0F, 0x2C, 0x08],\n\n Mode::Protected,\n\n &Instruction::new2(\n\n Mnemonic::CVTTPS2PI,\n\n Operand::Direct(Reg::MM1),\n\n Operand::Indirect(Reg::EAX, Some(OperandSize::Qword), None),\n\n ),\n\n ); // CVTTPS2PI MM1, [EAX]\n\n}\n\n\n", "file_path": "src/test/decode.rs", "rank": 35, "score": 317044.3639582245 }, { "content": "#[test]\n\nfn operand_type_vs() {\n\n decode_helper(\n\n &vec![0x66, 0x68, 0x34, 0x12],\n\n Mode::Protected,\n\n &Instruction::new1(Mnemonic::PUSH, Operand::Literal16(0x1234)),\n\n ); // PUSH 0x1234\n\n decode_helper(\n\n &vec![0x68, 0x78, 0x56, 0x34, 0x12],\n\n Mode::Protected,\n\n &Instruction::new1(Mnemonic::PUSH, Operand::Literal32(0x12345678)),\n\n ); // PUSH 0x12345678\n\n}\n\n\n", "file_path": "src/test/decode.rs", "rank": 36, "score": 317044.3639582245 }, { "content": "#[test]\n\nfn operand_type_vqp() {\n\n decode_helper(\n\n &vec![0x66, 0x01, 0xC3],\n\n Mode::Long,\n\n &Instruction::new2(\n\n Mnemonic::ADD,\n\n Operand::Direct(Reg::BX),\n\n Operand::Direct(Reg::AX),\n\n ),\n\n ); // ADD BX, AX\n\n decode_helper(\n\n &vec![0x01, 0xC3],\n\n Mode::Long,\n\n &Instruction::new2(\n\n Mnemonic::ADD,\n\n Operand::Direct(Reg::EBX),\n\n Operand::Direct(Reg::EAX),\n\n ),\n\n ); // ADD EBX, EAX\n\n decode_helper(\n\n &vec![0x48, 0x01, 0xC3],\n\n Mode::Long,\n\n &Instruction::new2(\n\n Mnemonic::ADD,\n\n Operand::Direct(Reg::RBX),\n\n Operand::Direct(Reg::RAX),\n\n ),\n\n ); // ADD RBX, RAX\n\n}\n\n\n", "file_path": "src/test/decode.rs", "rank": 37, "score": 317044.3639582245 }, { "content": "#[test]\n\nfn operand_type_dr() {\n\n decode_helper(\n\n &vec![0xDC, 0x00],\n\n Mode::Protected,\n\n &Instruction::new1(\n\n Mnemonic::FADD,\n\n Operand::Indirect(Reg::EAX, Some(OperandSize::Qword), None),\n\n ),\n\n ); // FADD QWORD PTR [EAX]\n\n}\n\n\n", "file_path": "src/test/decode.rs", "rank": 38, "score": 317044.3639582245 }, { "content": "#[test]\n\nfn operand_type_bound() {\n\n decode_helper(\n\n &vec![0xF3, 0x0F, 0x1A, 0xC8],\n\n Mode::Protected,\n\n &Instruction::new2(\n\n Mnemonic::BNDCL,\n\n Operand::Direct(Reg::BND1),\n\n Operand::Direct(Reg::EAX),\n\n ),\n\n ); // BNDCL BND1, EAX\n\n}\n\n\n", "file_path": "src/test/decode.rs", "rank": 39, "score": 317044.3639582245 }, { "content": "#[test]\n\nfn operand_type_qp() {\n\n decode_helper(\n\n &vec![0x48, 0xCF],\n\n Mode::Long,\n\n &Instruction::new0(Mnemonic::IRETQ),\n\n ); // IRETQ\n\n}\n\n\n", "file_path": "src/test/decode.rs", "rank": 40, "score": 317044.3639582245 }, { "content": "#[test]\n\nfn operand_type_bcd() {\n\n decode_helper(\n\n &vec![0xDF, 0x20],\n\n Mode::Protected,\n\n &Instruction::new1(\n\n Mnemonic::FBLD,\n\n Operand::Indirect(Reg::EAX, Some(OperandSize::Tbyte), None),\n\n ),\n\n ); // FBLD [EAX]\n\n}\n\n\n", "file_path": "src/test/decode.rs", "rank": 41, "score": 317044.3639582245 }, { "content": "#[test]\n\nfn operand_type_xmm() {\n\n decode_helper(\n\n &vec![0xC5, 0xE9, 0x58, 0xCB],\n\n Mode::Long,\n\n &Instruction::new3(\n\n Mnemonic::VADDPD,\n\n Operand::Direct(Reg::XMM1),\n\n Operand::Direct(Reg::XMM2),\n\n Operand::Direct(Reg::XMM3),\n\n ),\n\n ); // VADDPD XMM1, XMM2, XMM3\n\n decode_helper(\n\n &vec![0xC5, 0xE9, 0x58, 0x08],\n\n Mode::Long,\n\n &Instruction::new3(\n\n Mnemonic::VADDPD,\n\n Operand::Direct(Reg::XMM1),\n\n Operand::Direct(Reg::XMM2),\n\n Operand::Indirect(Reg::RAX, Some(OperandSize::Xmmword), None),\n\n ),\n\n ); // VADDPD XMM1, XMM2, [EAX}\n\n}\n\n\n", "file_path": "src/test/decode.rs", "rank": 42, "score": 317044.3639582245 }, { "content": "#[test]\n\nfn operand_type_vds() {\n\n decode_helper(\n\n &vec![0x05, 0x34, 0x12],\n\n Mode::Real,\n\n &Instruction::new2(\n\n Mnemonic::ADD,\n\n Operand::Direct(Reg::AX),\n\n Operand::Literal16(0x1234),\n\n ),\n\n ); // ADD AX, 0x1234\n\n decode_helper(\n\n &vec![0x66, 0x05, 0x78, 0x56, 0x34, 0x12],\n\n Mode::Real,\n\n &Instruction::new2(\n\n Mnemonic::ADD,\n\n Operand::Direct(Reg::EAX),\n\n Operand::Literal32(0x12345678),\n\n ),\n\n ); // ADD EAX, 0x12345678\n\n decode_helper(\n", "file_path": "src/test/decode.rs", "rank": 43, "score": 317044.3639582245 }, { "content": "#[test]\n\nfn operand_type_bss() {\n\n decode_helper(\n\n &vec![0x6A, 0x12],\n\n Mode::Protected,\n\n &Instruction::new1(Mnemonic::PUSH, Operand::Literal8(0x12)),\n\n ); // PUSH 0x12\n\n}\n\n\n", "file_path": "src/test/decode.rs", "rank": 44, "score": 317044.3639582245 }, { "content": "#[test]\n\nfn operand_type_ds() {\n\n decode_helper(\n\n &vec![0xE8, 0x78, 0x56, 0x34, 0x12],\n\n Mode::Protected,\n\n &Instruction::new1(Mnemonic::CALL, Operand::Offset(0x12345678, None, None)),\n\n ); // CALL 0x12345678\n\n}\n\n\n\n// I've temporarily disabled this test as the decoding logic will need to lookahead in order to\n\n// distiguish between a standalone FWAIT instruction and an instruction prefixed with 0x9B.\n\n// #[test]\n\n// fn operand_type_e() {\n\n// decode_helper(&vec![0x9B, 0xD9, 0x30], Mode::Protected, &Instruction::new1(Mnemonic::FSTENV, Operand::Indirect(Reg::EAX, None, None))); // FSTENV [EAX]\n\n// }\n\n\n", "file_path": "src/test/decode.rs", "rank": 45, "score": 317044.3639582245 }, { "content": "#[test]\n\nfn operand_type_sd() {\n\n decode_helper(\n\n &vec![0xF2, 0x0F, 0x58, 0xCA],\n\n Mode::Long,\n\n &Instruction::new2(\n\n Mnemonic::ADDSD,\n\n Operand::Direct(Reg::XMM1),\n\n Operand::Direct(Reg::XMM2),\n\n ),\n\n ); // ADDSD XMM1, XMM2\n\n decode_helper(\n\n &vec![0xF2, 0x0F, 0x58, 0x08],\n\n Mode::Long,\n\n &Instruction::new2(\n\n Mnemonic::ADDSD,\n\n Operand::Direct(Reg::XMM1),\n\n Operand::Indirect(Reg::RAX, Some(OperandSize::Qword), None),\n\n ),\n\n ); // ADDSD XMM1, [RAX]\n\n}\n\n\n", "file_path": "src/test/decode.rs", "rank": 46, "score": 317044.3639582245 }, { "content": "#[test]\n\nfn operand_type_ss() {\n\n decode_helper(\n\n &vec![0xF3, 0x0F, 0x58, 0xCA],\n\n Mode::Long,\n\n &Instruction::new2(\n\n Mnemonic::ADDSS,\n\n Operand::Direct(Reg::XMM1),\n\n Operand::Direct(Reg::XMM2),\n\n ),\n\n ); // ADDSS XMM1, XMM2\n\n decode_helper(\n\n &vec![0xF3, 0x0F, 0x58, 0x08],\n\n Mode::Long,\n\n &Instruction::new2(\n\n Mnemonic::ADDSS,\n\n Operand::Direct(Reg::XMM1),\n\n Operand::Indirect(Reg::RAX, Some(OperandSize::Dword), None),\n\n ),\n\n ); // ADDSS XMM1, [RAX]\n\n}\n\n\n", "file_path": "src/test/decode.rs", "rank": 47, "score": 317044.3639582245 }, { "content": "#[test]\n\nfn operand_type_avx() {\n\n decode_helper(\n\n &vec![0x62, 0xF1, 0xED, 0x0A, 0x58, 0xCB],\n\n Mode::Long,\n\n &Instruction {\n\n mnemonic: Mnemonic::VADDPD,\n\n operand1: Some(Operand::Direct(Reg::XMM1)),\n\n operand2: Some(Operand::Direct(Reg::XMM2)),\n\n operand3: Some(Operand::Direct(Reg::XMM3)),\n\n mask: Some(MaskReg::K2),\n\n merge_mode: Some(MergeMode::Merge),\n\n ..Default::default()\n\n },\n\n ); // VADDPD XMM1 {K2}, XMM2, XMM3\n\n decode_helper(\n\n &vec![0x62, 0xF1, 0xED, 0x2A, 0x58, 0xCB],\n\n Mode::Long,\n\n &Instruction {\n\n mnemonic: Mnemonic::VADDPD,\n\n operand1: Some(Operand::Direct(Reg::YMM1)),\n", "file_path": "src/test/decode.rs", "rank": 48, "score": 317044.3639582245 }, { "content": "#[test]\n\nfn operand_type_ymm() {\n\n decode_helper(\n\n &vec![0xC5, 0xED, 0x58, 0xCB],\n\n Mode::Long,\n\n &Instruction::new3(\n\n Mnemonic::VADDPD,\n\n Operand::Direct(Reg::YMM1),\n\n Operand::Direct(Reg::YMM2),\n\n Operand::Direct(Reg::YMM3),\n\n ),\n\n ); // VADDPD YMM1, YMM2, YMM3\n\n decode_helper(\n\n &vec![0xC5, 0xED, 0x58, 0x08],\n\n Mode::Long,\n\n &Instruction::new3(\n\n Mnemonic::VADDPD,\n\n Operand::Direct(Reg::YMM1),\n\n Operand::Direct(Reg::YMM2),\n\n Operand::Indirect(Reg::RAX, Some(OperandSize::Ymmword), None),\n\n ),\n\n ); // VADDPD YMM1, YMM2, [EAX}\n\n}\n\n\n", "file_path": "src/test/decode.rs", "rank": 49, "score": 317044.3639582245 }, { "content": "#[test]\n\nfn operand_type_dq() {\n\n decode_helper(\n\n &vec![0x66, 0x0F, 0x38, 0x00, 0x08],\n\n Mode::Protected,\n\n &Instruction::new2(\n\n Mnemonic::PSHUFB,\n\n Operand::Direct(Reg::XMM1),\n\n Operand::Indirect(Reg::EAX, Some(OperandSize::Xmmword), None),\n\n ),\n\n ); // PSHUFB XMM1, [EAX]\n\n decode_helper(\n\n &vec![0x66, 0x0F, 0x38, 0x00, 0xCA],\n\n Mode::Protected,\n\n &Instruction::new2(\n\n Mnemonic::PSHUFB,\n\n Operand::Direct(Reg::XMM1),\n\n Operand::Direct(Reg::XMM2),\n\n ),\n\n ); // PSHUFB XMM1, [EAX]\n\n}\n\n\n", "file_path": "src/test/decode.rs", "rank": 50, "score": 317044.3639582245 }, { "content": "#[test]\n\nfn operand_type_di() {\n\n decode_helper(\n\n &vec![0xDA, 0x00],\n\n Mode::Protected,\n\n &Instruction::new1(\n\n Mnemonic::FIADD,\n\n Operand::Indirect(Reg::EAX, Some(OperandSize::Dword), None),\n\n ),\n\n ); // FIADD DWORD PTR [EAX}\n\n}\n\n\n", "file_path": "src/test/decode.rs", "rank": 51, "score": 317044.3639582245 }, { "content": "#[test]\n\nfn operand_type_bs() {\n\n decode_helper(\n\n &vec![0x6B, 0xC3, 0x12],\n\n Mode::Protected,\n\n &Instruction::new3(\n\n Mnemonic::IMUL,\n\n Operand::Direct(Reg::EAX),\n\n Operand::Direct(Reg::EBX),\n\n Operand::Literal8(0x12),\n\n ),\n\n ); // IMUL EAX, EBX, 0x12\n\n}\n\n\n", "file_path": "src/test/decode.rs", "rank": 52, "score": 317044.3639582245 }, { "content": "#[test]\n\nfn operand_type_ps() {\n\n decode_helper(\n\n &vec![0x0F, 0x58, 0xCA],\n\n Mode::Long,\n\n &Instruction::new2(\n\n Mnemonic::ADDPS,\n\n Operand::Direct(Reg::XMM1),\n\n Operand::Direct(Reg::XMM2),\n\n ),\n\n ); // ADDPS XMM1, XMM2\n\n decode_helper(\n\n &vec![0x0F, 0x58, 0x08],\n\n Mode::Long,\n\n &Instruction::new2(\n\n Mnemonic::ADDPS,\n\n Operand::Direct(Reg::XMM1),\n\n Operand::Indirect(Reg::RAX, Some(OperandSize::Xmmword), None),\n\n ),\n\n ); // ADDPS XMM1, [EAX]1\n\n}\n\n\n", "file_path": "src/test/decode.rs", "rank": 53, "score": 317044.3639582245 }, { "content": "#[test]\n\nfn operand_type_pi() {\n\n decode_helper(\n\n &vec![0x0F, 0x2A, 0xCA],\n\n Mode::Protected,\n\n &Instruction::new2(\n\n Mnemonic::CVTPI2PS,\n\n Operand::Direct(Reg::XMM1),\n\n Operand::Direct(Reg::MM2),\n\n ),\n\n ); // CVTPI2PS XMM1, MM2\n\n}\n\n\n", "file_path": "src/test/decode.rs", "rank": 54, "score": 317044.3639582245 }, { "content": "#[test]\n\nfn operand_type_dqp() {\n\n decode_helper(\n\n &vec![0xF2, 0x48, 0x0F, 0x38, 0xF0, 0xC0],\n\n Mode::Long,\n\n &Instruction::new2(\n\n Mnemonic::CRC32,\n\n Operand::Direct(Reg::RAX),\n\n Operand::Direct(Reg::AL),\n\n ),\n\n ); // CRC32 RAX, AL\n\n decode_helper(\n\n &vec![0xF2, 0x0F, 0x38, 0xF0, 0xC0],\n\n Mode::Protected,\n\n &Instruction::new2(\n\n Mnemonic::CRC32,\n\n Operand::Direct(Reg::EAX),\n\n Operand::Direct(Reg::AL),\n\n ),\n\n ); // CRC32 EAX, AL\n\n}\n\n\n", "file_path": "src/test/decode.rs", "rank": 55, "score": 317044.3639582245 }, { "content": "#[test]\n\nfn operand_type_zmm() {\n\n decode_helper(\n\n &vec![0x62, 0xF1, 0xED, 0x48, 0x58, 0xCB],\n\n Mode::Long,\n\n &Instruction::new3(\n\n Mnemonic::VADDPD,\n\n Operand::Direct(Reg::ZMM1),\n\n Operand::Direct(Reg::ZMM2),\n\n Operand::Direct(Reg::ZMM3),\n\n ),\n\n ); // VADDPD ZMM1, ZMM2, ZMM3\n\n decode_helper(\n\n &vec![0x62, 0xF1, 0xED, 0x48, 0x58, 0x08],\n\n Mode::Long,\n\n &Instruction::new3(\n\n Mnemonic::VADDPD,\n\n Operand::Direct(Reg::ZMM1),\n\n Operand::Direct(Reg::ZMM2),\n\n Operand::Indirect(Reg::RAX, Some(OperandSize::Zmmword), None),\n\n ),\n\n ); // VADDPD ZMM1, ZMM2, [EAX}\n\n}\n\n\n", "file_path": "src/test/decode.rs", "rank": 56, "score": 317044.3639582245 }, { "content": "#[test]\n\nfn operand_type_ptp() {\n\n decode_helper(\n\n &vec![0xFF, 0x10],\n\n Mode::Protected,\n\n &Instruction::new1(\n\n Mnemonic::CALL,\n\n Operand::Indirect(Reg::EAX, Some(OperandSize::Dword), None),\n\n ),\n\n ); // CALL DWORD PTR [EAX]\n\n decode_helper(\n\n &vec![0xFF, 0x18],\n\n Mode::Protected,\n\n &Instruction::new1(\n\n Mnemonic::CALL,\n\n Operand::Indirect(Reg::EAX, Some(OperandSize::Fword), None),\n\n ),\n\n ); // CALL FWORD PTR [EAX]\n\n\n\n // TODO I'm not 100% sure this is correct. It seems to be from the Intel docs, but GCC won't\n\n // seem to accept this form?\n\n decode_helper(\n\n &vec![0x48, 0xFF, 0x18],\n\n Mode::Long,\n\n &Instruction::new1(\n\n Mnemonic::CALL,\n\n Operand::Indirect(Reg::RAX, Some(OperandSize::Tbyte), None),\n\n ),\n\n ); // CALL TBYTE PTR [EAX]\n\n}\n\n\n", "file_path": "src/test/decode.rs", "rank": 57, "score": 317044.3639582245 }, { "content": "#[test]\n\nfn operand_type_pd() {\n\n decode_helper(\n\n &vec![0x66, 0x0F, 0x58, 0xCA],\n\n Mode::Long,\n\n &Instruction::new2(\n\n Mnemonic::ADDPD,\n\n Operand::Direct(Reg::XMM1),\n\n Operand::Direct(Reg::XMM2),\n\n ),\n\n ); // ADDPD XMM1, XMM2\n\n decode_helper(\n\n &vec![0x66, 0x0F, 0x58, 0x08],\n\n Mode::Long,\n\n &Instruction::new2(\n\n Mnemonic::ADDPD,\n\n Operand::Direct(Reg::XMM1),\n\n Operand::Indirect(Reg::RAX, Some(OperandSize::Xmmword), None),\n\n ),\n\n ); // ADDPD XMM1, [EAX]1\n\n}\n\n\n", "file_path": "src/test/decode.rs", "rank": 58, "score": 317044.3639582245 }, { "content": "#[test]\n\nfn operand_type_vq() {\n\n decode_helper(\n\n &vec![0x66, 0x50],\n\n Mode::Long,\n\n &Instruction::new1(Mnemonic::PUSH, Operand::Direct(Reg::AX)),\n\n ); // PUSH AX\n\n decode_helper(\n\n &vec![0x50],\n\n Mode::Long,\n\n &Instruction::new1(Mnemonic::PUSH, Operand::Direct(Reg::RAX)),\n\n ); // PUSH RAX\n\n}\n\n\n", "file_path": "src/test/decode.rs", "rank": 59, "score": 317044.3639582245 }, { "content": "#[test]\n\nfn operand_type_er() {\n\n decode_helper(\n\n &vec![0xDB, 0x28],\n\n Mode::Protected,\n\n &Instruction::new1(\n\n Mnemonic::FLD,\n\n Operand::Indirect(Reg::EAX, Some(OperandSize::Tbyte), None),\n\n ),\n\n ); // FLD TBYTE PTR [EAX]\n\n}\n\n\n", "file_path": "src/test/decode.rs", "rank": 60, "score": 317044.3639582245 }, { "content": "fn build_test_instruction(def: &InstructionDefinition, op_defs: Vec<OperandDefinition>,\n\n addr_size: OperandSize) -> Instruction {\n\n\n\n let mut instr = Instruction {\n\n mnemonic: def.mnemonic.clone(),\n\n .. Default::default()\n\n };\n\n\n\n let first_op_not_mem = op_defs.iter().next().map(|o| !o.op_type.is_mem()).unwrap_or(true);\n\n if def.allow_mask && first_op_not_mem { instr.mask = Some(random_mask()); }\n\n if def.allow_merge_mode && first_op_not_mem { instr.merge_mode = Some(MergeMode::Zero) }\n\n\n\n if op_defs.iter().all(|d| !d.op_type.is_mem()) {\n\n if def.allow_rounding & op_defs.iter().all(\n\n |op_def| if let OperandType::Reg(_) = op_def.op_type { true } else { false })\n\n { instr.rounding_mode = Some(random_rounding_mode()); }\n\n else if def.allow_sae { instr.sae = true; }\n\n }\n\n\n\n let broadcast_size = op_defs.iter().filter_map(\n", "file_path": "gen_defs/src/gen_tests.rs", "rank": 61, "score": 316645.5576981066 }, { "content": "fn build_test_instructions(def: &InstructionDefinition, addr_size: OperandSize) -> Vec<Instruction> {\n\n let op_combinations = make_operand_combinations(def);\n\n op_combinations.into_iter().filter(filter_op_combination)\n\n .map(|op_c| build_test_instruction(def, op_c, addr_size)).collect()\n\n}\n\n\n", "file_path": "gen_defs/src/gen_tests.rs", "rank": 62, "score": 315604.41124553315 }, { "content": "#[test]\n\nfn addressing_mode_masked_reg() {\n\n decode_helper(\n\n &vec![0x62, 0xF1, 0xED, 0x0A, 0x58, 0xCB],\n\n Mode::Protected,\n\n &Instruction {\n\n mnemonic: Mnemonic::VADDPD,\n\n operand1: Some(Operand::Direct(Reg::XMM1)),\n\n operand2: Some(Operand::Direct(Reg::XMM2)),\n\n operand3: Some(Operand::Direct(Reg::XMM3)),\n\n mask: Some(MaskReg::K2),\n\n merge_mode: Some(MergeMode::Merge),\n\n ..Default::default()\n\n },\n\n ); // VADDPD XMM1 {K2}, XMM2, XMM3\n\n}\n\n\n", "file_path": "src/test/decode.rs", "rank": 63, "score": 311921.61597882846 }, { "content": "#[test]\n\nfn addressing_mode_mask_reg() {\n\n decode_helper(\n\n &vec![0xC5, 0xE5, 0x4A, 0xD4],\n\n Mode::Protected,\n\n &Instruction {\n\n mnemonic: Mnemonic::KADDB,\n\n operand1: Some(Operand::Direct(Reg::K2)),\n\n operand2: Some(Operand::Direct(Reg::K3)),\n\n operand3: Some(Operand::Direct(Reg::K4)),\n\n ..Default::default()\n\n },\n\n ); // KADDB K2, K3, K4\n\n}\n\n\n", "file_path": "src/test/decode.rs", "rank": 64, "score": 311921.61597882846 }, { "content": "#[test]\n\nfn operand_type_xmm_or_ymm() {\n\n decode_helper(\n\n &vec![0xC5, 0xE9, 0x58, 0xCB],\n\n Mode::Long,\n\n &Instruction::new3(\n\n Mnemonic::VADDPD,\n\n Operand::Direct(Reg::XMM1),\n\n Operand::Direct(Reg::XMM2),\n\n Operand::Direct(Reg::XMM3),\n\n ),\n\n ); // VADDPD XMM1, XMM2, XMM3\n\n decode_helper(\n\n &vec![0xC5, 0xED, 0x58, 0xCB],\n\n Mode::Long,\n\n &Instruction::new3(\n\n Mnemonic::VADDPD,\n\n Operand::Direct(Reg::YMM1),\n\n Operand::Direct(Reg::YMM2),\n\n Operand::Direct(Reg::YMM3),\n\n ),\n\n ); // VADDPD YMM1, YMM2, YMM3\n\n}\n\n\n", "file_path": "src/test/decode.rs", "rank": 65, "score": 311894.7044301774 }, { "content": "#[test]\n\nfn operand_type_bound_or_mem() {\n\n decode_helper(\n\n &vec![0x66, 0x0F, 0x1A, 0xCA],\n\n Mode::Protected,\n\n &Instruction::new2(\n\n Mnemonic::BNDMOV,\n\n Operand::Direct(Reg::BND1),\n\n Operand::Direct(Reg::BND2),\n\n ),\n\n ); // BNDMOV BND1, BND2\n\n decode_helper(\n\n &vec![0x66, 0x0F, 0x1A, 0x08],\n\n Mode::Protected,\n\n &Instruction::new2(\n\n Mnemonic::BNDMOV,\n\n Operand::Direct(Reg::BND1),\n\n Operand::Indirect(Reg::EAX, Some(OperandSize::Qword), None),\n\n ),\n\n ); // BNDMOV BND1, QWORD PTR [EAX]\n\n}\n\n\n", "file_path": "src/test/decode.rs", "rank": 66, "score": 311894.7044301774 }, { "content": "#[test]\n\nfn operand_type_xmm_or_mem32() {\n\n decode_helper(\n\n &vec![0xC5, 0xEA, 0x5A, 0xCB],\n\n Mode::Long,\n\n &Instruction::new3(\n\n Mnemonic::VCVTSS2SD,\n\n Operand::Direct(Reg::XMM1),\n\n Operand::Direct(Reg::XMM2),\n\n Operand::Direct(Reg::XMM3),\n\n ),\n\n ); // VCVTSS2SD XMM1, XMM2\n\n decode_helper(\n\n &vec![0xC5, 0xEA, 0x5A, 0x08],\n\n Mode::Long,\n\n &Instruction::new3(\n\n Mnemonic::VCVTSS2SD,\n\n Operand::Direct(Reg::XMM1),\n\n Operand::Direct(Reg::XMM2),\n\n Operand::Indirect(Reg::RAX, Some(OperandSize::Dword), None),\n\n ),\n", "file_path": "src/test/decode.rs", "rank": 67, "score": 311894.7044301774 }, { "content": "#[test]\n\nfn operand_type_xmm_or_mem64() {\n\n decode_helper(\n\n &vec![0x0F, 0x5A, 0xCA],\n\n Mode::Long,\n\n &Instruction::new2(\n\n Mnemonic::CVTPS2PD,\n\n Operand::Direct(Reg::XMM1),\n\n Operand::Direct(Reg::XMM2),\n\n ),\n\n ); // CVTPS2PD XMM1, XMM2\n\n decode_helper(\n\n &vec![0x0F, 0x5A, 0x08],\n\n Mode::Long,\n\n &Instruction::new2(\n\n Mnemonic::CVTPS2PD,\n\n Operand::Direct(Reg::XMM1),\n\n Operand::Indirect(Reg::RAX, Some(OperandSize::Qword), None),\n\n ),\n\n ); // CVTPS2PD XMM1, QWORD PTR [RAX]\n\n}\n\n\n", "file_path": "src/test/decode.rs", "rank": 68, "score": 311894.7044301774 }, { "content": "#[test]\n\nfn operand_type_unsized_memory() {\n\n decode_helper(\n\n &vec![0x8D, 0x03],\n\n Mode::Protected,\n\n &Instruction::new2(\n\n Mnemonic::LEA,\n\n Operand::Direct(Reg::EAX),\n\n Operand::Indirect(Reg::EBX, Some(OperandSize::Unsized), None),\n\n ),\n\n ); // LEA EAX, [EBX]\n\n}\n\n\n", "file_path": "src/test/decode.rs", "rank": 69, "score": 311894.7044301774 }, { "content": "#[test]\n\nfn operand_type_fpu_register() {\n\n decode_helper(\n\n &vec![0xD8, 0xC2],\n\n Mode::Protected,\n\n &Instruction::new2(\n\n Mnemonic::FADD,\n\n Operand::Direct(Reg::ST),\n\n Operand::Direct(Reg::ST2),\n\n ),\n\n ); // FADD ST(2)\n\n}\n", "file_path": "src/test/decode.rs", "rank": 70, "score": 311894.7044301774 }, { "content": "fn parse_operand_encoding_opt(operand: &str) -> Option<(OperandEncoding, OperandAccess)> {\n\n if operand.len() != 0 {\n\n Some(parse_operand_encoding(operand.as_bytes()).unwrap().1)\n\n } else {\n\n None\n\n }\n\n}\n\n\n\nnamed!(instruction_sep, eat_separator!(&b\", \"[..]));\n\nnamed!(parse_token_list<Vec<Vec<InstructionToken>>>, separated_list!(instruction_sep, parse_instruction_part));\n\nnamed!(parse_instruction<&[u8], (String, Vec<InstructionToken>), u32>, do_parse!(\n\n mnemonic: alphanumeric >> opt!(instruction_sep) >>\n\n tokens: opt!(complete!(parse_token_list)) >>\n\n (build_result(mnemonic, tokens))\n\n )\n\n);\n\n\n", "file_path": "gen_defs/src/main.rs", "rank": 71, "score": 311486.28128727485 }, { "content": "fn random_reg_64() -> Reg\n\n { random_of(&[Reg::RBX, Reg::RCX, Reg::RDX, Reg::RSI, Reg::RDI, Reg::RSP, Reg::RBP]) }\n\n\n", "file_path": "gen_defs/src/gen_tests.rs", "rank": 72, "score": 311326.47033738723 }, { "content": "fn random_reg_16() -> Reg\n\n { random_of(&[Reg::BX, Reg::CX, Reg::DX, Reg::SI, Reg::DI, Reg::SP, Reg::BP]) }\n", "file_path": "gen_defs/src/gen_tests.rs", "rank": 73, "score": 311326.47033738723 }, { "content": "fn random_reg_32() -> Reg\n\n { random_of(&[Reg::EBX, Reg::ECX, Reg::EDX, Reg::ESI, Reg::EDI, Reg::ESP, Reg::EBP]) }\n", "file_path": "gen_defs/src/gen_tests.rs", "rank": 74, "score": 311326.47033738723 }, { "content": "fn random_fpu_reg() -> Reg\n\n { random_of(&[Reg::ST1, Reg::ST2, Reg::ST3, Reg::ST4, Reg::ST5, Reg::ST6, Reg::ST7]) }\n\n\n", "file_path": "gen_defs/src/gen_tests.rs", "rank": 75, "score": 308105.8281911791 }, { "content": "fn random_reg_64_no_stack() -> Reg\n\n { random_of(&[Reg::RAX, Reg::RBX, Reg::RCX, Reg::RDX, Reg::RSI, Reg::RDI]) }\n\n\n", "file_path": "gen_defs/src/gen_tests.rs", "rank": 76, "score": 308105.8281911791 }, { "content": "fn random_reg_32_no_stack() -> Reg\n\n { random_of(&[Reg::EAX, Reg::EBX, Reg::ECX, Reg::EDX, Reg::ESI, Reg::EDI]) }\n", "file_path": "gen_defs/src/gen_tests.rs", "rank": 77, "score": 308105.8281911791 }, { "content": "fn random_mmx_reg() -> Reg\n\n { random_of(&[Reg::MM0, Reg::MM1, Reg::MM2, Reg::MM3, Reg::MM4, Reg::MM5, Reg::MM6, Reg::MM7]) }\n\n\n", "file_path": "gen_defs/src/gen_tests.rs", "rank": 78, "score": 308105.8281911791 }, { "content": "fn random_reg_16_no_stack() -> Reg\n\n { random_of(&[Reg::AX, Reg::BX, Reg::CX, Reg::DX, Reg::SI, Reg::DI]) }\n", "file_path": "gen_defs/src/gen_tests.rs", "rank": 79, "score": 308105.8281911791 }, { "content": "#[test]\n\nfn operand_type_ymm_or_mem_or_mem32() {\n\n decode_helper(\n\n &vec![0x62, 0xF1, 0x7C, 0x48, 0x5A, 0xCA],\n\n Mode::Long,\n\n &Instruction::new2(\n\n Mnemonic::VCVTPS2PD,\n\n Operand::Direct(Reg::ZMM1),\n\n Operand::Direct(Reg::YMM2),\n\n ),\n\n ); // VCVTPS2PD ZMM1, YMM2\n\n decode_helper(\n\n &vec![0x62, 0xF1, 0x7C, 0x48, 0x5A, 0x08],\n\n Mode::Long,\n\n &Instruction::new2(\n\n Mnemonic::VCVTPS2PD,\n\n Operand::Direct(Reg::ZMM1),\n\n Operand::Indirect(Reg::RAX, Some(OperandSize::Ymmword), None),\n\n ),\n\n ); // VCVTPS2PD ZMM1, YMMWORD PTR [RAX]\n\n decode_helper(\n", "file_path": "src/test/decode.rs", "rank": 80, "score": 306944.54334351444 }, { "content": "#[test]\n\nfn operand_type_ymm_or_mem_or_mem64() {\n\n decode_helper(\n\n &vec![0xC5, 0xFF, 0xE6, 0xCA],\n\n Mode::Long,\n\n &Instruction::new2(\n\n Mnemonic::VCVTPD2DQ,\n\n Operand::Direct(Reg::XMM1),\n\n Operand::Direct(Reg::YMM2),\n\n ),\n\n ); // VCVTPD2DQ XMM1, YMM2\n\n decode_helper(\n\n &vec![0xC5, 0xFF, 0xE6, 0x08],\n\n Mode::Long,\n\n &Instruction::new2(\n\n Mnemonic::VCVTPD2DQ,\n\n Operand::Direct(Reg::XMM1),\n\n Operand::Indirect(Reg::RAX, Some(OperandSize::Ymmword), None),\n\n ),\n\n ); // VCVTPD2DQ XMM1, YMMWORD PTR [RAX]\n\n decode_helper(\n", "file_path": "src/test/decode.rs", "rank": 81, "score": 306944.54334351444 }, { "content": "#[test]\n\nfn operand_type_zmm_or_mem_or_mem64() {\n\n decode_helper(\n\n &vec![0x62, 0xF1, 0xFD, 0x48, 0x5A, 0xCA],\n\n Mode::Long,\n\n &Instruction::new2(\n\n Mnemonic::VCVTPD2PS,\n\n Operand::Direct(Reg::YMM1),\n\n Operand::Direct(Reg::ZMM2),\n\n ),\n\n ); // VCVTPD2PS YMM1, ZMM2\n\n decode_helper(\n\n &vec![0x62, 0xF1, 0xFD, 0x48, 0x5A, 0x08],\n\n Mode::Long,\n\n &Instruction::new2(\n\n Mnemonic::VCVTPD2PS,\n\n Operand::Direct(Reg::YMM1),\n\n Operand::Indirect(Reg::RAX, Some(OperandSize::Zmmword), None),\n\n ),\n\n ); // VCVTPD2PS YMM1, ZMMWORD PTR [RAX]\n\n decode_helper(\n", "file_path": "src/test/decode.rs", "rank": 82, "score": 306944.54334351444 }, { "content": "#[test]\n\nfn infer_operand_size_16_32_instr() {\n\n encode32_helper2(\n\n Mnemonic::ADD,\n\n Operand::Direct(Reg::AX),\n\n Operand::Indirect(Reg::EBX, None, None),\n\n &vec![0x66, 0x03, 0x03],\n\n );\n\n encode32_helper2(\n\n Mnemonic::ADD,\n\n Operand::Direct(Reg::EAX),\n\n Operand::Indirect(Reg::EBX, None, None),\n\n &vec![0x03, 0x03],\n\n );\n\n}\n\n\n", "file_path": "src/test/size_inference.rs", "rank": 83, "score": 306944.54334351444 }, { "content": "fn encode(instr: &Instruction, def: &InstructionDefinition, addr_size: OperandSize)\n\n -> io::Result<Vec<u8>> {\n\n // Write instruction to file\n\n let mut test_file = File::create(\"test.s\")?;\n\n write!(test_file, \".intel_syntax noprefix\\n\")?;\n\n write!(test_file, \".code{}\\n\", match addr_size {\n\n OperandSize::Word => \"16\",\n\n OperandSize::Dword => \"32\",\n\n OperandSize::Qword => \"64\",\n\n _ => panic!(\"Invalid addressing size.\")\n\n })?;\n\n write_instruction(instr, def, &mut test_file)?;\n\n write!(test_file, \"\\n\")?;\n\n\n\n // Run assembler\n\n let as_result = Command::new(\"as\")\n\n .args(&[\"test.s\", \"-o\", \"test.out\"])\n\n .spawn()?\n\n .wait()?;\n\n if !as_result.success() {\n", "file_path": "gen_defs/src/gen_tests.rs", "rank": 84, "score": 303187.427868437 }, { "content": "#[test]\n\nfn addressing_mode_avx_reg_masked_rm() {\n\n decode_helper(\n\n &vec![0x62, 0xF1, 0xFF, 0x0D, 0x10, 0x10],\n\n Mode::Protected,\n\n &Instruction {\n\n mnemonic: Mnemonic::VMOVSD,\n\n operand1: Some(Operand::Direct(Reg::XMM2)),\n\n operand2: Some(Operand::Indirect(Reg::EAX, Some(OperandSize::Qword), None)),\n\n mask: Some(MaskReg::K5),\n\n merge_mode: Some(MergeMode::Merge),\n\n ..Default::default()\n\n },\n\n ); // VMOVSD XMM2 {K5}, [EAX]\n\n}\n\n\n", "file_path": "src/test/decode.rs", "rank": 85, "score": 302208.39689775347 }, { "content": "#[test]\n\nfn operand_type_xmm_or_ymm_or_mem_or_mem64() {\n\n decode_helper(\n\n &vec![0xC5, 0xF9, 0x5A, 0xCA],\n\n Mode::Long,\n\n &Instruction::new2(\n\n Mnemonic::VCVTPD2PS,\n\n Operand::Direct(Reg::XMM1),\n\n Operand::Direct(Reg::XMM2),\n\n ),\n\n ); // VCVTPD2PS XMM1, XMM2\n\n decode_helper(\n\n &vec![0xC5, 0xF9, 0x5A, 0x08],\n\n Mode::Long,\n\n &Instruction::new2(\n\n Mnemonic::VCVTPD2PS,\n\n Operand::Direct(Reg::XMM1),\n\n Operand::Indirect(Reg::RAX, Some(OperandSize::Xmmword), None),\n\n ),\n\n ); // VCVTPD2PS XMM1, XMMWORD PTR [RAX]\n\n decode_helper(\n", "file_path": "src/test/decode.rs", "rank": 86, "score": 302182.50809514255 }, { "content": "fn vcvtps2uqq_2() {\n\n run_test(&Instruction { mnemonic: Mnemonic::VCVTPS2UQQ, operand1: Some(Direct(XMM0)), operand2: Some(IndirectScaledDisplaced(ECX, Two, 1478787531, Some(OperandSize::Qword), None)), operand3: None, operand4: None, lock: false, rounding_mode: None, merge_mode: Some(MergeMode::Zero), sae: false, mask: Some(MaskReg::K7), broadcast: None }, &[98, 241, 125, 143, 121, 4, 77, 203, 129, 36, 88], OperandSize::Dword)\n\n}\n\n\n", "file_path": "src/test/instruction_tests/vcvtps2uqq.rs", "rank": 87, "score": 300752.634987277 }, { "content": "fn vcvtps2uqq_1() {\n\n run_test(&Instruction { mnemonic: Mnemonic::VCVTPS2UQQ, operand1: Some(Direct(XMM2)), operand2: Some(Direct(XMM2)), operand3: None, operand4: None, lock: false, rounding_mode: None, merge_mode: Some(MergeMode::Zero), sae: false, mask: Some(MaskReg::K2), broadcast: None }, &[98, 241, 125, 138, 121, 210], OperandSize::Dword)\n\n}\n\n\n", "file_path": "src/test/instruction_tests/vcvtps2uqq.rs", "rank": 88, "score": 300752.63498727704 }, { "content": "fn random_reg_8() -> Reg { random_of(&[Reg::BL, Reg::CL, Reg::DL]) }\n", "file_path": "gen_defs/src/gen_tests.rs", "rank": 89, "score": 299957.40658541943 }, { "content": "fn write_test<W: Write>(instr: &Instruction, encoded: &[u8], addr_size: OperandSize,\n\n writer: &mut W, test_count: &mut HashMap<String, u32>) -> io::Result<()> {\n\n let test_num = test_count.entry(instr.mnemonic.clone()).or_insert(0);\n\n *test_num += 1;\n\n\n\n write!(writer, \"#[test]\\nfn {}_{}() {{\\n run_test(&{:?}, &{:?}, {:?})\\n}}\\n\\n\",\n\n instr.mnemonic.to_lowercase(), test_num, instr, encoded, addr_size)\n\n}\n\n\n", "file_path": "gen_defs/src/gen_tests.rs", "rank": 92, "score": 295845.2649296818 }, { "content": "fn random_bound_reg() -> Reg { random_of(&[Reg::BND0, Reg::BND1, Reg::BND2, Reg::BND3]) }\n\n\n", "file_path": "gen_defs/src/gen_tests.rs", "rank": 93, "score": 294212.576199507 }, { "content": "fn random_control_reg() -> Reg { random_of(&[Reg::CR0, Reg::CR1, Reg::CR2, Reg::CR3, Reg::CR4 ]) }\n\n\n", "file_path": "gen_defs/src/gen_tests.rs", "rank": 94, "score": 290615.58209834783 }, { "content": "fn instr_token_to_operand_type(token: &InstructionToken) -> (OperandType, Option<OperandSize>) {\n\n match *token {\n\n InstructionToken::Reg(reg_type, op_size)\n\n => (OperandType::Reg(reg_type), Some(op_size)),\n\n InstructionToken::Mem(op_size)\n\n => (OperandType::Mem(Some(op_size)), Some(op_size)),\n\n InstructionToken::Imm(op_size)\n\n => (OperandType::Imm, Some(op_size)),\n\n InstructionToken::Bcst(bcst_size)\n\n => (OperandType::Bcst(bcst_size), None),\n\n InstructionToken::Rel(op_size)\n\n => (OperandType::Rel(op_size), Some(op_size)),\n\n InstructionToken::Offset(op_size)\n\n => (OperandType::Offset, Some(op_size)),\n\n InstructionToken::FixedReg(reg)\n\n => (OperandType::Fixed(FixedOperand::Reg(reg)), Some(reg.size())),\n\n InstructionToken::Constant(val)\n\n => (OperandType::Fixed(FixedOperand::Constant(val)), Some(OperandSize::Unsized)),\n\n InstructionToken::Mib\n\n => (OperandType::Mib, Some(OperandSize::Unsized)),\n\n _ => panic!(\"Unsupported type: {:?}\", *token)\n\n }\n\n}\n\n\n", "file_path": "gen_defs/src/main.rs", "rank": 95, "score": 290525.33096318727 }, { "content": "pub fn emit_tests_helper(instr: &InstructionDefinition, addr_size: OperandSize, output_dir: &str,\n\n test_count: &mut HashMap<String, u32>) -> io::Result<()> {\n\n if should_skip_instr(instr) { return Ok(()); }\n\n\n\n let test_instrs = build_test_instructions(instr, addr_size);\n\n\n\n let enc_result: io::Result<Vec<Vec<u8>>> = \n\n test_instrs.iter().map(|i| encode(i, instr, addr_size)).collect();\n\n let bytes = enc_result?;\n\n let mut writer = OpenOptions::new()\n\n .append(true)\n\n .create(true)\n\n .open(format!(\"{}/{}\", output_dir, instr.mnemonic.to_lowercase()))\n\n .unwrap();\n\n\n\n test_instrs.iter().zip(bytes.iter()).fold(Ok(()),\n\n |res, (i, b)| res.and(write_test(i, b, addr_size, &mut writer, test_count)))\n\n}\n\n\n", "file_path": "gen_defs/src/gen_tests.rs", "rank": 96, "score": 289957.72108000173 }, { "content": "fn random_segment_reg() -> Reg { random_of(&[Reg::CS, Reg::DS, Reg::ES, Reg::FS, Reg::GS, Reg::SS]) }\n\n\n", "file_path": "gen_defs/src/gen_tests.rs", "rank": 97, "score": 287095.9736255002 }, { "content": "fn random_debug_reg() -> Reg { random_of(&[Reg::DR0, Reg::DR1, Reg::DR2, Reg::DR3, Reg::DR4, Reg::DR5]) }\n\n\n", "file_path": "gen_defs/src/gen_tests.rs", "rank": 98, "score": 287095.9736255002 }, { "content": "fn size_seg_helper<F, W: Write>(f: &mut W, size: Option<OperandSize>, seg: Option<SegmentReg>,\n\n action: F) -> io::Result<()> where F: Fn(&mut W) -> io::Result<()> {\n\n write_size(f, size)?;\n\n write_seg(f, seg)?;\n\n action(f)\n\n}\n\n\n", "file_path": "gen_defs/src/gen_tests.rs", "rank": 99, "score": 279399.8178684347 } ]
Rust
verify/src/span.rs
tamasfe/verify
5f12650c5aef0edb63961042f7bc7b8da3644cea
use std::ops::{Add, AddAssign}; pub trait Span: core::fmt::Debug + Clone + core::ops::AddAssign {} pub trait SpanExt: Sized + Clone { fn combine(&mut self, span: Self); fn combined(&self, span: Self) -> Self { let mut new = self.clone(); new.combine(span); new } } impl<S: Span> SpanExt for S { fn combine(&mut self, span: Self) { *self += span; } } impl<S: Span> SpanExt for Option<S> { fn combine(&mut self, span: Self) { match span { Some(new_span) => match self { Some(s) => *s += new_span, None => *self = Some(new_span), }, None => { *self = None; } } } } pub trait Spanned { type Span: Span; fn span(&self) -> Option<Self::Span>; } #[cfg(feature = "smallvec")] type KeysSmallVecArray = [String; 10]; #[cfg(feature = "smallvec")] type KeysInner = smallvec_crate::SmallVec<KeysSmallVecArray>; #[cfg(not(feature = "smallvec"))] type KeysInner = Vec<String>; #[derive(Debug, Default, Clone, Eq, PartialEq)] #[repr(transparent)] pub struct Keys(KeysInner); impl Span for Keys {} impl Keys { pub fn new() -> Self { Keys(KeysInner::new()) } pub fn with_capacity(cap: usize) -> Self { Keys(KeysInner::with_capacity(cap)) } pub fn iter(&self) -> impl Iterator<Item = &String> { self.0.iter() } pub fn iter_mut(&mut self) -> impl Iterator<Item = &mut String> { self.0.iter_mut() } pub fn dotted(&self) -> String { self.0.join(".") } pub fn push(&mut self, value: String) { self.0.push(value) } pub fn into_inner(self) -> KeysInner { self.0 } } impl AddAssign for Keys { fn add_assign(&mut self, rhs: Self) { self.0.extend(rhs.0.into_iter()) } } impl<S: ToString> Add<S> for Keys { type Output = Self; fn add(mut self, rhs: S) -> Self::Output { self.push(rhs.to_string()); self } } impl From<String> for Keys { fn from(s: String) -> Self { let mut v = Self::new(); v.push(s); v } } impl IntoIterator for Keys { type Item = <KeysInner as IntoIterator>::Item; #[cfg(feature = "smallvec")] type IntoIter = smallvec_crate::IntoIter<KeysSmallVecArray>; #[cfg(not(feature = "smallvec"))] type IntoIter = std::vec::IntoIter<String>; fn into_iter(self) -> Self::IntoIter { self.0.into_iter() } }
use std::ops::{Add, AddAssign}; pub trait Span: core::fmt::Debug + Clone + core::ops::AddAssign {} pub trait SpanExt: Sized + Clone { fn combine(&mut self, span: Self); fn combined(&self, span: Self) -> Self { let mut new = self.clone(); new.combine(span); new } } impl<S: Span> SpanExt for S { fn combine(&mut self, span: Self) { *self += span; } } impl<S: Span> SpanExt for Option<S> {
} pub trait Spanned { type Span: Span; fn span(&self) -> Option<Self::Span>; } #[cfg(feature = "smallvec")] type KeysSmallVecArray = [String; 10]; #[cfg(feature = "smallvec")] type KeysInner = smallvec_crate::SmallVec<KeysSmallVecArray>; #[cfg(not(feature = "smallvec"))] type KeysInner = Vec<String>; #[derive(Debug, Default, Clone, Eq, PartialEq)] #[repr(transparent)] pub struct Keys(KeysInner); impl Span for Keys {} impl Keys { pub fn new() -> Self { Keys(KeysInner::new()) } pub fn with_capacity(cap: usize) -> Self { Keys(KeysInner::with_capacity(cap)) } pub fn iter(&self) -> impl Iterator<Item = &String> { self.0.iter() } pub fn iter_mut(&mut self) -> impl Iterator<Item = &mut String> { self.0.iter_mut() } pub fn dotted(&self) -> String { self.0.join(".") } pub fn push(&mut self, value: String) { self.0.push(value) } pub fn into_inner(self) -> KeysInner { self.0 } } impl AddAssign for Keys { fn add_assign(&mut self, rhs: Self) { self.0.extend(rhs.0.into_iter()) } } impl<S: ToString> Add<S> for Keys { type Output = Self; fn add(mut self, rhs: S) -> Self::Output { self.push(rhs.to_string()); self } } impl From<String> for Keys { fn from(s: String) -> Self { let mut v = Self::new(); v.push(s); v } } impl IntoIterator for Keys { type Item = <KeysInner as IntoIterator>::Item; #[cfg(feature = "smallvec")] type IntoIter = smallvec_crate::IntoIter<KeysSmallVecArray>; #[cfg(not(feature = "smallvec"))] type IntoIter = std::vec::IntoIter<String>; fn into_iter(self) -> Self::IntoIter { self.0.into_iter() } }
fn combine(&mut self, span: Self) { match span { Some(new_span) => match self { Some(s) => *s += new_span, None => *self = Some(new_span), }, None => { *self = None; } } }
function_block-full_function
[ { "content": "/// Spans is used to provide spans for values that implement Serde Serialize.\n\n///\n\n/// Span hierarchy is controlled by the validators, only the new spans are required.\n\npub trait Spans: Clone + Default {\n\n /// The span type that is associated with each value.\n\n type Span: Span;\n\n\n\n /// Span for a map key.\n\n fn key<S: ?Sized + Serialize>(&mut self, key: &S) -> NewSpan<Self::Span>;\n\n\n\n /// Span for a value.\n\n fn value<S: ?Sized + Serialize>(&mut self, value: &S) -> NewSpan<Self::Span>;\n\n\n\n /// Same as value but for unit types.\n\n fn unit(&mut self) -> NewSpan<Self::Span>;\n\n\n\n /// Span for a map value.\n\n fn map_start(&mut self) -> NewSpan<Self::Span>;\n\n\n\n /// Span for errors before closing a map.\n\n ///\n\n /// This doesn't get called for externally tagged variants.\n\n fn map_end(&mut self) -> NewSpan<Self::Span>;\n", "file_path": "verify/src/serde.rs", "rank": 1, "score": 120719.24843813365 }, { "content": "/// Values that implement [Validate](Validate) can validate themselves against\n\n/// types that implement this trait.\n\n///\n\n/// It is modelled after Serde [Serializer](serde::ser::Serializer), and works in a very similar fashion.\n\npub trait Validator<S: span::Span>: Sized {\n\n /// The error returned by the validator.\n\n type Error: Error;\n\n\n\n /// The type returned for validating sequences.\n\n ///\n\n /// The span type and error must match the Validator's.\n\n type ValidateSeq: ValidateSeq<S, Error = Self::Error>;\n\n\n\n /// The type returned for validating maps.\n\n ///\n\n /// The span type and error must match the Validator's.\n\n type ValidateMap: ValidateMap<S, Error = Self::Error>;\n\n\n\n /// Set the span for the current value that is being validated.\n\n ///\n\n /// In some cases this is needed to ensure that the validator returns\n\n /// the correct span in its errors.\n\n fn with_span(self, span: Option<S>) -> Self;\n\n\n", "file_path": "verify/src/lib.rs", "rank": 2, "score": 120611.51297615119 }, { "content": "/// Validate is implemented by values that can be validate themselves\n\n/// against a given validator.\n\npub trait Validate: span::Spanned {\n\n /// Validate self against a given validator.\n\n fn validate<V: Validator<Self::Span>>(&self, validator: V) -> Result<(), V::Error>;\n\n}\n\n\n", "file_path": "verify/src/lib.rs", "rank": 5, "score": 105642.13719865607 }, { "content": "/// This trait is implemented by types that validate a value internally.\n\n///\n\n/// It is useful when the actual [Validator](Validator) is not exposed, or there\n\n/// might be more than one validations taking place for the same value.\n\npub trait Verifier<S: span::Span> {\n\n /// The error returned by the validator.\n\n type Error: Error;\n\n\n\n /// Validate a value internally.\n\n fn verify_value<V: ?Sized + Validate<Span = S>>(&self, value: &V) -> Result<(), Self::Error>;\n\n\n\n /// Validators that support hierarchical spans might require a starting parent span.\n\n fn verify_value_with_span<V: ?Sized + Validate<Span = S>>(\n\n &self,\n\n value: &V,\n\n _span: Option<V::Span>,\n\n ) -> Result<(), Self::Error> {\n\n self.verify_value(value)\n\n }\n\n}\n\n\n", "file_path": "verify/src/lib.rs", "rank": 6, "score": 104371.06507609141 }, { "content": "/// Type returned by [validate_seq](Validator::validate_seq).\n\npub trait ValidateSeq<S: span::Span> {\n\n /// The error returned by the validator.\n\n type Error: std::error::Error;\n\n\n\n /// Set the span for the current value that is being validated.\n\n ///\n\n /// In some cases this is needed to ensure that the validator returns\n\n /// the correct span in its errors.\n\n fn with_span(&mut self, span: Option<S>) -> &mut Self;\n\n\n\n /// Validate an element in the sequence.\n\n fn validate_element<V>(&mut self, value: &V) -> Result<(), Self::Error>\n\n where\n\n V: ?Sized + Validate<Span = S> + core::hash::Hash;\n\n\n\n /// End the sequence.\n\n fn end(self) -> Result<(), Self::Error>;\n\n}\n\n\n", "file_path": "verify/src/lib.rs", "rank": 7, "score": 101362.31775034098 }, { "content": "/// Type returned by [validate_map](Validator::validate_map).\n\npub trait ValidateMap<S: span::Span> {\n\n /// The error returned by the validator.\n\n type Error: std::error::Error;\n\n\n\n /// Set the span for the current value that is being validated.\n\n ///\n\n /// In some cases this is needed to ensure that the validator returns\n\n /// the correct span in its errors.\n\n fn with_span(&mut self, span: Option<S>) -> &mut Self;\n\n\n\n /// Validate a key in the map.\n\n fn validate_key<V>(&mut self, key: &V) -> Result<(), Self::Error>\n\n where\n\n V: ?Sized + Validate<Span = S>;\n\n\n\n /// Validate a key in the map.\n\n ///\n\n /// This method guarantees that the key is a string\n\n /// or has a string representation.\n\n fn validate_string_key<V>(&mut self, key: &V) -> Result<(), Self::Error>\n", "file_path": "verify/src/lib.rs", "rank": 8, "score": 101362.31775034098 }, { "content": "/// Convenience trait for interacting with errors.\n\npub trait ErrorExt: Sized {\n\n /// Combine two error-like types. It is useful for\n\n /// spans wrapped in [Options](Option).\n\n fn combine(&mut self, span: Self);\n\n}\n\n\n\nimpl<T: Error> ErrorExt for T {\n\n fn combine(&mut self, span: Self) {\n\n *self += span;\n\n }\n\n}\n\n\n\nimpl<T: Error> ErrorExt for Option<T> {\n\n fn combine(&mut self, span: Self) {\n\n match span {\n\n Some(new_span) => match self {\n\n Some(s) => *s += new_span,\n\n None => *self = Some(new_span),\n\n },\n\n None => {\n\n *self = None;\n\n }\n\n }\n\n }\n\n}\n\n\n", "file_path": "verify/src/lib.rs", "rank": 9, "score": 91630.24750465188 }, { "content": "/// This trait is implemented by types that can validate themselves.\n\npub trait Verify {\n\n /// The error returned by the validator.\n\n type Error: Error;\n\n\n\n /// Validate self internally.\n\n fn verify(&self) -> Result<(), Self::Error>;\n\n}\n\n\n", "file_path": "verify/src/lib.rs", "rank": 10, "score": 76836.64608335297 }, { "content": "fn local_definition(path: &str) -> Option<&str> {\n\n if !path.starts_with(\"#/definitions/\") {\n\n return None;\n\n }\n\n\n\n Some(path.trim_start_matches(\"#/definitions/\"))\n\n}\n", "file_path": "verify/src/impls/schemars/verify.rs", "rank": 11, "score": 73220.72334241505 }, { "content": "fn local_definition(path: &str) -> Option<&str> {\n\n if !path.starts_with(\"#/definitions/\") {\n\n return None;\n\n }\n\n\n\n Some(path.trim_start_matches(\"#/definitions/\"))\n\n}\n", "file_path": "verify/src/impls/schemars/schema.rs", "rank": 12, "score": 73220.72334241505 }, { "content": "/// The errors returned by validators must implement this trait.\n\n///\n\n/// The [AddAssign](core::ops::AddAssign) bound is required in order to support\n\n/// validators that return multiple errors.\n\npub trait Error: Sized + std::error::Error + core::ops::AddAssign {\n\n /// Values that are being validated can report errors that\n\n /// are not related to the validators.\n\n fn custom<T: core::fmt::Display>(error: T) -> Self;\n\n}\n\n\n", "file_path": "verify/src/lib.rs", "rank": 13, "score": 69854.45949052605 }, { "content": "#[test]\n\nfn test_self_verify() {\n\n let schema_value = json! {\n\n {\n\n \"$schema\": \"http://json-schema.org/draft-07/schema#\",\n\n \"type\": \"object\",\n\n \"properties\": {\n\n \"invalid_string\": {\n\n \"type\": \"string\",\n\n \"pattern\": \"[[[[\\\\\"\n\n },\n\n \"missing_local\": {\n\n \"$ref\": \"#/definitions/Missing\"\n\n },\n\n \"external_ref\": {\n\n \"$ref\": \"http://example.com/schema.json#/definitions/Something\"\n\n }\n\n },\n\n }\n\n };\n\n\n", "file_path": "verify/tests/schemars.rs", "rank": 14, "score": 66424.10207026113 }, { "content": "fn verify_schema(\n\n schema: &Schema,\n\n definitions: &Map<String, Schema>,\n\n span: Keys,\n\n) -> Result<(), Errors<Keys>> {\n\n match schema {\n\n Schema::Bool(_) => Ok(()),\n\n Schema::Object(o) => verify_schema_object(o, definitions, span),\n\n }\n\n}\n\n\n", "file_path": "verify/src/impls/schemars/verify.rs", "rank": 15, "score": 61731.547408370294 }, { "content": "fn verify_schema_object(\n\n schema: &SchemaObject,\n\n definitions: &Map<String, Schema>,\n\n span: Keys,\n\n) -> Result<(), Errors<Keys>> {\n\n let mut errors = Errors::new();\n\n\n\n if let Some(r) = &schema.reference {\n\n match local_definition(r) {\n\n Some(s) => {\n\n if definitions.get(s).is_none() {\n\n errors.0.push(Error::new(\n\n None,\n\n Some(span.clone()),\n\n ErrorValue::InvalidSchema(InvalidSchema::MissingDefinition(s.to_string())),\n\n ));\n\n return Err(errors);\n\n }\n\n }\n\n None => {\n", "file_path": "verify/src/impls/schemars/verify.rs", "rank": 16, "score": 59630.20653934122 }, { "content": "/// A validator that validates a given schema.\n\n///\n\n/// This is not exposed directly because a value must be validated\n\n/// against multiple schemas in some cases. So the `Schema::verify` methods\n\n/// must be used instead, it will validate the value against subschemas.\n\nstruct SchemaValidator<'a, S: Span> {\n\n schema: SchemaRef<'a>,\n\n defs: &'a Map<String, Schema>,\n\n\n\n // If a schema was not found for an external tag,\n\n // everything should be allowed.\n\n tagged_allow: bool,\n\n\n\n parent_span: Option<S>,\n\n span: Option<S>,\n\n\n\n // to avoid some unnecessary clones\n\n combined_span: Option<S>,\n\n\n\n // Array tracking\n\n arr_item_count: usize,\n\n // For uniqueness checks\n\n arr_hashes: HashMap<u64, Option<S>>,\n\n arr_contains: Option<&'a Schema>,\n\n\n", "file_path": "verify/src/impls/schemars/schema.rs", "rank": 17, "score": 50183.49043480086 }, { "content": "#[proc_macro_error]\n\n#[proc_macro_derive(Verify, attributes(verify))]\n\npub fn derive_verify(input: proc_macro::TokenStream) -> proc_macro::TokenStream {\n\n let input = parse_macro_input!(input as syn::DeriveInput);\n\n\n\n let mut options = VerifyOptions::default();\n\n\n\n for a in &input.attrs {\n\n if a.path.is_ident(\"verify\") {\n\n let tokens = a.tokens.clone().into();\n\n options.merge(parse_macro_input!(tokens as VerifyOptions));\n\n }\n\n }\n\n\n\n match &input.data {\n\n Data::Struct(_) => Verify::new(input, options).derive().into(),\n\n Data::Enum(_) => Verify::new(input, options).derive().into(),\n\n Data::Union(u) => {\n\n abort!(u.union_token, \"unions are not supported by Verify\");\n\n }\n\n }\n\n}\n\n\n", "file_path": "verify-macros/src/lib.rs", "rank": 18, "score": 44649.682035874604 }, { "content": "#[test]\n\nfn test_verify() {\n\n let schema_value = json! {\n\n {\n\n \"$schema\": \"http://json-schema.org/draft-07/schema#\",\n\n \"title\": \"SomeStruct\",\n\n \"type\": \"object\",\n\n \"required\": [\n\n \"some_inner\",\n\n \"some_int\"\n\n ],\n\n \"additionalProperties\": false,\n\n \"properties\": {\n\n \"some_str\": {\n\n \"type\": \"string\"\n\n },\n\n \"some_inner\": {\n\n \"type\": \"object\",\n\n \"required\": [\n\n \"inner_values\",\n\n \"inner_value\"\n", "file_path": "verify/tests/schemars.rs", "rank": 19, "score": 42128.6396170811 }, { "content": "#[test]\n\nfn test_derive() {\n\n let some_struct = SomeStruct::default();\n\n assert!(some_struct.verify().is_ok());\n\n\n\n let some_struct_explicit = SomeStructExplicit::default();\n\n assert!(some_struct_explicit.verify().is_ok());\n\n}\n\n\n\n\n", "file_path": "verify/tests/schemars.rs", "rank": 20, "score": 42128.6396170811 }, { "content": "fn main() {\n\n let schema_value = json! {\n\n {\n\n \"$schema\": \"http://json-schema.org/draft-07/schema#\",\n\n \"title\": \"SomeStruct\",\n\n \"type\": \"object\",\n\n \"required\": [\n\n \"some_inner\",\n\n \"some_int\"\n\n ],\n\n \"additionalProperties\": false,\n\n \"properties\": {\n\n \"some_inner\": {\n\n \"type\": \"object\",\n\n \"required\": [\n\n \"inner_values\",\n\n \"inner_value\"\n\n ],\n\n \"properties\": {\n\n \"inner_values\": {\n", "file_path": "verify/examples/schemars_json.rs", "rank": 21, "score": 42128.6396170811 }, { "content": "#[test]\n\nfn test_verify() {\n\n let some_struct = SomeStruct::default();\n\n assert!(some_struct.verify().is_ok());\n\n\n\n let some_struct_explicit = SomeStructExplicit::default();\n\n assert!(some_struct_explicit.verify().is_ok());\n\n}\n", "file_path": "verify/tests/schemars_derive.rs", "rank": 22, "score": 40794.29039854626 }, { "content": "struct SpannedInner<'k, SP: Spans, V: Validator<SP::Span>> {\n\n spans: SP,\n\n span: Option<SP::Span>,\n\n\n\n validator: Option<V>,\n\n validator_seq: Option<V::ValidateSeq>,\n\n validator_map: Option<V::ValidateMap>,\n\n\n\n error: &'k mut Option<V::Error>,\n\n}\n\n\n\nimpl<'k, SP: Spans, V: Validator<SP::Span>> SpannedInner<'k, SP, V> {\n\n fn use_span(&mut self, new_span: NewSpan<SP::Span>) {\n\n match new_span {\n\n NewSpan::Add(span) => {\n\n self.span = span;\n\n }\n\n NewSpan::Reset(span) => {\n\n if let Some(v) = self.validator.take() {\n\n self.validator = Some(v.with_span(None));\n", "file_path": "verify/src/serde.rs", "rank": 23, "score": 39725.87463695469 }, { "content": "/// Implementations for [Schemars](https://docs.rs/schemars) Schema types.\n\n#[cfg(feature = \"schemars\")]\n\n#[cfg_attr(feature = \"docs\", doc(cfg(feature = \"schemars\")))]\n\npub mod schemars;\n", "file_path": "verify/src/impls.rs", "rank": 29, "score": 27334.616125721324 }, { "content": "#[derive(Default)]\n\nstruct VerifyOptions {\n\n verifier: Option<Ident>,\n\n verifier_name: Option<(Ident, TokenStream)>,\n\n verifier_create: Option<(Ident, TokenStream)>,\n\n verifier_error: Option<(Ident, TokenStream)>,\n\n\n\n is_serde: Option<Ident>,\n\n serde_spans: Option<(Ident, TokenStream)>,\n\n\n\n is_schemars: Option<Ident>,\n\n}\n\n\n\nimpl VerifyOptions {\n\n fn merge(&mut self, other: VerifyOptions) {\n\n if let Some(v) = other.verifier {\n\n if let Some(existing_v) = &self.verifier {\n\n emit_error!(existing_v, \"{} defined here\", existing_v);\n\n abort!(v, r#\"duplicate keys \"{}\"\"#, v);\n\n }\n\n\n", "file_path": "verify-macros/src/lib.rs", "rank": 30, "score": 25589.78458026768 }, { "content": "}\n\n\n\nimpl<S: Span> Error<S> {\n\n pub(crate) fn new(meta: Option<Box<Metadata>>, span: Option<S>, value: ErrorValue<S>) -> Self {\n\n Self { meta, span, value }\n\n }\n\n}\n\n\n\nimpl<S: Span> core::fmt::Display for Error<S> {\n\n fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {\n\n let mut start_paren = false;\n\n\n\n if f.alternate() {\n\n if let Some(span) = &self.span {\n\n write!(f, \"({:?}\", span)?;\n\n start_paren = true;\n\n }\n\n\n\n if let Some(meta) = &self.meta {\n\n if let Some(title) = &meta.title {\n", "file_path": "verify/src/impls/schemars/errors.rs", "rank": 31, "score": 24485.227033604257 }, { "content": " pub fn len(&self) -> usize {\n\n self.0.len()\n\n }\n\n\n\n pub fn iter(&self) -> impl Iterator<Item = &Error<S>> {\n\n self.0.iter()\n\n }\n\n\n\n pub(super) fn new() -> Self {\n\n Errors(ErrorsInner::new())\n\n }\n\n\n\n pub(super) fn one(error: Error<S>) -> Self {\n\n let mut v = ErrorsInner::new();\n\n v.push(error);\n\n Errors(v)\n\n }\n\n}\n\n\n\nimpl<S: Span> IntoIterator for Errors<S> {\n", "file_path": "verify/src/impls/schemars/errors.rs", "rank": 32, "score": 24484.621452345655 }, { "content": " self.combine_spans();\n\n\n\n self\n\n }\n\n\n\n fn with_parent_span(mut self, span: Option<S>) -> Self {\n\n self.parent_span = span;\n\n self.combine_spans();\n\n\n\n self\n\n }\n\n\n\n fn combine_spans(&mut self) {\n\n self.combined_span = self.parent_span.clone();\n\n if self.span.is_some() {\n\n self.combined_span.combine(self.span.clone());\n\n }\n\n }\n\n}\n\n\n", "file_path": "verify/src/impls/schemars/schema.rs", "rank": 33, "score": 24482.712452062628 }, { "content": "//! Error definitions used during Schema-related validation.\n\n\n\nuse crate::span::Span;\n\nuse schemars_crate::schema::{InstanceType, Metadata, SingleOrVec};\n\nuse std::ops::AddAssign;\n\n\n\n/// A validation error.\n\n///\n\n/// It contains an optional span of the invalid value and optional information about the schema that caused the error.\n\n#[derive(Debug, Clone, PartialEq)]\n\npub struct Error<S: Span> {\n\n /// Information about the schema that caused the validation\n\n /// error.\n\n pub meta: Option<Box<Metadata>>,\n\n\n\n /// The span of the invalid value.\n\n pub span: Option<S>,\n\n\n\n /// The actual error details.\n\n pub value: ErrorValue<S>,\n", "file_path": "verify/src/impls/schemars/errors.rs", "rank": 34, "score": 24482.314002641033 }, { "content": "impl<'a, S: Span> Validator<S> for SchemaValidator<'a, S> {\n\n type Error = Errors<S>;\n\n\n\n type ValidateSeq = Self;\n\n type ValidateMap = Self;\n\n\n\n fn with_span(mut self, span: Option<S>) -> Self {\n\n match span {\n\n Some(s) => {\n\n self.span = Some(s);\n\n }\n\n None => {\n\n self.parent_span = None;\n\n self.span = None;\n\n }\n\n }\n\n self.combine_spans();\n\n\n\n self\n\n }\n", "file_path": "verify/src/impls/schemars/schema.rs", "rank": 35, "score": 24481.42831069829 }, { "content": " Err(errors)\n\n } else {\n\n Ok(())\n\n }\n\n }\n\n}\n\n\n\nimpl<'a, S: Span> ValidateMap<S> for SchemaValidator<'a, S> {\n\n type Error = Errors<S>;\n\n\n\n fn with_span(&mut self, span: Option<S>) -> &mut Self {\n\n match span {\n\n Some(s) => {\n\n self.span = Some(s);\n\n }\n\n None => {\n\n self.parent_span = None;\n\n self.span = None;\n\n }\n\n }\n", "file_path": "verify/src/impls/schemars/schema.rs", "rank": 36, "score": 24481.299463713654 }, { "content": " }\n\n }\n\n if let Some(l) = len {\n\n self.arr_hashes.reserve(l);\n\n }\n\n\n\n self.parent_span = self.combined_span.clone();\n\n\n\n Ok(self)\n\n }\n\n\n\n fn validate_map(mut self, _len: Option<usize>) -> Result<Self::ValidateMap, Self::Error> {\n\n let s = not_bool_schema!(self, &self.schema, &self.combined_span);\n\n\n\n check_type!(s, &self.combined_span)?;\n\n\n\n if let Some(obj) = &s.object {\n\n self.obj_required = obj.required.clone();\n\n }\n\n\n", "file_path": "verify/src/impls/schemars/schema.rs", "rank": 37, "score": 24481.017063887128 }, { "content": " self.combine_spans();\n\n\n\n self\n\n }\n\n\n\n fn validate_key<T>(&mut self, key: &T) -> Result<(), Self::Error>\n\n where\n\n T: ?Sized + Validate<Span = S>,\n\n {\n\n if self.tagged_allow {\n\n return Ok(());\n\n }\n\n\n\n let meta = match &self.schema {\n\n SchemaRef::Bool(_) => None,\n\n SchemaRef::Object(o) => o.metadata.as_ref(),\n\n };\n\n\n\n Err(Errors::one(Error::new(\n\n meta.cloned(),\n", "file_path": "verify/src/impls/schemars/schema.rs", "rank": 38, "score": 24480.770866547486 }, { "content": "use crate::{span::Keys, Verify};\n\nuse schemars_crate::{\n\n schema::{RootSchema, Schema, SchemaObject},\n\n Map,\n\n};\n\n\n\nuse super::errors::{Error, ErrorValue, Errors, InvalidSchema};\n\n\n\nimpl Verify for RootSchema {\n\n type Error = Errors<Keys>;\n\n\n\n fn verify(&self) -> Result<(), Self::Error> {\n\n let mut errors = Errors::new();\n\n\n\n for (k, s) in &self.definitions {\n\n if let Err(err) = verify_schema(s, &self.definitions, Keys::new() + \"definitions\" + k) {\n\n errors += err;\n\n }\n\n }\n\n\n", "file_path": "verify/src/impls/schemars/verify.rs", "rank": 39, "score": 24480.731349055422 }, { "content": "}\n\n\n\nimpl<S: Span> std::error::Error for Errors<S> {}\n\nimpl<S: Span> crate::Error for Errors<S> {\n\n fn custom<T: core::fmt::Display>(error: T) -> Self {\n\n Self::one(Error::new(\n\n None,\n\n None,\n\n ErrorValue::Custom(error.to_string()),\n\n ))\n\n }\n\n}\n\n\n\nimpl<S: Span> AddAssign for Errors<S> {\n\n fn add_assign(&mut self, rhs: Self) {\n\n self.0.extend(rhs.0.into_iter());\n\n }\n\n}\n", "file_path": "verify/src/impls/schemars/errors.rs", "rank": 40, "score": 24480.40835960055 }, { "content": " fn verify_value<V: ?Sized + Validate<Span = S>>(&self, value: &V) -> Result<(), Self::Error> {\n\n self.verify_value_with_span(value, None)\n\n }\n\n\n\n fn verify_value_with_span<V: ?Sized + Validate<Span = S>>(\n\n &self,\n\n value: &V,\n\n span: Option<V::Span>,\n\n ) -> Result<(), Self::Error> {\n\n SchemaValidator::new(&self.definitions, (&self.schema).into())\n\n .with_parent_span(span)\n\n .validate_inner(value)\n\n }\n\n}\n\n\n\n/// This is technically not needed anymore,\n\n/// but should do no harm to leave it as is.\n", "file_path": "verify/src/impls/schemars/schema.rs", "rank": 41, "score": 24480.272342287386 }, { "content": " // Object tracking\n\n obj_required: Set<String>,\n\n obj_prop_count: usize,\n\n obj_last_key: Option<String>,\n\n obj_last_key_span: Option<S>,\n\n}\n\n\n\nimpl<'a, S: Span> SchemaValidator<'a, S> {\n\n fn new(defs: &'a Map<String, Schema>, schema: SchemaRef<'a>) -> Self {\n\n Self {\n\n schema,\n\n defs,\n\n parent_span: None,\n\n span: None,\n\n combined_span: None,\n\n tagged_allow: false,\n\n arr_item_count: 0,\n\n arr_hashes: HashMap::new(),\n\n arr_contains: None,\n\n obj_required: Set::new(),\n", "file_path": "verify/src/impls/schemars/schema.rs", "rank": 42, "score": 24480.172203889888 }, { "content": " }\n\n }\n\n\n\n if let Some(add_prop_schema) = &obj.additional_properties {\n\n self.schema = SchemaRef::from(&**add_prop_schema);\n\n return Ok(());\n\n }\n\n }\n\n\n\n self.tagged_allow = true;\n\n Ok(())\n\n }\n\n}\n\n\n\nimpl<'a, S: Span> ValidateSeq<S> for SchemaValidator<'a, S> {\n\n type Error = Errors<S>;\n\n\n\n fn with_span(&mut self, span: Option<S>) -> &mut Self {\n\n match span {\n\n Some(s) => {\n", "file_path": "verify/src/impls/schemars/schema.rs", "rank": 43, "score": 24480.072164725912 }, { "content": " for s in all_of {\n\n if let Err(e) = SchemaValidator::new(self.defs, s.into())\n\n .with_spans(self.parent_span.clone(), self.span.clone())\n\n .validate_inner(value)\n\n {\n\n errors.extend(e.0.into_iter());\n\n }\n\n }\n\n }\n\n\n\n if let Some(any_of) = &sub.any_of {\n\n let mut validated = Vec::with_capacity(any_of.len());\n\n let mut inner_errors: Vec<Errors<_>> = Vec::with_capacity(any_of.len());\n\n for s in any_of {\n\n match SchemaValidator::new(self.defs, s.into())\n\n .with_spans(self.parent_span.clone(), self.span.clone())\n\n .validate_inner(value)\n\n {\n\n Ok(_) => match s {\n\n Schema::Object(o) => {\n", "file_path": "verify/src/impls/schemars/schema.rs", "rank": 44, "score": 24479.77187398124 }, { "content": " },\n\n },\n\n ));\n\n }\n\n }\n\n\n\n return if errors.is_empty() {\n\n Ok(())\n\n } else {\n\n Err(Errors(errors))\n\n };\n\n }\n\n\n\n Ok(())\n\n }\n\n\n\n fn with_spans(mut self, parent: Option<S>, span: Option<S>) -> Self {\n\n self.parent_span = parent;\n\n self.span = span;\n\n\n", "file_path": "verify/src/impls/schemars/schema.rs", "rank": 45, "score": 24479.66842175488 }, { "content": " obj_prop_count: 0,\n\n obj_last_key: None,\n\n obj_last_key_span: None,\n\n }\n\n }\n\n\n\n fn validate_inner<V: ?Sized + Validate<Span = S>>(\n\n &mut self,\n\n value: &V,\n\n ) -> Result<(), Errors<S>> {\n\n let s = not_bool_schema!(&self.schema, &self.combined_span);\n\n\n\n let mut value_span = self.combined_span.clone();\n\n value_span.combine(value.span());\n\n\n\n if let Some(r) = &s.reference {\n\n match local_definition(r) {\n\n Some(local) => match self.defs.get(local) {\n\n Some(s) => {\n\n return SchemaValidator::new(self.defs, s.into())\n", "file_path": "verify/src/impls/schemars/schema.rs", "rank": 46, "score": 24479.053753143555 }, { "content": " .validate_inner(value)\n\n {\n\n errors.0.extend(e.0.into_iter());\n\n }\n\n }\n\n }\n\n }\n\n }\n\n\n\n if let Some(true) = arr.unique_items {\n\n let mut hasher = DefaultHasher::new();\n\n value.hash(&mut hasher);\n\n let h = hasher.finish();\n\n\n\n let existing = self.arr_hashes.insert(h, value_span.clone());\n\n\n\n if let Some(existing_val) = existing {\n\n errors.0.push(Error::new(\n\n s.metadata.clone(),\n\n value_span.clone(),\n", "file_path": "verify/src/impls/schemars/schema.rs", "rank": 47, "score": 24479.01437380429 }, { "content": " self.parent_span = self.combined_span.clone();\n\n\n\n Ok(self)\n\n }\n\n\n\n fn validate_tag<V>(&mut self, tag: &V) -> Result<(), Self::Error>\n\n where\n\n V: ?Sized + Validate<Span = S> + ToString,\n\n {\n\n let s = not_bool_schema!(&self.schema, &self.combined_span);\n\n\n\n check_type!(s, &self.combined_span)?;\n\n\n\n let key = tag.to_string();\n\n\n\n let tag_span = self.parent_span.combined(tag.span());\n\n\n\n // Look for the property that has the name of the tag,\n\n // and continue validation with that schema.\n\n if let Some(obj) = &s.object {\n", "file_path": "verify/src/impls/schemars/schema.rs", "rank": 48, "score": 24478.622089941386 }, { "content": " _ => {\n\n let mut errors = ErrorsInner::new();\n\n errors.push(Error::new(\n\n $schema.metadata.clone(),\n\n $span.clone(),\n\n ErrorValue::InvalidType {\n\n expected: s.clone(),\n\n actual: InstanceType::Object,\n\n },\n\n ));\n\n Err(Errors(errors))\n\n }\n\n },\n\n SingleOrVec::Vec(vec) => {\n\n if vec.iter().any(|i| *i == InstanceType::Object) {\n\n Ok(())\n\n } else {\n\n let mut errors = ErrorsInner::new();\n\n errors.push(Error::new(\n\n $schema.metadata.clone(),\n", "file_path": "verify/src/impls/schemars/macros.rs", "rank": 49, "score": 24478.592239958416 }, { "content": " }\n\n }\n\n\n\n if enum_contains {\n\n Ok(())\n\n } else {\n\n let mut errors = ErrorsInner::new();\n\n errors.push(Error::new(\n\n $schema.metadata.clone(),\n\n $span.clone(),\n\n ErrorValue::InvalidEnumValue {\n\n expected: enum_vals.clone(),\n\n },\n\n ));\n\n Err(Errors(errors))\n\n }\n\n } else {\n\n Ok(())\n\n }\n\n };\n", "file_path": "verify/src/impls/schemars/macros.rs", "rank": 50, "score": 24478.566351713594 }, { "content": "}\n\n\n\nmacro_rules! check_number {\n\n ($value:expr, $schema:expr, $span:expr) => {\n\n if let Some(n) = &$schema.number {\n\n let mut errors = ErrorsInner::new();\n\n\n\n let mut number_err = false;\n\n\n\n if let Some(m) = n.multiple_of {\n\n if m != 0f64 && $value as f64 % m != 0f64 {\n\n errors.push(Error::new(\n\n $schema.metadata.clone(),\n\n $span.clone(),\n\n ErrorValue::NotMultipleOf { multiple_of: m },\n\n ));\n\n number_err = true;\n\n }\n\n }\n\n\n", "file_path": "verify/src/impls/schemars/macros.rs", "rank": 51, "score": 24478.36339166639 }, { "content": " } else {\n\n Ok(())\n\n };\n\n };\n\n}\n\n\n\n// TODO format\n\nmacro_rules! check_string {\n\n ($value:expr, $schema:expr, $span:expr) => {\n\n if let Some(s) = &$schema.string {\n\n let mut errors = ErrorsInner::new();\n\n\n\n let mut string_err = false;\n\n\n\n if let Some(p) = &s.pattern {\n\n let re = regex::Regex::new(&*p).map_err(|error| {\n\n Errors::one(Error::new(\n\n $schema.metadata.clone(),\n\n $span.clone(),\n\n ErrorValue::InvalidSchema(InvalidSchema::InvalidPattern {\n", "file_path": "verify/src/impls/schemars/macros.rs", "rank": 52, "score": 24478.26074040461 }, { "content": "\n\n self.obj_required.remove(&key_string);\n\n self.obj_last_key = Some(key_string);\n\n self.obj_last_key_span = key.span();\n\n\n\n if let Some(obj) = &s.object {\n\n if let Some(name_schema) = &obj.property_names {\n\n if let Err(e) = SchemaValidator::new(&self.defs, (&**name_schema).into())\n\n .with_spans(self.parent_span.clone(), key_span)\n\n .validate_inner(key)\n\n {\n\n return Err(e);\n\n }\n\n }\n\n }\n\n\n\n Ok(())\n\n }\n\n\n\n fn validate_value<T>(&mut self, value: &T) -> Result<(), Self::Error>\n", "file_path": "verify/src/impls/schemars/schema.rs", "rank": 53, "score": 24478.16578861387 }, { "content": " self.span = Some(s);\n\n }\n\n None => {\n\n self.parent_span = None;\n\n self.span = None;\n\n }\n\n }\n\n self.combine_spans();\n\n\n\n self\n\n }\n\n\n\n fn validate_element<T>(&mut self, value: &T) -> Result<(), Self::Error>\n\n where\n\n T: ?Sized + Validate<Span = S> + Hash,\n\n {\n\n if self.tagged_allow {\n\n return Ok(());\n\n }\n\n\n", "file_path": "verify/src/impls/schemars/schema.rs", "rank": 54, "score": 24478.103785082232 }, { "content": " if let Some(v) = val.as_bool() {\n\n if v == $value {\n\n enum_contains = true;\n\n break;\n\n }\n\n }\n\n }\n\n\n\n if enum_contains {\n\n Ok(())\n\n } else {\n\n let mut errors = ErrorsInner::new();\n\n errors.push(Error::new(\n\n $schema.metadata.clone(),\n\n $span.clone(),\n\n ErrorValue::InvalidEnumValue {\n\n expected: enum_vals.clone(),\n\n },\n\n ));\n\n Err(Errors(errors))\n", "file_path": "verify/src/impls/schemars/macros.rs", "rank": 55, "score": 24478.03901526692 }, { "content": " Schema::Bool(_) => None,\n\n Schema::Object(o) => o.metadata.clone(),\n\n })\n\n .collect(),\n\n errors: inner_errors,\n\n },\n\n ));\n\n }\n\n }\n\n\n\n if let Some(one_of) = &sub.one_of {\n\n let mut validated = Vec::with_capacity(one_of.len());\n\n let mut inner_errors: Vec<Errors<_>> = Vec::with_capacity(one_of.len());\n\n for s in one_of {\n\n match SchemaValidator::new(self.defs, s.into())\n\n .with_spans(self.parent_span.clone(), self.span.clone())\n\n .validate_inner(value)\n\n {\n\n Ok(_) => match s {\n\n Schema::Object(o) => {\n", "file_path": "verify/src/impls/schemars/schema.rs", "rank": 56, "score": 24478.001172624357 }, { "content": " }\n\n }\n\n\n\n let mut errors = self.validate_subschemas(s, value).err();\n\n\n\n if s.instance_type.is_none() {\n\n return match errors {\n\n None => Ok(()),\n\n Some(e) => Err(e),\n\n };\n\n }\n\n\n\n if let Err(e) = value.validate(\n\n SchemaValidator::new(&self.defs, SchemaRef::from(*s))\n\n .with_spans(self.parent_span.clone(), value.span()),\n\n ) {\n\n match &mut errors {\n\n Some(errs) => {\n\n *errs += e;\n\n }\n", "file_path": "verify/src/impls/schemars/schema.rs", "rank": 57, "score": 24477.86852782554 }, { "content": "\n\n let s = not_bool_schema!(&self.schema, &self.combined_span);\n\n let mut errors = Errors::new();\n\n\n\n if let Some(c) = self.arr_contains {\n\n errors.0.push(Error::new(\n\n s.metadata.clone(),\n\n self.combined_span.clone(),\n\n ErrorValue::MustContain {\n\n schema: match c {\n\n Schema::Bool(_) => None,\n\n Schema::Object(o) => o.metadata.clone(),\n\n },\n\n },\n\n ));\n\n }\n\n\n\n if let Some(arr) = &s.array {\n\n if let Some(min) = arr.min_items {\n\n if self.arr_item_count < min as usize {\n", "file_path": "verify/src/impls/schemars/schema.rs", "rank": 58, "score": 24477.818688067757 }, { "content": " },\n\n ));\n\n }\n\n }\n\n\n\n if let (Some(sub_if), Some(sub_then)) = (&sub.if_schema, &sub.then_schema) {\n\n if SchemaValidator::new(self.defs, (&**sub_if).into())\n\n .with_spans(self.parent_span.clone(), self.span.clone())\n\n .validate_inner(value)\n\n .is_ok()\n\n {\n\n if let Err(e) = SchemaValidator::new(self.defs, (&**sub_then).into())\n\n .with_spans(self.parent_span.clone(), self.span.clone())\n\n .validate_inner(value)\n\n {\n\n errors.extend(e.0.into_iter());\n\n }\n\n } else if let Some(sub_else) = &sub.else_schema {\n\n if let Err(e) = SchemaValidator::new(self.defs, (&**sub_else).into())\n\n .with_spans(self.parent_span.clone(), self.span.clone())\n", "file_path": "verify/src/impls/schemars/schema.rs", "rank": 59, "score": 24477.723436940458 }, { "content": " self.arr_item_count += 1;\n\n\n\n let s = not_bool_schema!(&self.schema, &self.combined_span);\n\n\n\n let mut errors = Errors::new();\n\n\n\n let value_span = self.parent_span.combined(value.span());\n\n\n\n if let Some(arr) = &s.array {\n\n if let Some(c) = self.arr_contains {\n\n if SchemaValidator::new(&self.defs, c.into())\n\n .with_parent_span(self.parent_span.clone())\n\n .validate_inner(value)\n\n .is_ok()\n\n {\n\n self.arr_contains = None;\n\n }\n\n }\n\n\n\n if let Some(items) = &arr.items {\n", "file_path": "verify/src/impls/schemars/schema.rs", "rank": 60, "score": 24477.686991215945 }, { "content": " self.obj_last_key_span.take(),\n\n ErrorValue::UnknownProperty,\n\n )));\n\n } else {\n\n return Err(e);\n\n }\n\n }\n\n }\n\n }\n\n\n\n Ok(())\n\n }\n\n\n\n fn end(self) -> Result<(), Self::Error> {\n\n if self.tagged_allow {\n\n return Ok(());\n\n }\n\n\n\n let s = not_bool_schema!(&self.schema, &self.combined_span);\n\n let mut errors = Errors::new();\n", "file_path": "verify/src/impls/schemars/schema.rs", "rank": 61, "score": 24477.320642458857 }, { "content": " ));\n\n Err(Errors(errors))\n\n }\n\n },\n\n SingleOrVec::Vec(vec) => {\n\n if vec.iter().any(|i| *i == InstanceType::$actual_type) {\n\n Ok(())\n\n } else {\n\n let mut errors = ErrorsInner::new();\n\n errors.push(Error::new(\n\n $schema.metadata.clone(),\n\n $span.clone(),\n\n ErrorValue::InvalidType {\n\n expected: s.clone(),\n\n actual: InstanceType::$actual_type,\n\n },\n\n ));\n\n Err(Errors(errors))\n\n }\n\n }\n", "file_path": "verify/src/impls/schemars/macros.rs", "rank": 62, "score": 24477.20417764172 }, { "content": " .validate_inner(value)\n\n {\n\n errors.extend(e.0.into_iter());\n\n }\n\n }\n\n }\n\n\n\n if let Some(not) = &sub.not {\n\n if SchemaValidator::new(self.defs, (&**not).into())\n\n .with_spans(self.parent_span.clone(), self.span.clone())\n\n .validate_inner(value)\n\n .is_ok()\n\n {\n\n errors.push(Error::new(\n\n schema.metadata.clone(),\n\n value.span(),\n\n ErrorValue::ValidNot {\n\n matched: match &**not {\n\n Schema::Object(o) => o.metadata.clone(),\n\n _ => None,\n", "file_path": "verify/src/impls/schemars/schema.rs", "rank": 63, "score": 24476.982968114284 }, { "content": " SchemaRef::Object(o) => o,\n\n }\n\n };\n\n}\n\n\n\nmacro_rules! check_type {\n\n ($actual_type:ident, $schema:expr, $span:expr) => {\n\n match &$schema.instance_type {\n\n Some(s) => match s {\n\n SingleOrVec::Single(single) => match &**single {\n\n InstanceType::$actual_type => Ok(()),\n\n _ => {\n\n let mut errors = ErrorsInner::new();\n\n errors.push(Error::new(\n\n $schema.metadata.clone(),\n\n $span.clone(),\n\n ErrorValue::InvalidType {\n\n expected: s.clone(),\n\n actual: InstanceType::$actual_type,\n\n },\n", "file_path": "verify/src/impls/schemars/macros.rs", "rank": 64, "score": 24476.980272035536 }, { "content": " },\n\n None => {\n\n let mut errors = ErrorsInner::new();\n\n errors.push(Error::new(\n\n $schema.metadata.clone(),\n\n $span.clone(),\n\n ErrorValue::InvalidType {\n\n expected: SingleOrVec::Single(Box::new(InstanceType::Object)),\n\n actual: InstanceType::$actual_type,\n\n },\n\n ));\n\n Err(Errors(errors))\n\n }\n\n }\n\n };\n\n ($schema:expr, $span:expr) => {\n\n match &$schema.instance_type {\n\n Some(s) => match s {\n\n SingleOrVec::Single(single) => match &**single {\n\n InstanceType::Object => Ok(()),\n", "file_path": "verify/src/impls/schemars/macros.rs", "rank": 65, "score": 24476.962896436646 }, { "content": " .with_spans(self.parent_span.clone(), value.span())\n\n .validate_inner(value)\n\n }\n\n None => {\n\n return Err(Errors::one(Error::new(\n\n s.metadata.clone(),\n\n value_span.clone(),\n\n ErrorValue::InvalidSchema(InvalidSchema::MissingDefinition(\n\n local.to_string(),\n\n )),\n\n )));\n\n }\n\n },\n\n None => {\n\n return Err(Errors::one(Error::new(\n\n s.metadata.clone(),\n\n value_span.clone(),\n\n ErrorValue::InvalidSchema(InvalidSchema::ExternalReference(r.clone())),\n\n )));\n\n }\n", "file_path": "verify/src/impls/schemars/schema.rs", "rank": 66, "score": 24476.959703749453 }, { "content": " };\n\n (float, $value:expr, $schema:expr, $span:expr) => {\n\n if let Some(enum_vals) = &$schema.enum_values {\n\n let mut errors = ErrorsInner::new();\n\n\n\n let mut enum_contains = false;\n\n for val in enum_vals {\n\n if let Some(v) = val.as_f64() {\n\n if f64::abs(v - $value as f64) < core::f64::EPSILON {\n\n enum_contains = true;\n\n break;\n\n }\n\n }\n\n }\n\n\n\n if enum_contains {\n\n Ok(())\n\n } else {\n\n errors.push(Error::new(\n\n $schema.metadata.clone(),\n", "file_path": "verify/src/impls/schemars/macros.rs", "rank": 67, "score": 24476.77748147037 }, { "content": " Ok(())\n\n }\n\n\n\n fn validate_unit_variant(\n\n self,\n\n _name: &'static str,\n\n _variant_index: u32,\n\n variant: &'static str,\n\n ) -> Result<(), Self::Error> {\n\n self.validate_str(variant)\n\n }\n\n\n\n fn validate_seq(mut self, len: Option<usize>) -> Result<Self::ValidateSeq, Self::Error> {\n\n let s = not_bool_schema!(self, &self.schema, &self.combined_span);\n\n\n\n check_type!(Array, s, &self.combined_span)?;\n\n\n\n if let Some(arr) = &s.array {\n\n if let Some(s) = &arr.contains {\n\n self.arr_contains = Some(s);\n", "file_path": "verify/src/impls/schemars/schema.rs", "rank": 68, "score": 24476.68274440953 }, { "content": " return Err(e);\n\n }\n\n }\n\n }\n\n\n\n for (k, v) in obj.pattern_properties.iter() {\n\n let key_re = regex::Regex::new(k).map_err(|error| {\n\n Errors::one(Error::new(\n\n s.metadata.clone(),\n\n value.span(),\n\n ErrorValue::InvalidSchema(InvalidSchema::InvalidPattern {\n\n pattern: k.clone(),\n\n error,\n\n }),\n\n ))\n\n })?;\n\n\n\n if key_re.is_match(&key) {\n\n match SchemaValidator::new(&self.defs, v.into())\n\n .with_parent_span(self.parent_span.clone())\n", "file_path": "verify/src/impls/schemars/schema.rs", "rank": 69, "score": 24476.544218908122 }, { "content": " pattern: p.clone(),\n\n error,\n\n }),\n\n ))\n\n })?;\n\n\n\n if !re.is_match($value) {\n\n errors.push(Error::new(\n\n $schema.metadata.clone(),\n\n $span.clone(),\n\n ErrorValue::NoPatternMatch { pattern: p.clone() },\n\n ));\n\n string_err = true;\n\n }\n\n\n\n if let Some(max_length) = s.max_length {\n\n if $value.chars().count() > max_length as usize {\n\n errors.push(Error::new(\n\n $schema.metadata.clone(),\n\n $span.clone(),\n", "file_path": "verify/src/impls/schemars/macros.rs", "rank": 70, "score": 24476.427871253647 }, { "content": " match items {\n\n SingleOrVec::Single(single_schema) => {\n\n if let Err(e) = SchemaValidator::new(&self.defs, (&**single_schema).into())\n\n .with_parent_span(self.parent_span.clone())\n\n .validate_inner(value)\n\n {\n\n errors.0.extend(e.0.into_iter());\n\n }\n\n }\n\n SingleOrVec::Vec(schemas) => {\n\n if let Some(s) = schemas.get(self.arr_item_count - 1) {\n\n if let Err(e) = SchemaValidator::new(&self.defs, s.into())\n\n .with_parent_span(self.parent_span.clone())\n\n .validate_inner(value)\n\n {\n\n errors.0.extend(e.0.into_iter());\n\n }\n\n } else if let Some(s) = &arr.additional_items {\n\n if let Err(e) = SchemaValidator::new(&self.defs, (&**s).into())\n\n .with_parent_span(self.parent_span.clone())\n", "file_path": "verify/src/impls/schemars/schema.rs", "rank": 71, "score": 24476.422114920097 }, { "content": " where\n\n T: ?Sized + Validate<Span = S>,\n\n {\n\n if self.tagged_allow {\n\n return Ok(());\n\n }\n\n\n\n let s = not_bool_schema!(&self.schema, &self.combined_span);\n\n let key = self.obj_last_key.take().expect(\"no key before value\");\n\n\n\n if let Some(obj) = &s.object {\n\n if let Some(prop_schema) = obj.properties.get(&key) {\n\n match SchemaValidator::new(&self.defs, prop_schema.into())\n\n .with_parent_span(self.parent_span.clone())\n\n .validate_inner(value)\n\n {\n\n Ok(_) => {\n\n return Ok(());\n\n }\n\n Err(e) => {\n", "file_path": "verify/src/impls/schemars/schema.rs", "rank": 72, "score": 24476.33424007053 }, { "content": " key.span(),\n\n ErrorValue::UnsupportedValue(UnsupportedValue::KeyNotString),\n\n )))\n\n }\n\n\n\n fn validate_string_key<T>(&mut self, key: &T) -> Result<(), Self::Error>\n\n where\n\n T: ?Sized + Validate<Span = S> + ToString,\n\n {\n\n if self.tagged_allow {\n\n return Ok(());\n\n }\n\n\n\n self.obj_prop_count += 1;\n\n\n\n let s = not_bool_schema!(&self.schema, &self.combined_span);\n\n\n\n let key_span = self.parent_span.combined(key.span());\n\n\n\n let key_string = key.to_string();\n", "file_path": "verify/src/impls/schemars/schema.rs", "rank": 73, "score": 24476.31934628395 }, { "content": "//! This module contains macros for schema validation, as it is a very\n\n//! boilerplate-y procedure.\n\n//!\n\n//! Some of the macros below are repeated in every method for Validator.\n\n\n\nmacro_rules! not_bool_schema {\n\n ($schema:expr, $span:expr) => {\n\n not_bool_schema!((), $schema, $span)\n\n };\n\n ($ret_val:expr, $schema:expr, $span:expr) => {\n\n match &$schema {\n\n SchemaRef::Bool(allow_all) => {\n\n if *allow_all {\n\n return Ok($ret_val);\n\n } else {\n\n let mut errors = ErrorsInner::new();\n\n errors.push(Error::new(None, ($span).clone(), ErrorValue::Never));\n\n return Err(Errors(errors));\n\n }\n\n }\n", "file_path": "verify/src/impls/schemars/macros.rs", "rank": 74, "score": 24476.11425833037 }, { "content": " if let Some(min) = n.minimum {\n\n if ($value as f64) < min {\n\n errors.push(Error::new(\n\n $schema.metadata.clone(),\n\n $span.clone(),\n\n ErrorValue::LessThanExpected {\n\n min,\n\n exclusive: false,\n\n },\n\n ));\n\n number_err = true;\n\n }\n\n }\n\n\n\n if let Some(min) = n.exclusive_minimum {\n\n if ($value as f64) <= min {\n\n errors.push(Error::new(\n\n $schema.metadata.clone(),\n\n $span.clone(),\n\n ErrorValue::LessThanExpected {\n", "file_path": "verify/src/impls/schemars/macros.rs", "rank": 75, "score": 24476.07113330416 }, { "content": " errors.0.push(Error::new(\n\n s.metadata.clone(),\n\n self.combined_span.clone(),\n\n ErrorValue::NotEnoughItems { min: min as usize },\n\n ));\n\n }\n\n }\n\n\n\n if let Some(max) = arr.max_items {\n\n if self.arr_item_count > max as usize {\n\n errors.0.push(Error::new(\n\n s.metadata.clone(),\n\n self.combined_span.clone(),\n\n ErrorValue::TooManyItems { max: max as usize },\n\n ));\n\n }\n\n }\n\n }\n\n\n\n if !errors.0.is_empty() {\n", "file_path": "verify/src/impls/schemars/schema.rs", "rank": 76, "score": 24476.07113330416 }, { "content": " if let Some(o) = &schema.object {\n\n for (k, _) in &o.pattern_properties {\n\n if let Err(error) = regex::Regex::new(k) {\n\n errors.0.push(Error::new(\n\n None,\n\n Some(span.clone() + \"patternProperties\" + k),\n\n ErrorValue::InvalidSchema(InvalidSchema::InvalidPattern {\n\n pattern: k.clone(),\n\n error,\n\n }),\n\n ));\n\n }\n\n }\n\n\n\n for (k, s) in &o.properties {\n\n if let Err(err) = verify_schema(s, definitions, span.clone() + \"properties\" + k) {\n\n errors += err;\n\n }\n\n }\n\n\n", "file_path": "verify/src/impls/schemars/verify.rs", "rank": 77, "score": 24476.023437930347 }, { "content": "\n\n if let Some(obj) = &s.object {\n\n if let Some(max) = obj.max_properties {\n\n if self.obj_prop_count > max as usize {\n\n errors.0.push(Error::new(\n\n s.metadata.clone(),\n\n self.combined_span.clone(),\n\n ErrorValue::TooManyProperties { max: max as usize },\n\n ))\n\n }\n\n }\n\n\n\n if let Some(min) = obj.min_properties {\n\n if self.obj_prop_count < min as usize {\n\n errors.0.push(Error::new(\n\n s.metadata.clone(),\n\n self.combined_span.clone(),\n\n ErrorValue::NotEnoughProperties { min: min as usize },\n\n ))\n\n }\n", "file_path": "verify/src/impls/schemars/schema.rs", "rank": 78, "score": 24475.61943585383 }, { "content": " None => errors = Some(e),\n\n }\n\n }\n\n\n\n match errors {\n\n None => Ok(()),\n\n Some(e) => Err(e),\n\n }\n\n }\n\n\n\n /// Validate all the allOf anyOf, etc. schemas for a given value.\n\n fn validate_subschemas<V: ?Sized + Validate<Span = S>>(\n\n &self,\n\n schema: &SchemaObject,\n\n value: &V,\n\n ) -> Result<(), Errors<S>> {\n\n if let Some(sub) = &schema.subschemas {\n\n let mut errors = ErrorsInner::new();\n\n\n\n if let Some(all_of) = &sub.all_of {\n", "file_path": "verify/src/impls/schemars/schema.rs", "rank": 79, "score": 24475.60520729514 }, { "content": " break;\n\n }\n\n }\n\n }\n\n\n\n if enum_contains {\n\n Ok(())\n\n } else {\n\n errors.push(Error::new(\n\n $schema.metadata.clone(),\n\n $span.clone(),\n\n ErrorValue::InvalidEnumValue {\n\n expected: enum_vals.clone(),\n\n },\n\n ));\n\n Err(Errors(errors))\n\n }\n\n } else {\n\n Ok(())\n\n }\n", "file_path": "verify/src/impls/schemars/macros.rs", "rank": 80, "score": 24475.554602562497 }, { "content": " if let Some(s) = &o.additional_properties {\n\n if let Err(err) = verify_schema(s, definitions, span.clone() + \"additionalProperties\") {\n\n errors += err;\n\n }\n\n }\n\n }\n\n\n\n if let Some(st) = &schema.string {\n\n if let Some(p) = &st.pattern {\n\n if let Err(error) = regex::Regex::new(&p) {\n\n errors.0.push(Error::new(\n\n None,\n\n Some(span.clone() + \"pattern\"),\n\n ErrorValue::InvalidSchema(InvalidSchema::InvalidPattern {\n\n pattern: p.clone(),\n\n error,\n\n }),\n\n ));\n\n }\n\n }\n\n }\n\n\n\n if errors.is_empty() {\n\n Ok(())\n\n } else {\n\n Err(errors)\n\n }\n\n}\n\n\n", "file_path": "verify/src/impls/schemars/verify.rs", "rank": 81, "score": 24475.52898053299 }, { "content": " fn validate_some<T>(self, value: &T) -> Result<(), Self::Error>\n\n where\n\n T: ?Sized + Validate<Span = S>,\n\n {\n\n value.validate(self)\n\n }\n\n\n\n fn validate_unit(self) -> Result<(), Self::Error> {\n\n let s = not_bool_schema!(&self.schema, &self.combined_span);\n\n\n\n check_type!(Null, s, &self.combined_span)?;\n\n\n\n Ok(())\n\n }\n\n\n\n fn validate_unit_struct(self, _name: &'static str) -> Result<(), Self::Error> {\n\n let s = not_bool_schema!(&self.schema, &self.combined_span);\n\n\n\n check_type!(Null, s, &self.combined_span)?;\n\n\n", "file_path": "verify/src/impls/schemars/schema.rs", "rank": 82, "score": 24475.42769230316 }, { "content": " .validate_inner(value)\n\n {\n\n Ok(_) => {\n\n return Ok(());\n\n }\n\n Err(e) => {\n\n return Err(e);\n\n }\n\n }\n\n }\n\n }\n\n\n\n if let Some(add_prop_schema) = &obj.additional_properties {\n\n if let Err(e) = SchemaValidator::new(&self.defs, (&**add_prop_schema).into())\n\n .with_parent_span(self.parent_span.clone())\n\n .validate_inner(value)\n\n {\n\n if let ErrorValue::Never = &e.0.get(0).unwrap().value {\n\n return Err(Errors::one(Error::new(\n\n s.metadata.clone(),\n", "file_path": "verify/src/impls/schemars/schema.rs", "rank": 83, "score": 24475.4180667206 }, { "content": " errors.0.push(Error::new(\n\n None,\n\n Some(span.clone()),\n\n ErrorValue::InvalidSchema(InvalidSchema::ExternalReference(r.clone())),\n\n ));\n\n return Err(errors);\n\n }\n\n }\n\n }\n\n\n\n if let Some(subs) = &schema.subschemas {\n\n if let Some(all_ofs) = &subs.all_of {\n\n for (i, s) in all_ofs.iter().enumerate() {\n\n if let Err(err) = verify_schema(s, definitions, span.clone() + \"allOf\" + i) {\n\n errors += err;\n\n }\n\n }\n\n }\n\n\n\n if let Some(one_ofs) = &subs.one_of {\n", "file_path": "verify/src/impls/schemars/verify.rs", "rank": 84, "score": 24475.16367453049 }, { "content": "#[macro_use] mod macros;\n\nmod schema;\n\nmod verify;\n\n\n\npub mod errors;\n\n\n\npub use schema::*;\n\npub use errors::Errors;\n\n\n", "file_path": "verify/src/impls/schemars/mod.rs", "rank": 85, "score": 24475.062629359272 }, { "content": " $span.clone(),\n\n ErrorValue::InvalidEnumValue {\n\n expected: enum_vals.clone(),\n\n },\n\n ));\n\n Err(Errors(errors))\n\n }\n\n } else {\n\n Ok(())\n\n }\n\n };\n\n (str, $value:expr, $schema:expr, $span:expr) => {\n\n if let Some(enum_vals) = &$schema.enum_values {\n\n let mut enum_contains = false;\n\n for val in enum_vals {\n\n if let Some(v) = val.as_str() {\n\n if v == $value {\n\n enum_contains = true;\n\n break;\n\n }\n", "file_path": "verify/src/impls/schemars/macros.rs", "rank": 86, "score": 24474.963920848433 }, { "content": " $span.clone(),\n\n ErrorValue::InvalidType {\n\n expected: s.clone(),\n\n actual: InstanceType::Object,\n\n },\n\n ));\n\n Err(Errors(errors))\n\n }\n\n }\n\n },\n\n None => Ok(()),\n\n }\n\n };\n\n}\n\n\n\nmacro_rules! check_enum {\n\n (bool, $value:expr, $schema:expr, $span:expr) => {\n\n if let Some(enum_vals) = &$schema.enum_values {\n\n let mut enum_contains = false;\n\n for val in enum_vals {\n", "file_path": "verify/src/impls/schemars/macros.rs", "rank": 87, "score": 24474.890500011064 }, { "content": "//! Implementation of Verify, Verifier and Validator for schemas.\n\n\n\nuse crate::{\n\n span::{Span, SpanExt},\n\n Validate, ValidateMap, ValidateSeq, Validator, Verifier,\n\n};\n\nuse schemars_crate::{\n\n schema::{InstanceType, RootSchema, Schema, SchemaObject, SingleOrVec},\n\n Map, Set,\n\n};\n\nuse std::{\n\n collections::{hash_map::DefaultHasher, HashMap},\n\n hash::{Hash, Hasher},\n\n};\n\n\n\nuse super::errors::{Error, ErrorValue, Errors, ErrorsInner, InvalidSchema, UnsupportedValue};\n\n\n\nimpl<S: Span> Verifier<S> for RootSchema {\n\n type Error = Errors<S>;\n\n\n", "file_path": "verify/src/impls/schemars/schema.rs", "rank": 88, "score": 24474.87480148791 }, { "content": "\n\n /// Any error that does not originate from the validator.\n\n Custom(String),\n\n}\n\n\n\n/// Error that occurs when a value cannot be validated\n\n/// by a schema.\n\n#[derive(Debug, Clone, PartialEq)]\n\npub enum UnsupportedValue {\n\n /// Indicates that key of a map is not a string.\n\n KeyNotString,\n\n}\n\n\n\nimpl core::fmt::Display for UnsupportedValue {\n\n fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {\n\n match self {\n\n UnsupportedValue::KeyNotString => write!(f, \"map key must be a string\"),\n\n }\n\n }\n\n}\n", "file_path": "verify/src/impls/schemars/errors.rs", "rank": 89, "score": 24474.86516161358 }, { "content": " min,\n\n exclusive: true,\n\n },\n\n ));\n\n number_err = true;\n\n }\n\n }\n\n\n\n if let Some(max) = n.maximum {\n\n if ($value as f64) > max {\n\n errors.push(Error::new(\n\n $schema.metadata.clone(),\n\n $span.clone(),\n\n ErrorValue::MoreThanExpected {\n\n max,\n\n exclusive: false,\n\n },\n\n ));\n\n number_err = true;\n\n }\n", "file_path": "verify/src/impls/schemars/macros.rs", "rank": 90, "score": 24474.689128725717 }, { "content": " }\n\n\n\n if let Some(max) = n.exclusive_maximum {\n\n if ($value as f64) >= max {\n\n errors.push(Error::new(\n\n $schema.metadata.clone(),\n\n $span.clone(),\n\n ErrorValue::MoreThanExpected {\n\n max,\n\n exclusive: true,\n\n },\n\n ));\n\n number_err = true;\n\n }\n\n }\n\n if !number_err {\n\n Ok(())\n\n } else {\n\n Err(Errors(errors))\n\n }\n", "file_path": "verify/src/impls/schemars/macros.rs", "rank": 91, "score": 24474.604029083122 }, { "content": " ErrorValue::NotUnique {\n\n first: existing_val,\n\n duplicate: value_span.clone(),\n\n },\n\n ));\n\n }\n\n }\n\n }\n\n\n\n if !errors.0.is_empty() {\n\n Err(errors)\n\n } else {\n\n Ok(())\n\n }\n\n }\n\n\n\n fn end(self) -> Result<(), Self::Error> {\n\n if self.tagged_allow {\n\n return Ok(());\n\n }\n", "file_path": "verify/src/impls/schemars/schema.rs", "rank": 92, "score": 24474.58710212891 }, { "content": " type Item = <ErrorsInner<S> as IntoIterator>::Item;\n\n\n\n #[cfg(feature = \"smallvec\")]\n\n type IntoIter = smallvec_crate::IntoIter<SmallVecArray<S>>;\n\n\n\n #[cfg(not(feature = \"smallvec\"))]\n\n type IntoIter = std::vec::IntoIter<Error<S>>;\n\n\n\n fn into_iter(self) -> Self::IntoIter {\n\n self.0.into_iter()\n\n }\n\n}\n\n\n\nimpl<S: Span> core::fmt::Display for Errors<S> {\n\n fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {\n\n for e in &self.0 {\n\n writeln!(f, \"{}\", e)?;\n\n }\n\n Ok(())\n\n }\n", "file_path": "verify/src/impls/schemars/errors.rs", "rank": 93, "score": 24474.49853635101 }, { "content": " if let Some(prop_schema) = obj.properties.get(&key) {\n\n self.schema = SchemaRef::from(prop_schema);\n\n return Ok(());\n\n }\n\n\n\n for (k, v) in obj.pattern_properties.iter() {\n\n let key_re = regex::Regex::new(k).map_err(|error| {\n\n Errors::one(Error::new(\n\n s.metadata.clone(),\n\n tag_span.clone(),\n\n ErrorValue::InvalidSchema(InvalidSchema::InvalidPattern {\n\n pattern: k.clone(),\n\n error,\n\n }),\n\n ))\n\n })?;\n\n\n\n if key_re.is_match(&key) {\n\n self.schema = SchemaRef::from(v);\n\n return Ok(());\n", "file_path": "verify/src/impls/schemars/schema.rs", "rank": 94, "score": 24474.464114222716 }, { "content": " validated.push(o.metadata.clone());\n\n }\n\n _ => {\n\n validated.push(None);\n\n }\n\n },\n\n Err(e) => {\n\n inner_errors.push(e);\n\n }\n\n }\n\n }\n\n if validated.is_empty() {\n\n errors.push(Error::new(\n\n schema.metadata.clone(),\n\n value.span(),\n\n ErrorValue::NoneValid {\n\n exclusive: false,\n\n schemas: any_of\n\n .iter()\n\n .map(|s| match s {\n", "file_path": "verify/src/impls/schemars/schema.rs", "rank": 95, "score": 24474.43916347138 }, { "content": " }\n\n }\n\n\n\n for p in self.obj_required {\n\n errors.0.push(Error::new(\n\n s.metadata.clone(),\n\n self.combined_span.clone(),\n\n ErrorValue::RequiredProperty { name: p },\n\n ))\n\n }\n\n\n\n if !errors.0.is_empty() {\n\n Err(errors)\n\n } else {\n\n Ok(())\n\n }\n\n }\n\n\n\n fn string_key_required(&self) -> bool {\n\n if self.tagged_allow {\n\n // It is accepted either way.\n\n false\n\n } else {\n\n true\n\n }\n\n }\n\n}\n\n\n", "file_path": "verify/src/impls/schemars/schema.rs", "rank": 96, "score": 24474.43916347138 }, { "content": " validated.push(o.metadata.clone());\n\n }\n\n _ => {\n\n validated.push(None);\n\n }\n\n },\n\n Err(e) => {\n\n inner_errors.push(e);\n\n }\n\n }\n\n }\n\n if validated.is_empty() {\n\n errors.push(Error::new(\n\n schema.metadata.clone(),\n\n value.span(),\n\n ErrorValue::NoneValid {\n\n exclusive: true,\n\n schemas: one_of\n\n .iter()\n\n .map(|s| match s {\n", "file_path": "verify/src/impls/schemars/schema.rs", "rank": 97, "score": 24474.359284077967 }, { "content": " Schema::Bool(_) => None,\n\n Schema::Object(o) => o.metadata.clone(),\n\n })\n\n .collect(),\n\n errors: inner_errors,\n\n },\n\n ));\n\n } else if validated.len() > 1 {\n\n errors.push(Error::new(\n\n schema.metadata.clone(),\n\n value.span(),\n\n ErrorValue::MoreThanOneValid {\n\n schemas: one_of\n\n .iter()\n\n .map(|s| match s {\n\n Schema::Bool(_) => None,\n\n Schema::Object(o) => o.metadata.clone(),\n\n })\n\n .collect(),\n\n matched: validated,\n", "file_path": "verify/src/impls/schemars/schema.rs", "rank": 98, "score": 24474.25165041638 }, { "content": " }\n\n } else {\n\n Ok(())\n\n }\n\n };\n\n (int, $value:expr, $schema:expr, $span:expr) => {\n\n if let Some(enum_vals) = &$schema.enum_values {\n\n let mut errors = ErrorsInner::new();\n\n\n\n let mut enum_contains = false;\n\n for val in enum_vals {\n\n if let Some(v) = val.as_i64() {\n\n if v == $value as i64 {\n\n enum_contains = true;\n\n break;\n\n }\n\n }\n\n if let Some(v) = val.as_u64() {\n\n if v == $value as u64 {\n\n enum_contains = true;\n", "file_path": "verify/src/impls/schemars/macros.rs", "rank": 99, "score": 24474.145181672022 } ]
Rust
plonky2/src/gates/interpolation.rs
mfaulk/plonky2
2cedd1b02a718d19115560647ba1f741eab83260
use std::marker::PhantomData; use std::ops::Range; use plonky2_field::extension_field::algebra::PolynomialCoeffsAlgebra; use plonky2_field::extension_field::{Extendable, FieldExtension}; use plonky2_field::interpolation::interpolant; use plonky2_field::polynomial::PolynomialCoeffs; use crate::gadgets::interpolation::InterpolationGate; use crate::gadgets::polynomial::PolynomialCoeffsExtAlgebraTarget; use crate::gates::gate::Gate; use crate::gates::util::StridedConstraintConsumer; use crate::hash::hash_types::RichField; use crate::iop::ext_target::ExtensionTarget; use crate::iop::generator::{GeneratedValues, SimpleGenerator, WitnessGenerator}; use crate::iop::target::Target; use crate::iop::wire::Wire; use crate::iop::witness::{PartitionWitness, Witness}; use crate::plonk::circuit_builder::CircuitBuilder; use crate::plonk::vars::{EvaluationTargets, EvaluationVars, EvaluationVarsBase}; #[derive(Copy, Clone, Debug)] pub(crate) struct HighDegreeInterpolationGate<F: RichField + Extendable<D>, const D: usize> { pub subgroup_bits: usize, _phantom: PhantomData<F>, } impl<F: RichField + Extendable<D>, const D: usize> InterpolationGate<F, D> for HighDegreeInterpolationGate<F, D> { fn new(subgroup_bits: usize) -> Self { Self { subgroup_bits, _phantom: PhantomData, } } fn num_points(&self) -> usize { 1 << self.subgroup_bits } } impl<F: RichField + Extendable<D>, const D: usize> HighDegreeInterpolationGate<F, D> { fn end(&self) -> usize { self.start_coeffs() + self.num_points() * D } fn coset(&self, shift: F) -> impl Iterator<Item = F> { let g = F::primitive_root_of_unity(self.subgroup_bits); let size = 1 << self.subgroup_bits; g.powers().take(size).map(move |x| x * shift) } fn coset_ext(&self, shift: F::Extension) -> impl Iterator<Item = F::Extension> { let g = F::primitive_root_of_unity(self.subgroup_bits); let size = 1 << self.subgroup_bits; g.powers().take(size).map(move |x| shift.scalar_mul(x)) } fn coset_ext_recursive( &self, builder: &mut CircuitBuilder<F, D>, shift: ExtensionTarget<D>, ) -> Vec<ExtensionTarget<D>> { let g = F::primitive_root_of_unity(self.subgroup_bits); let size = 1 << self.subgroup_bits; g.powers() .take(size) .map(move |x| { let subgroup_element = builder.constant(x); builder.scalar_mul_ext(subgroup_element, shift) }) .collect() } } impl<F: RichField + Extendable<D>, const D: usize> Gate<F, D> for HighDegreeInterpolationGate<F, D> { fn id(&self) -> String { format!("{:?}<D={}>", self, D) } fn eval_unfiltered(&self, vars: EvaluationVars<F, D>) -> Vec<F::Extension> { let mut constraints = Vec::with_capacity(self.num_constraints()); let coeffs = (0..self.num_points()) .map(|i| vars.get_local_ext_algebra(self.wires_coeff(i))) .collect(); let interpolant = PolynomialCoeffsAlgebra::new(coeffs); let coset = self.coset_ext(vars.local_wires[self.wire_shift()]); for (i, point) in coset.into_iter().enumerate() { let value = vars.get_local_ext_algebra(self.wires_value(i)); let computed_value = interpolant.eval_base(point); constraints.extend(&(value - computed_value).to_basefield_array()); } let evaluation_point = vars.get_local_ext_algebra(self.wires_evaluation_point()); let evaluation_value = vars.get_local_ext_algebra(self.wires_evaluation_value()); let computed_evaluation_value = interpolant.eval(evaluation_point); constraints.extend(&(evaluation_value - computed_evaluation_value).to_basefield_array()); constraints } fn eval_unfiltered_base_one( &self, vars: EvaluationVarsBase<F>, mut yield_constr: StridedConstraintConsumer<F>, ) { let coeffs = (0..self.num_points()) .map(|i| vars.get_local_ext(self.wires_coeff(i))) .collect(); let interpolant = PolynomialCoeffs::new(coeffs); let coset = self.coset(vars.local_wires[self.wire_shift()]); for (i, point) in coset.into_iter().enumerate() { let value = vars.get_local_ext(self.wires_value(i)); let computed_value = interpolant.eval_base(point); yield_constr.many((value - computed_value).to_basefield_array()); } let evaluation_point = vars.get_local_ext(self.wires_evaluation_point()); let evaluation_value = vars.get_local_ext(self.wires_evaluation_value()); let computed_evaluation_value = interpolant.eval(evaluation_point); yield_constr.many((evaluation_value - computed_evaluation_value).to_basefield_array()); } fn eval_unfiltered_recursively( &self, builder: &mut CircuitBuilder<F, D>, vars: EvaluationTargets<D>, ) -> Vec<ExtensionTarget<D>> { let mut constraints = Vec::with_capacity(self.num_constraints()); let coeffs = (0..self.num_points()) .map(|i| vars.get_local_ext_algebra(self.wires_coeff(i))) .collect(); let interpolant = PolynomialCoeffsExtAlgebraTarget(coeffs); let coset = self.coset_ext_recursive(builder, vars.local_wires[self.wire_shift()]); for (i, point) in coset.into_iter().enumerate() { let value = vars.get_local_ext_algebra(self.wires_value(i)); let computed_value = interpolant.eval_scalar(builder, point); constraints.extend( &builder .sub_ext_algebra(value, computed_value) .to_ext_target_array(), ); } let evaluation_point = vars.get_local_ext_algebra(self.wires_evaluation_point()); let evaluation_value = vars.get_local_ext_algebra(self.wires_evaluation_value()); let computed_evaluation_value = interpolant.eval(builder, evaluation_point); constraints.extend( &builder .sub_ext_algebra(evaluation_value, computed_evaluation_value) .to_ext_target_array(), ); constraints } fn generators( &self, gate_index: usize, _local_constants: &[F], ) -> Vec<Box<dyn WitnessGenerator<F>>> { let gen = InterpolationGenerator::<F, D> { gate_index, gate: *self, _phantom: PhantomData, }; vec![Box::new(gen.adapter())] } fn num_wires(&self) -> usize { self.end() } fn num_constants(&self) -> usize { 0 } fn degree(&self) -> usize { self.num_points() } fn num_constraints(&self) -> usize { self.num_points() * D + D } } #[derive(Debug)] struct InterpolationGenerator<F: RichField + Extendable<D>, const D: usize> { gate_index: usize, gate: HighDegreeInterpolationGate<F, D>, _phantom: PhantomData<F>, } impl<F: RichField + Extendable<D>, const D: usize> SimpleGenerator<F> for InterpolationGenerator<F, D> { fn dependencies(&self) -> Vec<Target> { let local_target = |input| { Target::Wire(Wire { gate: self.gate_index, input, }) }; let local_targets = |inputs: Range<usize>| inputs.map(local_target); let num_points = self.gate.num_points(); let mut deps = Vec::with_capacity(1 + D + num_points * D); deps.push(local_target(self.gate.wire_shift())); deps.extend(local_targets(self.gate.wires_evaluation_point())); for i in 0..num_points { deps.extend(local_targets(self.gate.wires_value(i))); } deps } fn run_once(&self, witness: &PartitionWitness<F>, out_buffer: &mut GeneratedValues<F>) { let local_wire = |input| Wire { gate: self.gate_index, input, }; let get_local_wire = |input| witness.get_wire(local_wire(input)); let get_local_ext = |wire_range: Range<usize>| { debug_assert_eq!(wire_range.len(), D); let values = wire_range.map(get_local_wire).collect::<Vec<_>>(); let arr = values.try_into().unwrap(); F::Extension::from_basefield_array(arr) }; let points = self.gate.coset(get_local_wire(self.gate.wire_shift())); let points = points .into_iter() .enumerate() .map(|(i, point)| (point.into(), get_local_ext(self.gate.wires_value(i)))) .collect::<Vec<_>>(); let interpolant = interpolant(&points); for (i, &coeff) in interpolant.coeffs.iter().enumerate() { let wires = self.gate.wires_coeff(i).map(local_wire); out_buffer.set_ext_wires(wires, coeff); } let evaluation_point = get_local_ext(self.gate.wires_evaluation_point()); let evaluation_value = interpolant.eval(evaluation_point); let evaluation_value_wires = self.gate.wires_evaluation_value().map(local_wire); out_buffer.set_ext_wires(evaluation_value_wires, evaluation_value); } } #[cfg(test)] mod tests { use std::marker::PhantomData; use anyhow::Result; use plonky2_field::field_types::Field; use plonky2_field::goldilocks_field::GoldilocksField; use plonky2_field::polynomial::PolynomialCoeffs; use crate::gadgets::interpolation::InterpolationGate; use crate::gates::gate::Gate; use crate::gates::gate_testing::{test_eval_fns, test_low_degree}; use crate::gates::interpolation::HighDegreeInterpolationGate; use crate::hash::hash_types::HashOut; use crate::plonk::config::{GenericConfig, PoseidonGoldilocksConfig}; use crate::plonk::vars::EvaluationVars; #[test] fn wire_indices() { let gate = HighDegreeInterpolationGate::<GoldilocksField, 4> { subgroup_bits: 1, _phantom: PhantomData, }; assert_eq!(gate.wire_shift(), 0); assert_eq!(gate.wires_value(0), 1..5); assert_eq!(gate.wires_value(1), 5..9); assert_eq!(gate.wires_evaluation_point(), 9..13); assert_eq!(gate.wires_evaluation_value(), 13..17); assert_eq!(gate.wires_coeff(0), 17..21); assert_eq!(gate.wires_coeff(1), 21..25); assert_eq!(gate.num_wires(), 25); } #[test] fn low_degree() { test_low_degree::<GoldilocksField, _, 4>(HighDegreeInterpolationGate::new(2)); } #[test] fn eval_fns() -> Result<()> { const D: usize = 2; type C = PoseidonGoldilocksConfig; type F = <C as GenericConfig<D>>::F; test_eval_fns::<F, C, _, D>(HighDegreeInterpolationGate::new(2)) } #[test] fn test_gate_constraint() { const D: usize = 2; type C = PoseidonGoldilocksConfig; type F = <C as GenericConfig<D>>::F; type FF = <C as GenericConfig<D>>::FE; fn get_wires( gate: &HighDegreeInterpolationGate<F, D>, shift: F, coeffs: PolynomialCoeffs<FF>, eval_point: FF, ) -> Vec<FF> { let points = gate.coset(shift); let mut v = vec![shift]; for x in points { v.extend(coeffs.eval(x.into()).0); } v.extend(eval_point.0); v.extend(coeffs.eval(eval_point).0); for i in 0..coeffs.len() { v.extend(coeffs.coeffs[i].0); } v.iter().map(|&x| x.into()).collect() } let shift = F::rand(); let coeffs = PolynomialCoeffs::new(vec![FF::rand(), FF::rand()]); let eval_point = FF::rand(); let gate = HighDegreeInterpolationGate::<F, D>::new(1); let vars = EvaluationVars { local_constants: &[], local_wires: &get_wires(&gate, shift, coeffs, eval_point), public_inputs_hash: &HashOut::rand(), }; assert!( gate.eval_unfiltered(vars).iter().all(|x| x.is_zero()), "Gate constraints are not satisfied." ); } }
use std::marker::PhantomData; use std::ops::Range; use plonky2_field::extension_field::algebra::PolynomialCoeffsAlgebra; use plonky2_field::extension_field::{Extendable, FieldExtension}; use plonky2_field::interpolation::interpolant; use plonky2_field::polynomial::PolynomialCoeffs; use crate::gadgets::interpolation::InterpolationGate; use crate::gadgets::polynomial::PolynomialCoeffsExtAlgebraTarget; use crate::gates::gate::Gate; use crate::gates::util::StridedConstraintConsumer; use crate::hash::hash_types::RichField; use crate::iop::ext_target::ExtensionTarget; use crate::iop::generator::{GeneratedValues, SimpleGenerator, WitnessGenerator}; use crate::iop::target::Target; use crate::iop::wire::Wire; use crate::iop::witness::{PartitionWitness, Witness}; use crate::plonk::circuit_builder::CircuitBuilder; use crate::plonk::vars::{EvaluationTargets, EvaluationVars, EvaluationVarsBase}; #[derive(Copy, Clone, Debug)] pub(crate) struct HighDegreeInterpolationGate<F: RichField + Extendable<D>, const D: usize> { pub subgroup_bits: usize, _phantom: PhantomData<F>, } impl<F: RichField + Extendable<D>, const D: usize> InterpolationGate<F, D> for HighDegreeInterpolationGate<F, D> { fn new(subgroup_bits: usize) -> Self { Self { subgroup_bits, _phantom: PhantomData, } } fn num_points(&self) -> usize { 1 << self.subgroup_bits } } impl<F: RichField + Extendable<D>, const D: usize> HighDegreeInterpolationGate<F, D> { fn end(&self) -> usize { self.start_coeffs() + self.num_points() * D } fn coset(&self, shift: F) -> impl Iterator<Item = F> { let g = F::primitive_root_of_unity(self.subgroup_bits); let size = 1 << self.subgroup_bits; g.powers().take(size).map(move |x| x * shift) } fn coset_ext(&self, shift: F::Extension) -> impl Iterator<Item = F::Extension> { let g = F::primitive_root_of_unity(self.subgroup_bits); let size = 1 << self.subgroup_bits; g.powers().take(size).map(move |x| shift.scalar_mul(x)) } fn coset_ext_recursive( &self, builder: &mut CircuitBuilder<F, D>, shift: ExtensionTarget<D>, ) -> Vec<ExtensionTarget<D>> { let g = F::primitive_root_of_unity(self.subgroup_bits); let size = 1 << self.subgroup_bits; g.powers() .take(size) .map(move |x| { let subgroup_element = builder.constant(x); builder.scalar_mul_ext(subgroup_element, shift) }) .collect() } } impl<F: RichField + Extendable<D>, const D: usize> Gate<F, D> for HighDegreeInterpolationGate<F, D> { fn id(&self) -> String { format!("{:?}<D={}>", self, D) } fn eval_unfiltered(&self, vars: EvaluationVars<F, D>) -> Vec<F::Extension> {
fn eval_unfiltered_base_one( &self, vars: EvaluationVarsBase<F>, mut yield_constr: StridedConstraintConsumer<F>, ) { let coeffs = (0..self.num_points()) .map(|i| vars.get_local_ext(self.wires_coeff(i))) .collect(); let interpolant = PolynomialCoeffs::new(coeffs); let coset = self.coset(vars.local_wires[self.wire_shift()]); for (i, point) in coset.into_iter().enumerate() { let value = vars.get_local_ext(self.wires_value(i)); let computed_value = interpolant.eval_base(point); yield_constr.many((value - computed_value).to_basefield_array()); } let evaluation_point = vars.get_local_ext(self.wires_evaluation_point()); let evaluation_value = vars.get_local_ext(self.wires_evaluation_value()); let computed_evaluation_value = interpolant.eval(evaluation_point); yield_constr.many((evaluation_value - computed_evaluation_value).to_basefield_array()); } fn eval_unfiltered_recursively( &self, builder: &mut CircuitBuilder<F, D>, vars: EvaluationTargets<D>, ) -> Vec<ExtensionTarget<D>> { let mut constraints = Vec::with_capacity(self.num_constraints()); let coeffs = (0..self.num_points()) .map(|i| vars.get_local_ext_algebra(self.wires_coeff(i))) .collect(); let interpolant = PolynomialCoeffsExtAlgebraTarget(coeffs); let coset = self.coset_ext_recursive(builder, vars.local_wires[self.wire_shift()]); for (i, point) in coset.into_iter().enumerate() { let value = vars.get_local_ext_algebra(self.wires_value(i)); let computed_value = interpolant.eval_scalar(builder, point); constraints.extend( &builder .sub_ext_algebra(value, computed_value) .to_ext_target_array(), ); } let evaluation_point = vars.get_local_ext_algebra(self.wires_evaluation_point()); let evaluation_value = vars.get_local_ext_algebra(self.wires_evaluation_value()); let computed_evaluation_value = interpolant.eval(builder, evaluation_point); constraints.extend( &builder .sub_ext_algebra(evaluation_value, computed_evaluation_value) .to_ext_target_array(), ); constraints } fn generators( &self, gate_index: usize, _local_constants: &[F], ) -> Vec<Box<dyn WitnessGenerator<F>>> { let gen = InterpolationGenerator::<F, D> { gate_index, gate: *self, _phantom: PhantomData, }; vec![Box::new(gen.adapter())] } fn num_wires(&self) -> usize { self.end() } fn num_constants(&self) -> usize { 0 } fn degree(&self) -> usize { self.num_points() } fn num_constraints(&self) -> usize { self.num_points() * D + D } } #[derive(Debug)] struct InterpolationGenerator<F: RichField + Extendable<D>, const D: usize> { gate_index: usize, gate: HighDegreeInterpolationGate<F, D>, _phantom: PhantomData<F>, } impl<F: RichField + Extendable<D>, const D: usize> SimpleGenerator<F> for InterpolationGenerator<F, D> { fn dependencies(&self) -> Vec<Target> { let local_target = |input| { Target::Wire(Wire { gate: self.gate_index, input, }) }; let local_targets = |inputs: Range<usize>| inputs.map(local_target); let num_points = self.gate.num_points(); let mut deps = Vec::with_capacity(1 + D + num_points * D); deps.push(local_target(self.gate.wire_shift())); deps.extend(local_targets(self.gate.wires_evaluation_point())); for i in 0..num_points { deps.extend(local_targets(self.gate.wires_value(i))); } deps } fn run_once(&self, witness: &PartitionWitness<F>, out_buffer: &mut GeneratedValues<F>) { let local_wire = |input| Wire { gate: self.gate_index, input, }; let get_local_wire = |input| witness.get_wire(local_wire(input)); let get_local_ext = |wire_range: Range<usize>| { debug_assert_eq!(wire_range.len(), D); let values = wire_range.map(get_local_wire).collect::<Vec<_>>(); let arr = values.try_into().unwrap(); F::Extension::from_basefield_array(arr) }; let points = self.gate.coset(get_local_wire(self.gate.wire_shift())); let points = points .into_iter() .enumerate() .map(|(i, point)| (point.into(), get_local_ext(self.gate.wires_value(i)))) .collect::<Vec<_>>(); let interpolant = interpolant(&points); for (i, &coeff) in interpolant.coeffs.iter().enumerate() { let wires = self.gate.wires_coeff(i).map(local_wire); out_buffer.set_ext_wires(wires, coeff); } let evaluation_point = get_local_ext(self.gate.wires_evaluation_point()); let evaluation_value = interpolant.eval(evaluation_point); let evaluation_value_wires = self.gate.wires_evaluation_value().map(local_wire); out_buffer.set_ext_wires(evaluation_value_wires, evaluation_value); } } #[cfg(test)] mod tests { use std::marker::PhantomData; use anyhow::Result; use plonky2_field::field_types::Field; use plonky2_field::goldilocks_field::GoldilocksField; use plonky2_field::polynomial::PolynomialCoeffs; use crate::gadgets::interpolation::InterpolationGate; use crate::gates::gate::Gate; use crate::gates::gate_testing::{test_eval_fns, test_low_degree}; use crate::gates::interpolation::HighDegreeInterpolationGate; use crate::hash::hash_types::HashOut; use crate::plonk::config::{GenericConfig, PoseidonGoldilocksConfig}; use crate::plonk::vars::EvaluationVars; #[test] fn wire_indices() { let gate = HighDegreeInterpolationGate::<GoldilocksField, 4> { subgroup_bits: 1, _phantom: PhantomData, }; assert_eq!(gate.wire_shift(), 0); assert_eq!(gate.wires_value(0), 1..5); assert_eq!(gate.wires_value(1), 5..9); assert_eq!(gate.wires_evaluation_point(), 9..13); assert_eq!(gate.wires_evaluation_value(), 13..17); assert_eq!(gate.wires_coeff(0), 17..21); assert_eq!(gate.wires_coeff(1), 21..25); assert_eq!(gate.num_wires(), 25); } #[test] fn low_degree() { test_low_degree::<GoldilocksField, _, 4>(HighDegreeInterpolationGate::new(2)); } #[test] fn eval_fns() -> Result<()> { const D: usize = 2; type C = PoseidonGoldilocksConfig; type F = <C as GenericConfig<D>>::F; test_eval_fns::<F, C, _, D>(HighDegreeInterpolationGate::new(2)) } #[test] fn test_gate_constraint() { const D: usize = 2; type C = PoseidonGoldilocksConfig; type F = <C as GenericConfig<D>>::F; type FF = <C as GenericConfig<D>>::FE; fn get_wires( gate: &HighDegreeInterpolationGate<F, D>, shift: F, coeffs: PolynomialCoeffs<FF>, eval_point: FF, ) -> Vec<FF> { let points = gate.coset(shift); let mut v = vec![shift]; for x in points { v.extend(coeffs.eval(x.into()).0); } v.extend(eval_point.0); v.extend(coeffs.eval(eval_point).0); for i in 0..coeffs.len() { v.extend(coeffs.coeffs[i].0); } v.iter().map(|&x| x.into()).collect() } let shift = F::rand(); let coeffs = PolynomialCoeffs::new(vec![FF::rand(), FF::rand()]); let eval_point = FF::rand(); let gate = HighDegreeInterpolationGate::<F, D>::new(1); let vars = EvaluationVars { local_constants: &[], local_wires: &get_wires(&gate, shift, coeffs, eval_point), public_inputs_hash: &HashOut::rand(), }; assert!( gate.eval_unfiltered(vars).iter().all(|x| x.is_zero()), "Gate constraints are not satisfied." ); } }
let mut constraints = Vec::with_capacity(self.num_constraints()); let coeffs = (0..self.num_points()) .map(|i| vars.get_local_ext_algebra(self.wires_coeff(i))) .collect(); let interpolant = PolynomialCoeffsAlgebra::new(coeffs); let coset = self.coset_ext(vars.local_wires[self.wire_shift()]); for (i, point) in coset.into_iter().enumerate() { let value = vars.get_local_ext_algebra(self.wires_value(i)); let computed_value = interpolant.eval_base(point); constraints.extend(&(value - computed_value).to_basefield_array()); } let evaluation_point = vars.get_local_ext_algebra(self.wires_evaluation_point()); let evaluation_value = vars.get_local_ext_algebra(self.wires_evaluation_value()); let computed_evaluation_value = interpolant.eval(evaluation_point); constraints.extend(&(evaluation_value - computed_evaluation_value).to_basefield_array()); constraints }
function_block-function_prefix_line
[ { "content": "/// Tests that the constraints imposed by the given gate are low-degree by applying them to random\n\n/// low-degree witness polynomials.\n\npub fn test_low_degree<F: RichField + Extendable<D>, G: Gate<F, D>, const D: usize>(gate: G) {\n\n let rate_bits = log2_ceil(gate.degree() + 1);\n\n\n\n let wire_ldes = random_low_degree_matrix::<F::Extension>(gate.num_wires(), rate_bits);\n\n let constant_ldes = random_low_degree_matrix::<F::Extension>(gate.num_constants(), rate_bits);\n\n assert_eq!(wire_ldes.len(), constant_ldes.len());\n\n let public_inputs_hash = &HashOut::rand();\n\n\n\n let constraint_evals = wire_ldes\n\n .iter()\n\n .zip(constant_ldes.iter())\n\n .map(|(local_wires, local_constants)| EvaluationVars {\n\n local_constants,\n\n local_wires,\n\n public_inputs_hash,\n\n })\n\n .map(|vars| gate.eval_unfiltered(vars))\n\n .collect::<Vec<_>>();\n\n\n\n let constraint_eval_degrees = transpose(&constraint_evals)\n", "file_path": "plonky2/src/gates/gate_testing.rs", "rank": 0, "score": 418854.4010740311 }, { "content": "/// Add an AssertLessThanGate to assert that `lhs` is less than `rhs`, where their values are at most `bits` bits.\n\npub fn assert_le<F: RichField + Extendable<D>, const D: usize>(\n\n builder: &mut CircuitBuilder<F, D>,\n\n lhs: Target,\n\n rhs: Target,\n\n bits: usize,\n\n num_chunks: usize,\n\n) {\n\n let gate = AssertLessThanGate::new(bits, num_chunks);\n\n let gate_index = builder.add_gate(gate.clone(), vec![]);\n\n\n\n builder.connect(Target::wire(gate_index, gate.wire_first_input()), lhs);\n\n builder.connect(Target::wire(gate_index, gate.wire_second_input()), rhs);\n\n}\n\n\n", "file_path": "waksman/src/sorting.rs", "rank": 1, "score": 371619.0920617954 }, { "content": "/// Assert that two lists of expressions evaluate to permutations of one another.\n\npub fn assert_permutation<F: RichField + Extendable<D>, const D: usize>(\n\n builder: &mut CircuitBuilder<F, D>,\n\n a: Vec<Vec<Target>>,\n\n b: Vec<Vec<Target>>,\n\n) {\n\n assert_eq!(\n\n a.len(),\n\n b.len(),\n\n \"Permutation must have same number of inputs and outputs\"\n\n );\n\n assert_eq!(a[0].len(), b[0].len(), \"Chunk size must be the same\");\n\n\n\n let chunk_size = a[0].len();\n\n\n\n match a.len() {\n\n // Two empty lists are permutations of one another, trivially.\n\n 0 => (),\n\n // Two singleton lists are permutations of one another as long as their items are equal.\n\n 1 => {\n\n for e in 0..chunk_size {\n", "file_path": "waksman/src/permutation.rs", "rank": 2, "score": 371619.0920617954 }, { "content": "/// Sort memory operations by address value, then by timestamp value.\n\n/// This is done by combining address and timestamp into one field element (using their given bit lengths).\n\npub fn sort_memory_ops<F: RichField + Extendable<D>, const D: usize>(\n\n builder: &mut CircuitBuilder<F, D>,\n\n ops: &[MemoryOpTarget],\n\n address_bits: usize,\n\n timestamp_bits: usize,\n\n) -> Vec<MemoryOpTarget> {\n\n let n = ops.len();\n\n\n\n let combined_bits = address_bits + timestamp_bits;\n\n let chunk_bits = 3;\n\n let num_chunks = ceil_div_usize(combined_bits, chunk_bits);\n\n\n\n // This is safe because `assert_permutation` will force these targets (in the output list) to match the boolean values from the input list.\n\n let is_write_targets: Vec<_> = builder\n\n .add_virtual_targets(n)\n\n .iter()\n\n .map(|&t| BoolTarget::new_unsafe(t))\n\n .collect();\n\n\n\n let address_targets = builder.add_virtual_targets(n);\n", "file_path": "waksman/src/sorting.rs", "rank": 3, "score": 367192.3760649865 }, { "content": "/// Batch every D-sized chunks into extension targets.\n\npub fn unflatten_target<F: RichField + Extendable<D>, const D: usize>(\n\n l: &[Target],\n\n) -> Vec<ExtensionTarget<D>> {\n\n debug_assert_eq!(l.len() % D, 0);\n\n l.chunks_exact(D)\n\n .map(|c| c.to_vec().try_into().unwrap())\n\n .collect()\n\n}\n", "file_path": "plonky2/src/iop/ext_target.rs", "rank": 4, "score": 362916.0460593223 }, { "content": "pub fn assert_permutation_memory_ops<F: RichField + Extendable<D>, const D: usize>(\n\n builder: &mut CircuitBuilder<F, D>,\n\n a: &[MemoryOpTarget],\n\n b: &[MemoryOpTarget],\n\n) {\n\n let a_chunks: Vec<Vec<Target>> = a\n\n .iter()\n\n .map(|op| vec![op.address, op.timestamp, op.is_write.target, op.value])\n\n .collect();\n\n let b_chunks: Vec<Vec<Target>> = b\n\n .iter()\n\n .map(|op| vec![op.address, op.timestamp, op.is_write.target, op.value])\n\n .collect();\n\n\n\n assert_permutation(builder, a_chunks, b_chunks);\n\n}\n\n\n", "file_path": "waksman/src/sorting.rs", "rank": 5, "score": 362910.56982960703 }, { "content": "/// Evaluates all gate constraints.\n\n///\n\n/// `num_gate_constraints` is the largest number of constraints imposed by any gate. It is not\n\n/// strictly necessary, but it helps performance by ensuring that we allocate a vector with exactly\n\n/// the capacity that we need.\n\npub fn evaluate_gate_constraints<F: RichField + Extendable<D>, const D: usize>(\n\n gates: &[PrefixedGate<F, D>],\n\n num_gate_constraints: usize,\n\n vars: EvaluationVars<F, D>,\n\n) -> Vec<F::Extension> {\n\n let mut constraints = vec![F::Extension::ZERO; num_gate_constraints];\n\n for gate in gates {\n\n let gate_constraints = gate.gate.0.eval_filtered(vars, &gate.prefix);\n\n for (i, c) in gate_constraints.into_iter().enumerate() {\n\n debug_assert!(\n\n i < num_gate_constraints,\n\n \"num_constraints() gave too low of a number\"\n\n );\n\n constraints[i] += c;\n\n }\n\n }\n\n constraints\n\n}\n\n\n", "file_path": "plonky2/src/plonk/vanishing_poly.rs", "rank": 6, "score": 358780.7151032766 }, { "content": "/// Builds a FRI proof.\n\npub fn fri_proof<F: RichField + Extendable<D>, C: GenericConfig<D, F = F>, const D: usize>(\n\n initial_merkle_trees: &[&MerkleTree<F, C::Hasher>],\n\n // Coefficients of the polynomial on which the LDT is performed. Only the first `1/rate` coefficients are non-zero.\n\n lde_polynomial_coeffs: PolynomialCoeffs<F::Extension>,\n\n // Evaluation of the polynomial on the large domain.\n\n lde_polynomial_values: PolynomialValues<F::Extension>,\n\n challenger: &mut Challenger<F, C::Hasher>,\n\n fri_params: &FriParams,\n\n timing: &mut TimingTree,\n\n) -> FriProof<F, C::Hasher, D>\n\nwhere\n\n [(); C::Hasher::HASH_SIZE]:,\n\n{\n\n let n = lde_polynomial_values.len();\n\n assert_eq!(lde_polynomial_coeffs.len(), n);\n\n\n\n // Commit phase\n\n let (trees, final_coeffs) = timed!(\n\n timing,\n\n \"fold codewords in the commitment phase\",\n", "file_path": "plonky2/src/fri/prover.rs", "rank": 7, "score": 357865.42786706553 }, { "content": "pub fn reduce_with_powers_ext_recursive<F: RichField + Extendable<D>, const D: usize>(\n\n builder: &mut CircuitBuilder<F, D>,\n\n terms: &[ExtensionTarget<D>],\n\n alpha: Target,\n\n) -> ExtensionTarget<D> {\n\n let alpha = builder.convert_to_ext(alpha);\n\n let mut alpha = ReducingFactorTarget::new(alpha);\n\n alpha.reduce(terms, builder)\n\n}\n", "file_path": "plonky2/src/plonk/plonk_common.rs", "rank": 8, "score": 354790.3580145439 }, { "content": "pub fn evaluate_gate_constraints_recursively<F: RichField + Extendable<D>, const D: usize>(\n\n builder: &mut CircuitBuilder<F, D>,\n\n gates: &[PrefixedGate<F, D>],\n\n num_gate_constraints: usize,\n\n vars: EvaluationTargets<D>,\n\n) -> Vec<ExtensionTarget<D>> {\n\n let mut all_gate_constraints = vec![builder.zero_extension(); num_gate_constraints];\n\n for gate in gates {\n\n with_context!(\n\n builder,\n\n &format!(\"evaluate {} constraints\", gate.gate.0.id()),\n\n gate.gate.0.eval_filtered_recursively(\n\n builder,\n\n vars,\n\n &gate.prefix,\n\n &mut all_gate_constraints\n\n )\n\n );\n\n }\n\n all_gate_constraints\n", "file_path": "plonky2/src/plonk/vanishing_poly.rs", "rank": 9, "score": 354790.3580145439 }, { "content": "pub fn verify_fri_proof<F: RichField + Extendable<D>, C: GenericConfig<D, F = F>, const D: usize>(\n\n instance: &FriInstanceInfo<F, D>,\n\n openings: &FriOpenings<F, D>,\n\n challenges: &FriChallenges<F, D>,\n\n initial_merkle_caps: &[MerkleCap<F, C::Hasher>],\n\n proof: &FriProof<F, C::Hasher, D>,\n\n params: &FriParams,\n\n) -> Result<()>\n\nwhere\n\n [(); C::Hasher::HASH_SIZE]:,\n\n{\n\n ensure!(\n\n params.final_poly_len() == proof.final_poly.len(),\n\n \"Final polynomial has wrong degree.\"\n\n );\n\n\n\n // Size of the LDE domain.\n\n let n = params.lde_size();\n\n\n\n // Check PoW.\n", "file_path": "plonky2/src/fri/verifier.rs", "rank": 10, "score": 354496.4353188978 }, { "content": "/// Evaluate all gate constraints in the base field.\n\n///\n\n/// Returns a vector of `num_gate_constraints * vars_batch.len()` field elements. The constraints\n\n/// corresponding to `vars_batch[i]` are found in `result[i], result[vars_batch.len() + i],\n\n/// result[2 * vars_batch.len() + i], ...`.\n\npub fn evaluate_gate_constraints_base_batch<F: RichField + Extendable<D>, const D: usize>(\n\n gates: &[PrefixedGate<F, D>],\n\n num_gate_constraints: usize,\n\n vars_batch: EvaluationVarsBaseBatch<F>,\n\n) -> Vec<F> {\n\n let mut constraints_batch = vec![F::ZERO; num_gate_constraints * vars_batch.len()];\n\n for gate in gates {\n\n let gate_constraints_batch = gate\n\n .gate\n\n .0\n\n .eval_filtered_base_batch(vars_batch, &gate.prefix);\n\n debug_assert!(\n\n gate_constraints_batch.len() <= constraints_batch.len(),\n\n \"num_constraints() gave too low of a number\"\n\n );\n\n // below adds all constraints for all points\n\n batch_add_inplace(\n\n &mut constraints_batch[..gate_constraints_batch.len()],\n\n &gate_constraints_batch,\n\n );\n\n }\n\n constraints_batch\n\n}\n\n\n", "file_path": "plonky2/src/plonk/vanishing_poly.rs", "rank": 11, "score": 350939.11232865375 }, { "content": "/// Tests that the constraints imposed by the given STARK are low-degree by applying them to random\n\n/// low-degree witness polynomials.\n\npub fn test_stark_low_degree<F: RichField + Extendable<D>, S: Stark<F, D>, const D: usize>(\n\n stark: S,\n\n) -> Result<()>\n\nwhere\n\n [(); S::COLUMNS]:,\n\n [(); S::PUBLIC_INPUTS]:,\n\n{\n\n let rate_bits = log2_ceil(stark.constraint_degree() + 1);\n\n\n\n let trace_ldes = random_low_degree_matrix::<F>(S::COLUMNS, rate_bits);\n\n let size = trace_ldes.len();\n\n let public_inputs = F::rand_arr::<{ S::PUBLIC_INPUTS }>();\n\n\n\n let lagrange_first = PolynomialValues::selector(WITNESS_SIZE, 0).lde(rate_bits);\n\n let lagrange_last = PolynomialValues::selector(WITNESS_SIZE, WITNESS_SIZE - 1).lde(rate_bits);\n\n\n\n let last = F::primitive_root_of_unity(log2_strict(WITNESS_SIZE)).inverse();\n\n let subgroup =\n\n F::cyclic_subgroup_known_order(F::primitive_root_of_unity(log2_strict(size)), size);\n\n let alpha = F::rand();\n", "file_path": "starky/src/stark_testing.rs", "rank": 12, "score": 350165.9246890603 }, { "content": "pub fn add_virtual_stark_proof<F: RichField + Extendable<D>, S: Stark<F, D>, const D: usize>(\n\n builder: &mut CircuitBuilder<F, D>,\n\n stark: S,\n\n config: &StarkConfig,\n\n degree_bits: usize,\n\n) -> StarkProofTarget<D> {\n\n let fri_params = config.fri_params(degree_bits);\n\n let cap_height = fri_params.config.cap_height;\n\n\n\n let num_leaves_per_oracle = once(S::COLUMNS)\n\n .chain(\n\n stark\n\n .uses_permutation_args()\n\n .then(|| stark.num_permutation_batches(config)),\n\n )\n\n .chain(once(stark.quotient_degree_factor() * config.num_challenges))\n\n .collect_vec();\n\n\n\n let permutation_zs_cap = stark\n\n .uses_permutation_args()\n", "file_path": "starky/src/recursive_verifier.rs", "rank": 13, "score": 350160.67968718783 }, { "content": "/// Finds a set of shifts that result in unique cosets for the multiplicative subgroup of size\n\n/// `2^subgroup_bits`.\n\npub fn get_unique_coset_shifts<F: Field>(subgroup_size: usize, num_shifts: usize) -> Vec<F> {\n\n // From Lagrange's theorem.\n\n let num_cosets = (F::order() - 1u32) / (subgroup_size as u32);\n\n assert!(\n\n BigUint::from(num_shifts) <= num_cosets,\n\n \"The subgroup does not have enough distinct cosets\"\n\n );\n\n\n\n // Let g be a generator of the entire multiplicative group. Let n be the order of the subgroup.\n\n // The subgroup can be written as <g^(|F*| / n)>. We can use g^0, ..., g^(num_shifts - 1) as our\n\n // shifts, since g^i <g^(|F*| / n)> are distinct cosets provided i < |F*| / n, which we checked.\n\n F::MULTIPLICATIVE_GROUP_GENERATOR\n\n .powers()\n\n .take(num_shifts)\n\n .collect()\n\n}\n\n\n\n#[cfg(test)]\n\nmod tests {\n\n use std::collections::HashSet;\n", "file_path": "field/src/cosets.rs", "rank": 14, "score": 346675.3491050841 }, { "content": "pub trait CircuitBuilderInsert<F: RichField + Extendable<D>, const D: usize> {\n\n /// Inserts a `Target` in a vector at a non-deterministic index.\n\n /// Note: `index` is not range-checked.\n\n fn insert(\n\n &mut self,\n\n index: Target,\n\n element: ExtensionTarget<D>,\n\n v: Vec<ExtensionTarget<D>>,\n\n ) -> Vec<ExtensionTarget<D>>;\n\n}\n\n\n\nimpl<F: RichField + Extendable<D>, const D: usize> CircuitBuilderInsert<F, D>\n\n for CircuitBuilder<F, D>\n\n{\n\n fn insert(\n\n &mut self,\n\n index: Target,\n\n element: ExtensionTarget<D>,\n\n v: Vec<ExtensionTarget<D>>,\n\n ) -> Vec<ExtensionTarget<D>> {\n", "file_path": "insertion/src/insert_gadget.rs", "rank": 15, "score": 341593.0957900818 }, { "content": "/// Set the targets in a `FriProofTarget` to their corresponding values in a `FriProof`.\n\npub fn set_fri_proof_target<F, W, H, const D: usize>(\n\n witness: &mut W,\n\n fri_proof_target: &FriProofTarget<D>,\n\n fri_proof: &FriProof<F, H, D>,\n\n) where\n\n F: RichField + Extendable<D>,\n\n W: Witness<F> + ?Sized,\n\n H: AlgebraicHasher<F>,\n\n{\n\n witness.set_target(fri_proof_target.pow_witness, fri_proof.pow_witness);\n\n\n\n for (&t, &x) in fri_proof_target\n\n .final_poly\n\n .0\n\n .iter()\n\n .zip_eq(&fri_proof.final_poly.coeffs)\n\n {\n\n witness.set_extension_target(t, x);\n\n }\n\n\n", "file_path": "plonky2/src/fri/witness_util.rs", "rank": 16, "score": 340172.88110617886 }, { "content": "/// Trait for hash functions.\n\npub trait Hasher<F: RichField>: Sized + Clone + Debug + Eq + PartialEq {\n\n /// Size of `Hash` in bytes.\n\n const HASH_SIZE: usize;\n\n type Hash: GenericHashOut<F>;\n\n\n\n /// Permutation used in the sponge construction.\n\n type Permutation: PlonkyPermutation<F>;\n\n\n\n /// Hash a message without any padding step. Note that this can enable length-extension attacks.\n\n /// However, it is still collision-resistant in cases where the input has a fixed length.\n\n fn hash_no_pad(input: &[F]) -> Self::Hash;\n\n\n\n /// Pad the message using the `pad10*1` rule, then hash it.\n\n fn hash_pad(input: &[F]) -> Self::Hash {\n\n let mut padded_input = input.to_vec();\n\n padded_input.push(F::ONE);\n\n while (padded_input.len() + 1) % SPONGE_WIDTH != 0 {\n\n padded_input.push(F::ZERO);\n\n }\n\n padded_input.push(F::ONE);\n", "file_path": "plonky2/src/plonk/config.rs", "rank": 17, "score": 335455.8763356266 }, { "content": "pub fn prove<F, C, S, const D: usize>(\n\n stark: S,\n\n config: &StarkConfig,\n\n trace_poly_values: Vec<PolynomialValues<F>>,\n\n public_inputs: [F; S::PUBLIC_INPUTS],\n\n timing: &mut TimingTree,\n\n) -> Result<StarkProofWithPublicInputs<F, C, D>>\n\nwhere\n\n F: RichField + Extendable<D>,\n\n C: GenericConfig<D, F = F>,\n\n S: Stark<F, D>,\n\n [(); S::COLUMNS]:,\n\n [(); S::PUBLIC_INPUTS]:,\n\n [(); <<F as Packable>::Packing>::WIDTH]:,\n\n [(); C::Hasher::HASH_SIZE]:,\n\n{\n\n let degree = trace_poly_values[0].len();\n\n let degree_bits = log2_strict(degree);\n\n let fri_params = config.fri_params(degree_bits);\n\n let rate_bits = config.fri_config.rate_bits;\n", "file_path": "starky/src/prover.rs", "rank": 18, "score": 319090.43909235776 }, { "content": "/// Batch every D-sized chunks into extension field elements.\n\npub fn unflatten<F: Field, const D: usize>(l: &[F]) -> Vec<F::Extension>\n\nwhere\n\n F: Extendable<D>,\n\n{\n\n debug_assert_eq!(l.len() % D, 0);\n\n l.chunks_exact(D)\n\n .map(|c| F::Extension::from_basefield_array(c.to_vec().try_into().unwrap()))\n\n .collect()\n\n}\n", "file_path": "field/src/extension_field/mod.rs", "rank": 19, "score": 318480.22507800465 }, { "content": "/// Flatten the slice by sending every extension field element to its D-sized canonical representation.\n\npub fn flatten<F: Field, const D: usize>(l: &[F::Extension]) -> Vec<F>\n\nwhere\n\n F: Extendable<D>,\n\n{\n\n l.iter()\n\n .flat_map(|x| x.to_basefield_array().to_vec())\n\n .collect()\n\n}\n\n\n", "file_path": "field/src/extension_field/mod.rs", "rank": 20, "score": 318480.11347915 }, { "content": "/// A helper function to transpose a row-wise trace and put it in the format that `prove` expects.\n\npub fn trace_rows_to_poly_values<F: Field, const COLUMNS: usize>(\n\n trace_rows: Vec<[F; COLUMNS]>,\n\n) -> Vec<PolynomialValues<F>> {\n\n let trace_row_vecs = trace_rows.into_iter().map(|row| row.to_vec()).collect_vec();\n\n let trace_col_vecs: Vec<Vec<F>> = transpose(&trace_row_vecs);\n\n trace_col_vecs\n\n .into_iter()\n\n .map(|column| PolynomialValues::new(column))\n\n .collect()\n\n}\n", "file_path": "starky/src/util.rs", "rank": 21, "score": 314485.52253907884 }, { "content": "#[derive(Debug)]\n\nstruct SwitchGenerator<F: RichField + Extendable<D>, const D: usize> {\n\n gate_index: usize,\n\n gate: SwitchGate<F, D>,\n\n copy: usize,\n\n}\n\n\n\nimpl<F: RichField + Extendable<D>, const D: usize> SwitchGenerator<F, D> {\n\n fn in_out_dependencies(&self) -> Vec<Target> {\n\n let local_target = |input| Target::wire(self.gate_index, input);\n\n\n\n let mut deps = Vec::new();\n\n for e in 0..self.gate.chunk_size {\n\n deps.push(local_target(self.gate.wire_first_input(self.copy, e)));\n\n deps.push(local_target(self.gate.wire_second_input(self.copy, e)));\n\n deps.push(local_target(self.gate.wire_first_output(self.copy, e)));\n\n deps.push(local_target(self.gate.wire_second_output(self.copy, e)));\n\n }\n\n\n\n deps\n\n }\n", "file_path": "plonky2/src/gates/switch.rs", "rank": 22, "score": 314433.92711157666 }, { "content": "#[derive(Debug)]\n\nstruct InsertionGenerator<F: RichField + Extendable<D>, const D: usize> {\n\n gate_index: usize,\n\n gate: InsertionGate<F, D>,\n\n}\n\n\n\nimpl<F: RichField + Extendable<D>, const D: usize> SimpleGenerator<F> for InsertionGenerator<F, D> {\n\n fn dependencies(&self) -> Vec<Target> {\n\n let local_target = |input| Target::wire(self.gate_index, input);\n\n\n\n let local_targets = |inputs: Range<usize>| inputs.map(local_target);\n\n\n\n let mut deps = vec![local_target(self.gate.wires_insertion_index())];\n\n deps.extend(local_targets(self.gate.wires_element_to_insert()));\n\n for i in 0..self.gate.vec_size {\n\n deps.extend(local_targets(self.gate.wires_original_list_item(i)));\n\n }\n\n deps\n\n }\n\n\n\n fn run_once(&self, witness: &PartitionWitness<F>, out_buffer: &mut GeneratedValues<F>) {\n", "file_path": "insertion/src/insertion_gate.rs", "rank": 23, "score": 314433.92711157666 }, { "content": "#[derive(Debug)]\n\nstruct ComparisonGenerator<F: RichField + Extendable<D>, const D: usize> {\n\n gate_index: usize,\n\n gate: ComparisonGate<F, D>,\n\n}\n\n\n\nimpl<F: RichField + Extendable<D>, const D: usize> SimpleGenerator<F>\n\n for ComparisonGenerator<F, D>\n\n{\n\n fn dependencies(&self) -> Vec<Target> {\n\n let local_target = |input| Target::wire(self.gate_index, input);\n\n\n\n vec![\n\n local_target(self.gate.wire_first_input()),\n\n local_target(self.gate.wire_second_input()),\n\n ]\n\n }\n\n\n\n fn run_once(&self, witness: &PartitionWitness<F>, out_buffer: &mut GeneratedValues<F>) {\n\n let local_wire = |input| Wire {\n\n gate: self.gate_index,\n", "file_path": "plonky2/src/gates/comparison.rs", "rank": 24, "score": 314433.9271115768 }, { "content": "#[derive(Debug)]\n\nstruct ExponentiationGenerator<F: RichField + Extendable<D>, const D: usize> {\n\n gate_index: usize,\n\n gate: ExponentiationGate<F, D>,\n\n}\n\n\n\nimpl<F: RichField + Extendable<D>, const D: usize> SimpleGenerator<F>\n\n for ExponentiationGenerator<F, D>\n\n{\n\n fn dependencies(&self) -> Vec<Target> {\n\n let local_target = |input| Target::wire(self.gate_index, input);\n\n\n\n let mut deps = Vec::with_capacity(self.gate.num_power_bits + 1);\n\n deps.push(local_target(self.gate.wire_base()));\n\n for i in 0..self.gate.num_power_bits {\n\n deps.push(local_target(self.gate.wire_power_bit(i)));\n\n }\n\n deps\n\n }\n\n\n\n fn run_once(&self, witness: &PartitionWitness<F>, out_buffer: &mut GeneratedValues<F>) {\n", "file_path": "plonky2/src/gates/exponentiation.rs", "rank": 26, "score": 314433.9271115768 }, { "content": "#[derive(Copy, Clone)]\n\nstruct FibonacciStark<F: RichField + Extendable<D>, const D: usize> {\n\n num_rows: usize,\n\n _phantom: PhantomData<F>,\n\n}\n\n\n\nimpl<F: RichField + Extendable<D>, const D: usize> FibonacciStark<F, D> {\n\n // The first public input is `x0`.\n\n const PI_INDEX_X0: usize = 0;\n\n // The second public input is `x1`.\n\n const PI_INDEX_X1: usize = 1;\n\n // The third public input is the second element of the last row, which should be equal to the\n\n // `num_rows`-th Fibonacci number.\n\n const PI_INDEX_RES: usize = 2;\n\n\n\n fn new(num_rows: usize) -> Self {\n\n Self {\n\n num_rows,\n\n _phantom: PhantomData,\n\n }\n\n }\n", "file_path": "starky/src/fibonacci_stark.rs", "rank": 27, "score": 314433.9100651187 }, { "content": "/// Given two input wire chunks, add a new switch to the circuit (by adding one copy to a switch\n\n/// gate). Returns the wire for the switch boolean, and the two output wire chunks.\n\nfn create_switch<F: RichField + Extendable<D>, const D: usize>(\n\n builder: &mut CircuitBuilder<F, D>,\n\n a1: Vec<Target>,\n\n a2: Vec<Target>,\n\n) -> (Target, Vec<Target>, Vec<Target>) {\n\n assert_eq!(a1.len(), a2.len(), \"Chunk size must be the same\");\n\n\n\n let chunk_size = a1.len();\n\n\n\n let gate = SwitchGate::new_from_config(&builder.config, chunk_size);\n\n let params = vec![F::from_canonical_usize(chunk_size)];\n\n let (gate_index, next_copy) = builder.find_slot(gate, &params, &[]);\n\n\n\n let mut c = Vec::new();\n\n let mut d = Vec::new();\n\n for e in 0..chunk_size {\n\n builder.connect(\n\n a1[e],\n\n Target::wire(gate_index, gate.wire_first_input(next_copy, e)),\n\n );\n", "file_path": "waksman/src/permutation.rs", "rank": 28, "score": 312364.0724735564 }, { "content": "#[derive(Debug)]\n\nstruct MemoryOpSortGenerator<F: RichField + Extendable<D>, const D: usize> {\n\n input_ops: Vec<MemoryOpTarget>,\n\n output_ops: Vec<MemoryOpTarget>,\n\n _phantom: PhantomData<F>,\n\n}\n\n\n\nimpl<F: RichField + Extendable<D>, const D: usize> SimpleGenerator<F>\n\n for MemoryOpSortGenerator<F, D>\n\n{\n\n fn dependencies(&self) -> Vec<Target> {\n\n self.input_ops\n\n .iter()\n\n .flat_map(|op| vec![op.is_write.target, op.address, op.timestamp, op.value])\n\n .collect()\n\n }\n\n\n\n fn run_once(&self, witness: &PartitionWitness<F>, out_buffer: &mut GeneratedValues<F>) {\n\n let n = self.input_ops.len();\n\n debug_assert!(self.output_ops.len() == n);\n\n\n", "file_path": "waksman/src/sorting.rs", "rank": 29, "score": 310735.0515159291 }, { "content": "fn assert_permutation_recursive<F: RichField + Extendable<D>, const D: usize>(\n\n builder: &mut CircuitBuilder<F, D>,\n\n a: Vec<Vec<Target>>,\n\n b: Vec<Vec<Target>>,\n\n) {\n\n assert_eq!(\n\n a.len(),\n\n b.len(),\n\n \"Permutation must have same number of inputs and outputs\"\n\n );\n\n assert_eq!(a[0].len(), b[0].len(), \"Chunk size must be the same\");\n\n\n\n let n = a.len();\n\n let even = n % 2 == 0;\n\n\n\n let mut child_1_a = Vec::new();\n\n let mut child_1_b = Vec::new();\n\n let mut child_2_a = Vec::new();\n\n let mut child_2_b = Vec::new();\n\n\n", "file_path": "waksman/src/permutation.rs", "rank": 30, "score": 308534.73008827365 }, { "content": "/// Assert that [a1, a2] is a permutation of [b1, b2].\n\nfn assert_permutation_2x2<F: RichField + Extendable<D>, const D: usize>(\n\n builder: &mut CircuitBuilder<F, D>,\n\n a1: Vec<Target>,\n\n a2: Vec<Target>,\n\n b1: Vec<Target>,\n\n b2: Vec<Target>,\n\n) {\n\n assert!(\n\n a1.len() == a2.len() && a2.len() == b1.len() && b1.len() == b2.len(),\n\n \"Chunk size must be the same\"\n\n );\n\n\n\n let chunk_size = a1.len();\n\n\n\n let (_switch, gate_out1, gate_out2) = create_switch(builder, a1, a2);\n\n for e in 0..chunk_size {\n\n builder.connect(b1[e], gate_out1[e]);\n\n builder.connect(b2[e], gate_out2[e]);\n\n }\n\n}\n\n\n", "file_path": "waksman/src/permutation.rs", "rank": 31, "score": 308534.73008827365 }, { "content": "#[derive(Debug)]\n\nstruct PoseidonGenerator<F: RichField + Extendable<D> + Poseidon, const D: usize> {\n\n gate_index: usize,\n\n _phantom: PhantomData<F>,\n\n}\n\n\n\nimpl<F: RichField + Extendable<D> + Poseidon, const D: usize> SimpleGenerator<F>\n\n for PoseidonGenerator<F, D>\n\n{\n\n fn dependencies(&self) -> Vec<Target> {\n\n (0..SPONGE_WIDTH)\n\n .map(|i| PoseidonGate::<F, D>::wire_input(i))\n\n .chain(Some(PoseidonGate::<F, D>::WIRE_SWAP))\n\n .map(|input| Target::wire(self.gate_index, input))\n\n .collect()\n\n }\n\n\n\n fn run_once(&self, witness: &PartitionWitness<F>, out_buffer: &mut GeneratedValues<F>) {\n\n let local_wire = |input| Wire {\n\n gate: self.gate_index,\n\n input,\n", "file_path": "plonky2/src/gates/poseidon.rs", "rank": 32, "score": 307251.20396547293 }, { "content": "#[derive(Clone, Debug)]\n\nstruct U32SubtractionGenerator<F: RichField + Extendable<D>, const D: usize> {\n\n gate: U32SubtractionGate<F, D>,\n\n gate_index: usize,\n\n i: usize,\n\n _phantom: PhantomData<F>,\n\n}\n\n\n\nimpl<F: RichField + Extendable<D>, const D: usize> SimpleGenerator<F>\n\n for U32SubtractionGenerator<F, D>\n\n{\n\n fn dependencies(&self) -> Vec<Target> {\n\n let local_target = |input| Target::wire(self.gate_index, input);\n\n\n\n vec![\n\n local_target(self.gate.wire_ith_input_x(self.i)),\n\n local_target(self.gate.wire_ith_input_y(self.i)),\n\n local_target(self.gate.wire_ith_input_borrow(self.i)),\n\n ]\n\n }\n\n\n", "file_path": "plonky2/src/gates/subtraction_u32.rs", "rank": 33, "score": 307171.069607009 }, { "content": "#[derive(Clone, Debug)]\n\nstruct ArithmeticBaseGenerator<F: RichField + Extendable<D>, const D: usize> {\n\n gate_index: usize,\n\n const_0: F,\n\n const_1: F,\n\n i: usize,\n\n}\n\n\n\nimpl<F: RichField + Extendable<D>, const D: usize> SimpleGenerator<F>\n\n for ArithmeticBaseGenerator<F, D>\n\n{\n\n fn dependencies(&self) -> Vec<Target> {\n\n [\n\n ArithmeticGate::wire_ith_multiplicand_0(self.i),\n\n ArithmeticGate::wire_ith_multiplicand_1(self.i),\n\n ArithmeticGate::wire_ith_addend(self.i),\n\n ]\n\n .iter()\n\n .map(|&i| Target::wire(self.gate_index, i))\n\n .collect()\n\n }\n", "file_path": "plonky2/src/gates/arithmetic_base.rs", "rank": 34, "score": 307171.06960700906 }, { "content": "#[derive(Clone, Debug)]\n\nstruct MulExtensionGenerator<F: RichField + Extendable<D>, const D: usize> {\n\n gate_index: usize,\n\n const_0: F,\n\n i: usize,\n\n}\n\n\n\nimpl<F: RichField + Extendable<D>, const D: usize> SimpleGenerator<F>\n\n for MulExtensionGenerator<F, D>\n\n{\n\n fn dependencies(&self) -> Vec<Target> {\n\n MulExtensionGate::<D>::wires_ith_multiplicand_0(self.i)\n\n .chain(MulExtensionGate::<D>::wires_ith_multiplicand_1(self.i))\n\n .map(|i| Target::wire(self.gate_index, i))\n\n .collect()\n\n }\n\n\n\n fn run_once(&self, witness: &PartitionWitness<F>, out_buffer: &mut GeneratedValues<F>) {\n\n let extract_extension = |range: Range<usize>| -> F::Extension {\n\n let t = ExtensionTarget::from_range(self.gate_index, range);\n\n witness.get_extension_target(t)\n", "file_path": "plonky2/src/gates/multiplication_extension.rs", "rank": 35, "score": 307171.06960700906 }, { "content": "#[derive(Clone, Debug)]\n\nstruct U32ArithmeticGenerator<F: RichField + Extendable<D>, const D: usize> {\n\n gate: U32ArithmeticGate<F, D>,\n\n gate_index: usize,\n\n i: usize,\n\n _phantom: PhantomData<F>,\n\n}\n\n\n\nimpl<F: RichField + Extendable<D>, const D: usize> SimpleGenerator<F>\n\n for U32ArithmeticGenerator<F, D>\n\n{\n\n fn dependencies(&self) -> Vec<Target> {\n\n let local_target = |input| Target::wire(self.gate_index, input);\n\n\n\n vec![\n\n local_target(self.gate.wire_ith_multiplicand_0(self.i)),\n\n local_target(self.gate.wire_ith_multiplicand_1(self.i)),\n\n local_target(self.gate.wire_ith_addend(self.i)),\n\n ]\n\n }\n\n\n", "file_path": "plonky2/src/gates/arithmetic_u32.rs", "rank": 36, "score": 307171.06960700906 }, { "content": "#[derive(Clone, Debug)]\n\nstruct ArithmeticExtensionGenerator<F: RichField + Extendable<D>, const D: usize> {\n\n gate_index: usize,\n\n const_0: F,\n\n const_1: F,\n\n i: usize,\n\n}\n\n\n\nimpl<F: RichField + Extendable<D>, const D: usize> SimpleGenerator<F>\n\n for ArithmeticExtensionGenerator<F, D>\n\n{\n\n fn dependencies(&self) -> Vec<Target> {\n\n ArithmeticExtensionGate::<D>::wires_ith_multiplicand_0(self.i)\n\n .chain(ArithmeticExtensionGate::<D>::wires_ith_multiplicand_1(\n\n self.i,\n\n ))\n\n .chain(ArithmeticExtensionGate::<D>::wires_ith_addend(self.i))\n\n .map(|i| Target::wire(self.gate_index, i))\n\n .collect()\n\n }\n\n\n", "file_path": "plonky2/src/gates/arithmetic_extension.rs", "rank": 37, "score": 307171.06960700906 }, { "content": "#[derive(Debug)]\n\nstruct RandomAccessGenerator<F: RichField + Extendable<D>, const D: usize> {\n\n gate_index: usize,\n\n gate: RandomAccessGate<F, D>,\n\n copy: usize,\n\n}\n\n\n\nimpl<F: RichField + Extendable<D>, const D: usize> SimpleGenerator<F>\n\n for RandomAccessGenerator<F, D>\n\n{\n\n fn dependencies(&self) -> Vec<Target> {\n\n let local_target = |input| Target::wire(self.gate_index, input);\n\n\n\n let mut deps = vec![local_target(self.gate.wire_access_index(self.copy))];\n\n for i in 0..self.gate.vec_size() {\n\n deps.push(local_target(self.gate.wire_list_item(i, self.copy)));\n\n }\n\n deps\n\n }\n\n\n\n fn run_once(&self, witness: &PartitionWitness<F>, out_buffer: &mut GeneratedValues<F>) {\n", "file_path": "plonky2/src/gates/random_access.rs", "rank": 38, "score": 307165.48374809907 }, { "content": "#[derive(Debug)]\n\nstruct SplitToU32Generator<F: RichField + Extendable<D>, const D: usize> {\n\n x: Target,\n\n low: U32Target,\n\n high: U32Target,\n\n _phantom: PhantomData<F>,\n\n}\n\n\n\nimpl<F: RichField + Extendable<D>, const D: usize> SimpleGenerator<F>\n\n for SplitToU32Generator<F, D>\n\n{\n\n fn dependencies(&self) -> Vec<Target> {\n\n vec![self.x]\n\n }\n\n\n\n fn run_once(&self, witness: &PartitionWitness<F>, out_buffer: &mut GeneratedValues<F>) {\n\n let x = witness.get_target(self.x);\n\n let x_u64 = x.to_canonical_u64();\n\n let low = x_u64 as u32;\n\n let high = (x_u64 >> 32) as u32;\n\n\n", "file_path": "plonky2/src/gadgets/arithmetic_u32.rs", "rank": 39, "score": 307165.48374809907 }, { "content": "#[derive(Debug)]\n\nstruct AssertLessThanGenerator<F: RichField + Extendable<D>, const D: usize> {\n\n gate_index: usize,\n\n gate: AssertLessThanGate<F, D>,\n\n}\n\n\n\nimpl<F: RichField + Extendable<D>, const D: usize> SimpleGenerator<F>\n\n for AssertLessThanGenerator<F, D>\n\n{\n\n fn dependencies(&self) -> Vec<Target> {\n\n let local_target = |input| Target::wire(self.gate_index, input);\n\n\n\n vec![\n\n local_target(self.gate.wire_first_input()),\n\n local_target(self.gate.wire_second_input()),\n\n ]\n\n }\n\n\n\n fn run_once(&self, witness: &PartitionWitness<F>, out_buffer: &mut GeneratedValues<F>) {\n\n let local_wire = |input| Wire {\n\n gate: self.gate_index,\n", "file_path": "plonky2/src/gates/assert_le.rs", "rank": 40, "score": 307165.48374809907 }, { "content": "#[derive(Debug)]\n\nstruct InterpolationGenerator<F: RichField + Extendable<D>, const D: usize> {\n\n gate_index: usize,\n\n gate: LowDegreeInterpolationGate<F, D>,\n\n _phantom: PhantomData<F>,\n\n}\n\n\n\nimpl<F: RichField + Extendable<D>, const D: usize> SimpleGenerator<F>\n\n for InterpolationGenerator<F, D>\n\n{\n\n fn dependencies(&self) -> Vec<Target> {\n\n let local_target = |input| {\n\n Target::Wire(Wire {\n\n gate: self.gate_index,\n\n input,\n\n })\n\n };\n\n\n\n let local_targets = |inputs: Range<usize>| inputs.map(local_target);\n\n\n\n let num_points = self.gate.num_points();\n", "file_path": "plonky2/src/gates/low_degree_interpolation.rs", "rank": 41, "score": 307165.48374809907 }, { "content": "pub fn set_stark_proof_target<F, C: GenericConfig<D, F = F>, W, const D: usize>(\n\n witness: &mut W,\n\n proof_target: &StarkProofTarget<D>,\n\n proof: &StarkProof<F, C, D>,\n\n) where\n\n F: RichField + Extendable<D>,\n\n C::Hasher: AlgebraicHasher<F>,\n\n W: Witness<F>,\n\n{\n\n witness.set_cap_target(&proof_target.trace_cap, &proof.trace_cap);\n\n witness.set_cap_target(&proof_target.quotient_polys_cap, &proof.quotient_polys_cap);\n\n\n\n witness.set_fri_openings(\n\n &proof_target.openings.to_fri_openings(),\n\n &proof.openings.to_fri_openings(),\n\n );\n\n\n\n if let (Some(permutation_zs_cap_target), Some(permutation_zs_cap)) =\n\n (&proof_target.permutation_zs_cap, &proof.permutation_zs_cap)\n\n {\n\n witness.set_cap_target(permutation_zs_cap_target, permutation_zs_cap);\n\n }\n\n\n\n set_fri_proof_target(witness, &proof_target.opening_proof, &proof.opening_proof);\n\n}\n\n\n", "file_path": "starky/src/recursive_verifier.rs", "rank": 42, "score": 306082.9090944768 }, { "content": "/// Represents a STARK system.\n\npub trait Stark<F: RichField + Extendable<D>, const D: usize>: Sync {\n\n /// The total number of columns in the trace.\n\n const COLUMNS: usize;\n\n /// The number of public inputs.\n\n const PUBLIC_INPUTS: usize;\n\n\n\n /// Evaluate constraints at a vector of points.\n\n ///\n\n /// The points are elements of a field `FE`, a degree `D2` extension of `F`. This lets us\n\n /// evaluate constraints over a larger domain if desired. This can also be called with `FE = F`\n\n /// and `D2 = 1`, in which case we are using the trivial extension, i.e. just evaluating\n\n /// constraints over `F`.\n\n fn eval_packed_generic<FE, P, const D2: usize>(\n\n &self,\n\n vars: StarkEvaluationVars<FE, P, { Self::COLUMNS }, { Self::PUBLIC_INPUTS }>,\n\n yield_constr: &mut ConstraintConsumer<P>,\n\n ) where\n\n FE: FieldExtension<D2, BaseField = F>,\n\n P: PackedField<Scalar = FE>;\n\n\n", "file_path": "starky/src/stark.rs", "rank": 43, "score": 305454.47868540976 }, { "content": "fn eval_l_1_and_l_last_recursively<F: RichField + Extendable<D>, const D: usize>(\n\n builder: &mut CircuitBuilder<F, D>,\n\n log_n: usize,\n\n x: ExtensionTarget<D>,\n\n z_x: ExtensionTarget<D>,\n\n) -> (ExtensionTarget<D>, ExtensionTarget<D>) {\n\n let n = builder.constant_extension(F::Extension::from_canonical_usize(1 << log_n));\n\n let g = builder.constant_extension(F::Extension::primitive_root_of_unity(log_n));\n\n let one = builder.one_extension();\n\n let l_1_deno = builder.mul_sub_extension(n, x, n);\n\n let l_last_deno = builder.mul_sub_extension(g, x, one);\n\n let l_last_deno = builder.mul_extension(n, l_last_deno);\n\n\n\n (\n\n builder.div_extension(z_x, l_1_deno),\n\n builder.div_extension(z_x, l_last_deno),\n\n )\n\n}\n\n\n", "file_path": "starky/src/recursive_verifier.rs", "rank": 44, "score": 304841.6380446524 }, { "content": "fn compute_filter_recursively<F: RichField + Extendable<D>, const D: usize>(\n\n builder: &mut CircuitBuilder<F, D>,\n\n prefix: &[bool],\n\n constants: &[ExtensionTarget<D>],\n\n) -> ExtensionTarget<D> {\n\n let one = builder.one_extension();\n\n let v = prefix\n\n .iter()\n\n .enumerate()\n\n .map(|(i, &b)| {\n\n if b {\n\n constants[i]\n\n } else {\n\n builder.sub_extension(one, constants[i])\n\n }\n\n })\n\n .collect::<Vec<_>>();\n\n\n\n builder.mul_many_extension(&v)\n\n}\n", "file_path": "plonky2/src/gates/gate.rs", "rank": 45, "score": 304841.6380446524 }, { "content": "#[derive(Debug)]\n\nstruct BigUintDivRemGenerator<F: RichField + Extendable<D>, const D: usize> {\n\n a: BigUintTarget,\n\n b: BigUintTarget,\n\n div: BigUintTarget,\n\n rem: BigUintTarget,\n\n _phantom: PhantomData<F>,\n\n}\n\n\n\nimpl<F: RichField + Extendable<D>, const D: usize> SimpleGenerator<F>\n\n for BigUintDivRemGenerator<F, D>\n\n{\n\n fn dependencies(&self) -> Vec<Target> {\n\n self.a\n\n .limbs\n\n .iter()\n\n .chain(&self.b.limbs)\n\n .map(|&l| l.0)\n\n .collect()\n\n }\n\n\n", "file_path": "plonky2/src/gadgets/biguint.rs", "rank": 46, "score": 303718.5596457786 }, { "content": "pub fn set_stark_proof_with_pis_target<F, C: GenericConfig<D, F = F>, W, const D: usize>(\n\n witness: &mut W,\n\n stark_proof_with_pis_target: &StarkProofWithPublicInputsTarget<D>,\n\n stark_proof_with_pis: &StarkProofWithPublicInputs<F, C, D>,\n\n) where\n\n F: RichField + Extendable<D>,\n\n C::Hasher: AlgebraicHasher<F>,\n\n W: Witness<F>,\n\n{\n\n let StarkProofWithPublicInputs {\n\n proof,\n\n public_inputs,\n\n } = stark_proof_with_pis;\n\n let StarkProofWithPublicInputsTarget {\n\n proof: pt,\n\n public_inputs: pi_targets,\n\n } = stark_proof_with_pis_target;\n\n\n\n // Set public inputs.\n\n for (&pi_t, &pi) in pi_targets.iter().zip_eq(public_inputs) {\n\n witness.set_target(pi_t, pi);\n\n }\n\n\n\n set_stark_proof_target(witness, pt, proof);\n\n}\n\n\n", "file_path": "starky/src/recursive_verifier.rs", "rank": 47, "score": 303214.89866773324 }, { "content": "fn fri_proof_of_work<F: RichField + Extendable<D>, C: GenericConfig<D, F = F>, const D: usize>(\n\n current_hash: HashOut<F>,\n\n config: &FriConfig,\n\n) -> F {\n\n (0..=F::NEG_ONE.to_canonical_u64())\n\n .into_par_iter()\n\n .find_any(|&i| {\n\n C::InnerHasher::hash_no_pad(\n\n &current_hash\n\n .elements\n\n .iter()\n\n .copied()\n\n .chain(Some(F::from_canonical_u64(i)))\n\n .collect_vec(),\n\n )\n\n .elements[0]\n\n .to_canonical_u64()\n\n .leading_zeros()\n\n >= config.proof_of_work_bits + (64 - F::order().bits()) as u32\n\n })\n\n .map(F::from_canonical_u64)\n\n .expect(\"Proof of work failed. This is highly unlikely!\")\n\n}\n\n\n", "file_path": "plonky2/src/fri/prover.rs", "rank": 48, "score": 301970.41805066203 }, { "content": "fn get_challenges<F: RichField + Extendable<D>, C: GenericConfig<D, F = F>, const D: usize>(\n\n public_inputs_hash: <<C as GenericConfig<D>>::InnerHasher as Hasher<F>>::Hash,\n\n wires_cap: &MerkleCap<F, C::Hasher>,\n\n plonk_zs_partial_products_cap: &MerkleCap<F, C::Hasher>,\n\n quotient_polys_cap: &MerkleCap<F, C::Hasher>,\n\n openings: &OpeningSet<F, D>,\n\n commit_phase_merkle_caps: &[MerkleCap<F, C::Hasher>],\n\n final_poly: &PolynomialCoeffs<F::Extension>,\n\n pow_witness: F,\n\n common_data: &CommonCircuitData<F, C, D>,\n\n) -> anyhow::Result<ProofChallenges<F, D>> {\n\n let config = &common_data.config;\n\n let num_challenges = config.num_challenges;\n\n\n\n let mut challenger = Challenger::<F, C::Hasher>::new();\n\n\n\n // Observe the instance.\n\n challenger.observe_hash::<C::Hasher>(common_data.circuit_digest);\n\n challenger.observe_hash::<C::InnerHasher>(public_inputs_hash);\n\n\n", "file_path": "plonky2/src/plonk/get_challenges.rs", "rank": 49, "score": 301970.41805066203 }, { "content": "fn fri_committed_trees<F: RichField + Extendable<D>, C: GenericConfig<D, F = F>, const D: usize>(\n\n mut coeffs: PolynomialCoeffs<F::Extension>,\n\n mut values: PolynomialValues<F::Extension>,\n\n challenger: &mut Challenger<F, C::Hasher>,\n\n fri_params: &FriParams,\n\n) -> (\n\n Vec<MerkleTree<F, C::Hasher>>,\n\n PolynomialCoeffs<F::Extension>,\n\n)\n\nwhere\n\n [(); C::Hasher::HASH_SIZE]:,\n\n{\n\n let mut trees = Vec::new();\n\n\n\n let mut shift = F::MULTIPLICATIVE_GROUP_GENERATOR;\n\n for arity_bits in &fri_params.reduction_arity_bits {\n\n let arity = 1 << arity_bits;\n\n\n\n reverse_index_bits_in_place(&mut values.values);\n\n let chunked_values = values\n", "file_path": "plonky2/src/fri/prover.rs", "rank": 50, "score": 301970.41805066203 }, { "content": "#[derive(Clone, Debug)]\n\nstruct U32AddManyGenerator<F: RichField + Extendable<D>, const D: usize> {\n\n gate: U32AddManyGate<F, D>,\n\n gate_index: usize,\n\n i: usize,\n\n _phantom: PhantomData<F>,\n\n}\n\n\n\nimpl<F: RichField + Extendable<D>, const D: usize> SimpleGenerator<F>\n\n for U32AddManyGenerator<F, D>\n\n{\n\n fn dependencies(&self) -> Vec<Target> {\n\n let local_target = |input| Target::wire(self.gate_index, input);\n\n\n\n (0..self.gate.num_addends)\n\n .map(|j| local_target(self.gate.wire_ith_op_jth_addend(self.i, j)))\n\n .chain([local_target(self.gate.wire_ith_carry(self.i))])\n\n .collect()\n\n }\n\n\n\n fn run_once(&self, witness: &PartitionWitness<F>, out_buffer: &mut GeneratedValues<F>) {\n", "file_path": "plonky2/src/gates/add_many_u32.rs", "rank": 51, "score": 300393.6511077975 }, { "content": "pub trait PackedEvaluableBase<F: RichField + Extendable<D>, const D: usize>: Gate<F, D> {\n\n fn eval_unfiltered_base_packed<P: PackedField<Scalar = F>>(\n\n &self,\n\n vars_base: EvaluationVarsBasePacked<P>,\n\n yield_constr: StridedConstraintConsumer<P>,\n\n );\n\n\n\n /// Evaluates entire batch of points. Returns a matrix of constraints. Constraint `j` for point\n\n /// `i` is at `index j * batch_size + i`.\n\n fn eval_unfiltered_base_batch_packed(&self, vars_batch: EvaluationVarsBaseBatch<F>) -> Vec<F> {\n\n let mut res = vec![F::ZERO; vars_batch.len() * self.num_constraints()];\n\n let (vars_packed_iter, vars_leftovers_iter) = vars_batch.pack::<<F as Packable>::Packing>();\n\n let leftovers_start = vars_batch.len() - vars_leftovers_iter.len();\n\n for (i, vars_packed) in vars_packed_iter.enumerate() {\n\n self.eval_unfiltered_base_packed(\n\n vars_packed,\n\n StridedConstraintConsumer::new(\n\n &mut res[..],\n\n vars_batch.len(),\n\n <F as Packable>::Packing::WIDTH * i,\n", "file_path": "plonky2/src/gates/packed_util.rs", "rank": 52, "score": 299913.73022411607 }, { "content": "/// Utility function to check that all permutation data wrapped in `Option`s are `Some` iff\n\n/// the Stark uses a permutation argument.\n\nfn check_permutation_options<F: RichField + Extendable<D>, S: Stark<F, D>, const D: usize>(\n\n stark: &S,\n\n proof_with_pis: &StarkProofWithPublicInputsTarget<D>,\n\n challenges: &StarkProofChallengesTarget<D>,\n\n) -> Result<()> {\n\n let options_is_some = [\n\n proof_with_pis.proof.permutation_zs_cap.is_some(),\n\n proof_with_pis.proof.openings.permutation_zs.is_some(),\n\n proof_with_pis.proof.openings.permutation_zs_right.is_some(),\n\n challenges.permutation_challenge_sets.is_some(),\n\n ];\n\n ensure!(\n\n options_is_some\n\n .into_iter()\n\n .all(|b| b == stark.uses_permutation_args()),\n\n \"Permutation data doesn't match with Stark configuration.\"\n\n );\n\n Ok(())\n\n}\n", "file_path": "starky/src/recursive_verifier.rs", "rank": 53, "score": 299851.48635933653 }, { "content": "fn add_stark_opening_set<F: RichField + Extendable<D>, S: Stark<F, D>, const D: usize>(\n\n builder: &mut CircuitBuilder<F, D>,\n\n stark: S,\n\n config: &StarkConfig,\n\n) -> StarkOpeningSetTarget<D> {\n\n let num_challenges = config.num_challenges;\n\n StarkOpeningSetTarget {\n\n local_values: builder.add_virtual_extension_targets(S::COLUMNS),\n\n next_values: builder.add_virtual_extension_targets(S::COLUMNS),\n\n permutation_zs: stark\n\n .uses_permutation_args()\n\n .then(|| builder.add_virtual_extension_targets(stark.num_permutation_batches(config))),\n\n permutation_zs_right: stark\n\n .uses_permutation_args()\n\n .then(|| builder.add_virtual_extension_targets(stark.num_permutation_batches(config))),\n\n quotient_polys: builder\n\n .add_virtual_extension_targets(stark.quotient_degree_factor() * num_challenges),\n\n }\n\n}\n\n\n", "file_path": "starky/src/recursive_verifier.rs", "rank": 54, "score": 296803.2001855734 }, { "content": "/// Elementwise inplace multiplication of two slices of field elements.\n\n/// Implementation be faster than the trivial for loop.\n\npub fn batch_multiply_inplace<F: Field>(out: &mut [F], a: &[F]) {\n\n let n = out.len();\n\n assert_eq!(n, a.len(), \"both arrays must have the same length\");\n\n\n\n // Split out slice of vectors, leaving leftovers as scalars\n\n let (out_packed, out_leftovers) =\n\n pack_slice_with_leftovers_mut::<<F as Packable>::Packing>(out);\n\n let (a_packed, a_leftovers) = pack_slice_with_leftovers::<<F as Packable>::Packing>(a);\n\n\n\n // Multiply packed and the leftovers\n\n for (x_out, x_a) in out_packed.iter_mut().zip(a_packed) {\n\n *x_out *= *x_a;\n\n }\n\n for (x_out, x_a) in out_leftovers.iter_mut().zip(a_leftovers) {\n\n *x_out *= *x_a;\n\n }\n\n}\n\n\n", "file_path": "field/src/batch_util.rs", "rank": 55, "score": 296661.3669030666 }, { "content": "/// Elementwise inplace addition of two slices of field elements.\n\n/// Implementation be faster than the trivial for loop.\n\npub fn batch_add_inplace<F: Field>(out: &mut [F], a: &[F]) {\n\n let n = out.len();\n\n assert_eq!(n, a.len(), \"both arrays must have the same length\");\n\n\n\n // Split out slice of vectors, leaving leftovers as scalars\n\n let (out_packed, out_leftovers) =\n\n pack_slice_with_leftovers_mut::<<F as Packable>::Packing>(out);\n\n let (a_packed, a_leftovers) = pack_slice_with_leftovers::<<F as Packable>::Packing>(a);\n\n\n\n // Add packed and the leftovers\n\n for (x_out, x_a) in out_packed.iter_mut().zip(a_packed) {\n\n *x_out += *x_a;\n\n }\n\n for (x_out, x_a) in out_leftovers.iter_mut().zip(a_leftovers) {\n\n *x_out += *x_a;\n\n }\n\n}\n", "file_path": "field/src/batch_util.rs", "rank": 56, "score": 296661.3669030666 }, { "content": "#[derive(Debug)]\n\nstruct NonNativeMultiplicationGenerator<F: RichField + Extendable<D>, const D: usize, FF: Field> {\n\n a: NonNativeTarget<FF>,\n\n b: NonNativeTarget<FF>,\n\n prod: NonNativeTarget<FF>,\n\n overflow: BigUintTarget,\n\n _phantom: PhantomData<F>,\n\n}\n\n\n\nimpl<F: RichField + Extendable<D>, const D: usize, FF: PrimeField> SimpleGenerator<F>\n\n for NonNativeMultiplicationGenerator<F, D, FF>\n\n{\n\n fn dependencies(&self) -> Vec<Target> {\n\n self.a\n\n .value\n\n .limbs\n\n .iter()\n\n .cloned()\n\n .chain(self.b.value.limbs.clone())\n\n .map(|l| l.0)\n\n .collect()\n", "file_path": "plonky2/src/gadgets/nonnative.rs", "rank": 57, "score": 293641.0526311946 }, { "content": "#[derive(Debug)]\n\nstruct NonNativeSubtractionGenerator<F: RichField + Extendable<D>, const D: usize, FF: Field> {\n\n a: NonNativeTarget<FF>,\n\n b: NonNativeTarget<FF>,\n\n diff: NonNativeTarget<FF>,\n\n overflow: BoolTarget,\n\n _phantom: PhantomData<F>,\n\n}\n\n\n\nimpl<F: RichField + Extendable<D>, const D: usize, FF: PrimeField> SimpleGenerator<F>\n\n for NonNativeSubtractionGenerator<F, D, FF>\n\n{\n\n fn dependencies(&self) -> Vec<Target> {\n\n self.a\n\n .value\n\n .limbs\n\n .iter()\n\n .cloned()\n\n .chain(self.b.value.limbs.clone())\n\n .map(|l| l.0)\n\n .collect()\n", "file_path": "plonky2/src/gadgets/nonnative.rs", "rank": 58, "score": 293641.0526311946 }, { "content": "#[derive(Debug)]\n\nstruct NonNativeAdditionGenerator<F: RichField + Extendable<D>, const D: usize, FF: PrimeField> {\n\n a: NonNativeTarget<FF>,\n\n b: NonNativeTarget<FF>,\n\n sum: NonNativeTarget<FF>,\n\n overflow: BoolTarget,\n\n _phantom: PhantomData<F>,\n\n}\n\n\n\nimpl<F: RichField + Extendable<D>, const D: usize, FF: PrimeField> SimpleGenerator<F>\n\n for NonNativeAdditionGenerator<F, D, FF>\n\n{\n\n fn dependencies(&self) -> Vec<Target> {\n\n self.a\n\n .value\n\n .limbs\n\n .iter()\n\n .cloned()\n\n .chain(self.b.value.limbs.clone())\n\n .map(|l| l.0)\n\n .collect()\n", "file_path": "plonky2/src/gadgets/nonnative.rs", "rank": 59, "score": 290421.1867961203 }, { "content": "#[derive(Debug)]\n\nstruct NonNativeInverseGenerator<F: RichField + Extendable<D>, const D: usize, FF: PrimeField> {\n\n x: NonNativeTarget<FF>,\n\n inv: BigUintTarget,\n\n div: BigUintTarget,\n\n _phantom: PhantomData<F>,\n\n}\n\n\n\nimpl<F: RichField + Extendable<D>, const D: usize, FF: PrimeField> SimpleGenerator<F>\n\n for NonNativeInverseGenerator<F, D, FF>\n\n{\n\n fn dependencies(&self) -> Vec<Target> {\n\n self.x.value.limbs.iter().map(|&l| l.0).collect()\n\n }\n\n\n\n fn run_once(&self, witness: &PartitionWitness<F>, out_buffer: &mut GeneratedValues<F>) {\n\n let x = witness.get_nonnative_target(self.x.clone());\n\n let inv = x.inverse();\n\n\n\n let x_biguint = x.to_canonical_biguint();\n\n let inv_biguint = inv.to_canonical_biguint();\n", "file_path": "plonky2/src/gadgets/nonnative.rs", "rank": 60, "score": 290421.1867961203 }, { "content": "/// A custom gate.\n\npub trait Gate<F: RichField + Extendable<D>, const D: usize>: 'static + Send + Sync {\n\n fn id(&self) -> String;\n\n\n\n fn eval_unfiltered(&self, vars: EvaluationVars<F, D>) -> Vec<F::Extension>;\n\n\n\n /// Like `eval_unfiltered`, but specialized for points in the base field.\n\n ///\n\n ///\n\n /// `eval_unfiltered_base_batch` calls this method by default. If `eval_unfiltered_base_batch`\n\n /// is overridden, then `eval_unfiltered_base_one` is not necessary.\n\n ///\n\n /// By default, this just calls `eval_unfiltered`, which treats the point as an extension field\n\n /// element. This isn't very efficient.\n\n fn eval_unfiltered_base_one(\n\n &self,\n\n vars_base: EvaluationVarsBase<F>,\n\n mut yield_constr: StridedConstraintConsumer<F>,\n\n ) {\n\n // Note that this method uses `yield_constr` instead of returning its constraints.\n\n // `yield_constr` abstracts out the underlying memory layout.\n", "file_path": "plonky2/src/gates/gate.rs", "rank": 61, "score": 288927.26167920354 }, { "content": "#[derive(Debug)]\n\nstruct NonNativeMultipleAddsGenerator<F: RichField + Extendable<D>, const D: usize, FF: PrimeField>\n\n{\n\n summands: Vec<NonNativeTarget<FF>>,\n\n sum: NonNativeTarget<FF>,\n\n overflow: U32Target,\n\n _phantom: PhantomData<F>,\n\n}\n\n\n\nimpl<F: RichField + Extendable<D>, const D: usize, FF: PrimeField> SimpleGenerator<F>\n\n for NonNativeMultipleAddsGenerator<F, D, FF>\n\n{\n\n fn dependencies(&self) -> Vec<Target> {\n\n self.summands\n\n .iter()\n\n .flat_map(|summand| summand.value.limbs.iter().map(|limb| limb.0))\n\n .collect()\n\n }\n\n\n\n fn run_once(&self, witness: &PartitionWitness<F>, out_buffer: &mut GeneratedValues<F>) {\n\n let summands: Vec<_> = self\n", "file_path": "plonky2/src/gadgets/nonnative.rs", "rank": 62, "score": 287306.5274746074 }, { "content": "fn mds_layer<F, FE, P, const D: usize>(mut state: [P; SPONGE_WIDTH]) -> [P; SPONGE_WIDTH]\n\nwhere\n\n F: Poseidon,\n\n FE: FieldExtension<D, BaseField = F>,\n\n P: PackedField<Scalar = FE>,\n\n{\n\n for i in 0..P::WIDTH {\n\n let mut unpacked_state = [P::Scalar::default(); SPONGE_WIDTH];\n\n for j in 0..SPONGE_WIDTH {\n\n unpacked_state[j] = state[j].as_slice()[i];\n\n }\n\n unpacked_state = F::mds_layer_field(&unpacked_state);\n\n for j in 0..SPONGE_WIDTH {\n\n state[j].as_slice_mut()[i] = unpacked_state[j];\n\n }\n\n }\n\n state\n\n}\n\n\n\npub(crate) fn generate_permutation_unit<F: Poseidon>(values: &mut [F; NUM_COLUMNS]) {\n", "file_path": "system_zero/src/permutation_unit.rs", "rank": 63, "score": 271977.19846427167 }, { "content": "pub trait Extendable<const D: usize>: Field + Sized {\n\n type Extension: Field + OEF<D, BaseField = Self> + Frobenius<D> + From<Self>;\n\n\n\n const W: Self;\n\n\n\n const DTH_ROOT: Self;\n\n\n\n /// Chosen so that when raised to the power `(p^D - 1) >> F::Extension::TWO_ADICITY)`\n\n /// we obtain F::EXT_POWER_OF_TWO_GENERATOR.\n\n const EXT_MULTIPLICATIVE_GROUP_GENERATOR: [Self; D];\n\n\n\n /// Chosen so that when raised to the power `1<<(Self::TWO_ADICITY-Self::BaseField::TWO_ADICITY)`,\n\n /// we get `Self::BaseField::POWER_OF_TWO_GENERATOR`. This makes `primitive_root_of_unity` coherent\n\n /// with the base field which implies that the FFT commutes with field inclusion.\n\n const EXT_POWER_OF_TWO_GENERATOR: [Self; D];\n\n}\n\n\n\nimpl<F: Field + Frobenius<1> + FieldExtension<1, BaseField = F>> Extendable<1> for F {\n\n type Extension = F;\n\n const W: Self = F::ZERO;\n\n const DTH_ROOT: Self = F::ZERO;\n\n const EXT_MULTIPLICATIVE_GROUP_GENERATOR: [Self; 1] = [F::MULTIPLICATIVE_GROUP_GENERATOR];\n\n const EXT_POWER_OF_TWO_GENERATOR: [Self; 1] = [F::POWER_OF_TWO_GENERATOR];\n\n}\n\n\n", "file_path": "field/src/extension_field/mod.rs", "rank": 64, "score": 269974.9522526124 }, { "content": "/// A one-way compression function which takes two ~256 bit inputs and returns a ~256 bit output.\n\npub fn compress<F: RichField, P: PlonkyPermutation<F>>(x: HashOut<F>, y: HashOut<F>) -> HashOut<F> {\n\n let mut perm_inputs = [F::ZERO; SPONGE_WIDTH];\n\n perm_inputs[..4].copy_from_slice(&x.elements);\n\n perm_inputs[4..8].copy_from_slice(&y.elements);\n\n HashOut {\n\n elements: P::permute(perm_inputs)[..4].try_into().unwrap(),\n\n }\n\n}\n\n\n", "file_path": "plonky2/src/hash/hashing.rs", "rank": 65, "score": 260158.9848977289 }, { "content": "/// Interpolate the linear polynomial passing through `points` on `x`.\n\npub fn interpolate2<F: Field>(points: [(F, F); 2], x: F) -> F {\n\n // a0 -> a1\n\n // b0 -> b1\n\n // x -> a1 + (x-a0)*(b1-a1)/(b0-a0)\n\n let (a0, a1) = points[0];\n\n let (b0, b1) = points[1];\n\n assert_ne!(a0, b0);\n\n a1 + (x - a0) * (b1 - a1) / (b0 - a0)\n\n}\n\n\n\n#[cfg(test)]\n\nmod tests {\n\n use super::*;\n\n use crate::extension_field::quartic::QuarticExtension;\n\n use crate::field_types::Field;\n\n use crate::goldilocks_field::GoldilocksField;\n\n use crate::polynomial::PolynomialCoeffs;\n\n\n\n #[test]\n\n fn interpolant_random() {\n", "file_path": "field/src/interpolation.rs", "rank": 66, "score": 260059.77337616804 }, { "content": "pub fn fft_root_table<F: Field>(n: usize) -> FftRootTable<F> {\n\n let lg_n = log2_strict(n);\n\n // bases[i] = g^2^i, for i = 0, ..., lg_n - 1\n\n let mut bases = Vec::with_capacity(lg_n);\n\n let mut base = F::primitive_root_of_unity(lg_n);\n\n bases.push(base);\n\n for _ in 1..lg_n {\n\n base = base.square(); // base = g^2^_\n\n bases.push(base);\n\n }\n\n\n\n let mut root_table = Vec::with_capacity(lg_n);\n\n for lg_m in 1..=lg_n {\n\n let half_m = 1 << (lg_m - 1);\n\n let base = bases[lg_n - lg_m];\n\n let root_row = base.powers().take(half_m.max(2)).collect();\n\n root_table.push(root_row);\n\n }\n\n root_table\n\n}\n\n\n", "file_path": "field/src/fft.rs", "rank": 67, "score": 258753.89455499972 }, { "content": "/// Interpolate the polynomial defined by an arbitrary set of (point, value) pairs at the given\n\n/// point `x`.\n\npub fn interpolate<F: Field>(points: &[(F, F)], x: F, barycentric_weights: &[F]) -> F {\n\n // If x is in the list of points, the Lagrange formula would divide by zero.\n\n for &(x_i, y_i) in points {\n\n if x_i == x {\n\n return y_i;\n\n }\n\n }\n\n\n\n let l_x: F = points.iter().map(|&(x_i, _y_i)| x - x_i).product();\n\n\n\n let sum = (0..points.len())\n\n .map(|i| {\n\n let x_i = points[i].0;\n\n let y_i = points[i].1;\n\n let w_i = barycentric_weights[i];\n\n w_i / (x - x_i) * y_i\n\n })\n\n .sum();\n\n\n\n l_x * sum\n\n}\n\n\n", "file_path": "field/src/interpolation.rs", "rank": 68, "score": 254716.18863705083 }, { "content": "/// A generator participates in the generation of the witness.\n\npub trait WitnessGenerator<F: Field>: 'static + Send + Sync + Debug {\n\n /// Targets to be \"watched\" by this generator. Whenever a target in the watch list is populated,\n\n /// the generator will be queued to run.\n\n fn watch_list(&self) -> Vec<Target>;\n\n\n\n /// Run this generator, returning a flag indicating whether the generator is finished. If the\n\n /// flag is true, the generator will never be run again, otherwise it will be queued for another\n\n /// run next time a target in its watch list is populated.\n\n fn run(&self, witness: &PartitionWitness<F>, out_buffer: &mut GeneratedValues<F>) -> bool;\n\n}\n\n\n\n/// Values generated by a generator invocation.\n\n#[derive(Debug)]\n\npub struct GeneratedValues<F: Field> {\n\n pub(crate) target_values: Vec<(Target, F)>,\n\n}\n\n\n\nimpl<F: Field> From<Vec<(Target, F)>> for GeneratedValues<F> {\n\n fn from(target_values: Vec<(Target, F)>) -> Self {\n\n Self { target_values }\n", "file_path": "plonky2/src/iop/generator.rs", "rank": 69, "score": 249067.97958495846 }, { "content": "fn get_challenges<F, C, S, const D: usize>(\n\n stark: &S,\n\n trace_cap: &MerkleCap<F, C::Hasher>,\n\n permutation_zs_cap: Option<&MerkleCap<F, C::Hasher>>,\n\n quotient_polys_cap: &MerkleCap<F, C::Hasher>,\n\n openings: &StarkOpeningSet<F, D>,\n\n commit_phase_merkle_caps: &[MerkleCap<F, C::Hasher>],\n\n final_poly: &PolynomialCoeffs<F::Extension>,\n\n pow_witness: F,\n\n config: &StarkConfig,\n\n degree_bits: usize,\n\n) -> StarkProofChallenges<F, D>\n\nwhere\n\n F: RichField + Extendable<D>,\n\n C: GenericConfig<D, F = F>,\n\n S: Stark<F, D>,\n\n{\n\n let num_challenges = config.num_challenges;\n\n\n\n let mut challenger = Challenger::<F, C::Hasher>::new();\n", "file_path": "starky/src/get_challenges.rs", "rank": 70, "score": 248769.3028605272 }, { "content": "/// Hash a message without any padding step. Note that this can enable length-extension attacks.\n\n/// However, it is still collision-resistant in cases where the input has a fixed length.\n\npub fn hash_n_to_m_no_pad<F: RichField, P: PlonkyPermutation<F>>(\n\n inputs: &[F],\n\n num_outputs: usize,\n\n) -> Vec<F> {\n\n let mut state = [F::ZERO; SPONGE_WIDTH];\n\n\n\n // Absorb all input chunks.\n\n for input_chunk in inputs.chunks(SPONGE_RATE) {\n\n state[..input_chunk.len()].copy_from_slice(input_chunk);\n\n state = P::permute(state);\n\n }\n\n\n\n // Squeeze until we have the desired number of outputs.\n\n let mut outputs = Vec::new();\n\n loop {\n\n for &item in state.iter().take(SPONGE_RATE) {\n\n outputs.push(item);\n\n if outputs.len() == num_outputs {\n\n return outputs;\n\n }\n\n }\n\n state = P::permute(state);\n\n }\n\n}\n\n\n", "file_path": "plonky2/src/hash/hashing.rs", "rank": 71, "score": 247538.8728573867 }, { "content": "fn constant_layer<F, FE, P, const D: usize>(\n\n mut state: [P; SPONGE_WIDTH],\n\n round: usize,\n\n) -> [P; SPONGE_WIDTH]\n\nwhere\n\n F: Poseidon,\n\n FE: FieldExtension<D, BaseField = F>,\n\n P: PackedField<Scalar = FE>,\n\n{\n\n // One day I might actually vectorize this, but today is not that day.\n\n for i in 0..P::WIDTH {\n\n let mut unpacked_state = [P::Scalar::default(); SPONGE_WIDTH];\n\n for j in 0..SPONGE_WIDTH {\n\n unpacked_state[j] = state[j].as_slice()[i];\n\n }\n\n F::constant_layer_field(&mut unpacked_state, round);\n\n for j in 0..SPONGE_WIDTH {\n\n state[j].as_slice_mut()[i] = unpacked_state[j];\n\n }\n\n }\n\n state\n\n}\n\n\n", "file_path": "system_zero/src/permutation_unit.rs", "rank": 72, "score": 245592.9765455051 }, { "content": "pub fn hash_n_to_hash_no_pad<F: RichField, P: PlonkyPermutation<F>>(inputs: &[F]) -> HashOut<F> {\n\n HashOut::from_vec(hash_n_to_m_no_pad::<F, P>(inputs, 4))\n\n}\n", "file_path": "plonky2/src/hash/hashing.rs", "rank": 73, "score": 241909.57914486335 }, { "content": "/// Computes the quotient polynomials `(sum alpha^i C_i(x)) / Z_H(x)` for `alpha` in `alphas`,\n\n/// where the `C_i`s are the Stark constraints.\n\nfn compute_quotient_polys<'a, F, P, C, S, const D: usize>(\n\n stark: &S,\n\n trace_commitment: &'a PolynomialBatch<F, C, D>,\n\n permutation_zs_commitment_challenges: &'a Option<(\n\n PolynomialBatch<F, C, D>,\n\n Vec<PermutationChallengeSet<F>>,\n\n )>,\n\n public_inputs: [F; S::PUBLIC_INPUTS],\n\n alphas: Vec<F>,\n\n degree_bits: usize,\n\n config: &StarkConfig,\n\n) -> Vec<PolynomialCoeffs<F>>\n\nwhere\n\n F: RichField + Extendable<D>,\n\n P: PackedField<Scalar = F>,\n\n C: GenericConfig<D, F = F>,\n\n S: Stark<F, D>,\n\n [(); S::COLUMNS]:,\n\n [(); S::PUBLIC_INPUTS]:,\n\n [(); P::WIDTH]:,\n", "file_path": "starky/src/prover.rs", "rank": 74, "score": 240583.4303374316 }, { "content": "/// Evaluate the Lagrange polynomials `L_1` and `L_n` at a point `x`.\n\n/// `L_1(x) = (x^n - 1)/(n * (x - 1))`\n\n/// `L_n(x) = (x^n - 1)/(n * (g * x - 1))`, with `g` the first element of the subgroup.\n\nfn eval_l_1_and_l_last<F: Field>(log_n: usize, x: F) -> (F, F) {\n\n let n = F::from_canonical_usize(1 << log_n);\n\n let g = F::primitive_root_of_unity(log_n);\n\n let z_x = x.exp_power_of_2(log_n) - F::ONE;\n\n let invs = F::batch_multiplicative_inverse(&[n * (x - F::ONE), n * (g * x - F::ONE)]);\n\n\n\n (z_x * invs[0], z_x * invs[1])\n\n}\n\n\n", "file_path": "starky/src/verifier.rs", "rank": 75, "score": 236972.7544063938 }, { "content": "/// Computes the unique degree < n interpolant of an arbitrary list of n (point, value) pairs.\n\n///\n\n/// Note that the implementation assumes that `F` is two-adic, in particular that\n\n/// `2^{F::TWO_ADICITY} >= points.len()`. This leads to a simple FFT-based implementation.\n\npub fn interpolant<F: Field>(points: &[(F, F)]) -> PolynomialCoeffs<F> {\n\n let n = points.len();\n\n let n_log = log2_ceil(n);\n\n\n\n let subgroup = F::two_adic_subgroup(n_log);\n\n let barycentric_weights = barycentric_weights(points);\n\n let subgroup_evals = subgroup\n\n .into_iter()\n\n .map(|x| interpolate(points, x, &barycentric_weights))\n\n .collect();\n\n\n\n let mut coeffs = ifft(PolynomialValues {\n\n values: subgroup_evals,\n\n });\n\n coeffs.trim();\n\n coeffs\n\n}\n\n\n", "file_path": "field/src/interpolation.rs", "rank": 76, "score": 232177.43306996196 }, { "content": "pub fn barycentric_weights<F: Field>(points: &[(F, F)]) -> Vec<F> {\n\n let n = points.len();\n\n F::batch_multiplicative_inverse(\n\n &(0..n)\n\n .map(|i| {\n\n (0..n)\n\n .filter(|&j| j != i)\n\n .map(|j| points[i].0 - points[j].0)\n\n .product::<F>()\n\n })\n\n .collect::<Vec<_>>(),\n\n )\n\n}\n\n\n", "file_path": "field/src/interpolation.rs", "rank": 77, "score": 232171.98982156703 }, { "content": "/// Flatten the slice by sending every extension target to its D-sized canonical representation.\n\npub fn flatten_target<const D: usize>(l: &[ExtensionTarget<D>]) -> Vec<Target> {\n\n l.iter()\n\n .flat_map(|x| x.to_target_array().to_vec())\n\n .collect()\n\n}\n\n\n", "file_path": "plonky2/src/iop/ext_target.rs", "rank": 78, "score": 230104.65120674018 }, { "content": "pub fn salt_size(salted: bool) -> usize {\n\n if salted {\n\n SALT_SIZE\n\n } else {\n\n 0\n\n }\n\n}\n\n\n\n/// Evaluate the polynomial which vanishes on any multiplicative subgroup of a given order `n`.\n\npub(crate) fn eval_zero_poly<F: Field>(n: usize, x: F) -> F {\n\n // Z(x) = x^n - 1\n\n x.exp_u64(n as u64) - F::ONE\n\n}\n\n\n\n/// Evaluate the Lagrange basis `L_1` with `L_1(1) = 1`, and `L_1(x) = 0` for other members of an\n\n/// order `n` multiplicative subgroup.\n\npub(crate) fn eval_l_1<F: Field>(n: usize, x: F) -> F {\n\n if x.is_one() {\n\n // The code below would divide by zero, since we have (x - 1) in both the numerator and\n\n // denominator.\n", "file_path": "plonky2/src/plonk/plonk_common.rs", "rank": 79, "score": 229185.37666261487 }, { "content": "#[inline]\n\npub fn fft<F: Field>(poly: PolynomialCoeffs<F>) -> PolynomialValues<F> {\n\n fft_with_options(poly, None, None)\n\n}\n\n\n", "file_path": "field/src/fft.rs", "rank": 80, "score": 224550.36797339242 }, { "content": "#[inline]\n\npub fn ifft<F: Field>(poly: PolynomialValues<F>) -> PolynomialCoeffs<F> {\n\n ifft_with_options(poly, None, None)\n\n}\n\n\n", "file_path": "field/src/fft.rs", "rank": 81, "score": 224550.36797339242 }, { "content": "#[inline]\n\npub fn fft_with_options<F: Field>(\n\n poly: PolynomialCoeffs<F>,\n\n zero_factor: Option<usize>,\n\n root_table: Option<&FftRootTable<F>>,\n\n) -> PolynomialValues<F> {\n\n let PolynomialCoeffs { coeffs: mut buffer } = poly;\n\n fft_dispatch(&mut buffer, zero_factor, root_table);\n\n PolynomialValues { values: buffer }\n\n}\n\n\n", "file_path": "field/src/fft.rs", "rank": 82, "score": 224062.59014273487 }, { "content": "pub fn ifft_with_options<F: Field>(\n\n poly: PolynomialValues<F>,\n\n zero_factor: Option<usize>,\n\n root_table: Option<&FftRootTable<F>>,\n\n) -> PolynomialCoeffs<F> {\n\n let n = poly.len();\n\n let lg_n = log2_strict(n);\n\n let n_inv = F::inverse_2exp(lg_n);\n\n\n\n let PolynomialValues { values: mut buffer } = poly;\n\n fft_dispatch(&mut buffer, zero_factor, root_table);\n\n\n\n // We reverse all values except the first, and divide each by n.\n\n buffer[0] *= n_inv;\n\n buffer[n / 2] *= n_inv;\n\n for i in 1..(n / 2) {\n\n let j = n - i;\n\n let coeffs_i = buffer[j] * n_inv;\n\n let coeffs_j = buffer[i] * n_inv;\n\n buffer[i] = coeffs_i;\n\n buffer[j] = coeffs_j;\n\n }\n\n PolynomialCoeffs { coeffs: buffer }\n\n}\n\n\n\n/// Generic FFT implementation that works with both scalar and packed inputs.\n", "file_path": "field/src/fft.rs", "rank": 83, "score": 224062.59014273487 }, { "content": "pub fn transpose<F: Field>(matrix: &[Vec<F>]) -> Vec<Vec<F>> {\n\n let l = matrix.len();\n\n let w = matrix[0].len();\n\n\n\n let mut transposed = vec![vec![]; w];\n\n for i in 0..w {\n\n transposed[i].reserve_exact(l);\n\n unsafe {\n\n // After .reserve_exact(l), transposed[i] will have capacity at least l. Hence, set_len\n\n // will not cause the buffer to overrun.\n\n transposed[i].set_len(l);\n\n }\n\n }\n\n\n\n // Optimization: ensure the larger loop is outside.\n\n if w >= l {\n\n for i in 0..w {\n\n for j in 0..l {\n\n transposed[i][j] = matrix[j][i];\n\n }\n", "file_path": "plonky2/src/util/mod.rs", "rank": 84, "score": 222513.3475106777 }, { "content": "/// Given an input column and a table column, generate the permuted input and permuted table columns\n\n/// used in the Halo2 permutation argument.\n\npub fn permuted_cols<F: PrimeField64>(inputs: &[F], table: &[F]) -> (Vec<F>, Vec<F>) {\n\n let n = inputs.len();\n\n\n\n // The permuted inputs do not have to be ordered, but we found that sorting was faster than\n\n // hash-based grouping. We also sort the table, as this helps us identify \"unused\" table\n\n // elements efficiently.\n\n\n\n // To compare elements, e.g. for sorting, we first need them in canonical form. It would be\n\n // wasteful to canonicalize in each comparison, as a single element may be involved in many\n\n // comparisons. So we will canonicalize once upfront, then use `to_noncanonical_u64` when\n\n // comparing elements.\n\n\n\n let sorted_inputs = inputs\n\n .iter()\n\n .map(|x| x.to_canonical())\n\n .sorted_unstable_by_key(|x| x.to_noncanonical_u64())\n\n .collect_vec();\n\n let sorted_table = table\n\n .iter()\n\n .map(|x| x.to_canonical())\n", "file_path": "system_zero/src/lookup.rs", "rank": 85, "score": 221521.95161000532 }, { "content": "pub fn reverse_index_bits_in_place<T>(arr: &mut [T]) {\n\n let n = arr.len();\n\n let lb_n = log2_strict(n);\n\n // If the whole array fits in fast cache, then the trivial algorithm is cache friendly. Also, if\n\n // `T` is really big, then the trivial algorithm is cache-friendly, no matter the size of the\n\n // array.\n\n if size_of::<T>() << lb_n <= SMALL_ARR_SIZE || size_of::<T>() >= BIG_T_SIZE {\n\n unsafe {\n\n reverse_index_bits_in_place_small(arr, lb_n);\n\n }\n\n } else {\n\n debug_assert!(n >= 4); // By our choice of `BIG_T_SIZE` and `SMALL_ARR_SIZE`.\n\n\n\n // Algorithm:\n\n //\n\n // Treat `arr` as a `sqrt(n)` by `sqrt(n)` row-major matrix. (Assume for now that `lb_n` is\n\n // even, i.e., `n` is a square number.) To perform bit-order reversal we:\n\n // 1. Bit-reverse the order of the rows. (They are contiguous in memory, so this is\n\n // basically a series of large `memcpy`s.)\n\n // 2. Transpose the matrix.\n", "file_path": "util/src/lib.rs", "rank": 86, "score": 211386.31566410244 }, { "content": "/// A witness holds information on the values of targets in a circuit.\n\npub trait Witness<F: Field> {\n\n fn try_get_target(&self, target: Target) -> Option<F>;\n\n\n\n fn set_target(&mut self, target: Target, value: F);\n\n\n\n fn get_target(&self, target: Target) -> F {\n\n self.try_get_target(target).unwrap()\n\n }\n\n\n\n fn get_targets(&self, targets: &[Target]) -> Vec<F> {\n\n targets.iter().map(|&t| self.get_target(t)).collect()\n\n }\n\n\n\n fn get_extension_target<const D: usize>(&self, et: ExtensionTarget<D>) -> F::Extension\n\n where\n\n F: RichField + Extendable<D>,\n\n {\n\n F::Extension::from_basefield_array(\n\n self.get_targets(&et.to_target_array()).try_into().unwrap(),\n\n )\n", "file_path": "plonky2/src/iop/witness.rs", "rank": 87, "score": 209864.4331781848 }, { "content": "#[inline(always)]\n\nfn safe_iteration(f: &mut u64, g: &mut u64, c: &mut i128, d: &mut i128, k: &mut u32) {\n\n if f < g {\n\n std::mem::swap(f, g);\n\n std::mem::swap(c, d);\n\n }\n\n if *f & 3 == *g & 3 {\n\n // f - g = 0 (mod 4)\n\n *f -= *g;\n\n *c -= *d;\n\n\n\n // kk >= 2 because f is now 0 (mod 4).\n\n let kk = f.trailing_zeros();\n\n *f >>= kk;\n\n *d <<= kk;\n\n *k += kk;\n\n } else {\n\n // f + g = 0 (mod 4)\n\n *f = (*f >> 2) + (*g >> 2) + 1u64;\n\n *c += *d;\n\n let kk = f.trailing_zeros();\n", "file_path": "field/src/inversion.rs", "rank": 88, "score": 207475.752016372 }, { "content": "/// A generator which runs once after a list of dependencies is present in the witness.\n\npub trait SimpleGenerator<F: Field>: 'static + Send + Sync + Debug {\n\n fn dependencies(&self) -> Vec<Target>;\n\n\n\n fn run_once(&self, witness: &PartitionWitness<F>, out_buffer: &mut GeneratedValues<F>);\n\n\n\n fn adapter(self) -> SimpleGeneratorAdapter<F, Self>\n\n where\n\n Self: Sized,\n\n {\n\n SimpleGeneratorAdapter {\n\n inner: self,\n\n _phantom: PhantomData,\n\n }\n\n }\n\n}\n\n\n\n#[derive(Debug)]\n\npub struct SimpleGeneratorAdapter<F: Field, SG: SimpleGenerator<F> + ?Sized> {\n\n _phantom: PhantomData<F>,\n\n inner: SG,\n", "file_path": "plonky2/src/iop/generator.rs", "rank": 89, "score": 206583.48629244574 }, { "content": "#[must_use]\n\npub fn log2_ceil(n: usize) -> usize {\n\n (usize::BITS - n.saturating_sub(1).leading_zeros()) as usize\n\n}\n\n\n", "file_path": "util/src/lib.rs", "rank": 90, "score": 204236.61473374141 }, { "content": "/// Computes `log_2(n)`, panicking if `n` is not a power of two.\n\npub fn log2_strict(n: usize) -> usize {\n\n let res = n.trailing_zeros();\n\n assert!(n.wrapping_shr(res) == 1, \"Not a power of two: {}\", n);\n\n // Tell the optimizer about the semantics of `log2_strict`. i.e. it can replace `n` with\n\n // `1 << res` and vice versa.\n\n assume(n == 1 << res);\n\n res as usize\n\n}\n\n\n", "file_path": "util/src/lib.rs", "rank": 91, "score": 204231.02179897117 }, { "content": "#[derive(Debug)]\n\nstruct ReducingGenerator<const D: usize> {\n\n gate_index: usize,\n\n gate: ReducingGate<D>,\n\n}\n\n\n\nimpl<F: RichField + Extendable<D>, const D: usize> SimpleGenerator<F> for ReducingGenerator<D> {\n\n fn dependencies(&self) -> Vec<Target> {\n\n ReducingGate::<D>::wires_alpha()\n\n .chain(ReducingGate::<D>::wires_old_acc())\n\n .chain(self.gate.wires_coeffs())\n\n .map(|i| Target::wire(self.gate_index, i))\n\n .collect()\n\n }\n\n\n\n fn run_once(&self, witness: &PartitionWitness<F>, out_buffer: &mut GeneratedValues<F>) {\n\n let extract_extension = |range: Range<usize>| -> F::Extension {\n\n let t = ExtensionTarget::from_range(self.gate_index, range);\n\n witness.get_extension_target(t)\n\n };\n\n\n", "file_path": "plonky2/src/gates/reducing.rs", "rank": 92, "score": 200254.45518863964 }, { "content": "#[derive(Debug)]\n\nstruct ReducingGenerator<const D: usize> {\n\n gate_index: usize,\n\n gate: ReducingExtensionGate<D>,\n\n}\n\n\n\nimpl<F: RichField + Extendable<D>, const D: usize> SimpleGenerator<F> for ReducingGenerator<D> {\n\n fn dependencies(&self) -> Vec<Target> {\n\n ReducingExtensionGate::<D>::wires_alpha()\n\n .chain(ReducingExtensionGate::<D>::wires_old_acc())\n\n .chain((0..self.gate.num_coeffs).flat_map(ReducingExtensionGate::<D>::wires_coeff))\n\n .map(|i| Target::wire(self.gate_index, i))\n\n .collect()\n\n }\n\n\n\n fn run_once(&self, witness: &PartitionWitness<F>, out_buffer: &mut GeneratedValues<F>) {\n\n let local_extension = |range: Range<usize>| -> F::Extension {\n\n let t = ExtensionTarget::from_range(self.gate_index, range);\n\n witness.get_extension_target(t)\n\n };\n\n\n", "file_path": "plonky2/src/gates/reducing_extension.rs", "rank": 93, "score": 197574.89433422312 }, { "content": "#[derive(Clone, Debug)]\n\nstruct PoseidonMdsGenerator<const D: usize> {\n\n gate_index: usize,\n\n}\n\n\n\nimpl<F: RichField + Extendable<D> + Poseidon, const D: usize> SimpleGenerator<F>\n\n for PoseidonMdsGenerator<D>\n\n{\n\n fn dependencies(&self) -> Vec<Target> {\n\n (0..SPONGE_WIDTH)\n\n .flat_map(|i| {\n\n Target::wires_from_range(self.gate_index, PoseidonMdsGate::<F, D>::wires_input(i))\n\n })\n\n .collect()\n\n }\n\n\n\n fn run_once(&self, witness: &PartitionWitness<F>, out_buffer: &mut GeneratedValues<F>) {\n\n let get_local_get_target =\n\n |wire_range| ExtensionTarget::from_range(self.gate_index, wire_range);\n\n let get_local_ext =\n\n |wire_range| witness.get_extension_target(get_local_get_target(wire_range));\n", "file_path": "plonky2/src/gates/poseidon_mds.rs", "rank": 94, "score": 195003.56407596095 }, { "content": "#[derive(Debug)]\n\nstruct QuotientGeneratorExtension<const D: usize> {\n\n numerator: ExtensionTarget<D>,\n\n denominator: ExtensionTarget<D>,\n\n quotient: ExtensionTarget<D>,\n\n}\n\n\n\nimpl<F: RichField + Extendable<D>, const D: usize> SimpleGenerator<F>\n\n for QuotientGeneratorExtension<D>\n\n{\n\n fn dependencies(&self) -> Vec<Target> {\n\n let mut deps = self.numerator.to_target_array().to_vec();\n\n deps.extend(&self.denominator.to_target_array());\n\n deps\n\n }\n\n\n\n fn run_once(&self, witness: &PartitionWitness<F>, out_buffer: &mut GeneratedValues<F>) {\n\n let num = witness.get_extension_target(self.numerator);\n\n let dem = witness.get_extension_target(self.denominator);\n\n let quotient = num / dem;\n\n out_buffer.set_extension_target(self.quotient, quotient)\n", "file_path": "plonky2/src/gadgets/arithmetic_extension.rs", "rank": 95, "score": 194997.97821705096 }, { "content": "#[derive(Debug)]\n\nstruct BaseSumGenerator<const B: usize> {\n\n gate_index: usize,\n\n limbs: Vec<BoolTarget>,\n\n}\n\n\n\nimpl<F: Field, const B: usize> SimpleGenerator<F> for BaseSumGenerator<B> {\n\n fn dependencies(&self) -> Vec<Target> {\n\n self.limbs.iter().map(|b| b.target).collect()\n\n }\n\n\n\n fn run_once(&self, witness: &PartitionWitness<F>, out_buffer: &mut GeneratedValues<F>) {\n\n let sum = self\n\n .limbs\n\n .iter()\n\n .map(|&t| witness.get_bool_target(t))\n\n .rev()\n\n .fold(F::ZERO, |acc, limb| {\n\n acc * F::from_canonical_usize(B) + F::from_bool(limb)\n\n });\n\n\n", "file_path": "plonky2/src/gadgets/split_base.rs", "rank": 96, "score": 194997.97821705096 }, { "content": "pub fn bits_u64(n: u64) -> usize {\n\n (64 - n.leading_zeros()) as usize\n\n}\n\n\n\npub const fn ceil_div_usize(a: usize, b: usize) -> usize {\n\n (a + b - 1) / b\n\n}\n\n\n\n/// Computes `ceil(log_2(n))`.\n", "file_path": "util/src/lib.rs", "rank": 97, "score": 193049.09089460978 }, { "content": "/// Generic configuration trait.\n\npub trait GenericConfig<const D: usize>:\n\n Debug + Clone + Sync + Sized + Send + Eq + PartialEq\n\n{\n\n /// Main field.\n\n type F: RichField + Extendable<D, Extension = Self::FE>;\n\n /// Field extension of degree D of the main field.\n\n type FE: FieldExtension<D, BaseField = Self::F>;\n\n /// Hash function used for building Merkle trees.\n\n type Hasher: Hasher<Self::F>;\n\n /// Algebraic hash function used for the challenger and hashing public inputs.\n\n type InnerHasher: AlgebraicHasher<Self::F>;\n\n}\n\n\n\n/// Configuration using Poseidon over the Goldilocks field.\n\n#[derive(Debug, Copy, Clone, Eq, PartialEq)]\n\npub struct PoseidonGoldilocksConfig;\n\nimpl GenericConfig<2> for PoseidonGoldilocksConfig {\n\n type F = GoldilocksField;\n\n type FE = QuadraticExtension<Self::F>;\n\n type Hasher = PoseidonHash;\n", "file_path": "plonky2/src/plonk/config.rs", "rank": 98, "score": 192570.01893638453 }, { "content": "#[derive(Clone)]\n\nstruct PrecomputedReducedOpeningsTarget<const D: usize> {\n\n reduced_openings_at_point: Vec<ExtensionTarget<D>>,\n\n}\n\n\n\nimpl<const D: usize> PrecomputedReducedOpeningsTarget<D> {\n\n fn from_os_and_alpha<F: RichField + Extendable<D>>(\n\n openings: &FriOpeningsTarget<D>,\n\n alpha: ExtensionTarget<D>,\n\n builder: &mut CircuitBuilder<F, D>,\n\n ) -> Self {\n\n let reduced_openings_at_point = openings\n\n .batches\n\n .iter()\n\n .map(|batch| ReducingFactorTarget::new(alpha).reduce(&batch.values, builder))\n\n .collect();\n\n Self {\n\n reduced_openings_at_point,\n\n }\n\n }\n\n}\n", "file_path": "plonky2/src/fri/recursive_verifier.rs", "rank": 99, "score": 192517.94369953984 } ]
Rust
tests/config_read_tests/configuration_tests.rs
szarykott/miau
a2ad16c2f205a21c1c35ffd91c08163b583c4d29
use miau::{ builder::ConfigurationBuilder, configuration::{Configuration, ConfigurationRead}, error::ErrorCode, format::Json, source::InMemorySource, }; use rstest::rstest; #[test] fn test_arrays_are_subsituted_when_config_is_built() { let json1 = r#"{"array1" : [1,2,3,4]}"#; let json2 = r#"{"array1" : [5,6]}"#; let json3 = r#"{"array1" : [7]}"#; let mut builder = ConfigurationBuilder::default(); builder .add(InMemorySource::from_string_slice(json1), Json::new()) .add(InMemorySource::from_string_slice(json2), Json::new()) .add(InMemorySource::from_string_slice(json3), Json::new()); let confiuration = builder.build().unwrap(); assert_eq!(Some(7), confiuration.get("array1:[0]")); assert_eq!(Some(6), confiuration.get("array1:[1]")); assert_eq!(Some(3), confiuration.get("array1:[2]")); assert_eq!(Some(4), confiuration.get("array1:[3]")); } #[test] fn test_array_to_map_substitution() { let json1 = r#"{"key" : [7]}"#; let json2 = r#"{"key" : { "key" : 7 }}"#; let mut builder = ConfigurationBuilder::default(); builder .add(InMemorySource::from_string_slice(json1), Json::new()) .add(InMemorySource::from_string_slice(json2), Json::new()); let configuration = builder.build().unwrap(); assert_eq!(Some(7), configuration.get("key:[0]")); assert_eq!(Some(7), configuration.get("key:key")); } #[test] fn test_map_to_array_substitution() { let json1 = r#"{"key" : { "key" : 7 }}"#; let json2 = r#"{"key" : [7]}"#; let mut builder = ConfigurationBuilder::default(); builder .add(InMemorySource::from_string_slice(json1), Json::new()) .add(InMemorySource::from_string_slice(json2), Json::new()); let configuration = builder.build().unwrap(); assert_eq!(Some(7), configuration.get("key:[0]")); assert_eq!(Some(7), configuration.get("key:key")); } #[rstest( c1, c2, exp, case(r#"{"value1" : 1}"#, r#"{"value1" : 2}"#, 2), case(r#"{"value1" : 1.2}"#, r#"{"value1" : 1}"#, 1), case(r#"{"value1" : false}"#, r#"{"value1" : 3}"#, 3), case(r#"{"value1" : "true"}"#, r#"{"value1" : -4}"#, -4) )] fn test_type_to_integer_substitution(c1: &str, c2: &str, exp: isize) { let mut builder = ConfigurationBuilder::default(); builder.add(InMemorySource::from_string_slice(c1), Json::new()); builder.add(InMemorySource::from_string_slice(c2), Json::new()); let result = builder.build(); assert!(result.is_ok()); let result = result.unwrap(); assert_eq!(Some(exp), result.get("value1")); } #[rstest( c1, c2, exp, case(r#"{"value1" : 1}"#, r#"{"value1" : 2.1}"#, 2.1f64), case(r#"{"value1" : 1.2}"#, r#"{"value1" : 1.1}"#, 1.1f64), case(r#"{"value1" : false}"#, r#"{"value1" : 3.1}"#, 3.1f64), case(r#"{"value1" : "true"}"#, r#"{"value1" : 4.1}"#, 4.1f64) )] fn test_type_to_float_substitution(c1: &str, c2: &str, exp: f64) { let mut builder = ConfigurationBuilder::default(); builder.add(InMemorySource::from_string_slice(c1), Json::new()); builder.add(InMemorySource::from_string_slice(c2), Json::new()); let result = builder.build().unwrap(); assert_eq!(Some(exp), result.get("value1")); } #[rstest( c1, c2, exp, case(r#"{"value1" : 1}"#, r#"{"value1" : true}"#, true), case(r#"{"value1" : 1.2}"#, r#"{"value1" : true}"#, true), case(r#"{"value1" : false}"#, r#"{"value1" : true}"#, true), case(r#"{"value1" : "true"}"#, r#"{"value1" : false}"#, false) )] fn test_type_to_bool_substitution(c1: &str, c2: &str, exp: bool) { let mut builder = ConfigurationBuilder::default(); builder.add(InMemorySource::from_string_slice(c1), Json::new()); builder.add(InMemorySource::from_string_slice(c2), Json::new()); let result = builder.build().unwrap(); assert_eq!(Some(exp), result.get("value1")); } #[rstest( c1, c2, exp, case(r#"{"value1" : 1}"#, r#"{"value1" : "true"}"#, "true"), case(r#"{"value1" : 1.2}"#, r#"{"value1" : "true"}"#, "true"), case(r#"{"value1" : false}"#, r#"{"value1" : "true"}"#, "true"), case(r#"{"value1" : "true"}"#, r#"{"value1" : "false"}"#, "false") )] fn test_type_to_string_substitution(c1: &str, c2: &str, exp: &str) { let mut builder = ConfigurationBuilder::default(); builder.add(InMemorySource::from_string_slice(c1), Json::new()); builder.add(InMemorySource::from_string_slice(c2), Json::new()); let result = builder.build().unwrap(); assert_eq!(Some(exp), result.get("value1")); } #[test] fn test_single_value_integer_config_build_json() { let mut builder = ConfigurationBuilder::default(); let result = builder .add_provider(serde_json::from_str::<Configuration>("1").unwrap()) .add_provider(serde_json::from_str::<Configuration>("2").unwrap()) .build() .unwrap(); assert_eq!(Some(2i32), result.get("")); } #[test] fn test_single_map_entry_config_build_json() { let mut builder = ConfigurationBuilder::default(); let result = builder .add_provider(serde_json::from_str::<Configuration>(r#"{"value" : 1}"#).unwrap()) .add_provider(serde_json::from_str::<Configuration>(r#"{"value" : 2}"#).unwrap()) .build() .unwrap(); assert_eq!(Some(2), result.get("value")); } #[test] fn test_single_map_entry_config_build_json_different_type() { let config_str_1 = r#"{"value" : 1}"#; let config_str_2 = r#"{"value" : "2"}"#; let mut builder = ConfigurationBuilder::default(); let result = builder .add_provider(serde_json::from_str::<Configuration>(&config_str_1).unwrap()) .add_provider(serde_json::from_str::<Configuration>(&config_str_2).unwrap()) .build() .unwrap(); assert_eq!(Some("2"), result.get("value")); assert_eq!(Some(2), result.get("value")); } #[test] fn test_two_different_map_entries_config_build_json() { let config_str_1 = r#"{"value1" : 1}"#; let config_str_2 = r#"{"value2" : 2}"#; let mut builder = ConfigurationBuilder::default(); let result = builder .add_provider(serde_json::from_str::<Configuration>(&config_str_1).unwrap()) .add_provider(serde_json::from_str::<Configuration>(&config_str_2).unwrap()) .build() .unwrap(); assert_eq!(Some(1), result.get("value1")); assert_eq!(Some(2), result.get("value2")); } #[test] fn test_single_array_entry_config_build_json() { let config_str_1 = r#"[1]"#; let config_str_2 = r#"[2]"#; let mut builder = ConfigurationBuilder::default(); let result = builder .add_provider(serde_json::from_str::<Configuration>(&config_str_1).unwrap()) .add_provider(serde_json::from_str::<Configuration>(&config_str_2).unwrap()) .build() .unwrap(); assert_eq!(Some(2), result.get("[0]")); } #[test] fn test_complex_map_config_build_json() { let config_str_1 = r#" { "firstName": "John", "lastName": "Smith", "isAlive": true, "address": { "streetAddress": "21 2nd Street" }, "phoneNumbers": [ { "type": "home", "number": "212 555-1234" } ], "spouse": null } "# .trim(); let config_str_2 = r#" { "firstName": "Andrew", "isAlive": false, "address": { "streetAddress": "Knowhere" }, "phoneNumbers": [ { "type": "work", "number": "212 555-1234" } ], "spouse": true } "# .trim(); let mut builder = ConfigurationBuilder::default(); let result = builder .add_provider(serde_json::from_str::<Configuration>(&config_str_1).unwrap()) .add_provider(serde_json::from_str::<Configuration>(&config_str_2).unwrap()) .build() .unwrap(); assert_eq!(Some("Andrew"), result.get("firstName")); assert_eq!(Some("Smith"), result.get("lastName")); assert_eq!(Some(false), result.get("isAlive")); assert_eq!(Some("Knowhere"), result.get("address:streetAddress")); assert_eq!(Some("work"), result.get("phoneNumbers:[0]:type")); assert_eq!(Some(true), result.get("spouse")); } #[test] fn test_array_of_structs_build_json() { let config_str_1 = r#" { "array" : [ { "v" : 1, "k" : 11 }, { "v" : 3, "k" : 33 } ] } "# .trim(); let config_str_2 = r#" { "array": [ { "v" : 1, "k" : 12 } ] } "# .trim(); let mut builder = ConfigurationBuilder::default(); let result = builder .add_provider(serde_json::from_str::<Configuration>(&config_str_1).unwrap()) .add_provider(serde_json::from_str::<Configuration>(&config_str_2).unwrap()) .build() .unwrap(); assert_eq!(Some(12), result.get("array:[0]:k")); assert_eq!(Some(33), result.get("array:[1]:k")); } #[test] fn test_structs_of_arrays_build_json() { let config_str_1 = r#" { "structure" : { "a1" : [1, 42, 3], "a2" : [1, 2] } } "# .trim(); let config_str_2 = r#" { "structure" : { "a1" : [11], "a2" : [4, 5, 3] } } "# .trim(); let mut builder = ConfigurationBuilder::default(); let result = builder .add_provider(serde_json::from_str::<Configuration>(&config_str_1).unwrap()) .add_provider(serde_json::from_str::<Configuration>(&config_str_2).unwrap()) .build() .unwrap(); assert_eq!(Some(11), result.get("structure:a1:[0]")); assert_eq!(Some(42), result.get("structure:a1:[1]")); assert_eq!(Some(3), result.get("structure:a1:[2]")); assert_eq!( None, ConfigurationRead::<'_, i32, &str>::get(&result, "structure:a1:[3]") ); assert_eq!(Some(4), result.get("structure:a2:[0]")); assert_eq!(Some(5), result.get("structure:a2:[1]")); assert_eq!(Some(3), result.get("structure:a2:[2]")); assert_eq!( None, ConfigurationRead::<'_, i32, &str>::get(&result, "structure:a2:[3]") ); } #[test] fn test_triple_nested_map_build() { let config_str_1 = r#" { "key1" : { "key2" : { "key3" : true, "key4" : false } } } "# .trim(); let config_str_2 = r#" { "key1" : { "key2" : { "key3" : false } } } "# .trim(); let mut builder = ConfigurationBuilder::default(); let result = builder .add_provider(serde_json::from_str::<Configuration>(&config_str_1).unwrap()) .add_provider(serde_json::from_str::<Configuration>(&config_str_2).unwrap()) .build() .unwrap(); assert_eq!(Some(false), result.get("key1:key2:key3")); assert_eq!(Some(false), result.get("key1:key2:key4")); assert_eq!( None, ConfigurationRead::<'_, i32, &str>::get(&result, "key1:key2:key5") ); } #[test] fn test_get_result_non_existing_key() { let json1 = r#"{"key" : { "key" : 7 }}"#; let mut builder = ConfigurationBuilder::default(); builder.add(InMemorySource::from_string_slice(json1), Json::new()); let configuration = builder.build().unwrap(); let value = ConfigurationRead::<'_, i32, &str>::get_result(&configuration, "value").unwrap(); assert_eq!(None, value); } #[test] fn test_get_result_wrong_key_type() { let json1 = r#"{"key" : { "key" : "not_a_number" }}"#; let mut builder = ConfigurationBuilder::default(); builder.add(InMemorySource::from_string_slice(json1), Json::new()); let configuration = builder.build().unwrap(); let value = ConfigurationRead::<'_, i32, &str>::get_result(&configuration, "key:key").unwrap(); assert_eq!(None, value); } #[test] fn test_get_result_key_unparsable() { let json1 = r#"{"key" : { "key" : "not_a_number" }}"#; let mut builder = ConfigurationBuilder::default(); builder.add(InMemorySource::from_string_slice(json1), Json::new()); let configuration = builder.build().unwrap(); let key = "key:[A]:key"; let error = ConfigurationRead::<'_, i32, &str>::get_result(&configuration, key).unwrap_err(); let error_string = error.to_string(); assert!(std::matches!(error.get_code(), ErrorCode::ParsingError(..))); assert!(error_string.contains(key)); }
use miau::{ builder::ConfigurationBuilder, configuration::{Configuration, ConfigurationRead}, error::ErrorCode, format::Json, source::InMemorySource, }; use rstest::rstest; #[test] fn test_arrays_are_subsituted_when_config_is_built() { let json1 = r#"{"array1" : [1,2,3,4]}"#; let json2 = r#"{"array1" : [5,6]}"#; let json3 = r#"{"array1" : [7]}"#; let mut builder = ConfigurationBuilder::default(); builder .add(InMemorySource::from_string_slice(json1), Json::new()) .add(InMemorySource::from_string_slice(json2), Json::new()) .add(InMemorySource::from_string_slice(json3), Json::new()); let confiuration = builder.build().unwrap(); assert_eq!(Some(7), confiuration.get("array1:[0]")); assert_eq!(Some(6), confiuration.get("array1:[1]")); assert_eq!(Some(3), confiuration.get("array1:[2]")); assert_eq!(Some(4), confiuration.get("array1:[3]")); } #[test] fn test_array_to_map_substitution() { let json1 = r#"{"key" : [7]}"#; let json2 = r#"{"key" : { "key" : 7 }}"#; let mut builder = ConfigurationBuilder::default(); builder .add(InMemorySource::from_string_slice(json1), Json::new()) .add(InMemorySource::from_string_slice(json2), Json::new()); let configuration = builder.build().unwrap(); assert_eq!(Some(7), configuration.get("key:[0]")); assert_eq!(Some(7), configuration.get("key:key")); } #[test] fn test_map_to_array_substitution() { let json1 = r#"{"key" : { "key" : 7 }}"#; let json2 = r#"{"key" : [7]}"#; let mut builder = ConfigurationBuilder::default(); builder .add(InMemorySource::from_string_slice(json1), Json::new()) .add(InMemorySource::from_string_slice(json2), Json::new()); let configuration = builder.build().unwrap(); assert_eq!(Some(7), configuration.get("key:[0]")); assert_eq!(Some(7), configuration.get("key:key")); } #[rstest( c1, c2, exp, case(r#"{"value1" : 1}"#, r#"{"value1" : 2}"#, 2), case(r#"{"value1" : 1.2}"#, r#"{"value1" : 1}"#, 1), case(r#"{"value1" : false}"#, r#"{"value1" : 3}"#, 3), case(r#"{"value1" : "true"}"#, r#"{"value1" : -4}"#, -4) )] fn test_type_to_integer_substitution(c1: &str, c2: &str, exp: isize) { let mut builder = ConfigurationBuilder::default(); builder.add(InMemorySource::from_string_slice(c1), Json::new()); builder.add(InMemorySource::from_string_slice(c2), Json::new()); let result = builder.build(); assert!(result.is_ok()); let result = result.unwrap(); assert_eq!(Some(exp), result.get("value1")); } #[rstest( c1, c2, exp, case(r#"{"value1" : 1}"#, r#"{"value1" : 2.1}"#, 2.1f64), case(r#"{"value1" : 1.2}"#, r#"{"value1" : 1.1}"#, 1.1f64), case(r#"{"value1" : false}"#, r#"{"value1" : 3.1}"#, 3.1f64), case(r#"{"value1" : "true"}"#, r#"{"value1" : 4.1}"#, 4.1f64) )] fn test_type_to_float_substitution(c1: &str, c2: &str, exp: f64) { let mut builder = ConfigurationBuilder::default(); builder.add(InMemorySource::from_string_slice(c1), Json::new()); builder.add(InMemorySource::from_string_slice(c2), Json::new()); let result = builder.build().unwrap(); assert_eq!(Some(exp), result.get("value1")); } #[rstest( c1, c2, exp, case(r#"{"value1" : 1}"#, r#"{"value1" : true}"#, true), case(r#"{"value1" : 1.2}"#, r#"{"value1" : true}"#, true), case(r#"{"value1" : false}"#, r#"{"value1" : true}"#, true), case(r#"{"value1" : "true"}"#, r#"{"value1" : false}"#, false) )] fn test_type_to_bool_substitution(c1: &str, c2: &str, exp: bool) { let mut builder = ConfigurationBuilder::default(); builder.add(InMemorySource::from_string_slice(c1), Json::new()); builder.add(InMemorySource::from_string_slice(c2), Json::new()); let result = builder.build().unwrap(); assert_eq!(Some(exp), result.get("value1")); } #[rstest( c1, c2, exp, case(r#"{"value1" : 1}"#, r#"{"value1" : "true"}"#, "true"), case(r#"{"value1" : 1.2}"#, r#"{"value1" : "true"}"#, "true"), case(r#"{"value1" : false}"#, r#"{"value1" : "true"}"#, "true"), case(r#"{"value1" : "true"}"#, r#"{"value1" : "false"}"#, "false") )] fn test_type_to_string_substitution(c1: &str, c2: &str, exp: &str) { let mut builder = ConfigurationBuilder::default(); builder.add(InMemorySource::from_string_slice(c1), Json::new()); builder.add(InMemorySource::from_string_slice(c2), Json::new()); let result = builder.build().unwrap(); assert_eq!(Some(exp), result.get("value1")); } #[test] fn test_single_value_integer_config_build_json() { let mut builder = ConfigurationBuilder::default(); let result = builder .add_provider(serde_json::from_str::<Configuration>("1").unwrap()) .add_provider(serde_json::from_str::<Configuration>("2").unwrap()) .build() .unwrap(); assert_eq!(Some(2i32), result.get("")); } #[test] fn test_single_map_entry_config_build_json() { let mut builder = ConfigurationBuilder::default(); let result = builder .add_provider(serde_json::from_str::<Configuration>(r#"{"value" : 1}"#).unwrap()) .add_provider(serde_json::from_str::<Configuration>(r#"{"value" : 2}"#).unwrap()) .build() .unwrap(); assert_eq!(Some(2), result.get("value")); } #[test] fn test_single_map_entry_config_build_json_different_type() { let config_str_1 = r#"{"value" : 1}"#; let config_str_2 = r#"{"value" : "2"}"#; let mut builder = ConfigurationBuilder::default(); let result = builder .add_provider(serde_json::from_str::<Configuration>(&config_str_1).unwrap()) .add_provider(serde_json::from_str::<Configuration>(&config_str_2).unwrap()) .build() .unwrap(); assert_eq!(Some("2"), result.get("value")); assert_eq!(Some(2), result.get("value")); } #[test] fn test_two_different_map_entries_config_build_json() { let config_str_1 = r#"{"value1" : 1}"#; let config_str_2 = r#"{"value2" : 2}"#; let mut builder = ConfigurationBuilder::default(); let result = builder .add_provider(serde_json::from_str::<Configuration>(&config_str_1).unwrap()) .add_provider(serde_json::from_str::<Configuration>(&config_str_2).unwrap()) .build() .unwrap(); assert_eq!(Some(1), result.get("value1")); assert_eq!(Some(2), result.get("value2")); } #[test] fn test_single_array_entry_config_build_json() { let config_str_1 = r#"[1]"#; let config_str_2 = r#"[2]"#; let mut builder = ConfigurationBuilder::default(); let result = builder .add_provider(serde_json::fro
#[test] fn test_complex_map_config_build_json() { let config_str_1 = r#" { "firstName": "John", "lastName": "Smith", "isAlive": true, "address": { "streetAddress": "21 2nd Street" }, "phoneNumbers": [ { "type": "home", "number": "212 555-1234" } ], "spouse": null } "# .trim(); let config_str_2 = r#" { "firstName": "Andrew", "isAlive": false, "address": { "streetAddress": "Knowhere" }, "phoneNumbers": [ { "type": "work", "number": "212 555-1234" } ], "spouse": true } "# .trim(); let mut builder = ConfigurationBuilder::default(); let result = builder .add_provider(serde_json::from_str::<Configuration>(&config_str_1).unwrap()) .add_provider(serde_json::from_str::<Configuration>(&config_str_2).unwrap()) .build() .unwrap(); assert_eq!(Some("Andrew"), result.get("firstName")); assert_eq!(Some("Smith"), result.get("lastName")); assert_eq!(Some(false), result.get("isAlive")); assert_eq!(Some("Knowhere"), result.get("address:streetAddress")); assert_eq!(Some("work"), result.get("phoneNumbers:[0]:type")); assert_eq!(Some(true), result.get("spouse")); } #[test] fn test_array_of_structs_build_json() { let config_str_1 = r#" { "array" : [ { "v" : 1, "k" : 11 }, { "v" : 3, "k" : 33 } ] } "# .trim(); let config_str_2 = r#" { "array": [ { "v" : 1, "k" : 12 } ] } "# .trim(); let mut builder = ConfigurationBuilder::default(); let result = builder .add_provider(serde_json::from_str::<Configuration>(&config_str_1).unwrap()) .add_provider(serde_json::from_str::<Configuration>(&config_str_2).unwrap()) .build() .unwrap(); assert_eq!(Some(12), result.get("array:[0]:k")); assert_eq!(Some(33), result.get("array:[1]:k")); } #[test] fn test_structs_of_arrays_build_json() { let config_str_1 = r#" { "structure" : { "a1" : [1, 42, 3], "a2" : [1, 2] } } "# .trim(); let config_str_2 = r#" { "structure" : { "a1" : [11], "a2" : [4, 5, 3] } } "# .trim(); let mut builder = ConfigurationBuilder::default(); let result = builder .add_provider(serde_json::from_str::<Configuration>(&config_str_1).unwrap()) .add_provider(serde_json::from_str::<Configuration>(&config_str_2).unwrap()) .build() .unwrap(); assert_eq!(Some(11), result.get("structure:a1:[0]")); assert_eq!(Some(42), result.get("structure:a1:[1]")); assert_eq!(Some(3), result.get("structure:a1:[2]")); assert_eq!( None, ConfigurationRead::<'_, i32, &str>::get(&result, "structure:a1:[3]") ); assert_eq!(Some(4), result.get("structure:a2:[0]")); assert_eq!(Some(5), result.get("structure:a2:[1]")); assert_eq!(Some(3), result.get("structure:a2:[2]")); assert_eq!( None, ConfigurationRead::<'_, i32, &str>::get(&result, "structure:a2:[3]") ); } #[test] fn test_triple_nested_map_build() { let config_str_1 = r#" { "key1" : { "key2" : { "key3" : true, "key4" : false } } } "# .trim(); let config_str_2 = r#" { "key1" : { "key2" : { "key3" : false } } } "# .trim(); let mut builder = ConfigurationBuilder::default(); let result = builder .add_provider(serde_json::from_str::<Configuration>(&config_str_1).unwrap()) .add_provider(serde_json::from_str::<Configuration>(&config_str_2).unwrap()) .build() .unwrap(); assert_eq!(Some(false), result.get("key1:key2:key3")); assert_eq!(Some(false), result.get("key1:key2:key4")); assert_eq!( None, ConfigurationRead::<'_, i32, &str>::get(&result, "key1:key2:key5") ); } #[test] fn test_get_result_non_existing_key() { let json1 = r#"{"key" : { "key" : 7 }}"#; let mut builder = ConfigurationBuilder::default(); builder.add(InMemorySource::from_string_slice(json1), Json::new()); let configuration = builder.build().unwrap(); let value = ConfigurationRead::<'_, i32, &str>::get_result(&configuration, "value").unwrap(); assert_eq!(None, value); } #[test] fn test_get_result_wrong_key_type() { let json1 = r#"{"key" : { "key" : "not_a_number" }}"#; let mut builder = ConfigurationBuilder::default(); builder.add(InMemorySource::from_string_slice(json1), Json::new()); let configuration = builder.build().unwrap(); let value = ConfigurationRead::<'_, i32, &str>::get_result(&configuration, "key:key").unwrap(); assert_eq!(None, value); } #[test] fn test_get_result_key_unparsable() { let json1 = r#"{"key" : { "key" : "not_a_number" }}"#; let mut builder = ConfigurationBuilder::default(); builder.add(InMemorySource::from_string_slice(json1), Json::new()); let configuration = builder.build().unwrap(); let key = "key:[A]:key"; let error = ConfigurationRead::<'_, i32, &str>::get_result(&configuration, key).unwrap_err(); let error_string = error.to_string(); assert!(std::matches!(error.get_code(), ErrorCode::ParsingError(..))); assert!(error_string.contains(key)); }
m_str::<Configuration>(&config_str_1).unwrap()) .add_provider(serde_json::from_str::<Configuration>(&config_str_2).unwrap()) .build() .unwrap(); assert_eq!(Some(2), result.get("[0]")); }
function_block-function_prefixed
[ { "content": "fn test_arrays_are_merged_when_substituted(json1: &str, json2: &str, exp: Vec<i32>) {\n\n let mut builder = ConfigurationBuilder::default();\n\n\n\n builder.add(\n\n InMemorySource::from_string_slice(json1.as_ref()),\n\n Json::new(),\n\n );\n\n builder.add(\n\n InMemorySource::from_string_slice(json2.as_ref()),\n\n Json::new(),\n\n );\n\n\n\n let confiuration = builder.build().unwrap();\n\n\n\n let mut result = confiuration\n\n .try_convert_into::<HashMap<String, Vec<i32>>>()\n\n .unwrap();\n\n\n\n assert_eq!(exp, result.remove(\"array1\".into()).unwrap());\n\n}\n\n\n", "file_path": "tests/configuration_merge_tests.rs", "rank": 4, "score": 225723.4037285951 }, { "content": "fn test_node_merge_error_messages(cfg1: &str, cfg2: &str, exp_key: &str, exp_for: &str) {\n\n let mut builder = ConfigurationBuilder::default();\n\n builder.add(InMemorySource::from_string_slice(cfg1), Json::new());\n\n builder.add(InMemorySource::from_string_slice(cfg2), Json::new());\n\n\n\n let confiuration = builder.build().unwrap();\n\n\n\n let error = confiuration.merge_owned().unwrap_err();\n\n\n\n assert!(std::matches!(error.get_code(), ErrorCode::BadNodeMerge(..)));\n\n let error_string = error.to_string();\n\n assert!(error_string.contains(exp_key));\n\n assert!(error_string.contains(exp_for));\n\n}\n\n\n", "file_path": "tests/configuration_merge_tests.rs", "rank": 5, "score": 182465.18215920206 }, { "content": "#[test]\n\nfn test_key_succesfull_unwrap() {\n\n let key_map = Key::Map(\"A\".into());\n\n let key_arr = Key::Array(1);\n\n\n\n assert_eq!(\"A\".to_string(), key_map.unwrap_map());\n\n assert_eq!(1, key_arr.unwrap_array());\n\n}\n\n\n", "file_path": "tests/key_tests.rs", "rank": 7, "score": 143221.2026559118 }, { "content": "#[test]\n\n#[should_panic]\n\nfn test_key_array_unwrap_into_map_panics() {\n\n let key_arr = Key::Array(1);\n\n\n\n let _ = key_arr.unwrap_map();\n\n}\n", "file_path": "tests/key_tests.rs", "rank": 14, "score": 135539.72139905495 }, { "content": "#[test]\n\n#[should_panic]\n\nfn test_key_map_unwrap_into_array_panics() {\n\n let key_map = Key::Map(\"A\".into());\n\n\n\n let _ = key_map.unwrap_array();\n\n}\n\n\n", "file_path": "tests/key_tests.rs", "rank": 15, "score": 135539.72139905495 }, { "content": "#[test]\n\nfn test_node_key_not_found() {\n\n let mut builder = ConfigurationBuilder::default();\n\n builder.add(\n\n InMemorySource::from_string_slice(TEST_JSON.trim()),\n\n Json::default(),\n\n );\n\n\n\n let configuration = builder.build().unwrap().merge_owned().unwrap();\n\n\n\n let result: Result<Option<i32>, ConfigurationError> =\n\n configuration.get_result(\"map:entry:value2:arrayy:[66]\"); // typo in array\n\n\n\n let error = result.unwrap_err();\n\n\n\n assert!(std::matches!(error.get_code(), ErrorCode::KeyNotFound(..)));\n\n let error_string = error.to_string();\n\n assert!(error_string.contains(\"map-->entry-->value2-->arrayy\"))\n\n}\n\n\n", "file_path": "tests/config_read_tests/configuration_node_tests.rs", "rank": 17, "score": 120538.42748594288 }, { "content": "#[test]\n\nfn test_single_node_read_result() {\n\n let mut builder = ConfigurationBuilder::default();\n\n builder.add(\n\n InMemorySource::from_string_slice(TEST_JSON.trim()),\n\n Json::default(),\n\n );\n\n\n\n let configuration = builder.build().unwrap().merge_owned().unwrap();\n\n\n\n assert_eq!(\n\n Some(true),\n\n configuration.get_result(\"map:entry:value1\").unwrap()\n\n );\n\n assert_eq!(\n\n Some(\"true\"),\n\n configuration.get_result(\"map:entry:value1\").unwrap()\n\n );\n\n assert_eq!(\n\n Some(1),\n\n configuration\n", "file_path": "tests/config_read_tests/configuration_node_tests.rs", "rank": 21, "score": 117828.0325769656 }, { "content": "#[test]\n\nfn test_node_key_and_node_mismatch_descending() {\n\n let mut builder = ConfigurationBuilder::default();\n\n builder.add(\n\n InMemorySource::from_string_slice(TEST_JSON.trim()),\n\n Json::default(),\n\n );\n\n\n\n let configuration = builder.build().unwrap().merge_owned().unwrap();\n\n\n\n let result: Result<Option<i32>, ConfigurationError> = configuration.get_result(\"map:[1]\");\n\n\n\n let error = result.unwrap_err();\n\n\n\n assert!(std::matches!(error.get_code(), ErrorCode::WrongKeyType(..)));\n\n let error_string = error.to_string();\n\n assert!(error_string.contains(\"map-->[1]\"));\n\n\n\n let result: Result<Option<i32>, ConfigurationError> =\n\n configuration.get_result(\"map:array1:one\");\n\n\n\n let error = result.unwrap_err();\n\n\n\n assert!(std::matches!(error.get_code(), ErrorCode::WrongKeyType(..)));\n\n let error_string = error.to_string();\n\n assert!(error_string.contains(\"map-->array1-->one\"));\n\n}\n", "file_path": "tests/config_read_tests/configuration_node_tests.rs", "rank": 23, "score": 114859.63380520354 }, { "content": "#[test]\n\nfn build_tree_manually() {\n\n let mut root = HashMap::new();\n\n\n\n root.insert(\n\n \"key1\".to_string(),\n\n ConfigurationTree::Value(Some(Value::String(\"value1\".into()))),\n\n );\n\n root.insert(\n\n \"key2\".to_string(),\n\n ConfigurationTree::Array(vec![\n\n ConfigurationTree::Value(Some(Value::String(\"value2\".into()))),\n\n ConfigurationTree::Value(Some(Value::String(\"value3\".into()))),\n\n ConfigurationTree::Value(Some(Value::Bool(true))),\n\n ConfigurationTree::Value(None),\n\n ]),\n\n );\n\n\n\n let _cfg = ConfigurationTree::Map(root);\n\n\n\n // we got here we are all right!\n\n assert!(true)\n\n}\n", "file_path": "tests/config_build_tests/manual_build_tests.rs", "rank": 24, "score": 113322.26758713147 }, { "content": "#[test]\n\nfn test_configuration_as_configuration_source() {\n\n let mut builder1 = ConfigurationBuilder::default();\n\n builder1.add(\n\n InMemorySource::from_string_slice(json!({ \"value\" : 1 }).to_string().as_str()),\n\n Json::default(),\n\n );\n\n\n\n let configuration1 = builder1.build().unwrap();\n\n\n\n assert_eq!(Some(1), configuration1.get(\"value\"));\n\n\n\n let mut builder2 = ConfigurationBuilder::default();\n\n builder2.add_provider(configuration1);\n\n\n\n let configuration2 = builder2.build().unwrap();\n\n\n\n assert_eq!(Some(1), configuration2.get(\"value\"));\n\n}\n\n\n", "file_path": "tests/source_tests/config_provider_tests.rs", "rank": 26, "score": 109019.57346535144 }, { "content": "#[test]\n\nfn test_merge_empty_configuration_is_error() {\n\n let mut builder = ConfigurationBuilder::default();\n\n let configuration = builder.build().unwrap();\n\n\n\n let error = configuration.merge_owned().unwrap_err();\n\n\n\n println!(\"{}\", error);\n\n\n\n assert!(std::matches!(\n\n error.get_code(),\n\n ErrorCode::EmptyConfiguration\n\n ));\n\n assert!(error.get_context().is_some());\n\n assert!(!error.get_context().unwrap().is_empty())\n\n}\n", "file_path": "tests/configuration_merge_tests.rs", "rank": 27, "score": 108470.46235575982 }, { "content": "#[test]\n\nfn test_singular_configuration_into_struct() {\n\n let mut builder = ConfigurationBuilder::default();\n\n builder.add(\n\n InMemorySource::from_string_slice(TEST_JSON_2.trim()),\n\n Json::default(),\n\n );\n\n\n\n let configuration = builder.build().unwrap().merge_owned().unwrap();\n\n\n\n let config = configuration.try_convert_into::<Config>().unwrap();\n\n\n\n assert!(vec![1, 2].iter().eq(config.array.iter()));\n\n assert_eq!(\"a\", config.value3);\n\n assert_eq!(None, config.optional);\n\n}\n\n\n\n// ------------------- Failure tests ----------------------------- //\n\n\n", "file_path": "tests/config_read_tests/configuration_node_tests.rs", "rank": 28, "score": 106757.85781153262 }, { "content": "#[test]\n\nfn test_configuration_node_as_configuration_source() {\n\n let node = from_str::<ConfigurationTree>(json!({ \"value\" : 1 }).to_string().as_ref()).unwrap();\n\n\n\n let mut builder = ConfigurationBuilder::default();\n\n builder.add_provider(node);\n\n\n\n let configuration = builder.build().unwrap();\n\n\n\n assert_eq!(Some(1), configuration.get(\"value\"));\n\n}\n", "file_path": "tests/source_tests/config_provider_tests.rs", "rank": 29, "score": 106757.85781153262 }, { "content": "#[test]\n\nfn test_maps_are_merged_nested() {\n\n #[derive(Deserialize, Debug)]\n\n struct Config {\n\n value1: ConfigInner,\n\n value2: f64,\n\n }\n\n\n\n #[derive(Debug, Deserialize)]\n\n struct ConfigInner {\n\n value1: i32,\n\n }\n\n\n\n let cfg1 = r#\"{ \n\n \"value1\" : {\n\n \"value1\" : 12\n\n } \n\n }\"#\n\n .trim();\n\n\n\n let cfg2 = r#\"{ \n", "file_path": "tests/configuration_merge_tests.rs", "rank": 30, "score": 102098.5631820447 }, { "content": "#[test]\n\nfn test_maps_are_merged_simple() {\n\n #[derive(Deserialize, Debug)]\n\n struct Config {\n\n value1: i32,\n\n value2: f64,\n\n }\n\n\n\n let cfg1 = r#\"{ \"value1\" : 1 }\"#;\n\n let cfg2 = r#\"{ \"value2\" : -1.1 }\"#;\n\n\n\n let mut builder = ConfigurationBuilder::default();\n\n builder.add(InMemorySource::from_string_slice(cfg1), Json::new());\n\n builder.add(InMemorySource::from_string_slice(cfg2), Json::new());\n\n\n\n let confiuration = builder.build().unwrap();\n\n\n\n let result = confiuration.try_convert_into::<Config>().unwrap();\n\n\n\n assert_eq!(result.value1, 1);\n\n assert_eq!(result.value2, -1.1);\n\n}\n\n\n", "file_path": "tests/configuration_merge_tests.rs", "rank": 31, "score": 102098.5631820447 }, { "content": "#[test]\n\nfn test_lens_key_unparsable() {\n\n let mut builder = ConfigurationBuilder::default();\n\n\n\n let configuration = builder.build().unwrap();\n\n let error = configuration.lens().try_lens(\"drooids:[a]\").unwrap_err();\n\n\n\n assert!(std::matches!(error.get_code(), ErrorCode::ParsingError(..)));\n\n assert!(error.to_string().contains(\"drooids:[a]\"));\n\n}\n", "file_path": "tests/config_read_tests/lens_tests.rs", "rank": 32, "score": 101449.79780743713 }, { "content": "#[test]\n\nfn test_environment_source_compound_key() {\n\n env::set_var(\"t2_key:another_key\", \"my_awesome_value\");\n\n\n\n let mut builder = ConfigurationBuilder::default();\n\n builder.add(\n\n InMemorySource::from_string_slice(\n\n json!({\n\n \"t2_key\" : {\n\n \"first_key\" : \"first_value\",\n\n \"another_key\" : \"another_value\"\n\n }\n\n })\n\n .to_string()\n\n .as_ref(),\n\n ),\n\n Json::default(),\n\n );\n\n builder.add_provider(EnvironmentProvider::new());\n\n\n\n let configuration = builder.build().unwrap();\n\n\n\n assert_eq!(Some(\"first_value\"), configuration.get(\"t2_key:first_key\"));\n\n assert_eq!(\n\n Some(\"my_awesome_value\"),\n\n configuration.get(\"t2_key:another_key\")\n\n );\n\n}\n\n\n", "file_path": "tests/source_tests/environment_source_tests.rs", "rank": 35, "score": 99135.3863872901 }, { "content": "#[test]\n\nfn test_node_index_out_of_range() {\n\n let mut builder = ConfigurationBuilder::default();\n\n builder.add(\n\n InMemorySource::from_string_slice(TEST_JSON.trim()),\n\n Json::default(),\n\n );\n\n\n\n let configuration = builder.build().unwrap().merge_owned().unwrap();\n\n\n\n let result: Result<Option<i32>, ConfigurationError> =\n\n configuration.get_result(\"map:entry:value2:array:[66]\");\n\n\n\n let error = result.unwrap_err();\n\n\n\n assert!(std::matches!(\n\n error.get_code(),\n\n ErrorCode::IndexOutOfRange(..)\n\n ));\n\n let error_string = error.to_string();\n\n assert!(error_string.contains(\"map-->entry-->value2-->array-->[66]\"))\n\n}\n\n\n", "file_path": "tests/config_read_tests/configuration_node_tests.rs", "rank": 36, "score": 97696.38605472153 }, { "content": "fn create_tree(mut keys: impl Iterator<Item = String>, value: String) -> ConfigurationTree {\n\n match keys.next() {\n\n Some(key) => {\n\n let mut map = HashMap::new();\n\n map.insert(key, create_tree(keys, value));\n\n ConfigurationTree::Map(map)\n\n }\n\n None => ConfigurationTree::Value(Some(Value::String(value))),\n\n }\n\n}\n\n\n\nimpl Default for EnvironmentProvider {\n\n fn default() -> Self {\n\n EnvironmentProvider::new()\n\n }\n\n}\n\n\n\nimpl Provider for EnvironmentProvider {\n\n fn collect(&self) -> Result<Configuration, crate::error::ConfigurationError> {\n\n Ok(self.get())\n\n }\n\n\n\n fn describe(&self) -> ConfigurationInfo {\n\n ConfigurationInfo::new(\"environment\", \"environment\")\n\n }\n\n}\n", "file_path": "src/provider/env.rs", "rank": 37, "score": 95940.27716417958 }, { "content": "#[test]\n\nfn test_single_node_read_option() {\n\n let mut builder = ConfigurationBuilder::default();\n\n builder.add(\n\n InMemorySource::from_string_slice(TEST_JSON.trim()),\n\n Json::default(),\n\n );\n\n\n\n let configuration = builder.build().unwrap().merge_owned().unwrap();\n\n\n\n assert_eq!(Some(true), configuration.get(\"map:entry:value1\"));\n\n assert_eq!(Some(\"true\"), configuration.get(\"map:entry:value1\"));\n\n assert_eq!(Some(1), configuration.get(\"map:entry:value2:array:[0]\"));\n\n assert_eq!(\n\n None,\n\n ConfigurationRead::<'_, i32, &str>::get(&configuration, \"droid\")\n\n );\n\n}\n\n\n", "file_path": "tests/config_read_tests/configuration_node_tests.rs", "rank": 38, "score": 95571.1576948404 }, { "content": "#[test]\n\nfn test_node_wrong_type_conversion() {\n\n let mut builder = ConfigurationBuilder::default();\n\n builder.add(\n\n InMemorySource::from_string_slice(TEST_JSON.trim()),\n\n Json::default(),\n\n );\n\n\n\n let configuration = builder.build().unwrap().merge_owned().unwrap();\n\n\n\n let result: Result<Option<i32>, ConfigurationError> =\n\n configuration.get_result(\"map:entry:value3\"); // value3 is string\n\n\n\n let error = result.unwrap_err();\n\n\n\n assert!(std::matches!(\n\n error.get_code(),\n\n ErrorCode::WrongValueType(..)\n\n ));\n\n let error_string = error.to_string();\n\n assert!(error_string.contains(\"map-->entry-->value3\"))\n\n}\n\n\n", "file_path": "tests/config_read_tests/configuration_node_tests.rs", "rank": 39, "score": 95571.1576948404 }, { "content": "#[test]\n\nfn test_node_descending_into_non_descendable() {\n\n let mut builder = ConfigurationBuilder::default();\n\n builder.add(\n\n InMemorySource::from_string_slice(TEST_JSON.trim()),\n\n Json::default(),\n\n );\n\n\n\n let configuration = builder.build().unwrap().merge_owned().unwrap();\n\n\n\n let result: Result<Option<i32>, ConfigurationError> =\n\n configuration.get_result(\"map:entry:value1:[66]\"); // trying to index into bool\n\n\n\n let error = result.unwrap_err();\n\n\n\n assert!(std::matches!(\n\n error.get_code(),\n\n ErrorCode::WrongNodeType(..)\n\n ));\n\n let error_string = error.to_string();\n\n assert!(error_string.contains(\"map-->entry-->value1-->[66]\"))\n\n}\n\n\n", "file_path": "tests/config_read_tests/configuration_node_tests.rs", "rank": 40, "score": 95571.1576948404 }, { "content": "use async_trait::async_trait;\n\nuse miau::{\n\n builder::{AsyncConfigurationBuilder, ConfigurationBuilder},\n\n error::ConfigurationError,\n\n format,\n\n format::Format,\n\n source::{AsyncSource, FileSource, InMemorySource, Source},\n\n};\n\nuse std::path::{Path, PathBuf};\n\nuse tokio::{fs::File, io::AsyncReadExt};\n\n\n\n#[tokio::test]\n\nasync fn test_empty_async_builder() {\n\n let mut builder = AsyncConfigurationBuilder::default();\n\n\n\n let configuration = builder.build().await.unwrap();\n\n\n\n assert_eq!(0, configuration.infos().count());\n\n}\n\n\n", "file_path": "tests/config_build_tests/async_builder_tests.rs", "rank": 41, "score": 91217.83030185496 }, { "content": "\n\n assert_eq!(2, configuration.infos().count());\n\n assert!(configuration\n\n .infos()\n\n .map(|i| i.format())\n\n .eq(vec![&json5_desc, &json_desc]));\n\n}\n\n\n\n#[tokio::test]\n\nasync fn test_sync_to_async_builder() {\n\n let mut builder = ConfigurationBuilder::default();\n\n\n\n let path: PathBuf = [\"tests\", \"files\", \"config1.json\"].iter().collect();\n\n builder.add(FileSource::from_path(path), format::json());\n\n\n\n let path: PathBuf = [\"tests\", \"files\", \"config1.json5\"].iter().collect();\n\n let mut builder = builder.add_async(TestAsyncFileSource::from_path(path), format::json5());\n\n\n\n let configuration = builder.build().await.unwrap();\n\n\n", "file_path": "tests/config_build_tests/async_builder_tests.rs", "rank": 42, "score": 91213.38808191878 }, { "content": "#[tokio::test]\n\nasync fn test_adding_sync_source_to_async_builder() {\n\n let mut builder = AsyncConfigurationBuilder::default();\n\n builder.add(\n\n InMemorySource::from_string_slice(r#\"{ \"value\" : 1 }\"#),\n\n format::json(),\n\n );\n\n\n\n let configuration = builder.build().await.unwrap();\n\n\n\n assert_eq!(1, configuration.infos().count());\n\n assert!(configuration\n\n .infos()\n\n .map(|i| i.format())\n\n .eq(vec![format::json().describe()]));\n\n assert!(configuration\n\n .infos()\n\n .map(|i| i.source())\n\n .eq(vec![InMemorySource::default().describe()]));\n\n}\n", "file_path": "tests/config_build_tests/async_builder_tests.rs", "rank": 43, "score": 91212.8476542713 }, { "content": "\n\n#[tokio::test]\n\nasync fn test_adding_more_sync_sources_to_async_builder() {\n\n let mut builder = AsyncConfigurationBuilder::default();\n\n builder.add(\n\n InMemorySource::from_string_slice(r#\"{ \"value\" : 1 }\"#),\n\n format::json(),\n\n );\n\n builder.add(\n\n InMemorySource::from_string_slice(r#\"{ \"value\" : 2 }\"#),\n\n format::json(),\n\n );\n\n\n\n let json_desc = format::json().describe();\n\n let inmem_desc = InMemorySource::default().describe();\n\n\n\n let configuration = builder.build().await.unwrap();\n\n assert_eq!(2, configuration.infos().count());\n\n assert!(configuration\n\n .infos()\n", "file_path": "tests/config_build_tests/async_builder_tests.rs", "rank": 44, "score": 91212.60188329504 }, { "content": " .map(|i| i.format())\n\n .eq(vec![&json_desc, &json_desc]));\n\n assert!(configuration\n\n .infos()\n\n .map(|i| i.source())\n\n .eq(vec![&inmem_desc, &inmem_desc]));\n\n}\n\n\n\n#[tokio::test]\n\nasync fn test_adding_async_source_to_async_builder() {\n\n let mut builder = AsyncConfigurationBuilder::default();\n\n\n\n let path: PathBuf = [\"tests\", \"files\", \"config1.json5\"].iter().collect();\n\n builder.add_async(TestAsyncFileSource::from_path(path), format::json5());\n\n\n\n let configuration = builder.build().await.unwrap();\n\n\n\n assert_eq!(1, configuration.infos().count());\n\n assert!(configuration\n\n .infos()\n", "file_path": "tests/config_build_tests/async_builder_tests.rs", "rank": 45, "score": 91212.53935431308 }, { "content": " assert!(configuration\n\n .infos()\n\n .map(|i| i.format())\n\n .eq(vec![&json5_desc, &json_desc]));\n\n}\n\n\n\n#[tokio::test]\n\nasync fn test_mixing_sync_and_async_in_async_builder() {\n\n let mut builder = AsyncConfigurationBuilder::default();\n\n\n\n let path: PathBuf = [\"tests\", \"files\", \"config1.json5\"].iter().collect();\n\n builder.add_async(TestAsyncFileSource::from_path(path), format::json5());\n\n\n\n let path: PathBuf = [\"tests\", \"files\", \"config1.json\"].iter().collect();\n\n builder.add(FileSource::from_path(path), format::json());\n\n\n\n let configuration = builder.build().await.unwrap();\n\n\n\n let json_desc = format::json().describe();\n\n let json5_desc = format::json5().describe();\n", "file_path": "tests/config_build_tests/async_builder_tests.rs", "rank": 46, "score": 91211.52253395597 }, { "content": " .map(|i| i.format())\n\n .eq(vec![format::json5().describe()]));\n\n}\n\n\n\n#[tokio::test]\n\nasync fn test_adding_more_asyncs_sources_to_async_builder() {\n\n let mut builder = AsyncConfigurationBuilder::default();\n\n\n\n let path1: PathBuf = [\"tests\", \"files\", \"config1.json5\"].iter().collect();\n\n builder.add_async(TestAsyncFileSource::from_path(path1), format::json5());\n\n\n\n let path2: PathBuf = [\"tests\", \"files\", \"config1.json\"].iter().collect();\n\n builder.add_async(TestAsyncFileSource::from_path(path2), format::json());\n\n\n\n let configuration = builder.build().await.unwrap();\n\n\n\n let json_desc = format::json().describe();\n\n let json5_desc = format::json5().describe();\n\n\n\n assert_eq!(2, configuration.infos().count());\n", "file_path": "tests/config_build_tests/async_builder_tests.rs", "rank": 47, "score": 91211.42394896393 }, { "content": " }\n\n }\n\n}\n\n\n\n#[async_trait]\n\nimpl AsyncSource for TestAsyncFileSource {\n\n async fn collect(&self) -> Result<Vec<u8>, ConfigurationError> {\n\n let mut buffer = Vec::new();\n\n\n\n let mut f = File::open(&self.path)\n\n .await\n\n .map_err(|e| -> ConfigurationError { e.into() })\n\n .map_err(|e| {\n\n e.enrich_with_context(format!(\"Failed to open file : {}\", self.path.display()))\n\n })?;\n\n\n\n f.read_to_end(&mut buffer)\n\n .await\n\n .map_err(|e| -> ConfigurationError { e.into() })\n\n .map_err(|e| {\n", "file_path": "tests/config_build_tests/async_builder_tests.rs", "rank": 48, "score": 91207.14768214089 }, { "content": " let json_desc = format::json().describe();\n\n let json5_desc = format::json5().describe();\n\n\n\n assert_eq!(2, configuration.infos().count());\n\n assert!(configuration\n\n .infos()\n\n .map(|i| i.format())\n\n .eq(vec![&json_desc, &json5_desc]));\n\n}\n\n\n\n// ----------- Test implementations --------------- //\n\n\n\npub struct TestAsyncFileSource {\n\n path: PathBuf,\n\n}\n\n\n\nimpl TestAsyncFileSource {\n\n pub fn from_path<T: AsRef<Path>>(path: T) -> Self {\n\n TestAsyncFileSource {\n\n path: path.as_ref().to_path_buf(),\n", "file_path": "tests/config_build_tests/async_builder_tests.rs", "rank": 49, "score": 91202.52896899417 }, { "content": " e.enrich_with_context(format!(\"Failed to read file : {}\", self.path.display()))\n\n })?;\n\n\n\n Ok(buffer)\n\n }\n\n\n\n fn describe(&self) -> String {\n\n std::fs::canonicalize(&self.path)\n\n .unwrap_or_else(|_| self.path.clone())\n\n .display()\n\n .to_string()\n\n }\n\n}\n", "file_path": "tests/config_build_tests/async_builder_tests.rs", "rank": 50, "score": 91199.39055219317 }, { "content": "pub fn get_result_internal<'config, T>(\n\n nodes: impl DoubleEndedIterator<Item = &'config ConfigurationTree>,\n\n keys: &CompoundKey,\n\n) -> Result<Option<T>, ConfigurationError>\n\nwhere\n\n T: TryFrom<&'config Value, Error = ConfigurationError>,\n\n{\n\n for candidate in nodes.rev() {\n\n if let result @ Ok(_) = candidate.get_result_internal::<T>(keys) {\n\n return result;\n\n }\n\n }\n\n\n\n Ok(None)\n\n}\n\n\n", "file_path": "src/configuration/common.rs", "rank": 51, "score": 82949.52878086673 }, { "content": "#[test]\n\nfn test_deserialization_option() {\n\n #[derive(Deserialize)]\n\n struct Config {\n\n some: Option<f64>,\n\n none: Option<i16>, // value will be null\n\n none2: Option<i16>, // value will be missing\n\n }\n\n\n\n let config_str = serde_json::json!({\n\n \"some\": 3,\n\n \"none\": null\n\n })\n\n .to_string();\n\n\n\n let root = serde_json::from_str::<Configuration>(&config_str).unwrap();\n\n\n\n let config = root.try_convert_into::<Config>().unwrap();\n\n\n\n assert_eq!(Some(3f64), config.some);\n\n assert_eq!(None, config.none);\n\n assert_eq!(None, config.none2);\n\n}\n", "file_path": "tests/deserialization_tests.rs", "rank": 52, "score": 81890.1352529068 }, { "content": "#[test]\n\nfn test_msgpack_format() {\n\n let config = Config {\n\n value1: 1,\n\n value2: \"aha\".into(),\n\n value3: None,\n\n value4: true,\n\n };\n\n\n\n let ser = rmp_serde::to_vec_named(&config).unwrap();\n\n\n\n let mut builder = ConfigurationBuilder::default();\n\n builder.add(InMemorySource::from_bytes(ser), format::msgpack());\n\n\n\n let configuration = builder.build().unwrap();\n\n\n\n assert_eq!(Some(1), configuration.get(\"value1\"));\n\n assert_eq!(Some(\"aha\"), configuration.get(\"value2\"));\n\n assert_eq!(\n\n None,\n\n ConfigurationRead::<'_, &str, &str>::get(&configuration, \"value3\")\n\n );\n\n assert_eq!(Some(true), configuration.get(\"value4\"));\n\n assert_eq!(\n\n None,\n\n ConfigurationRead::<'_, &str, &str>::get(&configuration, \"value5\")\n\n );\n\n}\n", "file_path": "tests/format_tests/msgpack_tests.rs", "rank": 53, "score": 80913.52731178813 }, { "content": "#[test]\n\nfn test_deserialization_all_simple_types() {\n\n #[derive(Deserialize)]\n\n struct Config {\n\n integer64: i64,\n\n integer32: i32,\n\n integer16: i16,\n\n integer8: i8,\n\n uinteger64: u64,\n\n uinteger32: u32,\n\n uinteger16: u16,\n\n uinteger8: u8,\n\n boolean: bool,\n\n string_owned: String,\n\n float32: f32,\n\n float64: f64,\n\n unit: (),\n\n character: char,\n\n }\n\n\n\n let config_str = serde_json::json!({\n", "file_path": "tests/deserialization_tests.rs", "rank": 54, "score": 79916.26085339501 }, { "content": "#[test]\n\nfn test_boolean_variant_conversion() {\n\n let value = Value::Bool(true);\n\n\n\n let int: i32 = (&value).try_into().unwrap();\n\n assert_eq!(1, int);\n\n\n\n let flt: f64 = (&value).try_into().unwrap();\n\n assert_eq!(1f64, flt);\n\n\n\n let string_owned: String = (&value).try_into().unwrap();\n\n assert_eq!(\"true\".to_string(), string_owned);\n\n\n\n // it is actually possible with bools\n\n let string_ref: &str = (&value).try_into().unwrap();\n\n assert_eq!(\"true\", string_ref);\n\n\n\n let boolean: bool = (&value).try_into().unwrap();\n\n assert_eq!(true, boolean);\n\n}\n", "file_path": "tests/value_tests.rs", "rank": 55, "score": 79916.26085339501 }, { "content": "#[test]\n\nfn test_deserialization_struct_with_array() {\n\n #[derive(Deserialize)]\n\n struct Config {\n\n inner: Vec<i32>,\n\n }\n\n\n\n let config_str = serde_json::json!({\n\n \"inner\": [1, 2, 3]\n\n })\n\n .to_string();\n\n\n\n let root = serde_json::from_str::<Configuration>(&config_str).unwrap();\n\n\n\n let config = root.try_convert_into::<Config>().unwrap();\n\n\n\n assert!(vec![1, 2, 3].iter().eq(config.inner.iter()));\n\n}\n\n\n", "file_path": "tests/deserialization_tests.rs", "rank": 56, "score": 79916.26085339501 }, { "content": "#[test]\n\nfn test_string_variant_conversion() {\n\n let strv = Value::String(\"word\".into());\n\n\n\n let string_owned: String = (&strv).try_into().unwrap();\n\n assert_eq!(\"word\".to_string(), string_owned);\n\n\n\n let string_ref: &str = (&strv).try_into().unwrap();\n\n assert_eq!(\"word\", string_ref);\n\n\n\n let boolean: Result<bool, ConfigurationError> = (&strv).try_into();\n\n let error = boolean.unwrap_err();\n\n assert!(std::matches!(\n\n error.get_code(),\n\n ErrorCode::WrongValueType(..)\n\n ));\n\n\n\n let int: Result<i32, ConfigurationError> = (&strv).try_into();\n\n let error = int.unwrap_err();\n\n assert!(std::matches!(\n\n error.get_code(),\n", "file_path": "tests/value_tests.rs", "rank": 57, "score": 79916.26085339501 }, { "content": "#[test]\n\nfn test_deserialization_struct_with_hashmap() {\n\n #[derive(Deserialize)]\n\n struct Config {\n\n inner: HashMap<String, i32>,\n\n }\n\n\n\n let config_str = serde_json::json!({\n\n \"inner\": {\n\n \"a\" : 1,\n\n \"b\" : 2\n\n }\n\n })\n\n .to_string();\n\n\n\n let root = serde_json::from_str::<Configuration>(&config_str).unwrap();\n\n\n\n let config = root.try_convert_into::<Config>().unwrap();\n\n\n\n assert_eq!(Some(&1), config.inner.get(\"a\"));\n\n assert_eq!(Some(&2), config.inner.get(\"b\"));\n\n assert_eq!(None, config.inner.get(\"c\"));\n\n}\n\n\n", "file_path": "tests/deserialization_tests.rs", "rank": 58, "score": 79916.26085339501 }, { "content": "#[test]\n\nfn test_float_variant_conversion() {\n\n let value = Value::Float(1.23);\n\n\n\n let flt: f64 = (&value).try_into().unwrap();\n\n assert_eq!(1.23, flt);\n\n\n\n let string_owned: String = (&value).try_into().unwrap();\n\n assert_eq!(\"1.23\".to_string(), string_owned);\n\n\n\n // due to memory model used it is not possible\n\n let string_ref: Result<&str, ConfigurationError> = (&value).try_into();\n\n let error = string_ref.unwrap_err();\n\n assert!(std::matches!(\n\n error.get_code(),\n\n ErrorCode::WrongValueType(..)\n\n ));\n\n\n\n let int: i32 = (&value).try_into().unwrap();\n\n assert_eq!(1, int);\n\n\n", "file_path": "tests/value_tests.rs", "rank": 59, "score": 79916.26085339501 }, { "content": "#[test]\n\nfn test_deserialization_struct_with_map() {\n\n #[derive(Deserialize)]\n\n struct Config {\n\n inner: ConfigInner,\n\n }\n\n\n\n #[derive(Deserialize)]\n\n struct ConfigInner {\n\n value: i32,\n\n }\n\n\n\n let config_str = serde_json::json!({\n\n \"inner\": {\n\n \"value\" : 42\n\n },\n\n })\n\n .to_string();\n\n\n\n let root = serde_json::from_str::<Configuration>(&config_str).unwrap();\n\n\n\n let config = root.try_convert_into::<Config>().unwrap();\n\n\n\n assert_eq!(42, config.inner.value);\n\n}\n\n\n", "file_path": "tests/deserialization_tests.rs", "rank": 60, "score": 79916.26085339501 }, { "content": "#[test]\n\nfn test_integer_variant_conversion() {\n\n let value = Value::SignedInteger(1);\n\n\n\n let int: i32 = (&value).try_into().unwrap();\n\n assert_eq!(1, int);\n\n\n\n let flt: f64 = (&value).try_into().unwrap();\n\n assert_eq!(1f64, flt);\n\n\n\n let string_owned: String = (&value).try_into().unwrap();\n\n assert_eq!(\"1\".to_string(), string_owned);\n\n\n\n // due to memory model used it is not possible\n\n let string_ref: Result<&str, ConfigurationError> = (&value).try_into();\n\n let error = string_ref.unwrap_err();\n\n assert!(std::matches!(\n\n error.get_code(),\n\n ErrorCode::WrongValueType(..)\n\n ));\n\n\n\n let boolean: bool = (&value).try_into().unwrap();\n\n assert_eq!(true, boolean);\n\n}\n\n\n", "file_path": "tests/value_tests.rs", "rank": 61, "score": 79916.26085339501 }, { "content": "#[test]\n\nfn test_basic_lens() {\n\n let mut builder = ConfigurationBuilder::default();\n\n builder.add(\n\n InMemorySource::from_string_slice(TEST_JSON.trim()),\n\n Json::default(),\n\n );\n\n\n\n let configuration = builder.build().unwrap();\n\n let lens = configuration.lens().try_lens(\"map:entry\").unwrap();\n\n\n\n assert_eq!(Some(true), lens.get(\"value1\"));\n\n assert_eq!(Some(\"true\"), lens.get(\"value1\"));\n\n assert_eq!(Some(1), lens.get(\"value2:array:[0]\"));\n\n assert!(true)\n\n}\n\n\n", "file_path": "tests/config_read_tests/lens_tests.rs", "rank": 62, "score": 79281.66915182686 }, { "content": "#[test]\n\nfn test_double_lens() {\n\n let mut builder = ConfigurationBuilder::default();\n\n builder.add(\n\n InMemorySource::from_string_slice(TEST_JSON.trim()),\n\n Json::default(),\n\n );\n\n\n\n let configuration = builder.build().unwrap();\n\n let lens = configuration.lens().try_lens(\"map:entry\").unwrap();\n\n let inner_lens = lens.try_lens(\"value2\").unwrap();\n\n\n\n assert_eq!(Some(true), lens.get(\"value1\"));\n\n assert_eq!(Some(1), lens.get(\"value2:array:[0]\"));\n\n assert_eq!(Some(2), lens.get(\"value2:array:[1]\"));\n\n\n\n assert_eq!(Some(1), inner_lens.get(\"array:[0]\"));\n\n assert_eq!(Some(2), inner_lens.get(\"array:[1]\"));\n\n assert_eq!(Some(\"a\"), inner_lens.get(\"value3\"));\n\n}\n\n\n", "file_path": "tests/config_read_tests/lens_tests.rs", "rank": 63, "score": 79281.66915182686 }, { "content": "#[test]\n\nfn test_lens_into_struct() {\n\n let mut builder = ConfigurationBuilder::default();\n\n builder.add(\n\n InMemorySource::from_string_slice(TEST_JSON.trim()),\n\n Json::default(),\n\n );\n\n\n\n let configuration = builder.build().unwrap();\n\n let lens = configuration.lens().try_lens(\"map:entry:value2\").unwrap();\n\n\n\n let config = lens.try_convert_into::<Config>().unwrap();\n\n\n\n assert!(vec![1, 2].iter().eq(config.array.iter()));\n\n assert_eq!(\"a\", config.value3);\n\n assert_eq!(None, config.optional);\n\n assert!(true)\n\n}\n\n\n\n// --------------- Failure tests ---------------------- //\n\n\n", "file_path": "tests/config_read_tests/lens_tests.rs", "rank": 64, "score": 79281.66915182686 }, { "content": "#[test]\n\nfn test_deserialization_enum_newtype_variant() {\n\n #[derive(Deserialize)]\n\n struct Config {\n\n enumeration: DaEnum,\n\n }\n\n\n\n let config_str = serde_json::json!({\n\n \"enumeration\": {\n\n \"Newtype\" : 42\n\n },\n\n })\n\n .to_string();\n\n\n\n let root = serde_json::from_str::<Configuration>(&config_str).unwrap();\n\n\n\n let config = root.try_convert_into::<Config>().unwrap();\n\n\n\n assert_eq!(DaEnum::Newtype(42i32), config.enumeration);\n\n}\n\n\n", "file_path": "tests/deserialization_tests.rs", "rank": 65, "score": 78070.84627748968 }, { "content": "#[test]\n\nfn test_deserialization_enum_struct_variant() {\n\n #[derive(Deserialize)]\n\n struct Config {\n\n enumeration: DaEnum,\n\n }\n\n\n\n let config_str = serde_json::json!({\n\n \"enumeration\": {\n\n \"Structo\" : {\n\n \"value\" : 3\n\n }\n\n },\n\n })\n\n .to_string();\n\n\n\n let root = serde_json::from_str::<Configuration>(&config_str).unwrap();\n\n\n\n let config = root.try_convert_into::<Config>().unwrap();\n\n\n\n assert_eq!(DaEnum::Structo { value: 3 }, config.enumeration);\n\n}\n\n\n", "file_path": "tests/deserialization_tests.rs", "rank": 66, "score": 78070.84627748968 }, { "content": "#[test]\n\nfn test_deserialization_enum_unit_variant() {\n\n #[derive(Deserialize)]\n\n struct Config {\n\n enumeration: DaEnum,\n\n }\n\n\n\n let config_str = serde_json::json!({\n\n \"enumeration\": \"Unit\",\n\n })\n\n .to_string();\n\n\n\n let root = serde_json::from_str::<Configuration>(&config_str).unwrap();\n\n\n\n let config = root.try_convert_into::<Config>().unwrap();\n\n\n\n assert_eq!(DaEnum::Unit, config.enumeration);\n\n}\n\n\n", "file_path": "tests/deserialization_tests.rs", "rank": 67, "score": 78070.84627748968 }, { "content": "#[test]\n\nfn test_deserialization_enum_tuple_variant() {\n\n #[derive(Deserialize)]\n\n struct Config {\n\n enumeration: DaEnum,\n\n }\n\n\n\n let config_str = serde_json::json!({\n\n \"enumeration\": {\n\n \"Tuple\" : [1, 2]\n\n },\n\n })\n\n .to_string();\n\n\n\n let root = serde_json::from_str::<Configuration>(&config_str).unwrap();\n\n\n\n let config = root.try_convert_into::<Config>().unwrap();\n\n\n\n assert_eq!(DaEnum::Tuple(1, 2), config.enumeration);\n\n}\n\n\n", "file_path": "tests/deserialization_tests.rs", "rank": 68, "score": 78070.84627748968 }, { "content": "#[test]\n\nfn test_deserialization_struct_with_array_of_structs() {\n\n #[derive(Deserialize)]\n\n struct Config {\n\n inner: Vec<ConfigInner>,\n\n }\n\n\n\n #[derive(Deserialize, PartialEq)]\n\n struct ConfigInner {\n\n value: i32,\n\n }\n\n\n\n let config_str = serde_json::json!({\n\n \"inner\": [\n\n {\"value\" : 1},\n\n {\"value\" : 2},\n\n {\"value\" : 3},\n\n ]\n\n })\n\n .to_string();\n\n\n", "file_path": "tests/deserialization_tests.rs", "rank": 69, "score": 78070.84627748968 }, { "content": "#[test]\n\nfn test_file_source_json() {\n\n // done like this for correct execution on different OS\n\n let path: PathBuf = [\"tests\", \"files\", \"config1.json\"].iter().collect();\n\n\n\n let mut builder = ConfigurationBuilder::default();\n\n builder.add(FileSource::from_path(path), format::json());\n\n\n\n let configuration = builder.build().unwrap();\n\n\n\n assert_eq!(Some(1), configuration.get(\"value1\"));\n\n assert_eq!(Some(true), configuration.get(\"value2\"));\n\n assert_eq!(\n\n None,\n\n ConfigurationRead::<'_, &str, &str>::get(&configuration, \"value3\")\n\n );\n\n assert_eq!(Some(\"aha\"), configuration.get(\"value4\"));\n\n assert_eq!(\n\n None,\n\n ConfigurationRead::<'_, &str, &str>::get(&configuration, \"value5\")\n\n );\n\n}\n\n\n", "file_path": "tests/source_tests/file_source_tests.rs", "rank": 70, "score": 77744.60823509179 }, { "content": "#[test]\n\nfn test_file_source_ini() {\n\n // done like this for correct execution on different OS\n\n let path: PathBuf = [\"tests\", \"files\", \"config1.ini\"].iter().collect();\n\n\n\n let mut builder = ConfigurationBuilder::default();\n\n builder.add(FileSource::from_path(path), format::ini());\n\n\n\n let configuration = builder.build().unwrap();\n\n\n\n assert_eq!(Some(1), configuration.get(\"value1\"));\n\n assert_eq!(Some(true), configuration.get(\"value2\"));\n\n assert_eq!(\n\n None,\n\n ConfigurationRead::<'_, &str, &str>::get(&configuration, \"value3\")\n\n );\n\n assert_eq!(Some(\"aha\"), configuration.get(\"value4\"));\n\n assert_eq!(\n\n None,\n\n ConfigurationRead::<'_, &str, &str>::get(&configuration, \"value5\")\n\n );\n\n}\n\n\n", "file_path": "tests/source_tests/file_source_tests.rs", "rank": 71, "score": 77744.60823509179 }, { "content": "#[test]\n\nfn test_file_source_toml() {\n\n // done like this for correct execution on different OS\n\n let path: PathBuf = [\"tests\", \"files\", \"config1.toml\"].iter().collect();\n\n\n\n let mut builder = ConfigurationBuilder::default();\n\n builder.add(FileSource::from_path(path), format::toml());\n\n\n\n let configuration = builder.build().unwrap();\n\n\n\n assert_eq!(Some(1), configuration.get(\"value1\"));\n\n assert_eq!(Some(true), configuration.get(\"value2\"));\n\n assert_eq!(\n\n None,\n\n ConfigurationRead::<'_, &str, &str>::get(&configuration, \"value3\")\n\n );\n\n assert_eq!(Some(\"aha\"), configuration.get(\"value4\"));\n\n assert_eq!(\n\n None,\n\n ConfigurationRead::<'_, &str, &str>::get(&configuration, \"value5\")\n\n );\n\n}\n\n\n", "file_path": "tests/source_tests/file_source_tests.rs", "rank": 72, "score": 77744.60823509179 }, { "content": "#[test]\n\nfn test_environment_source_with_prefix() {\n\n env::set_var(\"my_t3_awesome_key\", \"my_awesome_value\");\n\n env::set_var(\"notmy_t3_awesome_key\", \"notmy_awesome_value\");\n\n\n\n let mut builder = ConfigurationBuilder::default();\n\n builder.add_provider(EnvironmentProvider::with_prefix(\"my\"));\n\n\n\n let configuration = builder.build().unwrap();\n\n\n\n assert_eq!(\n\n Some(\"my_awesome_value\"),\n\n configuration.get(\"my_t3_awesome_key\")\n\n );\n\n\n\n assert_eq!(\n\n None,\n\n ConfigurationRead::<'_, &str, &str>::get(&configuration, \"notmy_t3_awesome_key\")\n\n );\n\n}\n", "file_path": "tests/source_tests/environment_source_tests.rs", "rank": 73, "score": 77744.60823509179 }, { "content": "#[test]\n\nfn test_file_source_yaml() {\n\n // done like this for correct execution on different OS\n\n let path: PathBuf = [\"tests\", \"files\", \"config1.yaml\"].iter().collect();\n\n\n\n let mut builder = ConfigurationBuilder::default();\n\n builder.add(FileSource::from_path(path), format::yaml());\n\n\n\n let configuration = builder.build().unwrap();\n\n\n\n assert_eq!(Some(1), configuration.get(\"value1\"));\n\n assert_eq!(Some(true), configuration.get(\"value2\"));\n\n assert_eq!(\n\n None,\n\n ConfigurationRead::<'_, &str, &str>::get(&configuration, \"value3\")\n\n );\n\n assert_eq!(Some(\"aha\"), configuration.get(\"value4\"));\n\n assert_eq!(\n\n None,\n\n ConfigurationRead::<'_, &str, &str>::get(&configuration, \"value5\")\n\n );\n\n}\n\n\n", "file_path": "tests/source_tests/file_source_tests.rs", "rank": 74, "score": 77744.60823509179 }, { "content": "#[test]\n\nfn test_lensing_with_multiple_configs() {\n\n let json1 = r#\"\n\n {\n\n \"map\" : {\n\n \"value\" : 1,\n\n \"array\" : [1, 2, 3]\n\n },\n\n \"array\" : [1]\n\n }\n\n \"#\n\n .trim();\n\n\n\n let json2 = r#\"\n\n {\n\n \"map\" : {\n\n \"value\" : 2,\n\n \"array\" : [3]\n\n },\n\n \"array\" : [22, 23, 24, 25]\n\n }\n", "file_path": "tests/config_read_tests/lens_tests.rs", "rank": 75, "score": 77744.60823509179 }, { "content": "#[test]\n\nfn test_environment_source_no_prefix() {\n\n env::set_var(\"my_awesome_key\", \"my_awesome_value\");\n\n env::set_var(\"notmy_awesome_key\", \"notmy_awesome_value\");\n\n\n\n let mut builder = ConfigurationBuilder::default();\n\n builder.add_provider(EnvironmentProvider::new());\n\n\n\n let configuration = builder.build().unwrap();\n\n\n\n assert_eq!(\n\n Some(\"my_awesome_value\"),\n\n configuration.get(\"my_awesome_key\")\n\n );\n\n\n\n assert_eq!(\n\n Some(\"notmy_awesome_value\"),\n\n configuration.get(\"notmy_awesome_key\")\n\n );\n\n}\n\n\n", "file_path": "tests/source_tests/environment_source_tests.rs", "rank": 76, "score": 77744.60823509179 }, { "content": "#[test]\n\nfn test_missing_file_source() {\n\n // done like this for correct execution on different OS\n\n let path: PathBuf = [\"tests\", \"files\", \"not_present.json\"].iter().collect();\n\n\n\n let mut builder = ConfigurationBuilder::default();\n\n builder.add(FileSource::from_path(path.clone()), format::json());\n\n\n\n let error = builder.build().unwrap_err();\n\n\n\n assert!(std::matches!(error.get_code(), ErrorCode::IoError(..)));\n\n let error_string = error.to_string();\n\n assert!(error_string.contains(&path.display().to_string()))\n\n}\n", "file_path": "tests/source_tests/file_source_tests.rs", "rank": 77, "score": 77744.60823509179 }, { "content": "#[test]\n\nfn test_file_source_json5() {\n\n // done like this for correct execution on different OS\n\n let path: PathBuf = [\"tests\", \"files\", \"config1.json5\"].iter().collect();\n\n\n\n let mut builder = ConfigurationBuilder::default();\n\n builder.add(FileSource::from_path(path), format::json5());\n\n\n\n let configuration = builder.build().unwrap();\n\n\n\n assert_eq!(Some(1), configuration.get(\"value1\"));\n\n assert_eq!(Some(true), configuration.get(\"value2\"));\n\n assert_eq!(\n\n None,\n\n ConfigurationRead::<'_, &str, &str>::get(&configuration, \"value3\")\n\n );\n\n assert_eq!(Some(\"aha\"), configuration.get(\"value4\"));\n\n assert_eq!(\n\n None,\n\n ConfigurationRead::<'_, &str, &str>::get(&configuration, \"value5\")\n\n );\n\n}\n\n\n", "file_path": "tests/source_tests/file_source_tests.rs", "rank": 78, "score": 77744.60823509179 }, { "content": "#[test]\n\nfn test_deserialization_enum_newtype_variant_untagged() {\n\n #[derive(Deserialize)]\n\n struct Config {\n\n enumeration: DaEnumUntagged,\n\n }\n\n\n\n let config_str = serde_json::json!({\n\n \"enumeration\": 42,\n\n })\n\n .to_string();\n\n\n\n let root = serde_json::from_str::<Configuration>(&config_str).unwrap();\n\n\n\n let config = root.try_convert_into::<Config>().unwrap();\n\n\n\n assert_eq!(DaEnumUntagged::Newtype(42f32), config.enumeration);\n\n}\n\n\n", "file_path": "tests/deserialization_tests.rs", "rank": 79, "score": 76340.74504663926 }, { "content": "#[test]\n\nfn test_deserialization_enum_tuple_variant_untagged() {\n\n #[derive(Deserialize)]\n\n struct Config {\n\n enumeration: DaEnumUntagged,\n\n }\n\n\n\n let config_str = serde_json::json!({\n\n \"enumeration\": [1, 2],\n\n })\n\n .to_string();\n\n\n\n let root = serde_json::from_str::<Configuration>(&config_str).unwrap();\n\n\n\n let config = root.try_convert_into::<Config>().unwrap();\n\n\n\n assert_eq!(DaEnumUntagged::Tuple(1f32, 2), config.enumeration);\n\n}\n\n\n", "file_path": "tests/deserialization_tests.rs", "rank": 80, "score": 76340.74504663926 }, { "content": "#[test]\n\nfn test_deserialization_struct_with_hashmap_string_values() {\n\n #[derive(Deserialize)]\n\n struct Config {\n\n inner: HashMap<String, String>,\n\n }\n\n\n\n let config_str = serde_json::json!({\n\n \"inner\": {\n\n \"a\" : \"a\",\n\n \"b\" : \"b\"\n\n }\n\n })\n\n .to_string();\n\n\n\n let root = serde_json::from_str::<Configuration>(&config_str).unwrap();\n\n\n\n let config = root.try_convert_into::<Config>().unwrap();\n\n\n\n assert_eq!(Some(&\"a\".to_string()), config.inner.get(\"a\"));\n\n assert_eq!(Some(&\"b\".to_string()), config.inner.get(\"b\"));\n\n assert_eq!(None, config.inner.get(\"c\"));\n\n}\n\n\n", "file_path": "tests/deserialization_tests.rs", "rank": 81, "score": 76340.74504663926 }, { "content": "#[test]\n\nfn test_error_when_deserializing_char_longer_than_one() {\n\n #[derive(Deserialize, Debug)]\n\n struct Config {\n\n character: char,\n\n };\n\n\n\n let json = r#\"{ \"character\" : \"longer\" }\"#;\n\n\n\n let root = serde_json::from_str::<ConfigurationTree>(&json).unwrap();\n\n\n\n let error = root.try_convert_into::<Config>().unwrap_err();\n\n\n\n assert!(std::matches!(\n\n error.get_code(),\n\n ErrorCode::DeserializationError(..)\n\n ));\n\n assert!(error.to_string().contains(\"expected string of length 1\"));\n\n}\n\n\n", "file_path": "tests/deserialization_tests.rs", "rank": 82, "score": 76340.74504663926 }, { "content": "#[test]\n\nfn test_deserialization_struct_with_array_of_structs_transparent() {\n\n #[derive(Deserialize)]\n\n struct Config {\n\n inner: Vec<ConfigInner>,\n\n }\n\n\n\n #[derive(Deserialize, PartialEq)]\n\n #[serde(transparent)]\n\n struct ConfigInner {\n\n value: i32,\n\n }\n\n\n\n let config_str = serde_json::json!({\n\n \"inner\": [\n\n 1, 2, 3\n\n ]\n\n })\n\n .to_string();\n\n\n\n let root = serde_json::from_str::<Configuration>(&config_str).unwrap();\n", "file_path": "tests/deserialization_tests.rs", "rank": 83, "score": 76340.74504663926 }, { "content": "#[test]\n\nfn test_error_when_deserializing_external_source_fails() {\n\n let cfg_str = r#\" this is not json asdas1211/// \"#;\n\n\n\n let mut builder = ConfigurationBuilder::default();\n\n builder.add(InMemorySource::from_string_slice(cfg_str), Json::default());\n\n\n\n let error = builder.build().unwrap_err();\n\n\n\n assert!(std::matches!(\n\n error.get_code(),\n\n ErrorCode::DeserializationError(..)\n\n ));\n\n}\n\n\n", "file_path": "tests/deserialization_tests.rs", "rank": 84, "score": 76340.74504663926 }, { "content": "#[test]\n\nfn test_deserialization_enum_unit_variant_untagged() {\n\n #[derive(Deserialize)]\n\n struct Config {\n\n enumeration: DaEnumUntagged,\n\n }\n\n\n\n let config_str = serde_json::json!({\n\n \"enumeration\": null,\n\n })\n\n .to_string();\n\n\n\n let root = serde_json::from_str::<Configuration>(&config_str).unwrap();\n\n\n\n let config = root.try_convert_into::<Config>().unwrap();\n\n\n\n assert_eq!(DaEnumUntagged::Unit, config.enumeration);\n\n}\n\n\n", "file_path": "tests/deserialization_tests.rs", "rank": 85, "score": 76340.74504663926 }, { "content": "#[test]\n\nfn test_error_when_deserializing_internal_struct_fails() {\n\n #[derive(Deserialize, Debug)]\n\n struct Config {\n\n some_integer_field: u32,\n\n }\n\n\n\n let cfg_str = serde_json::json!({\n\n \"these_are_not_the_droids_you_are_looking_for\" : \"string\"\n\n })\n\n .to_string();\n\n\n\n let root = serde_json::from_str::<Configuration>(&cfg_str).unwrap();\n\n let error = root.try_convert_into::<Config>().unwrap_err();\n\n\n\n assert!(std::matches!(\n\n error.get_code(),\n\n ErrorCode::DeserializationError(..)\n\n ));\n\n let error_stringified = error.to_string();\n\n assert!(error_stringified.contains(\"some_integer_field\"));\n\n assert!(error_stringified.contains(&format!(\"{}\", std::any::type_name::<Config>())));\n\n}\n\n\n", "file_path": "tests/deserialization_tests.rs", "rank": 86, "score": 76340.74504663926 }, { "content": "#[test]\n\nfn test_deserialization_enum_struct_variant_untagged() {\n\n #[derive(Deserialize)]\n\n struct Config {\n\n enumeration: DaEnumUntagged,\n\n }\n\n\n\n let config_str = serde_json::json!({\n\n \"enumeration\": {\n\n \"value\" : 3\n\n },\n\n })\n\n .to_string();\n\n\n\n let root = serde_json::from_str::<Configuration>(&config_str).unwrap();\n\n\n\n let config = root.try_convert_into::<Config>().unwrap();\n\n\n\n assert_eq!(DaEnumUntagged::Structo { value: 3 }, config.enumeration);\n\n}\n\n\n", "file_path": "tests/deserialization_tests.rs", "rank": 87, "score": 76340.74504663926 }, { "content": "use miau::configuration::{ConfigurationTree, Value};\n\nuse std::collections::HashMap;\n\n\n\n#[test]\n", "file_path": "tests/config_build_tests/manual_build_tests.rs", "rank": 88, "score": 74056.13456958896 }, { "content": "fn merge_maps(\n\n mut previous: HashMap<String, ConfigurationTree>,\n\n mut next: HashMap<String, ConfigurationTree>,\n\n) -> Result<HashMap<String, ConfigurationTree>, ConfigurationError> {\n\n for (key, next_node) in next.drain() {\n\n if !previous.contains_key(&key) {\n\n previous.insert(key.clone(), next_node.clone());\n\n } else {\n\n let previous_node = previous.remove(&key).unwrap();\n\n match (previous_node, next_node) {\n\n (ConfigurationTree::Value(_), vn @ ConfigurationTree::Value(_)) => {\n\n previous.insert(key.clone(), vn.clone());\n\n }\n\n (ConfigurationTree::Map(mp), ConfigurationTree::Map(mn)) => {\n\n previous.insert(\n\n key.clone(),\n\n ConfigurationTree::Map(\n\n merge_maps(mp, mn)\n\n .map_err(|e| e.enrich_with_key(Key::Map(key.clone())))?,\n\n ),\n", "file_path": "src/configuration/tree.rs", "rank": 89, "score": 71868.85914489669 }, { "content": "fn merge_arrays(\n\n mut vp: Vec<ConfigurationTree>,\n\n vn: Vec<ConfigurationTree>,\n\n) -> Vec<ConfigurationTree> {\n\n if vp.len() >= vn.len() {\n\n for (index, root) in vn.iter().enumerate() {\n\n vp[index] = root.clone();\n\n }\n\n } else {\n\n vp.clear();\n\n for e in vn.iter() {\n\n vp.push(e.clone())\n\n }\n\n }\n\n\n\n vp\n\n}\n\n\n\nimpl Display for NodeType {\n\n fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {\n", "file_path": "src/configuration/tree.rs", "rank": 90, "score": 71868.85914489669 }, { "content": "use miau::configuration::Key;\n\n\n\n#[test]\n", "file_path": "tests/key_tests.rs", "rank": 91, "score": 69902.02469196124 }, { "content": "fn push(keys: impl Iterator<Item = (String, String)>) -> Option<ConfigurationTree> {\n\n let mut trees: Vec<ConfigurationTree> = Vec::new();\n\n for (key, value) in keys {\n\n if let Ok(ckey) = parsing::str_to_key(key.as_ref()) {\n\n let all_map = ckey.iter().all(|k| std::matches!(k, Key::Map(..)));\n\n\n\n if !all_map {\n\n continue;\n\n }\n\n\n\n trees.push(create_tree(ckey.iter().map(|k| k.unwrap_map()), value));\n\n }\n\n }\n\n\n\n let mut drain = trees.drain(..);\n\n match drain.next() {\n\n Some(node) => {\n\n if let Ok(final_node) = drain.try_fold(node, merge) {\n\n Some(final_node)\n\n } else {\n\n None\n\n }\n\n }\n\n None => None,\n\n }\n\n}\n\n\n", "file_path": "src/provider/env.rs", "rank": 92, "score": 69124.43061140497 }, { "content": "pub fn merge_owned(\n\n mut nodes: impl Iterator<Item = ConfigurationTree>,\n\n) -> Result<ConfigurationTree, ConfigurationError> {\n\n match nodes.next() {\n\n Some(node) => nodes.try_fold(node, tree::merge),\n\n None => {\n\n let error: ConfigurationError = ErrorCode::EmptyConfiguration.into();\n\n Err(error.enrich_with_context(\"Failed to merge configurations\"))\n\n }\n\n }\n\n}\n", "file_path": "src/configuration/common.rs", "rank": 93, "score": 67261.11849237845 }, { "content": "use miau::{builder::ConfigurationBuilder, error::ErrorCode, format::Json, source::InMemorySource};\n\nuse rstest::rstest;\n\nuse serde::Deserialize;\n\nuse std::collections::HashMap;\n\n\n\n#[rstest(\n\n json1,\n\n json2,\n\n exp,\n\n case(\n\n r#\"{\"array1\" : [1,2,3,4]}\"#,\n\n r#\"{\"array1\" : [4,5]}\"#,\n\n vec![4, 5, 3, 4]\n\n ),\n\n case(\n\n r#\"{\"array1\" : [1,2]}\"#,\n\n r#\"{\"array1\" : [4,5,6]}\"#,\n\n vec![4, 5, 6]\n\n ),\n\n case(\n", "file_path": "tests/configuration_merge_tests.rs", "rank": 94, "score": 65208.73407353412 }, { "content": " \"value2\" : -1.1,\n\n \"value1\" : {\n\n \"value1\" : 13\n\n } \n\n }\"#\n\n .trim();\n\n\n\n let mut builder = ConfigurationBuilder::default();\n\n builder.add(InMemorySource::from_string_slice(cfg1), Json::new());\n\n builder.add(InMemorySource::from_string_slice(cfg2), Json::new());\n\n\n\n let confiuration = builder.build().unwrap();\n\n\n\n let result = confiuration.try_convert_into::<Config>().unwrap();\n\n\n\n assert_eq!(result.value1.value1, 13);\n\n assert_eq!(result.value2, -1.1);\n\n}\n\n\n\n#[rstest(\n", "file_path": "tests/configuration_merge_tests.rs", "rank": 95, "score": 65208.12735141949 }, { "content": " cfg1,\n\n cfg2,\n\n exp_key,\n\n exp_for,\n\n case(\n\n r#\"{\"this_is_key\" : 1}\"#,\n\n r#\"{\"this_is_key\" : [1]}\"#,\n\n \"this_is_key\",\n\n \"array for value\"\n\n ),\n\n case(\n\n r#\"{\"this_is_key\" : {\"key\" : 1}}\"#,\n\n r#\"{\"this_is_key\" : [1]}\"#,\n\n \"this_is_key\",\n\n \"array for map\"\n\n ),\n\n case(\n\n r#\"{\"this_is_key\" : 1}\"#,\n\n r#\"{\"this_is_key\" : {\"key\" : 1}}\"#,\n\n \"this_is_key\",\n", "file_path": "tests/configuration_merge_tests.rs", "rank": 96, "score": 65194.411592129734 }, { "content": " \"map for value\"\n\n ),\n\n // one below is double to assert other key message\n\n case(\n\n r#\"{\"this_is_key\" : { \"key2\" : [1]} }\"#,\n\n r#\"{\"this_is_key\" : { \"key2\" : {\"key3\" : 1}} }\"#,\n\n \"this_is_key-->key2\",\n\n \"map for array\"\n\n ),\n\n case(\n\n r#\"{\"this_is_key\" : [1]}\"#,\n\n r#\"{\"this_is_key\" : {\"key\" : 1}}\"#,\n\n \"this_is_key\",\n\n \"map for array\"\n\n ),\n\n case(\n\n r#\"{\"this_is_key\" : [1]}\"#,\n\n r#\"{\"this_is_key\" : 1}\"#,\n\n \"this_is_key\",\n\n \"value for array\"\n\n ),\n\n case(\n\n r#\"{\"this_is_key\":{\"key\":1}}\"#,\n\n r#\"{\"this_is_key\":1}\"#,\n\n \"this_is_key\",\n\n \"value for map\"\n\n )\n\n)]\n", "file_path": "tests/configuration_merge_tests.rs", "rank": 97, "score": 65190.49846285614 }, { "content": " r#\"{\"array1\" : []}\"#,\n\n r#\"{\"array1\" : [4,5,6]}\"#,\n\n vec![4, 5, 6]\n\n ),\n\n case(\n\n r#\"{\"array1\" : [4,5,6]}\"#,\n\n r#\"{\"array1\" : []}\"#,\n\n vec![4, 5, 6]\n\n )\n\n)]\n\n\n", "file_path": "tests/configuration_merge_tests.rs", "rank": 98, "score": 65185.50017339492 } ]
Rust
src/logger.rs
dignifiedquire/rust-drand
57cd6bcb459fb3fca1deb11c5a789c413ee308e2
use std::cmp::max; use std::io::{stderr, stdout, Write}; use std::sync::atomic::{AtomicUsize, Ordering}; use ansi_term::{ANSIGenericString, Colour, Style}; use log::{Level, LevelFilter, Log, Metadata, Record, SetLoggerError}; use unicode_segmentation::UnicodeSegmentation; #[derive(Clone, Copy, Debug, Eq, Hash, Ord, PartialEq, PartialOrd)] pub enum Destination { Stdout, Stderr, } impl Destination { pub fn isatty(&self) -> bool { match *self { Destination::Stdout => atty::is(atty::Stream::Stdout), Destination::Stderr => atty::is(atty::Stream::Stderr), } } } impl Destination { fn write(&self) -> Box<dyn Write> { match *self { Destination::Stdout => Box::new(stdout()), Destination::Stderr => Box::new(stderr()), } } } impl Default for Destination { fn default() -> Destination { Destination::Stderr } } pub struct Logger { destination: Destination, level: LevelFilter, max_module_width: AtomicUsize, max_target_width: AtomicUsize, theme: Theme, } impl Logger { pub fn new(destination: Destination, level: LevelFilter, theme: Theme) -> Logger { Logger { destination, level, max_module_width: AtomicUsize::new(0), max_target_width: AtomicUsize::new(0), theme, } } pub fn set_logger(self) -> Result<(), SetLoggerError> { let level = self.level; log::set_boxed_logger(Box::new(self)).map(|()| log::set_max_level(level)) } fn update_module_width(&self, width: usize) -> usize { loop { let old = self.max_module_width.load(Ordering::SeqCst); let new = max(old, width); if self .max_module_width .compare_and_swap(old, new, Ordering::SeqCst) == old { return new; } } } fn update_target_width(&self, width: usize) -> usize { loop { let old = self.max_target_width.load(Ordering::SeqCst); let new = max(old, width); if self .max_target_width .compare_and_swap(old, new, Ordering::SeqCst) == old { return new; } } } } impl Default for Logger { fn default() -> Logger { let destination = Destination::default(); let theme = if destination.isatty() { Theme::default() } else { Theme::empty() }; Logger::new(destination, LevelFilter::Info, theme) } } impl Log for Logger { fn enabled(&self, metadata: &Metadata) -> bool { self.level .to_level() .map(|level| metadata.level() <= level) .unwrap_or(false) } fn flush(&self) {} fn log(&self, record: &Record) { if !self.enabled(record.metadata()) { return; } let module = record.module_path().unwrap_or("<unknown>"); let target = record.target(); let module_length = self.update_module_width(module.graphemes(true).count()); let _ = if module == target { writeln!( self.destination.write(), "{}|{:.*}| {}", self.theme.paint_log_level(record.level()), module_length, module, record.args() ) } else { let target_length = self.update_target_width(target.graphemes(true).count()); writeln!( self.destination.write(), "{}|{:.*}|{:.*}|{}", self.theme.paint_log_level(record.level()), module_length, module, target_length, target, record.args() ) }; } } #[derive(Clone, Copy, Debug, PartialEq)] pub struct Theme { pub error: Style, pub warn: Style, pub info: Style, pub debug: Style, pub trace: Style, pub module: Style, } impl Theme { pub fn empty() -> Theme { Theme { error: Style::new(), warn: Style::new(), info: Style::new(), debug: Style::new(), trace: Style::new(), module: Style::new(), } } pub fn paint_log_level(&self, level: Level) -> ANSIGenericString<'static, str> { let (style, name) = match level { Level::Error => (self.error, "😡 E "), Level::Warn => (self.warn, "😥 W "), Level::Info => (self.info, "😋 I "), Level::Debug => (self.debug, "🤔 D "), Level::Trace => (self.trace, "🤓 T "), }; style.paint(name) } } impl Default for Theme { fn default() -> Theme { Theme { error: Colour::Red.bold(), warn: Colour::Yellow.bold(), info: Colour::Cyan.normal(), debug: Colour::White.normal(), trace: Colour::White.dimmed(), module: Style::new(), } } } pub fn init( destination: Destination, level: LevelFilter, theme: Theme, ) -> Result<(), SetLoggerError> { platform_init(); Logger::new(destination, level, theme).set_logger() } pub fn init_level(level: LevelFilter) -> Result<(), SetLoggerError> { platform_init(); let mut logger = Logger::default(); logger.level = level; logger.set_logger() } pub fn init_to_defaults() -> Result<(), SetLoggerError> { platform_init(); Logger::default().set_logger() } #[cfg(windows)] fn platform_init() { use ansi_term::enable_ansi_support; let _ = enable_ansi_support(); } #[cfg(not(windows))] fn platform_init() {}
use std::cmp::max; use std::io::{stderr, stdout, Write}; use std::sync::atomic::{AtomicUsize, Ordering}; use ansi_term::{ANSIGenericString, Colour, Style}; use log::{Level, LevelFilter, Log, Metadata, Record, SetLoggerError}; use unicode_segmentation::UnicodeSegmentation; #[derive(Clone, Copy, Debug, Eq, Hash, Ord, PartialEq, PartialOrd)] pub enum Destination { Stdout, Stderr, } impl Destination { pub fn isatty(&self) -> bool { match *self { Destination::Stdout => atty::is(atty::Stream::Stdout), Destination::Stderr => atty::is(atty::Stream::Stderr), } } } impl Destination { fn write(&self) -> Box<dyn Write> { match *self { Destination::Stdout => Box::new(stdout()), Destination::Stderr => Box::new(stderr()),
, Debug, PartialEq)] pub struct Theme { pub error: Style, pub warn: Style, pub info: Style, pub debug: Style, pub trace: Style, pub module: Style, } impl Theme { pub fn empty() -> Theme { Theme { error: Style::new(), warn: Style::new(), info: Style::new(), debug: Style::new(), trace: Style::new(), module: Style::new(), } } pub fn paint_log_level(&self, level: Level) -> ANSIGenericString<'static, str> { let (style, name) = match level { Level::Error => (self.error, "😡 E "), Level::Warn => (self.warn, "😥 W "), Level::Info => (self.info, "😋 I "), Level::Debug => (self.debug, "🤔 D "), Level::Trace => (self.trace, "🤓 T "), }; style.paint(name) } } impl Default for Theme { fn default() -> Theme { Theme { error: Colour::Red.bold(), warn: Colour::Yellow.bold(), info: Colour::Cyan.normal(), debug: Colour::White.normal(), trace: Colour::White.dimmed(), module: Style::new(), } } } pub fn init( destination: Destination, level: LevelFilter, theme: Theme, ) -> Result<(), SetLoggerError> { platform_init(); Logger::new(destination, level, theme).set_logger() } pub fn init_level(level: LevelFilter) -> Result<(), SetLoggerError> { platform_init(); let mut logger = Logger::default(); logger.level = level; logger.set_logger() } pub fn init_to_defaults() -> Result<(), SetLoggerError> { platform_init(); Logger::default().set_logger() } #[cfg(windows)] fn platform_init() { use ansi_term::enable_ansi_support; let _ = enable_ansi_support(); } #[cfg(not(windows))] fn platform_init() {}
} } } impl Default for Destination { fn default() -> Destination { Destination::Stderr } } pub struct Logger { destination: Destination, level: LevelFilter, max_module_width: AtomicUsize, max_target_width: AtomicUsize, theme: Theme, } impl Logger { pub fn new(destination: Destination, level: LevelFilter, theme: Theme) -> Logger { Logger { destination, level, max_module_width: AtomicUsize::new(0), max_target_width: AtomicUsize::new(0), theme, } } pub fn set_logger(self) -> Result<(), SetLoggerError> { let level = self.level; log::set_boxed_logger(Box::new(self)).map(|()| log::set_max_level(level)) } fn update_module_width(&self, width: usize) -> usize { loop { let old = self.max_module_width.load(Ordering::SeqCst); let new = max(old, width); if self .max_module_width .compare_and_swap(old, new, Ordering::SeqCst) == old { return new; } } } fn update_target_width(&self, width: usize) -> usize { loop { let old = self.max_target_width.load(Ordering::SeqCst); let new = max(old, width); if self .max_target_width .compare_and_swap(old, new, Ordering::SeqCst) == old { return new; } } } } impl Default for Logger { fn default() -> Logger { let destination = Destination::default(); let theme = if destination.isatty() { Theme::default() } else { Theme::empty() }; Logger::new(destination, LevelFilter::Info, theme) } } impl Log for Logger { fn enabled(&self, metadata: &Metadata) -> bool { self.level .to_level() .map(|level| metadata.level() <= level) .unwrap_or(false) } fn flush(&self) {} fn log(&self, record: &Record) { if !self.enabled(record.metadata()) { return; } let module = record.module_path().unwrap_or("<unknown>"); let target = record.target(); let module_length = self.update_module_width(module.graphemes(true).count()); let _ = if module == target { writeln!( self.destination.write(), "{}|{:.*}| {}", self.theme.paint_log_level(record.level()), module_length, module, record.args() ) } else { let target_length = self.update_target_width(target.graphemes(true).count()); writeln!( self.destination.write(), "{}|{:.*}|{:.*}|{}", self.theme.paint_log_level(record.level()), module_length, module, target_length, target, record.args() ) }; } } #[derive(Clone, Copy
random
[ { "content": "pub fn group(\n\n key_paths: &[PathBuf],\n\n existing_group: Option<&PathBuf>,\n\n out: Option<&PathBuf>,\n\n period: Option<Duration>,\n\n) -> Result<()> {\n\n ensure!(\n\n existing_group.is_some() || key_paths.len() >= 3,\n\n \"groups must be at least 3 nodes large\"\n\n );\n\n\n\n let public_keys: Vec<_> = key_paths\n\n .iter()\n\n .map(|key_path| {\n\n info!(\"reading public identity from {}\", key_path.display());\n\n key::load_from_file(key_path)\n\n })\n\n .collect::<Result<_>>()?;\n\n\n\n let threshold = key::default_threshold(key_paths.len());\n", "file_path": "src/main.rs", "rank": 0, "score": 85238.05945094331 }, { "content": "pub fn sign(\n\n private_key: &dkg::Share,\n\n previous_signature: &[u8],\n\n previous_round: Round,\n\n round: Round,\n\n) -> Result<Vec<u8>> {\n\n let msg = hash(previous_signature, previous_round, round);\n\n <dkg::Scheme as ThresholdScheme>::partial_sign(private_key, &msg)\n\n .map_err(|err| anyhow!(\"failed to sign: {}\", err))\n\n}\n\n\n", "file_path": "src/beacon/beacon.rs", "rank": 3, "score": 82445.65867647254 }, { "content": "pub fn get() -> Result<()> {\n\n info!(\"get\");\n\n\n\n Ok(())\n\n}\n\n\n", "file_path": "src/main.rs", "rank": 4, "score": 79543.05737828811 }, { "content": "pub fn reset() -> Result<()> {\n\n info!(\"reset\");\n\n\n\n Ok(())\n\n}\n\n\n", "file_path": "src/main.rs", "rank": 5, "score": 79543.05737828811 }, { "content": "pub fn show() -> Result<()> {\n\n info!(\"show\");\n\n\n\n Ok(())\n\n}\n", "file_path": "src/main.rs", "rank": 6, "score": 79543.05737828811 }, { "content": "pub fn check_group() -> Result<()> {\n\n info!(\"check_group\");\n\n\n\n Ok(())\n\n}\n\n\n\npub async fn ping(control: usize) -> Result<()> {\n\n info!(\"sending ping\");\n\n\n\n daemon::ping(control).await?;\n\n\n\n info!(\"received pong\");\n\n\n\n Ok(())\n\n}\n\n\n", "file_path": "src/main.rs", "rank": 7, "score": 77030.85768838553 }, { "content": "/// The default threshold is calculated as floor(n * 2/3) + 1\n\npub fn default_threshold(n: usize) -> usize {\n\n ((n * 2) as f64 / 3.0).floor() as usize + 1\n\n}\n\n\n\n/// Holds the public key.\n\n#[derive(Debug, PartialEq, Clone, Serialize, Deserialize)]\n\npub struct Identity {\n\n #[serde(serialize_with = \"serialize_key\", deserialize_with = \"deserialize_key\")]\n\n public_key: PublicKey,\n\n address: Multiaddr,\n\n #[serde(\n\n serialize_with = \"serialize_peer_id\",\n\n deserialize_with = \"deserialize_peer_id\"\n\n )]\n\n peer_id: PeerId,\n\n}\n\n\n\nimpl Identity {\n\n pub fn public_key(&self) -> &PublicKey {\n\n &self.public_key\n", "file_path": "src/key/key.rs", "rank": 9, "score": 68212.57853009943 }, { "content": "pub fn write_to_file<P: AsRef<Path>, S: serde::ser::Serialize>(path: P, s: &S) -> Result<()> {\n\n let bytes = toml::to_vec(s).context(\"failed to serialize\")?;\n\n std::fs::write(path.as_ref(), &bytes)\n\n .with_context(|| format!(\"failed to write : {}\", path.as_ref().display()))?;\n\n Ok(())\n\n}\n", "file_path": "src/key/store.rs", "rank": 10, "score": 61150.18937549657 }, { "content": "pub fn keygen(address: Multiaddr, config_folder: &PathBuf) -> Result<()> {\n\n info!(\"Generating private / public key pair.\");\n\n let key_pair = key::Pair::new(address)?;\n\n\n\n let store = key::FileStore::new(config_folder)?;\n\n store.save_key_pair(&key_pair)?;\n\n\n\n info!(\"Generated keys at {}\", store.key_folder().display());\n\n info!(\"You can copy paste the following snippet to a common group.toml file:\");\n\n info!(\n\n \"\\n[[Nodes]]\\n{}\",\n\n toml::to_string_pretty(key_pair.public())?\n\n );\n\n info!(\"Or just collect all public key files and use the group command!\");\n\n\n\n Ok(())\n\n}\n\n\n", "file_path": "src/main.rs", "rank": 11, "score": 59713.33513571066 }, { "content": "fn hash(previous_signature: &[u8], previous_round: Round, round: Round) -> Vec<u8> {\n\n let mut hasher = Sha256::new();\n\n hasher.input(&previous_round.to_bytes());\n\n hasher.input(previous_signature);\n\n hasher.input(&round.to_bytes());\n\n hasher.result().as_ref().to_vec()\n\n}\n\n\n\n#[cfg(test)]\n\nmod tests {\n\n use super::*;\n\n use time::NumericalDuration;\n\n\n\n #[test]\n\n fn test_next_round() {\n\n let start = OffsetDateTime::now().timestamp();\n\n TEST_CLOCK.with(|t| *t.borrow_mut() = start);\n\n\n\n // start in 1 second\n\n let genesis = OffsetDateTime::from_unix_timestamp(start) + 1.seconds();\n", "file_path": "src/beacon/beacon.rs", "rank": 12, "score": 54671.313591841346 }, { "content": "/// Parse an address as multiaddr or as regular url.\n\npub fn multiaddr_from_url(url: &str) -> std::result::Result<Multiaddr, multiaddr::FromUrlErr> {\n\n match Multiaddr::from_str(url) {\n\n Ok(addr) => Ok(addr),\n\n Err(_) => multiaddr::from_url(url),\n\n }\n\n}\n\n\n", "file_path": "src/main.rs", "rank": 13, "score": 52044.84530327932 }, { "content": "#[derive(Debug)]\n\nenum NetworkEvent {\n\n Dkg(\n\n PeerId,\n\n std::result::Result<DkgProtocolMessage, serde_cbor::Error>,\n\n ),\n\n}\n\n\n\nimpl NodeBehaviour {\n\n /// Consumes the events list when polled.\n\n fn poll<TBehaviourIn>(\n\n &mut self,\n\n _: &mut Context,\n\n _params: &mut impl swarm::PollParameters,\n\n ) -> Poll<swarm::NetworkBehaviourAction<TBehaviourIn, NetworkEvent>> {\n\n if let Ok(event) = self.events.pop() {\n\n return Poll::Ready(swarm::NetworkBehaviourAction::GenerateEvent(event));\n\n }\n\n\n\n Poll::Pending\n\n }\n", "file_path": "src/swarm.rs", "rank": 14, "score": 48608.71154687794 }, { "content": "#[derive(Debug, StructOpt)]\n\nenum ShowCommand {\n\n /// Shows the private share.\n\n Share {},\n\n /// Shows the current group.toml used. The group.toml\n\n /// may contain the distributed public key if the DKG has been ran already.\n\n Group {\n\n /// Save the requested information into a separate file instead of stdout.\n\n #[structopt(long, short = \"o\", parse(from_os_str))]\n\n out: Option<PathBuf>,\n\n },\n\n /// Shows the collective key generated during DKG.\n\n Cokey {},\n\n /// Shows the long-term private key of a node.\n\n Private {},\n\n /// Shows the long-term public key of a node.\n\n Public {},\n\n}\n\n\n", "file_path": "src/main.rs", "rank": 15, "score": 48608.57386370751 }, { "content": "#[derive(Debug, StructOpt)]\n\nenum GetCommand {\n\n /// Get private randomness from the drand beacon as\n\n /// specified in group.toml. Only one node is contacted by\n\n /// default. Requests are ECIES-encrypted towards the public\n\n /// key of the contacted node. This command attempts to connect\n\n /// to the drand beacon via TLS and falls back to\n\n /// plaintext communication if the contacted node has not\n\n /// activated TLS in which case it prints a warning.\n\n Private {},\n\n /// Get the latest public randomness from the drand\n\n /// beacon and verify it against the collective public key\n\n /// as specified in group.toml. Only one node is contacted by\n\n /// default. This command attempts to connect to the drand\n\n /// beacon via TLS and falls back to plaintext communication\n\n /// if the contacted node has not activated TLS in which case\n\n /// it prints a warning.\n\n Public {},\n\n /// Get distributed public key generated during the DKG step.\n\n Cokey {},\n\n}\n\n\n", "file_path": "src/main.rs", "rank": 16, "score": 48608.57386370751 }, { "content": "#[derive(Debug, StructOpt)]\n\nenum DrandCommand {\n\n /// Start the drand daemon.\n\n Start {\n\n /// Set the port you want to listen to for control port commands.\n\n #[structopt(long, default_value = \"8888\")]\n\n control: usize,\n\n /// Push mode forces the daemon to start making beacon requests to the other node, instead of waiting the other\n\n /// nodes contact it to catch-up on the round.\n\n #[structopt(long)]\n\n push: bool,\n\n /// List of nodes to connecto to.\n\n addrs: Vec<Multiaddr>,\n\n },\n\n /// Stop a running drand daemon.\n\n Stop {\n\n /// Set the port you want to listen to for control port commands.\n\n #[structopt(long, default_value = \"8888\")]\n\n control: usize,\n\n },\n\n /// Launch a sharing protocol. If one group is given as\n", "file_path": "src/main.rs", "rank": 17, "score": 48608.57386370751 }, { "content": "#[derive(Debug, Clone, Serialize, Deserialize)]\n\nenum ControlResponse {\n\n Pong,\n\n Stopped,\n\n InitDkgSuccess,\n\n Error(String),\n\n}\n\n\n\nimpl ControlResponse {\n\n pub fn status_code(&self) -> u16 {\n\n match self {\n\n ControlResponse::Error(_) => 400,\n\n _ => 200,\n\n }\n\n }\n\n}\n\n\n\n/// Client to control the running daemon.\n\npub struct Client {\n\n server: String,\n\n client: surf::Client<http_client::native::NativeClient>,\n", "file_path": "src/control.rs", "rank": 18, "score": 48608.508799171046 }, { "content": "#[derive(Debug, Clone, Serialize, Deserialize)]\n\nenum ControlRequest {\n\n Ping,\n\n Stop,\n\n InitDkg {\n\n group_path: PathBuf,\n\n is_leader: bool,\n\n timeout: Duration,\n\n },\n\n}\n\n\n", "file_path": "src/control.rs", "rank": 19, "score": 48608.508799171046 }, { "content": "pub fn load_from_file<P: AsRef<Path>, S: serde::de::DeserializeOwned>(path: P) -> Result<S> {\n\n let bytes = std::fs::read(path.as_ref())\n\n .with_context(|| format!(\"failed to read data from {}\", path.as_ref().display()))?;\n\n let res = toml::from_slice(&bytes).context(\"failed to deserialize\")?;\n\n\n\n Ok(res)\n\n}\n\n\n", "file_path": "src/key/store.rs", "rank": 20, "score": 45225.54765909225 }, { "content": "/// Abstracts the loading and saving of any private/public cryptographic material to be used by drand.\n\npub trait Store {\n\n fn save_key_pair(&self, pair: &Pair) -> Result<()>;\n\n fn load_key_pair(&self) -> Result<Pair>;\n\n\n\n fn save_share(&self, share: &Share) -> Result<()>;\n\n fn load_share(&self) -> Result<Share>;\n\n\n\n fn save_dist_public(&self, share: &DistPublic) -> Result<()>;\n\n fn load_dist_public(&self) -> Result<DistPublic>;\n\n\n\n fn save_group(&self, share: &Group) -> Result<()>;\n\n fn load_group(&self) -> Result<Group>;\n\n}\n\n\n\nconst KEY_FOLDER_NAME: &str = \"key\";\n\nconst GROUP_FOLDER_NAME: &str = \"group\";\n\n\n\nconst KEY_FILE_NAME: &str = \"drand_id\";\n\nconst PRIVATE_EXTENSION: &str = \"private\";\n\nconst PUBLIC_EXTENSION: &str = \"public\";\n", "file_path": "src/key/store.rs", "rank": 21, "score": 43298.35079060611 }, { "content": "/// Store the results from a successfull DKG.\n\nfn save_dkg_result(\n\n res_node: Result<dkg::Node<dkg::node::Done>>,\n\n mut group: Group,\n\n store: &key::FileStore,\n\n) -> Result<()> {\n\n let node = res_node?;\n\n store.save_share(node.share()?)?;\n\n let dp = node.dist_public()?;\n\n store.save_dist_public(&dp)?;\n\n group.set_public_key(dp);\n\n\n\n store.save_group(&group)?;\n\n\n\n Ok(())\n\n}\n\n\n\n/// Setup a DKG.\n\nasync fn setup_dkg(\n\n board: Arc<\n\n Mutex<\n", "file_path": "src/daemon.rs", "rank": 24, "score": 40713.752854731385 }, { "content": "fn main() -> Result<()> {\n\n task::block_on(async move {\n\n let opts = Drand::from_args();\n\n\n\n opts.setup_logger();\n\n let config_folder = opts.folder.unwrap_or_else(get_default_folder);\n\n\n\n match opts.cmd {\n\n DrandCommand::Start { addrs, control, .. } => {\n\n let config = daemon::Config::new(addrs, config_folder, control);\n\n let mut d = daemon::Daemon::new(config)?;\n\n d.start().await\n\n }\n\n DrandCommand::Stop { control } => daemon::stop(control).await,\n\n DrandCommand::Share {\n\n group,\n\n control,\n\n leader,\n\n timeout,\n\n ..\n", "file_path": "src/main.rs", "rank": 25, "score": 40535.89586845046 }, { "content": "fn serialize_dist<S>(\n\n dist: &threshold::DistPublic<self::curve::KeyCurve>,\n\n serializer: S,\n\n) -> Result<S::Ok, S::Error>\n\nwhere\n\n S: Serializer,\n\n{\n\n let raw: Vec<_> = dist.clone().into();\n\n\n\n let mut seq = serializer.serialize_seq(Some(raw.len()))?;\n\n for element in raw {\n\n let value = hex::encode(element.marshal());\n\n seq.serialize_element(&value)?;\n\n }\n\n seq.end()\n\n}\n\n\n", "file_path": "src/dkg/mod.rs", "rank": 26, "score": 37904.17025478168 }, { "content": "fn get_default_folder() -> PathBuf {\n\n let home_dir = home::home_dir().expect(\"Unable to determine home_dir\");\n\n home_dir.join(DEFAULT_FOLDER_NAME)\n\n}\n\n\n", "file_path": "src/main.rs", "rank": 27, "score": 36776.90387764607 }, { "content": "fn deserialize_dist<'de, D>(\n\n deserializer: D,\n\n) -> Result<threshold::DistPublic<self::curve::KeyCurve>, D::Error>\n\nwhere\n\n D: Deserializer<'de>,\n\n{\n\n let hex_strings: Vec<String> = Deserialize::deserialize(deserializer)?;\n\n let coeffs = hex_strings\n\n .iter()\n\n .map(|s| {\n\n let bytes = hex::decode(s).map_err(|err| serde::de::Error::custom(err.to_string()))?;\n\n let mut coeff = self::curve::PublicKey::new();\n\n coeff\n\n .unmarshal(&bytes)\n\n .map_err(|err| serde::de::Error::custom(err.to_string()))?;\n\n Ok(coeff)\n\n })\n\n .collect::<Result<Vec<_>, _>>()?;\n\n\n\n let poly = coeffs.into();\n", "file_path": "src/dkg/mod.rs", "rank": 28, "score": 35493.990153408995 }, { "content": "/// Builds the transport stack that LibP2P will communicate over.\n\nfn build_transport(local_key: identity::Keypair) -> Libp2pStream {\n\n let dh_keys = noise::Keypair::<noise::X25519>::from_identity(&local_key)\n\n .expect(\"unable to generate Noise Keypair\");\n\n\n\n let transport = libp2p::tcp::TcpConfig::new().nodelay(true);\n\n let transport = libp2p::dns::DnsConfig::new(transport).unwrap();\n\n\n\n transport\n\n .upgrade(core::upgrade::Version::V1)\n\n .authenticate(noise::NoiseConfig::xx(dh_keys).into_authenticated())\n\n .multiplex(core::upgrade::SelectUpgrade::new(\n\n yamux::Config::default(),\n\n mplex::MplexConfig::new(),\n\n ))\n\n .map(|(peer, muxer), _| (peer, core::muxing::StreamMuxerBox::new(muxer)))\n\n .timeout(Duration::from_secs(20))\n\n .map_err(|err| io::Error::new(io::ErrorKind::Other, err))\n\n .boxed()\n\n}\n", "file_path": "src/swarm.rs", "rank": 29, "score": 30696.81911602101 }, { "content": "fn deserialize_key_pair<'de, D>(deserializer: D) -> Result<Keypair, D::Error>\n\nwhere\n\n D: Deserializer<'de>,\n\n{\n\n let hex_string: String = Deserialize::deserialize(deserializer)?;\n\n let mut bytes =\n\n hex::decode(&hex_string).map_err(|err| serde::de::Error::custom(err.to_string()))?;\n\n let res =\n\n Keypair::decode(&mut bytes).map_err(|err| serde::de::Error::custom(err.to_string()))?;\n\n\n\n Ok(res)\n\n}\n\n\n", "file_path": "src/key/key.rs", "rank": 30, "score": 25306.912228850684 }, { "content": "fn deserialize_peer_id<'de, D>(deserializer: D) -> Result<PeerId, D::Error>\n\nwhere\n\n D: Deserializer<'de>,\n\n{\n\n let raw_string: String = Deserialize::deserialize(deserializer)?;\n\n let res =\n\n PeerId::from_str(&raw_string).map_err(|err| serde::de::Error::custom(err.to_string()))?;\n\n\n\n Ok(res)\n\n}\n\n\n\n#[cfg(test)]\n\nmod tests {\n\n use super::*;\n\n\n\n use libp2p::multiaddr::multiaddr;\n\n\n\n #[test]\n\n fn test_key_public() {\n\n let addr = multiaddr!(Ip4([127, 0, 0, 1]), Tcp(1234u16));\n", "file_path": "src/key/key.rs", "rank": 31, "score": 24724.94228986639 }, { "content": "fn deserialize_key<'de, D, K: BlsSerialize>(deserializer: D) -> Result<K, D::Error>\n\nwhere\n\n D: Deserializer<'de>,\n\n{\n\n let hex_string: String = Deserialize::deserialize(deserializer)?;\n\n let bytes =\n\n hex::decode(&hex_string).map_err(|err| serde::de::Error::custom(err.to_string()))?;\n\n let res = K::from_bytes(&bytes).map_err(|err| serde::de::Error::custom(err.to_string()))?;\n\n\n\n Ok(res)\n\n}\n\n\n", "file_path": "src/key/key.rs", "rank": 32, "score": 23297.453735574585 }, { "content": "fn serialize_key_pair<S>(key: &Keypair, serializer: S) -> Result<S::Ok, S::Error>\n\nwhere\n\n S: Serializer,\n\n{\n\n let raw = key.encode();\n\n let value = hex::encode(&raw[..]);\n\n\n\n serializer.serialize_str(&value)\n\n}\n\n\n", "file_path": "src/key/key.rs", "rank": 33, "score": 23297.453735574585 }, { "content": "fn serialize_peer_id<S>(id: &PeerId, serializer: S) -> Result<S::Ok, S::Error>\n\nwhere\n\n S: Serializer,\n\n{\n\n let raw = id.to_string();\n\n serializer.serialize_str(&raw)\n\n}\n\n\n", "file_path": "src/key/key.rs", "rank": 34, "score": 22789.486021189 }, { "content": "fn serialize_key<S, K: BlsSerialize>(key: &K, serializer: S) -> Result<S::Ok, S::Error>\n\nwhere\n\n S: Serializer,\n\n{\n\n let raw = key.as_bytes();\n\n let value = hex::encode(&raw);\n\n\n\n serializer.serialize_str(&value)\n\n}\n\n\n", "file_path": "src/key/key.rs", "rank": 35, "score": 21596.165226389327 }, { "content": " /// Returns the index in the group of the partial signature.\n\n pub fn index(&self) -> Result<Index> {\n\n let (index, _) = dkg::Scheme::extract(&self.partial_signature)?;\n\n\n\n Ok(index)\n\n }\n\n}\n\n\n\n/// A specific round in the protocol.\n\n#[derive(Debug, Default, Clone, Copy, PartialEq, Eq, Hash, Serialize, Deserialize)]\n\npub struct Round(u64);\n\n\n\nimpl Round {\n\n /// The zero round.\n\n pub fn zero() -> Self {\n\n Round(0)\n\n }\n\n\n\n /// Returns the round as its byte representation.\n\n pub fn to_bytes(self) -> [u8; 8] {\n", "file_path": "src/beacon/beacon.rs", "rank": 39, "score": 15.866502269082922 }, { "content": " }\n\n\n\n pub fn previous_round(&self) -> Round {\n\n self.previous_round\n\n }\n\n\n\n pub fn previous_signature(&self) -> &[u8] {\n\n &self.previous_signature\n\n }\n\n}\n\n\n\nimpl From<&Beacon> for sled::IVec {\n\n fn from(beacon: &Beacon) -> Self {\n\n serde_cbor::to_vec(beacon).expect(\"invalid beacon\").into()\n\n }\n\n}\n\n\n\n#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]\n\npub struct PartialBeacon {\n\n /// The previous round this beacon points to.\n", "file_path": "src/beacon/beacon.rs", "rank": 45, "score": 12.43895131212039 }, { "content": " private_key_swarm: Keypair,\n\n public_key: Identity,\n\n}\n\n\n\nimpl PartialEq for Pair {\n\n fn eq(&self, other: &Self) -> bool {\n\n self.private_key_bls == other.private_key_bls\n\n && self.public_key == other.public_key\n\n && &self.private_key_swarm.encode()[..] == &other.private_key_swarm.encode()[..]\n\n }\n\n}\n\nimpl fmt::Debug for Pair {\n\n fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {\n\n f.debug_struct(\"Pair\")\n\n .field(\"private_key_bls\", &\"xxx\")\n\n .field(\"private_key_swarm\", &\"xxx\")\n\n .field(\"public_key\", &self.public_key)\n\n .finish()\n\n }\n\n}\n", "file_path": "src/key/key.rs", "rank": 46, "score": 12.251008668713645 }, { "content": "/// Wrapper around `threshold::DistPublic` for custom serialization.\n\n#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]\n\npub struct DistPublic(\n\n #[serde(\n\n serialize_with = \"serialize_dist\",\n\n deserialize_with = \"deserialize_dist\"\n\n )]\n\n threshold::DistPublic<self::curve::KeyCurve>,\n\n);\n\n\n\nimpl From<threshold::DistPublic<self::curve::KeyCurve>> for DistPublic {\n\n fn from(inner: threshold::DistPublic<self::curve::KeyCurve>) -> Self {\n\n Self(inner)\n\n }\n\n}\n\n\n\nimpl std::ops::Deref for DistPublic {\n\n type Target = threshold::DistPublic<self::curve::KeyCurve>;\n\n\n\n fn deref(&self) -> &Self::Target {\n\n &self.0\n\n }\n\n}\n\n\n", "file_path": "src/dkg/mod.rs", "rank": 48, "score": 10.33042103135301 }, { "content": "pub struct Config {\n\n addrs: Vec<Multiaddr>,\n\n config_folder: PathBuf,\n\n control_port: usize,\n\n}\n\n\n\nimpl Config {\n\n pub fn new(addrs: Vec<Multiaddr>, config_folder: PathBuf, control_port: usize) -> Self {\n\n Self {\n\n addrs,\n\n config_folder,\n\n control_port,\n\n }\n\n }\n\n}\n\n\n\n#[derive(Debug)]\n\npub struct Daemon {\n\n /// Configuration for the daemon.\n\n config: Config,\n", "file_path": "src/daemon.rs", "rank": 49, "score": 10.28686790237662 }, { "content": " let log_level = match self.verbose {\n\n 2 => log::LevelFilter::Debug,\n\n _ => log::LevelFilter::Info,\n\n };\n\n\n\n logger::init_level(log_level).expect(\"failed to initialize the logger\");\n\n }\n\n}\n\n\n\npub async fn share(\n\n group_path: &PathBuf,\n\n is_leader: bool,\n\n timeout: Duration,\n\n control: usize,\n\n _config_folder: &PathBuf,\n\n) -> Result<()> {\n\n info!(\"share\");\n\n\n\n // TODO: check and handle an existing group\n\n // let store = key::FileStore::new(config_folder)?;\n\n\n\n daemon::init_dkg(group_path, is_leader, *timeout, control).await?;\n\n\n\n Ok(())\n\n}\n\n\n", "file_path": "src/main.rs", "rank": 50, "score": 10.061997345858778 }, { "content": "pub enum ProtocolMessage {\n\n /// Contains the share of participant.\n\n Deal(dkg::BundledShares<KeyCurve>),\n\n /// Holds the response that a participant broadcasts after receiving a deal.\n\n Response(dkg::BundledResponses),\n\n /// Holds the justification from a dealer after a participant issued a complaint of a supposedly invalid deal.\n\n Justification(dkg::BundledJustification<KeyCurve>),\n\n}\n\n\n\nimpl std::fmt::Debug for ProtocolMessage {\n\n fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {\n\n match self {\n\n ProtocolMessage::Deal(_) => write!(f, \"ProtocolMessage::Deal\"),\n\n ProtocolMessage::Response(_) => write!(f, \"ProtocolMessage::Response\"),\n\n ProtocolMessage::Justification(_) => write!(f, \"ProtocolMessage::Justification\"),\n\n }\n\n }\n\n}\n\n\n\nimpl Board<Start> {\n", "file_path": "src/dkg/board.rs", "rank": 53, "score": 9.596443852555497 }, { "content": " nodes: Vec<Identity>,\n\n}\n\n\n\nimpl Group {\n\n /// Creates a minimal group.\n\n pub fn new(mut nodes: Vec<Identity>, threshold: usize) -> Self {\n\n // TODO: verify this sorting matches what the go impl does\n\n nodes.sort_by_key(|node| node.public_key().as_bytes());\n\n\n\n Group {\n\n period: None,\n\n nodes,\n\n threshold,\n\n public_key: None,\n\n }\n\n }\n\n\n\n pub fn public_key(&self) -> Option<&DistPublic> {\n\n self.public_key.as_ref()\n\n }\n", "file_path": "src/key/group.rs", "rank": 54, "score": 9.497010104645002 }, { "content": "use time::{Duration, OffsetDateTime};\n\n\n\nuse anyhow::{anyhow, Result};\n\nuse serde::{Deserialize, Serialize};\n\nuse sha2::{Digest, Sha256};\n\nuse threshold::{\n\n sig::{tbls::Serializer, Scheme, ThresholdScheme},\n\n Index,\n\n};\n\n\n\nuse crate::dkg;\n\n\n\n/// The randomness and the info to verify it.\n\n#[derive(Debug, PartialEq, Eq, Serialize, Deserialize)]\n\npub struct Beacon {\n\n /// The previous round this beacon points to.\n\n ///\n\n /// The beacon chain can have gaps if the network has been down for a while. The rule\n\n /// here is that one round corresponds to one exact time given a genesis time.\n\n previous_round: Round,\n", "file_path": "src/beacon/beacon.rs", "rank": 55, "score": 9.439722263768958 }, { "content": "}\n\n\n\nimpl Client {\n\n /// Creates a new control client, bound to the given address.\n\n pub fn new(addr: impl AsRef<str>) -> Self {\n\n Client {\n\n server: addr.as_ref().to_string(),\n\n client: surf::Client::new(),\n\n }\n\n }\n\n\n\n /// Pings the daemon, returns `Ok(())` if sucessfull.\n\n pub async fn ping(&self) -> Result<()> {\n\n match self.post(&ControlRequest::Ping).await? {\n\n ControlResponse::Pong => Ok(()),\n\n res => Err(anyhow!(\"Invalid response: {:?}\", res)),\n\n }\n\n }\n\n\n\n /// Stops a running daemon.\n", "file_path": "src/control.rs", "rank": 56, "score": 8.946139511165203 }, { "content": "}\n\n\n\npub struct Start(dkg::DKG<KeyCurve>);\n\npub struct One(dkg::DKGWaitingShare<KeyCurve>);\n\npub struct Two(dkg::DKGWaitingResponse<KeyCurve>);\n\npub struct Three(dkg::DKGWaitingJustification<KeyCurve>);\n\npub struct Done(Result<dkg::DKGOutput<KeyCurve>>);\n\n\n\nimpl Node<Start> {\n\n pub fn new(\n\n index: usize,\n\n private: PrivateKey,\n\n public: PublicKey,\n\n peer_id: PeerId,\n\n group: dkg::Group<KeyCurve>,\n\n ) -> Result<Self> {\n\n // XXX use lifetimes to remove cloning requirement\n\n let d = dkg::DKG::new(private, group.clone())?;\n\n Ok(Self {\n\n public,\n", "file_path": "src/dkg/node.rs", "rank": 57, "score": 8.799299199746354 }, { "content": " partial_beacon_store: sled::Tree,\n\n config: Arc<HandlerConfig>,\n\n /// Index in the group of the node running this beacon.\n\n index: usize,\n\n}\n\n\n\n/// Configuration for the [Handler].\n\n#[derive(Debug)]\n\npub struct HandlerConfig {\n\n pub share: dkg::Share,\n\n pub public_key: <dkg::Scheme as Scheme>::Public,\n\n pub private_key: key::Pair,\n\n pub group: key::Group,\n\n pub wait_time: Duration,\n\n}\n\n\n\n#[derive(Debug, Clone, PartialEq, Eq)]\n\npub enum BeaconRequest {\n\n /// Partial beacon, sent out from the pariticipants.\n\n PartialBeacon(PartialBeacon),\n", "file_path": "src/beacon/handler.rs", "rank": 58, "score": 8.745768512809427 }, { "content": "use std::collections::HashMap;\n\nuse std::time::Duration;\n\n\n\nuse anyhow::{bail, ensure, Result};\n\nuse async_std::prelude::*;\n\nuse async_std::sync::{channel, Arc, Receiver, RwLock, Sender};\n\nuse futures::future::Either;\n\nuse libp2p::PeerId;\n\nuse log::info;\n\nuse serde::{Deserialize, Serialize};\n\nuse stop_token::StopSource;\n\nuse threshold::dkg;\n\nuse threshold::*;\n\n\n\nuse super::curve::{KeyCurve, PublicKey};\n\n\n\npub struct Board<S> {\n\n group: dkg::Group<KeyCurve>,\n\n state: S,\n\n sender: Sender<(PeerId, ProtocolMessage)>,\n", "file_path": "src/dkg/board.rs", "rank": 59, "score": 8.694101615774077 }, { "content": "\n\n pub fn set_public_key(&mut self, key: DistPublic) {\n\n self.public_key = Some(key);\n\n }\n\n\n\n pub fn threshold(&self) -> usize {\n\n self.threshold\n\n }\n\n\n\n /// Creats a group with an existing public key.\n\n pub fn load(mut nodes: Vec<Identity>, threshold: usize, public_key: DistPublic) -> Self {\n\n // TODO: verify this sorting matches what the go impl does\n\n nodes.sort_by_key(|node| node.public_key().as_bytes());\n\n\n\n Group {\n\n period: None,\n\n nodes,\n\n threshold,\n\n public_key: Some(public_key),\n\n }\n", "file_path": "src/key/group.rs", "rank": 60, "score": 8.629048887562428 }, { "content": "use anyhow::{anyhow, Result};\n\nuse async_std::prelude::*;\n\nuse async_std::sync::{channel, Arc, Receiver, Sender};\n\nuse log::error;\n\nuse threshold::sig::Scheme;\n\nuse time::{Duration, OffsetDateTime};\n\n\n\nuse crate::dkg;\n\nuse crate::key;\n\n\n\nuse super::beacon::{self, Beacon, PartialBeacon, Round};\n\n\n\nconst DB_BEACON_STORE: &[u8] = b\"beacon\";\n\nconst DB_PARTIAL_BEACON_STORE: &[u8] = b\"partial-beacon\";\n\n\n\n/// Manages beacon generation and responding to network requests.\n\n#[derive(Debug)]\n\npub struct Handler {\n\n /// Stores the historic data of the beacons.\n\n beacon_store: sled::Tree,\n", "file_path": "src/beacon/handler.rs", "rank": 61, "score": 8.578494493540585 }, { "content": "use std::convert::TryInto;\n\nuse std::time::Duration;\n\n\n\nuse blake2b_simd::Params;\n\nuse bls_signatures::Serialize as BlsSerialize;\n\nuse serde::{Deserialize, Serialize};\n\n\n\nuse super::{default_threshold, Identity};\n\nuse crate::dkg::DistPublic;\n\n\n\n/// Holds all information about a group of drand nodes.\n\n#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]\n\npub struct Group {\n\n /// The threshold to setup during the DKG or resharing protocol.\n\n threshold: usize,\n\n /// Used for the beacon randomness generation.\n\n period: Option<Duration>,\n\n /// The distributed public key of this group. It is nil if the group has not ran a DKG protocol yet.\n\n public_key: Option<DistPublic>,\n\n /// List of ids forming this group.\n", "file_path": "src/key/group.rs", "rank": 62, "score": 8.258615504006377 }, { "content": " &mut self.period\n\n }\n\n\n\n /// Find the index of the given identity.\n\n pub fn index(&self, other: &Identity) -> Option<usize> {\n\n self.nodes.iter().position(|n| n == other)\n\n }\n\n\n\n pub fn len(&self) -> usize {\n\n self.nodes.len()\n\n }\n\n\n\n pub fn is_empty(&self) -> bool {\n\n self.nodes.is_empty()\n\n }\n\n}\n\n\n\nimpl TryInto<crate::dkg::Group> for Group {\n\n type Error = threshold::dkg::DKGError;\n\n\n", "file_path": "src/key/group.rs", "rank": 63, "score": 7.778898159819988 }, { "content": "mod group;\n\nmod key;\n\nmod store;\n\n\n\npub use self::group::*;\n\npub use self::key::*;\n\npub use self::store::*;\n", "file_path": "src/key/mod.rs", "rank": 64, "score": 7.756475762513006 }, { "content": "\n\nimpl Pair {\n\n /// Returns a freshly created private / public key pair. Currently, drand only supports Bls12_381.\n\n pub fn new(address: Multiaddr) -> Result<Self> {\n\n let private_key_bls = PrivateKey::generate(&mut rand::rngs::OsRng);\n\n let public_key = private_key_bls.public_key();\n\n\n\n let private_key_swarm = Keypair::generate();\n\n let private_key_enum = identity::Keypair::Ed25519(private_key_swarm.clone());\n\n let peer_id = PeerId::from(private_key_enum.public());\n\n\n\n Ok(Pair {\n\n private_key_bls,\n\n private_key_swarm,\n\n public_key: Identity {\n\n public_key,\n\n peer_id,\n\n address,\n\n },\n\n })\n", "file_path": "src/key/key.rs", "rank": 65, "score": 7.65093187734305 }, { "content": "mod curve;\n\nmod orchestrator;\n\n\n\npub mod board;\n\npub mod node;\n\n\n\npub type Group = threshold::dkg::Group<self::curve::KeyCurve>;\n\npub type DkgNode = threshold::dkg::Node<self::curve::KeyCurve>;\n\npub type Share = threshold::Share<self::curve::PrivateKey>;\n\n\n\npub use self::board::{Board, ProtocolMessage};\n\npub use self::curve::*;\n\npub use self::node::Node;\n\npub use threshold::Index;\n\n\n\nuse serde::de::Deserializer;\n\nuse serde::ser::{SerializeSeq, Serializer};\n\nuse serde::{Deserialize, Serialize};\n\nuse threshold::group::{Element, Encodable};\n\n\n", "file_path": "src/dkg/mod.rs", "rank": 66, "score": 7.625303607456994 }, { "content": "use std::path::PathBuf;\n\nuse std::time::Duration;\n\n\n\npub struct Config {\n\n pub config_folder: PathBuf,\n\n pub db_folder: PathBuf,\n\n pub listen_addr: Option<String>,\n\n pub control_port: usize,\n\n // grpc_opts []grpc.DialOption\n\n // callOpts []grpc.CallOption\n\n pub dkg_timeout: Duration,\n\n // boltOpts *bolt.Options\n\n // beaconCbs []func(*beacon.Beacon)\n\n // dkgCallback func(*key.Share)\n\n pub insecure: bool,\n\n pub cert_path: PathBuf,\n\n pub key_path: PathBuf,\n\n // certmanager *net.CertManager\n\n // clock clock.Clock\n\n}\n", "file_path": "src/core.rs", "rank": 67, "score": 7.515454261688189 }, { "content": "use std::convert::TryInto;\n\nuse std::path::PathBuf;\n\nuse std::time::Duration;\n\n\n\nuse anyhow::{bail, Result};\n\nuse async_std::prelude::*;\n\nuse async_std::{\n\n sync::{channel, Arc, Mutex, Receiver, RwLock, Sender},\n\n task,\n\n};\n\nuse futures::StreamExt;\n\nuse libp2p::{Multiaddr, PeerId};\n\nuse log::{error, info, warn};\n\n\n\nuse crate::control;\n\nuse crate::dkg;\n\nuse crate::key::{self, Group, Pair, Store};\n\nuse crate::swarm::{DkgProtocolMessage, Node, NodeAction, NodeEvent};\n\n\n\n#[derive(Debug)]\n", "file_path": "src/daemon.rs", "rank": 68, "score": 7.38639954242584 }, { "content": " pub async fn stop(&self) -> Result<()> {\n\n match self.post(&ControlRequest::Stop).await? {\n\n ControlResponse::Stopped => Ok(()),\n\n res => Err(anyhow!(\"invalid response: {:?}\", res)),\n\n }\n\n }\n\n\n\n /// Start the dkg protocol.\n\n pub async fn init_dkg(\n\n &self,\n\n group_path: &PathBuf,\n\n is_leader: bool,\n\n timeout: Duration,\n\n ) -> Result<()> {\n\n match self\n\n .post(&ControlRequest::InitDkg {\n\n group_path: group_path.clone(),\n\n is_leader,\n\n timeout,\n\n })\n", "file_path": "src/control.rs", "rank": 69, "score": 7.318055230181331 }, { "content": "use anyhow::{anyhow, Result};\n\nuse futures::future::Either;\n\nuse libp2p::PeerId;\n\nuse log::info;\n\nuse threshold::dkg;\n\nuse threshold::sig::ThresholdScheme;\n\nuse threshold::*;\n\n\n\nuse super::board::{self, Board};\n\nuse super::curve::{KeyCurve, PrivateKey, PublicKey, Scheme};\n\n\n\n/// Node holds the logic of a participants, for the different phases of the example.\n\npub struct Node<S> {\n\n public: PublicKey,\n\n peer_id: PeerId,\n\n // Index is a type alias to represent the index of a participant. It can be\n\n // changed depending on the size of the network - u16 is likely to work for\n\n // most cases though.\n\n index: Index,\n\n state: S,\n", "file_path": "src/dkg/node.rs", "rank": 70, "score": 6.941469997574833 }, { "content": "//! This module holds the curve to use for the example. One can switch the curve\n\n//! by changing the exported type `Curve`.\n\n\n\npub use threshold::curve::bls12381::{Curve as G1Curve, PairingCurve as Pairing};\n\nuse threshold::group::Curve;\n\nuse threshold::sig::tbls::TG1Scheme;\n\n\n\npub type KeyCurve = G1Curve;\n\npub type PrivateKey = <KeyCurve as Curve>::Scalar;\n\npub type PublicKey = <KeyCurve as Curve>::Point;\n\n/// The signature scheme used for signing and verifying the randomness.\n\npub type Scheme = TG1Scheme<Pairing>;\n", "file_path": "src/dkg/curve.rs", "rank": 71, "score": 6.895697605000922 }, { "content": " }\n\n}\n\n\n\nimpl InnerFileStore {\n\n pub fn key_folder(&self) -> &PathBuf {\n\n &self.key_folder\n\n }\n\n}\n\n\n\nimpl Store for InnerFileStore {\n\n /// First saves the private key in a file with tight permissions and then saves the public part in another file.\n\n fn save_key_pair(&self, pair: &Pair) -> Result<()> {\n\n let bytes = toml::to_vec(pair).context(\"failed to serialize keypair\")?;\n\n // TODO: secure file permissions\n\n std::fs::write(&self.private_key_file, &bytes).with_context(|| {\n\n format!(\n\n \"failed to write keypair to: {}\",\n\n &self.private_key_file.display()\n\n )\n\n })?;\n", "file_path": "src/key/store.rs", "rank": 72, "score": 6.856912082252264 }, { "content": " peer_id,\n\n index,\n\n state: One(ndkg),\n\n })\n\n }\n\n}\n\n\n\nimpl Node<One> {\n\n pub async fn dkg_phase2(\n\n self,\n\n board: &mut Board<board::Two>,\n\n shares: &Vec<dkg::BundledShares<KeyCurve>>,\n\n ) -> Result<Node<Two>> {\n\n let Self {\n\n peer_id,\n\n public,\n\n index,\n\n state,\n\n } = self;\n\n\n", "file_path": "src/dkg/node.rs", "rank": 73, "score": 6.699574140911974 }, { "content": " let kp = Pair::new(addr.clone()).unwrap();\n\n\n\n assert_eq!(kp.public().address(), &addr);\n\n\n\n let toml_str = toml::to_string(&kp).unwrap();\n\n let kp_ret: Pair = toml::from_str(&toml_str).unwrap();\n\n\n\n assert_eq!(&kp, &kp_ret);\n\n\n\n let toml_pub = toml::to_string(kp.public()).unwrap();\n\n let pub_ret: Identity = toml::from_str(&toml_pub).unwrap();\n\n assert_eq!(kp.public(), &pub_ret);\n\n }\n\n}\n", "file_path": "src/key/key.rs", "rank": 74, "score": 6.618679525381746 }, { "content": " /// NOTE: It currently does NOT take into account the distributed public key when\n\n /// set for simplicity (we want old nodes and new nodes to easily refer to the\n\n /// same group for example). This may cause trouble in the future and may require\n\n /// more thoughts.\n\n pub fn hash(&self) -> String {\n\n let mut hash = Params::new().hash_length(32).to_state();\n\n\n\n for (i, node) in self.nodes.iter().enumerate() {\n\n hash.update(&(i as u32).to_le_bytes());\n\n hash.update(&node.public_key().as_bytes());\n\n }\n\n\n\n hex::encode(&hash.finalize())\n\n }\n\n\n\n pub fn period(&self) -> &Option<Duration> {\n\n &self.period\n\n }\n\n\n\n pub fn period_mut(&mut self) -> &mut Option<Duration> {\n", "file_path": "src/key/group.rs", "rank": 75, "score": 6.600982833875148 }, { "content": "use std::path::{Path, PathBuf};\n\n\n\nuse anyhow::{Context, Result};\n\nuse async_std::sync::Arc;\n\nuse log::info;\n\n\n\nuse super::{Group, Pair};\n\nuse crate::dkg::{DistPublic, Share};\n\n\n\n/// Abstracts the loading and saving of any private/public cryptographic material to be used by drand.\n", "file_path": "src/key/store.rs", "rank": 76, "score": 6.489423635873988 }, { "content": " /// The local key pair.\n\n local_key_pair: Pair,\n\n /// Local file store.\n\n store: key::FileStore,\n\n}\n\n\n\nimpl Daemon {\n\n /// Construct a new daemon.\n\n pub fn new(config: Config) -> Result<Self> {\n\n let store = key::FileStore::new(&config.config_folder)?;\n\n let local_key_pair = store.load_key_pair()?;\n\n\n\n Ok(Self {\n\n config,\n\n local_key_pair,\n\n store,\n\n })\n\n }\n\n\n\n fn create_node(\n", "file_path": "src/daemon.rs", "rank": 77, "score": 6.464577575378641 }, { "content": " previous_round: Round,\n\n /// The signature from the previous round.\n\n previous_signature: Vec<u8>,\n\n /// The current round number of this beacon.\n\n round: Round,\n\n /// The partial signature, being built during the current round.\n\n partial_signature: Vec<u8>,\n\n}\n\n\n\nimpl From<&PartialBeacon> for sled::IVec {\n\n fn from(beacon: &PartialBeacon) -> Self {\n\n serde_cbor::to_vec(beacon)\n\n .expect(\"invalid partial beacon\")\n\n .into()\n\n }\n\n}\n\n\n\nimpl PartialBeacon {\n\n pub fn new(\n\n previous_round: Round,\n", "file_path": "src/beacon/beacon.rs", "rank": 78, "score": 6.3964949775816216 }, { "content": " previous_signature: Vec<u8>,\n\n round: Round,\n\n partial_signature: Vec<u8>,\n\n ) -> Self {\n\n Self {\n\n previous_round,\n\n previous_signature,\n\n round,\n\n partial_signature,\n\n }\n\n }\n\n\n\n pub fn round(&self) -> Round {\n\n self.round\n\n }\n\n\n\n pub fn partial_signature(&self) -> &[u8] {\n\n &self.partial_signature\n\n }\n\n\n", "file_path": "src/beacon/beacon.rs", "rank": 79, "score": 6.265108063993796 }, { "content": "use std::path::PathBuf;\n\nuse std::time::Duration;\n\n\n\nuse anyhow::{anyhow, Result};\n\nuse async_std::sync::Sender;\n\nuse serde::{Deserialize, Serialize};\n\n\n\n/// Server that responds to the control rpc commands.\n\npub struct Server {\n\n server: tide::Server<State>,\n\n}\n\n\n", "file_path": "src/control.rs", "rank": 80, "score": 6.137409286213693 }, { "content": " pub(super) async fn publish_justifications(\n\n &self,\n\n peer_id: PeerId,\n\n sender_pk: &PublicKey,\n\n bundle: dkg::BundledJustification<KeyCurve>,\n\n ) -> Result<()> {\n\n self.check_authenticity(sender_pk, bundle.dealer_idx)?;\n\n self.sender\n\n .send((peer_id, ProtocolMessage::Justification(bundle)))\n\n .await;\n\n Ok(())\n\n }\n\n}\n\n\n\nimpl<S> Board<S> {\n\n pub fn stop(&mut self) {\n\n // Interrupts the receiver stream, stopping the task started in `Self::start`.\n\n self.stop_source.take();\n\n }\n\n\n", "file_path": "src/dkg/board.rs", "rank": 81, "score": 6.073531815573949 }, { "content": "}\n\n\n\n// TODO: implement chain sync\n\n\n\nimpl Handler {\n\n pub fn new(store: sled::Db, config: HandlerConfig) -> Result<Self> {\n\n let index = config\n\n .group\n\n .index(config.private_key.public())\n\n .ok_or_else(|| anyhow!(\"keypair not included in teh given group\"))?;\n\n\n\n let beacon_store = store.open_tree(DB_BEACON_STORE)?;\n\n let partial_beacon_store = store.open_tree(DB_PARTIAL_BEACON_STORE)?;\n\n\n\n Ok(Self {\n\n beacon_store,\n\n partial_beacon_store,\n\n config: Arc::new(config),\n\n index,\n\n })\n", "file_path": "src/beacon/handler.rs", "rank": 82, "score": 5.888234890234003 }, { "content": " receiver: Receiver<(PeerId, ProtocolMessage)>,\n\n timeout: Duration,\n\n /// Token to stop the receiver stream.\n\n stop_source: Option<StopSource>,\n\n deals: Arc<RwLock<HashMap<PeerId, dkg::BundledShares<KeyCurve>>>>,\n\n deals_done: Option<Receiver<()>>,\n\n responses: Arc<RwLock<HashMap<PeerId, dkg::BundledResponses>>>,\n\n responses_done: Option<Receiver<()>>,\n\n justifications: Arc<RwLock<HashMap<PeerId, dkg::BundledJustification<KeyCurve>>>>,\n\n justifications_done: Option<Receiver<()>>,\n\n}\n\n\n\npub struct Start;\n\npub struct One;\n\npub struct Two;\n\npub struct Three;\n\npub struct Done;\n\n\n\n/// The messages a participant sends and receives during the dkg.\n\n#[derive(Clone, Serialize, Deserialize)]\n", "file_path": "src/dkg/board.rs", "rank": 83, "score": 5.839826054968645 }, { "content": "#![deny(clippy::all)]\n\n\n\nuse std::path::PathBuf;\n\nuse std::str::FromStr;\n\n\n\nuse anyhow::{ensure, Context, Result};\n\nuse async_std::task;\n\nuse humantime::Duration;\n\nuse lazy_static::lazy_static;\n\nuse libp2p::{multiaddr, Multiaddr};\n\nuse log::info;\n\nuse structopt::StructOpt;\n\n\n\nuse drand::{\n\n daemon,\n\n key::{self, Store},\n\n logger,\n\n};\n\n\n\nconst DEFAULT_FOLDER_NAME: &str = \".drand\";\n\n\n\nlazy_static! {\n\n static ref DEFAULT_TIMEOUT: Duration = std::time::Duration::from_secs(60).into();\n\n}\n\n\n\n/// Parse an address as multiaddr or as regular url.\n", "file_path": "src/main.rs", "rank": 84, "score": 5.777122244606529 }, { "content": "use anyhow::Result;\n\nuse async_std::prelude::*;\n\nuse async_std::{\n\n io,\n\n sync::{channel, Receiver, Sender},\n\n task,\n\n};\n\nuse futures::StreamExt;\n\nuse libp2p::{\n\n core,\n\n core::muxing::StreamMuxerBox,\n\n core::transport::boxed::Boxed,\n\n floodsub::{self, Floodsub, FloodsubEvent},\n\n identity, mplex, noise,\n\n swarm::{self, NetworkBehaviourEventProcess},\n\n yamux, Multiaddr, NetworkBehaviour, PeerId, Swarm, Transport,\n\n};\n\nuse log::{info, warn};\n\nuse serde::{Deserialize, Serialize};\n\nuse std::{\n\n io::Error,\n\n task::{Context, Poll},\n\n time::Duration,\n\n};\n\n\n", "file_path": "src/swarm.rs", "rank": 85, "score": 5.538192404343041 }, { "content": " });\n\n\n\n server\n\n }\n\n\n\n pub async fn listen(self, addr: impl async_std::net::ToSocketAddrs) -> Result<()> {\n\n self.server.listen(addr).await?;\n\n Ok(())\n\n }\n\n}\n\n\n\nasync fn main_control_point(mut req: tide::Request<State>) -> Result<ControlResponse> {\n\n match req.body_json().await? {\n\n ControlRequest::Ping => Ok(ControlResponse::Pong),\n\n ControlRequest::InitDkg {\n\n group_path,\n\n is_leader,\n\n timeout,\n\n } => {\n\n let state = req.state();\n", "file_path": "src/control.rs", "rank": 86, "score": 5.452823908401681 }, { "content": " fn now() -> OffsetDateTime {\n\n OffsetDateTime::now()\n\n }\n\n\n\n #[cfg(test)]\n\n fn now() -> OffsetDateTime {\n\n TEST_CLOCK.with(|t| OffsetDateTime::from_unix_timestamp(*t.borrow()))\n\n }\n\n}\n\n\n\n#[cfg(test)]\n\nthread_local!(static TEST_CLOCK: std::cell::RefCell<i64> = std::cell::RefCell::new(0));\n\n\n\nimpl From<u64> for Round {\n\n fn from(val: u64) -> Self {\n\n Round(val)\n\n }\n\n}\n\n\n\nimpl From<Round> for u64 {\n\n fn from(val: Round) -> Self {\n\n val.0\n\n }\n\n}\n\n\n", "file_path": "src/beacon/beacon.rs", "rank": 87, "score": 5.326905231685023 }, { "content": "pub enum NodeEvent {\n\n ReceiveDkg(PeerId, DkgProtocolMessage),\n\n}\n\n\n\n/// Protocol Messages for the DKG flow. Transmitted via floodsub.\n\n#[derive(Debug, Clone, Serialize, Deserialize)]\n\npub enum DkgProtocolMessage {\n\n Start,\n\n Message(crate::dkg::ProtocolMessage),\n\n}\n\n\n", "file_path": "src/swarm.rs", "rank": 88, "score": 5.273793453560497 }, { "content": " macro_rules! log_err {\n\n ($res:expr) => {\n\n match $res {\n\n Ok(res) => res,\n\n Err(err) => {\n\n error!(\"{}\", err);\n\n continue;\n\n }\n\n }\n\n };\n\n }\n\n\n\n // process exsting once\n\n for value in store.scan_prefix(&prefix).values() {\n\n let value = log_err!(value);\n\n let partial_beacon: PartialBeacon = log_err!(serde_cbor::from_slice(&value));\n\n partials.push(partial_beacon.partial_signature().to_vec());\n\n if partials.len() >= threshold {\n\n break;\n\n }\n", "file_path": "src/beacon/handler.rs", "rank": 89, "score": 5.238915474690832 }, { "content": "\n\n <dkg::Scheme as ThresholdScheme>::verify(public_key, &msg, &self.signature)\n\n .map_err(|err| anyhow!(\"invalid beacon: {}\", err))?;\n\n\n\n Ok(())\n\n }\n\n\n\n /// The message that is actually signed and verified.\n\n ///\n\n /// Currently: `Sha256(previous_round || previous_signature || round)`.\n\n pub fn message(&self) -> Vec<u8> {\n\n hash(&self.previous_signature, self.previous_round, self.round)\n\n }\n\n\n\n pub fn round(&self) -> Round {\n\n self.round\n\n }\n\n\n\n pub fn signature(&self) -> &[u8] {\n\n &self.signature\n", "file_path": "src/beacon/beacon.rs", "rank": 90, "score": 5.151440873013019 }, { "content": " /// The signature from the previous round.\n\n previous_signature: Vec<u8>,\n\n /// The current round number of this beacon.\n\n round: Round,\n\n /// The BLS signature over `round || previous_randomnes`\n\n signature: Vec<u8>,\n\n}\n\n\n\nimpl Beacon {\n\n pub fn aggregate(\n\n public_key: &<dkg::Scheme as Scheme>::Public,\n\n threshold: usize,\n\n partials: &[Vec<u8>],\n\n previous_round: Round,\n\n previous_signature: Vec<u8>,\n\n round: Round,\n\n ) -> Result<Self> {\n\n let signature = dkg::Scheme::aggregate(threshold, partials)\n\n .map_err(|err| anyhow!(\"failed to aggregate: {}\", err))?;\n\n\n", "file_path": "src/beacon/beacon.rs", "rank": 91, "score": 5.096788537132132 }, { "content": " }\n\n }\n\n }\n\n}\n\n\n\nimpl Node {\n\n pub fn new(\n\n local_key: &identity::ed25519::Keypair,\n\n local_peer_id: &PeerId,\n\n listen_addr: Multiaddr,\n\n action_receiver: Receiver<NodeAction>,\n\n event_sender: Sender<NodeEvent>,\n\n ) -> Result<Self> {\n\n let local_key = identity::Keypair::Ed25519(local_key.clone());\n\n info!(\"Local peer id: {:?}\", local_peer_id);\n\n\n\n let transport = build_transport(local_key);\n\n\n\n let topic = floodsub::Topic::new(\"drand\");\n\n let dkg_topic = floodsub::Topic::new(\"drand-dkg\");\n", "file_path": "src/swarm.rs", "rank": 92, "score": 5.004688056623392 }, { "content": " receiver,\n\n timeout,\n\n stop_source,\n\n deals,\n\n deals_done,\n\n responses,\n\n responses_done,\n\n justifications,\n\n justifications_done,\n\n }\n\n }\n\n\n\n pub async fn needs_justifications(&self) -> bool {\n\n !self.responses.read().await.is_empty()\n\n }\n\n\n\n pub async fn get_shares(&self) -> Vec<dkg::BundledShares<KeyCurve>> {\n\n self.deals.read().await.values().cloned().collect()\n\n }\n\n\n", "file_path": "src/dkg/board.rs", "rank": 93, "score": 5.002405840011759 }, { "content": " let beacon = Beacon {\n\n previous_round,\n\n previous_signature,\n\n round,\n\n signature,\n\n };\n\n\n\n beacon.verify(public_key)?;\n\n\n\n Ok(beacon)\n\n }\n\n\n\n /// Returns the hashed signature.\n\n pub fn randomness(&self) -> Vec<u8> {\n\n Sha256::digest(&self.signature).as_ref().to_vec()\n\n }\n\n\n\n /// Verifies this beacon with the provided public key.\n\n pub fn verify(&self, public_key: &<dkg::Scheme as Scheme>::Public) -> Result<()> {\n\n let msg = self.message();\n", "file_path": "src/beacon/beacon.rs", "rank": 94, "score": 4.979452522984291 }, { "content": " }\n\n }\n\n ProtocolMessage::Justification(just) => {\n\n {\n\n justifications.write().await.insert(peer, just);\n\n }\n\n if justifications.read().await.len() == group_len - 1 {\n\n justifications_done_sender.send(()).await;\n\n }\n\n }\n\n }\n\n }\n\n });\n\n\n\n self.set_state(One)\n\n }\n\n}\n\n\n\nimpl Board<One> {\n\n #[cfg(test)]\n", "file_path": "src/dkg/board.rs", "rank": 95, "score": 4.842053661598229 }, { "content": "const SHARE_FILE_NAME: &str = \"dist_key.private\";\n\nconst DIST_KEY_FILE_NAME: &str = \"dist_key.public\";\n\nconst GROUP_FILE_NAME: &str = \"drand_group.toml\";\n\n\n\n#[derive(Debug, Clone)]\n\npub struct FileStore {\n\n inner: Arc<InnerFileStore>,\n\n}\n\n\n\n#[derive(Debug)]\n\npub struct InnerFileStore {\n\n base_folder: PathBuf,\n\n key_folder: PathBuf,\n\n private_key_file: PathBuf,\n\n public_key_file: PathBuf,\n\n share_file: PathBuf,\n\n dist_key_file: PathBuf,\n\n group_file: PathBuf,\n\n}\n\n\n", "file_path": "src/key/store.rs", "rank": 96, "score": 4.768987650384608 }, { "content": " }\n\n\n\n /// Merges the provided list of nodes into this group.\n\n pub fn merge(&mut self, nodes: &[Identity]) {\n\n self.threshold = default_threshold(self.nodes.len() + nodes.len());\n\n self.nodes.extend_from_slice(nodes);\n\n self.nodes.sort_by_key(|node| node.public_key().as_bytes());\n\n }\n\n\n\n /// Returns the list of the current members of this group.\n\n pub fn identities(&self) -> &[Identity] {\n\n &self.nodes\n\n }\n\n\n\n /// Returns true if the given key is contained in the list of nodes of this group.\n\n pub fn contains(&self, other: &Identity) -> bool {\n\n self.nodes.iter().find(|&n| n == other).is_some()\n\n }\n\n\n\n /// Returns an unique short representation of this group.\n", "file_path": "src/key/group.rs", "rank": 97, "score": 4.696923239706713 }, { "content": " peer_id,\n\n index: index as Index,\n\n state: Start(d),\n\n })\n\n }\n\n\n\n #[cfg(test)]\n\n pub async fn dkg_phase1_no_publish(self) -> Result<Node<One>> {\n\n let Self {\n\n public,\n\n peer_id,\n\n index,\n\n state,\n\n } = self;\n\n\n\n let (ndkg, _shares) = state.0.shares();\n\n\n\n Ok(Node {\n\n public,\n\n peer_id,\n", "file_path": "src/dkg/node.rs", "rank": 98, "score": 4.59563301213551 }, { "content": "\n\n client.init_dkg(group_path, is_leader, timeout).await\n\n}\n\n\n\n/// Action to be executed on the daemon in general, sent from the control.\n\npub enum DaemonAction {\n\n Stop,\n\n Node(NodeAction),\n\n InitDkg {\n\n group_path: PathBuf,\n\n is_leader: bool,\n\n timeout: Duration,\n\n },\n\n}\n", "file_path": "src/daemon.rs", "rank": 99, "score": 4.579375675075861 } ]
Rust
src/jws/envelope.rs
andkononykhin/didcomm-rust
939e13bda8babe9c27bc197bce16c5272fc07637
use askar_crypto::sign::SignatureType; use serde::{Deserialize, Serialize}; use serde_enum_str::{Deserialize_enum_str, Serialize_enum_str}; use crate::error::{err_msg, ErrorKind, Result}; #[derive(Serialize, Deserialize, Debug, PartialEq, Eq)] pub(crate) struct JWS<'a> { pub signatures: Vec<Signature<'a>>, pub payload: &'a str, } #[derive(Serialize, Deserialize, Debug, PartialEq, Eq)] pub(crate) struct Signature<'a> { #[serde(borrow)] pub header: Header<'a>, pub protected: &'a str, pub signature: &'a str, } #[derive(Serialize, Deserialize, Debug, PartialEq, Eq)] pub(crate) struct ProtectedHeader<'a> { pub typ: &'a str, pub alg: Algorithm, } #[derive(Serialize, Deserialize, Debug, PartialEq, Eq)] pub(crate) struct Header<'a> { pub kid: &'a str, } #[derive(Deserialize_enum_str, Serialize_enum_str, Debug, Clone, Eq, PartialEq)] pub(crate) enum Algorithm { #[serde(rename = "EdDSA")] EdDSA, #[serde(rename = "ES256")] Es256, #[serde(rename = "ES256K")] Es256K, #[serde(other)] Other(String), } impl Algorithm { pub(crate) fn sig_type(&self) -> Result<SignatureType> { let sig_type = match self { Algorithm::EdDSA => SignatureType::EdDSA, Algorithm::Es256 => SignatureType::ES256, Algorithm::Es256K => SignatureType::ES256K, Algorithm::Other(_) => Err(err_msg( ErrorKind::NoCompatibleCrypto, "Unsuported signature type", ))?, }; Ok(sig_type) } } #[cfg(test)] mod tests { use super::*; #[test] fn algorithm_serialize_works() { let alg = Algorithm::EdDSA; let alg = serde_json::to_string(&alg).expect("Unable serialize"); assert_eq!(alg, "\"EdDSA\""); let alg = Algorithm::Es256; let alg = serde_json::to_string(&alg).expect("Unable serialize"); assert_eq!(alg, "\"ES256\""); let alg = Algorithm::Es256K; let alg = serde_json::to_string(&alg).expect("Unable serialize"); assert_eq!(alg, "\"ES256K\""); let alg = Algorithm::Other("Unknown".into()); let alg = serde_json::to_string(&alg).expect("Unable serialize"); assert_eq!(alg, "\"Unknown\""); let alg = Algorithm::Other("Unknown 2".into()); let alg = serde_json::to_string(&alg).expect("Unable serialize"); assert_eq!(alg, "\"Unknown 2\""); } #[test] fn algorithm_deserialize_works() { let alg: Algorithm = serde_json::from_str("\"EdDSA\"").expect("Unable deserialize"); assert_eq!(alg, Algorithm::EdDSA); let alg: Algorithm = serde_json::from_str("\"ES256\"").expect("Unable deserialize"); assert_eq!(alg, Algorithm::Es256); let alg: Algorithm = serde_json::from_str("\"ES256K\"").expect("Unable deserialize"); assert_eq!(alg, Algorithm::Es256K); let alg: Algorithm = serde_json::from_str("\"Unknown\"").expect("Unable deserialize"); assert_eq!(alg, Algorithm::Other("Unknown".into())); let alg: Algorithm = serde_json::from_str("\"Unknown 2\"").expect("Unable deserialize"); assert_eq!(alg, Algorithm::Other("Unknown 2".into())); } }
use askar_crypto::sign::SignatureType; use serde::{Deserialize, Serialize}; use serde_enum_str::{Deserialize_enum_str, Serialize_enum_str}; use crate::error::{err_msg, ErrorKind, Result}; #[derive(Serialize, Deserialize, Debug, PartialEq, Eq)] pub(crate) struct JWS<'a> { pub signatures: Vec<Signature<'a>>, pub payload: &'a str, } #[derive(Serialize, Deserialize, Debug, PartialEq, Eq)] pub(crate) struct Signature<'a> { #[serde(borrow)] pub header: Header<'a>, pub protected: &'a str, pub signature: &'a str, } #[derive(Serialize, Deserialize, Debug, PartialEq, Eq)] pub(crate) struct ProtectedHeader<'a> { pub typ: &'a str, pub alg: Algorithm, } #[derive(Serialize, Deserialize, Debug, PartialEq, Eq)
} #[test] fn algorithm_deserialize_works() { let alg: Algorithm = serde_json::from_str("\"EdDSA\"").expect("Unable deserialize"); assert_eq!(alg, Algorithm::EdDSA); let alg: Algorithm = serde_json::from_str("\"ES256\"").expect("Unable deserialize"); assert_eq!(alg, Algorithm::Es256); let alg: Algorithm = serde_json::from_str("\"ES256K\"").expect("Unable deserialize"); assert_eq!(alg, Algorithm::Es256K); let alg: Algorithm = serde_json::from_str("\"Unknown\"").expect("Unable deserialize"); assert_eq!(alg, Algorithm::Other("Unknown".into())); let alg: Algorithm = serde_json::from_str("\"Unknown 2\"").expect("Unable deserialize"); assert_eq!(alg, Algorithm::Other("Unknown 2".into())); } }
] pub(crate) struct Header<'a> { pub kid: &'a str, } #[derive(Deserialize_enum_str, Serialize_enum_str, Debug, Clone, Eq, PartialEq)] pub(crate) enum Algorithm { #[serde(rename = "EdDSA")] EdDSA, #[serde(rename = "ES256")] Es256, #[serde(rename = "ES256K")] Es256K, #[serde(other)] Other(String), } impl Algorithm { pub(crate) fn sig_type(&self) -> Result<SignatureType> { let sig_type = match self { Algorithm::EdDSA => SignatureType::EdDSA, Algorithm::Es256 => SignatureType::ES256, Algorithm::Es256K => SignatureType::ES256K, Algorithm::Other(_) => Err(err_msg( ErrorKind::NoCompatibleCrypto, "Unsuported signature type", ))?, }; Ok(sig_type) } } #[cfg(test)] mod tests { use super::*; #[test] fn algorithm_serialize_works() { let alg = Algorithm::EdDSA; let alg = serde_json::to_string(&alg).expect("Unable serialize"); assert_eq!(alg, "\"EdDSA\""); let alg = Algorithm::Es256; let alg = serde_json::to_string(&alg).expect("Unable serialize"); assert_eq!(alg, "\"ES256\""); let alg = Algorithm::Es256K; let alg = serde_json::to_string(&alg).expect("Unable serialize"); assert_eq!(alg, "\"ES256K\""); let alg = Algorithm::Other("Unknown".into()); let alg = serde_json::to_string(&alg).expect("Unable serialize"); assert_eq!(alg, "\"Unknown\""); let alg = Algorithm::Other("Unknown 2".into()); let alg = serde_json::to_string(&alg).expect("Unable serialize"); assert_eq!(alg, "\"Unknown 2\"");
random
[ { "content": "pub trait ResultContext<T> {\n\n fn context<D>(self, msg: D) -> Result<T>\n\n where\n\n D: fmt::Display + fmt::Debug + Send + Sync + 'static;\n\n}\n\n\n\nimpl<T> ResultContext<T> for Result<T> {\n\n fn context<D>(self, msg: D) -> Result<T>\n\n where\n\n D: fmt::Display + fmt::Debug + Send + Sync + 'static,\n\n {\n\n self.map_err(|e| {\n\n let Error { kind, source } = e;\n\n\n\n Error {\n\n kind,\n\n source: source.context(msg),\n\n }\n\n })\n\n }\n\n}\n\n\n", "file_path": "src/error.rs", "rank": 0, "score": 64484.756967703186 }, { "content": "pub trait ResultExt<T, E> {\n\n fn kind<D>(self, kind: ErrorKind, msg: D) -> Result<T>\n\n where\n\n D: fmt::Display + fmt::Debug + Send + Sync + 'static;\n\n}\n\n\n\nimpl<T, E> ResultExt<T, E> for std::result::Result<T, E>\n\nwhere\n\n E: std::error::Error + Send + Sync + 'static,\n\n{\n\n fn kind<D>(self, kind: ErrorKind, msg: D) -> Result<T>\n\n where\n\n D: fmt::Display + fmt::Debug + Send + Sync + 'static,\n\n {\n\n self.map_err(|e| Error {\n\n kind,\n\n source: anyhow::Error::new(e).context(msg),\n\n })\n\n }\n\n}\n\n\n", "file_path": "src/error.rs", "rank": 1, "score": 61824.44056915406 }, { "content": "#[async_trait]\n\npub trait DIDResolver {\n\n /// Resolves a DID document by the given DID.\n\n ///\n\n /// # Params\n\n /// - `did` a DID to be resolved.\n\n ///\n\n /// # Returns\n\n /// An instance of resolved DID DOC or None if DID is not found.\n\n ///\n\n /// # Errors\n\n /// - `IoError` IO error during resolving\n\n /// - `InvalidState` indicates a bug in resolver code\n\n async fn resolve(&self, did: &str) -> Result<Option<Box<dyn DIDDoc>>>;\n\n}\n", "file_path": "src/did/did_resolver.rs", "rank": 2, "score": 36883.45383144209 }, { "content": "/// Represents DID Document (https://www.w3.org/TR/did-core/)\n\npub trait DIDDoc {\n\n /// Returns a DID for the given DID Doc\n\n fn did(&self) -> &str;\n\n\n\n /// Returns DID URLs of verification methods used for key agreement.\n\n /// See https://www.w3.org/TR/did-core/#verification-methods.\n\n fn key_agreements(&self) -> &[String];\n\n\n\n /// Returns DID URLs of verification methods used for authentication.\n\n /// See https://www.w3.org/TR/did-core/#authentication\n\n fn authentications(&self) -> &[String];\n\n\n\n /// Returns all local verification methods including embedded to\n\n /// key agreement and authentication sections.\n\n /// See https://www.w3.org/TR/did-core/#verification-methods.\n\n fn verification_methods(&self) -> &[VerificationMethod];\n\n\n\n /// Returns all services (https://www.w3.org/TR/did-core/#services)\n\n fn services(&self) -> &[Service];\n\n}\n", "file_path": "src/did/did_doc.rs", "rank": 3, "score": 36883.45383144209 }, { "content": "/// Algorithms for anonymous encryption\n\n#[allow(non_camel_case_types)]\n\npub enum AnonCryptAlg {\n\n /// AES256-CBC + HMAC-SHA512 with a 512 bit key content encryption,\n\n /// ECDH-ES key agreement with A256KW key wrapping\n\n A256CBC_HS512_ECDH_ES_A256KW,\n\n\n\n /// XChaCha20Poly1305 with a 256 bit key content encryption,\n\n /// ECDH-ES key agreement with A256KW key wrapping\n\n XC20P_ECDH_ES_A256KW,\n\n\n\n /// A256GCM_ECDH_ES_A256KW: XChaCha20Poly1305 with a 256 bit key content encryption,\n\n /// ECDH-ES key agreement with A256KW key wrapping\n\n A256GCM_ECDH_ES_A256KW,\n\n}\n\n\n\n#[allow(non_camel_case_types)]\n\npub enum AuthCryptAlg {\n\n /// AES256-CBC + HMAC-SHA512 with a 512 bit key content encryption,\n\n /// ECDH-1PU key agreement with A256KW key wrapping\n\n A256CBC_HS512_ECDH_1PU_A256KW,\n\n}\n\n\n\npub enum SignAlg {\n\n EdDSA,\n\n ES256,\n\n ES256K,\n\n}\n", "file_path": "src/algorithms.rs", "rank": 4, "score": 36492.931664262906 }, { "content": "#[async_trait]\n\npub trait SecretsResolver {\n\n /// Finds private key identified by the given key ID.\n\n ///\n\n /// # Parameters\n\n /// - `did_url` the key ID (in form of DID URL) identifying a private key\n\n ///\n\n /// # Returns\n\n /// A private key or None of there is no key for the given key ID\n\n ///\n\n /// # Errors\n\n /// - IOError\n\n /// - InvalidState\n\n ///\n\n async fn resolve(&self, did_url: &str) -> Result<Option<Secret>>;\n\n}\n\n\n\n/// Represents secret.\n\n#[derive(Clone, Debug)]\n\npub struct Secret {\n\n /// A key ID identifying a secret (private key).\n", "file_path": "src/secrets/mod.rs", "rank": 5, "score": 34229.32370485702 }, { "content": "pub fn err_msg<D>(kind: ErrorKind, msg: D) -> Error\n\nwhere\n\n D: fmt::Display + fmt::Debug + Send + Sync + 'static,\n\n{\n\n Error::msg(kind, msg)\n\n}\n\n\n\n// TODO: Provide `From` implementation for serde and base64 errors to explicitly split malformed and no-memory errors\n", "file_path": "src/error.rs", "rank": 6, "score": 32674.450634042274 }, { "content": "\n\n /// BASE64URL(JWE Authentication Tag)\n\n pub tag: &'a str,\n\n}\n\n\n\n/// Protected header for authcrypt/anoncrypt-specific JWE.\n\n#[derive(Serialize, Deserialize, Debug, Clone, PartialEq, Eq)]\n\npub(crate) struct ProtectedHeader<'a> {\n\n /// Must be `application/didcomm-encrypted+json` or `didcomm-encrypted+json` for now.\n\n /// Something like `application/didcomm-encrypted+cbor` can be introduced in the\n\n /// future.\n\n pub typ: Option<&'a str>,\n\n\n\n /// Cryptographic algorithm used to encrypt or determine the value of the CEK.\n\n pub alg: Algorithm,\n\n\n\n /// Identifies the content encryption algorithm used to perform authenticated encryption\n\n /// on the plaintext to produce the ciphertext and the Authentication Tag.\n\n pub enc: EncAlgorithm,\n\n\n", "file_path": "src/jwe/envelope.rs", "rank": 9, "score": 45.020475212522236 }, { "content": "use askar_crypto::sign::KeySign;\n\n\n\nuse crate::{\n\n error::{ErrorKind, Result, ResultExt},\n\n jws::envelope::{Algorithm, Header, ProtectedHeader, Signature, JWS},\n\n};\n\n\n\npub(crate) fn sign<Key: KeySign>(\n\n payload: &[u8],\n\n signer: (&str, &Key),\n\n alg: Algorithm,\n\n) -> Result<String> {\n\n let (kid, key) = signer;\n\n\n\n let sig_type = alg.sig_type()?;\n\n\n\n let protected = {\n\n let protected = ProtectedHeader {\n\n typ: \"application/didcomm-signed+json\",\n\n alg,\n", "file_path": "src/jws/sign.rs", "rank": 11, "score": 43.288685870866516 }, { "content": " /// Per-recipient header\n\n /// Note it isn't serialized and not integrity protected\n\n pub header: PerRecipientHeader<'a>,\n\n\n\n /// BASE64URL(JWE Encrypted Key)\n\n pub encrypted_key: &'a str,\n\n}\n\n\n\n/// Per-recipient header part of authcrypt/anoncrypt-specific JWE\n\n#[derive(Serialize, Deserialize, Debug, Clone, PartialEq, Eq)]\n\npub(crate) struct PerRecipientHeader<'a> {\n\n /// Recipient KID as DID URL\n\n pub kid: &'a str,\n\n}\n\n\n\n/// Represents possible values for `alg` header.\n\n/// Cryptographic algorithm used to encrypt or determine the value of the CEK.\n\n#[derive(Deserialize_enum_str, Serialize_enum_str, Debug, Clone, Eq, PartialEq)]\n\npub(crate) enum Algorithm {\n\n #[serde(rename = \"ECDH-1PU+A256KW\")]\n", "file_path": "src/jwe/envelope.rs", "rank": 12, "score": 41.12236673306337 }, { "content": "use serde::{Deserialize, Serialize};\n\nuse serde_enum_str::{Deserialize_enum_str, Serialize_enum_str};\n\nuse serde_json::Value;\n\n\n\n/// Subset of JWE in generic json serialization form used for authcrypt\n\n/// and anoncrypt message types.\n\n#[derive(Serialize, Deserialize, Debug, Clone, PartialEq, Eq)]\n\npub(crate) struct JWE<'a> {\n\n /// BASE64URL(UTF8(JWE Protected Header))\n\n /// Note: this field value is used as AAD for JWE Ciphertext\n\n pub protected: &'a str,\n\n\n\n /// Array of recipient-specific objects\n\n pub recipients: Vec<Recepient<'a>>,\n\n\n\n /// BASE64URL(JWE Initialization Vector)\n\n pub iv: &'a str,\n\n\n\n /// BASE64URL(JWE Ciphertext)\n\n pub ciphertext: &'a str,\n", "file_path": "src/jwe/envelope.rs", "rank": 13, "score": 37.168719791433496 }, { "content": "use crate::{\n\n error::{err_msg, ErrorKind, Result, ResultExt},\n\n jws::envelope::{ProtectedHeader, JWS},\n\n};\n\n\n\n#[derive(Debug, PartialEq, Eq)]\n\npub(crate) struct ParsedJWS<'a, 'b> {\n\n pub(crate) jws: JWS<'a>,\n\n pub(crate) protected: Vec<ProtectedHeader<'b>>,\n\n}\n\n\n\npub(crate) fn parse<'a, 'b>(jws: &'a str, buf: &'b mut Vec<Vec<u8>>) -> Result<ParsedJWS<'a, 'b>> {\n\n let jws: JWS = serde_json::from_str(jws).kind(ErrorKind::Malformed, \"Unable parse jws\")?;\n\n\n\n let protected = {\n\n let len = jws.signatures.len();\n\n let mut protected = Vec::<ProtectedHeader>::with_capacity(len);\n\n buf.resize(len, vec![]);\n\n\n\n for (i, b) in buf.iter_mut().enumerate() {\n", "file_path": "src/jws/parse.rs", "rank": 14, "score": 34.82627054939334 }, { "content": "use sha2::{Digest, Sha256};\n\n\n\nuse crate::{\n\n error::{err_msg, ErrorKind, Result, ResultExt},\n\n jwe::envelope::{ProtectedHeader, JWE},\n\n};\n\n\n\n#[derive(Debug, PartialEq, Eq)]\n\npub(crate) struct ParsedJWE<'a, 'b> {\n\n pub(crate) jwe: JWE<'a>,\n\n pub(crate) protected: ProtectedHeader<'b>,\n\n pub(crate) apu: Option<Vec<u8>>,\n\n pub(crate) apv: Vec<u8>,\n\n}\n\n\n\npub(crate) fn parse<'a, 'b>(jwe: &'a str, buf: &'b mut Vec<u8>) -> Result<ParsedJWE<'a, 'b>> {\n\n let jwe: JWE = serde_json::from_str(jwe).kind(ErrorKind::Malformed, \"Unable parse jwe\")?;\n\n\n\n base64::decode_config_buf(jwe.protected, base64::URL_SAFE_NO_PAD, buf)\n\n .kind(ErrorKind::Malformed, \"Unable decode protected header\")?;\n", "file_path": "src/jwe/parse.rs", "rank": 15, "score": 31.64354998973758 }, { "content": "/// Identifies the content encryption algorithm used to perform authenticated encryption\n\n/// on the plaintext to produce the ciphertext and the Authentication Tag.\n\n#[derive(Deserialize_enum_str, Serialize_enum_str, Debug, Clone, Eq, PartialEq)]\n\npub(crate) enum EncAlgorithm {\n\n #[serde(rename = \"A256CBC-HS512\")]\n\n A256cbcHs512,\n\n\n\n #[serde(rename = \"XC20P\")]\n\n Xc20P,\n\n\n\n #[serde(rename = \"A256GCM\")]\n\n A256Gcm,\n\n\n\n #[serde(other)]\n\n Other(String),\n\n}\n\n\n\n#[cfg(test)]\n\nmod tests {\n\n use super::*;\n", "file_path": "src/jwe/envelope.rs", "rank": 16, "score": 30.240388544896074 }, { "content": " key: &str,\n\n pkey: &str,\n\n alg: Algorithm,\n\n payload: &str,\n\n ) {\n\n let res = _sign::<K>(kid, key, alg.clone(), payload);\n\n\n\n let msg = res.expect(\"Unable _sign\");\n\n\n\n let mut buf = vec![];\n\n let msg = jws::parse(&msg, &mut buf).expect(\"Unable parse.\");\n\n\n\n assert_eq!(\n\n msg.jws.payload,\n\n base64::encode_config(payload, base64::URL_SAFE_NO_PAD)\n\n );\n\n\n\n assert_eq!(msg.jws.signatures.len(), 1);\n\n assert_eq!(msg.jws.signatures[0].header.kid, kid);\n\n\n", "file_path": "src/jws/sign.rs", "rank": 17, "score": 28.428622748078112 }, { "content": "\n\n #[test]\n\n fn algorithm_serialize_works() {\n\n let alg = Algorithm::Ecdh1puA256kw;\n\n let alg = serde_json::to_string(&alg).expect(\"unable serialize.\");\n\n assert_eq!(alg, \"\\\"ECDH-1PU+A256KW\\\"\");\n\n\n\n let alg = Algorithm::Other(\"Unknown\".into());\n\n let alg = serde_json::to_string(&alg).expect(\"unable serialize.\");\n\n assert_eq!(alg, \"\\\"Unknown\\\"\");\n\n }\n\n\n\n #[test]\n\n fn algorithm_deserialize_works() {\n\n let alg: Algorithm =\n\n serde_json::from_str(\"\\\"ECDH-1PU+A256KW\\\"\").expect(\"unable deserialize.\");\n\n\n\n assert_eq!(alg, Algorithm::Ecdh1puA256kw);\n\n\n\n let alg: Algorithm = serde_json::from_str(\"\\\"Unknown\\\"\").expect(\"unable deserialize.\");\n", "file_path": "src/jwe/envelope.rs", "rank": 19, "score": 27.898389231385245 }, { "content": " /// Sender KID as DID Url.\n\n /// If absent implementations MUST be able to resolve the sender kid from the `apu` header.\n\n #[serde(skip_serializing_if = \"Option::is_none\")]\n\n pub skid: Option<&'a str>,\n\n\n\n /// BASE64URL(\"skid\" header value),\n\n #[serde(skip_serializing_if = \"Option::is_none\")]\n\n pub apu: Option<&'a str>,\n\n\n\n /// BASE64URL(SHA256(CONCAT('.', SORT([recipients[0].kid, ..., recipients[n].kid])))))\n\n pub apv: &'a str,\n\n\n\n /// EPK generated once for all recipients.\n\n /// It MUST be of the same type and curve as all recipient keys since kdf\n\n /// with the sender key must be on the same curve.\n\n pub epk: Value,\n\n}\n\n/// Recipient part of authcrypt/anoncrypt-specific JWE\n\n#[derive(Serialize, Deserialize, Debug, Clone, PartialEq, Eq)]\n\npub(crate) struct Recepient<'a> {\n", "file_path": "src/jwe/envelope.rs", "rank": 20, "score": 27.479837551909007 }, { "content": "\n\n assert_eq!(\n\n format!(\"{}\", err),\n\n \"No compatible crypto: Unsuported signature type\"\n\n );\n\n }\n\n }\n\n\n\n fn _sign<K: FromJwk + KeySign>(\n\n kid: &str,\n\n key: &str,\n\n alg: Algorithm,\n\n payload: &str,\n\n ) -> Result<String> {\n\n let key = K::from_jwk(key).expect(\"unable from_jwk.\");\n\n jws::sign(payload.as_bytes(), (&kid, &key), alg.clone())\n\n }\n\n\n\n const ALICE_KID_ED25519: &str = \"did:example:alice#key-1\";\n\n\n", "file_path": "src/jws/sign.rs", "rank": 21, "score": 27.433588303585925 }, { "content": " assert_eq!(alg, Algorithm::Other(\"Unknown\".into()));\n\n\n\n let alg: Algorithm = serde_json::from_str(\"\\\"Unknown 2\\\"\").expect(\"unable deserialize.\");\n\n assert_eq!(alg, Algorithm::Other(\"Unknown 2\".into()));\n\n }\n\n\n\n #[test]\n\n fn enc_algorithm_serialize_works() {\n\n let enc_alg = EncAlgorithm::A256cbcHs512;\n\n let enc_alg = serde_json::to_string(&enc_alg).expect(\"unable serialize.\");\n\n assert_eq!(enc_alg, \"\\\"A256CBC-HS512\\\"\");\n\n\n\n let enc_alg = EncAlgorithm::Other(\"Unknown\".into());\n\n let enc_alg = serde_json::to_string(&enc_alg).expect(\"unable serialize.\");\n\n assert_eq!(enc_alg, \"\\\"Unknown\\\"\");\n\n }\n\n\n\n #[test]\n\n fn enc_algorithm_deserialize_works() {\n\n let enc_alg: EncAlgorithm =\n", "file_path": "src/jwe/envelope.rs", "rank": 22, "score": 26.629961270541173 }, { "content": "use askar_crypto::{\n\n buffer::SecretBytes,\n\n encrypt::{KeyAeadInPlace, KeyAeadMeta},\n\n kdf::{FromKeyDerivation, KeyExchange},\n\n repr::{KeyGen, ToSecretBytes},\n\n};\n\n\n\nuse sha2::{Digest, Sha256};\n\n\n\nuse crate::{\n\n error::{ErrorKind, Result, ResultExt},\n\n jwe::envelope::{Algorithm, EncAlgorithm, PerRecipientHeader, ProtectedHeader, Recepient, JWE},\n\n jwk::ToJwkValue,\n\n utils::crypto::{JoseKDF, KeyWrap},\n\n};\n\n\n\npub(crate) fn encrypt<CE, KDF, KE, KW>(\n\n plaintext: &[u8],\n\n alg: Algorithm,\n\n enc: EncAlgorithm,\n", "file_path": "src/jwe/encrypt.rs", "rank": 23, "score": 26.59912722323443 }, { "content": " pub protect_sender: bool,\n\n\n\n /// Whether the encrypted messages need to be wrapped into `Forward` messages to be sent to Mediators\n\n /// as defined by the `Forward` protocol.\n\n pub forward: bool,\n\n\n\n /// if forward is enabled these optional headers can be passed to the wrapping `Forward` messages.\n\n /// If forward is disabled this property will be ignored.\n\n pub forward_headers: Option<Vec<(String, Value)>>,\n\n\n\n /// Identifier (DID URL) of messaging service (https://identity.foundation/didcomm-messaging/spec/#did-document-service-endpoint).\n\n /// If DID contains multiple messaging services it allows specify what service to use.\n\n /// If not present first service will be used.\n\n pub messaging_service: Option<String>,\n\n\n\n /// Algorithm used for authenticated encryption\n\n pub enc_alg_auth: AuthCryptAlg,\n\n\n\n /// Algorithm used for anonymous encryption\n\n pub enc_alg_anon: AnonCryptAlg,\n", "file_path": "src/pack_encrypted.rs", "rank": 25, "score": 24.323204232692028 }, { "content": " serde_json::from_str(\"\\\"A256CBC-HS512\\\"\").expect(\"unable deserialize.\");\n\n\n\n assert_eq!(enc_alg, EncAlgorithm::A256cbcHs512);\n\n\n\n let enc_alg: EncAlgorithm =\n\n serde_json::from_str(\"\\\"Unknown\\\"\").expect(\"unable deserialize.\");\n\n\n\n assert_eq!(enc_alg, EncAlgorithm::Other(\"Unknown\".into()));\n\n\n\n let enc_alg: EncAlgorithm =\n\n serde_json::from_str(\"\\\"Unknown 2\\\"\").expect(\"unable deserialize.\");\n\n\n\n assert_eq!(enc_alg, EncAlgorithm::Other(\"Unknown 2\".into()));\n\n }\n\n}\n", "file_path": "src/jwe/envelope.rs", "rank": 26, "score": 23.74283603146444 }, { "content": " pub json: Value,\n\n\n\n /// A JSON Web Signature over the content of the attachment.\n\n #[serde(skip_serializing_if = \"Option::is_none\")]\n\n pub jws: Option<String>,\n\n}\n\n\n\n#[derive(Debug, Serialize, Deserialize)]\n\npub struct LinksAttachmentData {\n\n /// A list of one or more locations at which the content may be fetched.\n\n pub links: Vec<String>,\n\n\n\n /// The hash of the content encoded in multi-hash format. Used as an integrity check for the attachment.\n\n pub hash: String,\n\n\n\n /// A JSON Web Signature over the content of the attachment.\n\n #[serde(skip_serializing_if = \"Option::is_none\")]\n\n pub jws: Option<String>,\n\n}\n\n\n", "file_path": "src/message/attachment.rs", "rank": 27, "score": 23.6982544484046 }, { "content": "use askar_crypto::sign::KeySigVerify;\n\n\n\nuse crate::{\n\n error::{err_msg, ErrorKind, Result, ResultExt},\n\n jws::ParsedJWS,\n\n};\n\n\n\nimpl<'a, 'b> ParsedJWS<'a, 'b> {\n\n pub(crate) fn verify<Key: KeySigVerify>(&self, signer: (&str, &Key)) -> Result<bool> {\n\n let (kid, key) = signer;\n\n\n\n let (i, signature) = self\n\n .jws\n\n .signatures\n\n .iter()\n\n .enumerate()\n\n .find(|(_, sig)| sig.header.kid == kid)\n\n .ok_or_else(|| err_msg(ErrorKind::InvalidState, \"KID not found\"))?;\n\n\n\n let protected = self\n", "file_path": "src/jws/verify.rs", "rank": 28, "score": 22.5523471588197 }, { "content": "\n\n /// Whether the plaintext was re-wrapped in a forward message by a mediator\n\n pub re_wrapped_in_forward: bool,\n\n\n\n /// Key ID of the sender used for authentication encryption if the plaintext has been authenticated and encrypted\n\n pub encrypted_from_kid: Option<String>,\n\n\n\n /// Target key IDS for encryption if the plaintext has been encrypted\n\n pub encrypted_to_kids: Option<Vec<String>>,\n\n\n\n /// Key ID used for signature if the plaintext has been signed\n\n pub sign_from: Option<String>,\n\n\n\n /// Algorithm used for authenticated encryption\n\n pub enc_alg_auth: Option<AuthCryptAlg>,\n\n\n\n /// Algorithm used for anonymous encryption\n\n pub enc_alg_anon: Option<AnonCryptAlg>,\n\n\n\n /// Algorithm used for message signing\n", "file_path": "src/unpack.rs", "rank": 30, "score": 21.950677515288486 }, { "content": " PAYLOAD,\n\n );\n\n\n\n _sign_works_unknown_alg::<K256KeyPair>(\n\n ALICE_KID_K256,\n\n ALICE_KEY_K256,\n\n Algorithm::Other(\"bls\".to_owned()),\n\n PAYLOAD,\n\n );\n\n\n\n fn _sign_works_unknown_alg<K: FromJwk + KeySign + KeySigVerify>(\n\n kid: &str,\n\n key: &str,\n\n alg: Algorithm,\n\n payload: &str,\n\n ) {\n\n let res = _sign::<K>(kid, key, alg.clone(), payload);\n\n\n\n let err = res.expect_err(\"res is ok\");\n\n assert_eq!(err.kind(), ErrorKind::NoCompatibleCrypto);\n", "file_path": "src/jws/sign.rs", "rank": 31, "score": 21.44903955184981 }, { "content": " );\n\n\n\n _sign_works_incompatible_alg::<K256KeyPair>(\n\n ALICE_KID_K256,\n\n ALICE_KEY_K256,\n\n Algorithm::Es256,\n\n PAYLOAD,\n\n );\n\n\n\n fn _sign_works_incompatible_alg<K: FromJwk + KeySign + KeySigVerify>(\n\n kid: &str,\n\n key: &str,\n\n alg: Algorithm,\n\n payload: &str,\n\n ) {\n\n let res = _sign::<K>(kid, key, alg.clone(), payload);\n\n\n\n let err = res.expect_err(\"res is ok\");\n\n assert_eq!(err.kind(), ErrorKind::InvalidState);\n\n\n", "file_path": "src/jws/sign.rs", "rank": 32, "score": 21.315637480206444 }, { "content": "#[serde(untagged)]\n\npub enum AttachmentData {\n\n Base64(Base64AttachmentData),\n\n Json(JsonAttachmentData),\n\n Links(LinksAttachmentData),\n\n}\n\n\n\n#[derive(Debug, Serialize, Deserialize)]\n\npub struct Base64AttachmentData {\n\n /// Base64-encoded data, when representing arbitrary content inline.\n\n pub base64: String,\n\n\n\n /// A JSON Web Signature over the content of the attachment.\n\n #[serde(skip_serializing_if = \"Option::is_none\")]\n\n pub jws: Option<String>,\n\n}\n\n\n\n#[derive(Debug, Serialize, Deserialize)]\n\npub struct JsonAttachmentData {\n\n /// Directly embedded JSON data.\n", "file_path": "src/message/attachment.rs", "rank": 33, "score": 21.309126410160307 }, { "content": "use serde::{Deserialize, Serialize};\n\nuse serde_json::Value;\n\nuse std::collections::HashMap;\n\n\n\nuse super::Attachment;\n\n\n\n/// Wrapper for plain message. Provides helpers for message building and packing/unpacking.\n\n#[derive(Debug, Serialize, Deserialize)]\n\npub struct Message {\n\n /// Message id. Must be unique to the sender.\n\n pub id: String,\n\n\n\n /// Message type attribute value MUST be a valid Message Type URI,\n\n /// that when resolved gives human readable information about the message.\n\n /// The attribute’s value also informs the content of the message,\n\n /// or example the presence of other attributes and how they should be processed.\n\n pub type_: String,\n\n\n\n /// Message body.\n\n pub body: Value,\n", "file_path": "src/message/message.rs", "rank": 34, "score": 20.886131129269486 }, { "content": "use serde::Serialize;\n\nuse std::fmt;\n\n\n\n#[derive(thiserror::Error, Debug, Copy, Clone, Eq, PartialEq, Serialize)]\n\npub enum ErrorKind {\n\n #[error(\"DID not resolved\")]\n\n DIDNotResolved,\n\n\n\n #[error(\"DID not resolved\")]\n\n DIDUrlNotFound,\n\n\n\n #[error(\"Secret not found\")]\n\n SecretNotFound,\n\n\n\n #[error(\"Malformed\")]\n\n Malformed,\n\n\n\n #[error(\"Message doesn't meet trust requrements\")]\n\n UnsatisfiedConstraint,\n\n\n", "file_path": "src/error.rs", "rank": 35, "score": 20.21027949758612 }, { "content": "use serde::{Deserialize, Serialize};\n\nuse serde_json::Value;\n\n\n\n#[derive(Debug, Serialize, Deserialize)]\n\npub struct Attachment {\n\n /// A JSON object that gives access to the actual content of the attachment.\n\n /// Can be based on base64, json or external links.\n\n pub data: AttachmentData,\n\n\n\n /// Identifies attached content within the scope of a given message.\n\n /// Recommended on appended attachment descriptors. Possible but generally unused\n\n /// on embedded attachment descriptors. Never required if no references to the attachment\n\n /// exist; if omitted, then there is no way to refer to the attachment later in the thread,\n\n /// in error messages, and so forth. Because id is used to compose URIs, it is recommended\n\n /// that this name be brief and avoid spaces and other characters that require URI escaping.\n\n #[serde(skip_serializing_if = \"Option::is_none\")]\n\n pub id: Option<String>,\n\n\n\n /// A human-readable description of the content.\n\n #[serde(skip_serializing_if = \"Option::is_none\")]\n", "file_path": "src/message/attachment.rs", "rank": 36, "score": 20.111603851084894 }, { "content": " assert_eq!(\n\n format!(\"{}\", err),\n\n \"Invalid state: Unable create signature: Unsupported signature type\"\n\n );\n\n }\n\n }\n\n\n\n #[test]\n\n fn sign_works_unknown_alg() {\n\n _sign_works_unknown_alg::<Ed25519KeyPair>(\n\n ALICE_KID_ED25519,\n\n ALICE_KEY_ED25519,\n\n Algorithm::Other(\"bls\".to_owned()),\n\n PAYLOAD,\n\n );\n\n\n\n _sign_works_unknown_alg::<P256KeyPair>(\n\n ALICE_KID_P256,\n\n ALICE_KEY_P256,\n\n Algorithm::Other(\"bls\".to_owned()),\n", "file_path": "src/jws/sign.rs", "rank": 37, "score": 20.07756818050052 }, { "content": " };\n\n\n\n let protected = serde_json::to_string(&protected)\n\n .kind(ErrorKind::InvalidState, \"Unable serialize protectd header\")?;\n\n\n\n base64::encode_config(protected, base64::URL_SAFE_NO_PAD)\n\n };\n\n\n\n let payload = base64::encode_config(payload, base64::URL_SAFE_NO_PAD);\n\n\n\n let signature = {\n\n // JWS Signing Input\n\n // The input to the digital signature or MAC computation. Its value\n\n // is ASCII(BASE64URL(UTF8(JWS Protected Header)) || '.' || BASE64URL(JWS Payload)).\n\n let sign_input = format!(\"{}.{}\", protected, payload);\n\n\n\n let signature = key\n\n .create_signature(sign_input.as_bytes(), Some(sig_type))\n\n .kind(ErrorKind::InvalidState, \"Unable create signature\")?;\n\n\n", "file_path": "src/jws/sign.rs", "rank": 38, "score": 19.967460312424652 }, { "content": " assert_eq!(msg.protected.len(), 1);\n\n assert_eq!(msg.protected[0].alg, alg);\n\n assert_eq!(msg.protected[0].typ, \"application/didcomm-signed+json\");\n\n\n\n let pkey = K::from_jwk(pkey).expect(\"unable from_jwk\");\n\n let valid = msg.verify::<K>((kid, &pkey)).expect(\"Unable verify\");\n\n\n\n assert!(valid);\n\n }\n\n }\n\n\n\n #[test]\n\n fn sign_works_incompatible_alg() {\n\n _sign_works_incompatible_alg::<Ed25519KeyPair>(\n\n ALICE_KID_ED25519,\n\n ALICE_KEY_ED25519,\n\n Algorithm::Es256,\n\n PAYLOAD,\n\n );\n\n\n", "file_path": "src/jws/sign.rs", "rank": 39, "score": 19.46022993993071 }, { "content": " alg.clone(),\n\n enc_alg.clone(),\n\n alice_priv,\n\n &bob_pub,\n\n )\n\n .expect(\"Unable encrypt\");\n\n\n\n let mut buf = vec![];\n\n let msg = jwe::parse(&msg, &mut buf).expect(\"Unable parse\");\n\n\n\n assert_eq!(msg.protected.alg, alg);\n\n assert_eq!(msg.protected.enc, enc_alg);\n\n assert_eq!(msg.jwe.recipients.len(), bob.len());\n\n\n\n assert_eq!(msg.apu.as_deref(), alice_kid.map(str::as_bytes));\n\n\n\n for recipient in &msg.jwe.recipients {\n\n let bob_edge_priv = bob_priv\n\n .iter()\n\n .find(|b| recipient.header.kid == b.0)\n", "file_path": "src/jwe/encrypt.rs", "rank": 40, "score": 18.848385612360445 }, { "content": " },\n\n protected: vec![ProtectedHeader {\n\n typ: \"application/didcomm-signed+json\",\n\n alg: Algorithm::EdDSA,\n\n }],\n\n };\n\n\n\n assert_eq!(res, exp);\n\n }\n\n\n\n #[test]\n\n fn parse_works_protected_unknown_fields() {\n\n let msg = r#\"\n\n {\n\n \"payload\":\"eyJpZCI6IjEyMzQ1Njc4OTAiLCJ0eXAiOiJhcHBsaWNhdGlvbi9kaWRjb21tLXBsYWluK2pzb24iLCJ0eXBlIjoiaHR0cDovL2V4YW1wbGUuY29tL3Byb3RvY29scy9sZXRzX2RvX2x1bmNoLzEuMC9wcm9wb3NhbCIsImZyb20iOiJkaWQ6ZXhhbXBsZTphbGljZSIsInRvIjpbImRpZDpleGFtcGxlOmJvYiJdLCJjcmVhdGVkX3RpbWUiOjE1MTYyNjkwMjIsImV4cGlyZXNfdGltZSI6MTUxNjM4NTkzMSwiYm9keSI6eyJtZXNzYWdlc3BlY2lmaWNhdHRyaWJ1dGUiOiJhbmQgaXRzIHZhbHVlIn19\",\n\n \"signatures\":[\n\n {\n\n \"protected\":\"eyJ0eXAiOiJhcHBsaWNhdGlvbi9kaWRjb21tLXNpZ25lZCtqc29uIiwiYWxnIjoiRWREU0EiLCJleHRyYSI6InZhbHVlIn0\",\n\n \"signature\":\"FW33NnvOHV0Ted9-F7GZbkia-vYAfBKtH4oBxbrttWAhBZ6UFJMxcGjL3lwOl4YohI3kyyd08LHPWNMgP2EVCQ\",\n\n \"header\":{\n", "file_path": "src/jws/parse.rs", "rank": 41, "score": 18.624927833622824 }, { "content": "}\n\n\n\nimpl Default for PackEncryptedOptions {\n\n fn default() -> Self {\n\n PackEncryptedOptions {\n\n protect_sender: false,\n\n forward: true,\n\n forward_headers: None,\n\n messaging_service: None,\n\n enc_alg_auth: AuthCryptAlg::A256CBC_HS512_ECDH_1PU_A256KW,\n\n enc_alg_anon: AnonCryptAlg::XC20P_ECDH_ES_A256KW,\n\n }\n\n }\n\n}\n\n\n\n/// Additional metadata about this `encrypt` method execution like used keys identifiers,\n\n/// used messaging service.\n\npub struct PackEncryptedMetadata {\n\n /// Information about messaging service used for message preparation.\n\n /// Practically `service_endpoint` field can be used to transport the message.\n", "file_path": "src/pack_encrypted.rs", "rank": 42, "score": 18.483472297029344 }, { "content": "mod tests {\n\n use askar_crypto::{\n\n alg::{ed25519::Ed25519KeyPair, k256::K256KeyPair, p256::P256KeyPair},\n\n jwk::FromJwk,\n\n sign::{KeySigVerify, KeySign},\n\n };\n\n\n\n use crate::{\n\n error::{ErrorKind, Result},\n\n jws::{self, envelope::Algorithm},\n\n };\n\n\n\n #[test]\n\n fn sign_works() {\n\n _sign_works::<Ed25519KeyPair>(\n\n ALICE_KID_ED25519,\n\n ALICE_KEY_ED25519,\n\n ALICE_PKEY_ED25519,\n\n Algorithm::EdDSA,\n\n PAYLOAD,\n", "file_path": "src/jws/sign.rs", "rank": 43, "score": 18.467262044760623 }, { "content": " protected: vec![ProtectedHeader {\n\n typ: \"application/didcomm-signed+json\",\n\n alg: Algorithm::EdDSA,\n\n }],\n\n };\n\n\n\n assert_eq!(res, exp);\n\n }\n\n\n\n #[test]\n\n fn parse_works_multiple_signatures() {\n\n let msg = r#\"\n\n {\n\n \"payload\":\"eyJpZCI6IjEyMzQ1Njc4OTAiLCJ0eXAiOiJhcHBsaWNhdGlvbi9kaWRjb21tLXBsYWluK2pzb24iLCJ0eXBlIjoiaHR0cDovL2V4YW1wbGUuY29tL3Byb3RvY29scy9sZXRzX2RvX2x1bmNoLzEuMC9wcm9wb3NhbCIsImZyb20iOiJkaWQ6ZXhhbXBsZTphbGljZSIsInRvIjpbImRpZDpleGFtcGxlOmJvYiJdLCJjcmVhdGVkX3RpbWUiOjE1MTYyNjkwMjIsImV4cGlyZXNfdGltZSI6MTUxNjM4NTkzMSwiYm9keSI6eyJtZXNzYWdlc3BlY2lmaWNhdHRyaWJ1dGUiOiJhbmQgaXRzIHZhbHVlIn19\",\n\n \"signatures\":[\n\n {\n\n \"protected\":\"eyJ0eXAiOiJhcHBsaWNhdGlvbi9kaWRjb21tLXNpZ25lZCtqc29uIiwiYWxnIjoiRWREU0EifQ\",\n\n \"signature\":\"FW33NnvOHV0Ted9-F7GZbkia-vYAfBKtH4oBxbrttWAhBZ6UFJMxcGjL3lwOl4YohI3kyyd08LHPWNMgP2EVCQ\",\n\n \"header\":{\n\n \"kid\":\"did:example:alice#key-1\"\n", "file_path": "src/jws/parse.rs", "rank": 44, "score": 18.421907083733515 }, { "content": " Signature {\n\n header: Header { kid: \"did:example:alice#key-1\" },\n\n protected: \"eyJ0eXAiOiJhcHBsaWNhdGlvbi9kaWRjb21tLXNpZ25lZCtqc29uIiwiYWxnIjoiRWREU0EifQ\",\n\n signature: \"FW33NnvOHV0Ted9-F7GZbkia-vYAfBKtH4oBxbrttWAhBZ6UFJMxcGjL3lwOl4YohI3kyyd08LHPWNMgP2EVCQ\",\n\n },\n\n Signature {\n\n header: Header { kid: \"did:example:alice#key-2\" },\n\n protected: \"eyJ0eXAiOiJhcHBsaWNhdGlvbi9kaWRjb21tLXNpZ25lZCtqc29uIiwiYWxnIjoiRWREU0EifQ\",\n\n signature: \"FW33NnvOHV0Ted9-F7GZbkia-vYAfBKtH4oBxbrttWAhBZ6UFJMxcGjL3lwOl4YohI3kyyd08LHPWNMgP2EVCQ\",\n\n }\n\n ],\n\n payload: \"eyJpZCI6IjEyMzQ1Njc4OTAiLCJ0eXAiOiJhcHBsaWNhdGlvbi9kaWRjb21tLXBsYWluK2pzb24iLCJ0eXBlIjoiaHR0cDovL2V4YW1wbGUuY29tL3Byb3RvY29scy9sZXRzX2RvX2x1bmNoLzEuMC9wcm9wb3NhbCIsImZyb20iOiJkaWQ6ZXhhbXBsZTphbGljZSIsInRvIjpbImRpZDpleGFtcGxlOmJvYiJdLCJjcmVhdGVkX3RpbWUiOjE1MTYyNjkwMjIsImV4cGlyZXNfdGltZSI6MTUxNjM4NTkzMSwiYm9keSI6eyJtZXNzYWdlc3BlY2lmaWNhdHRyaWJ1dGUiOiJhbmQgaXRzIHZhbHVlIn19\",\n\n },\n\n protected: vec![\n\n ProtectedHeader {\n\n typ: \"application/didcomm-signed+json\",\n\n alg: Algorithm::EdDSA,\n\n },\n\n ProtectedHeader {\n\n typ: \"application/didcomm-signed+json\",\n", "file_path": "src/jws/parse.rs", "rank": 45, "score": 18.291911658590003 }, { "content": " },\n\n protected: vec![ProtectedHeader {\n\n typ: \"application/didcomm-signed+json\",\n\n alg: Algorithm::EdDSA,\n\n }],\n\n };\n\n\n\n assert_eq!(res, exp);\n\n }\n\n\n\n #[test]\n\n fn parse_works_unknown_fields() {\n\n let msg = r#\"\n\n {\n\n \"payload\":\"eyJpZCI6IjEyMzQ1Njc4OTAiLCJ0eXAiOiJhcHBsaWNhdGlvbi9kaWRjb21tLXBsYWluK2pzb24iLCJ0eXBlIjoiaHR0cDovL2V4YW1wbGUuY29tL3Byb3RvY29scy9sZXRzX2RvX2x1bmNoLzEuMC9wcm9wb3NhbCIsImZyb20iOiJkaWQ6ZXhhbXBsZTphbGljZSIsInRvIjpbImRpZDpleGFtcGxlOmJvYiJdLCJjcmVhdGVkX3RpbWUiOjE1MTYyNjkwMjIsImV4cGlyZXNfdGltZSI6MTUxNjM4NTkzMSwiYm9keSI6eyJtZXNzYWdlc3BlY2lmaWNhdHRyaWJ1dGUiOiJhbmQgaXRzIHZhbHVlIn19\",\n\n \"signatures\":[\n\n {\n\n \"protected\":\"eyJ0eXAiOiJhcHBsaWNhdGlvbi9kaWRjb21tLXNpZ25lZCtqc29uIiwiYWxnIjoiRWREU0EifQ\",\n\n \"signature\":\"FW33NnvOHV0Ted9-F7GZbkia-vYAfBKtH4oBxbrttWAhBZ6UFJMxcGjL3lwOl4YohI3kyyd08LHPWNMgP2EVCQ\",\n\n \"header\":{\n", "file_path": "src/jws/parse.rs", "rank": 46, "score": 18.02369400372379 }, { "content": " base64::encode_config(&signature, base64::URL_SAFE_NO_PAD)\n\n };\n\n\n\n let signature = Signature {\n\n header: Header { kid },\n\n protected: &protected,\n\n signature: &signature,\n\n };\n\n\n\n let jws = JWS {\n\n signatures: vec![signature],\n\n payload: &&payload,\n\n };\n\n\n\n let jws = serde_json::to_string(&jws).kind(ErrorKind::InvalidState, \"Unable serialize jws\")?;\n\n\n\n Ok(jws)\n\n}\n\n\n\n#[cfg(test)]\n", "file_path": "src/jws/sign.rs", "rank": 47, "score": 17.455456957807925 }, { "content": "use crate::{\n\n algorithms::{AnonCryptAlg, AuthCryptAlg, SignAlg},\n\n did::DIDResolver,\n\n error::Result,\n\n secrets::SecretsResolver,\n\n Message,\n\n};\n\n\n\nimpl Message {\n\n /// Unpacks the packed message by doing decryption and verifying the signatures.\n\n /// This method supports all DID Comm message types (encrypted, signed, plaintext).\n\n ///\n\n /// If unpack options expect a particular property (for example that a message is encrypted)\n\n /// and the packed message doesn't meet the criteria (it's not encrypted), then a MessageUntrusted\n\n /// error will be returned.\n\n ///\n\n /// # Params\n\n /// - `packed_msg` the message as JSON string to be unpacked\n\n /// - `did_resolver` instance of `DIDResolver` to resolve DIDs\n\n /// - `secrets_resolver` instance of SecretsResolver` to resolve sender DID keys secrets\n", "file_path": "src/unpack.rs", "rank": 49, "score": 16.896161557457326 }, { "content": "use crate::{error::Result, Message};\n\n\n\nimpl Message {\n\n /// Produces `DIDComm Plaintext Messages`\n\n /// https://identity.foundation/didcomm-messaging/spec/#didcomm-plaintext-messages.\n\n ///\n\n /// A DIDComm message in its plaintext form, not packaged into any protective envelope,\n\n /// is known as a DIDComm plaintext message. Plaintext messages lack confidentiality and integrity\n\n /// guarantees, and are repudiable. They are therefore not normally transported across security boundaries.\n\n /// However, this may be a helpful format to inspect in debuggers, since it exposes underlying semantics,\n\n /// and it is the format used in this spec to give examples of headers and other internals.\n\n /// Depending on ambient security, plaintext may or may not be an appropriate format for DIDComm data at rest.\n\n ///\n\n /// # Returns\n\n /// - a DIDComm plaintext message s JSON string\n\n ///\n\n /// # Errors\n\n /// - InvalidState\n\n pub fn pack_plaintext(&self) -> Result<String> {\n\n todo!()\n", "file_path": "src/pack_plaintext.rs", "rank": 50, "score": 16.640343651870474 }, { "content": "use askar_crypto::{\n\n alg::aes::{A128Kw, A256Kw, AesKey},\n\n buffer::SecretBytes,\n\n encrypt::KeyAeadInPlace,\n\n kdf::{ecdh_1pu::Ecdh1PU, ecdh_es::EcdhEs, FromKeyDerivation, KeyExchange},\n\n repr::{KeySecretBytes, ToSecretBytes},\n\n};\n\n\n\nuse crate::error::{err_msg, ErrorKind, Result, ResultExt};\n\n\n\n/// Note this trait is compatible with KW algorithms only\n\npub(crate) trait KeyWrap: KeyAeadInPlace {\n\n fn wrap_key<K: KeyAeadInPlace + ToSecretBytes>(&self, key: &K) -> Result<SecretBytes> {\n\n let params = self.aead_params();\n\n\n\n let key_len = key\n\n .secret_bytes_length()\n\n .kind(ErrorKind::InvalidState, \"Unable get key len\")?;\n\n\n\n let mut buf = SecretBytes::with_capacity(key_len + params.tag_length);\n", "file_path": "src/utils/crypto.rs", "rank": 51, "score": 16.47262667192901 }, { "content": " pub pthid: Option<String>,\n\n\n\n /// Custom message headers.\n\n #[serde(flatten)]\n\n #[serde(skip_serializing_if = \"Option::is_none\")]\n\n pub extra_headers: Option<HashMap<String, Value>>,\n\n\n\n /// The attribute is used for the sender\n\n /// to express when they created the message, expressed in\n\n /// UTC Epoch Seconds (seconds since 1970-01-01T00:00:00Z UTC).\n\n /// This attribute is informative to the recipient, and may be relied on by protocols.\n\n #[serde(skip_serializing_if = \"Option::is_none\")]\n\n pub created_time: Option<u64>,\n\n\n\n /// The expires_time attribute is used for the sender to express when they consider\n\n /// the message to be expired, expressed in UTC Epoch Seconds (seconds since 1970-01-01T00:00:00Z UTC).\n\n /// This attribute signals when the message is considered no longer valid by the sender.\n\n /// When omitted, the message is considered to have no expiration by the sender.\n\n #[serde(skip_serializing_if = \"Option::is_none\")]\n\n pub expires_time: Option<u64>,\n", "file_path": "src/message/message.rs", "rank": 52, "score": 16.315375324247743 }, { "content": "use askar_crypto::{\n\n buffer::SecretBytes,\n\n encrypt::KeyAeadInPlace,\n\n kdf::{FromKeyDerivation, KeyExchange},\n\n repr::{KeyGen, KeySecretBytes},\n\n};\n\n\n\nuse crate::{\n\n error::{err_msg, ErrorKind, Result, ResultContext, ResultExt},\n\n jwe::ParsedJWE,\n\n jwk::{FromJwkValue, ToJwkValue},\n\n utils::crypto::{JoseKDF, KeyWrap},\n\n};\n\n\n\nimpl<'a, 'b> ParsedJWE<'a, 'b> {\n\n pub(crate) fn decrypt<CE, KDF, KE, KW>(\n\n &self,\n\n sender: Option<(&str, &KE)>,\n\n recepient: (&str, &KE),\n\n ) -> Result<Vec<u8>>\n", "file_path": "src/jwe/decrypt.rs", "rank": 53, "score": 15.998386685646183 }, { "content": " Ecdh1puA256kw,\n\n\n\n #[serde(rename = \"ECDH-ES+A256KW\")]\n\n EcdhEsA256kw,\n\n\n\n #[serde(other)]\n\n Other(String),\n\n}\n\n\n\nimpl Algorithm {\n\n pub(crate) fn as_str(&self) -> &str {\n\n match self {\n\n Algorithm::Ecdh1puA256kw => \"ECDH-1PU+A256KW\",\n\n Algorithm::EcdhEsA256kw => \"ECDH-ES+A256KW\",\n\n Algorithm::Other(ref s) => &s,\n\n }\n\n }\n\n}\n\n\n\n/// Represents possible values for `enc` header.\n", "file_path": "src/jwe/envelope.rs", "rank": 54, "score": 15.986875864750752 }, { "content": "use async_trait::async_trait;\n\n\n\nuse crate::{\n\n error::Result,\n\n secrets::{Secret, SecretsResolver},\n\n};\n\n\n\npub struct ExampleSecretsResolver {\n\n _known_secrets: Vec<Secret>,\n\n}\n\n\n\nimpl ExampleSecretsResolver {\n\n pub fn new(known_secrets: Vec<Secret>) -> Self {\n\n ExampleSecretsResolver {\n\n _known_secrets: known_secrets,\n\n }\n\n }\n\n}\n\n\n\n#[async_trait]\n\nimpl SecretsResolver for ExampleSecretsResolver {\n\n async fn resolve(&self, _did_url: &str) -> Result<Option<Secret>> {\n\n todo!()\n\n }\n\n}\n", "file_path": "src/secrets/resolvers/example.rs", "rank": 55, "score": 15.883162870060888 }, { "content": "use askar_crypto::{\n\n alg::{ed25519::Ed25519KeyPair, p256::P256KeyPair, x25519::X25519KeyPair},\n\n jwk::{FromJwk, ToJwk},\n\n};\n\n\n\nuse serde_json::Value;\n\n\n\nuse crate::error::{ErrorKind, Result, ResultExt};\n\n\n\npub(crate) trait FromJwkValue: FromJwk {\n\n /// Import the key from a JWK string reference\n\n fn from_jwk_value(jwk: &Value) -> Result<Self> {\n\n let jwk = serde_json::to_string(jwk)\n\n .kind(ErrorKind::InvalidState, \"Unable produce jwk string\")?;\n\n\n\n Self::from_jwk(&jwk).kind(ErrorKind::Malformed, \"Unable produce jwk\")\n\n }\n\n}\n\n\n\npub(crate) trait ToJwkValue: ToJwk {\n", "file_path": "src/jwk.rs", "rank": 56, "score": 15.869538950665074 }, { "content": " let mut buf = vec![];\n\n let res = jws::parse(&msg, &mut buf);\n\n\n\n let res = res.expect_err(\"res is ok\");\n\n assert_eq!(res.kind(), ErrorKind::Malformed);\n\n\n\n assert_eq!(\n\n format!(\"{}\", res),\n\n \"Malformed: Unable parse protected header: invalid type: string \\\"typ\\\", expected struct ProtectedHeader at line 1 column 5\"\n\n );\n\n }\n\n}\n", "file_path": "src/jws/parse.rs", "rank": 57, "score": 15.844122223245172 }, { "content": " ) {\n\n let res = _verify::<K>(kid, key, msg);\n\n\n\n let err = res.expect_err(\"res is ok\");\n\n assert_eq!(err.kind(), ErrorKind::Malformed);\n\n\n\n assert_eq!(\n\n format!(\"{}\", err),\n\n \"Malformed: Unable decode signature: Invalid byte 33, offset 0.\"\n\n );\n\n }\n\n }\n\n\n\n fn _verify<Key: FromJwk + KeySigVerify>(\n\n kid: &str,\n\n key: &str,\n\n msg: &str,\n\n ) -> Result<bool, Error> {\n\n let key = Key::from_jwk(key).expect(\"unable from_jwk.\");\n\n\n", "file_path": "src/jws/verify.rs", "rank": 58, "score": 15.536979129753906 }, { "content": " Attachment {\n\n data: self.data,\n\n id: self.id,\n\n description: self.description,\n\n filename: self.filename,\n\n media_type: self.media_type,\n\n format: self.format,\n\n lastmod_time: self.lastmod_time,\n\n byte_count: self.byte_count,\n\n }\n\n }\n\n}\n\n\n\n// Attention: we are using untagged enum serialization variant.\n\n// Serde will try to match the data against each variant in order and the\n\n// first one that deserializes successfully is the one returned.\n\n// It should work as we always have discrimination here.\n\n\n\n/// Represents attachment data in Base64, embedded Json or Links form.\n\n#[derive(Debug, Serialize, Deserialize)]\n", "file_path": "src/message/attachment.rs", "rank": 59, "score": 15.440047879427562 }, { "content": " /// Tuple (signed_message, metadata)\n\n /// - `signed_message` a DIDComm signed message as JSON string\n\n /// - `metadata` additional metadata about this `encrypt` execution like used keys identifiers and algorithms.\n\n ///\n\n /// # Errors\n\n /// - `DIDNotResolved` Sender or recipient DID not found.\n\n /// - `DIDUrlNotResolved` DID doesn't contain mentioned DID Urls (for ex., key id)\n\n /// - `SecretNotFound` Sender secret is not found.\n\n /// - `InvalidState` Indicates library error.\n\n /// - `IOError` IO error during DID or secrets resolving\n\n /// TODO: verify and update errors list\n\n pub async fn pack_signed<'dr, 'sr>(\n\n &self,\n\n _sign_by: &str,\n\n _did_resolver: &'dr (dyn DIDResolver + 'dr),\n\n _secrets_resolver: &'sr (dyn SecretsResolver + 'sr),\n\n ) -> Result<(String, SignMetadata)> {\n\n todo!()\n\n }\n\n}\n", "file_path": "src/pack_signed.rs", "rank": 60, "score": 15.047822797940036 }, { "content": " .protected\n\n .get(i)\n\n .ok_or_else(|| err_msg(ErrorKind::InvalidState, \"Invalid protected header index\"))?;\n\n\n\n let sig_type = protected.alg.sig_type()?;\n\n let sign_input = format!(\"{}.{}\", signature.protected, self.jws.payload);\n\n\n\n let signature = base64::decode_config(&signature.signature, base64::URL_SAFE_NO_PAD)\n\n .kind(ErrorKind::Malformed, \"Unable decode signature\")?;\n\n\n\n let valid = key\n\n .verify_signature(sign_input.as_bytes(), &signature, Some(sig_type))\n\n .kind(ErrorKind::Malformed, \"Unable verify signature\")?;\n\n\n\n Ok(valid)\n\n }\n\n}\n\n\n\n#[cfg(test)]\n\nmod tests {\n", "file_path": "src/jws/verify.rs", "rank": 61, "score": 14.768459894317857 }, { "content": "// TODO: Remove allow\n\n#[allow(unused_imports)]\n\npub(crate) use parse::{parse, ParsedJWS};\n\n\n\n#[cfg(test)]\n\nmod tests {\n\n use askar_crypto::{alg::ed25519::Ed25519KeyPair, jwk::FromJwk};\n\n\n\n use crate::jws::{self, envelope::Algorithm};\n\n\n\n #[test]\n\n fn demo_works() {\n\n // Identifier of Alice key\n\n let alice_kid = \"did:example:alice#key-1\";\n\n\n\n // Alice private key\n\n let alice_key = Ed25519KeyPair::from_jwk(\n\n r#\"\n\n {\n\n \"kty\":\"OKP\",\n", "file_path": "src/jws/mod.rs", "rank": 62, "score": 14.71598089035367 }, { "content": "#[cfg(test)]\n\nmod tests {\n\n use crate::{\n\n error::ErrorKind,\n\n jws::{\n\n self,\n\n envelope::{Algorithm, Header, ProtectedHeader, Signature, JWS},\n\n ParsedJWS,\n\n },\n\n };\n\n\n\n #[test]\n\n fn parse_works() {\n\n let msg = r#\"\n\n {\n\n \"payload\":\"eyJpZCI6IjEyMzQ1Njc4OTAiLCJ0eXAiOiJhcHBsaWNhdGlvbi9kaWRjb21tLXBsYWluK2pzb24iLCJ0eXBlIjoiaHR0cDovL2V4YW1wbGUuY29tL3Byb3RvY29scy9sZXRzX2RvX2x1bmNoLzEuMC9wcm9wb3NhbCIsImZyb20iOiJkaWQ6ZXhhbXBsZTphbGljZSIsInRvIjpbImRpZDpleGFtcGxlOmJvYiJdLCJjcmVhdGVkX3RpbWUiOjE1MTYyNjkwMjIsImV4cGlyZXNfdGltZSI6MTUxNjM4NTkzMSwiYm9keSI6eyJtZXNzYWdlc3BlY2lmaWNhdHRyaWJ1dGUiOiJhbmQgaXRzIHZhbHVlIn19\",\n\n \"signatures\":[\n\n {\n\n \"protected\":\"eyJ0eXAiOiJhcHBsaWNhdGlvbi9kaWRjb21tLXNpZ25lZCtqc29uIiwiYWxnIjoiRWREU0EifQ\",\n\n \"signature\":\"FW33NnvOHV0Ted9-F7GZbkia-vYAfBKtH4oBxbrttWAhBZ6UFJMxcGjL3lwOl4YohI3kyyd08LHPWNMgP2EVCQ\",\n", "file_path": "src/jws/parse.rs", "rank": 63, "score": 14.495802559319475 }, { "content": " async fn resolve(&self, _did: &str) -> Result<Option<Box<dyn DIDDoc>>> {\n\n Ok(self\n\n .known_dids\n\n .iter()\n\n .find(|ddoc| ddoc.did() == _did)\n\n .map(|ddoc| Box::new((*ddoc).clone()) as Box<dyn DIDDoc>))\n\n }\n\n}\n\n\n\n#[derive(Clone, Debug)]\n\npub struct ExampleDIDDoc {\n\n did: String,\n\n key_agreements: Vec<String>,\n\n authentications: Vec<String>,\n\n verification_methods: Vec<VerificationMethod>,\n\n services: Vec<Service>,\n\n}\n\n\n\nimpl DIDDoc for ExampleDIDDoc {\n\n fn did(&self) -> &str {\n", "file_path": "src/did/resolvers/example.rs", "rank": 64, "score": 14.45528962181656 }, { "content": "use serde_json::Value;\n\n\n\nuse crate::{\n\n algorithms::{AnonCryptAlg, AuthCryptAlg},\n\n did::DIDResolver,\n\n error::Result,\n\n secrets::SecretsResolver,\n\n Message,\n\n};\n\n\n\nimpl Message {\n\n /// Produces `DIDComm Encrypted Message`\n\n /// https://identity.foundation/didcomm-messaging/spec/#didcomm-encrypted-message.\n\n ///\n\n /// A DIDComm encrypted message is an encrypted JWM (JSON Web Messages) and\n\n /// hides its content from all but authorized recipients, discloses (optionally) and proves\n\n /// the sender to exactly and only those recipients, and provides integrity guarantees.\n\n /// It is important in privacy-preserving routing. It is what normally moves over network\n\n /// transports in DIDComm applications, and is the safest format for storing DIDComm data at rest.\n\n ///\n", "file_path": "src/pack_encrypted.rs", "rank": 65, "score": 14.377906298791569 }, { "content": " /// - `options` allow fine configuration of unpacking process and imposing additional restrictions\n\n /// to message to be trusted.\n\n ///\n\n /// # Returns\n\n /// Tuple `(message, metadata)`.\n\n /// - `message` plain message instance\n\n /// - `metadata` additional metadata about this `unpack` execution like used keys identifiers,\n\n /// trust context, algorithms and etc.\n\n ///\n\n /// # Errors\n\n /// - `DIDNotResolved` Sender or recipient DID not found.\n\n /// - `DIDUrlNotResolved` DID doesn't contain mentioned DID Urls (for ex., key id)\n\n /// - `MessageMalformed` message doesn't correspond to DID Comm or has invalid encryption or signatures.\n\n /// - `UnsatisfiedConstraint` message doesn't satisfy checks requested by unpack options.\n\n /// - `SecretNotFound` No recipient secrets found.\n\n /// - `InvalidState` Indicates library error.\n\n /// - `IOError` IO error during DID or secrets resolving.\n\n /// TODO: verify and update errors list\n\n pub async fn unpack<'dr, 'sr>(\n\n _packed_msg: &str,\n", "file_path": "src/unpack.rs", "rank": 66, "score": 14.3703172781169 }, { "content": "\n\n _sign_works_incompatible_alg::<P256KeyPair>(\n\n ALICE_KID_P256,\n\n ALICE_KEY_P256,\n\n Algorithm::Es256K,\n\n PAYLOAD,\n\n );\n\n\n\n _sign_works_incompatible_alg::<K256KeyPair>(\n\n ALICE_KID_K256,\n\n ALICE_KEY_K256,\n\n Algorithm::Es256,\n\n PAYLOAD,\n\n );\n\n\n\n _sign_works_incompatible_alg::<K256KeyPair>(\n\n ALICE_KID_K256,\n\n ALICE_KEY_K256,\n\n Algorithm::EdDSA,\n\n PAYLOAD,\n", "file_path": "src/jws/sign.rs", "rank": 67, "score": 13.948581022428282 }, { "content": " _sign_works_incompatible_alg::<Ed25519KeyPair>(\n\n ALICE_KID_ED25519,\n\n ALICE_KEY_ED25519,\n\n Algorithm::Es256K,\n\n PAYLOAD,\n\n );\n\n\n\n _sign_works_incompatible_alg::<P256KeyPair>(\n\n ALICE_KID_P256,\n\n ALICE_KEY_P256,\n\n Algorithm::Es256K,\n\n PAYLOAD,\n\n );\n\n\n\n _sign_works_incompatible_alg::<P256KeyPair>(\n\n ALICE_KID_P256,\n\n ALICE_KEY_P256,\n\n Algorithm::EdDSA,\n\n PAYLOAD,\n\n );\n", "file_path": "src/jws/sign.rs", "rank": 68, "score": 13.921923855239445 }, { "content": " Sha256::digest(kids.join(\".\").as_bytes())\n\n };\n\n\n\n let epk = KE::generate(&mut rng).kind(ErrorKind::InvalidState, \"Unable generate epk\")?;\n\n\n\n let protected = {\n\n let epk = epk.to_jwk_public_value()?;\n\n let apu = skid.map(|skid| base64::encode_config(skid, base64::URL_SAFE_NO_PAD));\n\n let apv = base64::encode_config(apv, base64::URL_SAFE_NO_PAD);\n\n\n\n let p = ProtectedHeader {\n\n typ: Some(\"application/didcomm-encrypted+json\"),\n\n alg: alg.clone(),\n\n enc,\n\n skid,\n\n apu: apu.as_deref(),\n\n apv: &apv,\n\n epk,\n\n };\n\n\n", "file_path": "src/jwe/encrypt.rs", "rank": 69, "score": 13.864752951267844 }, { "content": " pub description: Option<String>,\n\n\n\n /// A hint about the name that might be used if this attachment is persisted as a file.\n\n /// It is not required, and need not be unique. If this field is present and mime-type is not,\n\n /// the extension on the filename may be used to infer a MIME type.\n\n #[serde(skip_serializing_if = \"Option::is_none\")]\n\n pub filename: Option<String>,\n\n\n\n /// Describes the MIME type of the attached content.\n\n #[serde(skip_serializing_if = \"Option::is_none\")]\n\n pub media_type: Option<String>,\n\n\n\n /// Describes the format of the attachment if the mime_type is not sufficient.\n\n #[serde(skip_serializing_if = \"Option::is_none\")]\n\n pub format: Option<String>,\n\n\n\n /// A hint about when the content in this attachment was last modified\n\n /// in UTC Epoch Seconds (seconds since 1970-01-01T00:00:00Z UTC).\n\n #[serde(skip_serializing_if = \"Option::is_none\")]\n\n pub lastmod_time: Option<u64>,\n", "file_path": "src/message/attachment.rs", "rank": 70, "score": 13.359869703261948 }, { "content": " alg: Algorithm::EdDSA,\n\n }\n\n ],\n\n };\n\n\n\n assert_eq!(res, exp);\n\n }\n\n\n\n #[test]\n\n fn parse_works_unparsable() {\n\n let msg = r#\"\n\n {\n\n \"payload\":\"eyJpZCI6IjEyMzQ1Njc4OTAiLCJ0eXAiOiJhcHBsaWNhdGlvbi9kaWRjb21tLXBsYWluK2pzb24iLCJ0eXBlIjoiaHR0cDovL2V4YW1wbGUuY29tL3Byb3RvY29scy9sZXRzX2RvX2x1bmNoLzEuMC9wcm9wb3NhbCIsImZyb20iOiJkaWQ6ZXhhbXBsZTphbGljZSIsInRvIjpbImRpZDpleGFtcGxlOmJvYiJdLCJjcmVhdGVkX3RpbWUiOjE1MTYyNjkwMjIsImV4cGlyZXNfdGltZSI6MTUxNjM4NTkzMSwiYm9keSI6eyJtZXNzYWdlc3BlY2lmaWNhdHRyaWJ1dGUiOiJhbmQgaXRzIHZhbHVlIn19\",\n\n \"signatures\":[\n\n {\n\n \"protected\":\"eyJ0eXAiOiJhcHBsaWNhdGlvbi9kaWRjb21tLXNpZ25lZCtqc29uIiwiYWxnIjoiRWREU0EifQ\",\n\n \"signature\":\"FW33NnvOHV0Ted9-F7GZbkia-vYAfBKtH4oBxbrttWAhBZ6UFJMxcGjL3lwOl4YohI3kyyd08LHPWNMgP2EVCQ\",\n\n \"header\":{\n\n \"kid\":\"did:example:alice#key-1\",\n\n }\n", "file_path": "src/jws/parse.rs", "rank": 71, "score": 13.146893036745155 }, { "content": " typ: Some(\"application/didcomm-encrypted+json\"),\n\n alg: jwe::envelope::Algorithm::Ecdh1puA256kw,\n\n enc: EncAlgorithm::A256cbcHs512,\n\n skid: Some(\"did:example:alice#key-x25519-1\"),\n\n apu: Some(\"ZGlkOmV4YW1wbGU6YWxpY2Uja2V5LXgyNTUxOS0x\"),\n\n apv: \"NcsuAnrRfPK69A-rkZ0L9XWUG4jMvNC3Zg74BPz53PA\",\n\n epk: json!({\n\n \"kty\":\"OKP\",\n\n \"crv\":\"X25519\",\n\n \"x\":\"GFcMopJljf4pLZfch4a_GhTM_YAf6iNI1dWDGyVCaw0\"\n\n }),\n\n },\n\n apu: Some(b\"did:example:alice#key-x25519-1\".to_vec()),\n\n apv: vec![53, 203, 46, 2, 122, 209, 124, 242, 186, 244, 15, 171, 145, 157, 11, 245, 117, 148, 27, 136, 204, 188, 208, 183, 102, 14, 248, 4, 252, 249, 220, 240],\n\n };\n\n\n\n assert_eq!(res, exp);\n\n }\n\n\n\n #[test]\n", "file_path": "src/jwe/parse.rs", "rank": 72, "score": 12.808253403080887 }, { "content": " alice: Option<(&str, &str, &str)>,\n\n bob: &[(&str, &str, &str)],\n\n alg: Algorithm,\n\n enc_alg: EncAlgorithm,\n\n ) where\n\n CE: KeyAeadInPlace + KeyAeadMeta + KeyGen + ToSecretBytes + KeySecretBytes,\n\n KDF: JoseKDF<KE, KW>,\n\n KE: KeyExchange + KeyGen + ToJwkValue + FromJwkValue + ToPublicBytes + KeyPublicBytes,\n\n KW: KeyWrap + FromKeyDerivation,\n\n {\n\n let alice = alice.map(|a| {\n\n (\n\n a.0,\n\n KE::from_jwk(a.1).expect(\"Unable from_jwk\"),\n\n KE::from_jwk(a.2).expect(\"Unable from_jwk\"),\n\n )\n\n });\n\n\n\n let alice_kid = alice.as_ref().map(|a| a.0);\n\n let alice_priv = alice.as_ref().map(|a| (a.0, &a.1));\n", "file_path": "src/jwe/encrypt.rs", "rank": 73, "score": 12.806436830410991 }, { "content": " let signature = jws\n\n .signatures\n\n .get(i)\n\n .ok_or_else(|| err_msg(ErrorKind::InvalidState, \"Invalid signature index\"))?;\n\n\n\n base64::decode_config_buf(signature.protected, base64::URL_SAFE_NO_PAD, b)\n\n .kind(ErrorKind::Malformed, \"Unable decode protected header\")?;\n\n\n\n let p: ProtectedHeader = serde_json::from_slice(b)\n\n .kind(ErrorKind::Malformed, \"Unable parse protected header\")?;\n\n\n\n protected.push(p);\n\n }\n\n\n\n protected\n\n };\n\n\n\n Ok(ParsedJWS { jws, protected })\n\n}\n\n\n", "file_path": "src/jws/parse.rs", "rank": 74, "score": 12.801903435277431 }, { "content": " },\n\n Recepient {\n\n header: PerRecipientHeader { kid: \"did:example:bob#key-x25519-3\" },\n\n encrypted_key: \"TEWlqlq-ao7Lbynf0oZYhxs7ZB39SUWBCK4qjqQqfeItfwmNyDm73A\",\n\n },\n\n ],\n\n iv: \"ESpmcyGiZpRjc5urDela21TOOTW8Wqd1\",\n\n ciphertext: \"KWS7gJU7TbyJlcT9dPkCw-ohNigGaHSukR9MUqFM0THbCTCNkY-g5tahBFyszlKIKXs7qOtqzYyWbPou2q77XlAeYs93IhF6NvaIjyNqYklvj-OtJt9W2Pj5CLOMdsR0C30wchGoXd6wEQZY4ttbzpxYznqPmJ0b9KW6ZP-l4_DSRYe9B-1oSWMNmqMPwluKbtguC-riy356Xbu2C9ShfWmpmjz1HyJWQhZfczuwkWWlE63g26FMskIZZd_jGpEhPFHKUXCFwbuiw_Iy3R0BIzmXXdK_w7PZMMPbaxssl2UeJmLQgCAP8j8TukxV96EKa6rGgULvlo7qibjJqsS5j03bnbxkuxwbfyu3OxwgVzFWlyHbUH6p\",\n\n tag: \"6ylC_iAs4JvDQzXeY6MuYQ\",\n\n },\n\n protected: ProtectedHeader {\n\n typ: Some(\"application/didcomm-encrypted+json\"),\n\n alg: jwe::envelope::Algorithm::EcdhEsA256kw,\n\n enc: EncAlgorithm::Xc20P,\n\n skid: None,\n\n apu: None,\n\n apv: \"NcsuAnrRfPK69A-rkZ0L9XWUG4jMvNC3Zg74BPz53PA\",\n\n epk: json!({\n\n \"kty\":\"OKP\",\n\n \"crv\":\"X25519\",\n", "file_path": "src/jwe/parse.rs", "rank": 75, "score": 12.717927062209256 }, { "content": " }\n\n\n\n pub fn new<E>(kind: ErrorKind, source: E) -> Error\n\n where\n\n E: std::error::Error + Send + Sync + 'static,\n\n {\n\n Error {\n\n kind,\n\n source: anyhow::Error::new(source),\n\n }\n\n }\n\n\n\n pub fn msg<D>(kind: ErrorKind, msg: D) -> Error\n\n where\n\n D: fmt::Display + fmt::Debug + Send + Sync + 'static,\n\n {\n\n Error {\n\n kind,\n\n source: anyhow::Error::msg(msg),\n\n }\n\n }\n\n}\n\n\n\npub type Result<T> = std::result::Result<T, Error>;\n\n\n", "file_path": "src/error.rs", "rank": 76, "score": 12.65934172898477 }, { "content": " pub sign_alg: Option<SignAlg>,\n\n\n\n /// If the plaintext has been signed, the JWS is returned for non-repudiation purposes\n\n pub signed_plaintext: Option<String>,\n\n}\n\n\n\n#[cfg(test)]\n\nmod test {\n\n use super::*;\n\n\n\n use crate::{did::resolvers::ExampleDIDResolver, secrets::resolvers::ExampleSecretsResolver};\n\n\n\n #[tokio::test]\n\n #[ignore = \"will be fixed after https://github.com/sicpa-dlab/didcomm-gemini/issues/71\"]\n\n async fn unpack_works() {\n\n let msg = \"{}\"; // TODO: use test vector from DID Comm specification.\n\n\n\n let did_resolver = ExampleDIDResolver::new(vec![]);\n\n let secrets_resolver = ExampleSecretsResolver::new(vec![]);\n\n\n", "file_path": "src/unpack.rs", "rank": 77, "score": 12.550719316896707 }, { "content": "mod jwe;\n\nmod jwk;\n\nmod jws;\n\nmod message;\n\nmod pack_encrypted;\n\nmod pack_plaintext;\n\nmod pack_signed;\n\nmod unpack;\n\nmod utils;\n\n\n\npub mod algorithms;\n\npub mod did;\n\npub mod error;\n\npub mod secrets;\n\n\n\npub(crate) use askar_crypto as crypto;\n\n\n\npub use message::{\n\n Attachment, AttachmentBuilder, AttachmentData, Base64AttachmentData, JsonAttachmentData,\n\n LinksAttachmentData, Message, MessageBuilder,\n", "file_path": "src/lib.rs", "rank": 78, "score": 12.466681254280992 }, { "content": "//! Set of interfaces that allow access to DID Document secrets\n\n\n\npub mod resolvers;\n\n\n\nuse async_trait::async_trait;\n\nuse serde_json::Value;\n\n\n\nuse crate::error::Result;\n\n\n\n/// Interface for secrets resolver.\n\n/// Resolves secrets such as private keys to be used for signing and encryption.\n\n#[async_trait]\n", "file_path": "src/secrets/mod.rs", "rank": 79, "score": 12.409212880793739 }, { "content": " Recepient {\n\n header: PerRecipientHeader { kid: \"did:example:bob#key-x25519-1\" },\n\n encrypted_key: \"3n1olyBR3nY7ZGAprOx-b7wYAKza6cvOYjNwVg3miTnbLwPP_FmE1A\",\n\n },\n\n Recepient {\n\n header: PerRecipientHeader { kid: \"did:example:bob#key-x25519-2\" },\n\n encrypted_key: \"j5eSzn3kCrIkhQAWPnEwrFPMW6hG0zF_y37gUvvc5gvlzsuNX4hXrQ\",\n\n },\n\n Recepient {\n\n header: PerRecipientHeader { kid: \"did:example:bob#key-x25519-3\" },\n\n encrypted_key: \"TEWlqlq-ao7Lbynf0oZYhxs7ZB39SUWBCK4qjqQqfeItfwmNyDm73A\",\n\n },\n\n ],\n\n iv: \"ESpmcyGiZpRjc5urDela21TOOTW8Wqd1\",\n\n ciphertext: \"KWS7gJU7TbyJlcT9dPkCw-ohNigGaHSukR9MUqFM0THbCTCNkY-g5tahBFyszlKIKXs7qOtqzYyWbPou2q77XlAeYs93IhF6NvaIjyNqYklvj-OtJt9W2Pj5CLOMdsR0C30wchGoXd6wEQZY4ttbzpxYznqPmJ0b9KW6ZP-l4_DSRYe9B-1oSWMNmqMPwluKbtguC-riy356Xbu2C9ShfWmpmjz1HyJWQhZfczuwkWWlE63g26FMskIZZd_jGpEhPFHKUXCFwbuiw_Iy3R0BIzmXXdK_w7PZMMPbaxssl2UeJmLQgCAP8j8TukxV96EKa6rGgULvlo7qibjJqsS5j03bnbxkuxwbfyu3OxwgVzFWlyHbUH6p\",\n\n tag: \"6ylC_iAs4JvDQzXeY6MuYQ\",\n\n },\n\n protected: ProtectedHeader {\n\n typ: Some(\"application/didcomm-encrypted+json\"),\n\n alg: jwe::envelope::Algorithm::EcdhEsA256kw,\n", "file_path": "src/jwe/parse.rs", "rank": 80, "score": 12.016165923904591 }, { "content": " );\n\n\n\n _sign_works::<P256KeyPair>(\n\n ALICE_KID_P256,\n\n ALICE_KEY_P256,\n\n ALICE_PKEY_P256,\n\n Algorithm::Es256,\n\n PAYLOAD,\n\n );\n\n\n\n _sign_works::<K256KeyPair>(\n\n ALICE_KID_K256,\n\n ALICE_KEY_K256,\n\n ALICE_PKEY_K256,\n\n Algorithm::Es256K,\n\n PAYLOAD,\n\n );\n\n\n\n fn _sign_works<K: FromJwk + KeySign + KeySigVerify>(\n\n kid: &str,\n", "file_path": "src/jws/sign.rs", "rank": 81, "score": 11.997266028031916 }, { "content": "use async_trait::async_trait;\n\n\n\nuse crate::{\n\n did::{DIDDoc, DIDResolver, Service, VerificationMethod},\n\n error::Result,\n\n};\n\n\n\n/// Allows resolve pre-defined did's for `example` and other methods.\n\npub struct ExampleDIDResolver {\n\n known_dids: Vec<ExampleDIDDoc>,\n\n}\n\n\n\nimpl ExampleDIDResolver {\n\n pub fn new(known_dids: Vec<ExampleDIDDoc>) -> Self {\n\n ExampleDIDResolver { known_dids }\n\n }\n\n}\n\n\n\n#[async_trait]\n\nimpl DIDResolver for ExampleDIDResolver {\n", "file_path": "src/did/resolvers/example.rs", "rank": 82, "score": 11.981570186062623 }, { "content": " \"#;\n\n\n\n let mut buf = vec![];\n\n let res = jws::parse(&msg, &mut buf);\n\n\n\n let res = res.expect_err(\"res is ok\");\n\n assert_eq!(res.kind(), ErrorKind::Malformed);\n\n\n\n assert_eq!(\n\n format!(\"{}\", res),\n\n \"Malformed: Unable decode protected header: Invalid byte 33, offset 0.\"\n\n );\n\n }\n\n\n\n #[test]\n\n fn parse_works_unparsable_protected() {\n\n let msg = r#\"\n\n {\n\n \"payload\":\"eyJpZCI6IjEyMzQ1Njc4OTAiLCJ0eXAiOiJhcHBsaWNhdGlvbi9kaWRjb21tLXBsYWluK2pzb24iLCJ0eXBlIjoiaHR0cDovL2V4YW1wbGUuY29tL3Byb3RvY29scy9sZXRzX2RvX2x1bmNoLzEuMC9wcm9wb3NhbCIsImZyb20iOiJkaWQ6ZXhhbXBsZTphbGljZSIsInRvIjpbImRpZDpleGFtcGxlOmJvYiJdLCJjcmVhdGVkX3RpbWUiOjE1MTYyNjkwMjIsImV4cGlyZXNfdGltZSI6MTUxNjM4NTkzMSwiYm9keSI6eyJtZXNzYWdlc3BlY2lmaWNhdHRyaWJ1dGUiOiJhbmQgaXRzIHZhbHVlIn19\",\n\n \"signatures\":[\n", "file_path": "src/jws/parse.rs", "rank": 83, "score": 11.97102498428025 }, { "content": "// TODO: remove allow\n\n#[allow(unused_imports)]\n\npub(crate) use parse::{parse, ParsedJWE};\n\n\n\n#[cfg(test)]\n\npub(crate) mod test_support {\n\n pub(crate) const ALICE_KID_X25519_1: &str = \"did:example:alice#key-x25519-1\";\n\n\n\n pub(crate) const ALICE_KEY_X25519_1: &str = r#\"{\n\n \"kty\":\"OKP\",\n\n \"d\":\"r-jK2cO3taR8LQnJB1_ikLBTAnOtShJOsHXRUWT-aZA\",\n\n \"crv\":\"X25519\",\n\n \"x\":\"avH0O2Y4tqLAq8y9zpianr8ajii5m4F_mICrzNlatXs\"\n\n }\"#;\n\n\n\n pub(crate) const ALICE_PKEY_X25519_1: &str = r#\"{\n\n \"kty\":\"OKP\",\n\n \"crv\":\"X25519\",\n\n \"x\":\"avH0O2Y4tqLAq8y9zpianr8ajii5m4F_mICrzNlatXs\"\n\n }\"#;\n", "file_path": "src/jwe/mod.rs", "rank": 84, "score": 11.94954281265569 }, { "content": " header: PerRecipientHeader { kid: \"did:example:bob#key-x25519-1\" },\n\n encrypted_key: \"o0FJASHkQKhnFo_rTMHTI9qTm_m2mkJp-wv96mKyT5TP7QjBDuiQ0AMKaPI_RLLB7jpyE-Q80Mwos7CvwbMJDhIEBnk2qHVB\",\n\n },\n\n Recepient {\n\n header: PerRecipientHeader { kid: \"did:example:bob#key-x25519-2\" },\n\n encrypted_key: \"rYlafW0XkNd8kaXCqVbtGJ9GhwBC3lZ9AihHK4B6J6V2kT7vjbSYuIpr1IlAjvxYQOw08yqEJNIwrPpB0ouDzKqk98FVN7rK\",\n\n },\n\n Recepient {\n\n header: PerRecipientHeader { kid: \"did:example:bob#key-x25519-3\" },\n\n encrypted_key: \"aqfxMY2sV-njsVo-_9Ke9QbOf6hxhGrUVh_m-h_Aq530w3e_4IokChfKWG1tVJvXYv_AffY7vxj0k5aIfKZUxiNmBwC_QsNo\",\n\n },\n\n ],\n\n iv: \"o02OXDQ6_-sKz2PX_6oyJg\",\n\n ciphertext: \"MJezmxJ8DzUB01rMjiW6JViSaUhsZBhMvYtezkhmwts1qXWtDB63i4-FHZP6cJSyCI7eU-gqH8lBXO_UVuviWIqnIUrTRLaumanZ4q1dNKAnxNL-dHmb3coOqSvy3ZZn6W17lsVudjw7hUUpMbeMbQ5W8GokK9ZCGaaWnqAzd1ZcuGXDuemWeA8BerQsfQw_IQm-aUKancldedHSGrOjVWgozVL97MH966j3i9CJc3k9jS9xDuE0owoWVZa7SxTmhl1PDetmzLnYIIIt-peJtNYGdpd-FcYxIFycQNRUoFEr77h4GBTLbC-vqbQHJC1vW4O2LEKhnhOAVlGyDYkNbA4DSL-LMwKxenQXRARsKSIMn7z-ZIqTE-VCNj9vbtgR\",\n\n tag: \"uYeo7IsZjN7AnvBjUZE5lNryNENbf6_zew_VC-d4b3U\",\n\n },\n\n protected: ProtectedHeader {\n\n typ: Some(\"application/didcomm-encrypted+json\"),\n\n alg: jwe::envelope::Algorithm::Ecdh1puA256kw,\n\n enc: EncAlgorithm::A256cbcHs512,\n", "file_path": "src/jwe/parse.rs", "rank": 85, "score": 11.809614728006416 }, { "content": " header: PerRecipientHeader { kid: \"did:example:bob#key-x25519-1\" },\n\n encrypted_key: \"o0FJASHkQKhnFo_rTMHTI9qTm_m2mkJp-wv96mKyT5TP7QjBDuiQ0AMKaPI_RLLB7jpyE-Q80Mwos7CvwbMJDhIEBnk2qHVB\",\n\n },\n\n Recepient {\n\n header: PerRecipientHeader { kid: \"did:example:bob#key-x25519-2\" },\n\n encrypted_key: \"rYlafW0XkNd8kaXCqVbtGJ9GhwBC3lZ9AihHK4B6J6V2kT7vjbSYuIpr1IlAjvxYQOw08yqEJNIwrPpB0ouDzKqk98FVN7rK\",\n\n },\n\n Recepient {\n\n header: PerRecipientHeader { kid: \"did:example:bob#key-x25519-3\" },\n\n encrypted_key: \"aqfxMY2sV-njsVo-_9Ke9QbOf6hxhGrUVh_m-h_Aq530w3e_4IokChfKWG1tVJvXYv_AffY7vxj0k5aIfKZUxiNmBwC_QsNo\",\n\n },\n\n ],\n\n iv: \"o02OXDQ6_-sKz2PX_6oyJg\",\n\n ciphertext: \"MJezmxJ8DzUB01rMjiW6JViSaUhsZBhMvYtezkhmwts1qXWtDB63i4-FHZP6cJSyCI7eU-gqH8lBXO_UVuviWIqnIUrTRLaumanZ4q1dNKAnxNL-dHmb3coOqSvy3ZZn6W17lsVudjw7hUUpMbeMbQ5W8GokK9ZCGaaWnqAzd1ZcuGXDuemWeA8BerQsfQw_IQm-aUKancldedHSGrOjVWgozVL97MH966j3i9CJc3k9jS9xDuE0owoWVZa7SxTmhl1PDetmzLnYIIIt-peJtNYGdpd-FcYxIFycQNRUoFEr77h4GBTLbC-vqbQHJC1vW4O2LEKhnhOAVlGyDYkNbA4DSL-LMwKxenQXRARsKSIMn7z-ZIqTE-VCNj9vbtgR\",\n\n tag: \"uYeo7IsZjN7AnvBjUZE5lNryNENbf6_zew_VC-d4b3U\",\n\n },\n\n protected: ProtectedHeader {\n\n typ: Some(\"application/didcomm-encrypted+json\"),\n\n alg: jwe::envelope::Algorithm::Ecdh1puA256kw,\n\n enc: EncAlgorithm::A256cbcHs512,\n", "file_path": "src/jwe/parse.rs", "rank": 86, "score": 11.809614728006416 }, { "content": " ciphertext: \"KWS7gJU7TbyJlcT9dPkCw-ohNigGaHSukR9MUqFM0THbCTCNkY-g5tahBFyszlKIKXs7qOtqzYyWbPou2q77XlAeYs93IhF6NvaIjyNqYklvj-OtJt9W2Pj5CLOMdsR0C30wchGoXd6wEQZY4ttbzpxYznqPmJ0b9KW6ZP-l4_DSRYe9B-1oSWMNmqMPwluKbtguC-riy356Xbu2C9ShfWmpmjz1HyJWQhZfczuwkWWlE63g26FMskIZZd_jGpEhPFHKUXCFwbuiw_Iy3R0BIzmXXdK_w7PZMMPbaxssl2UeJmLQgCAP8j8TukxV96EKa6rGgULvlo7qibjJqsS5j03bnbxkuxwbfyu3OxwgVzFWlyHbUH6p\",\n\n tag: \"6ylC_iAs4JvDQzXeY6MuYQ\",\n\n },\n\n protected: ProtectedHeader {\n\n typ: Some(\"application/didcomm-encrypted+json\"),\n\n alg: jwe::envelope::Algorithm::EcdhEsA256kw,\n\n enc: EncAlgorithm::Xc20P,\n\n skid: None,\n\n apu: None,\n\n apv: \"NcsuAnrRfPK69A-rkZ0L9XWUG4jMvNC3Zg74BPz53PA\",\n\n epk: json!({\n\n \"kty\":\"OKP\",\n\n \"crv\":\"X25519\",\n\n \"x\":\"JHjsmIRZAaB0zRG_wNXLV2rPggF00hdHbW5rj8g0I24\"\n\n }),\n\n },\n\n apu: None,\n\n apv: vec![53, 203, 46, 2, 122, 209, 124, 242, 186, 244, 15, 171, 145, 157, 11, 245, 117, 148, 27, 136, 204, 188, 208, 183, 102, 14, 248, 4, 252, 249, 220, 240],\n\n };\n\n\n", "file_path": "src/jwe/parse.rs", "rank": 87, "score": 11.767888508634066 }, { "content": " header: PerRecipientHeader { kid: \"did:example:bob#key-x25519-2\" },\n\n encrypted_key: \"rYlafW0XkNd8kaXCqVbtGJ9GhwBC3lZ9AihHK4B6J6V2kT7vjbSYuIpr1IlAjvxYQOw08yqEJNIwrPpB0ouDzKqk98FVN7rK\",\n\n },\n\n Recepient {\n\n header: PerRecipientHeader { kid: \"did:example:bob#key-x25519-3\" },\n\n encrypted_key: \"aqfxMY2sV-njsVo-_9Ke9QbOf6hxhGrUVh_m-h_Aq530w3e_4IokChfKWG1tVJvXYv_AffY7vxj0k5aIfKZUxiNmBwC_QsNo\",\n\n },\n\n ],\n\n iv: \"o02OXDQ6_-sKz2PX_6oyJg\",\n\n ciphertext: \"MJezmxJ8DzUB01rMjiW6JViSaUhsZBhMvYtezkhmwts1qXWtDB63i4-FHZP6cJSyCI7eU-gqH8lBXO_UVuviWIqnIUrTRLaumanZ4q1dNKAnxNL-dHmb3coOqSvy3ZZn6W17lsVudjw7hUUpMbeMbQ5W8GokK9ZCGaaWnqAzd1ZcuGXDuemWeA8BerQsfQw_IQm-aUKancldedHSGrOjVWgozVL97MH966j3i9CJc3k9jS9xDuE0owoWVZa7SxTmhl1PDetmzLnYIIIt-peJtNYGdpd-FcYxIFycQNRUoFEr77h4GBTLbC-vqbQHJC1vW4O2LEKhnhOAVlGyDYkNbA4DSL-LMwKxenQXRARsKSIMn7z-ZIqTE-VCNj9vbtgR\",\n\n tag: \"uYeo7IsZjN7AnvBjUZE5lNryNENbf6_zew_VC-d4b3U\",\n\n },\n\n protected: ProtectedHeader {\n\n typ: Some(\"application/didcomm-encrypted+json\"),\n\n alg: jwe::envelope::Algorithm::Ecdh1puA256kw,\n\n enc: EncAlgorithm::A256cbcHs512,\n\n skid: Some(\"did:example:alice#key-x25519-1\"),\n\n apu: Some(\"ZGlkOmV4YW1wbGU6YWxpY2Uja2V5LXgyNTUxOS0x\"),\n\n apv: \"NcsuAnrRfPK69A-rkZ0L9XWUG4jMvNC3Zg74BPz53PA\",\n\n epk: json!({\n", "file_path": "src/jwe/parse.rs", "rank": 88, "score": 11.523303285501932 }, { "content": " // Message payload\n\n let payload = \"Hello World!\";\n\n\n\n // Produce signed message\n\n\n\n let msg = jws::sign(\n\n payload.as_bytes(),\n\n (alice_kid, &alice_key),\n\n Algorithm::EdDSA,\n\n )\n\n .expect(\"unable sign\");\n\n\n\n // Parse message\n\n\n\n let mut buf = vec![];\n\n let msg = jws::parse(&msg, &mut buf).expect(\"Unable parse\");\n\n\n\n // Verify signature\n\n\n\n let valid = msg\n\n .verify((alice_kid, &alice_pkey))\n\n .expect(\"Unable verify.\");\n\n\n\n assert!(valid);\n\n }\n\n}\n", "file_path": "src/jws/mod.rs", "rank": 89, "score": 11.478798284422023 }, { "content": " BOB_MSG_ED25519,\n\n );\n\n\n\n _verify_works_different_key::<P256KeyPair>(ALICE_KID_P256, ALICE_PKEY_P256, BOB_MSG_P256);\n\n\n\n _verify_works_different_key::<K256KeyPair>(ALICE_KID_K256, ALICE_PKEY_K256, BOB_MSG_K256);\n\n\n\n fn _verify_works_different_key<K: FromJwk + KeySigVerify>(kid: &str, key: &str, msg: &str) {\n\n let res = _verify::<K>(kid, key, msg);\n\n let res = res.expect(\"res is err\");\n\n assert_eq!(res, false);\n\n }\n\n }\n\n\n\n #[test]\n\n fn verify_works_changed_payload() {\n\n _verify_works_changed_payload::<Ed25519KeyPair>(\n\n ALICE_KID_ED25519,\n\n ALICE_PKEY_ED25519,\n\n ALICE_MSG_ED25519_CHANGED_PAYLOAD,\n", "file_path": "src/jws/verify.rs", "rank": 90, "score": 11.431345525948931 }, { "content": " /// - `InvalidState` Indicates library error.\n\n /// - `IOError` IO error during DID or secrets resolving\n\n /// TODO: verify and update errors list\n\n pub async fn pack_encrypted<'dr, 'sr>(\n\n &self,\n\n _to: &str,\n\n _from: Option<&str>,\n\n _from_signed: Option<&str>,\n\n _did_resolver: &'dr (dyn DIDResolver + 'dr),\n\n _secrets_resolver: &'sr (dyn SecretsResolver + 'sr),\n\n _options: &PackEncryptedOptions,\n\n ) -> Result<(String, PackEncryptedMetadata)> {\n\n todo!(\"Implement me.\");\n\n }\n\n}\n\n\n\n/// Allow fine configuration of packing process.\n\npub struct PackEncryptedOptions {\n\n /// If `true` and message is authenticated than information about sender will be protected from mediators, but\n\n /// additional re-encryption will be required. For anonymous messages this property will be ignored.\n", "file_path": "src/pack_encrypted.rs", "rank": 91, "score": 11.341695240835685 }, { "content": " encrypted_key: \"TEWlqlq-ao7Lbynf0oZYhxs7ZB39SUWBCK4qjqQqfeItfwmNyDm73A\",\n\n },\n\n ],\n\n iv: \"ESpmcyGiZpRjc5urDela21TOOTW8Wqd1\",\n\n ciphertext: \"KWS7gJU7TbyJlcT9dPkCw-ohNigGaHSukR9MUqFM0THbCTCNkY-g5tahBFyszlKIKXs7qOtqzYyWbPou2q77XlAeYs93IhF6NvaIjyNqYklvj-OtJt9W2Pj5CLOMdsR0C30wchGoXd6wEQZY4ttbzpxYznqPmJ0b9KW6ZP-l4_DSRYe9B-1oSWMNmqMPwluKbtguC-riy356Xbu2C9ShfWmpmjz1HyJWQhZfczuwkWWlE63g26FMskIZZd_jGpEhPFHKUXCFwbuiw_Iy3R0BIzmXXdK_w7PZMMPbaxssl2UeJmLQgCAP8j8TukxV96EKa6rGgULvlo7qibjJqsS5j03bnbxkuxwbfyu3OxwgVzFWlyHbUH6p\",\n\n tag: \"6ylC_iAs4JvDQzXeY6MuYQ\",\n\n },\n\n protected: ProtectedHeader {\n\n typ: Some(\"application/didcomm-encrypted+json\"),\n\n alg: jwe::envelope::Algorithm::EcdhEsA256kw,\n\n enc: EncAlgorithm::Xc20P,\n\n skid: None,\n\n apu: None,\n\n apv: \"NcsuAnrRfPK69A-rkZ0L9XWUG4jMvNC3Zg74BPz53PA\",\n\n epk: json!({\n\n \"kty\":\"OKP\",\n\n \"crv\":\"X25519\",\n\n \"x\":\"JHjsmIRZAaB0zRG_wNXLV2rPggF00hdHbW5rj8g0I24\"\n\n }),\n\n },\n", "file_path": "src/jwe/parse.rs", "rank": 92, "score": 11.238163896893212 }, { "content": " ALICE_PKEY_K256,\n\n ALICE_MSG_ED25519_P256_K256,\n\n );\n\n\n\n fn _verify_works_multiple_signatures<K: FromJwk + KeySigVerify>(\n\n kid: &str,\n\n key: &str,\n\n msg: &str,\n\n ) {\n\n let res = _verify::<K>(kid, key, msg);\n\n let res = res.expect(\"res is err\");\n\n assert_eq!(res, true);\n\n }\n\n }\n\n\n\n #[test]\n\n fn verify_works_different_key() {\n\n _verify_works_different_key::<Ed25519KeyPair>(\n\n ALICE_KID_ED25519,\n\n ALICE_PKEY_ED25519,\n", "file_path": "src/jws/verify.rs", "rank": 93, "score": 11.103403190500511 }, { "content": "mod tests {\n\n use askar_crypto::{\n\n alg::{\n\n aes::{A256CbcHs512, A256Gcm, A256Kw, AesKey},\n\n chacha20::{Chacha20Key, XC20P},\n\n p256::P256KeyPair,\n\n x25519::X25519KeyPair,\n\n },\n\n encrypt::{KeyAeadInPlace, KeyAeadMeta},\n\n jwk::FromJwk,\n\n kdf::{ecdh_1pu::Ecdh1PU, ecdh_es::EcdhEs, FromKeyDerivation, KeyExchange},\n\n repr::{KeyGen, KeyPublicBytes, KeySecretBytes, ToPublicBytes, ToSecretBytes},\n\n };\n\n\n\n use crate::{\n\n error::ErrorKind,\n\n jwe::{\n\n self,\n\n envelope::{Algorithm, EncAlgorithm},\n\n test_support::*,\n", "file_path": "src/jwe/encrypt.rs", "rank": 94, "score": 11.091894543796888 }, { "content": " msg: &str,\n\n payload: &str,\n\n ) where\n\n CE: KeyAeadInPlace + KeySecretBytes,\n\n KDF: JoseKDF<KE, KW>,\n\n KE: KeyExchange + KeyGen + ToJwkValue + FromJwkValue,\n\n KW: KeyWrap + FromKeyDerivation,\n\n {\n\n let res = _decrypt::<CE, KDF, KE, KW>(sender, recepient, msg);\n\n let res = res.expect(\"res is err\");\n\n assert_eq!(res, payload.as_bytes());\n\n }\n\n }\n\n\n\n #[test]\n\n fn decrypt_works_authcrypt_different_skid() {\n\n let res = _decrypt::<\n\n AesKey<A256CbcHs512>,\n\n Ecdh1PU<'_, P256KeyPair>,\n\n P256KeyPair,\n", "file_path": "src/jwe/decrypt.rs", "rank": 95, "score": 11.087897873624815 }, { "content": " \"signatures\":[\n\n {\n\n \"protected\":\"eyJ0eXAiOiJhcHBsaWNhdGlvbi9kaWRjb21tLXNpZ25lZCtqc29uIiwiYWxnIjoiRVMyNTZLIn0\",\n\n \"signature\":\"EGjhIcts6tqiJgqtxaTiTY3EUvL-_rLjn9lxaZ4eRUwa1-CS1nknZoyJWbyY5NQnUafWh5nvCtQpdpMyzH3blw\",\n\n \"header\":{\n\n \"kid\":\"did:example:alice#key-3\"\n\n }\n\n }\n\n ]\n\n }\n\n \"#;\n\n\n\n const ALICE_MSG_K256_CHANGED_PAYLOAD: &str = r#\"\n\n {\n\n \"payload\":\"eyJpZCI6IjAyMzQ1Njc4OTAiLCJ0eXAiOiJhcHBsaWNhdGlvbi9kaWRjb21tLXBsYWluK2pzb24iLCJ0eXBlIjoiaHR0cDovL2V4YW1wbGUuY29tL3Byb3RvY29scy9sZXRzX2RvX2x1bmNoLzEuMC9wcm9wb3NhbCIsImZyb20iOiJkaWQ6ZXhhbXBsZTphbGljZSIsInRvIjpbImRpZDpleGFtcGxlOmJvYiJdLCJjcmVhdGVkX3RpbWUiOjE1MTYyNjkwMjIsImV4cGlyZXNfdGltZSI6MTUxNjM4NTkzMSwiYm9keSI6eyJtZXNzYWdlc3BlY2lmaWNhdHRyaWJ1dGUiOiJhbmQgaXRzIHZhbHVlIn19\",\n\n \"signatures\":[\n\n {\n\n \"protected\":\"eyJ0eXAiOiJhcHBsaWNhdGlvbi9kaWRjb21tLXNpZ25lZCtqc29uIiwiYWxnIjoiRVMyNTZLIn0\",\n\n \"signature\":\"EGjhIcts6tqiJgqtxaTiTY3EUvL-_rLjn9lxaZ4eRUwa1-CS1nknZoyJWbyY5NQnUafWh5nvCtQpdpMyzH3blw\",\n\n \"header\":{\n", "file_path": "src/jws/verify.rs", "rank": 96, "score": 10.893297916709681 }, { "content": " pub expect_protected_sender: bool,\n\n\n\n /// Whether the same DID must be used for encryption and signing. True by default.\n\n pub expect_signed_by_encrypter: bool,\n\n\n\n /// Whether the plaintext must be decryptable by all keys resolved by the secrets resolver. False by default.\n\n pub expect_decrypt_by_all_keys: bool,\n\n\n\n /// If `true` (default), and the packed message is a `Forward`\n\n /// wrapping a plaintext packed for the given recipient, then both Forward and packed plaintext are unpacked automatically,\n\n /// and the unpacked plaintext will be returned instead of unpacked Forward.\n\n pub unwrap_re_wrapping_forward: bool,\n\n}\n\n\n\nimpl Default for UnpackOptions {\n\n fn default() -> Self {\n\n UnpackOptions {\n\n expect_non_repudiation: false,\n\n expect_encrypted: false,\n\n expect_authenticated: false,\n", "file_path": "src/unpack.rs", "rank": 97, "score": 10.76180784126674 }, { "content": " use askar_crypto::{\n\n alg::{ed25519::Ed25519KeyPair, k256::K256KeyPair, p256::P256KeyPair},\n\n jwk::FromJwk,\n\n sign::KeySigVerify,\n\n };\n\n\n\n use crate::{\n\n error::{Error, ErrorKind},\n\n jws,\n\n };\n\n\n\n #[test]\n\n fn verify_works() {\n\n _verify_works::<Ed25519KeyPair>(ALICE_KID_ED25519, ALICE_PKEY_ED25519, ALICE_MSG_ED25519);\n\n _verify_works::<P256KeyPair>(ALICE_KID_P256, ALICE_PKEY_P256, ALICE_MSG_P256);\n\n _verify_works::<K256KeyPair>(ALICE_KID_K256, ALICE_PKEY_K256, ALICE_MSG_K256);\n\n\n\n fn _verify_works<K: FromJwk + KeySigVerify>(kid: &str, key: &str, msg: &str) {\n\n let res = _verify::<K>(kid, key, msg);\n\n let res = res.expect(\"res is err\");\n", "file_path": "src/jws/verify.rs", "rank": 98, "score": 10.748170384945519 }, { "content": "\n\n const ALICE_MSG_P256_UNDECODABLE_SIG: &str = r#\"\n\n {\n\n \"payload\":\"eyJpZCI6IjEyMzQ1Njc4OTAiLCJ0eXAiOiJhcHBsaWNhdGlvbi9kaWRjb21tLXBsYWluK2pzb24iLCJ0eXBlIjoiaHR0cDovL2V4YW1wbGUuY29tL3Byb3RvY29scy9sZXRzX2RvX2x1bmNoLzEuMC9wcm9wb3NhbCIsImZyb20iOiJkaWQ6ZXhhbXBsZTphbGljZSIsInRvIjpbImRpZDpleGFtcGxlOmJvYiJdLCJjcmVhdGVkX3RpbWUiOjE1MTYyNjkwMjIsImV4cGlyZXNfdGltZSI6MTUxNjM4NTkzMSwiYm9keSI6eyJtZXNzYWdlc3BlY2lmaWNhdHRyaWJ1dGUiOiJhbmQgaXRzIHZhbHVlIn19\",\n\n \"signatures\":[\n\n {\n\n \"protected\":\"eyJ0eXAiOiJhcHBsaWNhdGlvbi9kaWRjb21tLXNpZ25lZCtqc29uIiwiYWxnIjoiRVMyNTYifQ\",\n\n \"signature\":\"!gcW3lVifhyR48mLHbbpnGZQuziskR5-wXf6IoBlpa9SzERfSG9I7oQ9pssmHZwbvJvyMvxskpH5oudw1W3X5Qg\",\n\n \"header\":{\n\n \"kid\":\"did:example:alice#key-2\"\n\n }\n\n }\n\n ]\n\n }\n\n \"#;\n\n\n\n const ALICE_KID_K256: &str = \"did:example:alice#key-3\";\n\n\n\n const ALICE_KEY_K256: &str = r#\"\n\n {\n", "file_path": "src/jws/verify.rs", "rank": 99, "score": 10.38880827446028 } ]
Rust
src/backend/wgpu_impl/shape_vertex_layout.rs
eaglekindoms/LemoGUI
a1499502c2f87cd8919b4de0ac26363b1755bf4a
use wgpu::*; use crate::backend::wgpu_impl::*; use crate::device::GPUContext; use crate::graphic::base::*; use crate::graphic::style::{Bordering, Rounding, Style}; #[repr(C)] #[derive(Copy, Default, Clone, Debug, bytemuck::Pod, bytemuck::Zeroable)] pub struct CircleVertex { pub position: [f32; 2], pub color: [f32; 4], pub radius: f32, pub edge: u32, } impl CircleVertex { pub fn new(point: &Circle, edge: u32, color: RGBA) -> Self { log::info!("create the PolygonVertex obj"); Self { position: [point.position.x, point.position.y], color: color.to_vec(), radius: point.radius, edge, } } } const CIRCLE_ATTRS: [VertexAttribute; 4] = wgpu::vertex_attr_array![ 0 => Float32x2, 1 => Float32x4, 2 => Float32, 3 => Uint32]; impl VertexLayout for CircleVertex { fn set_vertex_desc<'a>() -> VertexBufferLayout<'a> { wgpu::VertexBufferLayout { array_stride: std::mem::size_of::<CircleVertex>() as wgpu::BufferAddress, step_mode: wgpu::VertexStepMode::Instance, attributes: &CIRCLE_ATTRS, } } fn get_shader(device: &Device) -> ShaderModule { device.create_shader_module(&wgpu::ShaderModuleDescriptor { label: Some("circle shader"), source: wgpu::ShaderSource::Wgsl(std::borrow::Cow::Borrowed( include_str!(concat!(env!("CARGO_MANIFEST_DIR"), "/shader_c/circle.wgsl")), )), }) } } #[derive(Debug, Default, Clone, Copy, bytemuck::Pod, bytemuck::Zeroable)] #[repr(C)] pub struct RectVertex { pub size: [f32; 2], pub position: [f32; 2], pub border_color: [f32; 4], pub rect_color: [f32; 4], pub is_round_or_border: [u32; 2], } const RECT_ATTRS: [VertexAttribute; 5] = wgpu::vertex_attr_array![ 0 => Float32x2, 1 => Float32x2, 2 => Float32x4, 3 => Float32x4, 4 => Uint32x2]; impl VertexLayout for RectVertex { fn set_vertex_desc<'a>() -> VertexBufferLayout<'a> { wgpu::VertexBufferLayout { array_stride: std::mem::size_of::<RectVertex>() as wgpu::BufferAddress, step_mode: wgpu::VertexStepMode::Instance, attributes: &RECT_ATTRS, } } fn get_shader(device: &Device) -> ShaderModule { device.create_shader_module(&wgpu::ShaderModuleDescriptor { label: Some("round_rect shader"), source: wgpu::ShaderSource::Wgsl(std::borrow::Cow::Borrowed( include_str!(concat!(env!("CARGO_MANIFEST_DIR"), "/shader_c/round_rect.wgsl")), )), }) } } impl RectVertex { pub fn new(rect: &Rectangle, style: Style) -> RectVertex { let mut border_color = [0.0, 0.0, 0.0, 0.0]; let rect_color = style.get_display_color().to_vec(); let is_round; let is_border; match style.get_round() { Rounding::Round => { is_round = 1 } Rounding::NoRound => { is_round = 0 } } match style.get_border() { Bordering::Border(color) => { is_border = 1; border_color = color.to_vec() } Bordering::NoBorder => { is_border = 0 } } RectVertex { size: [rect.width as f32, rect.height as f32], position: [rect.position.x, rect.position.y], border_color, rect_color, is_round_or_border: [is_round, is_border], } } } #[repr(C)] #[derive(Copy, Default, Clone, Debug, bytemuck::Pod, bytemuck::Zeroable)] pub struct PointVertex { pub position: [f32; 2], pub color: [f32; 4], } impl PointVertex { pub fn new(x: f32, y: f32, color: RGBA) -> Self { log::info!("create the PointVertex obj"); Self { position: [x, y], color: color.to_vec(), } } } const POINT_ATTRS: [VertexAttribute; 2] = wgpu::vertex_attr_array![ 0 => Float32x2, 1 => Float32x4 ]; impl VertexLayout for PointVertex { fn set_vertex_desc<'a>() -> VertexBufferLayout<'a> { wgpu::VertexBufferLayout { array_stride: std::mem::size_of::<PointVertex>() as wgpu::BufferAddress, step_mode: wgpu::VertexStepMode::Vertex, attributes: &POINT_ATTRS, } } fn get_shader(device: &Device) -> ShaderModule { device.create_shader_module(&wgpu::ShaderModuleDescriptor { label: Some("triangle shader"), source: wgpu::ShaderSource::Wgsl(std::borrow::Cow::Borrowed( include_str!(concat!(env!("CARGO_MANIFEST_DIR"), "/shader_c/triangle.wgsl")), )), }) } } impl PointVertex { pub fn from_shape_to_vector(gpu_context: &GPUContext, points: &Vec<Point<f32>>, color: RGBA) -> VertexBuffer { let vertex_nums = (points.len() - 3) * 2 + points.len(); let mut vect = Vec::with_capacity(points.len()); let mut indices = Vec::with_capacity(vertex_nums); for i in 0..points.len() { vect.push(PointVertex::new(points[i].x, points[i].y, color)); } let mut i = 1u16; while i < points.len() as u16 - 1 { indices.push(0); indices.push(i); i = i + 1; indices.push(i); } let point_buffer = VertexBuffer::create_vertex_buf::<PointVertex> (&gpu_context.device, vect, indices.as_slice()); point_buffer } }
use wgpu::*; use crate::backend::wgpu_impl::*; use crate::device::GPUContext; use crate::graphic::base::*; use crate::graphic::style::{Bordering, Rounding, Style}; #[repr(C)] #[derive(Copy, Default, Clone, Debug, bytemuck::Pod, bytemuck::Zeroable)] pub struct CircleVertex { pub position: [f32; 2], pub color: [f32; 4], pub radius: f32, pub edge: u32, } impl CircleVertex { pub fn new(point: &Circle, edge: u32, color: RGBA) -> Self { log::info!("create the PolygonVertex obj"); Self { position: [point.position.x, point.position.y], color: color.to_vec(), radius: point.radius, edge, } } } const CIRCLE_ATTRS: [VertexAttribute; 4] = wgpu::vertex_attr_array![ 0 => Float32x2, 1 => Float32x4, 2 => Float32, 3 => Uint32]; impl VertexLayout for CircleVertex { fn set_vertex_desc<'a>() -> VertexBufferLayout<'a> { wgpu::VertexBufferLayout { array_stride: std::mem::size_of::<CircleVertex>() as wgpu::BufferAddress, step_mode: wgpu::VertexStepMode::Instance, attributes: &CIRCLE_ATTRS, } } fn get_shader(device: &Device) -> ShaderModule { device.create_shader_module(&wgpu::ShaderModuleDescriptor { label: Some("circle shader"), source: wgpu::ShaderSource::Wgsl(std::borrow::Cow::Borrowed( include_str!(concat!(env!("CARGO_MANIFEST_DIR"), "/shader_c/circle.wgsl")), )), }) } } #[derive(Debug, Default, Clone, Copy, bytemuck::Pod, bytemuck::Zeroable)] #[repr(C)] pub struct RectV
::ShaderModuleDescriptor { label: Some("round_rect shader"), source: wgpu::ShaderSource::Wgsl(std::borrow::Cow::Borrowed( include_str!(concat!(env!("CARGO_MANIFEST_DIR"), "/shader_c/round_rect.wgsl")), )), }) } } impl RectVertex { pub fn new(rect: &Rectangle, style: Style) -> RectVertex { let mut border_color = [0.0, 0.0, 0.0, 0.0]; let rect_color = style.get_display_color().to_vec(); let is_round; let is_border; match style.get_round() { Rounding::Round => { is_round = 1 } Rounding::NoRound => { is_round = 0 } } match style.get_border() { Bordering::Border(color) => { is_border = 1; border_color = color.to_vec() } Bordering::NoBorder => { is_border = 0 } } RectVertex { size: [rect.width as f32, rect.height as f32], position: [rect.position.x, rect.position.y], border_color, rect_color, is_round_or_border: [is_round, is_border], } } } #[repr(C)] #[derive(Copy, Default, Clone, Debug, bytemuck::Pod, bytemuck::Zeroable)] pub struct PointVertex { pub position: [f32; 2], pub color: [f32; 4], } impl PointVertex { pub fn new(x: f32, y: f32, color: RGBA) -> Self { log::info!("create the PointVertex obj"); Self { position: [x, y], color: color.to_vec(), } } } const POINT_ATTRS: [VertexAttribute; 2] = wgpu::vertex_attr_array![ 0 => Float32x2, 1 => Float32x4 ]; impl VertexLayout for PointVertex { fn set_vertex_desc<'a>() -> VertexBufferLayout<'a> { wgpu::VertexBufferLayout { array_stride: std::mem::size_of::<PointVertex>() as wgpu::BufferAddress, step_mode: wgpu::VertexStepMode::Vertex, attributes: &POINT_ATTRS, } } fn get_shader(device: &Device) -> ShaderModule { device.create_shader_module(&wgpu::ShaderModuleDescriptor { label: Some("triangle shader"), source: wgpu::ShaderSource::Wgsl(std::borrow::Cow::Borrowed( include_str!(concat!(env!("CARGO_MANIFEST_DIR"), "/shader_c/triangle.wgsl")), )), }) } } impl PointVertex { pub fn from_shape_to_vector(gpu_context: &GPUContext, points: &Vec<Point<f32>>, color: RGBA) -> VertexBuffer { let vertex_nums = (points.len() - 3) * 2 + points.len(); let mut vect = Vec::with_capacity(points.len()); let mut indices = Vec::with_capacity(vertex_nums); for i in 0..points.len() { vect.push(PointVertex::new(points[i].x, points[i].y, color)); } let mut i = 1u16; while i < points.len() as u16 - 1 { indices.push(0); indices.push(i); i = i + 1; indices.push(i); } let point_buffer = VertexBuffer::create_vertex_buf::<PointVertex> (&gpu_context.device, vect, indices.as_slice()); point_buffer } }
ertex { pub size: [f32; 2], pub position: [f32; 2], pub border_color: [f32; 4], pub rect_color: [f32; 4], pub is_round_or_border: [u32; 2], } const RECT_ATTRS: [VertexAttribute; 5] = wgpu::vertex_attr_array![ 0 => Float32x2, 1 => Float32x2, 2 => Float32x4, 3 => Float32x4, 4 => Uint32x2]; impl VertexLayout for RectVertex { fn set_vertex_desc<'a>() -> VertexBufferLayout<'a> { wgpu::VertexBufferLayout { array_stride: std::mem::size_of::<RectVertex>() as wgpu::BufferAddress, step_mode: wgpu::VertexStepMode::Instance, attributes: &RECT_ATTRS, } } fn get_shader(device: &Device) -> ShaderModule { device.create_shader_module(&wgpu
random
[ { "content": "/// 描述纹理顶点数据布局,用于着色器识别数据\n\npub fn bind_group(device: &wgpu::Device,\n\n bind_group_layout: &wgpu::BindGroupLayout,\n\n target: &wgpu::TextureView,\n\n sampler: &wgpu::Sampler) -> wgpu::BindGroup\n\n{\n\n device.create_bind_group(\n\n &wgpu::BindGroupDescriptor {\n\n layout: &bind_group_layout,\n\n entries: &[\n\n wgpu::BindGroupEntry {\n\n binding: 0,\n\n resource: wgpu::BindingResource::TextureView(target),\n\n },\n\n wgpu::BindGroupEntry {\n\n binding: 1,\n\n resource: wgpu::BindingResource::Sampler(sampler),\n\n }\n\n ],\n\n label: None,\n\n }\n", "file_path": "src/backend/wgpu_impl/texture.rs", "rank": 0, "score": 149994.4165355319 }, { "content": "/// 定义纹理描述符\n\n/// 参数:纹理尺寸\n\n/// 输出配置:定义纹理尺寸,维度:2d,颜色格式:rgba,纹理来源:sampled,copy_dst\n\npub fn create_2d_texture(device: &wgpu::Device, texture_size: wgpu::Extent3d,\n\n texture_format: wgpu::TextureFormat) -> wgpu::Texture {\n\n device.create_texture(&wgpu::TextureDescriptor {\n\n label: None,\n\n size: texture_size,\n\n mip_level_count: 1,\n\n sample_count: 1,\n\n dimension: wgpu::TextureDimension::D2,\n\n format: texture_format,\n\n usage: wgpu::TextureUsages::TEXTURE_BINDING | wgpu::TextureUsages::COPY_DST,\n\n })\n\n}\n\n\n", "file_path": "src/backend/wgpu_impl/texture.rs", "rank": 1, "score": 140483.60180329217 }, { "content": "pub fn writer_data_to_texture(queue: &wgpu::Queue,\n\n texture: &wgpu::Texture,\n\n image_layout: wgpu::ImageDataLayout,\n\n size: wgpu::Extent3d,\n\n raw_data: ImageRaw) -> wgpu::TextureView\n\n{\n\n queue.write_texture(\n\n texture.as_image_copy(),\n\n raw_data.data.as_slice(),\n\n image_layout,\n\n size,\n\n );\n\n return texture.create_view(&wgpu::TextureViewDescriptor::default());\n\n}\n\n\n", "file_path": "src/backend/wgpu_impl/texture.rs", "rank": 2, "score": 119008.2874449825 }, { "content": "fn orthographic_projection(w: f32, h: f32) -> [[f32; 4]; 4] {\n\n [\n\n [2.0 / w, 0.0, 0.0, 0.0],\n\n [0.0, 2.0 / h, 0.0, 0.0],\n\n [0.0, 0.0, 1.0, 0.0],\n\n [-1.0, -1.0, 0.0, 1.0],\n\n ]\n\n}", "file_path": "example/proto/test_algo.rs", "rank": 3, "score": 103418.11212306579 }, { "content": "/// wgpu图形顶点布局trait\n\n/// 作用:定义顶点布局接口\n\npub trait VertexLayout: Sized {\n\n /// 设置图形顶点缓存布局\n\n fn set_vertex_desc<'a>() -> wgpu::VertexBufferLayout<'a>;\n\n /// 设置图元渲染器\n\n fn get_shader(device: &Device) -> ShaderModule;\n\n /// 设置渲染管线布局\n\n fn set_pipeline_layout(device: &Device) -> PipelineLayout {\n\n let render_pipeline_layout = device.create_pipeline_layout(&wgpu::PipelineLayoutDescriptor {\n\n label: Some(\"Render Pipeline Layout\"),\n\n bind_group_layouts: &[],\n\n push_constant_ranges: &[],\n\n });\n\n return render_pipeline_layout;\n\n }\n\n /// 创建渲染管线\n\n fn create_render_pipeline(device: &Device,\n\n fill_topology: PrimitiveTopology,\n\n ) -> RenderPipeline {\n\n let shader = Self::get_shader(device);\n\n let render_pipeline = device\n", "file_path": "src/backend/wgpu_impl/vertex_buffer_layout.rs", "rank": 4, "score": 88249.00789836828 }, { "content": "/// 创建渲染中间变量\n\nfn create_render_pass<'a>(encoder: &'a mut wgpu::CommandEncoder, target: &'a wgpu::TextureView) -> wgpu::RenderPass<'a> {\n\n let render_pass = encoder.begin_render_pass(&wgpu::RenderPassDescriptor {\n\n label: None,\n\n color_attachments: &[wgpu::RenderPassColorAttachment {\n\n view: target,\n\n resolve_target: None,\n\n ops: wgpu::Operations {\n\n load: wgpu::LoadOp::Load,\n\n store: true,\n\n },\n\n }],\n\n depth_stencil_attachment: None,\n\n });\n\n render_pass\n\n}", "file_path": "src/backend/wgpu_impl/vertex_buffer.rs", "rank": 5, "score": 80307.74412560085 }, { "content": "pub fn indices() {\n\n let mut ind = Vec::new();\n\n let lens = 3;\n\n let mut i = 1;\n\n while i < lens - 1 {\n\n ind.push(0);\n\n ind.push(i);\n\n i = i + 1;\n\n ind.push(i);\n\n }\n\n println!(\"hello{:?}\", ind);\n\n}\n\n\n", "file_path": "example/proto/test_closure.rs", "rank": 6, "score": 78327.64560999617 }, { "content": "struct ShaderData {\n\n src: String,\n\n src_path: PathBuf,\n\n spv_path: PathBuf,\n\n kind: shaderc::ShaderKind,\n\n}\n\n\n\nimpl ShaderData {\n\n pub fn load(src_path: PathBuf) -> Result<Self> {\n\n let extension = src_path\n\n .extension()\n\n .context(\"File has no extension\")?\n\n .to_str()\n\n .context(\"Extension cannot be converted to &str\")?;\n\n let kind = match extension {\n\n \"vert\" => shaderc::ShaderKind::Vertex,\n\n \"frag\" => shaderc::ShaderKind::Fragment,\n\n \"comp\" => shaderc::ShaderKind::Compute,\n\n _ => bail!(\"Unsupported shader: {}\", src_path.display()),\n\n };\n", "file_path": "build.rs", "rank": 7, "score": 77678.5309955573 }, { "content": "pub fn closure3() -> Box<dyn Fn(i32) -> i32>\n\n{\n\n let num = 12;\n\n Box::new(move |x| x + num)\n\n}", "file_path": "example/proto/test_closure.rs", "rank": 8, "score": 72208.00927268967 }, { "content": "fn blank_character(scale: u32) -> Character {\n\n Character {\n\n character: ' ',\n\n scale,\n\n width: scale / 2,\n\n height: scale,\n\n bearing_x: 0,\n\n bearing_y: 0,\n\n advance: scale / 2,\n\n bitmap: vec![0; (scale * scale / 2) as usize],\n\n texture: None,\n\n }\n\n}\n\n\n\n/// save characters glyph map\n\n#[derive(Debug)]\n\npub struct GCharMap {\n\n pub scale: f32,\n\n pub scaled_font: PxScaleFont<FontVec>,\n\n pub map: HashMap<char, Character>,\n", "file_path": "src/graphic/base/font.rs", "rank": 9, "score": 70440.02708476238 }, { "content": "pub fn closure1<T>(x: T, num: &dyn Fn(T) -> T) {\n\n num(x);\n\n}\n\n\n", "file_path": "example/proto/test_closure.rs", "rank": 10, "score": 65835.52408398163 }, { "content": "pub fn closure<F>(num: F)\n\n where F: Fn(i32) -> i32 {\n\n let x = num(12);\n\n println!(\"{:?}\", x);\n\n}\n\n\n", "file_path": "example/proto/test_closure.rs", "rank": 11, "score": 65390.266622717274 }, { "content": "pub fn num<T>(x: T) -> T\n\n where T: Debug\n\n{\n\n println!(\"{:?}\", x);\n\n x\n\n}\n\n\n", "file_path": "example/proto/test_closure.rs", "rank": 12, "score": 63730.537041306925 }, { "content": "pub fn closure2<T>(x: T, num: Box<dyn Fn(T) -> T>)\n\n{\n\n num(x);\n\n}\n\n\n", "file_path": "example/proto/test_closure.rs", "rank": 13, "score": 63592.73939404139 }, { "content": "/// 加载icon\n\npub fn load_icon(path: &Path) -> Option<Icon> {\n\n let (icon_rgba, icon_width, icon_height) = {\n\n let image = image::open(path)\n\n .expect(\"Failed to open icon path\")\n\n .into_rgba8();\n\n let (width, height) = image.dimensions();\n\n let rgba = image.into_raw();\n\n (rgba, width, height)\n\n };\n\n Some(Icon::from_rgba(icon_rgba, icon_width, icon_height).expect(\"Failed to open icon\"))\n\n}\n\n\n\n\n\npub struct Setting {\n\n pub title: String,\n\n pub icon_path: Option<String>,\n\n pub font_path: String,\n\n pub size: Point<f32>,\n\n}\n\n\n\nimpl Default for Setting {\n\n fn default() -> Self {\n\n Setting {\n\n title: \"untitled\".to_string(),\n\n icon_path: None,\n\n font_path: concat!(env!(\"CARGO_MANIFEST_DIR\"), \"/res/SourceHanSansCN-Regular.otf\").into(),\n\n size: Point::new(40., 40.),\n\n }\n\n }\n\n}", "file_path": "src/widget/instance.rs", "rank": 14, "score": 62074.46661995664 }, { "content": "/// 渲染容器trait\n\n/// 在事件循环时会调用实现该trait的对象\n\n/// 作用:定义渲染所需的公共接口\n\npub trait Container<M>: Sized {\n\n /// 键鼠输入事件响应\n\n fn update(&mut self, event_context: &mut EventContext<'_, M>) -> bool;\n\n /// 容器渲染\n\n fn render(&mut self, paint_brush: &mut dyn PaintBrush);\n\n}\n\n\n\n\n", "file_path": "src/device/container.rs", "rank": 15, "score": 59120.45628925925 }, { "content": "use std::fmt::Debug;\n\n\n\nuse winit::window::Window;\n\n\n\nuse crate::backend::wgpu_impl::*;\n\nuse crate::device::Container;\n\nuse crate::graphic::base::*;\n\nuse crate::graphic::render_api::PaintBrush;\n\n\n\n/// 图形渲染上下文结构体\n\n/// 作用:封装wgpu渲染所需的结构体\n\n#[derive(Debug)]\n\npub struct GPUContext {\n\n /// 渲染面板\n\n pub surface: wgpu::Surface,\n\n /// 图形设备\n\n pub device: wgpu::Device,\n\n /// 渲染命令队列\n\n pub queue: wgpu::Queue,\n\n /// 交换缓冲区描述符\n", "file_path": "src/device/wgpu_context.rs", "rank": 16, "score": 52174.98300843803 }, { "content": "\n\n let format = surface\n\n .get_preferred_format(&adapter)\n\n .expect(\"Get preferred format\");\n\n\n\n let (device, queue) = adapter\n\n .request_device(\n\n &wgpu::DeviceDescriptor {\n\n label: None,\n\n features: wgpu::Features::empty(),\n\n limits: wgpu::Limits::downlevel_defaults().using_resolution(adapter.limits()),\n\n },\n\n None, // Trace path\n\n )\n\n .await\n\n .unwrap();\n\n // : wgpu::TextureFormat::Bgra8UnormSrgb\n\n let sc_desc = wgpu::SurfaceConfiguration {\n\n usage: wgpu::TextureUsages::RENDER_ATTACHMENT,\n\n format,\n", "file_path": "src/device/wgpu_context.rs", "rank": 17, "score": 52169.59155120518 }, { "content": " width: size.width,\n\n height: size.height,\n\n present_mode: wgpu::PresentMode::Fifo,\n\n };\n\n let glob_pipeline = PipelineState::default(&device);\n\n\n\n surface.configure(&device, &sc_desc);\n\n GPUContext {\n\n surface,\n\n device,\n\n queue,\n\n sc_desc,\n\n glob_pipeline,\n\n }\n\n }\n\n // 更新交换缓冲区\n\n pub fn update_surface_configure<P: Into<Point<u32>>>(&mut self, size: P) {\n\n let size = size.into();\n\n self.sc_desc.width = size.x;\n\n self.sc_desc.height = size.y;\n", "file_path": "src/device/wgpu_context.rs", "rank": 18, "score": 52166.10574885206 }, { "content": " self.surface.configure(&self.device, &self.sc_desc);\n\n }\n\n\n\n pub fn get_surface_size(&self) -> Point<u32> {\n\n Point::new(self.sc_desc.width, self.sc_desc.height)\n\n }\n\n\n\n /// 显示图形内容\n\n pub fn present<C, M>(&mut self,\n\n container: &mut C)\n\n where C: Container<M> + 'static, M: 'static + Debug\n\n {\n\n match self.surface.get_current_texture() {\n\n Err(error) => {\n\n log::error!(\"{}\", error);\n\n }\n\n Ok(target_view) => {\n\n let mut utils\n\n = RenderUtil::new(&target_view, self);\n\n utils.clear_frame(BACKGROUND_COLOR);\n\n container.render(&mut utils);\n\n utils.context.queue.submit(Some(utils.encoder.finish()));\n\n target_view.present();\n\n }\n\n }\n\n }\n\n}", "file_path": "src/device/wgpu_context.rs", "rank": 19, "score": 52165.783098249056 }, { "content": " sc_desc: wgpu::SurfaceConfiguration,\n\n /// 渲染管道\n\n pub glob_pipeline: PipelineState,\n\n}\n\n\n\nimpl GPUContext {\n\n pub async fn new(window: &Window) -> GPUContext {\n\n log::info!(\"Initializing the surface...\");\n\n let instance = wgpu::Instance::new(wgpu::Backends::all());\n\n let size = window.inner_size();\n\n\n\n let surface = unsafe { instance.create_surface(window) };\n\n let adapter = instance\n\n .request_adapter(&wgpu::RequestAdapterOptions {\n\n power_preference: wgpu::PowerPreference::HighPerformance,\n\n force_fallback_adapter: false,\n\n compatible_surface: Some(&surface),\n\n })\n\n .await\n\n .expect(\"Request adapter\");\n", "file_path": "src/device/wgpu_context.rs", "rank": 20, "score": 52164.94526073725 }, { "content": "use std::num::NonZeroU32;\n\n\n\nuse wgpu::TextureFormat;\n\n\n\nuse crate::graphic::base::*;\n\n\n\n#[derive(Debug)]\n\npub struct TextureBufferData {\n\n pub width: u32,\n\n pub height: u32,\n\n pub uniform: wgpu::BindGroup,\n\n}\n\n\n\n#[derive(Debug)]\n\npub struct GTexture {\n\n pub texture: wgpu::Texture,\n\n pub sampler: wgpu::Sampler,\n\n pub bind_group_layout: wgpu::BindGroupLayout,\n\n pub texture_format: wgpu::TextureFormat,\n\n pub image_layout: wgpu::ImageDataLayout,\n", "file_path": "src/backend/wgpu_impl/texture.rs", "rank": 21, "score": 48641.425316199515 }, { "content": " pub size: wgpu::Extent3d,\n\n}\n\n\n\nimpl GTexture {\n\n pub fn new(device: &wgpu::Device, data_size: Point<u32>,\n\n texture_format: wgpu::TextureFormat) -> Self {\n\n let size = wgpu::Extent3d {\n\n width: data_size.x,\n\n height: data_size.y,\n\n depth_or_array_layers: 1,\n\n };\n\n // 参数:纹理数据来源的尺寸\n\n // 用途:指定纹理数据的布局\n\n // 具体含义:偏移量,行数宽度,列数宽度\n\n // 注:图像纹理导入后会被转化为包含每个像素点rgba颜色值的一维数组\n\n // 因此行数宽度为图像宽度*4,列数宽度不变\n\n let image_width: u32;\n\n match texture_format {\n\n TextureFormat::R8Unorm => image_width = data_size.x,\n\n _ => image_width = data_size.x * 4\n", "file_path": "src/backend/wgpu_impl/texture.rs", "rank": 22, "score": 48641.148835668864 }, { "content": " lod_max_clamp: f32::MAX,\n\n compare: None,\n\n anisotropy_clamp: None,\n\n border_color: None,\n\n};\n\n\n\n/// 默认着色器绑定组描述符\n\n///\n\n/// 用途:设定片段着色器程序传入参数在数据中的位置\n\n/// 此配置为:指定纹理二维坐标,及默认采样器配置\n\npub const DEFAULT_BIND_GROUP_LAYOUT: &wgpu::BindGroupLayoutDescriptor =\n\n &wgpu::BindGroupLayoutDescriptor {\n\n entries: &[\n\n wgpu::BindGroupLayoutEntry {\n\n binding: 0,\n\n visibility: wgpu::ShaderStages::FRAGMENT,\n\n ty: wgpu::BindingType::Texture {\n\n sample_type: wgpu::TextureSampleType::Float { filterable: true },\n\n view_dimension: wgpu::TextureViewDimension::D2,\n\n multisampled: false,\n", "file_path": "src/backend/wgpu_impl/texture.rs", "rank": 23, "score": 48637.83967132383 }, { "content": " }\n\n let image_layout = wgpu::ImageDataLayout {\n\n offset: 0,\n\n bytes_per_row: NonZeroU32::new(image_width),\n\n rows_per_image: NonZeroU32::new(data_size.y),\n\n };\n\n\n\n let texture = create_2d_texture(device, size, texture_format);\n\n let sampler = device.create_sampler(DEFAULT_TEXTURE_SAMPLER);\n\n let layout = device.create_bind_group_layout(DEFAULT_BIND_GROUP_LAYOUT);\n\n Self {\n\n texture,\n\n sampler,\n\n bind_group_layout: layout,\n\n texture_format,\n\n image_layout,\n\n size,\n\n }\n\n }\n\n\n", "file_path": "src/backend/wgpu_impl/texture.rs", "rank": 24, "score": 48637.33862737472 }, { "content": " pub fn update_size(&mut self, device: &wgpu::Device, size: Point<u32>) {\n\n self.size.width = size.x;\n\n self.size.height = size.y;\n\n self.texture = create_2d_texture(device, self.size, self.texture_format);\n\n match self.texture_format {\n\n TextureFormat::R8Unorm => self.image_layout.bytes_per_row = NonZeroU32::new(size.x),\n\n _ => self.image_layout.bytes_per_row = NonZeroU32::new(size.x * 4),\n\n }\n\n self.image_layout.rows_per_image = NonZeroU32::new(size.y);\n\n }\n\n\n\n pub fn create_bind_group(&mut self, device: &wgpu::Device,\n\n queue: &wgpu::Queue, raw_data: ImageRaw) -> TextureBufferData {\n\n self.update_size(device, Point::new(raw_data.width, raw_data.height));\n\n let width = raw_data.width;\n\n let height = raw_data.height;\n\n let view = writer_data_to_texture(queue,\n\n &self.texture, self.image_layout, self.size, raw_data);\n\n let uniform = bind_group(device, &self.bind_group_layout, &view, &self.sampler);\n\n TextureBufferData {\n", "file_path": "src/backend/wgpu_impl/texture.rs", "rank": 25, "score": 48635.78081846121 }, { "content": " )\n\n}\n\n\n\n/// 默认采样器描述符\n\n///\n\n/// 用途:配置纹理采样方式(环绕、过滤,多级渐远纹理过滤)\n\n/// 此配置为:环绕=ClampToEdge纹理被约束到0-1之间,造成拉伸效果(大图缩小,小图边缘重复填充)\n\n/// 过滤:纹理被缩小的时候使用邻近过滤Nearest,被放大时使用线性过滤Linear\n\n/// 多级渐远纹理过滤选项Nearest,多级渐远纹理主要是使用在纹理被缩小的情况下的:纹理放大不会使用多级渐远纹理\n\n/// GL_NEAREST产生颗粒状的图案,GL_LINEAR产生更平滑的图案\n\n/// 参考文档:[\"https://learnopengl-cn.github.io/01%20Getting%20started/06%20Textures/\"]\n\npub const DEFAULT_TEXTURE_SAMPLER: &wgpu::SamplerDescriptor = &wgpu::SamplerDescriptor {\n\n label: None,\n\n address_mode_u: wgpu::AddressMode::ClampToEdge,\n\n address_mode_v: wgpu::AddressMode::ClampToEdge,\n\n address_mode_w: wgpu::AddressMode::ClampToEdge,\n\n mag_filter: wgpu::FilterMode::Linear,\n\n min_filter: wgpu::FilterMode::Nearest,\n\n mipmap_filter: wgpu::FilterMode::Nearest,\n\n lod_min_clamp: 0.0,\n", "file_path": "src/backend/wgpu_impl/texture.rs", "rank": 26, "score": 48635.6113113796 }, { "content": "pub use pipeline_state::*;\n\npub use render_utils::*;\n\npub use shape_transfer::*;\n\npub use shape_vertex_layout::*;\n\npub use texture::*;\n\npub use texture_vertex_layout::*;\n\npub use vertex_buffer::*;\n\npub use vertex_buffer_layout::*;\n\n\n\n/// 定义图形顶点缓冲布局\n\nmod shape_vertex_layout;\n\n/// 图形转换为wgpu顶点缓冲\n\nmod shape_transfer;\n\n/// 定义纹理缓冲布局\n\nmod texture_vertex_layout;\n\n/// 定义纹理\n\nmod texture;\n\n/// 定义顶点缓冲布局\n\nmod vertex_buffer_layout;\n\n/// 定义顶点缓冲\n\nmod vertex_buffer;\n\n/// 封装简单渲染方法\n\nmod render_utils;\n\n/// 定义渲染管道\n\nmod pipeline_state;\n\n\n", "file_path": "src/backend/wgpu_impl/mod.rs", "rank": 27, "score": 48635.172541657135 }, { "content": " },\n\n count: None,\n\n },\n\n wgpu::BindGroupLayoutEntry {\n\n binding: 1,\n\n visibility: wgpu::ShaderStages::FRAGMENT,\n\n ty: wgpu::BindingType::Sampler(wgpu::SamplerBindingType::Filtering),\n\n count: None,\n\n },\n\n ],\n\n label: Some(\"default_bind_group_layout\"),\n\n };", "file_path": "src/backend/wgpu_impl/texture.rs", "rank": 28, "score": 48634.8648112419 }, { "content": " width,\n\n height,\n\n uniform,\n\n }\n\n }\n\n}\n\n\n\n/// 定义纹理描述符\n\n/// 参数:纹理尺寸\n\n/// 输出配置:定义纹理尺寸,维度:2d,颜色格式:rgba,纹理来源:sampled,copy_dst\n", "file_path": "src/backend/wgpu_impl/texture.rs", "rank": 29, "score": 48632.281731122785 }, { "content": "struct Counter {\n\n value: i32,\n\n text: String,\n\n}\n\n\n\nimpl Instance for Counter {\n\n type M = Ms;\n\n\n\n fn new() -> Self {\n\n Counter {\n\n value: 0,\n\n text: \"文本测试\".to_string(),\n\n }\n\n }\n\n\n\n fn layout(&self) -> Panel<Ms> {\n\n // 自定义设置\n\n let rect = Rectangle::new(100.0, 100.0, 170, 40);\n\n let style = Style::default()\n\n .border(RGBA(0.2, 0.2, 0.2, 0.5))\n", "file_path": "example/show_button.rs", "rank": 30, "score": 47376.03298278203 }, { "content": "struct Board;\n\n\n\nimpl Instance for Board {\n\n type M = ();\n\n\n\n fn new() -> Self {\n\n Self\n\n }\n\n\n\n fn layout(&self) -> Panel<()> {\n\n // 自定义设置\n\n let mut shapes: Vec<Box<dyn ShapeGraph>> = Vec::with_capacity(10);\n\n let rect = Rectangle::new(21.0, 31.0, 221, 111);\n\n let rect2 = Rectangle::new(21.0, 181.0, 221, 111);\n\n let circle = Circle::new(401., 160.2, 110.2);\n\n let triangle = RegularPolygon::new(\n\n Circle::new(331., 560.2, 100.2), 3);\n\n\n\n let polygon = RegularPolygon::new(\n\n Circle::new(131., 510.2, 110.2), 6);\n", "file_path": "example/show_shape.rs", "rank": 31, "score": 47376.03298278203 }, { "content": "use std::collections::HashMap;\n\n\n\nuse wgpu::*;\n\nuse wgpu::PrimitiveTopology::*;\n\n\n\nuse crate::backend::wgpu_impl::*;\n\nuse crate::graphic::base::ShapeType;\n\n\n\n/// 渲染管道状态元结构体\n\n#[derive(Debug)]\n\npub struct PipelineState {\n\n context: HashMap<ShapeType, RenderPipeline>,\n\n}\n\n\n\n/// 图元渲染器\n\n#[derive(Debug)]\n\npub struct Shader {\n\n pub vs_module: wgpu::ShaderModule,\n\n pub fs_module: wgpu::ShaderModule,\n\n}\n", "file_path": "src/backend/wgpu_impl/pipeline_state.rs", "rank": 32, "score": 46422.34444643191 }, { "content": "use std::borrow::BorrowMut;\n\n\n\nuse bytemuck::Pod;\n\nuse wgpu::{Device, RenderPipeline};\n\nuse wgpu::util::{BufferInitDescriptor, DeviceExt};\n\n\n\nuse crate::backend::wgpu_impl::*;\n\nuse crate::graphic::base::ShapeType;\n\n\n\n/// 渲染顶点缓冲结构体\n\n#[derive(Debug)]\n\npub struct VertexBuffer {\n\n pub vertex_buffer: wgpu::Buffer,\n\n pub index_buffer: wgpu::Buffer,\n\n pub num_indices: u32,\n\n // pub shape_type: ShapeType,\n\n}\n\n\n\npub const RECT_INDEX: &[u16; 4] = &[0, 2, 1, 3];\n\npub const RECT_LINE_INDEX: &[u16; 5] = &[0, 1, 3, 2, 0];\n", "file_path": "src/backend/wgpu_impl/vertex_buffer.rs", "rank": 33, "score": 46421.76920839929 }, { "content": "use wgpu::{CommandEncoder, SurfaceTexture, TextureView};\n\n\n\nuse crate::backend::wgpu_impl::*;\n\nuse crate::device::GPUContext;\n\nuse crate::graphic::base::*;\n\nuse crate::graphic::render_api::PaintBrush;\n\nuse crate::graphic::style::Style;\n\n\n\n/// 渲染工具封装结构体\n\n/// 作用:省事\n\n#[derive(Debug)]\n\npub struct RenderUtil<'a> {\n\n pub encoder: CommandEncoder,\n\n pub view: TextureView,\n\n pub context: &'a mut GPUContext,\n\n pub g_texture: GTexture,\n\n}\n\n\n\nimpl<'a> RenderUtil<'a> {\n\n pub fn new(target_view: &SurfaceTexture,\n", "file_path": "src/backend/wgpu_impl/render_utils.rs", "rank": 34, "score": 46421.380823059495 }, { "content": "use crate::backend::wgpu_impl::*;\n\nuse crate::device::*;\n\nuse crate::graphic::base::*;\n\nuse crate::graphic::style::Style;\n\n\n\nimpl ShapeGraph for Rectangle {\n\n fn to_buffer(&self, gpu_context: &GPUContext, style: Style) -> VertexBuffer {\n\n let rect_vertex = RectVertex::new(&self, style);\n\n let rect_vertex = VertexBuffer::create_vertex_buf::<RectVertex>\n\n (&gpu_context.device, vec![rect_vertex], RECT_INDEX);\n\n rect_vertex\n\n }\n\n\n\n fn get_type(&self) -> ShapeType {\n\n ShapeType::ROUND\n\n }\n\n}\n\n\n\nimpl ShapeGraph for Circle {\n\n fn to_buffer(&self, gpu_context: &GPUContext, style: Style) -> VertexBuffer {\n", "file_path": "src/backend/wgpu_impl/shape_transfer.rs", "rank": 35, "score": 46420.39165186002 }, { "content": " let circle_vertex\n\n = CircleVertex::new(&self, 0, style.get_display_color());\n\n let cricle_buffer = VertexBuffer::create_vertex_buf::<CircleVertex>\n\n (&gpu_context.device, vec![circle_vertex], RECT_INDEX);\n\n cricle_buffer\n\n }\n\n\n\n fn get_type(&self) -> ShapeType {\n\n ShapeType::Circle\n\n }\n\n}\n\n\n\nimpl ShapeGraph for RegularPolygon {\n\n fn to_buffer(&self, gpu_context: &GPUContext, style: Style) -> VertexBuffer {\n\n let circle_vertex\n\n = CircleVertex::new(&self.point, self.edge, style.get_display_color());\n\n let cricle_buffer = VertexBuffer::create_vertex_buf::<CircleVertex>\n\n (&gpu_context.device, vec![circle_vertex], RECT_INDEX);\n\n cricle_buffer\n\n }\n", "file_path": "src/backend/wgpu_impl/shape_transfer.rs", "rank": 36, "score": 46418.71192293594 }, { "content": "\n\nimpl PipelineState {\n\n pub fn default(device: &Device) -> Self {\n\n // 固定渲染管道配置:纹理管道,矩形管道,边框管道。\n\n // 全局设置\n\n log::info!(\"create the PipelineState obj\");\n\n let context = HashMap::with_capacity(4);\n\n let mut glob_pipeline = Self {\n\n context,\n\n };\n\n glob_pipeline.set_pipeline::<RectVertex>(device, TriangleStrip, ShapeType::ROUND);\n\n glob_pipeline.set_pipeline::<CircleVertex>(device, TriangleStrip, ShapeType::Circle);\n\n glob_pipeline.set_pipeline::<PointVertex>(device, TriangleList, ShapeType::POINT);\n\n glob_pipeline.set_pipeline::<PointVertex>(device, LineStrip, ShapeType::BORDER);\n\n glob_pipeline.set_pipeline::<TextureVertex>(device, TriangleStrip, ShapeType::TEXTURE);\n\n glob_pipeline\n\n }\n\n /// 创建渲染管道\n\n /// 参数:全局状态,着色器,渲染类型\n\n pub fn set_pipeline<V>(&mut self, device: &Device, fill_topology: PrimitiveTopology, shape_type: ShapeType)\n", "file_path": "src/backend/wgpu_impl/pipeline_state.rs", "rank": 37, "score": 46417.54811117938 }, { "content": "\n\nimpl<'a> VertexBuffer {\n\n pub fn create_vertex_buf<V>(device: &Device, vect: Vec<V>\n\n , indices: &'a [u16],\n\n // , shape_type: ShapeType,\n\n ) -> Self\n\n where V: Pod\n\n {\n\n log::info!(\"----create wgpu buffer----\");\n\n let vertex_buffer = device\n\n .create_buffer_init(&BufferInitDescriptor {\n\n label: None,\n\n contents: bytemuck::cast_slice(vect.as_slice()),\n\n usage: wgpu::BufferUsages::VERTEX,\n\n });\n\n let index_buffer = device.create_buffer_init(\n\n &BufferInitDescriptor {\n\n label: None,\n\n contents: bytemuck::cast_slice(indices),\n\n usage: wgpu::BufferUsages::INDEX,\n", "file_path": "src/backend/wgpu_impl/vertex_buffer.rs", "rank": 38, "score": 46417.20733233343 }, { "content": " fn clear_frame(&mut self, color: RGBA) {\n\n self.encoder.begin_render_pass(&wgpu::RenderPassDescriptor {\n\n label: None,\n\n color_attachments: &[wgpu::RenderPassColorAttachment {\n\n view: &self.view,\n\n resolve_target: None,\n\n ops: wgpu::Operations {\n\n load: wgpu::LoadOp::Clear(wgpu::Color {\n\n r: color.0 as f64,\n\n g: color.1 as f64,\n\n b: color.2 as f64,\n\n a: color.3 as f64,\n\n }),\n\n store: true,\n\n },\n\n }],\n\n depth_stencil_attachment: None,\n\n });\n\n }\n\n\n", "file_path": "src/backend/wgpu_impl/render_utils.rs", "rank": 39, "score": 46416.057130665824 }, { "content": " fn draw_shape(&mut self, shape: &Box<dyn ShapeGraph>, shape_style: Style) {\n\n let shape_buffer = shape.to_buffer(self.context, shape_style);\n\n shape_buffer.render(self, shape.get_type());\n\n }\n\n\n\n fn draw_text(&mut self, font_map: &mut GCharMap, text_rect: &Rectangle, text: &str, text_color: RGBA) {\n\n let mut x = text_rect.position.x + 8.;\n\n let scale = 10. / (font_map.scale / 2.5);\n\n for c in text.chars() {\n\n let c_font = font_map.character_texture(c, &mut self.g_texture,\n\n &self.context.device, &self.context.queue);\n\n let c_buffer = c_font.texture.as_ref().unwrap();\n\n let c_x = x;\n\n let c_y = text_rect.position.y;\n\n let scale_width = c_buffer.width as f32 * scale;\n\n let c_rect =\n\n Rectangle::new(c_x, c_y, scale_width as u32, c_buffer.height);\n\n x = x + scale_width;\n\n let c_vertex =\n\n TextureVertex::new(&self.context.device,\n\n &self.context.get_surface_size(), &c_rect, text_color);\n\n\n\n c_vertex.render_t(self, &c_buffer);\n\n }\n\n }\n\n\n\n fn draw_image(&mut self, image_rect: &Rectangle, image: ImageRaw) {}\n\n}", "file_path": "src/backend/wgpu_impl/render_utils.rs", "rank": 40, "score": 46415.87470306821 }, { "content": " gpu_context: &'a mut GPUContext) -> Self {\n\n let view = target_view\n\n .texture\n\n .create_view(&wgpu::TextureViewDescriptor::default());\n\n let encoder = gpu_context.device\n\n .create_command_encoder(&wgpu::CommandEncoderDescriptor {\n\n label: Some(\"Render Encoder\"),\n\n });\n\n let g_texture = GTexture::new(&gpu_context.device,\n\n Point::new(40, 40), wgpu::TextureFormat::R8Unorm);\n\n RenderUtil {\n\n encoder,\n\n view,\n\n context: gpu_context,\n\n g_texture,\n\n }\n\n }\n\n}\n\n\n\nimpl PaintBrush for RenderUtil<'_> {\n", "file_path": "src/backend/wgpu_impl/render_utils.rs", "rank": 41, "score": 46415.22352521727 }, { "content": "\n\n fn get_type(&self) -> ShapeType {\n\n ShapeType::Circle\n\n }\n\n}\n\n\n\nimpl ShapeGraph for Polygon {\n\n fn to_buffer(&self, gpu_context: &GPUContext, style: Style) -> VertexBuffer {\n\n PointVertex::from_shape_to_vector(gpu_context, &self.points, style.get_display_color())\n\n }\n\n\n\n fn get_type(&self) -> ShapeType {\n\n ShapeType::POINT\n\n }\n\n}", "file_path": "src/backend/wgpu_impl/shape_transfer.rs", "rank": 42, "score": 46414.42240869664 }, { "content": " });\n\n let num_indices = indices.len() as u32;\n\n Self {\n\n vertex_buffer,\n\n num_indices,\n\n index_buffer,\n\n // shape_type,\n\n }\n\n }\n\n\n\n pub fn render(&'a self, render_utils: &mut RenderUtil, shape_type: ShapeType) {\n\n let pipeline = render_utils.context.glob_pipeline.get_pipeline(shape_type).unwrap();\n\n let mut render_pass =\n\n create_render_pass(&mut render_utils.encoder, &render_utils.view);\n\n self.render_shape(render_pass.borrow_mut(), pipeline)\n\n }\n\n\n\n pub fn render_t(&'a self, render_utils: &mut RenderUtil,\n\n texture_state: &'a TextureBufferData) {\n\n let pipeline = render_utils.context.glob_pipeline.get_pipeline(ShapeType::TEXTURE).unwrap();\n", "file_path": "src/backend/wgpu_impl/vertex_buffer.rs", "rank": 43, "score": 46409.7984836819 }, { "content": " where V: VertexLayout {\n\n // 作用:绑定着色器,图形填充\n\n let render_pipeline = V::create_render_pipeline(device, fill_topology);\n\n if self.context.get(&shape_type).is_none() {\n\n self.context.insert(shape_type, render_pipeline);\n\n }\n\n }\n\n /// 获取渲染管线\n\n pub fn get_pipeline(&self, shape_type: ShapeType) -> Option<&RenderPipeline> {\n\n self.context.get(&shape_type)\n\n }\n\n}\n\n\n", "file_path": "src/backend/wgpu_impl/pipeline_state.rs", "rank": 44, "score": 46409.078403722684 }, { "content": " render_pass.set_index_buffer(self.index_buffer.slice(..), wgpu::IndexFormat::Uint16);\n\n render_pass.draw_indexed(0..self.num_indices, 0, 0..1);\n\n }\n\n\n\n pub fn render_g_texture(&'a self,\n\n render_pass: &mut wgpu::RenderPass<'a>,\n\n render_pipeline: &'a RenderPipeline,\n\n texture_buffer: &'a TextureBufferData)\n\n {\n\n render_pass.set_pipeline(&render_pipeline);\n\n render_pass.set_bind_group(0, &texture_buffer.uniform, &[]);\n\n render_pass.set_vertex_buffer(0, self.vertex_buffer.slice(..));\n\n render_pass.set_index_buffer(self.index_buffer.slice(..), wgpu::IndexFormat::Uint16);\n\n render_pass.draw_indexed(0..self.num_indices, 0, 0..1);\n\n }\n\n}\n\n\n\n/// 创建渲染中间变量\n", "file_path": "src/backend/wgpu_impl/vertex_buffer.rs", "rank": 45, "score": 46409.04726027987 }, { "content": " let mut render_pass =\n\n create_render_pass(&mut render_utils.encoder, &render_utils.view);\n\n self.render_texture(render_pass.borrow_mut(), texture_state, pipeline)\n\n }\n\n\n\n #[deprecated]\n\n fn render_shape(&'a self, render_pass: &mut wgpu::RenderPass<'a>,\n\n shape_pipeline: &'a RenderPipeline) {\n\n render_pass.set_pipeline(shape_pipeline);\n\n render_pass.set_vertex_buffer(0, self.vertex_buffer.slice(..));\n\n render_pass.set_index_buffer(self.index_buffer.slice(..), wgpu::IndexFormat::Uint16);\n\n render_pass.draw_indexed(0..self.num_indices, 0, 0..1);\n\n }\n\n\n\n fn render_texture(&'a self, render_pass: &mut wgpu::RenderPass<'a>,\n\n texture_state: &'a TextureBufferData,\n\n render_pipeline: &'a RenderPipeline) {\n\n render_pass.set_pipeline(&render_pipeline);\n\n render_pass.set_bind_group(0, &texture_state.uniform, &[]);\n\n render_pass.set_vertex_buffer(0, self.vertex_buffer.slice(..));\n", "file_path": "src/backend/wgpu_impl/vertex_buffer.rs", "rank": 46, "score": 46407.50136246759 }, { "content": "use wgpu::*;\n\n\n\nuse crate::backend::wgpu_impl::*;\n\nuse crate::graphic::base::{Point, Rectangle, RGBA};\n\n\n\n/// 2D纹理顶点数据布局结构体\n\n#[repr(C)]\n\n#[derive(Copy, Default, Clone, Debug, bytemuck::Pod, bytemuck::Zeroable)]\n\npub struct TextureVertex {\n\n pub position: [f32; 2],\n\n pub tex_coords: [f32; 2],\n\n pub color: [f32; 4],\n\n}\n\n\n\nconst TEXTURE_ATTRS: [VertexAttribute; 3] = wgpu::vertex_attr_array![\n\n 0 => Float32x2,\n\n 1 => Float32x2,\n\n 2 => Float32x4 ];\n\n\n\nimpl VertexLayout for TextureVertex {\n", "file_path": "src/backend/wgpu_impl/texture_vertex_layout.rs", "rank": 49, "score": 44406.82486864967 }, { "content": " );\n\n let render_pipeline_layout = device.create_pipeline_layout(&wgpu::PipelineLayoutDescriptor {\n\n label: Some(\"Render Pipeline Layout\"),\n\n bind_group_layouts: &[&texture_bind_group_layout],\n\n push_constant_ranges: &[],\n\n });\n\n return render_pipeline_layout;\n\n }\n\n}\n\n\n\nimpl TextureVertex {\n\n pub fn new(device: &Device, sc_desc: &Point<u32>, rect: &Rectangle, font_color: RGBA) -> VertexBuffer {\n\n let (t_x, t_y, t_w, t_h) =\n\n rect.get_coord(sc_desc.x, sc_desc.y);\n\n let color: [f32; 4] = font_color.to_vec();\n\n let vect: Vec<TextureVertex> = vec![\n\n TextureVertex { position: [t_x, t_y], tex_coords: [t_w, t_h], color }\n\n ];\n\n let vertex_buffer = VertexBuffer::create_vertex_buf::<TextureVertex>\n\n (device, vect, RECT_INDEX);\n\n vertex_buffer\n\n }\n\n}", "file_path": "src/backend/wgpu_impl/texture_vertex_layout.rs", "rank": 55, "score": 44393.61236373558 }, { "content": " fn set_vertex_desc<'a>() -> VertexBufferLayout<'a> {\n\n wgpu::VertexBufferLayout {\n\n array_stride: std::mem::size_of::<TextureVertex>() as wgpu::BufferAddress,\n\n step_mode: wgpu::VertexStepMode::Instance,\n\n attributes: &TEXTURE_ATTRS,\n\n }\n\n }\n\n\n\n fn get_shader(device: &Device) -> ShaderModule {\n\n device.create_shader_module(&wgpu::ShaderModuleDescriptor {\n\n label: Some(\"texture shader\"),\n\n source: wgpu::ShaderSource::Wgsl(std::borrow::Cow::Borrowed(\n\n include_str!(concat!(env!(\"CARGO_MANIFEST_DIR\"), \"/shader_c/image.wgsl\")),\n\n )),\n\n })\n\n }\n\n\n\n fn set_pipeline_layout(device: &Device) -> PipelineLayout {\n\n let texture_bind_group_layout = device.create_bind_group_layout(\n\n DEFAULT_BIND_GROUP_LAYOUT\n", "file_path": "src/backend/wgpu_impl/texture_vertex_layout.rs", "rank": 56, "score": 44393.56399852286 }, { "content": " .create_render_pipeline(&wgpu::RenderPipelineDescriptor {\n\n label: Some(\"Render Pipeline\"),\n\n layout: Some(&Self::set_pipeline_layout(device)),\n\n vertex: VertexState {\n\n module: &shader,\n\n entry_point: \"vs_main\",\n\n buffers: &[Self::set_vertex_desc()],\n\n },\n\n primitive: wgpu::PrimitiveState {\n\n topology: fill_topology,\n\n front_face: wgpu::FrontFace::Ccw,\n\n cull_mode: Some(wgpu::Face::Back),\n\n ..Default::default()\n\n },\n\n depth_stencil: None,\n\n multisample: wgpu::MultisampleState::default(),\n\n fragment: Some(wgpu::FragmentState {\n\n module: &shader,\n\n entry_point: \"fs_main\",\n\n targets: &[wgpu::ColorTargetState {\n", "file_path": "src/backend/wgpu_impl/vertex_buffer_layout.rs", "rank": 58, "score": 44391.562680090115 }, { "content": "use wgpu::*;\n\n\n\n/// wgpu图形顶点布局trait\n\n/// 作用:定义顶点布局接口\n", "file_path": "src/backend/wgpu_impl/vertex_buffer_layout.rs", "rank": 60, "score": 44384.427771058225 }, { "content": " format: wgpu::TextureFormat::Bgra8UnormSrgb,\n\n write_mask: wgpu::ColorWrites::ALL,\n\n blend: Some(wgpu::BlendState::ALPHA_BLENDING),\n\n }],\n\n }),\n\n multiview: None,\n\n });\n\n return render_pipeline;\n\n }\n\n}", "file_path": "src/backend/wgpu_impl/vertex_buffer_layout.rs", "rank": 61, "score": 44383.899031948255 }, { "content": "fn main() {\n\n SimpleLogger::new().with_level(log::LevelFilter::Info).init().unwrap();\n\n Board::run();\n\n}\n\n\n\n\n", "file_path": "example/show_shape.rs", "rank": 62, "score": 42749.24036783182 }, { "content": "fn main() {\n\n // SimpleLogger::new().with_level(log::LevelFilter::Info).init().unwrap();\n\n Counter::run();\n\n}\n\n\n", "file_path": "example/show_button.rs", "rank": 63, "score": 42749.24036783182 }, { "content": "/// 运行窗口实例\n\nfn run_instance<C, M>(window: DisplayWindow<'static, M>, container: C)\n\n where C: Container<M> + 'static, M: 'static + Debug {\n\n let (mut sender, receiver)\n\n = mpsc::unbounded();\n\n let mut instance_listener\n\n = Box::pin(event_listener(window.gpu_context,\n\n window.event_context,\n\n container,\n\n receiver));\n\n let mut context = task::Context::from_waker(task::noop_waker_ref());\n\n window.event_loop.run(move |event, _, control_flow| {\n\n if let ControlFlow::Exit = control_flow {\n\n return;\n\n }\n\n // 封装窗口尺寸变更事件\n\n let event = match event {\n\n Event::WindowEvent {\n\n event:\n\n WindowEvent::ScaleFactorChanged {\n\n new_inner_size,\n", "file_path": "src/device/display_window.rs", "rank": 64, "score": 42641.73568860417 }, { "content": "fn main() -> Result<()> {\n\n // Collect all shaders recursively within /src/\n\n let mut shader_paths = [\n\n glob(\"./shader_c/*.vert\")?,\n\n glob(\"./shader_c/*.frag\")?,\n\n ];\n\n\n\n // This could be parallelized\n\n let shaders = shader_paths\n\n .iter_mut()\n\n .flatten()\n\n .map(|glob_result| ShaderData::load(glob_result?))\n\n .collect::<Vec<Result<_>>>()\n\n .into_iter()\n\n .collect::<Result<Vec<_>>>()?;\n\n\n\n let mut compiler = shaderc::Compiler::new().context(\"Unable to create shader compiler\")?;\n\n\n\n // This can't be parallelized. The [shaderc::Compiler] is not\n\n // thread safe. Also, it creates a lot of resources. You could\n", "file_path": "build.rs", "rank": 65, "score": 42496.24266250534 }, { "content": "#[derive(Debug)]\n\nstruct State<M> {\n\n event: EventType,\n\n message: Option<M>,\n\n}\n\n\n", "file_path": "example/proto/test_alter_message.rs", "rank": 66, "score": 41702.664695448024 }, { "content": "fn main() {\n\n closure(|x| x + 2);\n\n closure1::<i32>(12, &num);\n\n closure2::<f32>(12., Box::new(num));\n\n let x = closure3()(2);\n\n println!(\"{:#?}\", x);\n\n\n\n let width: f32 = 400.;\n\n let height: f32 = 800.;\n\n let projection: Matrix4<f32> = orthographic_projection(width, height).into();\n\n let position: Vector4<f32> = Vector4::new(110.5, 110.5, 0.0, 0.0);\n\n println!(\"{:?}\", projection);\n\n let p = projection * position;\n\n println!(\"{:?}\", position);\n\n println!(\"{:?}\", p);\n\n}\n\n\n", "file_path": "example/proto/test_algo.rs", "rank": 67, "score": 41467.64876765972 }, { "content": "/// 实例 trait\n\n/// 用于定义具体应用\n\npub trait Instance {\n\n type M: 'static + Clone + PartialEq + Debug;\n\n /// 新建实例\n\n fn new() -> Self;\n\n /// 组件布局\n\n fn layout(&self) -> Panel<Self::M>;\n\n /// 状态更新\n\n fn update(&mut self, _broadcast: &Self::M) {}\n\n /// 窗体设置\n\n fn setting() -> Setting;\n\n /// 运行实例\n\n fn run() where Self: 'static + Sized {\n\n let setting = Self::setting();\n\n let mut builder = winit::window::WindowBuilder::new();\n\n let icon = if setting.icon_path.is_some() {\n\n load_icon(Path::new(setting.icon_path.unwrap().as_str()))\n\n } else {\n\n None\n\n };\n\n builder = builder.with_title(setting.title)\n\n .with_inner_size(winit::dpi::LogicalSize::new(setting.size.x, setting.size.y))\n\n .with_window_icon(icon);\n\n let window = DisplayWindow::new(builder);\n\n let mut frame = Frame::new(setting.font_path);\n\n let instance = Self::new();\n\n frame.add_instance(instance);\n\n window.start(frame)\n\n }\n\n}\n\n\n", "file_path": "src/widget/instance.rs", "rank": 68, "score": 40864.02917624405 }, { "content": "fn main() {\n\n use simple_logger::SimpleLogger;\n\n use winit::{\n\n event::{Event, WindowEvent},\n\n event_loop::{ControlFlow, EventLoop},\n\n window::WindowBuilder,\n\n };\n\n\n\n #[derive(Debug, Clone, Copy)]\n\n enum CustomEvent {\n\n Timer,\n\n }\n\n\n\n SimpleLogger::new().init().unwrap();\n\n let event_loop = EventLoop::<CustomEvent>::with_user_event();\n\n\n\n let _window = WindowBuilder::new()\n\n .with_title(\"A fantastic window!\")\n\n .build(&event_loop)\n\n .unwrap();\n", "file_path": "example/proto/test_alter_message.rs", "rank": 69, "score": 40303.15328323579 }, { "content": "/// 定义绘图接口,实现解耦\n\npub trait PaintBrush {\n\n /// 由指定颜色清空屏幕\n\n fn clear_frame(&mut self, color: RGBA);\n\n\n\n /// 绘制图形\n\n fn draw_shape(&mut self, shape: &Box<dyn ShapeGraph>, shape_style: Style);\n\n\n\n /// 绘制文本\n\n fn draw_text(&mut self, font_map: &mut GCharMap,\n\n text_rect: &Rectangle, text: &str, text_color: RGBA);\n\n\n\n /// 绘制图像\n\n fn draw_image(&mut self, image_rect: &Rectangle, image: ImageRaw);\n\n}\n", "file_path": "src/graphic/render_api.rs", "rank": 70, "score": 38627.685065318816 }, { "content": "/// 图形缓冲转换接口\n\npub trait ShapeGraph {\n\n /// 转换为顶点缓冲数据\n\n fn to_buffer(&self, gpu_context: &GPUContext, style: Style) -> VertexBuffer;\n\n /// 获取图形类型\n\n fn get_type(&self) -> ShapeType;\n\n}\n", "file_path": "src/graphic/base/shape.rs", "rank": 71, "score": 38627.685065318816 }, { "content": "/// 组件模型trait\n\n/// 作用:定义组件必须的公共方法接口\n\npub trait ComponentModel<M> {\n\n /// 组件绘制方法实现\n\n fn draw(&self, paint_brush: &mut dyn PaintBrush, font_map: &mut GCharMap);\n\n /// 键盘事件监听器\n\n fn key_listener(&mut self,\n\n _event_context: &EventContext<'_, M>,\n\n _virtual_keycode: Option<KeyCode>) -> bool {\n\n false\n\n }\n\n /// 鼠标点击事件监听器\n\n fn action_listener(&mut self,\n\n _event_context: &EventContext<'_, M>,\n\n _mouse: Mouse) -> bool\n\n { false }\n\n /// 鼠标悬停事件监听器\n\n fn hover_listener(&mut self,\n\n _event_context: &EventContext<'_, M>) -> bool\n\n { false }\n\n fn received_character(&mut self,\n\n _event_context: &EventContext<'_, M>, c: char) -> bool\n", "file_path": "src/widget/component.rs", "rank": 72, "score": 37182.47855344053 }, { "content": "pub use container::*;\n\npub use display_window::*;\n\npub use event_context::*;\n\npub use wgpu_context::*;\n\n\n\nmod display_window;\n\nmod container;\n\nmod wgpu_context;\n\nmod event_context;", "file_path": "src/device.rs", "rank": 73, "score": 29608.840988270447 }, { "content": "/// 字体样式枚举\n\n#[derive(Copy, Clone, Debug)]\n\npub enum FontStyle {\n\n // 无字体\n\n NoFont,\n\n // 字体颜色\n\n Font(RGBA),\n\n}\n\n\n\n/// 形状样式\n\n#[derive(Copy, Clone, Debug)]\n\npub struct ShapeStyle {\n\n /// 是否有边界\n\n border: Bordering,\n\n /// 是否圆角\n\n round: Rounding,\n\n /// 背景色\n\n back_color: RGBA,\n\n /// 悬浮色\n\n hover_color: RGBA,\n", "file_path": "src/graphic/style.rs", "rank": 74, "score": 28625.96733841963 }, { "content": "//\n\n// impl Bordering {\n\n// pub fn get_color(&self) -> RGBA {\n\n// match self {\n\n// Bordering::Border(color) => color.clone(),\n\n// Bordering::NoBorder => RGBA([0.0, 0.0, 0.0, 0.0])\n\n// }\n\n// }\n\n// }\n\n\n\nimpl Default for Rounding {\n\n fn default() -> Self {\n\n Rounding::NoRound\n\n }\n\n}", "file_path": "src/graphic/style.rs", "rank": 75, "score": 28624.36095664659 }, { "content": "use crate::graphic::base::*;\n\n\n\n/// 边框枚举\n\n#[derive(Copy, Clone, Debug)]\n\npub enum Bordering {\n\n /// 边框颜色\n\n Border(RGBA),\n\n /// 无边框\n\n NoBorder,\n\n}\n\n\n\n/// 圆角枚举\n\n#[derive(Copy, Clone, Debug)]\n\npub enum Rounding {\n\n /// 圆角宽度和颜色\n\n Round,\n\n /// 无圆角\n\n NoRound,\n\n}\n\n\n", "file_path": "src/graphic/style.rs", "rank": 76, "score": 28622.570450614523 }, { "content": " }\n\n pub fn no_round(&mut self) -> Self {\n\n self.shape_style.round = Rounding::NoRound;\n\n *self\n\n }\n\n\n\n pub fn font_color(&mut self, color: RGBA) -> Self {\n\n self.font_style = FontStyle::Font(color);\n\n *self\n\n }\n\n\n\n pub fn back_color(&mut self, color: RGBA) -> Self {\n\n self.shape_style.back_color = color;\n\n self.shape_style.display_color = color;\n\n *self\n\n }\n\n\n\n pub fn hover_color(&mut self, color: RGBA) -> Self {\n\n self.shape_style.hover_color = color;\n\n *self\n", "file_path": "src/graphic/style.rs", "rank": 77, "score": 28621.500417830845 }, { "content": " match self.font_style {\n\n FontStyle::NoFont => DEFAULT_FONT_COLOR,\n\n FontStyle::Font(color) => color\n\n }\n\n }\n\n\n\n pub fn get_hover_color(&self) -> RGBA {\n\n self.shape_style.hover_color\n\n }\n\n\n\n pub fn get_display_color(&self) -> RGBA {\n\n self.shape_style.display_color\n\n }\n\n}\n\n\n\nimpl Default for Bordering {\n\n fn default() -> Self {\n\n Bordering::NoBorder\n\n }\n\n}\n", "file_path": "src/graphic/style.rs", "rank": 78, "score": 28620.61068005386 }, { "content": " }\n\n\n\n pub fn display_color(&mut self, color: RGBA) -> Self {\n\n self.shape_style.display_color = color;\n\n *self\n\n }\n\n\n\n pub fn get_border(&self) -> &Bordering {\n\n &self.shape_style.border\n\n }\n\n\n\n pub fn get_round(&self) -> &Rounding {\n\n &self.shape_style.round\n\n }\n\n\n\n pub fn get_back_color(&self) -> RGBA {\n\n self.shape_style.back_color\n\n }\n\n\n\n pub fn get_font_color(&self) -> RGBA {\n", "file_path": "src/graphic/style.rs", "rank": 79, "score": 28620.181810636685 }, { "content": " // 默认背景显示颜色\n\n display_color: RGBA,\n\n}\n\n\n\n/// 样式结构体\n\n/// 作用:设置图形样式\n\n#[derive(Debug, Clone, Copy)]\n\npub struct Style {\n\n /// 文字样式\n\n font_style: FontStyle,\n\n /// 形状样式\n\n shape_style: ShapeStyle,\n\n}\n\n\n\nimpl Style {\n\n pub fn default() -> Style {\n\n Style {\n\n font_style: FontStyle::NoFont,\n\n shape_style: ShapeStyle {\n\n border: Bordering::Border(BLACK),\n", "file_path": "src/graphic/style.rs", "rank": 80, "score": 28620.0300160456 }, { "content": " round: Rounding::NoRound,\n\n back_color: LIGHT_WHITE,\n\n hover_color: LIGHT_BLUE,\n\n display_color: LIGHT_WHITE,\n\n },\n\n }\n\n }\n\n pub fn border(&mut self, color: RGBA) -> Self {\n\n self.shape_style.border = Bordering::Border(color);\n\n *self\n\n }\n\n\n\n pub fn no_border(&mut self) -> Self {\n\n self.shape_style.border = Bordering::NoBorder;\n\n *self\n\n }\n\n\n\n pub fn round(&mut self) -> Self {\n\n self.shape_style.round = Rounding::Round;\n\n *self\n", "file_path": "src/graphic/style.rs", "rank": 81, "score": 28619.42395760094 }, { "content": "use crate::device::event_context::EventContext;\n\nuse crate::graphic::render_api::PaintBrush;\n\n\n\n/// 渲染容器trait\n\n/// 在事件循环时会调用实现该trait的对象\n\n/// 作用:定义渲染所需的公共接口\n", "file_path": "src/device/container.rs", "rank": 82, "score": 28037.674845583973 }, { "content": "/// 颜色结构体\n\n#[repr(C)]\n\n#[derive(Copy, Default, Clone, Debug)]\n\npub struct RGBA(pub f32, pub f32, pub f32, pub f32);\n\n\n\npub const BLACK: RGBA = RGBA(0.0, 0.0, 0.0, 1.0);\n\npub const WHITE: RGBA = RGBA(1.0, 1.0, 1.0, 1.0);\n\npub const LIGHT_WHITE: RGBA = RGBA(0.8, 0.8, 0.8, 1.0);\n\npub const LIGHT_BLUE: RGBA = RGBA(0.0, 0.75, 1.0, 0.5);\n\n\n\n/// 默认窗口帧背景色\n\npub const BACKGROUND_COLOR: RGBA = RGBA(0.9, 0.9, 0.9, 1.0);\n\n\n\nimpl RGBA {\n\n pub fn to_u8(&self) -> (u8, u8, u8, u8) {\n\n let r = (self.0 * 255.0) as u8;\n\n let g = (self.1 * 255.0) as u8;\n\n let b = (self.2 * 255.0) as u8;\n\n let a = (self.3 * 255.0) as u8;\n\n (r, g, b, a)\n\n }\n\n pub fn to_vec(&self) -> [f32; 4] {\n\n [self.0, self.1, self.2, self.3]\n\n }\n\n}\n\n\n", "file_path": "src/graphic/base/color.rs", "rank": 83, "score": 27427.466210109757 }, { "content": "use std::fmt::Debug;\n\nuse std::future::Future;\n\n\n\nuse futures::{StreamExt, task};\n\nuse futures::channel::mpsc;\n\nuse winit::event::*;\n\nuse winit::event_loop::*;\n\nuse winit::window::*;\n\n\n\nuse crate::device::container::Container;\n\nuse crate::device::event_context::EventContext;\n\nuse crate::device::wgpu_context::GPUContext;\n\n\n\n/// 窗口结构体\n\n/// 作用:封装窗体,事件循环器,图形上下文\n\npub struct DisplayWindow<'a, M: 'static> {\n\n /// 图形上下文\n\n pub gpu_context: GPUContext,\n\n /// 时间监听器\n\n event_loop: EventLoop<M>,\n", "file_path": "src/device/display_window.rs", "rank": 84, "score": 26634.235393891096 }, { "content": " }\n\n\n\n pub fn send_message(&self, message: M) {\n\n self.message_channel.send_event(message).ok();\n\n }\n\n /// 键鼠单击动画效果\n\n pub fn action_animation(&self, style: &mut Style, position: &Rectangle,\n\n message: Option<M>) -> bool {\n\n let input = position\n\n .contain_coord(self.cursor_pos);\n\n if input && message.is_some() {\n\n let message = message.unwrap();\n\n let hover_color = style.get_hover_color();\n\n let back_color = style.get_back_color();\n\n if self.get_event().state == State::Pressed {\n\n style.display_color(hover_color);\n\n self.send_message(message);\n\n } else if self.get_event().state == State::Released {\n\n style.display_color(back_color);\n\n }\n", "file_path": "src/device/event_context.rs", "rank": 85, "score": 26633.796902825747 }, { "content": "use winit::event::WindowEvent;\n\nuse winit::event_loop::{EventLoop, EventLoopProxy};\n\nuse winit::window::Window;\n\n\n\nuse crate::graphic::base::*;\n\nuse crate::graphic::style::Style;\n\nuse crate::widget::{Component, EventType, GEvent, State};\n\n\n\n/// 事件上下文\n\npub struct EventContext<'a, M: 'static> {\n\n /// 窗口id\n\n pub window: Window,\n\n /// 鼠标位置\n\n pub cursor_pos: Point<f32>,\n\n /// 窗口事件\n\n pub window_event: Option<WindowEvent<'a>>,\n\n /// 自定义事件\n\n pub message: Option<M>,\n\n /// 自定义事件广播器\n\n message_channel: EventLoopProxy<M>,\n", "file_path": "src/device/event_context.rs", "rank": 86, "score": 26632.56337224116 }, { "content": " /// 事件上下文\n\n event_context: EventContext<'a, M>,\n\n}\n\n\n\nimpl<M: 'static + Debug> DisplayWindow<'static, M> {\n\n pub fn start<C>(self, container: C)\n\n where C: Container<M> + 'static {\n\n run_instance(self, container);\n\n }\n\n\n\n pub fn new<'a>(builder: WindowBuilder) -> DisplayWindow<'a, M> {\n\n use futures::executor::block_on;\n\n block_on(Self::init_window(builder))\n\n }\n\n /// 初始化窗口\n\n async fn init_window<'a>(builder: WindowBuilder) -> DisplayWindow<'a, M>\n\n {\n\n log::info!(\"Initializing the window...\");\n\n let event_loop = EventLoop::<M>::with_user_event();\n\n let window = builder.build(&event_loop).unwrap();\n", "file_path": "src/device/display_window.rs", "rank": 87, "score": 26630.212181064733 }, { "content": "}\n\n\n\nimpl<'a, M: 'static> EventContext<'a, M> {\n\n pub fn new(window: Window, event_loop: &EventLoop<M>) -> EventContext<'a, M> {\n\n EventContext {\n\n window,\n\n cursor_pos: Point::new(-1.0, -1.0),\n\n window_event: None,\n\n message: None,\n\n message_channel: event_loop.create_proxy(),\n\n }\n\n }\n\n\n\n // 更新鼠标坐标\n\n pub fn update_cursor<P: Into<Point<f32>>>(&mut self, pos: P) {\n\n self.cursor_pos = pos.into();\n\n }\n\n\n\n pub fn get_event(&self) -> GEvent {\n\n self.window_event.as_ref().unwrap().into()\n", "file_path": "src/device/event_context.rs", "rank": 88, "score": 26628.24783667184 }, { "content": " return true;\n\n }\n\n return false;\n\n }\n\n}\n\n\n\nimpl<'a, M: 'static> EventContext<'a, M> {\n\n /// 事件监听器\n\n /// 作用:监听用户交互事件\n\n pub fn component_listener(&self, listener: &mut Component<M>) -> bool\n\n {\n\n let mut key_listener = false;\n\n let mut mouse_listener = false;\n\n let hover_listener;\n\n let g_event = self.get_event();\n\n match g_event.event {\n\n EventType::Mouse(mouse) => {\n\n if g_event.state == State::Released {\n\n self.window.set_ime_position(self.cursor_pos);\n\n }\n", "file_path": "src/device/event_context.rs", "rank": 89, "score": 26627.70059674766 }, { "content": " } if window_id == event_context.window.id() => {\n\n // 捕获窗口关闭请求\n\n if event == WindowEvent::CloseRequested {\n\n break;\n\n }\n\n match event {\n\n WindowEvent::Resized(new_size) => {\n\n // 更新swapChain交换缓冲区\n\n gpu_context.update_surface_configure(new_size);\n\n }\n\n // 储存鼠标位置坐标\n\n WindowEvent::CursorMoved { position, .. }\n\n => {\n\n event_context.update_cursor(position);\n\n }\n\n _ => {}\n\n }\n\n // 监听到组件关注事件,决定是否重绘\n\n event_context.window_event = Some(event);\n\n if container.update(&mut event_context) {\n", "file_path": "src/device/display_window.rs", "rank": 90, "score": 26625.061838652167 }, { "content": " ControlFlow::Exit\n\n }\n\n };\n\n }\n\n });\n\n}\n\n\n\n/// 事件监听方法\n\nasync fn event_listener<C, M>(mut gpu_context: GPUContext,\n\n // glob_pipeline: PipelineState,\n\n mut event_context: EventContext<'_, M>,\n\n mut container: C,\n\n mut receiver: mpsc::UnboundedReceiver<winit::event::Event<'_, M>>)\n\n where C: Container<M> + 'static, M: 'static + Debug\n\n{\n\n while let Some(event) = receiver.next().await {\n\n match event {\n\n Event::WindowEvent {\n\n event,\n\n window_id,\n", "file_path": "src/device/display_window.rs", "rank": 91, "score": 26624.16983562233 }, { "content": " mouse_listener = listener.widget.action_listener(&self, mouse);\n\n }\n\n EventType::KeyBoard(key_code) => {\n\n key_listener = listener.widget.key_listener(&self, key_code);\n\n }\n\n EventType::ReceivedCharacter(c) => {\n\n listener.widget.received_character(&self, c);\n\n }\n\n _ => {}\n\n }\n\n hover_listener = listener.widget.hover_listener(&self);\n\n key_listener || mouse_listener || hover_listener\n\n }\n\n}", "file_path": "src/device/event_context.rs", "rank": 92, "score": 26622.527990658393 }, { "content": " let gpu_context = GPUContext::new(&window).await;\n\n let event_context = EventContext::new(window, &event_loop);\n\n let display_window = DisplayWindow {\n\n gpu_context,\n\n // glob_pipeline,\n\n event_loop,\n\n event_context,\n\n };\n\n return display_window;\n\n }\n\n}\n\n\n\n/// 运行窗口实例\n", "file_path": "src/device/display_window.rs", "rank": 93, "score": 26622.527990658393 }, { "content": " ..\n\n },\n\n window_id,\n\n } => Some(Event::WindowEvent {\n\n event: WindowEvent::Resized(*new_inner_size),\n\n window_id,\n\n }),\n\n _ => event.to_static(),\n\n };\n\n // 异步发送到事件监听器\n\n if let Some(event) = event {\n\n sender.start_send(event).expect(\"Send event\");\n\n let poll = instance_listener.as_mut().poll(&mut context);\n\n *control_flow = match poll {\n\n task::Poll::Pending => {\n\n // println!(\"--------pending--------\");\n\n ControlFlow::Wait\n\n }\n\n task::Poll::Ready(_) => {\n\n // println!(\"--------ready--------\");\n", "file_path": "src/device/display_window.rs", "rank": 94, "score": 26622.527990658393 }, { "content": " gpu_context.present(&mut container)\n\n }\n\n }\n\n Event::RedrawRequested(window_id)\n\n if window_id == event_context.window.id() => {\n\n gpu_context.present(&mut container)\n\n }\n\n Event::UserEvent(event) => {\n\n event_context.message = Some(event);\n\n }\n\n _ => {}\n\n }\n\n };\n\n}\n", "file_path": "src/device/display_window.rs", "rank": 95, "score": 26622.527990658393 }, { "content": " fn from(position: winit::dpi::PhysicalPosition<f64>) -> Point<f32> {\n\n Point::new(position.x as f32, position.y as f32)\n\n }\n\n}\n\n\n\nimpl From<winit::dpi::PhysicalSize<u32>> for Point<u32> {\n\n fn from(position: PhysicalSize<u32>) -> Self {\n\n Point::new(position.width, position.height)\n\n }\n\n}\n\n\n\nimpl From<winit::event::MouseButton> for Mouse {\n\n fn from(winit_mouse: MouseButton) -> Self {\n\n match winit_mouse {\n\n MouseButton::Left => { Mouse::Left }\n\n MouseButton::Right => { Mouse::Right }\n\n MouseButton::Middle => { Mouse::Middle }\n\n MouseButton::Other(_) => { Mouse::Other }\n\n }\n\n }\n", "file_path": "src/backend/event_winit_impl.rs", "rank": 96, "score": 24327.080395818542 }, { "content": "use winit::dpi::PhysicalSize;\n\nuse winit::event::*;\n\n\n\nuse crate::graphic::base::Point;\n\nuse crate::widget::*;\n\n\n\nimpl From<Point<f32>> for winit::dpi::Position {\n\n #[inline]\n\n fn from(position: Point<f32>) -> winit::dpi::Position {\n\n winit::dpi::Position::Physical(\n\n winit::dpi::PhysicalPosition\n\n {\n\n x: position.x as i32,\n\n y: position.y as i32,\n\n })\n\n }\n\n}\n\n\n\nimpl From<winit::dpi::PhysicalPosition<f64>> for Point<f32> {\n\n #[inline]\n", "file_path": "src/backend/event_winit_impl.rs", "rank": 97, "score": 24326.04492227975 }, { "content": "}\n\n\n\nimpl From<winit::event::ElementState> for State {\n\n fn from(winit_state: ElementState) -> Self {\n\n match winit_state {\n\n ElementState::Pressed => { State::Pressed }\n\n ElementState::Released => { State::Released }\n\n }\n\n }\n\n}\n\n\n\nimpl From<&winit::event::WindowEvent<'_>> for GEvent {\n\n fn from(winit_event: &WindowEvent) -> Self {\n\n match winit_event {\n\n WindowEvent::MouseInput {\n\n state,\n\n button,\n\n ..\n\n } => {\n\n GEvent {\n", "file_path": "src/backend/event_winit_impl.rs", "rank": 98, "score": 24318.472635732127 }, { "content": " event: EventType::Mouse((*button).into()),\n\n state: (*state).into(),\n\n }\n\n }\n\n WindowEvent::KeyboardInput {\n\n input:\n\n KeyboardInput {\n\n state,\n\n virtual_keycode,\n\n ..\n\n },\n\n ..\n\n } => {\n\n GEvent {\n\n event: EventType::KeyBoard(*virtual_keycode),\n\n state: (*state).into(),\n\n }\n\n }\n\n WindowEvent::ReceivedCharacter(c) => {\n\n GEvent {\n", "file_path": "src/backend/event_winit_impl.rs", "rank": 99, "score": 24313.39489147029 } ]
Rust
src/rustc/middle/trans/impl.rs
mernen/rust
bb5c07922f20559af1e40d63a15b1be0402e5fe4
import libc::c_uint; import base::*; import common::*; import type_of::*; import build::*; import driver::session::session; import syntax::{ast, ast_map}; import ast_map::{path, path_mod, path_name, node_id_to_str}; import driver::session::expect; import syntax::ast_util::local_def; import metadata::csearch; import back::{link, abi}; import lib::llvm::llvm; import lib::llvm::{ValueRef, TypeRef}; import lib::llvm::llvm::LLVMGetParam; import std::map::hashmap; import util::ppaux::{ty_to_str, tys_to_str}; import syntax::print::pprust::expr_to_str; /** The main "translation" pass for methods. Generates code for non-monomorphized methods only. Other methods will be generated once they are invoked with specific type parameters, see `trans::base::lval_static_fn()` or `trans::base::monomorphic_fn()`. */ fn trans_impl(ccx: @crate_ctxt, path: path, name: ast::ident, methods: ~[@ast::method], tps: ~[ast::ty_param]) { let _icx = ccx.insn_ctxt("impl::trans_impl"); if tps.len() > 0u { return; } let sub_path = vec::append_one(path, path_name(name)); for vec::each(methods) |method| { if method.tps.len() == 0u { let llfn = get_item_val(ccx, method.id); let path = vec::append_one(sub_path, path_name(method.ident)); trans_method(ccx, path, method, none, llfn); } } } /** Translates a (possibly monomorphized) method body. # Parameters - `path`: the path to the method - `method`: the AST node for the method - `param_substs`: if this is a generic method, the current values for type parameters and so forth, else none - `llfn`: the LLVM ValueRef for the method */ fn trans_method(ccx: @crate_ctxt, path: path, method: &ast::method, param_substs: option<param_substs>, llfn: ValueRef) { let self_arg = match method.self_ty.node { ast::sty_static => { no_self } _ => { let self_ty = ty::node_id_to_type(ccx.tcx, method.self_id); let self_ty = match param_substs { none => self_ty, some({tys: ref tys, _}) => ty::subst_tps(ccx.tcx, *tys, self_ty) }; match method.self_ty.node { ast::sty_value => { impl_owned_self(self_ty) } _ => { impl_self(self_ty) } } } }; trans_fn(ccx, path, method.decl, method.body, llfn, self_arg, param_substs, method.id); } fn trans_self_arg(bcx: block, base: @ast::expr, mentry: typeck::method_map_entry) -> result { let _icx = bcx.insn_ctxt("impl::trans_self_arg"); let basety = expr_ty(bcx, base); let mode = ast::expl(mentry.self_mode); let mut temp_cleanups = ~[]; let result = trans_arg_expr(bcx, {mode: mode, ty: basety}, T_ptr(type_of::type_of(bcx.ccx(), basety)), base, temp_cleanups, none, mentry.derefs); return result; } fn trans_method_callee(bcx: block, callee_id: ast::node_id, self: @ast::expr, mentry: typeck::method_map_entry) -> lval_maybe_callee { let _icx = bcx.insn_ctxt("impl::trans_method_callee"); match mentry.origin { typeck::method_static(did) => { let {bcx, val} = trans_self_arg(bcx, self, mentry); {env: self_env(val, node_id_type(bcx, self.id), none, mentry.self_mode) with lval_static_fn(bcx, did, callee_id)} } typeck::method_param({trait_id:trait_id, method_num:off, param_num:p, bound_num:b}) => { match bcx.fcx.param_substs { some(substs) => { let vtbl = find_vtable_in_fn_ctxt(substs, p, b); trans_monomorphized_callee(bcx, callee_id, self, mentry, trait_id, off, vtbl) } none => fail ~"trans_method_callee: missing param_substs" } } typeck::method_trait(_, off) => { let {bcx, val} = trans_temp_expr(bcx, self); let fty = node_id_type(bcx, callee_id); let self_ty = node_id_type(bcx, self.id); let {bcx, val, _} = autoderef(bcx, self.id, val, self_ty, uint::max_value); trans_trait_callee(bcx, val, fty, off) } } } fn trans_static_method_callee(bcx: block, method_id: ast::def_id, callee_id: ast::node_id) -> lval_maybe_callee { let _icx = bcx.insn_ctxt("impl::trans_static_method_callee"); let ccx = bcx.ccx(); let mname = if method_id.crate == ast::local_crate { match bcx.tcx().items.get(method_id.node) { ast_map::node_trait_method(trait_method, _, _) => { ast_util::trait_method_to_ty_method(*trait_method).ident } _ => fail ~"callee is not a trait method" } } else { let path = csearch::get_item_path(bcx.tcx(), method_id); match path[path.len()-1] { path_name(s) => { s } path_mod(_) => { fail ~"path doesn't have a name?" } } }; debug!("trans_static_method_callee: method_id=%?, callee_id=%?, \ name=%s", method_id, callee_id, ccx.sess.str_of(mname)); let vtbls = resolve_vtables_in_fn_ctxt( bcx.fcx, ccx.maps.vtable_map.get(callee_id)); match vtbls[0] { typeck::vtable_static(impl_did, impl_substs, sub_origins) => { let mth_id = method_with_name(bcx.ccx(), impl_did, mname); let n_m_tps = method_ty_param_count(ccx, mth_id, impl_did); let node_substs = node_id_type_params(bcx, callee_id); let ty_substs = vec::append(impl_substs, vec::tailn(node_substs, node_substs.len() - n_m_tps)); let lval = lval_static_fn_inner(bcx, mth_id, callee_id, ty_substs, some(sub_origins)); {env: null_env, val: PointerCast(bcx, lval.val, T_ptr(type_of_fn_from_ty( ccx, node_id_type(bcx, callee_id)))) with lval} } _ => { fail ~"vtable_param left in monomorphized function's vtable substs"; } } } fn method_from_methods(ms: ~[@ast::method], name: ast::ident) -> ast::def_id { local_def(option::get(vec::find(ms, |m| m.ident == name)).id) } fn method_with_name(ccx: @crate_ctxt, impl_id: ast::def_id, name: ast::ident) -> ast::def_id { if impl_id.crate == ast::local_crate { match ccx.tcx.items.get(impl_id.node) { ast_map::node_item(@{node: ast::item_impl(_, _, _, ms), _}, _) => { method_from_methods(ms, name) } ast_map::node_item(@{node: ast::item_class(struct_def, _), _}, _) => { method_from_methods(struct_def.methods, name) } _ => fail ~"method_with_name" } } else { csearch::get_impl_method(ccx.sess.cstore, impl_id, name) } } fn method_ty_param_count(ccx: @crate_ctxt, m_id: ast::def_id, i_id: ast::def_id) -> uint { if m_id.crate == ast::local_crate { match ccx.tcx.items.get(m_id.node) { ast_map::node_method(m, _, _) => vec::len(m.tps), _ => fail ~"method_ty_param_count" } } else { csearch::get_type_param_count(ccx.sess.cstore, m_id) - csearch::get_type_param_count(ccx.sess.cstore, i_id) } } fn trans_monomorphized_callee(bcx: block, callee_id: ast::node_id, base: @ast::expr, mentry: typeck::method_map_entry, trait_id: ast::def_id, n_method: uint, vtbl: typeck::vtable_origin) -> lval_maybe_callee { let _icx = bcx.insn_ctxt("impl::trans_monomorphized_callee"); match vtbl { typeck::vtable_static(impl_did, impl_substs, sub_origins) => { let ccx = bcx.ccx(); let mname = ty::trait_methods(ccx.tcx, trait_id)[n_method].ident; let mth_id = method_with_name(bcx.ccx(), impl_did, mname); let n_m_tps = method_ty_param_count(ccx, mth_id, impl_did); let node_substs = node_id_type_params(bcx, callee_id); let ty_substs = vec::append(impl_substs, vec::tailn(node_substs, node_substs.len() - n_m_tps)); let {bcx, val} = trans_self_arg(bcx, base, mentry); let lval = lval_static_fn_inner(bcx, mth_id, callee_id, ty_substs, some(sub_origins)); {env: self_env(val, node_id_type(bcx, base.id), none, mentry.self_mode), val: PointerCast(bcx, lval.val, T_ptr(type_of_fn_from_ty( ccx, node_id_type(bcx, callee_id)))) with lval} } typeck::vtable_trait(trait_id, tps) => { let {bcx, val} = trans_temp_expr(bcx, base); let fty = node_id_type(bcx, callee_id); trans_trait_callee(bcx, val, fty, n_method) } typeck::vtable_param(n_param, n_bound) => { fail ~"vtable_param left in monomorphized function's vtable substs"; } } } fn trans_trait_callee(bcx: block, val: ValueRef, callee_ty: ty::t, n_method: uint) -> lval_maybe_callee { let _icx = bcx.insn_ctxt("impl::trans_trait_callee"); let ccx = bcx.ccx(); let vtable = Load(bcx, PointerCast(bcx, GEPi(bcx, val, ~[0u, 0u]), T_ptr(T_ptr(T_vtable())))); let llbox = Load(bcx, GEPi(bcx, val, ~[0u, 1u])); let self = GEPi(bcx, llbox, ~[0u, abi::box_field_body]); let env = self_env(self, ty::mk_opaque_box(bcx.tcx()), some(llbox), ast::by_ref); let llfty = type_of::type_of_fn_from_ty(ccx, callee_ty); let vtable = PointerCast(bcx, vtable, T_ptr(T_array(T_ptr(llfty), n_method + 1u))); let mptr = Load(bcx, GEPi(bcx, vtable, ~[0u, n_method])); {bcx: bcx, val: mptr, kind: lv_owned, env: env} } fn find_vtable_in_fn_ctxt(ps: param_substs, n_param: uint, n_bound: uint) -> typeck::vtable_origin { let mut vtable_off = n_bound, i = 0u; for vec::each(*ps.bounds) |bounds| { if i >= n_param { break; } for vec::each(*bounds) |bound| { match bound { ty::bound_trait(_) => vtable_off += 1u, _ => () } } i += 1u; } option::get(ps.vtables)[vtable_off] } fn resolve_vtables_in_fn_ctxt(fcx: fn_ctxt, vts: typeck::vtable_res) -> typeck::vtable_res { @vec::map(*vts, |d| resolve_vtable_in_fn_ctxt(fcx, d)) } fn resolve_vtable_in_fn_ctxt(fcx: fn_ctxt, vt: typeck::vtable_origin) -> typeck::vtable_origin { match vt { typeck::vtable_static(trait_id, tys, sub) => { let tys = match fcx.param_substs { some(substs) => { vec::map(tys, |t| ty::subst_tps(fcx.ccx.tcx, substs.tys, t)) } _ => tys }; typeck::vtable_static(trait_id, tys, resolve_vtables_in_fn_ctxt(fcx, sub)) } typeck::vtable_param(n_param, n_bound) => { match fcx.param_substs { some(substs) => { find_vtable_in_fn_ctxt(substs, n_param, n_bound) } _ => fail ~"resolve_vtable_in_fn_ctxt: no substs" } } _ => vt } } fn vtable_id(ccx: @crate_ctxt, origin: typeck::vtable_origin) -> mono_id { match origin { typeck::vtable_static(impl_id, substs, sub_vtables) => { make_mono_id(ccx, impl_id, substs, if (*sub_vtables).len() == 0u { none } else { some(sub_vtables) }, none) } typeck::vtable_trait(trait_id, substs) => { @{def: trait_id, params: vec::map(substs, |t| mono_precise(t, none))} } _ => fail ~"vtable_id" } } fn get_vtable(ccx: @crate_ctxt, origin: typeck::vtable_origin) -> ValueRef { let hash_id = vtable_id(ccx, origin); match ccx.vtables.find(hash_id) { some(val) => val, none => match origin { typeck::vtable_static(id, substs, sub_vtables) => { make_impl_vtable(ccx, id, substs, sub_vtables) } _ => fail ~"get_vtable: expected a static origin" } } } fn make_vtable(ccx: @crate_ctxt, ptrs: ~[ValueRef]) -> ValueRef { let _icx = ccx.insn_ctxt("impl::make_vtable"); let tbl = C_struct(ptrs); let vt_gvar = str::as_c_str(ccx.sess.str_of(ccx.names(~"vtable")), |buf| { llvm::LLVMAddGlobal(ccx.llmod, val_ty(tbl), buf) }); llvm::LLVMSetInitializer(vt_gvar, tbl); llvm::LLVMSetGlobalConstant(vt_gvar, lib::llvm::True); lib::llvm::SetLinkage(vt_gvar, lib::llvm::InternalLinkage); vt_gvar } fn make_impl_vtable(ccx: @crate_ctxt, impl_id: ast::def_id, substs: ~[ty::t], vtables: typeck::vtable_res) -> ValueRef { let _icx = ccx.insn_ctxt("impl::make_impl_vtable"); let tcx = ccx.tcx; let trt_id = expect(ccx.sess, ty::ty_to_def_id(ty::impl_traits(tcx, impl_id)[0]), || ~"make_impl_vtable: non-trait-type implemented"); let has_tps = (*ty::lookup_item_type(ccx.tcx, impl_id).bounds).len() > 0u; make_vtable(ccx, vec::map(*ty::trait_methods(tcx, trt_id), |im| { let fty = ty::subst_tps(tcx, substs, ty::mk_fn(tcx, im.fty)); if (*im.tps).len() > 0u || ty::type_has_self(fty) { C_null(T_ptr(T_nil())) } else { let mut m_id = method_with_name(ccx, impl_id, im.ident); if has_tps { if m_id.crate != ast::local_crate { m_id = maybe_instantiate_inline(ccx, m_id); } monomorphic_fn(ccx, m_id, substs, some(vtables), none).val } else if m_id.crate == ast::local_crate { get_item_val(ccx, m_id.node) } else { trans_external_path(ccx, m_id, fty) } } })) } fn trans_cast(bcx: block, val: @ast::expr, id: ast::node_id, dest: dest) -> block { let _icx = bcx.insn_ctxt("impl::trans_cast"); if dest == ignore { return trans_expr(bcx, val, ignore); } let ccx = bcx.ccx(); let v_ty = expr_ty(bcx, val); let {bcx: bcx, box: llbox, body: body} = malloc_boxed(bcx, v_ty); add_clean_free(bcx, llbox, heap_shared); let bcx = trans_expr_save_in(bcx, val, body); revoke_clean(bcx, llbox); let result = get_dest_addr(dest); Store(bcx, llbox, PointerCast(bcx, GEPi(bcx, result, ~[0u, 1u]), T_ptr(val_ty(llbox)))); let orig = ccx.maps.vtable_map.get(id)[0]; let orig = resolve_vtable_in_fn_ctxt(bcx.fcx, orig); let vtable = get_vtable(bcx.ccx(), orig); Store(bcx, vtable, PointerCast(bcx, GEPi(bcx, result, ~[0u, 0u]), T_ptr(val_ty(vtable)))); bcx }
import libc::c_uint; import base::*; import common::*; import type_of::*; import build::*; import driver::session::session; import syntax::{ast, ast_map}; import ast_map::{path, path_mod, path_name, node_id_to_str}; import driver::session::expect; import syntax::ast_util::local_def; import metadata::csearch; import back::{link, abi}; import lib::llvm::llvm; import lib::llvm::{ValueRef, TypeRef}; import lib::llvm::llvm::LLVMGetParam; import std::map::hashmap; import util::ppaux::{ty_to_str, tys_to_str}; import syntax::print::pprust::expr_to_str; /** The main "translation" pass for methods. Generates code for non-monomorphized methods only. Other methods will be generated once they are invoked with specific type parameters, see `trans::base::lval_static_fn()` or `trans::base::monomorphic_fn()`. */ fn trans_impl(ccx: @crate_ctxt, path: path, name: ast::ident, methods: ~[@ast::method], tps: ~[ast::ty_param]) { let _icx = ccx.insn_ctxt("impl::trans_impl"); if tps.len() > 0u { return; } let sub_path = vec::append_one(path, path_name(name)); for vec::each(methods) |method| { if method.tps.len() == 0u { let llfn = get_item_val(ccx, method.id); let path = vec::append_one(sub_path, path_name(method.ident)); trans_method(ccx, path, method, none, llfn); } } } /** Translates a (possibly monomorphized) method body. # Parameters - `path`: the path to the method - `method`: the AST node for the method - `param_substs`: if this is a generic method, the current values for type parameters and so forth, else none - `llfn`: the LLVM ValueRef for the method */
fn trans_self_arg(bcx: block, base: @ast::expr, mentry: typeck::method_map_entry) -> result { let _icx = bcx.insn_ctxt("impl::trans_self_arg"); let basety = expr_ty(bcx, base); let mode = ast::expl(mentry.self_mode); let mut temp_cleanups = ~[]; let result = trans_arg_expr(bcx, {mode: mode, ty: basety}, T_ptr(type_of::type_of(bcx.ccx(), basety)), base, temp_cleanups, none, mentry.derefs); return result; } fn trans_method_callee(bcx: block, callee_id: ast::node_id, self: @ast::expr, mentry: typeck::method_map_entry) -> lval_maybe_callee { let _icx = bcx.insn_ctxt("impl::trans_method_callee"); match mentry.origin { typeck::method_static(did) => { let {bcx, val} = trans_self_arg(bcx, self, mentry); {env: self_env(val, node_id_type(bcx, self.id), none, mentry.self_mode) with lval_static_fn(bcx, did, callee_id)} } typeck::method_param({trait_id:trait_id, method_num:off, param_num:p, bound_num:b}) => { match bcx.fcx.param_substs { some(substs) => { let vtbl = find_vtable_in_fn_ctxt(substs, p, b); trans_monomorphized_callee(bcx, callee_id, self, mentry, trait_id, off, vtbl) } none => fail ~"trans_method_callee: missing param_substs" } } typeck::method_trait(_, off) => { let {bcx, val} = trans_temp_expr(bcx, self); let fty = node_id_type(bcx, callee_id); let self_ty = node_id_type(bcx, self.id); let {bcx, val, _} = autoderef(bcx, self.id, val, self_ty, uint::max_value); trans_trait_callee(bcx, val, fty, off) } } } fn trans_static_method_callee(bcx: block, method_id: ast::def_id, callee_id: ast::node_id) -> lval_maybe_callee { let _icx = bcx.insn_ctxt("impl::trans_static_method_callee"); let ccx = bcx.ccx(); let mname = if method_id.crate == ast::local_crate { match bcx.tcx().items.get(method_id.node) { ast_map::node_trait_method(trait_method, _, _) => { ast_util::trait_method_to_ty_method(*trait_method).ident } _ => fail ~"callee is not a trait method" } } else { let path = csearch::get_item_path(bcx.tcx(), method_id); match path[path.len()-1] { path_name(s) => { s } path_mod(_) => { fail ~"path doesn't have a name?" } } }; debug!("trans_static_method_callee: method_id=%?, callee_id=%?, \ name=%s", method_id, callee_id, ccx.sess.str_of(mname)); let vtbls = resolve_vtables_in_fn_ctxt( bcx.fcx, ccx.maps.vtable_map.get(callee_id)); match vtbls[0] { typeck::vtable_static(impl_did, impl_substs, sub_origins) => { let mth_id = method_with_name(bcx.ccx(), impl_did, mname); let n_m_tps = method_ty_param_count(ccx, mth_id, impl_did); let node_substs = node_id_type_params(bcx, callee_id); let ty_substs = vec::append(impl_substs, vec::tailn(node_substs, node_substs.len() - n_m_tps)); let lval = lval_static_fn_inner(bcx, mth_id, callee_id, ty_substs, some(sub_origins)); {env: null_env, val: PointerCast(bcx, lval.val, T_ptr(type_of_fn_from_ty( ccx, node_id_type(bcx, callee_id)))) with lval} } _ => { fail ~"vtable_param left in monomorphized function's vtable substs"; } } } fn method_from_methods(ms: ~[@ast::method], name: ast::ident) -> ast::def_id { local_def(option::get(vec::find(ms, |m| m.ident == name)).id) } fn method_with_name(ccx: @crate_ctxt, impl_id: ast::def_id, name: ast::ident) -> ast::def_id { if impl_id.crate == ast::local_crate { match ccx.tcx.items.get(impl_id.node) { ast_map::node_item(@{node: ast::item_impl(_, _, _, ms), _}, _) => { method_from_methods(ms, name) } ast_map::node_item(@{node: ast::item_class(struct_def, _), _}, _) => { method_from_methods(struct_def.methods, name) } _ => fail ~"method_with_name" } } else { csearch::get_impl_method(ccx.sess.cstore, impl_id, name) } } fn method_ty_param_count(ccx: @crate_ctxt, m_id: ast::def_id, i_id: ast::def_id) -> uint { if m_id.crate == ast::local_crate { match ccx.tcx.items.get(m_id.node) { ast_map::node_method(m, _, _) => vec::len(m.tps), _ => fail ~"method_ty_param_count" } } else { csearch::get_type_param_count(ccx.sess.cstore, m_id) - csearch::get_type_param_count(ccx.sess.cstore, i_id) } } fn trans_monomorphized_callee(bcx: block, callee_id: ast::node_id, base: @ast::expr, mentry: typeck::method_map_entry, trait_id: ast::def_id, n_method: uint, vtbl: typeck::vtable_origin) -> lval_maybe_callee { let _icx = bcx.insn_ctxt("impl::trans_monomorphized_callee"); match vtbl { typeck::vtable_static(impl_did, impl_substs, sub_origins) => { let ccx = bcx.ccx(); let mname = ty::trait_methods(ccx.tcx, trait_id)[n_method].ident; let mth_id = method_with_name(bcx.ccx(), impl_did, mname); let n_m_tps = method_ty_param_count(ccx, mth_id, impl_did); let node_substs = node_id_type_params(bcx, callee_id); let ty_substs = vec::append(impl_substs, vec::tailn(node_substs, node_substs.len() - n_m_tps)); let {bcx, val} = trans_self_arg(bcx, base, mentry); let lval = lval_static_fn_inner(bcx, mth_id, callee_id, ty_substs, some(sub_origins)); {env: self_env(val, node_id_type(bcx, base.id), none, mentry.self_mode), val: PointerCast(bcx, lval.val, T_ptr(type_of_fn_from_ty( ccx, node_id_type(bcx, callee_id)))) with lval} } typeck::vtable_trait(trait_id, tps) => { let {bcx, val} = trans_temp_expr(bcx, base); let fty = node_id_type(bcx, callee_id); trans_trait_callee(bcx, val, fty, n_method) } typeck::vtable_param(n_param, n_bound) => { fail ~"vtable_param left in monomorphized function's vtable substs"; } } } fn trans_trait_callee(bcx: block, val: ValueRef, callee_ty: ty::t, n_method: uint) -> lval_maybe_callee { let _icx = bcx.insn_ctxt("impl::trans_trait_callee"); let ccx = bcx.ccx(); let vtable = Load(bcx, PointerCast(bcx, GEPi(bcx, val, ~[0u, 0u]), T_ptr(T_ptr(T_vtable())))); let llbox = Load(bcx, GEPi(bcx, val, ~[0u, 1u])); let self = GEPi(bcx, llbox, ~[0u, abi::box_field_body]); let env = self_env(self, ty::mk_opaque_box(bcx.tcx()), some(llbox), ast::by_ref); let llfty = type_of::type_of_fn_from_ty(ccx, callee_ty); let vtable = PointerCast(bcx, vtable, T_ptr(T_array(T_ptr(llfty), n_method + 1u))); let mptr = Load(bcx, GEPi(bcx, vtable, ~[0u, n_method])); {bcx: bcx, val: mptr, kind: lv_owned, env: env} } fn find_vtable_in_fn_ctxt(ps: param_substs, n_param: uint, n_bound: uint) -> typeck::vtable_origin { let mut vtable_off = n_bound, i = 0u; for vec::each(*ps.bounds) |bounds| { if i >= n_param { break; } for vec::each(*bounds) |bound| { match bound { ty::bound_trait(_) => vtable_off += 1u, _ => () } } i += 1u; } option::get(ps.vtables)[vtable_off] } fn resolve_vtables_in_fn_ctxt(fcx: fn_ctxt, vts: typeck::vtable_res) -> typeck::vtable_res { @vec::map(*vts, |d| resolve_vtable_in_fn_ctxt(fcx, d)) } fn resolve_vtable_in_fn_ctxt(fcx: fn_ctxt, vt: typeck::vtable_origin) -> typeck::vtable_origin { match vt { typeck::vtable_static(trait_id, tys, sub) => { let tys = match fcx.param_substs { some(substs) => { vec::map(tys, |t| ty::subst_tps(fcx.ccx.tcx, substs.tys, t)) } _ => tys }; typeck::vtable_static(trait_id, tys, resolve_vtables_in_fn_ctxt(fcx, sub)) } typeck::vtable_param(n_param, n_bound) => { match fcx.param_substs { some(substs) => { find_vtable_in_fn_ctxt(substs, n_param, n_bound) } _ => fail ~"resolve_vtable_in_fn_ctxt: no substs" } } _ => vt } } fn vtable_id(ccx: @crate_ctxt, origin: typeck::vtable_origin) -> mono_id { match origin { typeck::vtable_static(impl_id, substs, sub_vtables) => { make_mono_id(ccx, impl_id, substs, if (*sub_vtables).len() == 0u { none } else { some(sub_vtables) }, none) } typeck::vtable_trait(trait_id, substs) => { @{def: trait_id, params: vec::map(substs, |t| mono_precise(t, none))} } _ => fail ~"vtable_id" } } fn get_vtable(ccx: @crate_ctxt, origin: typeck::vtable_origin) -> ValueRef { let hash_id = vtable_id(ccx, origin); match ccx.vtables.find(hash_id) { some(val) => val, none => match origin { typeck::vtable_static(id, substs, sub_vtables) => { make_impl_vtable(ccx, id, substs, sub_vtables) } _ => fail ~"get_vtable: expected a static origin" } } } fn make_vtable(ccx: @crate_ctxt, ptrs: ~[ValueRef]) -> ValueRef { let _icx = ccx.insn_ctxt("impl::make_vtable"); let tbl = C_struct(ptrs); let vt_gvar = str::as_c_str(ccx.sess.str_of(ccx.names(~"vtable")), |buf| { llvm::LLVMAddGlobal(ccx.llmod, val_ty(tbl), buf) }); llvm::LLVMSetInitializer(vt_gvar, tbl); llvm::LLVMSetGlobalConstant(vt_gvar, lib::llvm::True); lib::llvm::SetLinkage(vt_gvar, lib::llvm::InternalLinkage); vt_gvar } fn make_impl_vtable(ccx: @crate_ctxt, impl_id: ast::def_id, substs: ~[ty::t], vtables: typeck::vtable_res) -> ValueRef { let _icx = ccx.insn_ctxt("impl::make_impl_vtable"); let tcx = ccx.tcx; let trt_id = expect(ccx.sess, ty::ty_to_def_id(ty::impl_traits(tcx, impl_id)[0]), || ~"make_impl_vtable: non-trait-type implemented"); let has_tps = (*ty::lookup_item_type(ccx.tcx, impl_id).bounds).len() > 0u; make_vtable(ccx, vec::map(*ty::trait_methods(tcx, trt_id), |im| { let fty = ty::subst_tps(tcx, substs, ty::mk_fn(tcx, im.fty)); if (*im.tps).len() > 0u || ty::type_has_self(fty) { C_null(T_ptr(T_nil())) } else { let mut m_id = method_with_name(ccx, impl_id, im.ident); if has_tps { if m_id.crate != ast::local_crate { m_id = maybe_instantiate_inline(ccx, m_id); } monomorphic_fn(ccx, m_id, substs, some(vtables), none).val } else if m_id.crate == ast::local_crate { get_item_val(ccx, m_id.node) } else { trans_external_path(ccx, m_id, fty) } } })) } fn trans_cast(bcx: block, val: @ast::expr, id: ast::node_id, dest: dest) -> block { let _icx = bcx.insn_ctxt("impl::trans_cast"); if dest == ignore { return trans_expr(bcx, val, ignore); } let ccx = bcx.ccx(); let v_ty = expr_ty(bcx, val); let {bcx: bcx, box: llbox, body: body} = malloc_boxed(bcx, v_ty); add_clean_free(bcx, llbox, heap_shared); let bcx = trans_expr_save_in(bcx, val, body); revoke_clean(bcx, llbox); let result = get_dest_addr(dest); Store(bcx, llbox, PointerCast(bcx, GEPi(bcx, result, ~[0u, 1u]), T_ptr(val_ty(llbox)))); let orig = ccx.maps.vtable_map.get(id)[0]; let orig = resolve_vtable_in_fn_ctxt(bcx.fcx, orig); let vtable = get_vtable(bcx.ccx(), orig); Store(bcx, vtable, PointerCast(bcx, GEPi(bcx, result, ~[0u, 0u]), T_ptr(val_ty(vtable)))); bcx }
fn trans_method(ccx: @crate_ctxt, path: path, method: &ast::method, param_substs: option<param_substs>, llfn: ValueRef) { let self_arg = match method.self_ty.node { ast::sty_static => { no_self } _ => { let self_ty = ty::node_id_to_type(ccx.tcx, method.self_id); let self_ty = match param_substs { none => self_ty, some({tys: ref tys, _}) => ty::subst_tps(ccx.tcx, *tys, self_ty) }; match method.self_ty.node { ast::sty_value => { impl_owned_self(self_ty) } _ => { impl_self(self_ty) } } } }; trans_fn(ccx, path, method.decl, method.body, llfn, self_arg, param_substs, method.id); }
function_block-full_function
[ { "content": "fn val_ty(v: ValueRef) -> TypeRef { return llvm::LLVMTypeOf(v); }\n\n\n", "file_path": "src/rustc/middle/trans/common.rs", "rank": 0, "score": 566159.6927412436 }, { "content": "// LLVM constant constructors.\n\nfn C_null(t: TypeRef) -> ValueRef { return llvm::LLVMConstNull(t); }\n\n\n", "file_path": "src/rustc/middle/trans/common.rs", "rank": 1, "score": 545707.7497899571 }, { "content": "fn register_method(ccx: @crate_ctxt, id: ast::node_id, pth: @ast_map::path,\n\n m: @ast::method) -> ValueRef {\n\n let mty = ty::node_id_to_type(ccx.tcx, id);\n\n let pth = vec::append(*pth, ~[path_name(ccx.names(~\"meth\")),\n\n path_name(m.ident)]);\n\n let llfn = register_fn_full(ccx, m.span, pth, id, mty);\n\n set_inline_hint_if_appr(m.attrs, llfn);\n\n llfn\n\n}\n\n\n", "file_path": "src/rustc/middle/trans/base.rs", "rank": 2, "score": 527418.2091790575 }, { "content": "fn is_main_name(path: syntax::ast_map::path) -> bool {\n\n // FIXME (#34): path should be a constrained type, so we know\n\n // the call to last doesn't fail.\n\n vec::last(path) == syntax::ast_map::path_name(\n\n syntax::parse::token::special_idents::main\n\n )\n\n}\n\n\n\n//\n\n// Local Variables:\n\n// mode: rust\n\n// fill-column: 78;\n\n// indent-tabs-mode: nil\n\n// c-basic-offset: 4\n\n// buffer-file-coding-system: utf-8-unix\n\n// End:\n\n//\n", "file_path": "src/rustc/util/common.rs", "rank": 3, "score": 499685.17496024445 }, { "content": "fn T_metadata() -> TypeRef { return llvm::LLVMMetadataType(); }\n\n\n", "file_path": "src/rustc/middle/trans/common.rs", "rank": 4, "score": 494508.0339859681 }, { "content": "fn T_f64() -> TypeRef { return llvm::LLVMDoubleType(); }\n\n\n", "file_path": "src/rustc/middle/trans/common.rs", "rank": 5, "score": 494508.0339859681 }, { "content": "fn T_i1() -> TypeRef { return llvm::LLVMInt1Type(); }\n\n\n", "file_path": "src/rustc/middle/trans/common.rs", "rank": 6, "score": 494508.0339859681 }, { "content": "fn T_i8() -> TypeRef { return llvm::LLVMInt8Type(); }\n\n\n", "file_path": "src/rustc/middle/trans/common.rs", "rank": 7, "score": 494508.0339859681 }, { "content": "fn T_f32() -> TypeRef { return llvm::LLVMFloatType(); }\n\n\n", "file_path": "src/rustc/middle/trans/common.rs", "rank": 8, "score": 494508.0339859681 }, { "content": "fn T_i16() -> TypeRef { return llvm::LLVMInt16Type(); }\n\n\n", "file_path": "src/rustc/middle/trans/common.rs", "rank": 9, "score": 494508.0339859681 }, { "content": "fn T_i32() -> TypeRef { return llvm::LLVMInt32Type(); }\n\n\n", "file_path": "src/rustc/middle/trans/common.rs", "rank": 10, "score": 494508.0339859681 }, { "content": "fn T_i64() -> TypeRef { return llvm::LLVMInt64Type(); }\n\n\n", "file_path": "src/rustc/middle/trans/common.rs", "rank": 11, "score": 494508.0339859681 }, { "content": "fn get_dtor_symbol(ccx: @crate_ctxt, path: path, id: ast::node_id,\n\n substs: option<param_substs>) -> ~str {\n\n let t = ty::node_id_to_type(ccx.tcx, id);\n\n match ccx.item_symbols.find(id) {\n\n some(s) => s,\n\n none if is_none(substs) => {\n\n let s = mangle_exported_name(\n\n ccx,\n\n vec::append(path, ~[path_name(ccx.names(~\"dtor\"))]),\n\n t);\n\n ccx.item_symbols.insert(id, s);\n\n s\n\n }\n\n none => {\n\n // Monomorphizing, so just make a symbol, don't add\n\n // this to item_symbols\n\n match substs {\n\n some(ss) => {\n\n let mono_ty = ty::subst_tps(ccx.tcx, ss.tys, t);\n\n mangle_exported_name(\n", "file_path": "src/rustc/middle/trans/base.rs", "rank": 13, "score": 458455.4169444203 }, { "content": "// Create a /real/ closure: this is like create_fn_pair, but creates a\n\n// a fn value on the stack with a specified environment (which need not be\n\n// on the stack).\n\nfn create_real_fn_pair(cx: block, llfnty: TypeRef, llfn: ValueRef,\n\n llenvptr: ValueRef) -> ValueRef {\n\n let pair = alloca(cx, T_fn_pair(cx.ccx(), llfnty));\n\n fill_fn_pair(cx, pair, llfn, llenvptr);\n\n return pair;\n\n}\n\n\n", "file_path": "src/rustc/middle/trans/base.rs", "rank": 15, "score": 449854.62820107746 }, { "content": "fn main() { let x = f(); }\n", "file_path": "src/test/run-pass/return-nil.rs", "rank": 16, "score": 446532.8539597242 }, { "content": "fn decl_cdecl_fn(llmod: ModuleRef, name: ~str, llty: TypeRef) -> ValueRef {\n\n return decl_fn(llmod, name, lib::llvm::CCallConv, llty);\n\n}\n\n\n\n\n", "file_path": "src/rustc/middle/trans/base.rs", "rank": 17, "score": 438813.923292815 }, { "content": "fn main(args: ~[~str]) { return; }\n", "file_path": "src/test/run-pass/type-ptr.rs", "rank": 18, "score": 435065.33888822177 }, { "content": "fn get_item_val(ccx: @crate_ctxt, id: ast::node_id) -> ValueRef {\n\n debug!(\"get_item_val(id=`%?`)\", id);\n\n let tcx = ccx.tcx;\n\n match ccx.item_vals.find(id) {\n\n some(v) => v,\n\n none => {\n\n let mut exprt = false;\n\n let val = match ccx.tcx.items.get(id) {\n\n ast_map::node_item(i, pth) => {\n\n let my_path = vec::append(*pth, ~[path_name(i.ident)]);\n\n match i.node {\n\n ast::item_const(_, _) => {\n\n let typ = ty::node_id_to_type(ccx.tcx, i.id);\n\n let s = mangle_exported_name(ccx, my_path, typ);\n\n let g = str::as_c_str(s, |buf| {\n\n llvm::LLVMAddGlobal(ccx.llmod, type_of(ccx, typ), buf)\n\n });\n\n ccx.item_symbols.insert(i.id, s);\n\n g\n\n }\n", "file_path": "src/rustc/middle/trans/base.rs", "rank": 19, "score": 434568.7850266979 }, { "content": "fn new_fn_ctxt(ccx: @crate_ctxt, path: path, llfndecl: ValueRef,\n\n sp: option<span>) -> fn_ctxt {\n\n return new_fn_ctxt_w_id(ccx, path, llfndecl, -1, none, sp);\n\n}\n\n\n\n// NB: must keep 4 fns in sync:\n\n//\n\n// - type_of_fn\n\n// - create_llargs_for_fn_args.\n\n// - new_fn_ctxt\n\n// - trans_args\n\n\n", "file_path": "src/rustc/middle/trans/base.rs", "rank": 20, "score": 432856.82071610226 }, { "content": "fn field_expr(f: ast::field) -> @ast::expr { return f.node.expr; }\n\n\n", "file_path": "src/rustc/util/common.rs", "rank": 21, "score": 429557.5028497504 }, { "content": "fn trans_foreign_fn(ccx: @crate_ctxt, path: ast_map::path, decl: ast::fn_decl,\n\n body: ast::blk, llwrapfn: ValueRef, id: ast::node_id) {\n\n\n\n let _icx = ccx.insn_ctxt(\"foreign::build_foreign_fn\");\n\n\n\n fn build_rust_fn(ccx: @crate_ctxt, path: ast_map::path,\n\n decl: ast::fn_decl, body: ast::blk,\n\n id: ast::node_id) -> ValueRef {\n\n let _icx = ccx.insn_ctxt(\"foreign::foreign::build_rust_fn\");\n\n let t = ty::node_id_to_type(ccx.tcx, id);\n\n let ps = link::mangle_internal_name_by_path(\n\n ccx, vec::append_one(path, ast_map::path_name(\n\n syntax::parse::token::special_idents::clownshoe_abi\n\n )));\n\n let llty = type_of_fn_from_ty(ccx, t);\n\n let llfndecl = decl_internal_cdecl_fn(ccx.llmod, ps, llty);\n\n trans_fn(ccx, path, decl, body, llfndecl, no_self, none, id);\n\n return llfndecl;\n\n }\n\n\n", "file_path": "src/rustc/middle/trans/foreign.rs", "rank": 22, "score": 429166.78400713165 }, { "content": "// trans_closure: Builds an LLVM function out of a source function.\n\n// If the function closes over its environment a closure will be\n\n// returned.\n\nfn trans_closure(ccx: @crate_ctxt, path: path, decl: ast::fn_decl,\n\n body: ast::blk, llfndecl: ValueRef,\n\n ty_self: self_arg,\n\n param_substs: option<param_substs>,\n\n id: ast::node_id,\n\n maybe_load_env: fn(fn_ctxt),\n\n finish: fn(block)) {\n\n let _icx = ccx.insn_ctxt(\"trans_closure\");\n\n set_uwtable(llfndecl);\n\n\n\n // Set up arguments to the function.\n\n let fcx = new_fn_ctxt_w_id(ccx, path, llfndecl, id, param_substs,\n\n some(body.span));\n\n create_llargs_for_fn_args(fcx, ty_self, decl.inputs);\n\n\n\n // Set GC for function.\n\n if ccx.sess.opts.gc {\n\n do str::as_c_str(\"generic\") |strategy| {\n\n llvm::LLVMSetGC(fcx.llfn, strategy);\n\n }\n", "file_path": "src/rustc/middle/trans/base.rs", "rank": 23, "score": 425707.1594135277 }, { "content": "fn trans_class_ctor(ccx: @crate_ctxt, path: path, decl: ast::fn_decl,\n\n body: ast::blk, llctor_decl: ValueRef,\n\n psubsts: param_substs, ctor_id: ast::node_id,\n\n parent_id: ast::def_id, sp: span) {\n\n // Add ctor to the ctor map\n\n ccx.class_ctors.insert(ctor_id, parent_id);\n\n\n\n // Translate the ctor\n\n\n\n // Set up the type for the result of the ctor\n\n // kludgy -- this wouldn't be necessary if the typechecker\n\n // special-cased constructors, then we could just look up\n\n // the ctor's return type.\n\n let rslt_ty = ty::mk_class(ccx.tcx, parent_id,\n\n dummy_substs(psubsts.tys));\n\n\n\n // Make the fn context\n\n let fcx = new_fn_ctxt_w_id(ccx, path, llctor_decl, ctor_id,\n\n some(psubsts), some(sp));\n\n create_llargs_for_fn_args(fcx, no_self, decl.inputs);\n", "file_path": "src/rustc/middle/trans/base.rs", "rank": 24, "score": 422565.4076526762 }, { "content": "fn invoke(bcx: block, llfn: ValueRef, llargs: ~[ValueRef]) -> block {\n\n let _icx = bcx.insn_ctxt(\"invoke_\");\n\n if bcx.unreachable { return bcx; }\n\n if need_invoke(bcx) {\n\n log(debug, ~\"invoking\");\n\n let normal_bcx = sub_block(bcx, ~\"normal return\");\n\n Invoke(bcx, llfn, llargs, normal_bcx.llbb, get_landing_pad(bcx));\n\n return normal_bcx;\n\n } else {\n\n log(debug, ~\"calling\");\n\n Call(bcx, llfn, llargs);\n\n return bcx;\n\n }\n\n}\n\n\n", "file_path": "src/rustc/middle/trans/base.rs", "rank": 25, "score": 421410.2435303456 }, { "content": "fn C_named_struct(T: TypeRef, elts: ~[ValueRef]) -> ValueRef unsafe {\n\n return llvm::LLVMConstNamedStruct(T, vec::unsafe::to_ptr(elts),\n\n elts.len() as c_uint);\n\n}\n\n\n", "file_path": "src/rustc/middle/trans/common.rs", "rank": 26, "score": 417461.80499330856 }, { "content": "fn main() { let mut a: option<int> = some::<int>(@10); a = none::<int>; }\n", "file_path": "src/test/run-pass/generic-tag.rs", "rank": 27, "score": 415867.03692217753 }, { "content": "fn item_path(ccx: @crate_ctxt, i: @ast::item) -> path {\n\n vec::append(\n\n *match ccx.tcx.items.get(i.id) {\n\n ast_map::node_item(_, p) => p,\n\n // separate map for paths?\n\n _ => fail ~\"item_path\"\n\n },\n\n ~[path_name(i.ident)])\n\n}\n\n\n\n/* If there's already a symbol for the dtor with <id> and substs <substs>,\n\n return it; otherwise, create one and register it, returning it as well */\n", "file_path": "src/rustc/middle/trans/base.rs", "rank": 28, "score": 413259.86499985284 }, { "content": "fn main() { let x: a = {a: 1}; assert (a(x) == 1); }\n", "file_path": "src/test/run-pass/type-namespace.rs", "rank": 29, "score": 408177.5187986221 }, { "content": "fn path_node(ids: ~[ast::ident]) -> @ast::path {\n\n @{span: dummy_sp(), global: false, idents: ids, rp: none, types: ~[]}\n\n}\n\n\n", "file_path": "src/rustc/front/test.rs", "rank": 30, "score": 407527.462691371 }, { "content": "fn main() { mk_raw_ty(ty_nil, none::<~str>); }\n", "file_path": "src/test/run-pass/alias-uninit-value.rs", "rank": 31, "score": 404892.0363436685 }, { "content": "fn g(a: *int) -> *int { let b = f(a); return b; }\n\n\n", "file_path": "src/test/run-pass/type-ptr.rs", "rank": 32, "score": 404237.26770845003 }, { "content": "// Create a _rust_main(args: ~[str]) function which will be called from the\n\n// runtime rust_start function\n\nfn create_main_wrapper(ccx: @crate_ctxt, sp: span, main_llfn: ValueRef,\n\n main_node_type: ty::t) {\n\n\n\n if ccx.main_fn != none::<ValueRef> {\n\n ccx.sess.span_fatal(sp, ~\"multiple 'main' functions\");\n\n }\n\n\n\n let main_takes_argv =\n\n // invariant!\n\n match ty::get(main_node_type).struct {\n\n ty::ty_fn({inputs, _}) => inputs.len() != 0u,\n\n _ => ccx.sess.span_fatal(sp, ~\"main has a non-function type\")\n\n };\n\n\n\n let llfn = create_main(ccx, main_llfn, main_takes_argv);\n\n ccx.main_fn = some(llfn);\n\n create_entry_fn(ccx, llfn);\n\n\n\n fn create_main(ccx: @crate_ctxt, main_llfn: ValueRef,\n\n takes_argv: bool) -> ValueRef {\n", "file_path": "src/rustc/middle/trans/base.rs", "rank": 33, "score": 402367.14148135344 }, { "content": "fn T_taskptr(cx: @crate_ctxt) -> TypeRef { return T_ptr(cx.task_type); }\n\n\n\n\n", "file_path": "src/rustc/middle/trans/common.rs", "rank": 34, "score": 396776.63259212417 }, { "content": "fn f() { let x: () = (); return x; }\n\n\n", "file_path": "src/test/run-pass/return-nil.rs", "rank": 35, "score": 396036.3491528918 }, { "content": "fn main() { return ::f(); }\n", "file_path": "src/test/run-pass/expr-scope.rs", "rank": 36, "score": 393987.9932682081 }, { "content": "// -*- rust -*-\n\nfn main() { if 1 == 1 { return; } debug!(\"Paul is dead\"); }\n", "file_path": "src/test/run-pass/dead-code-one-arm-if.rs", "rank": 37, "score": 392665.90697935293 }, { "content": "type val_pair_fn = fn@(block, ValueRef, ValueRef) -> block;\n", "file_path": "src/rustc/middle/trans/base.rs", "rank": 38, "score": 392622.9544844898 }, { "content": "type node_id_gen = fn@() -> ast::node_id;\n\n\n", "file_path": "src/rustc/front/test.rs", "rank": 39, "score": 390209.4302642428 }, { "content": "fn T_typaram_ptr(tn: type_names) -> TypeRef { return T_ptr(T_typaram(tn)); }\n\n\n", "file_path": "src/rustc/middle/trans/common.rs", "rank": 40, "score": 389780.3657589003 }, { "content": "fn mk_name_value_item(name: ~str, +value: ast::lit)\n\n -> @ast::meta_item {\n\n return @dummy_spanned(ast::meta_name_value(name, value));\n\n}\n\n\n", "file_path": "src/libsyntax/attr.rs", "rank": 41, "score": 389676.76187954994 }, { "content": "fn check_method(ccx: @crate_ctxt, method: @ast::method,\n\n self_ty: ty::t, self_impl_def_id: ast::def_id) {\n\n let self_info = {self_ty: self_ty,\n\n self_id: method.self_id,\n\n def_id: self_impl_def_id,\n\n explicit_self: method.self_ty };\n\n check_bare_fn(ccx, method.decl, method.body, method.id, some(self_info));\n\n}\n\n\n", "file_path": "src/rustc/middle/typeck/check.rs", "rank": 42, "score": 388264.2453723453 }, { "content": "fn T_named_struct(name: ~str) -> TypeRef {\n\n let c = llvm::LLVMGetGlobalContext();\n\n return str::as_c_str(name, |buf| llvm::LLVMStructCreateNamed(c, buf));\n\n}\n\n\n", "file_path": "src/rustc/middle/trans/common.rs", "rank": 43, "score": 387631.565885187 }, { "content": "fn lookup_discriminant(ccx: @crate_ctxt, vid: ast::def_id) -> ValueRef {\n\n let _icx = ccx.insn_ctxt(\"lookup_discriminant\");\n\n match ccx.discrims.find(vid) {\n\n none => {\n\n // It's an external discriminant that we haven't seen yet.\n\n assert (vid.crate != ast::local_crate);\n\n let sym = csearch::get_symbol(ccx.sess.cstore, vid);\n\n let gvar = str::as_c_str(sym, |buf| {\n\n llvm::LLVMAddGlobal(ccx.llmod, ccx.int_type, buf)\n\n });\n\n lib::llvm::SetLinkage(gvar, lib::llvm::ExternalLinkage);\n\n llvm::LLVMSetGlobalConstant(gvar, True);\n\n ccx.discrims.insert(vid, gvar);\n\n return gvar;\n\n }\n\n some(llval) => return llval,\n\n }\n\n}\n\n\n", "file_path": "src/rustc/middle/trans/base.rs", "rank": 44, "score": 387219.1804678062 }, { "content": "fn T_uint_ty(cx: @crate_ctxt, t: ast::uint_ty) -> TypeRef {\n\n match t {\n\n ast::ty_u => cx.int_type,\n\n ast::ty_u8 => T_i8(),\n\n ast::ty_u16 => T_i16(),\n\n ast::ty_u32 => T_i32(),\n\n ast::ty_u64 => T_i64()\n\n }\n\n}\n\n\n", "file_path": "src/rustc/middle/trans/common.rs", "rank": 45, "score": 387054.758642087 }, { "content": "fn T_int_ty(cx: @crate_ctxt, t: ast::int_ty) -> TypeRef {\n\n match t {\n\n ast::ty_i => cx.int_type,\n\n ast::ty_char => T_char(),\n\n ast::ty_i8 => T_i8(),\n\n ast::ty_i16 => T_i16(),\n\n ast::ty_i32 => T_i32(),\n\n ast::ty_i64 => T_i64()\n\n }\n\n}\n\n\n", "file_path": "src/rustc/middle/trans/common.rs", "rank": 46, "score": 387054.758642087 }, { "content": "fn T_float_ty(cx: @crate_ctxt, t: ast::float_ty) -> TypeRef {\n\n match t {\n\n ast::ty_f => cx.float_type,\n\n ast::ty_f32 => T_f32(),\n\n ast::ty_f64 => T_f64()\n\n }\n\n}\n\n\n", "file_path": "src/rustc/middle/trans/common.rs", "rank": 47, "score": 387054.758642087 }, { "content": "fn fill_fn_pair(bcx: block, pair: ValueRef, llfn: ValueRef,\n\n llenvptr: ValueRef) {\n\n let ccx = bcx.ccx();\n\n let code_cell = GEPi(bcx, pair, ~[0u, abi::fn_field_code]);\n\n Store(bcx, llfn, code_cell);\n\n let env_cell = GEPi(bcx, pair, ~[0u, abi::fn_field_box]);\n\n let llenvblobptr = PointerCast(bcx, llenvptr, T_opaque_box_ptr(ccx));\n\n Store(bcx, llenvblobptr, env_cell);\n\n}\n\n\n", "file_path": "src/rustc/middle/trans/base.rs", "rank": 48, "score": 385132.73492886266 }, { "content": "#[auto_serialize]\n\ntype path_list_ident_ = {name: ident, id: node_id};\n\n\n", "file_path": "src/libsyntax/ast.rs", "rank": 49, "score": 384577.7149017743 }, { "content": "fn make_generic_glue(ccx: @crate_ctxt, t: ty::t, llfn: ValueRef,\n\n helper: glue_helper, name: ~str)\n\n -> ValueRef {\n\n let _icx = ccx.insn_ctxt(\"make_generic_glue\");\n\n if !ccx.sess.trans_stats() {\n\n return make_generic_glue_inner(ccx, t, llfn, helper);\n\n }\n\n\n\n let start = time::get_time();\n\n let llval = make_generic_glue_inner(ccx, t, llfn, helper);\n\n let end = time::get_time();\n\n log_fn_time(ccx, ~\"glue \" + name + ~\" \" + ty_to_short_str(ccx.tcx, t),\n\n start, end);\n\n return llval;\n\n}\n\n\n", "file_path": "src/rustc/middle/trans/base.rs", "rank": 50, "score": 384529.9075015135 }, { "content": "fn push_rtcall(ccx: @crate_ctxt, name: ~str, did: ast::def_id) {\n\n if ccx.rtcalls.contains_key(name) {\n\n fail fmt!(\"multiple definitions for runtime call %s\", name);\n\n }\n\n ccx.rtcalls.insert(name, did);\n\n}\n\n\n", "file_path": "src/rustc/middle/trans/base.rs", "rank": 51, "score": 383955.79253609723 }, { "content": "// Regression test for issue #388\n\nfn main() { let x = { { @10 } }; }\n", "file_path": "src/test/run-pass/expr-block-ref.rs", "rank": 52, "score": 382425.81492540555 }, { "content": "fn main() { return foo::g(); }\n\n\n", "file_path": "src/test/run-pass/global-scope.rs", "rank": 53, "score": 382402.76130580995 }, { "content": "// Regression test for issue #388\n\nfn main() { let x = if false { @0u } else if true { @10u } else { @0u }; }\n", "file_path": "src/test/run-pass/expr-elseif-ref2.rs", "rank": 54, "score": 381662.99084699946 }, { "content": "// -*- rust -*-\n\nfn main() { let x: int = 10; }\n", "file_path": "src/test/run-pass/int.rs", "rank": 55, "score": 380361.7954385661 }, { "content": "// Creates the standard set of basic blocks for a function\n\nfn mk_standard_basic_blocks(llfn: ValueRef) ->\n\n {sa: BasicBlockRef, ca: BasicBlockRef, rt: BasicBlockRef} {\n\n {sa: str::as_c_str(~\"static_allocas\",\n\n |buf| llvm::LLVMAppendBasicBlock(llfn, buf)),\n\n ca: str::as_c_str(~\"load_env\",\n\n |buf| llvm::LLVMAppendBasicBlock(llfn, buf)),\n\n rt: str::as_c_str(~\"return\",\n\n |buf| llvm::LLVMAppendBasicBlock(llfn, buf))}\n\n}\n\n\n\n\n", "file_path": "src/rustc/middle/trans/base.rs", "rank": 56, "score": 380136.25541359565 }, { "content": "fn main() { let x: @int = @10; let y: int = *x; }\n", "file_path": "src/test/run-pass/deref.rs", "rank": 57, "score": 380002.81067385944 }, { "content": "fn no_op_type_glue_name() -> ~str { return ~\"rust_no_op_type_glue\"; }\n\n//\n\n// Local Variables:\n\n// mode: rust\n\n// fill-column: 78;\n\n// indent-tabs-mode: nil\n\n// c-basic-offset: 4\n\n// buffer-file-coding-system: utf-8-unix\n\n// End:\n\n//\n", "file_path": "src/rustc/back/abi.rs", "rank": 58, "score": 379343.397882208 }, { "content": "fn main() { let b: x = ~[]; }\n", "file_path": "src/test/compile-fail/infinite-vec-type-recursion.rs", "rank": 59, "score": 379175.30490604043 }, { "content": "fn main() { let quux: @~[uint] = @~[]; }\n", "file_path": "src/test/run-pass/vector-no-ann-2.rs", "rank": 60, "score": 378134.4641748691 }, { "content": "fn main() { let i: (); i = f(()); }\n", "file_path": "src/test/compile-fail/arg-type-mismatch.rs", "rank": 61, "score": 376963.7754355582 }, { "content": "fn main() { let c = a(3); }\n", "file_path": "src/test/run-pass/generic-tag-local.rs", "rank": 62, "score": 375903.01919030433 }, { "content": "fn main() { let x = m::f(); }\n", "file_path": "src/test/run-pass/mod-view-items.rs", "rank": 63, "score": 375903.01919030433 }, { "content": "fn main() { let v = foo::a; }\n", "file_path": "src/test/run-pass/export-glob.rs", "rank": 64, "score": 375903.01919030433 }, { "content": "fn main() { let x = (); match x { () => { } } }\n", "file_path": "src/test/run-pass/nil-pattern.rs", "rank": 65, "score": 375903.01919030433 }, { "content": "// xfail-test\n\nfn main() { let early_error: fn@(str) -> ! = {|msg| fail }; }\n\n\n", "file_path": "src/test/run-pass/issue-1516.rs", "rank": 66, "score": 375000.5200408246 }, { "content": "fn main() { return f(\"main\"); debug!(\"Paul is dead\"); }\n\n\n", "file_path": "src/test/compile-fail/dead-code-ret.rs", "rank": 67, "score": 374189.1493428196 }, { "content": "fn T_char() -> TypeRef { return T_i32(); }\n\n\n", "file_path": "src/rustc/middle/trans/common.rs", "rank": 68, "score": 372639.9141854171 }, { "content": "fn T_bool() -> TypeRef { return T_i1(); }\n\n\n", "file_path": "src/rustc/middle/trans/common.rs", "rank": 69, "score": 372639.9141854171 }, { "content": "fn arrayalloca(cx: block, t: TypeRef, v: ValueRef) -> ValueRef {\n\n let _icx = cx.insn_ctxt(\"arrayalloca\");\n\n if cx.unreachable { return llvm::LLVMGetUndef(t); }\n\n return ArrayAlloca(\n\n raw_block(cx.fcx, false, cx.fcx.llstaticallocas), t, v);\n\n}\n\n\n", "file_path": "src/rustc/middle/trans/base.rs", "rank": 70, "score": 371774.71810562164 }, { "content": "fn main() { let x = some(~\"hi\"); }\n", "file_path": "src/test/run-pass/generic-tag-corruption.rs", "rank": 71, "score": 371611.66843976785 }, { "content": "fn first_attr_value_str_by_name(attrs: ~[ast::attribute], name: ~str)\n\n -> option<~str> {\n\n\n\n let mattrs = find_attrs_by_name(attrs, name);\n\n if vec::len(mattrs) > 0u {\n\n return get_meta_item_value_str(attr_meta(mattrs[0]));\n\n }\n\n return option::none;\n\n}\n\n\n", "file_path": "src/libsyntax/attr.rs", "rank": 72, "score": 371050.1360547418 }, { "content": "fn monomorphic_fn(ccx: @crate_ctxt, fn_id: ast::def_id,\n\n real_substs: ~[ty::t],\n\n vtables: option<typeck::vtable_res>,\n\n ref_id: option<ast::node_id>)\n\n -> {val: ValueRef, must_cast: bool} {\n\n let _icx = ccx.insn_ctxt(\"monomorphic_fn\");\n\n let mut must_cast = false;\n\n let substs = vec::map(real_substs, |t| {\n\n match normalize_for_monomorphization(ccx.tcx, t) {\n\n some(t) => { must_cast = true; t }\n\n none => t\n\n }\n\n });\n\n\n\n for real_substs.each() |s| { assert !ty::type_has_params(s); }\n\n for substs.each() |s| { assert !ty::type_has_params(s); }\n\n let param_uses = type_use::type_uses_for(ccx, fn_id, substs.len());\n\n let hash_id = make_mono_id(ccx, fn_id, substs, vtables, some(param_uses));\n\n if vec::any(hash_id.params,\n\n |p| match p { mono_precise(_, _) => false, _ => true }) {\n", "file_path": "src/rustc/middle/trans/base.rs", "rank": 73, "score": 370052.00580656354 }, { "content": "fn C_array(ty: TypeRef, elts: ~[ValueRef]) -> ValueRef unsafe {\n\n return llvm::LLVMConstArray(ty, vec::unsafe::to_ptr(elts),\n\n elts.len() as c_uint);\n\n}\n\n\n", "file_path": "src/rustc/middle/trans/common.rs", "rank": 74, "score": 369967.5898073818 }, { "content": "fn main() { let x = 10; test(x); }\n", "file_path": "src/test/run-pass/move-arg.rs", "rank": 75, "score": 369910.80175258423 }, { "content": "fn main() { let a: bool = 1i; let b: int = true; }\n", "file_path": "src/test/compile-fail/type-mismatch-multiple.rs", "rank": 76, "score": 369638.0943251364 }, { "content": "fn test_ret() { let x: @int = return; }\n\n\n", "file_path": "src/test/run-pass/terminate-in-initializer.rs", "rank": 77, "score": 369090.4367196031 }, { "content": "fn main() { let x = 10, y = x; assert (y == 10); }\n", "file_path": "src/test/run-pass/multi-let.rs", "rank": 78, "score": 368837.77833233407 }, { "content": "fn T_empty_struct() -> TypeRef { return T_struct(~[]); }\n\n\n", "file_path": "src/rustc/middle/trans/common.rs", "rank": 79, "score": 368770.53897735587 }, { "content": "fn f<T: copy>() -> option<T> { return none; }\n\n\n", "file_path": "src/test/run-pass/ret-none.rs", "rank": 80, "score": 368580.74343552627 }, { "content": "fn main() { let x = 10; let x = x + 20; assert (x == 30); foo(~[]); }\n", "file_path": "src/test/run-pass/shadow.rs", "rank": 81, "score": 367951.36081049533 }, { "content": "fn main() { let i: (@int, int) = (@10, 10); let (a, _) = i; }\n", "file_path": "src/test/run-pass/box-in-tup.rs", "rank": 82, "score": 367813.9993759395 }, { "content": "fn main() { let _kitty = cat(~\"Spotty\"); }\n", "file_path": "src/test/run-pass/class-attributes-1.rs", "rank": 83, "score": 367478.48681980686 }, { "content": "fn main() { let v = foo::t1; }\n", "file_path": "src/test/run-pass/export-tag-variant.rs", "rank": 84, "score": 367478.48681980686 }, { "content": "fn main() { let i: int; i = f(); }\n", "file_path": "src/test/compile-fail/output-type-mismatch.rs", "rank": 85, "score": 366660.29173321906 }, { "content": "fn main(args: ~[~str]) { foo::bar(0u); }\n", "file_path": "src/test/run-pass/path.rs", "rank": 86, "score": 365629.1987837737 }, { "content": "// Simple wrapper around GEP that takes an array of ints and wraps them\n\n// in C_i32()\n\nfn GEPi(cx: block, base: ValueRef, ixs: ~[uint]) -> ValueRef {\n\n let mut v: ~[ValueRef] = ~[];\n\n for vec::each(ixs) |i| { vec::push(v, C_i32(i as i32)); }\n\n count_insn(cx, \"gepi\");\n\n return InBoundsGEP(cx, base, v);\n\n}\n\n\n", "file_path": "src/rustc/middle/trans/build.rs", "rank": 87, "score": 365463.9480421066 }, { "content": "fn main() { let x = f(~3); log(debug, *x); }\n", "file_path": "src/test/run-pass/generic-fn-unique.rs", "rank": 88, "score": 364764.6059918113 }, { "content": "fn main() { let x = f(@3); log(debug, *x); }\n", "file_path": "src/test/run-pass/generic-fn-box.rs", "rank": 89, "score": 364764.6059918113 }, { "content": "// -*- rust -*-\n\nfn main() { let x: uint = 10 as uint; }\n", "file_path": "src/test/run-pass/uint.rs", "rank": 90, "score": 364386.95508218254 }, { "content": "fn last_meta_item_value_str_by_name(items: ~[@ast::meta_item], name: ~str)\n\n -> option<~str> {\n\n\n\n match last_meta_item_by_name(items, name) {\n\n some(item) => match attr::get_meta_item_value_str(item) {\n\n some(value) => some(value),\n\n none => none\n\n },\n\n none => none\n\n }\n\n}\n\n\n", "file_path": "src/libsyntax/attr.rs", "rank": 91, "score": 364028.83816572465 }, { "content": "fn main() { let x: int = 42; let y: int = id(x); assert (x == y); }\n", "file_path": "src/test/run-pass/generic-fn-infer.rs", "rank": 92, "score": 363936.0904410076 }, { "content": "fn item_path(cx: ctxt, id: ast::def_id) -> ast_map::path {\n\n if id.crate != ast::local_crate {\n\n csearch::get_item_path(cx, id)\n\n } else {\n\n let node = cx.items.get(id.node);\n\n match node {\n\n ast_map::node_item(item, path) => {\n\n let item_elt = match item.node {\n\n item_mod(_) | item_foreign_mod(_) => {\n\n ast_map::path_mod(item.ident)\n\n }\n\n _ => {\n\n ast_map::path_name(item.ident)\n\n }\n\n };\n\n vec::append_one(*path, item_elt)\n\n }\n\n\n\n ast_map::node_foreign_item(nitem, _, path) => {\n\n vec::append_one(*path, ast_map::path_name(nitem.ident))\n", "file_path": "src/rustc/middle/ty.rs", "rank": 93, "score": 362434.59547021193 }, { "content": "// Structural comparison: a rather involved form of glue.\n\nfn maybe_name_value(cx: @crate_ctxt, v: ValueRef, s: ~str) {\n\n if cx.sess.opts.save_temps {\n\n let _: () = str::as_c_str(s, |buf| llvm::LLVMSetValueName(v, buf));\n\n }\n\n}\n\n\n\n\n", "file_path": "src/rustc/middle/trans/base.rs", "rank": 94, "score": 362271.7568786853 }, { "content": "fn main() { let x = @{x: 1, y: 2, z: 3}; let y <- x; assert (y.y == 2); }\n", "file_path": "src/test/run-pass/move-2.rs", "rank": 95, "score": 361893.75113046647 }, { "content": "fn ArrayAlloca(cx: block, Ty: TypeRef, Val: ValueRef) -> ValueRef {\n\n if cx.unreachable { return llvm::LLVMGetUndef(T_ptr(Ty)); }\n\n count_insn(cx, \"arrayalloca\");\n\n return llvm::LLVMBuildArrayAlloca(B(cx), Ty, Val, noname());\n\n}\n\n\n", "file_path": "src/rustc/middle/trans/build.rs", "rank": 96, "score": 361839.68465213355 }, { "content": "fn ArrayMalloc(cx: block, Ty: TypeRef, Val: ValueRef) -> ValueRef {\n\n if cx.unreachable { return llvm::LLVMGetUndef(T_ptr(T_i8())); }\n\n count_insn(cx, \"arraymalloc\");\n\n return llvm::LLVMBuildArrayMalloc(B(cx), Ty, Val, noname());\n\n}\n\n\n", "file_path": "src/rustc/middle/trans/build.rs", "rank": 97, "score": 361839.68465213355 }, { "content": "fn VAArg(cx: block, list: ValueRef, Ty: TypeRef) -> ValueRef {\n\n if cx.unreachable { return llvm::LLVMGetUndef(Ty); }\n\n count_insn(cx, \"vaarg\");\n\n return llvm::LLVMBuildVAArg(B(cx), list, Ty, noname());\n\n}\n\n\n", "file_path": "src/rustc/middle/trans/build.rs", "rank": 98, "score": 361839.68465213355 }, { "content": "fn Trunc(cx: block, Val: ValueRef, DestTy: TypeRef) -> ValueRef {\n\n if cx.unreachable { return llvm::LLVMGetUndef(DestTy); }\n\n count_insn(cx, \"trunc\");\n\n return llvm::LLVMBuildTrunc(B(cx), Val, DestTy, noname());\n\n}\n\n\n", "file_path": "src/rustc/middle/trans/build.rs", "rank": 99, "score": 361839.68465213355 } ]
Rust
src/dms/font.rs
mnit-rtmc/ntcip
ccc7d59869d4fc406f7f0d0550112e5b3b390bb2
use crate::dms::multi::SyntaxError; use crate::dms::Result; use log::debug; use pix::{rgb::SRgb8, Raster}; use std::collections::HashMap; #[derive(Deserialize, Serialize)] pub struct Character { number: u16, width: u8, #[serde(with = "super::base64")] bitmap: Vec<u8>, } #[derive(Deserialize, Serialize)] pub struct Font { number: u8, name: String, height: u8, char_spacing: u8, line_spacing: u8, characters: Vec<Character>, version_id: u16, } #[derive(Default)] pub struct FontCache { fonts: HashMap<u8, Font>, } impl Character { pub fn number(&self) -> u16 { self.number } pub fn width(&self) -> u8 { self.width } fn render_char( &self, page: &mut Raster<SRgb8>, x: i32, y: i32, height: i32, cf: SRgb8, ) { let width = i32::from(self.width); debug!( "render_char: {} @ {},{} width: {}", self.number, x, y, width ); let mut xx = 0; let mut yy = 0; for by in &self.bitmap { for bi in 0..8 { if by >> (7 - bi) & 1 != 0 { *page.pixel_mut(x + xx, y + yy) = cf; } xx += 1; if xx >= width { xx = 0; yy += 1; if yy >= height { break; } } } } } } impl<'a> Font { pub fn number(&self) -> u8 { self.number } pub fn name(&self) -> &str { &self.name } pub fn height(&self) -> u8 { self.height } pub fn char_spacing(&self) -> u8 { self.char_spacing } pub fn line_spacing(&self) -> u8 { self.line_spacing } pub fn character(&'a self, ch: char) -> Result<&'a Character> { let code_point = u32::from(ch); if code_point <= u32::from(std::u16::MAX) { let n = code_point as u16; if let Some(c) = self.characters.iter().find(|c| c.number == n) { return Ok(c); } } Err(SyntaxError::CharacterNotDefined(ch)) } pub fn text_width(&self, text: &str, cs: Option<u16>) -> Result<u16> { let mut width = 0; let cs = cs.unwrap_or_else(|| u16::from(self.char_spacing)); for ch in text.chars() { let c = self.character(ch)?; if width > 0 { width += cs; } width += u16::from(c.width()); } Ok(width) } pub fn render_text( &self, page: &mut Raster<SRgb8>, text: &str, x: i32, y: i32, cs: i32, cf: SRgb8, ) -> Result<()> { let height = i32::from(self.height()); debug!( "render_text: font number {}, name {}", self.number(), self.name() ); debug!("render_text: {} @ {},{} height: {}", text, x, y, height); let mut xx = 0; for ch in text.chars() { let c = self.character(ch)?; if xx > 0 { xx += cs; } c.render_char(page, x + xx, y, height, cf); xx += i32::from(c.width()); } Ok(()) } pub fn version_id(&self) -> u16 { self.version_id } } impl FontCache { pub fn insert(&mut self, font: Font) { self.fonts.insert(font.number(), font); } pub fn lookup<'a>( &'a self, fnum: u8, version_id: Option<u16>, ) -> Result<&'a Font> { match (self.fonts.get(&fnum), version_id) { (Some(f), Some(vid)) => { if vid == f.version_id { Ok(f) } else { Err(SyntaxError::FontVersionID) } } (Some(f), None) => Ok(f), (None, _) => Err(SyntaxError::FontNotDefined(fnum)), } } pub fn lookup_name<'a>(&'a self, name: &str) -> Option<&'a Font> { self.fonts.values().find(|f| f.name() == name) } }
use crate::dms::multi::SyntaxError; use crate::dms::Result; use log::debug; use pix::{rgb::SRgb8, Raster}; use std::collections::HashMap; #[derive(Deserialize, Serialize)] pub struct Character { number: u16, width: u8, #[serde(with = "super::base64")] bitmap: Vec<u8>, } #[derive(Deserialize, Serialize)] pub struct Font { number: u8, name: String, height: u8, char_spacing: u8, line_spacing: u8, characters: Vec<Character>, version_id: u16, } #[derive(Default)] pub struct FontCache { fonts: HashMap<u8, Font>, } impl Character { pub fn number(&self) -> u16 { self.number } pub fn width(&self) -> u8 { self.width } fn render_char( &self, page: &mut Raster<SRgb8>, x: i32, y: i32, height: i32, cf: SRgb8, ) { let width = i32::from(self.width); debug!( "render_char: {} @ {},{} width: {}", self.number, x, y, width ); let mut xx = 0; let mut yy = 0; for by in &self.bitmap { for bi in 0..8 { if by >> (7 - bi) & 1 != 0 { *page.pixel_mut(x + xx, y + yy) = cf; } xx += 1; if xx >= width { xx = 0; yy += 1; if yy >= height { break; } } } } } } impl<'a> Font { pub fn number(&self) -> u8 { self.number } pub fn name(&self) -> &str { &self.name } pub fn height(&self) -> u8 { self.height } pub fn char_spacing(&self) -> u8 { self.char_spacing } pub fn line_spacing(&self) -> u8 { self.line_spacing } pub fn character(&'a self, ch: char) -> Result<&'a Character> { let code_point = u32::from(ch); if code_point <= u32::from(std::u16::MAX) { let n = code_point as u16; if let Some(c) = self.characters.iter().find(|c| c.number == n) { return Ok(c); } } Err(SyntaxError::CharacterNotDefined(ch)) } pub fn text_width(&self, text: &str, cs: Option<u16>) -> Result<u16> { let mut width = 0; let cs = cs.unwrap_or_else(|| u16::from(self.char_spacing)); for ch in text.chars() { let c = self.character(ch)?; if width > 0 { width += cs; } width += u16::from(c.width()); } Ok(width) } pub fn render_text( &self, page: &mut Raster<SRgb8>,
pub fn version_id(&self) -> u16 { self.version_id } } impl FontCache { pub fn insert(&mut self, font: Font) { self.fonts.insert(font.number(), font); } pub fn lookup<'a>( &'a self, fnum: u8, version_id: Option<u16>, ) -> Result<&'a Font> { match (self.fonts.get(&fnum), version_id) { (Some(f), Some(vid)) => { if vid == f.version_id { Ok(f) } else { Err(SyntaxError::FontVersionID) } } (Some(f), None) => Ok(f), (None, _) => Err(SyntaxError::FontNotDefined(fnum)), } } pub fn lookup_name<'a>(&'a self, name: &str) -> Option<&'a Font> { self.fonts.values().find(|f| f.name() == name) } }
text: &str, x: i32, y: i32, cs: i32, cf: SRgb8, ) -> Result<()> { let height = i32::from(self.height()); debug!( "render_text: font number {}, name {}", self.number(), self.name() ); debug!("render_text: {} @ {},{} height: {}", text, x, y, height); let mut xx = 0; for ch in text.chars() { let c = self.character(ch)?; if xx > 0 { xx += cs; } c.render_char(page, x + xx, y, height, cf); xx += i32::from(c.width()); } Ok(()) }
function_block-function_prefix_line
[ { "content": "/// Normalize a MULTI string.\n\npub fn normalize(ms: &str) -> String {\n\n let mut s = String::with_capacity(ms.len());\n\n for t in Parser::new(ms) {\n\n if let Ok(v) = t {\n\n s.push_str(&v.to_string());\n\n }\n\n }\n\n s\n\n}\n\n\n\n#[cfg(test)]\n\nmod test {\n\n use super::*;\n\n\n\n #[test]\n\n fn value_size() {\n\n assert_eq!(std::mem::size_of::<Value>(), 32);\n\n }\n\n\n\n #[test]\n", "file_path": "src/dms/multi.rs", "rank": 0, "score": 125084.69830992918 }, { "content": "fn render_full(multi: &str) -> Result<Vec<(Raster<SRgb8>, u16)>> {\n\n let fonts = font_cache();\n\n Pages::builder(140, 28)\n\n .with_color_ctx(ColorCtx::new(\n\n ColorScheme::Color24Bit,\n\n ColorClassic::White.rgb(),\n\n ColorClassic::Black.rgb(),\n\n ))\n\n .with_page_on_time_ds(20)\n\n .with_justification_page(JustificationPage::Top)\n\n .with_justification_line(JustificationLine::Left)\n\n .with_font_num(3)\n\n .with_fonts(Some(&fonts))\n\n .build(multi)\n\n .collect()\n\n}\n\n\n", "file_path": "examples/pages.rs", "rank": 1, "score": 124575.78948967013 }, { "content": "/// Parse an x/y pair.\n\nfn parse_xy(x: &str, y: &str) -> Result<(u16, u16), ()> {\n\n if let (Ok(x), Ok(y)) = (x.parse(), y.parse()) {\n\n if x > 0 && y > 0 {\n\n return Ok((x, y));\n\n }\n\n }\n\n Err(())\n\n}\n\n\n", "file_path": "src/dms/multi.rs", "rank": 2, "score": 117114.09188874686 }, { "content": "fn make_indexed(page: Raster<SRgb8>) -> (Raster<Gray8>, Palette) {\n\n let mut palette = Palette::new(256);\n\n let mut indexed = Raster::with_clear(page.width(), page.height());\n\n for (dst, src) in indexed.pixels_mut().iter_mut().zip(page.pixels()) {\n\n if let Some(d) = palette.set_entry(*src) {\n\n *dst = Gray8::new(d as u8);\n\n } else {\n\n panic!(\"Palette full!\");\n\n }\n\n }\n\n (indexed, palette)\n\n}\n\n\n", "file_path": "examples/pages.rs", "rank": 3, "score": 112848.1894543776 }, { "content": "fn font_cache() -> FontCache {\n\n let mut fonts = FontCache::default();\n\n let fts: Vec<Font> =\n\n serde_json::from_str(include_str!(\"../test/font.json\")).unwrap();\n\n for font in fts {\n\n fonts.insert(font);\n\n }\n\n fonts\n\n}\n\n\n", "file_path": "examples/pages.rs", "rank": 4, "score": 93912.32406225608 }, { "content": "/// Function to lookup a pixel from a graphic buffer\n\ntype PixFn = dyn Fn(&Graphic, i32, i32, &ColorCtx, &[u8]) -> Option<SRgb8>;\n\n\n\nimpl Graphic {\n\n /// Get the number\n\n pub fn number(&self) -> u8 {\n\n self.number\n\n }\n\n\n\n /// Get the name\n\n pub fn name(&self) -> &str {\n\n &self.name\n\n }\n\n\n\n /// Get the height in pixels\n\n pub fn height(&self) -> u32 {\n\n self.height.into()\n\n }\n\n\n\n /// Get the width in pixels\n\n pub fn width(&self) -> u32 {\n", "file_path": "src/dms/graphic.rs", "rank": 5, "score": 92691.12593731906 }, { "content": "/// Parse a pont value.\n\nfn parse_point<'a, I>(v: &mut I) -> Result<Option<(u16, u16)>, ()>\n\nwhere\n\n I: Iterator<Item = &'a str>,\n\n{\n\n match (v.next(), v.next()) {\n\n (Some(x), Some(y)) => Ok(Some(parse_xy(x, y)?)),\n\n (Some(_), None) => Err(()),\n\n (_, _) => Ok(None),\n\n }\n\n}\n\n\n", "file_path": "src/dms/multi.rs", "rank": 6, "score": 90214.11332045525 }, { "content": "pub fn serialize<S>(bytes: &[u8], serializer: S) -> Result<S::Ok, S::Error>\n\nwhere\n\n S: Serializer,\n\n{\n\n serializer.collect_str(&Base64Display::with_config(bytes, base64::STANDARD))\n\n}\n\n\n", "file_path": "src/dms/base64.rs", "rank": 7, "score": 86451.75876930165 }, { "content": "/// Parse a hexadecimal value.\n\nfn parse_hexadecimal<'a, I>(v: &mut I) -> Result<u16, ()>\n\nwhere\n\n I: Iterator<Item = &'a str>,\n\n{\n\n if let Some(s) = v.next() {\n\n // May be 1 to 4 hexadecimal digits\n\n if let Ok(i) = u16::from_str_radix(s, 16) {\n\n return Ok(i);\n\n }\n\n }\n\n Err(())\n\n}\n\n\n", "file_path": "src/dms/multi.rs", "rank": 8, "score": 85006.50058558631 }, { "content": "/// Parse an optional value ranging from 0 to 99.\n\nfn parse_optional_99<'a, I>(v: &mut I) -> Result<Option<u8>, ()>\n\nwhere\n\n I: Iterator<Item = &'a str>,\n\n{\n\n if let Some(s) = v.next() {\n\n if s.is_empty() {\n\n return Ok(None);\n\n }\n\n if let Ok(i) = s.parse::<u8>() {\n\n if i <= 99 {\n\n return Ok(Some(i));\n\n }\n\n }\n\n return Err(());\n\n }\n\n Ok(None)\n\n}\n\n\n", "file_path": "src/dms/multi.rs", "rank": 9, "score": 80078.93895248823 }, { "content": "/// Parse a Font tag [fo]\n\nfn parse_font(tag: &str) -> Option<Value> {\n\n if tag.len() > 2 {\n\n let mut vs = tag[2..].splitn(2, ',');\n\n match (parse_nonzero(&mut vs), parse_version_id(&mut vs)) {\n\n (Some(n), Ok(vid)) => Some(Value::Font(Some((n, vid)))),\n\n _ => None,\n\n }\n\n } else {\n\n Some(Value::Font(None))\n\n }\n\n}\n\n\n", "file_path": "src/dms/multi.rs", "rank": 10, "score": 79049.85811981942 }, { "content": "/// Parse a version ID value.\n\nfn parse_version_id<'a, I>(v: &mut I) -> Result<Option<u16>, ()>\n\nwhere\n\n I: Iterator<Item = &'a str>,\n\n{\n\n match v.next() {\n\n Some(s) if s.len() == 4 => match u16::from_str_radix(s, 16) {\n\n Ok(i) => Ok(Some(i)),\n\n _ => Err(()),\n\n },\n\n Some(_) => Err(()),\n\n _ => Ok(None),\n\n }\n\n}\n\n\n", "file_path": "src/dms/multi.rs", "rank": 11, "score": 77358.55371245075 }, { "content": "/// Parse moving text direction\n\nfn parse_moving_text_dir(d: Option<char>) -> Option<MovingTextDirection> {\n\n match d {\n\n Some('l') | Some('L') => Some(MovingTextDirection::Left),\n\n Some('r') | Some('R') => Some(MovingTextDirection::Right),\n\n _ => None,\n\n }\n\n}\n\n\n", "file_path": "src/dms/multi.rs", "rank": 12, "score": 76850.9142333571 }, { "content": "/// Parse a Spacing -- Character tag [sc].\n\nfn parse_spacing_character(tag: &str) -> Option<Value> {\n\n // Not really looking for commas -- just need an iterator\n\n let mut vs = tag[2..].splitn(1, ',');\n\n match parse_int(&mut vs) {\n\n Some(s) if s < 100 => Some(Value::SpacingCharacter(s)),\n\n _ => None,\n\n }\n\n}\n\n\n", "file_path": "src/dms/multi.rs", "rank": 13, "score": 76529.70579039348 }, { "content": "/// Parse a hexadecimal character tag [hc].\n\nfn parse_hexadecimal_character(tag: &str) -> Option<Value> {\n\n // Not really looking for commas -- just need an iterator\n\n let mut vs = tag[2..].splitn(1, ',');\n\n match parse_hexadecimal(&mut vs) {\n\n Ok(hc) => Some(Value::HexadecimalCharacter(hc)),\n\n Err(_) => None,\n\n }\n\n}\n\n\n", "file_path": "src/dms/multi.rs", "rank": 14, "score": 76529.70579039348 }, { "content": "/// Parse a Moving text tag [mv].\n\nfn parse_moving_text(tag: &str) -> Option<Value> {\n\n if tag.len() > 2 {\n\n let t = &tag[3..];\n\n match &tag[2..3] {\n\n \"c\" | \"C\" => parse_moving_text_mode(t, MovingTextMode::Circular),\n\n \"l\" | \"L\" => parse_moving_text_linear(t),\n\n _ => None,\n\n }\n\n } else {\n\n None\n\n }\n\n}\n\n\n", "file_path": "src/dms/multi.rs", "rank": 15, "score": 76472.712423502 }, { "content": "/// Parse a Text Rectangle tag [tr].\n\nfn parse_text_rectangle(tag: &str) -> Option<Value> {\n\n let mut vs = tag[2..].splitn(4, ',');\n\n match parse_rectangle(&mut vs) {\n\n Some(r) => Some(Value::TextRectangle(r)),\n\n _ => None,\n\n }\n\n}\n\n\n", "file_path": "src/dms/multi.rs", "rank": 16, "score": 76472.712423502 }, { "content": "/// Parse a Justification -- Page tag [jp].\n\nfn parse_justification_page(tag: &str) -> Option<Value> {\n\n if tag.len() > 2 {\n\n match JustificationPage::new(&tag[2..]) {\n\n Some(jl) => Some(Value::JustificationPage(Some(jl))),\n\n None => None,\n\n }\n\n } else {\n\n Some(Value::JustificationPage(None))\n\n }\n\n}\n\n\n", "file_path": "src/dms/multi.rs", "rank": 17, "score": 76429.93477143251 }, { "content": "/// Parse a Page -- Background tag [pb].\n\nfn parse_page_background(tag: &str) -> Option<Value> {\n\n if tag.len() > 2 {\n\n match parse_color(tag[2..].split(',')) {\n\n Some(c) => Some(Value::PageBackground(Some(c))),\n\n _ => None,\n\n }\n\n } else {\n\n Some(Value::PageBackground(None))\n\n }\n\n}\n\n\n", "file_path": "src/dms/multi.rs", "rank": 18, "score": 76429.93477143251 }, { "content": "/// Parse a New Page tag [np].\n\nfn parse_new_page(tag: &str) -> Option<Value> {\n\n match tag.len() {\n\n 2 => Some(Value::NewPage()),\n\n _ => None,\n\n }\n\n}\n\n\n", "file_path": "src/dms/multi.rs", "rank": 19, "score": 76429.93477143251 }, { "content": "/// Parse a Page Time tag [pt].\n\nfn parse_page_time(tag: &str) -> Option<Value> {\n\n let mut vs = tag[2..].splitn(2, 'o');\n\n match (parse_optional(&mut vs), parse_optional(&mut vs)) {\n\n (Ok(t), Ok(o)) => Some(Value::PageTime(t, o)),\n\n _ => None,\n\n }\n\n}\n\n\n", "file_path": "src/dms/multi.rs", "rank": 20, "score": 76429.93477143251 }, { "content": "/// Parse a Spacing -- Character end tag [/sc].\n\nfn parse_spacing_character_end(tag: &str) -> Option<Value> {\n\n if tag.len() == 3 {\n\n Some(Value::SpacingCharacterEnd())\n\n } else {\n\n None\n\n }\n\n}\n\n\n", "file_path": "src/dms/multi.rs", "rank": 21, "score": 74083.45184003907 }, { "content": "/// Parse a moving text linear fragment.\n\nfn parse_moving_text_linear(tag: &str) -> Option<Value> {\n\n if !tag.is_empty() {\n\n let t = &tag[1..];\n\n if let Ok(i) = &tag[..1].parse::<u8>() {\n\n parse_moving_text_mode(t, MovingTextMode::Linear(*i))\n\n } else {\n\n parse_moving_text_mode(tag, MovingTextMode::Linear(0))\n\n }\n\n } else {\n\n None\n\n }\n\n}\n\n\n", "file_path": "src/dms/multi.rs", "rank": 22, "score": 74029.04836890406 }, { "content": "/// Parse a moving text mode fragment.\n\nfn parse_moving_text_mode(tag: &str, mode: MovingTextMode) -> Option<Value> {\n\n if !tag.is_empty() {\n\n let dir = parse_moving_text_dir(tag.chars().next());\n\n let mut vs = tag[1..].splitn(4, ',');\n\n let width = parse_int(&mut vs);\n\n let s = parse_int(&mut vs);\n\n let r = parse_int(&mut vs);\n\n let text = vs.next();\n\n if let (Some(dir), Some(width), Some(s), Some(r), Some(text)) =\n\n (dir, width, s, r, text)\n\n {\n\n return Some(Value::MovingText(\n\n mode,\n\n dir,\n\n width,\n\n s,\n\n r,\n\n text.into(),\n\n ));\n\n }\n\n }\n\n None\n\n}\n\n\n", "file_path": "src/dms/multi.rs", "rank": 23, "score": 70456.48995911695 }, { "content": "#[derive(Clone)]\n\nstruct TextLine {\n\n /// Height in pixels\n\n height: u16,\n\n\n\n /// Font spacing\n\n font_spacing: u16,\n\n\n\n /// Specified line spacing\n\n line_spacing: Option<u16>,\n\n}\n\n\n\n/// Builder for dynamic message sign MULTI page renderer.\n\n///\n\n/// # Example\n\n///\n\n/// ```rust\n\n/// use ntcip::dms::Pages;\n\n/// use ntcip::dms::multi::{JustificationLine, JustificationPage};\n\n///\n\n/// let pages = Pages::builder(100, 14)\n", "file_path": "src/dms/render.rs", "rank": 24, "score": 70331.83652631604 }, { "content": "#[derive(Clone)]\n\nstruct TextSpan {\n\n /// Render state for span\n\n state: RenderState,\n\n\n\n /// Text string\n\n text: String,\n\n}\n\n\n\n/// Text line\n", "file_path": "src/dms/render.rs", "rank": 25, "score": 70331.83652631604 }, { "content": "pub fn deserialize<'de, D>(deserializer: D) -> Result<Vec<u8>, D::Error>\n\nwhere\n\n D: Deserializer<'de>,\n\n{\n\n let s = <String>::deserialize(deserializer)?;\n\n base64::decode(&s).map_err(de::Error::custom)\n\n}\n", "file_path": "src/dms/base64.rs", "rank": 26, "score": 65675.02950784675 }, { "content": "/// Parse a flash off -> on tag fragment.\n\nfn parse_flash_off(v: &str) -> Option<Value> {\n\n let mut vs = v.splitn(2, 't');\n\n let o = parse_optional_99(&mut vs).ok()?;\n\n let t = parse_optional_99(&mut vs).ok()?;\n\n Some(Value::Flash(FlashOrder::OffOn, o, t))\n\n}\n\n\n", "file_path": "src/dms/multi.rs", "rank": 27, "score": 61583.01579698312 }, { "content": "/// Parse a flash on -> off tag fragment.\n\nfn parse_flash_on(v: &str) -> Option<Value> {\n\n let mut vs = v.splitn(2, 'o');\n\n let t = parse_optional_99(&mut vs).ok()?;\n\n let o = parse_optional_99(&mut vs).ok()?;\n\n Some(Value::Flash(FlashOrder::OnOff, t, o))\n\n}\n\n\n", "file_path": "src/dms/multi.rs", "rank": 28, "score": 61583.01579698312 }, { "content": "/// Parse a Field tag [f].\n\nfn parse_field(tag: &str) -> Option<Value> {\n\n let mut vs = tag[1..].splitn(2, ',');\n\n match (parse_int(&mut vs), parse_optional(&mut vs)) {\n\n (Some(fid), Ok(w)) if fid < 100 => Some(Value::Field(fid, w)),\n\n _ => None,\n\n }\n\n}\n\n\n", "file_path": "src/dms/multi.rs", "rank": 29, "score": 59627.71981646608 }, { "content": "/// Parse a Graphic tag [g]\n\nfn parse_graphic(tag: &str) -> Option<Value> {\n\n let mut vs = tag[1..].splitn(4, ',');\n\n let n = parse_nonzero(&mut vs);\n\n let p = parse_point(&mut vs);\n\n let vid = parse_version_id(&mut vs);\n\n match (n, p, vid) {\n\n (Some(n), Ok(Some((x, y))), Ok(vid)) => {\n\n Some(Value::Graphic(n, Some((x, y, vid))))\n\n }\n\n (Some(n), Ok(None), Ok(None)) => Some(Value::Graphic(n, None)),\n\n _ => None,\n\n }\n\n}\n\n\n", "file_path": "src/dms/multi.rs", "rank": 30, "score": 59627.71981646608 }, { "content": "/// Parse a Color -- Foreground tag [cf].\n\nfn parse_color_foreground(tag: &str) -> Option<Value> {\n\n if tag.len() > 2 {\n\n match parse_color(tag[2..].split(',')) {\n\n Some(c) => Some(Value::ColorForeground(Some(c))),\n\n _ => None,\n\n }\n\n } else {\n\n Some(Value::ColorForeground(None))\n\n }\n\n}\n\n\n", "file_path": "src/dms/multi.rs", "rank": 31, "score": 57858.40365785583 }, { "content": "/// Parse a Color Rectangle tag [cr].\n\nfn parse_color_rectangle(tag: &str) -> Option<Value> {\n\n let mut vs = tag[2..].splitn(7, ',');\n\n match (parse_rectangle(&mut vs), parse_color(vs)) {\n\n (Some(r), Some(c)) => Some(Value::ColorRectangle(r, c)),\n\n _ => None,\n\n }\n\n}\n\n\n", "file_path": "src/dms/multi.rs", "rank": 32, "score": 57854.53473609523 }, { "content": "/// Parse a Manufacturer Specific tag [ms].\n\nfn parse_manufacturer_specific(tag: &str) -> Option<Value> {\n\n let mut vs = tag[2..].splitn(2, ',');\n\n match (parse_int(&mut vs), vs.next()) {\n\n (Some(m), Some(t)) => {\n\n Some(Value::ManufacturerSpecific(m, Some(t.into())))\n\n }\n\n (Some(m), None) => Some(Value::ManufacturerSpecific(m, None)),\n\n _ => None,\n\n }\n\n}\n\n\n", "file_path": "src/dms/multi.rs", "rank": 33, "score": 57854.53473609523 }, { "content": "/// Parse a Justification -- Line tag [jl].\n\nfn parse_justification_line(tag: &str) -> Option<Value> {\n\n if tag.len() > 2 {\n\n match JustificationLine::new(&tag[2..]) {\n\n Some(jl) => Some(Value::JustificationLine(Some(jl))),\n\n None => None,\n\n }\n\n } else {\n\n Some(Value::JustificationLine(None))\n\n }\n\n}\n\n\n", "file_path": "src/dms/multi.rs", "rank": 34, "score": 57854.53473609523 }, { "content": "/// Parse a flash end tag [/fl].\n\nfn parse_flash_end(tag: &str) -> Option<Value> {\n\n if tag.len() == 3 {\n\n Some(Value::FlashEnd())\n\n } else {\n\n None\n\n }\n\n}\n\n\n", "file_path": "src/dms/multi.rs", "rank": 35, "score": 57854.53473609523 }, { "content": "/// Parse a Color -- Background tag (cb).\n\nfn parse_color_background(tag: &str) -> Option<Value> {\n\n if tag.len() > 2 {\n\n // 1203 specifies a numeric value between 0 and 999,\n\n // but anything above 255 does not make sense\n\n match tag[2..].parse::<u8>() {\n\n Ok(n) => Some(Value::ColorBackground(Some(Color::Legacy(n)))),\n\n Err(_) => None,\n\n }\n\n } else {\n\n Some(Value::ColorBackground(None))\n\n }\n\n}\n\n\n", "file_path": "src/dms/multi.rs", "rank": 36, "score": 57854.53473609523 }, { "content": "/// Parse a Flash time tag [fl].\n\nfn parse_flash_time(tag: &str) -> Option<Value> {\n\n if tag.len() > 2 {\n\n let v = &tag[2..];\n\n match &v[..1] {\n\n \"t\" => parse_flash_on(&v[1..]),\n\n \"o\" => parse_flash_off(&v[1..]),\n\n _ => None,\n\n }\n\n } else {\n\n Some(Value::Flash(FlashOrder::OnOff, None, None))\n\n }\n\n}\n\n\n", "file_path": "src/dms/multi.rs", "rank": 37, "score": 57854.53473609523 }, { "content": "/// Parse a New Line tag [nl].\n\nfn parse_new_line(tag: &str) -> Option<Value> {\n\n // 1203 only specifies a single digit parameter for \"nl\" tag (0-9)\n\n match tag.len() {\n\n 2 => Some(Value::NewLine(None)),\n\n 3 => match tag[2..].parse::<u8>() {\n\n Ok(n) => Some(Value::NewLine(Some(n))),\n\n Err(_) => None,\n\n },\n\n _ => None,\n\n }\n\n}\n\n\n", "file_path": "src/dms/multi.rs", "rank": 38, "score": 57854.53473609523 }, { "content": "/// Parse a rectangle from a tag.\n\n///\n\n/// * `v` Iterator of rectangle parameters.\n\nfn parse_rectangle<'a, I>(v: &mut I) -> Option<Rectangle>\n\nwhere\n\n I: Iterator<Item = &'a str>,\n\n{\n\n if let (Some(x), Some(y), Some(w), Some(h)) =\n\n (v.next(), v.next(), v.next(), v.next())\n\n {\n\n if let (Ok(x), Ok(y), Ok(w), Ok(h)) =\n\n (x.parse(), y.parse(), w.parse(), h.parse())\n\n {\n\n if x > 0 && y > 0 {\n\n return Some(Rectangle::new(x, y, w, h));\n\n }\n\n }\n\n }\n\n None\n\n}\n\n\n", "file_path": "src/dms/multi.rs", "rank": 39, "score": 56311.58573513344 }, { "content": "/// Parse a Manufacturer Specific end tag [/ms].\n\nfn parse_manufacturer_specific_end(tag: &str) -> Option<Value> {\n\n let mut vs = tag[3..].splitn(2, ',');\n\n match (parse_int(&mut vs), vs.next()) {\n\n (Some(m), Some(t)) => {\n\n Some(Value::ManufacturerSpecificEnd(m, Some(t.into())))\n\n }\n\n (Some(m), None) => Some(Value::ManufacturerSpecificEnd(m, None)),\n\n _ => None,\n\n }\n\n}\n\n\n", "file_path": "src/dms/multi.rs", "rank": 40, "score": 56239.15066990258 }, { "content": "/// Parse an integer value.\n\nfn parse_int<'a, I, T>(v: &mut I) -> Option<T>\n\nwhere\n\n I: Iterator<Item = &'a str>,\n\n T: FromStr,\n\n{\n\n if let Some(s) = v.next() {\n\n if let Ok(i) = s.parse::<T>() {\n\n return Some(i);\n\n }\n\n }\n\n None\n\n}\n\n\n", "file_path": "src/dms/multi.rs", "rank": 41, "score": 53033.557723305305 }, { "content": "/// Parse a nonzero value.\n\nfn parse_nonzero<'a, I, T>(v: &mut I) -> Option<T>\n\nwhere\n\n I: Iterator<Item = &'a str>,\n\n T: FromStr + PartialOrd + Default,\n\n{\n\n if let Some(s) = v.next() {\n\n if let Ok(i) = s.parse::<T>() {\n\n // Use default to check for nonzero\n\n if i != T::default() {\n\n return Some(i);\n\n }\n\n }\n\n }\n\n None\n\n}\n\n\n", "file_path": "src/dms/multi.rs", "rank": 42, "score": 53033.557723305305 }, { "content": "/// Parse a tag (without brackets).\n\nfn parse_tag(tag: &str) -> Result<Option<Value>, SyntaxError> {\n\n let tl = &tag.to_ascii_lowercase();\n\n let t = tl.as_str();\n\n // Sorted by most likely occurrence\n\n let v = if t.starts_with(\"nl\") {\n\n parse_new_line(t)\n\n } else if t.starts_with(\"np\") {\n\n parse_new_page(t)\n\n } else if t.starts_with(\"fo\") {\n\n parse_font(t)\n\n } else if t.starts_with(\"jl\") {\n\n parse_justification_line(t)\n\n } else if t.starts_with(\"jp\") {\n\n parse_justification_page(t)\n\n } else if t.starts_with(\"pt\") {\n\n parse_page_time(t)\n\n } else if t.starts_with(\"pb\") {\n\n parse_page_background(t)\n\n } else if t.starts_with(\"cf\") {\n\n parse_color_foreground(t)\n", "file_path": "src/dms/multi.rs", "rank": 43, "score": 50536.81570976459 }, { "content": "/// Parse an optional value.\n\nfn parse_optional<'a, I, T>(v: &mut I) -> Result<Option<T>, ()>\n\nwhere\n\n I: Iterator<Item = &'a str>,\n\n T: FromStr,\n\n{\n\n if let Some(s) = v.next() {\n\n if s.is_empty() {\n\n return Ok(None);\n\n }\n\n if let Ok(i) = s.parse::<T>() {\n\n Ok(Some(i))\n\n } else {\n\n Err(())\n\n }\n\n } else {\n\n Ok(None)\n\n }\n\n}\n\n\n", "file_path": "src/dms/multi.rs", "rank": 44, "score": 50137.03652700306 }, { "content": "#[derive(Clone)]\n\nstruct RenderState {\n\n /// Color context\n\n color_ctx: ColorCtx,\n\n\n\n /// Character width in pixels\n\n char_width: u8,\n\n\n\n /// Character height in pixels\n\n char_height: u8,\n\n\n\n /// Page-on time in deciseconds\n\n page_on_time_ds: u8,\n\n\n\n /// Page-off time in deciseconds\n\n page_off_time_ds: u8,\n\n\n\n /// Current text rectangle\n\n text_rectangle: Rectangle,\n\n\n\n /// Current page justification\n", "file_path": "src/dms/render.rs", "rank": 45, "score": 46067.56437901266 }, { "content": "/// Render a color rectangle.\n\nfn render_rect(\n\n raster: &mut Raster<SRgb8>,\n\n rect: Rectangle,\n\n clr: SRgb8,\n\n value: &Value,\n\n) -> Result<()> {\n\n debug_assert!(rect.x > 0);\n\n debug_assert!(rect.y > 0);\n\n let rx = i32::from(rect.x) - 1;\n\n let ry = i32::from(rect.y) - 1;\n\n let rw = u32::from(rect.w);\n\n let rh = u32::from(rect.h);\n\n let region = Region::new(rx, ry, rw, rh);\n\n if raster.intersection(region) == region {\n\n raster.copy_color(region, clr);\n\n Ok(())\n\n } else {\n\n Err(SyntaxError::UnsupportedTagValue(value.into()))\n\n }\n\n}\n", "file_path": "src/dms/render.rs", "rank": 46, "score": 44327.85349037686 }, { "content": "fn main() -> std::result::Result<(), Box<dyn std::error::Error>> {\n\n let mut writer = BufWriter::new(File::create(\"pages.gif\")?);\n\n let mut enc = Encoder::new(&mut writer).into_step_enc().with_loop_count(0);\n\n let pages = render_full(\"[cf1]LEFT[jl3][cf2]MIDDLE[jl4][cf3]RIGHT[nl][cf4][jl2]THE[cf5][jl3]CENTER[cf6][jl4]LINE[nl][jl3][cf7]THE BOTTOM LINE[np][cf8][jp3][jl3]SECOND PAGE[np][cr1,1,20,8,255,128,128][cr121,1,20,8,128,255,128][cr1,21,20,8,128,128,255][cr121,21,20,8,128,128,128][pb32,0,64][pt40o10]PAGE 3\")?;\n\n for (page, delay_ds) in pages {\n\n let (pg, palette) = make_indexed(page);\n\n let delay = delay_ds * 10;\n\n let step =\n\n Step::with_indexed(pg, palette).with_delay_time_cs(Some(delay));\n\n enc.encode_step(&step)?;\n\n }\n\n Ok(())\n\n}\n", "file_path": "examples/pages.rs", "rank": 47, "score": 42137.67235391209 }, { "content": "/// Example rendering to a .gif file\n\nuse gift::{Encoder, Step};\n\nuse ntcip::dms::multi::{\n\n ColorClassic, ColorCtx, ColorScheme, JustificationLine, JustificationPage,\n\n};\n\nuse ntcip::dms::{Font, FontCache, Pages, Result};\n\nuse pix::{gray::Gray8, rgb::SRgb8, Palette, Raster};\n\nuse std::fs::File;\n\nuse std::io::BufWriter;\n\n\n", "file_path": "examples/pages.rs", "rank": 48, "score": 29611.663832961476 }, { "content": "/// Parse a color from a tag.\n\n///\n\n/// * `v` Iterator of color parameters.\n\nfn parse_color<'a, I>(v: I) -> Option<Color>\n\nwhere\n\n I: Iterator<Item = &'a str>,\n\n{\n\n match v.map(|i| i.parse::<u8>()).collect::<Vec<_>>().as_slice() {\n\n [Ok(r), Ok(g), Ok(b)] => Some(Color::RGB(*r, *g, *b)),\n\n [Ok(n)] => Some(Color::Legacy(*n)),\n\n _ => None,\n\n }\n\n}\n\n\n", "file_path": "src/dms/multi.rs", "rank": 49, "score": 29526.697147806106 }, { "content": "#[derive(Clone, Copy, Debug, Eq, PartialEq)]\n\nenum PageState {\n\n /// Page ON with flag for more pages\n\n On(bool),\n\n\n\n /// Page OFF with flag for more pages\n\n Off(bool),\n\n\n\n /// All pages done\n\n Done,\n\n}\n\n\n\n/// Page render state\n", "file_path": "src/dms/render.rs", "rank": 62, "score": 24212.214704926962 }, { "content": " ) -> Result<()> {\n\n debug_assert!(x > 0);\n\n debug_assert!(y > 0);\n\n let x = x - 1;\n\n let y = y - 1;\n\n let w = i32::from(self.width);\n\n let h = i32::from(self.height);\n\n let width = i32::try_from(page.width()).unwrap();\n\n let height = i32::try_from(page.height()).unwrap();\n\n if x + w > width || y + h > height {\n\n // There is no GraphicTooBig syntax error\n\n return Err(SyntaxError::Other(\"Graphic too big\"));\n\n }\n\n let pix_fn = self.pixel_fn();\n\n for yy in 0..h {\n\n for xx in 0..w {\n\n if let Some(clr) = pix_fn(self, xx, yy, ctx, &self.bitmap) {\n\n *page.pixel_mut(x + xx, y + yy) = clr;\n\n }\n\n }\n", "file_path": "src/dms/graphic.rs", "rank": 63, "score": 34.34697981462345 }, { "content": " graphics: None,\n\n default_state,\n\n }\n\n }\n\n\n\n /// Adjust the color context.\n\n pub fn with_color_ctx(mut self, color_ctx: ColorCtx) -> Self {\n\n self.default_state.color_ctx = color_ctx;\n\n self\n\n }\n\n\n\n /// Adjust the character size.\n\n pub fn with_char_size(mut self, width: u8, height: u8) -> Self {\n\n self.default_state.char_width = width;\n\n self.default_state.char_height = height;\n\n self\n\n }\n\n\n\n /// Adjust the default page on time (deciseconds).\n\n pub fn with_page_on_time_ds(mut self, page_on_time_ds: u8) -> Self {\n", "file_path": "src/dms/render.rs", "rank": 64, "score": 29.50786792926067 }, { "content": " fn line_spacing(&self) -> Option<u16> {\n\n match self.state.line_spacing {\n\n Some(sp) => Some(sp.into()),\n\n None => None,\n\n }\n\n }\n\n\n\n /// Render the text span.\n\n fn render_text(\n\n &self,\n\n raster: &mut Raster<SRgb8>,\n\n font: &Font,\n\n x: i32,\n\n y: i32,\n\n ) -> Result<()> {\n\n let cs = self.char_spacing_font(font).into();\n\n let cf = self.state.foreground_rgb();\n\n Ok(font.render_text(raster, &self.text, x, y, cs, cf)?)\n\n }\n\n}\n", "file_path": "src/dms/render.rs", "rank": 65, "score": 28.817308350476768 }, { "content": "// graphic.rs\n\n//\n\n// Copyright (C) 2018-2020 Minnesota Department of Transportation\n\n//\n\n//! Graphics are used on dynamic message signs.\n\nuse crate::dms::multi::{Color, ColorCtx, ColorScheme, SyntaxError};\n\nuse crate::dms::Result;\n\nuse log::debug;\n\nuse pix::{rgb::SRgb8, Raster};\n\nuse std::collections::HashMap;\n\nuse std::convert::TryFrom;\n\n\n\n/// An uncompressed DMS graphic.\n\n#[derive(Deserialize, Serialize)]\n\npub struct Graphic {\n\n /// Graphic number\n\n number: u8,\n\n /// Name (max 64 characters)\n\n name: String,\n\n /// Height in pixels\n", "file_path": "src/dms/graphic.rs", "rank": 66, "score": 28.07702529753632 }, { "content": "\n\nimpl<'a> TextSpan {\n\n /// Create a new text span.\n\n fn new(state: &RenderState, text: String) -> Self {\n\n let state = state.clone();\n\n TextSpan { state, text }\n\n }\n\n\n\n /// Get the width of a text span.\n\n fn width(&self, fonts: Option<&FontCache>) -> Result<u16> {\n\n let font = self.state.font(fonts)?;\n\n let cs = self.char_spacing_fonts(fonts)?;\n\n Ok(font.text_width(&self.text, Some(cs))?)\n\n }\n\n\n\n /// Get the char spacing.\n\n fn char_spacing_fonts(&self, fonts: Option<&FontCache>) -> Result<u16> {\n\n match self.state.char_spacing {\n\n Some(sp) => Ok(sp.into()),\n\n None => Ok(self.state.font(fonts)?.char_spacing().into()),\n", "file_path": "src/dms/render.rs", "rank": 67, "score": 27.033995033943352 }, { "content": " }\n\n\n\n /// Calculate horizontal offsets of a span.\n\n ///\n\n /// Returns a tuple of (before, after) widths of matching spans.\n\n fn offset_horiz(&self, text_span: &TextSpan) -> Result<(u16, u16)> {\n\n debug!(\"offset_horiz '{}'\", text_span.text);\n\n let rs = &text_span.state;\n\n let mut before = 0;\n\n let mut after = 0;\n\n let mut pspan = None;\n\n for span in self.spans.iter().filter(|s| rs.matches_span(&s.state)) {\n\n if let Some(ps) = pspan {\n\n let w = span.char_spacing_between(ps, self.fonts)?;\n\n if span.state.span_number <= rs.span_number {\n\n before += w\n\n } else {\n\n after += w\n\n }\n\n debug!(\" spacing {} before {} after {}\", w, before, after);\n", "file_path": "src/dms/render.rs", "rank": 68, "score": 24.591360113053835 }, { "content": "\n\n /// Get the character width (1 for variable width).\n\n fn char_width(&self) -> u16 {\n\n if self.is_char_matrix() {\n\n self.char_width.into()\n\n } else {\n\n 1\n\n }\n\n }\n\n\n\n /// Get the character height (1 for variable height).\n\n fn char_height(&self) -> u16 {\n\n if self.char_height > 0 {\n\n self.char_height.into()\n\n } else {\n\n 1\n\n }\n\n }\n\n\n\n /// Update the text rectangle.\n", "file_path": "src/dms/render.rs", "rank": 69, "score": 23.647110230571656 }, { "content": " }\n\n\n\n /// Render an OFF page.\n\n fn render_off_page(&mut self) -> (Raster<SRgb8>, u16) {\n\n self.page_state = self.page_state.next_state();\n\n (self.build_raster(), self.page_off_time_ds())\n\n }\n\n\n\n /// Build a raster.\n\n fn build_raster(&self) -> Raster<SRgb8> {\n\n let width = self.state.text_rectangle.w.into();\n\n let height = self.state.text_rectangle.h.into();\n\n let clr = self.state.background_rgb();\n\n Raster::with_color(width, height, clr)\n\n }\n\n\n\n /// Render an ON page.\n\n fn render_on_page(&mut self) -> Result<(Raster<SRgb8>, u16)> {\n\n self.check_unsupported()?;\n\n self.update_page_state()?;\n", "file_path": "src/dms/render.rs", "rank": 70, "score": 23.211880407770963 }, { "content": " just_page: JustificationPage,\n\n\n\n /// Current line justification\n\n just_line: JustificationLine,\n\n\n\n /// Font number\n\n font_num: u8,\n\n\n\n /// Font version_id\n\n font_version_id: Option<u16>,\n\n\n\n /// Current specified line spacing\n\n line_spacing: Option<u8>,\n\n\n\n /// Current specified char spacing\n\n char_spacing: Option<u8>,\n\n\n\n /// Current line number\n\n line_number: u8,\n\n\n\n /// Current text span number\n\n span_number: u8,\n\n}\n\n\n\n/// Text span\n", "file_path": "src/dms/render.rs", "rank": 71, "score": 23.09821765766171 }, { "content": " PageState::Off(false) => PageState::Done,\n\n PageState::Done => PageState::Done,\n\n }\n\n }\n\n}\n\n\n\nimpl RenderState {\n\n /// Create a new render state.\n\n fn new(width: u16, height: u16) -> Self {\n\n RenderState {\n\n color_ctx: ColorCtx::new(\n\n ColorScheme::Monochrome1Bit,\n\n ColorClassic::Amber.rgb(),\n\n ColorClassic::Black.rgb(),\n\n ),\n\n char_width: 0,\n\n char_height: 0,\n\n page_on_time_ds: 30,\n\n page_off_time_ds: 0,\n\n text_rectangle: Rectangle::new(1, 1, width, height),\n", "file_path": "src/dms/render.rs", "rank": 72, "score": 23.004621776453213 }, { "content": "\n\nimpl TextLine {\n\n /// Create a new text line.\n\n fn new(height: u16, font_spacing: u16, line_spacing: Option<u16>) -> Self {\n\n TextLine {\n\n height,\n\n font_spacing,\n\n line_spacing,\n\n }\n\n }\n\n\n\n /// Combine a text line with another.\n\n fn combine(&mut self, rhs: &Self) {\n\n self.height = self.height.max(rhs.height);\n\n self.font_spacing = self.font_spacing.max(rhs.font_spacing);\n\n self.line_spacing = self.line_spacing.or(rhs.line_spacing);\n\n }\n\n\n\n /// Get the spacing between two text lines.\n\n fn spacing(&self, rhs: &Self) -> u16 {\n", "file_path": "src/dms/render.rs", "rank": 73, "score": 22.975955677379716 }, { "content": " }\n\n debug!(\" line {} above {} below {}\", ln, above, below);\n\n }\n\n if above + below <= rs.text_rectangle.h {\n\n Ok((above, below))\n\n } else {\n\n Err(SyntaxError::TextTooBig)\n\n }\n\n }\n\n}\n\n\n\nimpl<'a> Iterator for Pages<'a> {\n\n type Item = Result<(Raster<SRgb8>, u16)>;\n\n\n\n fn next(&mut self) -> Option<Self::Item> {\n\n match self.page_state {\n\n PageState::On(_) => Some(self.render_on_page()),\n\n PageState::Off(_) => Some(Ok(self.render_off_page())),\n\n _ => None,\n\n }\n\n }\n\n}\n\n\n", "file_path": "src/dms/render.rs", "rank": 74, "score": 22.323950223711872 }, { "content": " if let Some(ls) = self.line_spacing {\n\n ls\n\n } else {\n\n // NTCIP 1203 fontLineSpacing:\n\n // \"The number of pixels between adjacent lines\n\n // is the average of the 2 line spacings of each\n\n // line, rounded up to the nearest whole pixel.\"\n\n let ps = rhs.font_spacing;\n\n let fs = self.font_spacing;\n\n ((ps + fs) >> 1) + ((ps + fs) & 1)\n\n }\n\n }\n\n}\n\n\n\nimpl<'a> PageBuilder<'a> {\n\n /// Create a new dynamic message sign MULTI page builder.\n\n fn new(width: u16, height: u16) -> Self {\n\n let default_state = RenderState::new(width, height);\n\n PageBuilder {\n\n fonts: None,\n", "file_path": "src/dms/render.rs", "rank": 75, "score": 22.286990569623295 }, { "content": " let mut raster = self.build_raster();\n\n debug!(\"render_on_page {}x{}\", raster.width(), raster.height());\n\n let mut n_text_rectangles = 0;\n\n self.page_state = PageState::On(false);\n\n while self.page_state == PageState::On(false) {\n\n self.render_graphics(&mut raster)?;\n\n self.render_text_rectangle(&mut raster)?;\n\n n_text_rectangles += 1;\n\n if n_text_rectangles > MAX_TEXT_RECTANGLES {\n\n return Err(SyntaxError::Other(\"Too many text rectangles\"));\n\n }\n\n }\n\n Ok((raster, self.page_on_time_ds()))\n\n }\n\n\n\n /// Check for unsupported MULTI tags in a page.\n\n fn check_unsupported(&self) -> Result<()> {\n\n for value in self.parser.clone() {\n\n let val = value?;\n\n match val {\n", "file_path": "src/dms/render.rs", "rank": 76, "score": 21.699927531831037 }, { "content": " just_page: JustificationPage::Middle,\n\n just_line: JustificationLine::Center,\n\n font_num: 1,\n\n font_version_id: None,\n\n line_spacing: None,\n\n char_spacing: None,\n\n line_number: 0,\n\n span_number: 0,\n\n }\n\n }\n\n\n\n /// Check if the sign is character-matrix.\n\n fn is_char_matrix(&self) -> bool {\n\n self.char_width > 0\n\n }\n\n\n\n /// Check if the sign is character- or line-matrix.\n\n fn is_char_or_line_matrix(&self) -> bool {\n\n self.char_height > 0\n\n }\n", "file_path": "src/dms/render.rs", "rank": 77, "score": 21.61719702037195 }, { "content": " height: u8,\n\n /// Width in pixels\n\n width: u16,\n\n /// Color scheme, or dmsGraphicType from NTCIP 1203\n\n color_scheme: String,\n\n /// Transparent color (RGB)\n\n transparent_color: Option<i32>,\n\n /// Bitmap data (by rows)\n\n #[serde(with = \"super::base64\")]\n\n bitmap: Vec<u8>,\n\n}\n\n\n\n/// A cache of graphics.\n\n#[derive(Default)]\n\npub struct GraphicCache {\n\n /// Graphics in cache\n\n graphics: HashMap<u8, Graphic>,\n\n}\n\n\n\n/// Function to lookup a pixel from a graphic buffer\n", "file_path": "src/dms/graphic.rs", "rank": 78, "score": 21.17608017589722 }, { "content": " self.width.into()\n\n }\n\n\n\n /// Get the color scheme\n\n pub fn color_scheme(&self) -> &str {\n\n &self.color_scheme\n\n }\n\n\n\n /// Get the transparent color\n\n pub fn transparent_color(&self) -> Option<i32> {\n\n self.transparent_color\n\n }\n\n\n\n /// Render graphic onto a Raster\n\n pub fn render_graphic(\n\n &self,\n\n page: &mut Raster<SRgb8>,\n\n x: i32,\n\n y: i32,\n\n ctx: &ColorCtx,\n", "file_path": "src/dms/graphic.rs", "rank": 79, "score": 21.14024785288832 }, { "content": "// render.rs\n\n//\n\n// Copyright (C) 2018-2020 Minnesota Department of Transportation\n\n//\n\n//! This module is for NTCIP 1203 DMS rendering.\n\nuse crate::dms::multi::{\n\n ColorClassic, ColorCtx, ColorScheme, JustificationLine, JustificationPage,\n\n Parser, Rectangle, SyntaxError, Value,\n\n};\n\nuse crate::dms::{Font, FontCache, Graphic, GraphicCache, Result};\n\nuse log::debug;\n\nuse pix::{rgb::SRgb8, Raster, Region};\n\n\n\n/// Maximum number of text rectangles per page\n\nconst MAX_TEXT_RECTANGLES: u32 = 50;\n\n\n\n/// Page state\n\n#[derive(Clone, Copy, Debug, Eq, PartialEq)]\n", "file_path": "src/dms/render.rs", "rank": 80, "score": 21.12693431118638 }, { "content": " pub fn new(m: &'a str) -> Self {\n\n debug!(\"Parser::new {}\", m);\n\n let remaining = m.chars().peekable();\n\n Parser {\n\n remaining,\n\n within_tag: false,\n\n }\n\n }\n\n\n\n /// Peek at the next character.\n\n fn peek_char(&mut self) -> Option<char> {\n\n if let Some(c) = self.remaining.peek() {\n\n Some(*c)\n\n } else {\n\n None\n\n }\n\n }\n\n\n\n /// Get the next character.\n\n fn next_char(&mut self) -> Result<Option<char>, SyntaxError> {\n", "file_path": "src/dms/multi.rs", "rank": 81, "score": 21.0523302782676 }, { "content": "\n\n /// Graphic tag\n\n ///\n\n /// * Graphic number\n\n /// * Optional tuple containing X and Y position and optional version ID\n\n Graphic(u8, Option<(u16, u16, Option<u16>)>),\n\n\n\n /// Hexadecimal character tag\n\n ///\n\n /// * Character number (code point)\n\n HexadecimalCharacter(u16),\n\n\n\n /// Line justification tag\n\n JustificationLine(Option<JustificationLine>),\n\n\n\n /// Page justification tag\n\n JustificationPage(Option<JustificationPage>),\n\n\n\n /// Manufacturer specific start tag\n\n ManufacturerSpecific(u32, Option<String>),\n", "file_path": "src/dms/multi.rs", "rank": 82, "score": 20.341199778383277 }, { "content": " pub fn with_justification_line(\n\n mut self,\n\n just_line: JustificationLine,\n\n ) -> Self {\n\n self.default_state.just_line = just_line;\n\n self\n\n }\n\n\n\n /// Adjust the default font number.\n\n pub fn with_font_num(mut self, font_num: u8) -> Self {\n\n self.default_state.font_num = font_num;\n\n self\n\n }\n\n\n\n /// Set the font cache.\n\n pub fn with_fonts(mut self, fonts: Option<&'a FontCache>) -> Self {\n\n self.fonts = fonts;\n\n self\n\n }\n\n\n", "file_path": "src/dms/render.rs", "rank": 83, "score": 20.181510065917468 }, { "content": " }\n\n\n\n /// Calculate vertical offset of a span.\n\n ///\n\n /// Returns a tuple of (above, below) heights of matching lines.\n\n fn offset_vert(&self, text_span: &TextSpan) -> Result<(u16, u16)> {\n\n debug!(\"offset_vert '{}'\", text_span.text);\n\n let rs = &text_span.state;\n\n let mut lines = vec![];\n\n for span in self.spans.iter().filter(|s| rs.matches_line(&s.state)) {\n\n let ln = usize::from(span.state.line_number);\n\n let h = span.height(self.fonts)?;\n\n let fs = span.font_spacing(self.fonts)?;\n\n let ls = span.line_spacing();\n\n let line = TextLine::new(h, fs, ls);\n\n if ln >= lines.len() {\n\n lines.push(line);\n\n } else {\n\n lines[ln].combine(&line);\n\n }\n", "file_path": "src/dms/render.rs", "rank": 84, "score": 19.90138869855265 }, { "content": " \"5\" => Some(JustificationLine::Full),\n\n _ => None,\n\n }\n\n }\n\n}\n\n\n\nimpl fmt::Display for JustificationPage {\n\n fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {\n\n write!(f, \"{}\", *self as u8)\n\n }\n\n}\n\n\n\nimpl JustificationPage {\n\n /// Create a page justification.\n\n pub fn new(v: &str) -> Option<Self> {\n\n match v {\n\n \"1\" => Some(JustificationPage::Other),\n\n \"2\" => Some(JustificationPage::Top),\n\n \"3\" => Some(JustificationPage::Middle),\n\n \"4\" => Some(JustificationPage::Bottom),\n", "file_path": "src/dms/multi.rs", "rank": 85, "score": 19.873294207248254 }, { "content": " parser,\n\n spans,\n\n }\n\n }\n\n}\n\n\n\nimpl<'a> Pages<'a> {\n\n /// Create a builder for dynamic message sign MULTI pages.\n\n pub fn builder(width: u16, height: u16) -> PageBuilder<'a> {\n\n PageBuilder::new(width, height)\n\n }\n\n\n\n /// Get the page-on time (deciseconds).\n\n fn page_on_time_ds(&self) -> u16 {\n\n self.state.page_on_time_ds.into()\n\n }\n\n\n\n /// Get the page-off time (deciseconds).\n\n fn page_off_time_ds(&self) -> u16 {\n\n self.state.page_off_time_ds.into()\n", "file_path": "src/dms/render.rs", "rank": 86, "score": 19.45007384693956 }, { "content": "// ntcip::dms\n\n//\n\n// Copyright (C) 2019-2020 Minnesota Department of Transportation\n\n//\n\n//! Dynamic message signs specified by NTCIP 1203.\n\nmod base64;\n\nmod font;\n\nmod graphic;\n\npub mod multi;\n\nmod render;\n\n\n\n/// Result type\n\npub type Result<T> = std::result::Result<T, multi::SyntaxError>;\n\n\n\npub use font::{Character, Font, FontCache};\n\npub use graphic::{Graphic, GraphicCache};\n\npub use render::{PageBuilder, Pages};\n", "file_path": "src/dms/mod.rs", "rank": 87, "score": 18.96809765476644 }, { "content": " /// Set the graphic cache.\n\n pub fn with_graphics(mut self, graphics: Option<&'a GraphicCache>) -> Self {\n\n self.graphics = graphics;\n\n self\n\n }\n\n\n\n /// Build the page renderer.\n\n ///\n\n /// * `ms` MULTI string to parse.\n\n pub fn build(self, ms: &'a str) -> Pages<'a> {\n\n let default_state = self.default_state;\n\n let state = default_state.clone();\n\n let parser = Parser::new(ms);\n\n let spans = vec![];\n\n Pages {\n\n fonts: self.fonts,\n\n graphics: self.graphics,\n\n default_state,\n\n state,\n\n page_state: PageState::On(true),\n", "file_path": "src/dms/render.rs", "rank": 88, "score": 18.801657659603265 }, { "content": "\n\n#[cfg(test)]\n\nmod test {\n\n use super::*;\n\n use crate::dms::multi::{ColorClassic, ColorCtx, ColorScheme};\n\n\n\n fn font_cache() -> FontCache {\n\n let mut fonts = FontCache::default();\n\n let fts: Vec<Font> =\n\n serde_json::from_str(include_str!(\"../../test/font.json\")).unwrap();\n\n for font in fts {\n\n fonts.insert(font);\n\n }\n\n fonts\n\n }\n\n\n\n fn render_full(multi: &str) -> Result<Vec<(Raster<SRgb8>, u16)>> {\n\n let fonts = font_cache();\n\n Pages::builder(60, 30)\n\n .with_color_ctx(ColorCtx::new(\n", "file_path": "src/dms/render.rs", "rank": 89, "score": 18.793127004598915 }, { "content": " fn update_text_rectangle(\n\n &mut self,\n\n default_state: &RenderState,\n\n rect: Rectangle,\n\n val: &Value,\n\n ) -> Result<()> {\n\n let rect = rect.match_width_height(default_state.text_rectangle);\n\n if !default_state.text_rectangle.contains(rect) {\n\n return Err(SyntaxError::UnsupportedTagValue(val.into()));\n\n }\n\n let cw = self.char_width();\n\n debug_assert!(cw > 0);\n\n // Check text rectangle matches character boundaries\n\n let x = rect.x - 1;\n\n if x % cw != 0 || rect.w % cw != 0 {\n\n return Err(SyntaxError::UnsupportedTagValue(val.into()));\n\n }\n\n let lh = self.char_height();\n\n debug_assert!(lh > 0);\n\n // Check text rectangle matches line boundaries\n", "file_path": "src/dms/render.rs", "rank": 90, "score": 18.5238185261269 }, { "content": " }\n\n Value::NewPage() => {\n\n self.page_state = PageState::new_page(page_off);\n\n break;\n\n }\n\n Value::SpacingCharacter(sc) => {\n\n if rs.is_char_matrix() && sc > 0 {\n\n return Err(SyntaxError::UnsupportedTagValue(\n\n val.into(),\n\n ));\n\n }\n\n rs.char_spacing = Some(sc);\n\n }\n\n Value::SpacingCharacterEnd() => {\n\n rs.char_spacing = None;\n\n }\n\n Value::TextRectangle(rect) => {\n\n self.page_state = PageState::On(false);\n\n rs.line_number = 0;\n\n rs.span_number = 0;\n", "file_path": "src/dms/render.rs", "rank": 91, "score": 18.318417810210388 }, { "content": " // NTCIP 1203 fontCharSpacing:\n\n // \"... the average character spacing of the two fonts,\n\n // rounded up to the nearest whole pixel ...\" ???\n\n let psc = prev.char_spacing_fonts(fonts)?;\n\n let sc = self.char_spacing_fonts(fonts)?;\n\n Ok(((psc + sc) >> 1) + ((psc + sc) & 1))\n\n }\n\n }\n\n\n\n /// Get the height of a text span.\n\n fn height(&self, fonts: Option<&FontCache>) -> Result<u16> {\n\n Ok(self.state.font(fonts)?.height().into())\n\n }\n\n\n\n /// Get the font line spacing.\n\n fn font_spacing(&self, fonts: Option<&FontCache>) -> Result<u16> {\n\n Ok(self.state.font(fonts)?.line_spacing().into())\n\n }\n\n\n\n /// Get the line spacing.\n", "file_path": "src/dms/render.rs", "rank": 92, "score": 18.18125417497255 }, { "content": " TextTooBig,\n\n /// Specified font not defined\n\n FontNotDefined(u8),\n\n /// Specified character not defined in font\n\n CharacterNotDefined(char),\n\n /// Specified field device does not exist\n\n FieldDeviceNotExist,\n\n /// Field device communication error\n\n FieldDeviceError,\n\n /// Specified flash region not supported\n\n FlashRegionError,\n\n /// Specified tags conflict with each other\n\n TagConflict,\n\n /// Number of pages not supported\n\n TooManyPages,\n\n /// Specified font version ID does not match\n\n FontVersionID,\n\n /// Specified graphic version ID does not match\n\n GraphicID,\n\n /// Specified graphic number not defined\n", "file_path": "src/dms/multi.rs", "rank": 93, "score": 17.899401643103346 }, { "content": " /// Interpolate between two color components\n\n fn lerp(bg: u8, fg: u8, v: u8) -> u8 {\n\n let d = bg.max(fg) - bg.min(fg);\n\n let c = d as u32 * v as u32;\n\n // cheap alternative to divide by 255\n\n let r = (((c + 1) + (c >> 8)) >> 8) as u8;\n\n bg.min(fg) + r\n\n }\n\n}\n\n\n\nimpl fmt::Display for Rectangle {\n\n fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {\n\n write!(f, \"{},{},{},{}\", self.x, self.y, self.w, self.h)\n\n }\n\n}\n\n\n\nimpl Rectangle {\n\n /// Create a new rectangle\n\n pub fn new(x: u16, y: u16, w: u16, h: u16) -> Self {\n\n Rectangle { x, y, w, h }\n", "file_path": "src/dms/multi.rs", "rank": 94, "score": 17.749249872806995 }, { "content": " }\n\n let w = span.width(self.fonts)?;\n\n if span.state.span_number < rs.span_number {\n\n before += w\n\n } else {\n\n after += w\n\n }\n\n debug!(\" span '{}' before {} after {}\", span.text, before, after);\n\n pspan = Some(span);\n\n }\n\n if before + after <= rs.text_rectangle.w {\n\n Ok((before, after))\n\n } else {\n\n Err(SyntaxError::TextTooBig)\n\n }\n\n }\n\n\n\n /// Get the Y position of a text span.\n\n fn span_y(&self, span: &TextSpan) -> Result<u16> {\n\n let b = self.baseline(span)?;\n", "file_path": "src/dms/render.rs", "rank": 95, "score": 17.626409816498374 }, { "content": "// multi.rs\n\n//\n\n// Copyright (C) 2018-2020 Minnesota Department of Transportation\n\n//\n\n//! MULTI (Markup Language for Transportation Information) for dynamic message\n\n//! signs, specified in NTCIP 1203.\n\n//!\n\nuse log::{debug, warn};\n\nuse std::fmt;\n\nuse std::iter::Peekable;\n\nuse std::str::Chars;\n\nuse std::str::FromStr;\n\n\n\n/// Classic color values\n\n#[derive(Clone, Copy, Debug, Eq, PartialEq)]\n\npub enum ColorClassic {\n\n Black,\n\n Red,\n\n Yellow,\n\n Green,\n", "file_path": "src/dms/multi.rs", "rank": 96, "score": 17.45185507012736 }, { "content": " /// Check if states match for text spans.\n\n fn matches_span(&self, rhs: &Self) -> bool {\n\n self.just_page == rhs.just_page\n\n && self.line_number == rhs.line_number\n\n && self.just_line == rhs.just_line\n\n }\n\n\n\n /// Check if states match for lines.\n\n fn matches_line(&self, rhs: &Self) -> bool {\n\n self.just_page == rhs.just_page\n\n }\n\n\n\n /// Lookup current font in cache.\n\n fn font<'a>(&self, fonts: Option<&'a FontCache>) -> Result<&'a Font> {\n\n debug!(\"RenderState::font {}\", self.font_num);\n\n fonts\n\n .ok_or_else(|| SyntaxError::FontNotDefined(self.font_num))?\n\n .lookup(self.font_num, self.font_version_id)\n\n }\n\n}\n", "file_path": "src/dms/render.rs", "rank": 97, "score": 17.36827349696677 }, { "content": "\n\n /// Manufacturer specific end tag\n\n ManufacturerSpecificEnd(u32, Option<String>),\n\n\n\n /// Moving text tag\n\n ///\n\n /// * Moving text mode\n\n /// * Moving text direction\n\n /// * Width in pixels\n\n /// * Pixels offset at each time step\n\n /// * Deciseconds between time steps\n\n /// * Text to be moved\n\n MovingText(MovingTextMode, MovingTextDirection, u16, u8, u8, String),\n\n\n\n /// New line tag\n\n ///\n\n /// * Optional line spacing\n\n NewLine(Option<u8>),\n\n\n\n /// New page tag\n", "file_path": "src/dms/multi.rs", "rank": 98, "score": 17.303270122689163 }, { "content": " justify_dot(\"[tr2,2,10,10].\", 481);\n\n }\n\n\n\n fn render_char(multi: &str) -> Result<Vec<(Raster<SRgb8>, u16)>> {\n\n let fonts = font_cache();\n\n Pages::builder(100, 21)\n\n .with_color_ctx(ColorCtx::new(\n\n ColorScheme::Monochrome1Bit,\n\n ColorClassic::White.rgb(),\n\n ColorClassic::Black.rgb(),\n\n ))\n\n .with_char_size(5, 7)\n\n .with_page_on_time_ds(20)\n\n .with_justification_page(JustificationPage::Top)\n\n .with_justification_line(JustificationLine::Left)\n\n .with_fonts(Some(&fonts))\n\n .build(multi)\n\n .collect()\n\n }\n\n\n", "file_path": "src/dms/render.rs", "rank": 99, "score": 17.06516081018549 } ]
Rust
rust/src/methods/reshape/mod.rs
stencila/stencila
bff4faceb1460a84b096e9e45f4a4580a0156295
use super::decode::date::decode_date_maybe; use super::decode::person::decode_person; use super::encode::txt::ToTxt; use defaults::Defaults; use eyre::Result; use once_cell::sync::Lazy; use regex::Regex; use stencila_schema::{ Article, BlockContent, CreativeWorkAuthors, CreativeWorkTitle, Date, InlineContent, Node, Paragraph, Person, ThingDescription, }; #[derive(Defaults)] pub struct Options { #[def = "true"] article: bool, #[def = "true"] detect_title: bool, #[def = "true"] infer_title: bool, #[def = "true"] detect_authors: bool, #[def = "true"] infer_authors: bool, #[def = "true"] detect_date: bool, #[def = "true"] infer_date: bool, #[def = "true"] detect_keywords: bool, #[def = "true"] detect_abstract: bool, } pub fn reshape(node: &mut Node, options: Options) -> Result<()> { if let (Node::Article(article), true) = (node, &options.article) { reshape_article(article, &options) } Ok(()) } pub fn reshape_article(article: &mut Article, options: &Options) { if let Some(blocks) = &mut article.content { let mut index = 0; while index < blocks.len() { let mut delta = 1; if index == 0 { if article.title.is_none() && options.detect_title { delta += detect_title(&mut article.title, blocks, index) } if !blocks.is_empty() && article.title.is_none() && options.infer_title { delta += infer_title(&mut article.title, blocks, index) } if !blocks.is_empty() && article.authors.is_none() && options.detect_authors { delta += detect_authors(&mut article.authors, blocks, index) } if !blocks.is_empty() && article.authors.is_none() && options.infer_authors { delta += infer_authors(&mut article.authors, blocks, index) } if !blocks.is_empty() && article.date_modified.is_none() && options.detect_date { delta += detect_date(&mut article.date_modified, blocks, index) } if !blocks.is_empty() && article.date_modified.is_none() && options.infer_date { delta += infer_date(&mut article.date_modified, blocks, index) } if !blocks.is_empty() && article.keywords.is_none() && options.detect_keywords { delta += detect_keywords(&mut article.keywords, blocks, index) } if !blocks.is_empty() && article.description.is_none() && options.detect_abstract { delta += detect_abstract(&mut article.description, blocks, index) } } index = index.saturating_add(delta.max(0) as usize); } } } fn first_is_strong(paragraph: &Paragraph) -> bool { matches!(paragraph.content.first(), Some(InlineContent::Strong(_))) } fn first_is_emphasis(paragraph: &Paragraph) -> bool { matches!(paragraph.content.first(), Some(InlineContent::Emphasis(_))) } fn has_superscript(paragraph: &Paragraph) -> bool { paragraph .content .iter() .any(|inline| matches!(inline, InlineContent::Superscript(_))) } fn remove_first_mark(paragraph: &Paragraph) -> Vec<InlineContent> { let mut content = match paragraph.content.first() { Some(InlineContent::Emphasis(emphasis)) => emphasis.content.clone(), Some(InlineContent::Strong(strong)) => strong.content.clone(), _ => Vec::new(), }; let mut rest = paragraph.content.clone(); rest.remove(0); content.append(&mut rest); content } fn detect_title( title: &mut Option<Box<CreativeWorkTitle>>, blocks: &mut Vec<BlockContent>, index: usize, ) -> i32 { static BEGINS_REGEX: Lazy<Regex> = Lazy::new(|| { Regex::new("^(?:T|t)itle\\b(?:[^\\w]*)?(.*)").expect("Unable to create regex") }); if let BlockContent::Paragraph(paragraph) = &blocks[index] { let txt = paragraph.to_txt(); if let Some(captures) = BEGINS_REGEX.captures(&txt) { *title = Some(Box::new(CreativeWorkTitle::VecInlineContent(vec![ InlineContent::String(captures[1].to_string()), ]))); blocks.remove(index); return -1; } } 0 } fn infer_title( title: &mut Option<Box<CreativeWorkTitle>>, blocks: &mut Vec<BlockContent>, index: usize, ) -> i32 { let inferred = match &blocks[index] { BlockContent::Heading(heading) => { if heading.depth == Some(1) { Some(Box::new(CreativeWorkTitle::VecInlineContent( heading.content.clone(), ))) } else { None } } BlockContent::Paragraph(paragraph) => { if first_is_strong(paragraph) || first_is_emphasis(paragraph) { Some(Box::new(CreativeWorkTitle::VecInlineContent( remove_first_mark(paragraph), ))) } else { None } } _ => None, }; if inferred.is_some() { *title = inferred; blocks.remove(index); -1 } else { 0 } } fn detect_authors( authors: &mut Option<Vec<CreativeWorkAuthors>>, blocks: &mut Vec<BlockContent>, index: usize, ) -> i32 { static BEGINS_REGEX: Lazy<Regex> = Lazy::new(|| { Regex::new("^(?:A|a)uthors?\\b(?:[^\\w]*)?(.*)").expect("Unable to create regex") }); static SPLIT_REGEX: Lazy<Regex> = Lazy::new(|| Regex::new("\\s*;|(and)|&\\s*").expect("Unable to create regex")); if let BlockContent::Paragraph(paragraph) = &blocks[index] { let txt = paragraph.to_txt(); if let Some(captures) = BEGINS_REGEX.captures(&txt) { let authors_ = SPLIT_REGEX .split(&captures[1]) .map(|str| CreativeWorkAuthors::Person(decode_person(str))) .collect(); *authors = Some(authors_); blocks.remove(index); return -1; } } 0 } fn infer_authors( authors: &mut Option<Vec<CreativeWorkAuthors>>, blocks: &mut Vec<BlockContent>, index: usize, ) -> i32 { let inferred = match &blocks[index] { BlockContent::Paragraph(paragraph) => { if has_superscript(paragraph) { Some(vec![CreativeWorkAuthors::Person(Person { name: Some(Box::new("superscripted".to_string())), ..Default::default() })]) } else { None } } _ => None, }; if inferred.is_some() { *authors = inferred; blocks.remove(index); -1 } else { 0 } } fn detect_date(date: &mut Option<Box<Date>>, blocks: &mut Vec<BlockContent>, index: usize) -> i32 { static BEGINS_REGEX: Lazy<Regex> = Lazy::new(|| Regex::new("^(?:D|d)ate\\b(?:[^\\w]*)?(.*)").expect("Unable to create regex")); if let BlockContent::Paragraph(paragraph) = &blocks[index] { let txt = paragraph.to_txt(); if let Some(captures) = BEGINS_REGEX.captures(&txt) { if let Some(date_) = decode_date_maybe(&captures[1]) { *date = Some(Box::new(date_)); blocks.remove(index); return -1; } } } 0 } fn infer_date(date: &mut Option<Box<Date>>, blocks: &mut Vec<BlockContent>, index: usize) -> i32 { if let BlockContent::Paragraph(paragraph) = &blocks[index] { let txt = paragraph.to_txt(); if let Some(date_) = decode_date_maybe(&txt) { *date = Some(Box::new(date_)); blocks.remove(index); return -1; } } 0 } fn detect_keywords( keywords: &mut Option<Vec<String>>, blocks: &mut Vec<BlockContent>, index: usize, ) -> i32 { static BEGINS_REGEX: Lazy<Regex> = Lazy::new(|| { Regex::new("^(?:K|k)eywords?\\b(?:[^\\w]*)?(.*)").expect("Unable to create regex") }); static SPLIT_REGEX: Lazy<Regex> = Lazy::new(|| Regex::new("\\s*;|,\\s*").expect("Unable to create regex")); if let BlockContent::Paragraph(paragraph) = &blocks[index] { let txt = paragraph.to_txt(); if let Some(captures) = BEGINS_REGEX.captures(&txt) { let keywords_ = SPLIT_REGEX .split(&captures[1]) .map(|str| str.to_string()) .collect(); *keywords = Some(keywords_); blocks.remove(index); return -1; } } 0 } fn detect_abstract( abstract_: &mut Option<Box<ThingDescription>>, blocks: &mut Vec<BlockContent>, index: usize, ) -> i32 { let is_abstract = match &blocks[index] { BlockContent::Heading(heading) => { let txt = heading.to_txt(); txt.trim() == "Abstract" } BlockContent::Paragraph(paragraph) => { let txt = paragraph.to_txt(); txt.trim() == "Abstract" } _ => false, }; if !is_abstract { return 0; } blocks.remove(index); let mut removed = 1; let mut content: Vec<BlockContent> = Vec::new(); while index < blocks.len() { let next = &blocks[index]; match next { BlockContent::Paragraph(_) => { content.push(next.clone()); blocks.remove(index); removed += 1; } _ => break, } } *abstract_ = Some(Box::new(ThingDescription::VecBlockContent(content))); -removed } #[cfg(test)] mod tests { use super::*; use crate::methods::decode::yaml; use crate::utils::tests::snapshot_fixtures; use insta::assert_json_snapshot; #[test] fn reshape_yaml_articles() { snapshot_fixtures("articles/reshape-*.yaml", |_path, content| { let mut article = yaml::decode(&content).expect("Unable to decode YAML"); reshape(&mut article, Options::default()).expect("Unable to reshape"); assert_json_snapshot!(article); }); } }
use super::decode::date::decode_date_maybe; use super::decode::person::decode_person; use super::encode::txt::ToTxt; use defaults::Defaults; use eyre::Result; use once_cell::sync::Lazy; use regex::Regex; use stencila_schema::{ Article, BlockContent, CreativeWorkAuthors, CreativeWorkTitle, Date, InlineContent, Node, Paragraph, Person, ThingDescription, }; #[derive(Defaults)] pub struct Options { #[def = "true"] article: bool, #[def = "true"] detect_title: bool, #[def = "true"] infer_title: bool, #[def = "true"] detect_authors: bool, #[def = "true"] infer_authors: bool, #[def = "true"] detect_date: bool, #[def = "true"] infer_date: bool, #[def = "true"] detect_keywords: bool, #[def = "true"] detect_abstract: bool, } pub fn reshape(node: &mut Node, options: Options) -> Result<()> { if let (Node::Article(article), true) = (node, &options.article) { reshape_article(article, &options) } Ok(()) } pub fn reshape_article(article: &mut Article, options: &Options) { if let Some(blocks) = &mut article.content { let mut index = 0; while index < blocks.len() { let mut delta = 1; if index == 0 { if article.title.is_none() && options.detect_title { delta += detect_title(&mut article.title, blocks, index) } if !blocks.is_empty() && article.title.is_none() && options.infer_title { delta += infer_title(&mut article.title, blocks, index) } if !blocks.is_empty() && article.authors.is_none() && options.detect_authors { delta += detect_authors(&mut article.authors, blocks, index) } if !blocks.is_empty() && article.authors.is_none() && options.infer_authors { delta += infer_authors(&mut article.authors, blocks, index) } if !blocks.is_empty() && article.date_modified.is_none() && options.detect_date { delta += detect_date(&mut article.date_modified, blocks, index) } if !blocks.is_empty() && article.date_modified.is_none() && options.infer_date { delta += infer_date(&mut article.date_modified, blocks, index) } if !blocks.is_empty() && article.keywords.is_none() && options.detect_keywords { delta += detect_keywords(&mut article.keywords, blocks, index) } if !blocks.is_empty() && article.description.is_none() && options.detect_abstract { delta += detect_abstract(&mut article.description, blocks, index) } } index = index.saturating_add(delta.max(0) as usize); } } } fn first_is_strong(paragraph: &Paragraph) -> bool { matches!(paragraph.content.first(), Some(InlineContent::Strong(_))) } fn first_is_emphasis(paragraph: &Paragraph) -> bool { matches!(paragraph.content.first(), Some(InlineContent::Emphasis(_))) } fn has_superscript(paragraph: &Paragraph) -> bool { paragraph .content .iter() .any(|inline| matches!(inline, InlineContent::Superscript(_))) } fn remove_first_mark(paragraph: &Paragraph) -> Vec<InlineContent> { let mut content = match paragraph.content.first() { Some(InlineContent::Emphasis(emphasis)) => emphasis.content.clone(), Some(InlineContent::Strong(strong)) => strong.content.clone(), _ => Vec::new(), }; let mut rest = paragraph.content.clone(); rest.remove(0); content.append(&mut rest); content } fn detect_title( title: &mut Option<Box<CreativeWorkTitle>>, blocks: &mut Vec<BlockContent>, index: usize, ) -> i32 { static BEGINS_REGEX: Lazy<Regex> = Lazy::new(|| { Regex::new("^(?:T|t)itle\\b(?:[^\\w]*)?(.*)").expect("Unable to create regex") }); if let BlockContent::Paragraph(paragraph) = &blocks[index] { let txt = paragraph.to_txt(); if let Some(captures) = BEGINS_REGEX.captures(&txt) { *title = Some(Box::new(CreativeWorkTitle::VecInlineContent(vec![ InlineContent::String(captures[1].to_string()), ]))); blocks.remove(index); return -1; } } 0 } fn infer_title( title: &mut Option<Box<CreativeWorkTitle>>, blocks: &mut Vec<BlockContent>, index: usize, ) -> i32 { let inferred = match &blocks[index] { BlockContent::Heading(heading) => { if heading.depth == Some(1) { Some(Box::new(CreativeWorkTitle::VecInlineContent( heading.content.clone(), ))) } else { None } } BlockContent::Paragraph(paragraph) => { if first_is_strong(paragraph) || first_is_emphasis(paragraph) { Some(Box::new(CreativeWorkTitle::VecInlineContent( remove_first_mark(paragraph), ))) } else { None } } _ => None, }; if inferred.is_some() { *title = inferred; blocks.remove(index); -1 } else { 0 } } fn detect_authors( authors: &mut Option<Vec<CreativeWorkAuthors>>, blocks: &mut Vec<BlockContent>, index: usize, ) -> i32 { static BEGINS_REGEX: Lazy<Regex> = Lazy::new(|| { Regex::new("^(?:A|a)uthors?\\b(?:[^\\w]*)?(.*)").expect("Unable to create r
BEGINS_REGEX: Lazy<Regex> = Lazy::new(|| Regex::new("^(?:D|d)ate\\b(?:[^\\w]*)?(.*)").expect("Unable to create regex")); if let BlockContent::Paragraph(paragraph) = &blocks[index] { let txt = paragraph.to_txt(); if let Some(captures) = BEGINS_REGEX.captures(&txt) { if let Some(date_) = decode_date_maybe(&captures[1]) { *date = Some(Box::new(date_)); blocks.remove(index); return -1; } } } 0 } fn infer_date(date: &mut Option<Box<Date>>, blocks: &mut Vec<BlockContent>, index: usize) -> i32 { if let BlockContent::Paragraph(paragraph) = &blocks[index] { let txt = paragraph.to_txt(); if let Some(date_) = decode_date_maybe(&txt) { *date = Some(Box::new(date_)); blocks.remove(index); return -1; } } 0 } fn detect_keywords( keywords: &mut Option<Vec<String>>, blocks: &mut Vec<BlockContent>, index: usize, ) -> i32 { static BEGINS_REGEX: Lazy<Regex> = Lazy::new(|| { Regex::new("^(?:K|k)eywords?\\b(?:[^\\w]*)?(.*)").expect("Unable to create regex") }); static SPLIT_REGEX: Lazy<Regex> = Lazy::new(|| Regex::new("\\s*;|,\\s*").expect("Unable to create regex")); if let BlockContent::Paragraph(paragraph) = &blocks[index] { let txt = paragraph.to_txt(); if let Some(captures) = BEGINS_REGEX.captures(&txt) { let keywords_ = SPLIT_REGEX .split(&captures[1]) .map(|str| str.to_string()) .collect(); *keywords = Some(keywords_); blocks.remove(index); return -1; } } 0 } fn detect_abstract( abstract_: &mut Option<Box<ThingDescription>>, blocks: &mut Vec<BlockContent>, index: usize, ) -> i32 { let is_abstract = match &blocks[index] { BlockContent::Heading(heading) => { let txt = heading.to_txt(); txt.trim() == "Abstract" } BlockContent::Paragraph(paragraph) => { let txt = paragraph.to_txt(); txt.trim() == "Abstract" } _ => false, }; if !is_abstract { return 0; } blocks.remove(index); let mut removed = 1; let mut content: Vec<BlockContent> = Vec::new(); while index < blocks.len() { let next = &blocks[index]; match next { BlockContent::Paragraph(_) => { content.push(next.clone()); blocks.remove(index); removed += 1; } _ => break, } } *abstract_ = Some(Box::new(ThingDescription::VecBlockContent(content))); -removed } #[cfg(test)] mod tests { use super::*; use crate::methods::decode::yaml; use crate::utils::tests::snapshot_fixtures; use insta::assert_json_snapshot; #[test] fn reshape_yaml_articles() { snapshot_fixtures("articles/reshape-*.yaml", |_path, content| { let mut article = yaml::decode(&content).expect("Unable to decode YAML"); reshape(&mut article, Options::default()).expect("Unable to reshape"); assert_json_snapshot!(article); }); } }
egex") }); static SPLIT_REGEX: Lazy<Regex> = Lazy::new(|| Regex::new("\\s*;|(and)|&\\s*").expect("Unable to create regex")); if let BlockContent::Paragraph(paragraph) = &blocks[index] { let txt = paragraph.to_txt(); if let Some(captures) = BEGINS_REGEX.captures(&txt) { let authors_ = SPLIT_REGEX .split(&captures[1]) .map(|str| CreativeWorkAuthors::Person(decode_person(str))) .collect(); *authors = Some(authors_); blocks.remove(index); return -1; } } 0 } fn infer_authors( authors: &mut Option<Vec<CreativeWorkAuthors>>, blocks: &mut Vec<BlockContent>, index: usize, ) -> i32 { let inferred = match &blocks[index] { BlockContent::Paragraph(paragraph) => { if has_superscript(paragraph) { Some(vec![CreativeWorkAuthors::Person(Person { name: Some(Box::new("superscripted".to_string())), ..Default::default() })]) } else { None } } _ => None, }; if inferred.is_some() { *authors = inferred; blocks.remove(index); -1 } else { 0 } } fn detect_date(date: &mut Option<Box<Date>>, blocks: &mut Vec<BlockContent>, index: usize) -> i32 { static
random
[ { "content": "/// Decode any front matter in a Markdown document into a `Node`\n\n///\n\n/// Any front matter will be coerced into a `Node`, defaulting to the\n\n/// `Node::Article` variant, if `type` is not defined.\n\n/// If there is no front matter detected, will return `None`.\n\npub fn decode_frontmatter(md: &str) -> Result<(Option<usize>, Option<Node>)> {\n\n static REGEX: Lazy<Regex> =\n\n Lazy::new(|| Regex::new(\"^-{3,}((.|\\\\n)*)?\\\\n-{3,}\").expect(\"Unable to create regex\"));\n\n\n\n if let Some(captures) = REGEX.captures(md) {\n\n let end = Some(captures[0].len());\n\n\n\n let yaml = captures[1].trim().to_string();\n\n if yaml.is_empty() {\n\n return Ok((end, None));\n\n }\n\n\n\n let node = match serde_yaml::from_str(&yaml) {\n\n Ok(serde_json::Value::Object(mut node)) => {\n\n if node.get(\"type\").is_none() {\n\n node.insert(\n\n \"type\".to_string(),\n\n serde_json::Value::String(\"Article\".to_string()),\n\n );\n\n }\n", "file_path": "rust/src/methods/decode/md.rs", "rank": 3, "score": 393931.52690795495 }, { "content": "/// Decode plain text to a `Node`\n\n///\n\n/// Attempts to decode as a JSON5 string first, falling back\n\n/// to unquoting a string, falling back to just returning a\n\n/// string node.\n\n///\n\n/// Uses JSON5 over JSON, as a more permissive standard (e.g. strings can\n\n/// be single quoted) and thus able to deal with representations of values\n\n/// that are not strictly JSON (e.g. a Python dict repr).\n\n///\n\n/// This function is useful in contexts where some text may or may not\n\n/// represent a boolean, number or some other JSON object, for example\n\n/// the output of a Jupyter code cell where a `dict` has a representation\n\n/// which can be parsed as a JSON object.\n\npub fn decode(txt: &str) -> Result<Node> {\n\n Ok(decode_fragment(txt))\n\n}\n\n\n", "file_path": "rust/src/methods/decode/txt.rs", "rank": 4, "score": 380906.957778991 }, { "content": "/// Encode a `Node` to a JSON document\n\n///\n\n/// Defaults to pretty (indented). Use `compact: true` option for no indentation.\n\npub fn encode(node: &Node, options: Option<Options>) -> Result<String> {\n\n let compact = options.map_or_else(|| false, |options| options.compact);\n\n let json = match compact {\n\n true => serde_json::to_string::<Node>(node)?,\n\n false => serde_json::to_string_pretty::<Node>(node)?,\n\n };\n\n Ok(json)\n\n}\n", "file_path": "rust/src/methods/encode/json.rs", "rank": 5, "score": 375564.95699958596 }, { "content": "/// Encode a `Node` to a JSON5 document\n\n///\n\n/// At the time of writing, the `json5` crate actually produces plain\n\n/// old JSON, and does not offer pretty printing (so we use `serde_json` for that).\n\npub fn encode(node: &Node, options: Option<Options>) -> Result<String> {\n\n let Options { theme, .. } = options.unwrap_or_default();\n\n let json = match theme.as_str() {\n\n \"compact\" => json5::to_string::<Node>(node)?,\n\n _ => serde_json::to_string_pretty::<Node>(node)?,\n\n };\n\n Ok(json)\n\n}\n", "file_path": "rust/src/methods/encode/json5.rs", "rank": 6, "score": 375553.91782104364 }, { "content": "/// Encode a `Node` to a HTML document\n\npub fn encode(node: &Node, options: Option<Options>) -> Result<String> {\n\n let html = encode_address(node, options.clone());\n\n\n\n let Options {\n\n theme, standalone, ..\n\n } = options.unwrap_or_default();\n\n\n\n let html = if standalone {\n\n wrap_standalone(\"\", &theme, &html)\n\n } else {\n\n html\n\n };\n\n\n\n Ok(html)\n\n}\n\n\n", "file_path": "rust/src/methods/encode/html/mod.rs", "rank": 7, "score": 371929.4030423286 }, { "content": "/// Encode a `Node` to plain, unstructured text\n\n///\n\n/// This is an an intentionally lossy encoding for when a\n\n/// plain text encoding of a node is needed. The only structure\n\n/// is adds is placing two newlines after each `BlockContent`\n\n/// node. e.g. paragraphs, code blocks\n\npub fn encode(node: &Node) -> Result<String> {\n\n Ok(node.to_txt().trim().to_string())\n\n}\n\n\n", "file_path": "rust/src/methods/encode/txt.rs", "rank": 8, "score": 362561.5204790984 }, { "content": "/// Lock the global config store\n\npub fn lock(cx: &mut FunctionContext) -> NeonResult<MutexGuard<'static, Config>> {\n\n match CONFIG.try_lock() {\n\n Ok(guard) => Ok(guard),\n\n Err(error) => cx.throw_error(format!(\n\n \"When attempting to obtain config: {}\",\n\n error.to_string()\n\n )),\n\n }\n\n}\n\n\n", "file_path": "node/src/config.rs", "rank": 9, "score": 344006.88324564905 }, { "content": "/// Lock the global plugins store\n\npub fn lock(cx: &mut FunctionContext) -> NeonResult<MutexGuard<'static, Plugins>> {\n\n match PLUGINS.try_lock() {\n\n Ok(guard) => Ok(guard),\n\n Err(error) => cx.throw_error(format!(\n\n \"When attempting to lock plugins: {}\",\n\n error.to_string()\n\n )),\n\n }\n\n}\n\n\n", "file_path": "node/src/plugins.rs", "rank": 10, "score": 344006.88324564905 }, { "content": "pub fn execute<Type>(node: &mut Type, kernels: &mut KernelSpace) -> Result<()>\n\nwhere\n\n Type: Compile,\n\n{\n\n node.execute(kernels)\n\n}\n\n\n\n/// The compilation context, used to pass down properties of the\n\n/// root node and to record inputs and outputs etc during compilation\n\n#[derive(Debug, Default)]\n\npub struct Context {\n\n /// The path of the document being compiled.\n\n /// Used to resolve relative paths e.g. in `ImageObject` and `Include` nodes\n\n path: PathBuf,\n\n\n\n /// The project that the document is within.\n\n /// Used to restrict any file links to be within the project\n\n project: PathBuf,\n\n\n\n /// A map of node ids to addresses\n\n pub addresses: HashMap<String, Address>,\n\n\n\n /// Relations with other resources for each compiled resource\n\n /// in the document.\n\n pub relations: Vec<(Resource, Vec<(Relation, Resource)>)>,\n\n}\n\n\n", "file_path": "rust/src/methods/compile/mod.rs", "rank": 11, "score": 342439.3748631672 }, { "content": "/// Decode a string into a `Node::Date` variant.\n\n///\n\n/// Always returns an `Ok` result with a `Node::Date` value\n\n/// but its `value` may be `None`.\n\npub fn decode(input: &str) -> Result<Node> {\n\n Ok(Node::Date(decode_date(input)))\n\n}\n\n\n", "file_path": "rust/src/methods/decode/date.rs", "rank": 12, "score": 338383.07169868983 }, { "content": "/// Decode a string into a `Node::Person` variant.\n\n///\n\n/// Always returns an `Ok` result with a `Node::Person` value.\n\npub fn decode(input: &str) -> Result<Node> {\n\n Ok(Node::Person(decode_person(input)))\n\n}\n\n\n", "file_path": "rust/src/methods/decode/person.rs", "rank": 13, "score": 338378.68592883216 }, { "content": "/// Create a document\n\npub fn create(mut cx: FunctionContext) -> JsResult<JsString> {\n\n let path = not_empty_or_none(&cx.argument::<JsString>(0)?.value(&mut cx));\n\n let format = not_empty_or_none(&cx.argument::<JsString>(1)?.value(&mut cx));\n\n\n\n let result = RUNTIME.block_on(async { DOCUMENTS.create(path, format).await });\n\n to_json_or_throw(cx, result)\n\n}\n\n\n", "file_path": "node/src/documents.rs", "rank": 14, "score": 337107.68647604657 }, { "content": "/// Apply a [`Patch`] to a node.\n\npub fn apply<Type>(node: &mut Type, patch: &Patch) -> Result<()>\n\nwhere\n\n Type: Patchable,\n\n{\n\n node.apply_patch(patch)\n\n}\n\n\n", "file_path": "rust/src/patches/mod.rs", "rank": 15, "score": 335886.6298484208 }, { "content": "/// Decode a HTML document to a `Node`\n\n///\n\n/// Intended for decoding an entire document into an `Article`.\n\npub fn decode(html: &str, decode_text_as_markdown: bool) -> Result<Node> {\n\n let content = decode_fragment(html, decode_text_as_markdown);\n\n\n\n let article = Article {\n\n content: Some(content),\n\n ..Default::default()\n\n };\n\n\n\n Ok(Node::Article(article))\n\n}\n\n\n", "file_path": "rust/src/methods/decode/html.rs", "rank": 16, "score": 335039.04421096214 }, { "content": "/// Obtain the subscriptions store\n\npub fn obtain(cx: &mut FunctionContext) -> NeonResult<MutexGuard<'static, Vec<JsSubscription>>> {\n\n match SUBSCRIPTIONS.try_lock() {\n\n Ok(guard) => Ok(guard),\n\n Err(error) => cx.throw_error(format!(\n\n \"When attempting to obtain subscriptions: {}\",\n\n error.to_string()\n\n )),\n\n }\n\n}\n\n\n", "file_path": "node/src/pubsub.rs", "rank": 17, "score": 330035.74823224416 }, { "content": "/// Coerce a JSON value to the Stencila JSON Schema\n\n///\n\n/// This function is intended to be used prior to deserializing\n\n/// generic data formats e.g JSON, YAML to to a `Node`.\n\n/// For example, coercing an object to the schema avoids `serde` treating\n\n/// it as the lowest common denominator type i.e. an `Entity` unless all of\n\n/// its properties match the schema.\n\n///\n\n/// Examples of places where this might be necessary:\n\n/// - when decoding JSON, YAML, etc documents\n\n/// - when deserializing the result from delegating a method\n\n/// to a peer or plugin\n\n/// - when decoding the YAML header of a Markdown document\n\npub fn coerce(value: JsonValue, type_: Option<String>) -> Result<Node> {\n\n let type_ = if type_.is_some() {\n\n type_\n\n } else {\n\n value\n\n .get(\"type\")\n\n .and_then(|value| value.as_str())\n\n .map(|type_| type_.to_string())\n\n };\n\n\n\n if let Some(type_) = type_ {\n\n let mut value = value;\n\n coerce_to_type(&mut value, &type_);\n\n let node = serde_json::from_value(value)?;\n\n return Ok(node);\n\n }\n\n\n\n Ok(match coerce_to_primitive(value) {\n\n Primitive::Null(node) => Node::Null(node),\n\n Primitive::Boolean(node) => Node::Boolean(node),\n", "file_path": "rust/src/methods/coerce/mod.rs", "rank": 18, "score": 328006.4662261397 }, { "content": "/// Compile a node\n\n///\n\n/// Compiling a document involves walking over the node tree and compiling each\n\n/// individual node so that it is ready to be built & executed. This includes\n\n/// (but is not limited to):\n\n///\n\n/// - for those node types needing to be accesses directly (e.g. executable nodes) ensuring\n\n/// they have an `id` and recording their address\n\n/// - for executable nodes (e.g. `CodeChunk`) performing semantic analysis of the code\n\n/// - determining dependencies within and between documents and other resources\n\npub fn compile(node: &mut Node, path: &Path, project: &Path) -> Result<(Addresses, Relations)> {\n\n let mut address = Address::default();\n\n let mut context = Context {\n\n path: PathBuf::from(path),\n\n project: PathBuf::from(project),\n\n ..Default::default()\n\n };\n\n node.compile(&mut address, &mut context)?;\n\n\n\n let addresses = context.addresses;\n\n let relations = context.relations.into_iter().collect();\n\n Ok((addresses, relations))\n\n}\n\n\n", "file_path": "rust/src/methods/compile/mod.rs", "rank": 19, "score": 327731.34924537246 }, { "content": "/// Encode a `Node` to R Markdown\n\npub fn encode(node: &Node) -> Result<String> {\n\n let mut node = node.clone();\n\n if let Node::Article(article) = &mut node {\n\n if let Some(content) = &mut article.content {\n\n transform_blocks(content)\n\n }\n\n }\n\n md::encode(&node)\n\n}\n\n\n", "file_path": "rust/src/methods/encode/rmd.rs", "rank": 21, "score": 318037.03271815705 }, { "content": "/// Encode a `Node` to Markdown\n\npub fn encode(node: &Node) -> Result<String> {\n\n Ok(node.to_md().trim().to_string())\n\n}\n\n\n", "file_path": "rust/src/methods/encode/md.rs", "rank": 22, "score": 318031.4156112723 }, { "content": "/// Encode a `Node` to a YAML document\n\npub fn encode(node: &Node) -> Result<String> {\n\n Ok(serde_yaml::to_string::<Node>(node)?)\n\n}\n", "file_path": "rust/src/methods/encode/yaml.rs", "rank": 23, "score": 318031.35958810116 }, { "content": "/// Encode a `Node` to a TOML document\n\n///\n\n/// TOML is not recommended for large complex documents and encoding\n\n/// may fail with the error \"values must be emitted before tables\".\n\npub fn encode(node: &Node) -> Result<String> {\n\n Ok(toml::to_string::<Node>(node)?)\n\n}\n", "file_path": "rust/src/methods/encode/toml.rs", "rank": 24, "score": 318030.7223517328 }, { "content": "/// Encode a `Node` to a Jupyter Notebook.\n\n///\n\n/// Note that the order of properties in various JSON objects is\n\n/// consistent with Jupyter and other tools. Also, the JSON is\n\n/// pretty printed with a one space indentation.\n\npub fn encode(node: &Node) -> Result<String> {\n\n let article = match node {\n\n Node::Article(article) => article,\n\n _ => bail!(\"Only able to encode an `Article` as a Jupyter Notebook`\"),\n\n };\n\n\n\n let notebook = json!({\n\n \"cells\": encode_content(&article.content),\n\n \"metadata\": encode_metadata(article),\n\n \"nbformat\": 4,\n\n \"nbformat_minor\": 5\n\n });\n\n\n\n let buffer = Vec::new();\n\n let formatter = serde_json::ser::PrettyFormatter::with_indent(b\" \");\n\n let mut serializer = serde_json::Serializer::with_formatter(buffer, formatter);\n\n notebook.serialize(&mut serializer).unwrap();\n\n let json = String::from_utf8(serializer.into_inner())?;\n\n\n\n Ok(json)\n\n}\n\n\n", "file_path": "rust/src/methods/encode/ipynb.rs", "rank": 25, "score": 318030.59576290357 }, { "content": "/// Decode plain text to a `Node`, infallibly.\n\n///\n\n/// This function simply exists for when you want a `Node`, rather\n\n/// than a `Result<Node>` which is the return signature of all decode functions.\n\npub fn decode_fragment(txt: &str) -> Node {\n\n match txt.trim() {\n\n \"true\" | \"TRUE\" | \"True\" => return Node::Boolean(true),\n\n \"false\" | \"FALSE\" | \"False\" => return Node::Boolean(false),\n\n \"null\" | \"NULL\" | \"Null\" => return Node::Null(Null {}),\n\n _ => (),\n\n };\n\n\n\n if let Ok(node) = json5::decode(txt) {\n\n return node;\n\n }\n\n\n\n Node::String(txt.to_string())\n\n}\n\n\n\n#[cfg(test)]\n\nmod tests {\n\n use super::*;\n\n use crate::assert_json_eq;\n\n use eyre::bail;\n", "file_path": "rust/src/methods/decode/txt.rs", "rank": 26, "score": 314733.79346779437 }, { "content": "/// If a string is empty then return `None`, otherwise `Some(text)`\n\npub fn not_empty_or_none(text: &str) -> Option<String> {\n\n if text.is_empty() {\n\n None\n\n } else {\n\n Some(text.into())\n\n }\n\n}\n\n\n", "file_path": "node/src/prelude.rs", "rank": 27, "score": 313445.51697901153 }, { "content": "/// Generate the HTML fragment for an address within a node\n\n///\n\n/// This function is used when translating a `Operation` (where any value of\n\n/// the operation is a `Node` and the operation is applied to a `Node`) to a `DomOperation`\n\n/// (where any value is either a HTML or JSON string and the operation is applied to a browser DOM).\n\npub fn encode_address(node: &Node, options: Option<Options>) -> String {\n\n let Options {\n\n bundle, compact, ..\n\n } = options.unwrap_or_default();\n\n\n\n let context = Context { root: node, bundle };\n\n let html = node.to_html(\"root\", &context);\n\n\n\n if compact {\n\n html\n\n } else {\n\n indent(&html)\n\n }\n\n}\n\n\n", "file_path": "rust/src/methods/encode/html/mod.rs", "rank": 28, "score": 311576.81039064366 }, { "content": "/// Encode a `Node` to a Pandoc document\n\n///\n\n/// Compared to the `encode` function this function does not spawn a Pandoc\n\n/// process, or ceate RPNGS and returns a `pandoc_types` definition instead.\n\n/// It intended mainly for generative testing.\n\npub fn encode_node(node: &Node) -> Result<pandoc::Pandoc> {\n\n let mut context = Context::new()?;\n\n let pandoc = node.to_pandoc(&mut context);\n\n Ok(pandoc)\n\n}\n\n\n\n/// Encode a Pandoc document to desired format.\n\n///\n\n/// Calls Pandoc binary to convert the Pandoc JSON to the desired format.\n\nasync fn encode_pandoc(\n\n doc: pandoc::Pandoc,\n\n output: &str,\n\n format: &str,\n\n args: &[String],\n\n) -> Result<String> {\n\n let json = serde_json::to_string(&doc)?;\n\n\n\n if format == \"pandoc\" {\n\n Ok(json)\n\n } else {\n", "file_path": "rust/src/methods/encode/pandoc.rs", "rank": 29, "score": 310449.8119379987 }, { "content": "#[extendr]\n\nfn serve(url: Option<String>, background: Option<bool>) -> Result<()> {\n\n let background = background.unwrap_or(false);\n\n match if background {\n\n stencila::serve::serve_background(url, None)\n\n } else {\n\n stencila::serve::serve_blocking(url, None)\n\n } {\n\n Ok(_) => Ok(()),\n\n Err(error) => Err(Error::Other(error.to_string())),\n\n }\n\n}\n\n\n\nextendr_module! {\n\n mod stencila;\n\n fn init;\n\n fn serve;\n\n}\n", "file_path": "r/src/lib.rs", "rank": 30, "score": 310135.0725031878 }, { "content": "/// Attempt to decode a string to a `Person` struct.\n\n///\n\n/// Returns `Some(Person)` if parsing was successful, `None` otherwise.\n\npub fn decode_person_maybe(input: &str) -> Option<Person> {\n\n if let Some(name) = human_name::Name::parse(input) {\n\n let given_names = if let Some(first_name) = name.given_name() {\n\n let mut given_names = vec![first_name.to_string()];\n\n if let Some(middle_names) = name.middle_names() {\n\n let mut middle_names = middle_names\n\n .iter()\n\n .map(|str| str.to_string())\n\n .collect::<Vec<String>>();\n\n given_names.append(&mut middle_names)\n\n }\n\n Some(given_names)\n\n } else {\n\n None\n\n };\n\n\n\n let family_names = if name.surnames().is_empty() {\n\n None\n\n } else {\n\n Some(\n", "file_path": "rust/src/methods/decode/person.rs", "rank": 31, "score": 306782.1443471988 }, { "content": "/// Attempt to decode a string to a `Date` struct.\n\n///\n\n/// Returns `Some(Date)` if parsing was successful, `None` otherwise.\n\npub fn decode_date_maybe(input: &str) -> Option<Date> {\n\n if let Ok((naive, offset)) = dtparse::parse(input) {\n\n let utc = match offset {\n\n Some(offset) => {\n\n let tz = offset.from_local_datetime(&naive).unwrap();\n\n DateTime::<Utc>::from(tz)\n\n }\n\n None => {\n\n let local = Local.from_local_datetime(&naive).unwrap();\n\n DateTime::<Utc>::from(local)\n\n }\n\n };\n\n Some(Date {\n\n value: utc.to_rfc3339(),\n\n ..Default::default()\n\n })\n\n } else {\n\n None\n\n }\n\n}\n", "file_path": "rust/src/methods/decode/date.rs", "rank": 32, "score": 306778.0575765202 }, { "content": "/// Get the directory where configuration data is stored\n\npub fn dir(ensure: bool) -> Result<PathBuf> {\n\n let config_base = dirs_next::config_dir().unwrap_or_else(|| env::current_dir().unwrap());\n\n let dir = match env::consts::OS {\n\n \"macos\" => config_base.join(\"Stencila\"),\n\n \"windows\" => config_base.join(\"Stencila\").join(\"Config\"),\n\n _ => config_base.join(\"stencila\"),\n\n };\n\n if ensure {\n\n fs::create_dir_all(&dir)?;\n\n }\n\n Ok(dir)\n\n}\n\n\n", "file_path": "rust/src/config.rs", "rank": 33, "score": 298164.61457228125 }, { "content": "/// Get the directory within which plugins and their configurations are installed\n\npub fn plugins_dir(ensure: bool) -> Result<PathBuf> {\n\n let user_data_dir = dirs_next::data_dir().unwrap_or_else(|| env::current_dir().unwrap());\n\n let dir = match env::consts::OS {\n\n \"macos\" | \"windows\" => user_data_dir.join(\"Stencila\").join(\"Plugins\"),\n\n _ => user_data_dir.join(\"stencila\").join(\"plugins\"),\n\n };\n\n if ensure {\n\n fs::create_dir_all(&dir)?;\n\n }\n\n Ok(dir)\n\n}\n\n\n\n/// Plugin installation method\n\n///\n\n/// Which method to use to install a plugin.\n\n#[derive(\n\n Debug, Display, Clone, Copy, EnumString, EnumIter, PartialEq, JsonSchema, Deserialize, Serialize,\n\n)]\n\n#[serde(rename_all = \"lowercase\")]\n\n#[strum(serialize_all = \"lowercase\")]\n", "file_path": "rust/src/plugins.rs", "rank": 34, "score": 294442.71903089824 }, { "content": "/// Get the entire global configuration object\n\npub fn get(mut cx: FunctionContext) -> JsResult<JsString> {\n\n let config = lock(&mut cx)?;\n\n to_json(cx, config.clone())\n\n}\n\n\n", "file_path": "node/src/config.rs", "rank": 35, "score": 294341.27338437387 }, { "content": "pub fn init(mut cx: FunctionContext) -> JsResult<JsUndefined> {\n\n let conf = match cx.argument_opt(0) {\n\n Some(arg) => {\n\n let json = arg\n\n .downcast::<JsString, FunctionContext>(&mut cx)\n\n .or_throw(&mut cx)?\n\n .value(&mut cx);\n\n from_json::<Config>(&mut cx, &json)?\n\n }\n\n None => crate::config::lock(&mut cx)?.clone(),\n\n };\n\n\n\n // Do not emit log events to stderr, instead enable pubsub and file handlers\n\n if let Err(error) = logging::init(false, true, true, &conf.logging) {\n\n return cx.throw_error(format!(\n\n \"When attempting to initialize logging: {}\",\n\n error.to_string()\n\n ));\n\n };\n\n Ok(cx.undefined())\n\n}\n\n\n", "file_path": "node/src/logging.rs", "rank": 36, "score": 294341.27338437387 }, { "content": "/// Close a document\n\npub fn close(mut cx: FunctionContext) -> JsResult<JsUndefined> {\n\n let id = &cx.argument::<JsString>(0)?.value(&mut cx);\n\n\n\n let result = RUNTIME.block_on(async { DOCUMENTS.close(id).await });\n\n to_undefined_or_throw(cx, result)\n\n}\n", "file_path": "node/src/documents.rs", "rank": 37, "score": 294341.27338437387 }, { "content": "/// Dump a document\n\npub fn dump(mut cx: FunctionContext) -> JsResult<JsString> {\n\n let id = &cx.argument::<JsString>(0)?.value(&mut cx);\n\n let format = cx.argument::<JsString>(1)?.value(&mut cx);\n\n let format = if format.is_empty() {\n\n None\n\n } else {\n\n Some(format)\n\n };\n\n\n\n let result = RUNTIME.block_on(async {\n\n match DOCUMENTS.get(id).await {\n\n Ok(document) => document.lock().await.dump(format).await,\n\n Err(error) => Err(error),\n\n }\n\n });\n\n to_string_or_throw(cx, result)\n\n}\n\n\n", "file_path": "node/src/documents.rs", "rank": 38, "score": 294341.27338437387 }, { "content": "/// List plugins\n\npub fn list(mut cx: FunctionContext) -> JsResult<JsString> {\n\n let aliases = &config::lock(&mut cx)?.plugins.aliases;\n\n let plugins = &*lock(&mut cx)?;\n\n\n\n to_json(cx, plugins.list_plugins(aliases))\n\n}\n\n\n", "file_path": "node/src/plugins.rs", "rank": 39, "score": 294341.27338437387 }, { "content": "/// Alter a document's properties\n\npub fn alter(mut cx: FunctionContext) -> JsResult<JsString> {\n\n let id = &cx.argument::<JsString>(0)?.value(&mut cx);\n\n let path = not_empty_or_none(&cx.argument::<JsString>(1)?.value(&mut cx));\n\n let format = not_empty_or_none(&cx.argument::<JsString>(2)?.value(&mut cx));\n\n\n\n let result = RUNTIME.block_on(async {\n\n match DOCUMENTS.get(id).await {\n\n Ok(document) => {\n\n let document = &mut *document.lock().await;\n\n document.alter(path, format).await?;\n\n Ok(document.clone())\n\n }\n\n Err(error) => Err(error),\n\n }\n\n });\n\n to_json_or_throw(cx, result)\n\n}\n\n\n", "file_path": "node/src/documents.rs", "rank": 40, "score": 294341.27338437387 }, { "content": "/// Publish data for a topic\n\npub fn publish(mut cx: FunctionContext) -> JsResult<JsUndefined> {\n\n let topic = cx.argument::<JsString>(0)?.value(&mut cx);\n\n let json = cx.argument::<JsString>(1)?.value(&mut cx);\n\n\n\n bridging_subscriber(topic, from_json::<serde_json::Value>(&mut cx, &json)?);\n\n\n\n Ok(cx.undefined())\n\n}\n\n\n", "file_path": "node/src/pubsub.rs", "rank": 41, "score": 294341.27338437387 }, { "content": "/// Read a document\n\npub fn read(mut cx: FunctionContext) -> JsResult<JsString> {\n\n let id = &cx.argument::<JsString>(0)?.value(&mut cx);\n\n\n\n let result = RUNTIME.block_on(async {\n\n match DOCUMENTS.get(id).await {\n\n Ok(document) => document.lock().await.read().await,\n\n Err(error) => Err(error),\n\n }\n\n });\n\n to_string_or_throw(cx, result)\n\n}\n\n\n", "file_path": "node/src/documents.rs", "rank": 42, "score": 294341.27338437387 }, { "content": "/// Write a document\n\npub fn write(mut cx: FunctionContext) -> JsResult<JsUndefined> {\n\n let id = &cx.argument::<JsString>(0)?.value(&mut cx);\n\n let content = cx.argument::<JsString>(1)?.value(&mut cx);\n\n let format = not_empty_or_none(&cx.argument::<JsString>(2)?.value(&mut cx));\n\n\n\n let result = RUNTIME.block_on(async {\n\n match DOCUMENTS.get(id).await {\n\n Ok(document) => document.lock().await.write(Some(content), format).await,\n\n Err(error) => Err(error),\n\n }\n\n });\n\n to_undefined_or_throw(cx, result)\n\n}\n\n\n", "file_path": "node/src/documents.rs", "rank": 43, "score": 294341.27338437387 }, { "content": "/// Open a document\n\npub fn open(mut cx: FunctionContext) -> JsResult<JsString> {\n\n let path = &cx.argument::<JsString>(0)?.value(&mut cx);\n\n let format = not_empty_or_none(&cx.argument::<JsString>(1)?.value(&mut cx));\n\n\n\n let result = RUNTIME.block_on(async { DOCUMENTS.open(path, format).await });\n\n to_json_or_throw(cx, result)\n\n}\n\n\n", "file_path": "node/src/documents.rs", "rank": 44, "score": 294341.27338437387 }, { "content": "/// Get a project graph in a desired format\n\npub fn graph(mut cx: FunctionContext) -> JsResult<JsString> {\n\n let path = &cx.argument::<JsString>(0)?.value(&mut cx);\n\n let format = &cx.argument::<JsString>(1)?.value(&mut cx);\n\n\n\n let result = RUNTIME.block_on(async {\n\n match PROJECTS.get(&path).await {\n\n Ok(project) => project.lock().await.graph(format),\n\n Err(error) => Err(error),\n\n }\n\n });\n\n to_string_or_throw(cx, result)\n\n}\n", "file_path": "node/src/projects.rs", "rank": 45, "score": 294341.27338437387 }, { "content": "/// Open a project\n\npub fn open(mut cx: FunctionContext) -> JsResult<JsString> {\n\n let path = &cx.argument::<JsString>(0)?.value(&mut cx);\n\n\n\n let result = RUNTIME.block_on(async { PROJECTS.open(Some(path), true).await });\n\n to_json_or_throw(cx, result)\n\n}\n\n\n", "file_path": "node/src/projects.rs", "rank": 46, "score": 294341.27338437387 }, { "content": "/// Subscribe to one or more of a document's topics\n\npub fn subscribe(mut cx: FunctionContext) -> JsResult<JsUndefined> {\n\n let id = &cx.argument::<JsString>(0)?.value(&mut cx);\n\n let topic = &cx.argument::<JsString>(1)?.value(&mut cx);\n\n\n\n let result = RUNTIME.block_on(async {\n\n match DOCUMENTS.get(id).await {\n\n Ok(document) => {\n\n document.lock().await.subscribe(topic, CLIENT_ID);\n\n Ok(())\n\n }\n\n Err(error) => Err(error),\n\n }\n\n });\n\n to_undefined_or_throw(cx, result)\n\n}\n\n\n", "file_path": "node/src/documents.rs", "rank": 47, "score": 294341.27338437387 }, { "content": "/// Unsubscribe from one or more of a document's topics\n\npub fn unsubscribe(mut cx: FunctionContext) -> JsResult<JsUndefined> {\n\n let id = &cx.argument::<JsString>(0)?.value(&mut cx);\n\n let topic = &cx.argument::<JsString>(1)?.value(&mut cx);\n\n\n\n let result = RUNTIME.block_on(async {\n\n match DOCUMENTS.get(id).await {\n\n Ok(document) => {\n\n document.lock().await.unsubscribe(topic, CLIENT_ID);\n\n Ok(())\n\n }\n\n Err(error) => Err(error),\n\n }\n\n });\n\n to_undefined_or_throw(cx, result)\n\n}\n\n\n", "file_path": "node/src/documents.rs", "rank": 48, "score": 294341.2733843739 }, { "content": "/// Uninstall a plugin\n\npub fn uninstall(mut cx: FunctionContext) -> JsResult<JsString> {\n\n let alias = &cx.argument::<JsString>(0)?.value(&mut cx);\n\n let aliases = &config::lock(&mut cx)?.plugins.aliases;\n\n let plugins = &mut *lock(&mut cx)?;\n\n\n\n match Plugin::uninstall(alias, aliases, plugins) {\n\n Ok(_) => to_json(cx, plugins.list_plugins(aliases)),\n\n Err(error) => cx.throw_error(error.to_string()),\n\n }\n\n}\n\n\n", "file_path": "node/src/plugins.rs", "rank": 49, "score": 294341.27338437387 }, { "content": "/// Initialize the pubsub module by registering the `bridging_subscriber`\n\n/// as a subscriber to all topics.\n\npub fn init(mut cx: FunctionContext) -> JsResult<JsUndefined> {\n\n if let Err(error) = pubsub::subscribe(\"*\", pubsub::Subscriber::Function(bridging_subscriber)) {\n\n return cx.throw_error(format!(\n\n \"While attempting to initialize pubsub: {}\",\n\n error.to_string()\n\n ));\n\n }\n\n Ok(cx.undefined())\n\n}\n", "file_path": "node/src/pubsub.rs", "rank": 50, "score": 294341.27338437387 }, { "content": "/// Upgrade a plugin\n\npub fn upgrade(mut cx: FunctionContext) -> JsResult<JsString> {\n\n let spec = &cx.argument::<JsString>(0)?.value(&mut cx);\n\n let config = &config::lock(&mut cx)?;\n\n let installs = &config.plugins.installations;\n\n let aliases = &config.plugins.aliases;\n\n let plugins = &mut *lock(&mut cx)?;\n\n\n\n match RUNTIME.block_on(async { Plugin::upgrade(spec, installs, aliases, plugins).await }) {\n\n Ok(_) => to_json(cx, plugins.list_plugins(aliases)),\n\n Err(error) => cx.throw_error(error.to_string()),\n\n }\n\n}\n\n\n", "file_path": "node/src/plugins.rs", "rank": 51, "score": 294341.27338437387 }, { "content": "pub fn test(mut cx: FunctionContext) -> JsResult<JsUndefined> {\n\n logging::test_events();\n\n Ok(cx.undefined())\n\n}\n", "file_path": "node/src/logging.rs", "rank": 52, "score": 294341.27338437387 }, { "content": "/// Load a document\n\npub fn load(mut cx: FunctionContext) -> JsResult<JsUndefined> {\n\n let id = &cx.argument::<JsString>(0)?.value(&mut cx);\n\n let content = cx.argument::<JsString>(1)?.value(&mut cx);\n\n let format = not_empty_or_none(&cx.argument::<JsString>(2)?.value(&mut cx));\n\n\n\n let result = RUNTIME.block_on(async {\n\n match DOCUMENTS.get(id).await {\n\n Ok(document) => document.lock().await.load(content, format).await,\n\n Err(error) => Err(error),\n\n }\n\n });\n\n to_undefined_or_throw(cx, result)\n\n}\n\n\n", "file_path": "node/src/documents.rs", "rank": 53, "score": 294341.27338437387 }, { "content": "/// Get a document\n\npub fn get(mut cx: FunctionContext) -> JsResult<JsString> {\n\n let id = &cx.argument::<JsString>(0)?.value(&mut cx);\n\n\n\n let result = RUNTIME.block_on(async {\n\n match DOCUMENTS.get(id).await {\n\n Ok(document) => {\n\n let document = &mut *document.lock().await;\n\n Ok(document.clone())\n\n }\n\n Err(error) => Err(error),\n\n }\n\n });\n\n to_json_or_throw(cx, result)\n\n}\n\n\n", "file_path": "node/src/documents.rs", "rank": 54, "score": 294341.2733843739 }, { "content": "/// Start collecting errors\n\npub fn start(mut cx: FunctionContext) -> JsResult<JsUndefined> {\n\n errors::start();\n\n Ok(cx.undefined())\n\n}\n\n\n", "file_path": "node/src/errors.rs", "rank": 55, "score": 294341.27338437387 }, { "content": "/// Subscribe to a topic\n\npub fn subscribe(mut cx: FunctionContext) -> JsResult<JsUndefined> {\n\n let topic = cx.argument::<JsString>(0)?.value(&mut cx);\n\n let subscriber = cx.argument::<JsFunction>(1)?.root(&mut cx);\n\n\n\n let channel = cx.channel();\n\n if CHANNEL.set(channel).is_err() {\n\n // Ignore because it just means channel was already set\n\n }\n\n\n\n let mut subscriptions = obtain(&mut cx)?;\n\n subscriptions.push(JsSubscription { topic, subscriber });\n\n\n\n Ok(cx.undefined())\n\n}\n\n\n", "file_path": "node/src/pubsub.rs", "rank": 56, "score": 294341.27338437387 }, { "content": "/// Set the entire global configuration object\n\npub fn set(mut cx: FunctionContext) -> JsResult<JsString> {\n\n let json = cx.argument::<JsString>(0)?.value(&mut cx);\n\n\n\n // Set the config from JSON and write to disk\n\n let config = &mut *lock(&mut cx)?;\n\n *config = from_json::<Config>(&mut cx, &json)?;\n\n if let Err(error) = config.write() {\n\n return cx.throw_error(error.to_string());\n\n }\n\n\n\n to_json(cx, config.clone())\n\n}\n\n\n", "file_path": "node/src/config.rs", "rank": 57, "score": 294341.27338437387 }, { "content": "/// Write a document to another path / format\n\npub fn write_as(mut cx: FunctionContext) -> JsResult<JsUndefined> {\n\n let id = &cx.argument::<JsString>(0)?.value(&mut cx);\n\n let path = cx.argument::<JsString>(1)?.value(&mut cx);\n\n let format = cx.argument::<JsString>(2)?.value(&mut cx);\n\n let format = if format.is_empty() {\n\n None\n\n } else {\n\n Some(format)\n\n };\n\n let theme = cx.argument::<JsString>(3)?.value(&mut cx);\n\n let theme = if theme.is_empty() { None } else { Some(theme) };\n\n\n\n let result = RUNTIME.block_on(async {\n\n match DOCUMENTS.get(id).await {\n\n Ok(document) => document.lock().await.write_as(path, format, theme).await,\n\n Err(error) => Err(error),\n\n }\n\n });\n\n to_undefined_or_throw(cx, result)\n\n}\n\n\n", "file_path": "node/src/documents.rs", "rank": 58, "score": 294341.2733843739 }, { "content": "/// Install a plugin\n\npub fn install(mut cx: FunctionContext) -> JsResult<JsString> {\n\n let spec = &cx.argument::<JsString>(0)?.value(&mut cx);\n\n\n\n let config = &config::lock(&mut cx)?;\n\n let installs = &installations(&mut cx, 1, config)?;\n\n let aliases = &config.plugins.aliases;\n\n let plugins = &mut *lock(&mut cx)?;\n\n\n\n match RUNTIME.block_on(async { Plugin::install(spec, installs, aliases, plugins, None).await })\n\n {\n\n Ok(_) => to_json(cx, plugins.list_plugins(aliases)),\n\n Err(error) => cx.throw_error(error.to_string()),\n\n }\n\n}\n\n\n", "file_path": "node/src/plugins.rs", "rank": 59, "score": 294341.27338437387 }, { "content": "/// Unsubscribe from a topic\n\npub fn unsubscribe(mut cx: FunctionContext) -> JsResult<JsUndefined> {\n\n let topic = cx.argument::<JsString>(0)?.value(&mut cx);\n\n\n\n let mut subscriptions = obtain(&mut cx)?;\n\n subscriptions.retain(|subscription| subscription.topic != topic);\n\n\n\n Ok(cx.undefined())\n\n}\n\n\n", "file_path": "node/src/pubsub.rs", "rank": 60, "score": 294341.27338437387 }, { "content": "/// Refresh plugins\n\npub fn refresh(mut cx: FunctionContext) -> JsResult<JsString> {\n\n let arg = cx.argument::<JsArray>(0)?.to_vec(&mut cx)?;\n\n let list = arg\n\n .iter()\n\n .map(|item| {\n\n item.to_string(&mut cx)\n\n .expect(\"Unable to convert to string\")\n\n .value(&mut cx)\n\n })\n\n .collect();\n\n\n\n let config = &config::lock(&mut cx)?;\n\n let aliases = &config.plugins.aliases;\n\n let plugins = &mut *lock(&mut cx)?;\n\n\n\n match RUNTIME.block_on(async { Plugin::refresh_list(list, aliases, plugins).await }) {\n\n Ok(_) => to_json(cx, plugins.list_plugins(aliases)),\n\n Err(error) => cx.throw_error(error.to_string()),\n\n }\n\n}\n\n\n", "file_path": "node/src/plugins.rs", "rank": 61, "score": 294341.27338437387 }, { "content": "/// Write a project\n\npub fn write(mut cx: FunctionContext) -> JsResult<JsUndefined> {\n\n let path = &cx.argument::<JsString>(0)?.value(&mut cx);\n\n let updates = &cx.argument::<JsString>(1)?.value(&mut cx);\n\n let updates = from_json::<Project>(&mut cx, updates)?;\n\n\n\n let result = RUNTIME.block_on(async {\n\n match PROJECTS.get(&path).await {\n\n Ok(project) => project.lock().await.write(Some(updates)).await,\n\n Err(error) => Err(error),\n\n }\n\n });\n\n to_undefined_or_throw(cx, result)\n\n}\n\n\n", "file_path": "node/src/projects.rs", "rank": 62, "score": 294341.27338437387 }, { "content": "/// Validate a config\n\npub fn validate(mut cx: FunctionContext) -> JsResult<JsBoolean> {\n\n let json = cx.argument::<JsString>(0)?.value(&mut cx);\n\n\n\n let config = from_json::<Config>(&mut cx, &json)?;\n\n match config.validate() {\n\n Ok(_) => Ok(cx.boolean(true)),\n\n Err(error) => {\n\n cx.throw_error(serde_json::to_string(&error).expect(\"Unable to convert to JSON\"))\n\n }\n\n }\n\n}\n\n\n", "file_path": "node/src/config.rs", "rank": 63, "score": 294341.2733843739 }, { "content": "/// Close a project\n\npub fn close(mut cx: FunctionContext) -> JsResult<JsUndefined> {\n\n let path = &cx.argument::<JsString>(0)?.value(&mut cx);\n\n\n\n to_undefined_or_throw(cx, RUNTIME.block_on(async { PROJECTS.close(path).await }))\n\n}\n\n\n", "file_path": "node/src/projects.rs", "rank": 64, "score": 294341.27338437387 }, { "content": "/// Decode a Markdown document to a `Node`\n\n///\n\n/// Intended for decoding an entire document, this function extracts\n\n/// YAML front matter, parses the Markdown, and returns a `Node::Article` variant.\n\npub fn decode(md: &str) -> Result<Node> {\n\n let (end, node) = decode_frontmatter(md)?;\n\n\n\n let md = match end {\n\n Some(end) => &md[end..],\n\n None => md,\n\n };\n\n\n\n let mut node = match node {\n\n Some(node) => node,\n\n None => Node::Article(Article::default()),\n\n };\n\n\n\n let content = decode_fragment(md, None);\n\n if !content.is_empty() {\n\n let content = Some(content);\n\n match &mut node {\n\n Node::Article(article) => article.content = content,\n\n _ => bail!(\"Unsupported node type {:?}\", node),\n\n }\n\n }\n\n\n\n Ok(node)\n\n}\n\n\n", "file_path": "rust/src/methods/decode/md.rs", "rank": 65, "score": 293831.3810520394 }, { "content": "/// Decode a R Markdown document to a `Node`\n\npub fn decode(input: &str) -> Result<Node> {\n\n let mut node = md::decode(input)?;\n\n if let Node::Article(article) = &mut node {\n\n if let Some(content) = &mut article.content {\n\n transform_blocks(content)\n\n }\n\n }\n\n Ok(node)\n\n}\n\n\n", "file_path": "rust/src/methods/decode/rmd.rs", "rank": 66, "score": 293826.7973044651 }, { "content": "/// Decode a \"Reproducible PNG\" to a `Node`.\n\n///\n\n/// Extracts the JSON representation of the node from any iTXt chunk\n\n/// in the image that has the keyword `json`.\n\npub fn decode(input: &str) -> Result<Node> {\n\n // Decode the PNG bytes from the data URI or file\n\n let image_bytes = if let Some(data) = input.strip_prefix(\"data:image/png;base64,\") {\n\n base64::decode(data)?\n\n } else {\n\n let path = if let Some(path) = input.strip_prefix(\"file://\") {\n\n path\n\n } else {\n\n input\n\n };\n\n fs::read(path)?\n\n };\n\n\n\n // Decode the bytes and check if there is a matching iTXt chunk\n\n let decoder = png::Decoder::new(image_bytes.as_slice());\n\n let reader = decoder.read_info()?;\n\n let info = reader.info();\n\n let json = info\n\n .utf8_text\n\n .iter()\n", "file_path": "rust/src/methods/decode/rpng.rs", "rank": 67, "score": 293821.715724135 }, { "content": "/// Decode a JSON5 document to a `Node`\n\npub fn decode(json: &str) -> Result<Node> {\n\n coerce(json5::from_str(json)?, None)\n\n}\n", "file_path": "rust/src/methods/decode/json5.rs", "rank": 68, "score": 293821.2358270301 }, { "content": "/// Decode a JSON document to a `Node`\n\npub fn decode(json: &str) -> Result<Node> {\n\n coerce(serde_json::from_str(json)?, None)\n\n}\n", "file_path": "rust/src/methods/decode/json.rs", "rank": 69, "score": 293821.23582703003 }, { "content": "/// Decode a TOML document to a `Node`\n\npub fn decode(toml: &str) -> Result<Node> {\n\n coerce(toml::from_str(toml)?, None)\n\n}\n", "file_path": "rust/src/methods/decode/toml.rs", "rank": 70, "score": 293821.2358270301 }, { "content": "/// Decode a YAML document to a `Node`\n\npub fn decode(yaml: &str) -> Result<Node> {\n\n coerce(serde_yaml::from_str(yaml)?, None)\n\n}\n", "file_path": "rust/src/methods/decode/yaml.rs", "rank": 71, "score": 293821.23582703003 }, { "content": "/// Decode a Jupyter Notebook to a `Node`.\n\n///\n\n/// Aims to support the [Jupyter Notebook v4.5 schema](https://github.com/jupyter/nbformat/blob/master/nbformat/v4/nbformat.v4.5.schema.json)\n\n/// but should work for any v4 notebook.\n\n///\n\n/// Aims to be permissive by ignoring but warning about data that does not meet v4 schema\n\n/// (rather than erroring on it).\n\npub fn decode(ipynb: &str) -> Result<Node> {\n\n let notebook = serde_json::from_str::<serde_json::Value>(ipynb)?;\n\n\n\n if let Some(version) = notebook.get(\"nbformat\").and_then(|value| value.as_u64()) {\n\n if version != 4 {\n\n tracing::warn!(\n\n \"Jupyter Notebook has unsupported format version: {}\",\n\n version\n\n );\n\n }\n\n } else {\n\n tracing::warn!(\n\n \"Jupyter Notebook does not have a valid `nbformat` property; assuming version 4\"\n\n );\n\n }\n\n\n\n let metadata = notebook.get(\"metadata\");\n\n\n\n let mut article = if let Some(metadata) = metadata {\n\n match coerce(metadata.clone(), Some(\"Article\".to_string()))? {\n", "file_path": "rust/src/methods/decode/ipynb.rs", "rank": 72, "score": 293819.8948075559 }, { "content": "/// Set a property of the global config\n\npub fn set_property(mut cx: FunctionContext) -> JsResult<JsString> {\n\n let pointer = cx.argument::<JsString>(0)?.value(&mut cx);\n\n let value = cx.argument::<JsString>(1)?.value(&mut cx);\n\n\n\n let config = &mut *lock(&mut cx)?;\n\n if let Err(error) = config.set(&pointer, &value) {\n\n return cx.throw_error(error.to_string());\n\n }\n\n\n\n to_json(cx, config.clone())\n\n}\n\n\n", "file_path": "node/src/config.rs", "rank": 73, "score": 290225.95958713966 }, { "content": "/// Remove a source\n\npub fn remove_source(mut cx: FunctionContext) -> JsResult<JsString> {\n\n let path = &cx.argument::<JsString>(0)?.value(&mut cx);\n\n let name = &cx.argument::<JsString>(1)?.value(&mut cx);\n\n\n\n let result = RUNTIME.block_on(async {\n\n match PROJECTS.get(&path).await {\n\n Ok(project) => project.lock().await.remove_source(name).await,\n\n Err(error) => Err(error),\n\n }\n\n });\n\n to_json_or_throw(cx, result)\n\n}\n\n\n", "file_path": "node/src/projects.rs", "rank": 74, "score": 290225.9595871397 }, { "content": "/// Add a source\n\npub fn add_source(mut cx: FunctionContext) -> JsResult<JsString> {\n\n let path = &cx.argument::<JsString>(0)?.value(&mut cx);\n\n let source = &cx.argument::<JsString>(1)?.value(&mut cx);\n\n let destination = not_empty_or_none(&cx.argument::<JsString>(2)?.value(&mut cx));\n\n let name = not_empty_or_none(&cx.argument::<JsString>(3)?.value(&mut cx));\n\n\n\n let result = RUNTIME.block_on(async {\n\n match PROJECTS.get(&path).await {\n\n Ok(project) => {\n\n project\n\n .lock()\n\n .await\n\n .add_source(source, destination, name)\n\n .await\n\n }\n\n Err(error) => Err(error),\n\n }\n\n });\n\n to_json_or_throw(cx, result)\n\n}\n\n\n", "file_path": "node/src/projects.rs", "rank": 75, "score": 290225.9595871397 }, { "content": "/// Import a new or existing source\n\npub fn import_source(mut cx: FunctionContext) -> JsResult<JsString> {\n\n let path = &cx.argument::<JsString>(0)?.value(&mut cx);\n\n let name_or_identifier = &cx.argument::<JsString>(1)?.value(&mut cx);\n\n let destination = not_empty_or_none(&cx.argument::<JsString>(2)?.value(&mut cx));\n\n\n\n let result = RUNTIME.block_on(async {\n\n match PROJECTS.get(&path).await {\n\n Ok(project) => {\n\n project\n\n .lock()\n\n .await\n\n .import_source(name_or_identifier, destination)\n\n .await\n\n }\n\n Err(error) => Err(error),\n\n }\n\n });\n\n to_json_or_throw(cx, result)\n\n}\n\n\n", "file_path": "node/src/projects.rs", "rank": 76, "score": 290225.9595871397 }, { "content": "/// Reset a property of the global config\n\npub fn reset_property(mut cx: FunctionContext) -> JsResult<JsString> {\n\n let property = cx.argument::<JsString>(0)?.value(&mut cx);\n\n\n\n let config = &mut *lock(&mut cx)?;\n\n if let Err(error) = config.reset(&property) {\n\n return cx.throw_error(error.to_string());\n\n }\n\n\n\n to_json(cx, config.clone())\n\n}\n", "file_path": "node/src/config.rs", "rank": 77, "score": 290225.95958713966 }, { "content": "/// Convert JSON to a value\n\npub fn from_json<'a, Type>(cx: &mut FunctionContext, json: &'a str) -> Result<Type, Throw>\n\nwhere\n\n Type: Deserialize<'a>,\n\n{\n\n match serde_json::from_str::<Type>(json) {\n\n Ok(value) => Ok(value),\n\n Err(error) => cx.throw_error(error.to_string()),\n\n }\n\n}\n\n\n\n/// A global async runtime used to run any async functions\n\npub static RUNTIME: Lazy<Runtime> = Lazy::new(|| Runtime::new().expect(\"Unable to create runtime\"));\n", "file_path": "node/src/prelude.rs", "rank": 78, "score": 285369.02108436404 }, { "content": "/// Decode a Pandoc document to a `Node`\n\npub fn decode_pandoc(pandoc: pandoc::Pandoc) -> Result<Node> {\n\n let context = Context {};\n\n let mut article = translate_meta(pandoc.0, &context)?;\n\n\n\n let content = translate_blocks(&pandoc.1, &context);\n\n article.content = if content.is_empty() {\n\n None\n\n } else {\n\n Some(content)\n\n };\n\n\n\n Ok(Node::Article(article))\n\n}\n\n\n", "file_path": "rust/src/methods/decode/pandoc.rs", "rank": 79, "score": 279879.7120672338 }, { "content": "#[tracing::instrument]\n\npub fn serve_background(url: &str, key: Option<String>) -> Result<()> {\n\n // Spawn a thread, start a runtime in it, and serve using that runtime.\n\n // Any errors within the thread are logged because we can't return a\n\n // `Result` from the thread to the caller of this function.\n\n let url = url.to_string();\n\n std::thread::spawn(move || {\n\n let _span = tracing::trace_span!(\"serve_in_background\");\n\n\n\n let runtime = match tokio::runtime::Runtime::new() {\n\n Ok(runtime) => runtime,\n\n Err(error) => {\n\n tracing::error!(\"{}\", error.to_string());\n\n return;\n\n }\n\n };\n\n match runtime.block_on(async { serve(&url, key).await }) {\n\n Ok(_) => {}\n\n Err(error) => tracing::error!(\"{}\", error.to_string()),\n\n };\n\n });\n\n\n\n Ok(())\n\n}\n\n\n\n/// Static assets\n\n///\n\n/// During development, these are served from the `static` folder (which\n\n/// has a symlink to `web/dist/browser` (and maybe in the future other folders).\n\n/// At build time these are embedded in the binary. Use `include` and `exclude`\n\n/// glob patterns to only include the assets that are required.\n", "file_path": "rust/src/serve.rs", "rank": 80, "score": 277612.9035319566 }, { "content": "/// Decode a HTML fragment to a vector of `BlockContent`\n\n///\n\n/// Intended for decoding a fragment of HTML (e.g. some HTML in a\n\n/// Markdown document) and inserting it into a larger document.\n\n///\n\n/// If any block content is present in the fragment then that will be returned.\n\n/// Otherwise, if the fragment only consists of inline content a vector with\n\n/// a single paragraph containing that content will be returned.\n\npub fn decode_fragment(html: &str, decode_text_as_markdown: bool) -> Vec<BlockContent> {\n\n if html.is_empty() {\n\n return vec![];\n\n }\n\n\n\n let context = Context {\n\n decode_text_as_markdown,\n\n };\n\n let document = kuchiki::parse_html().one(html);\n\n\n\n let content = decode_blocks(&document, &context);\n\n if !content.is_empty() {\n\n return content;\n\n }\n\n\n\n let content = decode_inlines(&document, &context);\n\n if !content.is_empty() {\n\n return vec![BlockContent::Paragraph(Paragraph {\n\n content,\n\n ..Default::default()\n\n })];\n\n }\n\n\n\n vec![]\n\n}\n\n\n\n// Private implementation structs and functions...\n\n\n", "file_path": "rust/src/methods/decode/html.rs", "rank": 81, "score": 275041.42403057625 }, { "content": "fn author_person_to_html(person: &Person, orgs: Option<&Vec<&Organization>>) -> String {\n\n let name_string = if person.given_names.is_some() && person.family_names.is_some() {\n\n [\n\n person\n\n .given_names\n\n .as_ref()\n\n .map_or(\"\".to_string(), |vec| vec.join(\" \")),\n\n person\n\n .family_names\n\n .as_ref()\n\n .map_or(\"\".to_string(), |vec| vec.join(\" \")),\n\n ]\n\n .join(\" \")\n\n } else {\n\n person\n\n .name\n\n .as_ref()\n\n .map_or(\"\".to_string(), |name| *name.clone())\n\n };\n\n let name_string = match name_string.is_empty() {\n", "file_path": "rust/src/methods/encode/html/works.rs", "rank": 82, "score": 271081.5200882071 }, { "content": "/// Decode a Markdown fragment to a vector of `BlockContent`\n\n///\n\n/// Intended for decoding a fragment of Markdown (e.g. a Markdown cell in\n\n/// a Jupyter Notebook) and inserting it into a larger document.\n\n///\n\n/// Uses the `pulldown_cmark` and transforms its `Event`s into\n\n/// `Vec<BlockContent>`. Text is further parsed using `nom` based parsers\n\n/// to handle the elements that `pulldown_cmark` does not handle (e.g. math).\n\n///\n\n/// # Arguments\n\n///\n\n/// - `default_lang`: The default programming language to use on executable code\n\n/// nodes e.g. `CodeExpression` which do not explicitly se a language.\n\npub fn decode_fragment(md: &str, default_lang: Option<String>) -> Vec<BlockContent> {\n\n let mut inlines = Inlines {\n\n default_lang: default_lang.clone(),\n\n active: false,\n\n text: String::new(),\n\n nodes: Vec::new(),\n\n marks: Vec::new(),\n\n };\n\n\n\n let mut html = Html {\n\n html: String::new(),\n\n tags: Vec::new(),\n\n };\n\n\n\n let mut lists = Lists {\n\n items: Vec::new(),\n\n marks: Vec::new(),\n\n is_checked: None,\n\n };\n\n\n", "file_path": "rust/src/methods/decode/md.rs", "rank": 83, "score": 270813.03128122777 }, { "content": "/// Decode input to a type of `MediaObject` having the input as its `content_url`.\n\npub fn decode(input: &str, format: FormatType) -> Result<Node> {\n\n Ok(match format {\n\n FormatType::AudioObject => Node::AudioObject(AudioObject {\n\n content_url: input.to_string(),\n\n ..Default::default()\n\n }),\n\n FormatType::ImageObject => Node::ImageObject(ImageObject {\n\n content_url: input.to_string(),\n\n ..Default::default()\n\n }),\n\n FormatType::VideoObject => Node::VideoObject(VideoObject {\n\n content_url: input.to_string(),\n\n ..Default::default()\n\n }),\n\n _ => unreachable!(),\n\n })\n\n}\n", "file_path": "rust/src/methods/decode/media.rs", "rank": 84, "score": 270409.76283766044 }, { "content": "/// Decode input to a type of `SoftwareSourceCode` with `text`\n\n/// and `programming_language` properties.\n\npub fn decode(text: &str, programming_language: &str) -> Result<Node> {\n\n let programming_language = match programming_language.is_empty() {\n\n true => None,\n\n false => Some(Box::new(programming_language.to_string())),\n\n };\n\n Ok(Node::SoftwareSourceCode(SoftwareSourceCode {\n\n text: Some(Box::new(text.to_string())),\n\n programming_language,\n\n ..Default::default()\n\n }))\n\n}\n", "file_path": "rust/src/methods/decode/code.rs", "rank": 85, "score": 270404.4414719689 }, { "content": "/// Convert a value to JSON, throwing an error if that fails\n\npub fn to_json<Type>(mut cx: FunctionContext, value: Type) -> JsResult<JsString>\n\nwhere\n\n Type: Serialize,\n\n{\n\n match serde_json::to_string(&value) {\n\n Ok(json) => Ok(cx.string(json)),\n\n Err(error) => cx.throw_error(error.to_string()),\n\n }\n\n}\n\n\n", "file_path": "node/src/prelude.rs", "rank": 86, "score": 270020.0311456709 }, { "content": "/// Create an `InvalidSlotIndex` error\n\npub fn invalid_slot_index<Type: ?Sized>(index: usize) -> Error {\n\n Error::InvalidSlotIndex {\n\n index,\n\n type_name: type_name::<Type>().into(),\n\n }\n\n}\n\n\n", "file_path": "rust/src/errors.rs", "rank": 87, "score": 268534.02959248587 }, { "content": "/// Merge changes from two or more derived versions of a node into\n\n/// their common ancestor version.\n\n///\n\n/// This is equivalent to `git merge` except that there can be\n\n/// more than two derived versions and conflicts are always resolved.\n\n/// Conflicts are resolved by preferring the changes in 'later' derived\n\n/// version (i.e. those that are later in the `derived` list).\n\n///\n\n/// # Arguments\n\n///\n\n/// - `ancestor`: The ancestor node\n\n/// - `derived`: A list of derived nodes in ascending order of priority\n\n/// when resolving merge conflicts i.e. the last in the list\n\n/// will win over all other nodes that it conflicts with\n\npub fn merge<Type>(ancestor: &mut Type, derived: &[&Type]) -> Result<()>\n\nwhere\n\n Type: Patchable,\n\n{\n\n let patches: Vec<Patch> = derived.iter().map(|node| diff(ancestor, *node)).collect();\n\n\n\n // TODO transform operations (shift address based on other operations) and resolve conflicts\n\n tracing::warn!(\"Merging is work in progress\");\n\n\n\n for patch in patches {\n\n apply(ancestor, &patch)?;\n\n }\n\n Ok(())\n\n}\n\n\n", "file_path": "rust/src/patches/mod.rs", "rank": 88, "score": 268472.48516493436 }, { "content": "/// Apply a [`Patch`] to a clone of a node.\n\n///\n\n/// In contrast to `apply`, this does not alter the original node.\n\npub fn apply_new<Type>(node: &Type, patch: &Patch) -> Result<Type>\n\nwhere\n\n Type: Patchable + Clone,\n\n{\n\n let mut node = node.clone();\n\n node.apply_patch(patch)?;\n\n Ok(node)\n\n}\n\n\n", "file_path": "rust/src/patches/mod.rs", "rank": 89, "score": 264882.23292886774 }, { "content": "/// Throw an error as JSON\n\npub fn throw_error<T>(mut cx: FunctionContext, error: eyre::Report) -> JsResult<T>\n\nwhere\n\n T: Managed,\n\n{\n\n let message = error.to_string();\n\n let value = match error.downcast_ref::<Error>() {\n\n Some(error) => error_to_json(error),\n\n None => error_to_json(&Error::Unspecified { message }),\n\n };\n\n let json = serde_json::to_string_pretty(&value).expect(\"To always be able to stringify\");\n\n cx.throw_error(json)\n\n}\n\n\n", "file_path": "node/src/errors.rs", "rank": 91, "score": 262997.3112842078 }, { "content": "#[pyfunction]\n\nfn serve(py: Python, url: Option<String>, background: Option<bool>) -> PyResult<()> {\n\n let background = background.unwrap_or(false);\n\n // When creating threads that will aquire the GIL, or doing any blocking,\n\n // it is necessary to call `py.allow_threads`\n\n py.allow_threads(|| {\n\n match if background {\n\n stencila::serve::serve_background(url, None)\n\n } else {\n\n stencila::serve::serve_blocking(url, None)\n\n } {\n\n Ok(_) => Ok(()),\n\n Err(error) => Err(PyRuntimeError::new_err(error.to_string())),\n\n }\n\n })\n\n}\n\n\n\n/// Define the `stencila` Python module\n", "file_path": "python/src/lib.rs", "rank": 92, "score": 262067.8811757215 }, { "content": "// Test whether a string is an identifer for a particular family\n\npub fn matches(family: Family, id: &str) -> bool {\n\n let pattern = match family {\n\n Family::Project => \"[0-9a-z]{20}\",\n\n _ => \"[0-9a-zA-Z]{20}\",\n\n };\n\n let re = [&family.to_string(), SEPARATOR, pattern].concat();\n\n let re = Regex::new(&re).expect(\"Should be a valid regex\");\n\n re.is_match(id)\n\n}\n\n\n", "file_path": "rust/src/utils/uuids.rs", "rank": 95, "score": 259699.67378488678 }, { "content": "/// Encode a `Article`'s content as a vector of Jupyter cells\n\nfn encode_content(content: &Option<Vec<BlockContent>>) -> Vec<serde_json::Value> {\n\n let blocks = if let Some(blocks) = content {\n\n blocks\n\n } else {\n\n return Vec::new();\n\n };\n\n\n\n let mut cells = Vec::with_capacity(blocks.len());\n\n let mut content = Vec::new();\n\n for block in blocks {\n\n match block {\n\n BlockContent::CodeChunk(chunk) => {\n\n if !content.is_empty() {\n\n cells.push(encode_markdown(&content));\n\n content.clear()\n\n }\n\n cells.push(encode_chunk(chunk));\n\n }\n\n _ => content.push(block.clone()),\n\n }\n\n }\n\n if !content.is_empty() {\n\n cells.push(encode_markdown(&content))\n\n }\n\n\n\n cells\n\n}\n\n\n", "file_path": "rust/src/methods/encode/ipynb.rs", "rank": 96, "score": 258919.66860498703 }, { "content": "pub fn encode(key: String, expiry_seconds: Option<i64>) -> Result<String, JwtError> {\n\n let exp = chrono::Utc::now()\n\n .checked_add_signed(chrono::Duration::seconds(expiry_seconds.unwrap_or(60)))\n\n .expect(\"valid timestamp\")\n\n .timestamp();\n\n let claims = Claims { exp };\n\n match jsonwebtoken::encode(\n\n &jsonwebtoken::Header::new(jsonwebtoken::Algorithm::HS512),\n\n &claims,\n\n &jsonwebtoken::EncodingKey::from_secret(key.as_bytes()),\n\n ) {\n\n Ok(token) => Ok(token),\n\n Err(error) => Err(error.into()),\n\n }\n\n}\n\n\n", "file_path": "rust/src/jwt.rs", "rank": 97, "score": 257211.72550516488 }, { "content": "fn transform_blocks(blocks: &mut Vec<BlockContent>) {\n\n for block in blocks {\n\n match block {\n\n // Code blocks with curly braced language are transformed to code chunks\n\n BlockContent::CodeBlock(CodeBlock {\n\n programming_language,\n\n text,\n\n ..\n\n }) => {\n\n let lang = programming_language\n\n .clone()\n\n .map(|boxed| *boxed)\n\n .unwrap_or_else(|| \"\".to_string());\n\n if lang.starts_with('{') && lang.ends_with('}') {\n\n let lang = lang[1..(lang.len() - 1)].to_string();\n\n *block = BlockContent::CodeChunk(CodeChunk {\n\n programming_language: lang,\n\n text: text.to_string(),\n\n ..Default::default()\n\n })\n\n }\n\n }\n\n // Transform the inline content of other block types\n\n BlockContent::Paragraph(Paragraph { content, .. }) => transform_inlines(content),\n\n _ => (),\n\n }\n\n }\n\n}\n\n\n", "file_path": "rust/src/methods/decode/rmd.rs", "rank": 98, "score": 254416.99651174046 }, { "content": "fn transform_blocks(blocks: &mut Vec<BlockContent>) {\n\n for block in blocks {\n\n match block {\n\n // Code chunks are transformed to code blocks with curly braced language\n\n BlockContent::CodeChunk(CodeChunk {\n\n programming_language,\n\n text,\n\n ..\n\n }) => {\n\n *block = BlockContent::CodeBlock(CodeBlock {\n\n programming_language: Some(Box::new([\"{\", programming_language, \"}\"].concat())),\n\n text: text.to_string(),\n\n ..Default::default()\n\n })\n\n }\n\n // Transform the inline content of other block types\n\n BlockContent::Paragraph(Paragraph { content, .. }) => transform_inlines(content),\n\n _ => (),\n\n }\n\n }\n\n}\n\n\n", "file_path": "rust/src/methods/encode/rmd.rs", "rank": 99, "score": 254416.99651174046 } ]
Rust
db/src/models/group.rs
davedray/gatekeeper
0292c33941ec08da2f6e5514b70b9c80fd74ea47
use chrono::{DateTime, Utc}; use diesel::{AsChangeset, Insertable, Queryable}; use serde::{Deserialize, Serialize}; use uuid::Uuid; use crate::models::{Realm, Role, User}; use crate::schema::{groups, groups_roles, users_groups}; #[derive(Insertable, Identifiable, Queryable, Associations, Serialize, Deserialize, PartialEq, Debug, Clone)] #[belongs_to(Realm, foreign_key = "realm_id")] pub struct Group { pub id: Uuid, pub realm_id: Uuid, pub name: String, pub description: String, pub created_at: DateTime<Utc>, pub updated_at: DateTime<Utc>, } #[derive(Identifiable, Insertable, Queryable, Associations, Serialize, Deserialize, PartialEq, Debug, Clone)] #[belongs_to(Group, foreign_key = "group_id")] #[belongs_to(User, foreign_key = "user_id")] #[primary_key(user_id, group_id)] #[table_name="users_groups"] pub struct GroupUser { pub group_id: Uuid, pub user_id: Uuid, pub created_at: DateTime<Utc>, pub updated_at: DateTime<Utc>, } #[derive(Identifiable, Serialize, Deserialize, PartialEq, Debug, Clone)] #[primary_key(user_id, group_id)] #[table_name="users_groups"] pub struct DeleteGroupUser { pub group_id: Uuid, pub user_id: Uuid, } #[derive(Identifiable, Insertable, Queryable, Associations, Serialize, Deserialize, PartialEq, Debug, Clone)] #[belongs_to(Group, foreign_key = "group_id")] #[belongs_to(Role, foreign_key = "role_id")] #[primary_key(group_id, role_id)] #[table_name="groups_roles"] pub struct GroupRole { pub group_id: Uuid, pub role_id: Uuid, pub created_at: DateTime<Utc>, pub updated_at: DateTime<Utc>, } #[derive(Identifiable, Serialize, Deserialize, PartialEq, Debug, Clone)] #[primary_key(group_id, role_id)] #[table_name="groups_roles"] pub struct DeleteGroupRole { pub group_id: Uuid, pub role_id: Uuid, } impl GroupUser { pub fn from(a: domain::AddUserToGroup) -> Self { Self { user_id: a.user_id, group_id: a.group_id, created_at: Utc::now(), updated_at: Utc::now(), } } } impl From<domain::RemoveUserFromGroup> for DeleteGroupUser { fn from(a: domain::RemoveUserFromGroup) -> Self { Self { user_id: a.user_id, group_id: a.group_id, } } } impl GroupRole { pub fn from(a: domain::AddRoleToGroup) -> Self { Self { role_id: a.role_id, group_id: a.group_id, created_at: Utc::now(), updated_at: Utc::now(), } } } impl From<domain::RemoveRoleFromGroup> for DeleteGroupRole { fn from(a: domain::RemoveRoleFromGroup) -> Self { Self { role_id: a.role_id, group_id: a.group_id, } } } impl From<Group> for domain::Group { fn from(a: Group) -> Self { domain::Group::new( a.id, a.realm_id, a.name, a.description, a.created_at, a.updated_at, ) } } #[derive(AsChangeset)] #[table_name = "groups"] pub struct UpdateGroup { pub id: Uuid, pub name: Option<String>, pub description: Option<String>, pub updated_at: DateTime<Utc>, } impl Group { pub fn from(a: domain::AddRealmGroup) -> Self { Self { id: Uuid::new_v4(), realm_id: a.realm_id, name: a.name, description: a.description, created_at: Utc::now(), updated_at: Utc::now(), } } } impl UpdateGroup { pub fn from(a: domain::UpdateGroup) -> Self { Self { id: a.id, name: a.name, description: a.description, updated_at: Utc::now(), } } }
use chrono::{DateTime, Utc}; use diesel::{AsChangeset, Insertable, Queryable}; use serde::{Deserialize, Serialize}; use uuid::Uuid; use crate::models::{Realm, Role, User}; use crate::schema::{groups, groups_roles, users_groups}; #[derive(Insertable, Identifiable, Queryable, Associations, Serialize, Deserialize, PartialEq, Debug, Clone)] #[belongs_to(Realm, foreign_key = "realm_id")] pub struct Group { pub id: Uuid, pub realm_id: Uuid, pub name: String, pub description: String, pub created_at: DateTime<Utc>, pub updated_at: DateTime<Utc>, } #[derive(Identifiable, Insertable, Queryable, Associations, Serialize, Deserialize, PartialEq, Debug, Clone)] #[belongs_to(Group, foreign_key = "group_id")] #[belongs_to(User, foreign_key = "user_id")] #[primary_key(user_id, group_id)] #[table_name="users_groups"] pub struct GroupUser { pub group_id: Uuid, pub user_id: Uuid, pub created_at: DateTime<Utc>, pub updated_at: DateTime<Utc>, } #[derive(Identifiable, Serialize, Deserialize, PartialEq, Debug, Clone)] #[primary_key(user_id, group_id)] #[table_name="users_groups"] pub struct DeleteGroupUser { pub group_id: Uuid, pub user_id: Uuid, } #[derive(Identifiable, Insertable, Queryable, Associations, Serialize, Deserialize, PartialEq, Debug, Clone)] #[belongs_to(Group, foreign_key = "group_id")] #[belongs_to(Role, foreign_key = "role_id")] #[primary_key(group_id, role_id)] #[table_name="groups_roles"] pub struct GroupRole { pub group_id: Uuid, pub role_id: Uuid, pub created_at: DateTime<Utc>, pub updated_at: DateTime<Utc>, } #[derive(Identifiable, Serialize, Deserialize, PartialEq, Debug, Clone)] #[primary_key(group_id, role_id)] #[table_name="groups_roles"] pub struct DeleteGroupRole { pub group_id: Uuid, pub role_id: Uuid, } impl GroupUser { pub fn from(a: domain::AddUserToGroup) -> Self { Self { user_id: a.user_id, group_id: a.group_id, created_at: Utc::now(), updated_at: Utc::now(), } } } impl From<domain::RemoveUserFromGroup> for DeleteGroupUser { fn from(a: domain::RemoveUserFromGroup) -> Self { Self { user_id: a.user_id, group_id: a.group_id, } } } impl GroupRole { pub fn from(a: domain::AddRoleToGroup) -> Self { Self { role_id: a.role_id, group_id: a.group_id, created_at: Utc::now(), updated_at: Utc::now(), } } } impl From<domain::RemoveRoleFromGroup> for DeleteGroupRole {
} impl From<Group> for domain::Group { fn from(a: Group) -> Self { domain::Group::new( a.id, a.realm_id, a.name, a.description, a.created_at, a.updated_at, ) } } #[derive(AsChangeset)] #[table_name = "groups"] pub struct UpdateGroup { pub id: Uuid, pub name: Option<String>, pub description: Option<String>, pub updated_at: DateTime<Utc>, } impl Group { pub fn from(a: domain::AddRealmGroup) -> Self { Self { id: Uuid::new_v4(), realm_id: a.realm_id, name: a.name, description: a.description, created_at: Utc::now(), updated_at: Utc::now(), } } } impl UpdateGroup { pub fn from(a: domain::UpdateGroup) -> Self { Self { id: a.id, name: a.name, description: a.description, updated_at: Utc::now(), } } }
fn from(a: domain::RemoveRoleFromGroup) -> Self { Self { role_id: a.role_id, group_id: a.group_id, } }
function_block-full_function
[ { "content": "pub fn ids_by_group(repo: &Postgres, group: Uuid) -> Result<Vec<Uuid>, Error> {\n\n use crate::schema::groups_roles::dsl::*;\n\n groups_roles.filter(group_id.eq(group)).select(role_id).load(&repo.conn())\n\n}\n\n\n", "file_path": "db/src/queries/roles.rs", "rank": 0, "score": 291048.1289718679 }, { "content": "pub fn ids_by_role(repo: &Postgres, role: Uuid) -> Result<Vec<Uuid>, Error> {\n\n use crate::schema::groups_roles::dsl::*;\n\n groups_roles.filter(role_id.eq(role)).select(group_id).load(&repo.conn())\n\n}\n\n\n", "file_path": "db/src/queries/groups.rs", "rank": 1, "score": 291014.46540410834 }, { "content": "pub fn ids_by_group(repo: &Postgres, group: Uuid) -> Result<Vec<Uuid>, Error> {\n\n use crate::schema::users_groups::dsl::*;\n\n users_groups.filter(group_id.eq(group)).select(user_id).load(&repo.conn())\n\n}\n\n\n", "file_path": "db/src/queries/users.rs", "rank": 2, "score": 290719.67517218424 }, { "content": "pub fn ids_by_user(repo: &Postgres, user: Uuid) -> Result<Vec<Uuid>, Error> {\n\n use crate::schema::users_groups::dsl::*;\n\n users_groups.filter(user_id.eq(user)).select(group_id).load(&repo.conn())\n\n}\n\n\n", "file_path": "db/src/queries/groups.rs", "rank": 3, "score": 290596.5249219641 }, { "content": "pub fn ids_by_role(repo: &Postgres, role: Uuid) -> Result<Vec<Uuid>, Error> {\n\n use crate::schema::users_roles::dsl::*;\n\n users_roles.filter(role_id.eq(role)).select(user_id).load(&repo.conn())\n\n}\n\n\n", "file_path": "db/src/queries/users.rs", "rank": 4, "score": 290562.45213794865 }, { "content": "pub fn ids_by_user(repo: &Postgres, user: Uuid) -> Result<Vec<Uuid>, Error> {\n\n use crate::schema::users_roles::dsl::*;\n\n users_roles.filter(user_id.eq(user)).select(role_id).load(&repo.conn())\n\n}\n\n\n", "file_path": "db/src/queries/roles.rs", "rank": 5, "score": 290472.96545548807 }, { "content": "pub fn find_for_authentication(repo: &Postgres, realm_id: Uuid, username: String) -> Result<UserWithPassword, Error> {\n\n use crate::schema::users::dsl;\n\n dsl::users.filter(dsl::realm_id.eq(realm_id).and(dsl::username.eq(username))).first(&repo.conn())\n\n}\n\n\n", "file_path": "db/src/queries/users.rs", "rank": 6, "score": 274539.7442737488 }, { "content": "pub fn ids_by_group(repo: &Postgres, group: Uuid) -> Result<Vec<Uuid>, Error> {\n\n use crate::schema::groups_permissions::dsl::*;\n\n groups_permissions.filter(group_id.eq(group)).select(permission_id).load(&repo.conn())\n\n}", "file_path": "db/src/queries/permissions.rs", "rank": 7, "score": 256621.48886142956 }, { "content": "pub fn ids_by_role(repo: &Postgres, role: Uuid) -> Result<Vec<Uuid>, Error> {\n\n use crate::schema::roles_permissions::dsl::*;\n\n roles_permissions.filter(role_id.eq(role)).select(permission_id).load(&repo.conn())\n\n}\n\n\n", "file_path": "db/src/queries/permissions.rs", "rank": 8, "score": 256464.26582719389 }, { "content": "pub fn ids_by_user(repo: &Postgres, user: Uuid) -> Result<Vec<Uuid>, Error> {\n\n use crate::schema::users_permissions::dsl::*;\n\n users_permissions.filter(user_id.eq(user)).select(permission_id).load(&repo.conn())\n\n}\n\n\n", "file_path": "db/src/queries/permissions.rs", "rank": 9, "score": 256046.32534504967 }, { "content": "pub fn ids_by_permission(repo: &Postgres, permission: Uuid) -> Result<Vec<Uuid>, Error> {\n\n use crate::schema::groups_permissions::dsl::*;\n\n groups_permissions.filter(permission_id.eq(permission)).select(group_id).load(&repo.conn())\n\n}", "file_path": "db/src/queries/groups.rs", "rank": 10, "score": 233986.74963652735 }, { "content": "pub fn ids_by_permission(repo: &Postgres, permission: Uuid) -> Result<Vec<Uuid>, Error> {\n\n use crate::schema::roles_permissions::dsl::*;\n\n roles_permissions.filter(permission_id.eq(permission)).select(role_id).load(&repo.conn())\n\n}", "file_path": "db/src/queries/roles.rs", "rank": 11, "score": 233863.1901700513 }, { "content": "pub fn ids_by_permission(repo: &Postgres, permission: Uuid) -> Result<Vec<Uuid>, Error> {\n\n use crate::schema::users_permissions::dsl::*;\n\n users_permissions.filter(permission_id.eq(permission)).select(user_id).load(&repo.conn())\n\n}\n", "file_path": "db/src/queries/users.rs", "rank": 12, "score": 233534.7363703676 }, { "content": "pub fn find_one(repo: &Postgres, uuid: Uuid) -> Result<Group, Error> {\n\n use crate::schema::groups::dsl::*;\n\n groups.filter(id.eq(uuid)).first(&repo.conn())\n\n}\n\n\n", "file_path": "db/src/queries/groups.rs", "rank": 13, "score": 226469.23370697873 }, { "content": "pub fn find_one(repo: &Postgres, uuid: Uuid) -> Result<Role, Error> {\n\n use crate::schema::roles::dsl::*;\n\n roles.filter(id.eq(uuid)).first(&repo.conn())\n\n}\n\n\n", "file_path": "db/src/queries/roles.rs", "rank": 14, "score": 226310.4856119558 }, { "content": "pub fn find_group(repo: &Postgres, realm: Uuid, uuid: Uuid) -> Result<Group, Error> {\n\n use crate::schema::groups::dsl::*;\n\n groups.filter(id.eq(uuid).and(realm_id.eq(realm))).first(&repo.conn())\n\n}\n\n\n", "file_path": "db/src/queries/realms.rs", "rank": 15, "score": 225579.30004632677 }, { "content": "pub fn find_role(repo: &Postgres, realm: Uuid, uuid: Uuid) -> Result<Role, Error> {\n\n use crate::schema::roles::dsl::*;\n\n roles.filter(id.eq(uuid).and(realm_id.eq(realm))).first(&repo.conn())\n\n}\n\n\n", "file_path": "db/src/queries/realms.rs", "rank": 16, "score": 225423.57304979727 }, { "content": "pub fn find_one(repo: &Postgres, realm: Uuid, uuid: Uuid) -> Result<User, Error> {\n\n use crate::schema::users::dsl::*;\n\n users.filter(realm_id.eq(realm).and(id.eq(uuid))).select((id, realm_id, username, banned, suspended_until, created_at, updated_at)).first(&repo.conn())\n\n\n\n}\n\n\n", "file_path": "db/src/queries/users.rs", "rank": 17, "score": 225009.6094322597 }, { "content": "pub fn delete(repo: &Postgres, group: Uuid) -> Option<Error> {\n\n use crate::schema::groups::dsl::*;\n\n diesel::delete(groups.find(group))\n\n .execute(&repo.conn())\n\n .err()\n\n}\n\n\n", "file_path": "db/src/queries/groups.rs", "rank": 18, "score": 216696.01591904063 }, { "content": "pub fn delete(repo: &Postgres, role: Uuid) -> Option<Error> {\n\n use crate::schema::roles::dsl::*;\n\n diesel::delete(roles.find(role))\n\n .execute(&repo.conn())\n\n .err()\n\n}\n\n\n", "file_path": "db/src/queries/roles.rs", "rank": 19, "score": 216534.12718808366 }, { "content": "pub fn delete(repo: &Postgres, user: Uuid) -> Option<Error> {\n\n use crate::schema::users::dsl::*;\n\n diesel::delete(users.find(user))\n\n .execute(&repo.conn())\n\n .err()\n\n}\n\n\n", "file_path": "db/src/queries/users.rs", "rank": 20, "score": 216103.7840478511 }, { "content": "pub fn find(repo: &Postgres, realm: Uuid) -> Result<Vec<Group>, Error> {\n\n use crate::schema::groups::dsl::*;\n\n groups.filter(realm_id.eq(realm)).load(&repo.conn())\n\n}\n\n\n", "file_path": "db/src/queries/groups.rs", "rank": 21, "score": 204736.77640352468 }, { "content": "pub fn find(repo: &Postgres, realm: Uuid) -> Result<Vec<Role>, Error> {\n\n use crate::schema::roles::dsl::*;\n\n roles.filter(realm_id.eq(realm)).load(&repo.conn())\n\n}\n\n\n", "file_path": "db/src/queries/roles.rs", "rank": 22, "score": 204578.02830850176 }, { "content": "pub fn find(repo: &Postgres, realm: Uuid) -> Result<Vec<User>, Error> {\n\n use crate::schema::users::dsl::*;\n\n users.filter(realm_id.eq(realm)).select((id, realm_id, username, banned, suspended_until, created_at, updated_at)).load(&repo.conn())\n\n}\n\n\n", "file_path": "db/src/queries/users.rs", "rank": 23, "score": 204156.0338107113 }, { "content": "pub fn add_role(repo: &Postgres, role_group: domain::AddRoleToGroup) -> Result<GroupRole, Error> {\n\n use crate::schema::groups_roles;\n\n let r = GroupRole::from(role_group);\n\n diesel::insert_into(groups_roles::table).values(&r).get_result(&repo.conn())\n\n}\n\n\n", "file_path": "db/src/queries/groups.rs", "rank": 24, "score": 191993.82018612607 }, { "content": "pub fn add_user(repo: &Postgres, user_group: domain::AddUserToGroup) -> Result<GroupUser, Error> {\n\n use crate::schema::users_groups;\n\n let r = GroupUser::from(user_group);\n\n diesel::insert_into(users_groups::table).values(&r).get_result(&repo.conn())\n\n}\n\n\n", "file_path": "db/src/queries/groups.rs", "rank": 25, "score": 191520.49574624686 }, { "content": "pub fn remove_role(repo: &Postgres, role_group: domain::RemoveRoleFromGroup) -> Option<Error> {\n\n let r = DeleteGroupRole::from(role_group);\n\n diesel::delete(&r).execute(&repo.conn()).err()\n\n}\n\n\n", "file_path": "db/src/queries/groups.rs", "rank": 26, "score": 191511.8724568839 }, { "content": "pub fn add_user(repo: &Postgres, user_role: domain::AddUserToRole) -> Result<RoleUser, Error> {\n\n use crate::schema::users_roles;\n\n let r = RoleUser::from(user_role);\n\n diesel::insert_into(users_roles::table).values(&r).get_result(&repo.conn())\n\n}\n\n\n", "file_path": "db/src/queries/roles.rs", "rank": 27, "score": 191342.43808541942 }, { "content": "pub fn remove_user(repo: &Postgres, user_group: domain::RemoveUserFromGroup) -> Option<Error> {\n\n let r = DeleteGroupUser::from(user_group);\n\n diesel::delete(&r).execute(&repo.conn()).err()\n\n}\n\n\n", "file_path": "db/src/queries/groups.rs", "rank": 28, "score": 191058.57129271817 }, { "content": "pub fn remove_user(repo: &Postgres, user_role: domain::RemoveUserFromRole) -> Option<Error> {\n\n let r = DeleteRoleUser::from(user_role);\n\n diesel::delete(&r).execute(&repo.conn()).err()\n\n}\n\n\n", "file_path": "db/src/queries/roles.rs", "rank": 29, "score": 190888.04609236657 }, { "content": "fn secure_password(plaintext: String) -> (String, String) {\n\n const CREDENTIAL_LEN: usize = 128 / 8;\n\n let rng = rand::SystemRandom::new();\n\n let mut salt = [0u8; CREDENTIAL_LEN];\n\n rng.fill(&mut salt).expect(\"Could not generate salt\");\n\n let password_salt = BASE64.encode(&salt);\n\n let password_hash = BASE64\n\n .encode(digest(&SHA256, (plaintext + password_salt.as_str()).as_bytes()).as_ref());\n\n (password_salt, password_hash)\n\n}", "file_path": "db/src/models/user.rs", "rank": 30, "score": 181594.38324036245 }, { "content": "fn handle_unique_error(msg: String, name: String, error: DieselError) -> Error {\n\n match error {\n\n DieselError::DatabaseError(kind, info) => {\n\n if let DatabaseErrorKind::UniqueViolation = kind {\n\n return Error::DuplicateRealm(name);\n\n }\n\n Error::Database(info.message().to_string())\n\n }\n\n _ => Error::Database(msg),\n\n }\n\n}\n", "file_path": "db/src/repository.rs", "rank": 31, "score": 173096.52432594256 }, { "content": "pub fn add_group(repo: &Postgres, group_permission: domain::AddPermissionToGroup) -> Result<RolePermission, Error> {\n\n use crate::schema::groups_permissions;\n\n let r = GroupPermission::from(group_permission);\n\n diesel::insert_into(groups_permissions::table).values(&r).get_result(&repo.conn())\n\n}\n\n\n", "file_path": "db/src/queries/permissions.rs", "rank": 32, "score": 172088.7895170078 }, { "content": "pub fn find_permission(repo: &Postgres, realm: Uuid, uuid: Uuid) -> Result<Permission, Error> {\n\n use crate::schema::permissions::dsl::*;\n\n permissions.filter(id.eq(uuid).and(realm_id.eq(realm))).first(&repo.conn())\n\n}\n", "file_path": "db/src/queries/realms.rs", "rank": 33, "score": 169609.49105358805 }, { "content": "pub fn update(repo: &Postgres, group: domain::UpdateGroup) -> Result<Group, Error> {\n\n use crate::schema::groups::dsl::*;\n\n let r = UpdateGroup::from(group);\n\n diesel::update(groups.find(r.id))\n\n .set(&r)\n\n .get_result(&repo.conn())\n\n}\n\n\n", "file_path": "db/src/queries/groups.rs", "rank": 34, "score": 169087.1190985387 }, { "content": "pub fn update(repo: &Postgres, role: domain::UpdateRole) -> Result<Role, Error> {\n\n use crate::schema::roles::dsl::*;\n\n let r = UpdateRole::from(role);\n\n diesel::update(roles.find(r.id))\n\n .set(&r)\n\n .get_result(&repo.conn())\n\n}\n\n\n", "file_path": "db/src/queries/roles.rs", "rank": 35, "score": 168905.10077156546 }, { "content": "pub fn update(repo: &Postgres, user: domain::UpdateUser) -> Result<User, Error> {\n\n use crate::schema::users::dsl::*;\n\n let u = UpdateUser::from(user);\n\n diesel::update(users.find(u.id))\n\n .set(&u)\n\n .returning((id, realm_id, username, banned, suspended_until, created_at, updated_at))\n\n .get_result::<User>(&repo.conn())\n\n}\n\n\n", "file_path": "db/src/queries/users.rs", "rank": 36, "score": 168421.24783166952 }, { "content": "pub fn find_one(repo: &Postgres, uuid: Uuid) -> Result<Realm, Error> {\n\n use crate::schema::realms::dsl::*;\n\n realms.filter(id.eq(uuid)).first(&repo.conn())\n\n}\n\n\n", "file_path": "db/src/queries/realms.rs", "rank": 37, "score": 167951.848766855 }, { "content": "pub fn find_one(repo: &Postgres, uuid: Uuid) -> Result<Permission, Error> {\n\n use crate::schema::permissions::dsl::*;\n\n permissions.filter(id.eq(uuid)).first(&repo.conn())\n\n}\n\n\n", "file_path": "db/src/queries/permissions.rs", "rank": 38, "score": 167951.848766855 }, { "content": "pub fn create(repo: &Postgres, group: domain::AddRealmGroup) -> Result<Group, Error> {\n\n use crate::schema::groups;\n\n let r = Group::from(group);\n\n diesel::insert_into(groups::table)\n\n .values(&r)\n\n .get_result(&repo.conn())\n\n}\n\n\n", "file_path": "db/src/queries/groups.rs", "rank": 39, "score": 167750.91980118927 }, { "content": "pub fn create(repo: &Postgres, role: domain::AddRealmRole) -> Result<Role, Error> {\n\n use crate::schema::roles;\n\n let r = Role::from(role);\n\n diesel::insert_into(roles::table)\n\n .values(&r)\n\n .get_result(&repo.conn())\n\n}\n\n\n", "file_path": "db/src/queries/roles.rs", "rank": 40, "score": 167569.90806814705 }, { "content": "pub fn create(repo: &Postgres, user: domain::AddRealmUser) -> Result<User, Error> {\n\n use crate::schema::users;\n\n let u = NewUser::from(user);\n\n let result = diesel::insert_into(users::table)\n\n .values(&u)\n\n .execute(&repo.conn());\n\n match result {\n\n Ok(_) => Ok(u.into()),\n\n Err(error) => Err(error),\n\n }\n\n}\n\n\n", "file_path": "db/src/queries/users.rs", "rank": 41, "score": 167088.73092162263 }, { "content": "pub fn update_password(repo: &Postgres, user: domain::ChangeUserPassword) -> Result<User, Error> {\n\n use crate::schema::users::dsl::*;\n\n let u = UpdateUserPassword::from(user);\n\n diesel::update(users.find(u.id))\n\n .set(&u)\n\n .returning((id, realm_id, username, banned, suspended_until, created_at, updated_at))\n\n .get_result::<User>(&repo.conn())\n\n}\n\n\n", "file_path": "db/src/queries/users.rs", "rank": 42, "score": 165790.18806685568 }, { "content": "pub fn delete(repo: &Postgres, permission: Uuid) -> Option<Error> {\n\n use crate::schema::permissions::dsl::*;\n\n diesel::delete(permissions.find(permission))\n\n .execute(&repo.conn())\n\n .err()\n\n}\n\n\n", "file_path": "db/src/queries/permissions.rs", "rank": 43, "score": 156261.13016194664 }, { "content": "pub fn delete(repo: &Postgres, realm: Uuid) -> Option<Error> {\n\n use crate::schema::realms::dsl::*;\n\n diesel::delete(realms.find(realm))\n\n .execute(&repo.conn())\n\n .err()\n\n}\n\n\n", "file_path": "db/src/queries/realms.rs", "rank": 44, "score": 156261.13016194664 }, { "content": "pub fn find(repo: &Postgres, realm: Uuid) -> Result<Vec<Permission>, Error> {\n\n use crate::schema::permissions::dsl::*;\n\n permissions.filter(realm_id.eq(realm)).load(&repo.conn())\n\n}\n\n\n", "file_path": "db/src/queries/permissions.rs", "rank": 45, "score": 147125.39391373584 }, { "content": "pub fn remove_group(repo: &Postgres, group_permission: domain::RemovePermissionFromGroup) -> Option<Error> {\n\n let r = DeleteGroupPermission::from(group_permission);\n\n diesel::delete(&r).execute(&repo.conn()).err()\n\n}\n\n\n", "file_path": "db/src/queries/permissions.rs", "rank": 46, "score": 143999.44892758402 }, { "content": "pub fn remove_role(repo: &Postgres, role_permission: domain::RemovePermissionFromRole) -> Option<Error> {\n\n let r = DeleteRolePermission::from(role_permission);\n\n diesel::delete(&r).execute(&repo.conn()).err()\n\n}\n\n\n\n\n", "file_path": "db/src/queries/permissions.rs", "rank": 47, "score": 143828.92372723244 }, { "content": "pub fn remove_user(repo: &Postgres, user_permission: domain::RemovePermissionFromUser) -> Option<Error> {\n\n let r = DeleteUserPermission::from(user_permission);\n\n diesel::delete(&r).execute(&repo.conn()).err()\n\n}\n\n\n", "file_path": "db/src/queries/permissions.rs", "rank": 48, "score": 143375.6225630667 }, { "content": "pub fn add_role(repo: &Postgres, role_permission: domain::AddPermissionToRole) -> Result<RolePermission, Error> {\n\n use crate::schema::roles_permissions;\n\n let r = RolePermission::from(role_permission);\n\n diesel::insert_into(roles_permissions::table).values(&r).get_result(&repo.conn())\n\n}\n\n\n", "file_path": "db/src/queries/permissions.rs", "rank": 49, "score": 142204.6142819495 }, { "content": "pub fn add_user(repo: &Postgres, user_permission: domain::AddPermissionToUser) -> Result<UserPermission, Error> {\n\n use crate::schema::users_permissions;\n\n let r = UserPermission::from(user_permission);\n\n diesel::insert_into(users_permissions::table).values(&r).get_result(&repo.conn())\n\n}\n\n\n", "file_path": "db/src/queries/permissions.rs", "rank": 50, "score": 141731.28984207028 }, { "content": "-- Sets up a trigger for the given table to automatically set a column called\n", "file_path": "db/migrations/00000000000000_diesel_initial_setup/up.sql", "rank": 51, "score": 139864.04336505316 }, { "content": "pub fn routes(\n\n state: AppState,\n\n) -> impl Filter<Extract = impl warp::Reply, Error = std::convert::Infallible> + Clone {\n\n warp::path::end()\n\n .map(handlers::index::index)\n\n .or(warp::path!(\"api\" / \"realms\")\n\n .and(warp::get())\n\n .and(with_state(state.clone()))\n\n .and_then(handlers::realms::list::list))\n\n .or(warp::path!(\"api\" / \"realms\")\n\n .and(warp::post())\n\n .and(warp::body::json())\n\n .and(with_state(state.clone()))\n\n .and_then(handlers::realms::create::create))\n\n .or(warp::path!(\"api\" / \"realms\" / Uuid)\n\n .and(warp::put())\n\n .and(warp::body::json())\n\n .and(with_state(state.clone()))\n\n .and_then(handlers::realms::update::update))\n\n .or(warp::path!(\"api\" / \"realms\" / Uuid)\n", "file_path": "http/src/routes.rs", "rank": 52, "score": 136347.0265662848 }, { "content": "pub fn test() {\n\n println!(\"Hello, world!\");\n\n}\n", "file_path": "db/src/lib.rs", "rank": 53, "score": 136347.0265662848 }, { "content": "pub fn index() -> &'static str {\n\n \"Hello world!\"\n\n}\n", "file_path": "http/src/handlers/index.rs", "rank": 54, "score": 121102.67267699266 }, { "content": "pub fn find(repo: &Postgres) -> Result<Vec<Realm>, Error> {\n\n use crate::schema::realms::dsl::*;\n\n realms.load(&repo.conn())\n\n}\n\n\n", "file_path": "db/src/queries/realms.rs", "rank": 55, "score": 103781.67554168546 }, { "content": " createRoleGroupSuccess(state: RoleGroupsState, {payload}: PayloadAction<{role: string, group: string}>) {\n\n const {role, group} = payload;\n\n state.roleGroups[role] = state.roleGroups[role] || [];\n\n state.groupRoles[group] = state.groupRoles[group] || [];\n\n state.roleGroups[role].push(group);\n\n state.groupRoles[group].push(role);\n\n state.isCreatingGroup[role] = false;\n\n state.isCreatingRole[group] = false;\n\n state.error = null;\n", "file_path": "ui/src/app/roleGroups/roleGroupsSlice.ts", "rank": 56, "score": 100493.71119128891 }, { "content": " deleteRoleGroupSuccess(state: RoleGroupsState, {payload}: PayloadAction<{role: string, group: string}>) {\n\n const {role, group} = payload;\n\n state.roleGroups[role] = state.roleGroups[role].filter((r) => group !== r);\n\n state.groupRoles[group] = state.groupRoles[group].filter((r) => role !== r);\n\n state.error = null;\n\n state.isDeletingGroup[role] = false;\n\n state.isDeletingRole[group] = false;\n", "file_path": "ui/src/app/roleGroups/roleGroupsSlice.ts", "rank": 57, "score": 100493.71119128891 }, { "content": " getGroupRolesSuccess(state: RoleGroupsState, {payload}: PayloadAction<{group: string, roles: string[]}>) {\n\n payload.roles.forEach((role) => {\n\n state.roleGroups[role] = state.roleGroups[role] || [];\n\n if (!state.groupRoles[payload.group].includes(role)) {\n\n state.groupRoles[payload.group].push(role);\n\n }\n\n if (!state.roleGroups[role].includes(payload.group)) {\n\n state.roleGroups[role].push(payload.group);\n\n }\n\n });\n\n state.error = null;\n\n state.isLoadingRoles[payload.group] = false;\n\n state.hasGroupRoles[payload.group] = true;\n", "file_path": "ui/src/app/roleGroups/roleGroupsSlice.ts", "rank": 58, "score": 100493.71119128891 }, { "content": " getRoleGroupsSuccess(state: RoleGroupsState, {payload}: PayloadAction<{role: string, groups: string[]}>) {\n\n payload.groups.forEach((group) => {\n\n state.groupRoles[group] = state.groupRoles[group] || [];\n\n if (!state.roleGroups[payload.role].includes(group)) {\n\n state.roleGroups[payload.role].push(group);\n\n }\n\n if (!state.groupRoles[group].includes(payload.role)) {\n\n state.groupRoles[group].push(payload.role);\n\n }\n\n });\n\n state.error = null;\n\n state.isLoadingGroups[payload.role] = false;\n\n state.hasRoleGroups[payload.role] = true;\n", "file_path": "ui/src/app/roleGroups/roleGroupsSlice.ts", "rank": 59, "score": 100493.71119128891 }, { "content": " createUserGroupSuccess(state: UserGroupsState, {payload}: PayloadAction<{user: string, group: string}>) {\n\n const {user, group} = payload;\n\n state.userGroups[user] = state.userGroups[user] || [];\n\n state.groupUsers[group] = state.groupUsers[group] || [];\n\n state.userGroups[user].push(group);\n\n state.groupUsers[group].push(user);\n\n state.isCreatingGroup[user] = false;\n\n state.isCreatingUser[group] = false;\n\n state.error = null;\n", "file_path": "ui/src/app/groupUsers/groupUsersSlice.ts", "rank": 60, "score": 100015.18040567014 }, { "content": " deleteUserGroupSuccess(state: UserGroupsState, {payload}: PayloadAction<{user: string, group: string}>) {\n\n const {user, group} = payload;\n\n state.userGroups[user] = state.userGroups[user].filter((r) => group !== r);\n\n state.groupUsers[group] = state.groupUsers[group].filter((r) => user !== r);\n\n state.error = null;\n\n state.isDeletingGroup[user] = false;\n\n state.isDeletingUser[group] = false;\n", "file_path": "ui/src/app/groupUsers/groupUsersSlice.ts", "rank": 61, "score": 100015.18040567014 }, { "content": " getUserGroupsSuccess(state: UserGroupsState, {payload}: PayloadAction<{user: string, groups: string[]}>) {\n\n payload.groups.forEach((group) => {\n\n state.groupUsers[group] = state.groupUsers[group] || [];\n\n if (!state.userGroups[payload.user].includes(group)) {\n\n state.userGroups[payload.user].push(group);\n\n }\n\n if (!state.groupUsers[group].includes(payload.user)) {\n\n state.groupUsers[group].push(payload.user);\n\n }\n\n });\n\n state.error = null;\n\n state.isLoadingGroups[payload.user] = false;\n\n state.hasUserGroups[payload.user] = true;\n", "file_path": "ui/src/app/groupUsers/groupUsersSlice.ts", "rank": 62, "score": 100015.18040567014 }, { "content": " getGroupUsersSuccess(state: UserGroupsState, {payload}: PayloadAction<{group: string, users: string[]}>) {\n\n payload.users.forEach((user) => {\n\n state.userGroups[user] = state.userGroups[user] || [];\n\n if (!state.groupUsers[payload.group].includes(user)) {\n\n state.groupUsers[payload.group].push(user);\n\n }\n\n if (!state.userGroups[user].includes(payload.group)) {\n\n state.userGroups[user].push(payload.group);\n\n }\n\n });\n\n state.error = null;\n\n state.isLoadingUsers[payload.group] = false;\n\n state.hasGroupUsers[payload.group] = true;\n", "file_path": "ui/src/app/groupUsers/groupUsersSlice.ts", "rank": 63, "score": 100015.18040567014 }, { "content": " getRoleUsersSuccess(state: RoleUsersState, {payload}: PayloadAction<{role: string, users: string[]}>) {\n\n payload.users.forEach((user) => {\n\n state.userRoles[user] = state.userRoles[user] || [];\n\n if (!state.roleUsers[payload.role].includes(user)) {\n\n state.roleUsers[payload.role].push(user);\n\n }\n\n if (!state.userRoles[user].includes(payload.role)) {\n\n state.userRoles[user].push(payload.role);\n\n }\n\n });\n\n state.error = null;\n\n state.isLoadingUsers[payload.role] = false;\n\n state.hasRoleUsers[payload.role] = true;\n", "file_path": "ui/src/app/roleUsers/roleUsersSlice.ts", "rank": 64, "score": 99835.16419450018 }, { "content": " deleteRoleUserSuccess(state: RoleUsersState, {payload}: PayloadAction<{role: string, user: string}>) {\n\n const {role, user} = payload;\n\n state.roleUsers[role] = state.roleUsers[role].filter((r) => user !== r);\n\n state.userRoles[user] = state.userRoles[user].filter((r) => role !== r);\n\n state.error = null;\n\n state.isDeletingUser[role] = false;\n\n state.isDeletingRole[user] = false;\n", "file_path": "ui/src/app/roleUsers/roleUsersSlice.ts", "rank": 65, "score": 99835.16419450018 }, { "content": " getUserRolesSuccess(state: RoleUsersState, {payload}: PayloadAction<{user: string, roles: string[]}>) {\n\n payload.roles.forEach((role) => {\n\n state.roleUsers[role] = state.roleUsers[role] || [];\n\n if (!state.userRoles[payload.user].includes(role)) {\n\n state.userRoles[payload.user].push(role);\n\n }\n\n if (!state.roleUsers[role].includes(payload.user)) {\n\n state.roleUsers[role].push(payload.user);\n\n }\n\n });\n\n state.error = null;\n\n state.isLoadingRoles[payload.user] = false;\n\n state.hasUserRoles[payload.user] = true;\n", "file_path": "ui/src/app/roleUsers/roleUsersSlice.ts", "rank": 66, "score": 99835.16419450018 }, { "content": " createRoleUserSuccess(state: RoleUsersState, {payload}: PayloadAction<{role: string, user: string}>) {\n\n const {role, user} = payload;\n\n state.roleUsers[role] = state.roleUsers[role] || [];\n\n state.userRoles[user] = state.userRoles[user] || [];\n\n state.roleUsers[role].push(user);\n\n state.userRoles[user].push(role);\n\n state.isCreatingUser[role] = false;\n\n state.isCreatingRole[user] = false;\n\n state.error = null;\n", "file_path": "ui/src/app/roleUsers/roleUsersSlice.ts", "rank": 67, "score": 99835.16419450018 }, { "content": "const roleGroups = createSlice({\n\n initialState: roleGroupsInitialState,\n\n name: 'roleGroups',\n\n reducers: {\n\n getRoleGroupsStart: startLoadingGroups,\n\n getRoleGroupsFailure: loadingGroupsFailed,\n\n getRoleGroupsSuccess(state: RoleGroupsState, {payload}: PayloadAction<{role: string, groups: string[]}>) {\n\n payload.groups.forEach((group) => {\n\n state.groupRoles[group] = state.groupRoles[group] || [];\n\n if (!state.roleGroups[payload.role].includes(group)) {\n\n state.roleGroups[payload.role].push(group);\n\n }\n\n if (!state.groupRoles[group].includes(payload.role)) {\n\n state.groupRoles[group].push(payload.role);\n\n }\n\n });\n\n state.error = null;\n\n state.isLoadingGroups[payload.role] = false;\n\n state.hasRoleGroups[payload.role] = true;\n\n },\n\n deleteRoleGroupStart: startDeletingGroup,\n\n deleteRoleGroupFailure: deletingGroupFailed,\n\n deleteRoleGroupSuccess(state: RoleGroupsState, {payload}: PayloadAction<{role: string, group: string}>) {\n\n const {role, group} = payload;\n\n state.roleGroups[role] = state.roleGroups[role].filter((r) => group !== r);\n\n state.groupRoles[group] = state.groupRoles[group].filter((r) => role !== r);\n\n state.error = null;\n\n state.isDeletingGroup[role] = false;\n\n state.isDeletingRole[group] = false;\n\n },\n\n createRoleGroupStart: startCreatingGroup,\n\n createRoleGroupFailure: creatingGroupFailed,\n\n createRoleGroupSuccess(state: RoleGroupsState, {payload}: PayloadAction<{role: string, group: string}>) {\n\n const {role, group} = payload;\n\n state.roleGroups[role] = state.roleGroups[role] || [];\n\n state.groupRoles[group] = state.groupRoles[group] || [];\n\n state.roleGroups[role].push(group);\n\n state.groupRoles[group].push(role);\n\n state.isCreatingGroup[role] = false;\n\n state.isCreatingRole[group] = false;\n\n state.error = null;\n\n },\n\n getGroupRolesStart: startLoadingRoles,\n\n getGroupRolesFailure: loadingRolesFailed,\n\n getGroupRolesSuccess(state: RoleGroupsState, {payload}: PayloadAction<{group: string, roles: string[]}>) {\n\n payload.roles.forEach((role) => {\n\n state.roleGroups[role] = state.roleGroups[role] || [];\n\n if (!state.groupRoles[payload.group].includes(role)) {\n\n state.groupRoles[payload.group].push(role);\n\n }\n\n if (!state.roleGroups[role].includes(payload.group)) {\n\n state.roleGroups[role].push(payload.group);\n\n }\n\n });\n\n state.error = null;\n\n state.isLoadingRoles[payload.group] = false;\n\n state.hasGroupRoles[payload.group] = true;\n\n },\n\n }\n", "file_path": "ui/src/app/roleGroups/roleGroupsSlice.ts", "rank": 68, "score": 97916.02771349996 }, { "content": "const userGroups = createSlice({\n\n initialState: userGroupsInitialState,\n\n name: 'userGroups',\n\n reducers: {\n\n getUserGroupsStart: startLoadingGroups,\n\n getUserGroupsFailure: loadingGroupsFailed,\n\n getUserGroupsSuccess(state: UserGroupsState, {payload}: PayloadAction<{user: string, groups: string[]}>) {\n\n payload.groups.forEach((group) => {\n\n state.groupUsers[group] = state.groupUsers[group] || [];\n\n if (!state.userGroups[payload.user].includes(group)) {\n\n state.userGroups[payload.user].push(group);\n\n }\n\n if (!state.groupUsers[group].includes(payload.user)) {\n\n state.groupUsers[group].push(payload.user);\n\n }\n\n });\n\n state.error = null;\n\n state.isLoadingGroups[payload.user] = false;\n\n state.hasUserGroups[payload.user] = true;\n\n },\n\n deleteUserGroupStart: startDeletingGroup,\n\n deleteUserGroupFailure: deletingGroupFailed,\n\n deleteUserGroupSuccess(state: UserGroupsState, {payload}: PayloadAction<{user: string, group: string}>) {\n\n const {user, group} = payload;\n\n state.userGroups[user] = state.userGroups[user].filter((r) => group !== r);\n\n state.groupUsers[group] = state.groupUsers[group].filter((r) => user !== r);\n\n state.error = null;\n\n state.isDeletingGroup[user] = false;\n\n state.isDeletingUser[group] = false;\n\n },\n\n createUserGroupStart: startCreatingGroup,\n\n createUserGroupFailure: creatingGroupFailed,\n\n createUserGroupSuccess(state: UserGroupsState, {payload}: PayloadAction<{user: string, group: string}>) {\n\n const {user, group} = payload;\n\n state.userGroups[user] = state.userGroups[user] || [];\n\n state.groupUsers[group] = state.groupUsers[group] || [];\n\n state.userGroups[user].push(group);\n\n state.groupUsers[group].push(user);\n\n state.isCreatingGroup[user] = false;\n\n state.isCreatingUser[group] = false;\n\n state.error = null;\n\n },\n\n getGroupUsersStart: startLoadingUsers,\n\n getGroupUsersFailure: loadingUsersFailed,\n\n getGroupUsersSuccess(state: UserGroupsState, {payload}: PayloadAction<{group: string, users: string[]}>) {\n\n payload.users.forEach((user) => {\n\n state.userGroups[user] = state.userGroups[user] || [];\n\n if (!state.groupUsers[payload.group].includes(user)) {\n\n state.groupUsers[payload.group].push(user);\n\n }\n\n if (!state.userGroups[user].includes(payload.group)) {\n\n state.userGroups[user].push(payload.group);\n\n }\n\n });\n\n state.error = null;\n\n state.isLoadingUsers[payload.group] = false;\n\n state.hasGroupUsers[payload.group] = true;\n\n },\n\n }\n", "file_path": "ui/src/app/groupUsers/groupUsersSlice.ts", "rank": 69, "score": 97449.77133674799 }, { "content": "const roleUsers = createSlice({\n\n initialState: roleUsersInitialState,\n\n name: 'roleUsers',\n\n reducers: {\n\n getRoleUsersStart: startLoadingUsers,\n\n getRoleUsersFailure: loadingUsersFailed,\n\n getRoleUsersSuccess(state: RoleUsersState, {payload}: PayloadAction<{role: string, users: string[]}>) {\n\n payload.users.forEach((user) => {\n\n state.userRoles[user] = state.userRoles[user] || [];\n\n if (!state.roleUsers[payload.role].includes(user)) {\n\n state.roleUsers[payload.role].push(user);\n\n }\n\n if (!state.userRoles[user].includes(payload.role)) {\n\n state.userRoles[user].push(payload.role);\n\n }\n\n });\n\n state.error = null;\n\n state.isLoadingUsers[payload.role] = false;\n\n state.hasRoleUsers[payload.role] = true;\n\n },\n\n deleteRoleUserStart: startDeletingUser,\n\n deleteRoleUserFailure: deletingUserFailed,\n\n deleteRoleUserSuccess(state: RoleUsersState, {payload}: PayloadAction<{role: string, user: string}>) {\n\n const {role, user} = payload;\n\n state.roleUsers[role] = state.roleUsers[role].filter((r) => user !== r);\n\n state.userRoles[user] = state.userRoles[user].filter((r) => role !== r);\n\n state.error = null;\n\n state.isDeletingUser[role] = false;\n\n state.isDeletingRole[user] = false;\n\n },\n\n createRoleUserStart: startCreatingUser,\n\n createRoleUserFailure: creatingUserFailed,\n\n createRoleUserSuccess(state: RoleUsersState, {payload}: PayloadAction<{role: string, user: string}>) {\n\n const {role, user} = payload;\n\n state.roleUsers[role] = state.roleUsers[role] || [];\n\n state.userRoles[user] = state.userRoles[user] || [];\n\n state.roleUsers[role].push(user);\n\n state.userRoles[user].push(role);\n\n state.isCreatingUser[role] = false;\n\n state.isCreatingRole[user] = false;\n\n state.error = null;\n\n },\n\n getUserRolesStart: startLoadingRoles,\n\n getUserRolesFailure: loadingRolesFailed,\n\n getUserRolesSuccess(state: RoleUsersState, {payload}: PayloadAction<{user: string, roles: string[]}>) {\n\n payload.roles.forEach((role) => {\n\n state.roleUsers[role] = state.roleUsers[role] || [];\n\n if (!state.userRoles[payload.user].includes(role)) {\n\n state.userRoles[payload.user].push(role);\n\n }\n\n if (!state.roleUsers[role].includes(payload.user)) {\n\n state.roleUsers[role].push(payload.user);\n\n }\n\n });\n\n state.error = null;\n\n state.isLoadingRoles[payload.user] = false;\n\n state.hasUserRoles[payload.user] = true;\n\n },\n\n }\n", "file_path": "ui/src/app/roleUsers/roleUsersSlice.ts", "rank": 70, "score": 97274.37257683708 }, { "content": "export const deleteRoleGroup = (role: Role, group: Group): AppThunk => async dispatch => {\n\n try {\n\n dispatch(deleteRoleGroupStart({role: role.id, group: group.id}));\n\n await actions.deleteRoleGroup(role, group);\n\n dispatch(createSuccessToast({\n\n message: \"Group removed from role\"\n\n }));\n\n return dispatch(deleteRoleGroupSuccess({role: role.id, group: group.id}));\n\n } catch (err) {\n\n dispatch(createErrorToast({\n\n message: err.toString() || 'Could not remove group from role'\n\n }));\n\n return dispatch(deleteRoleGroupFailure({role: role.id, group: group.id, error: err.toString()}))\n\n }\n", "file_path": "ui/src/app/roleGroups/roleGroupsSlice.ts", "rank": 71, "score": 97221.38811705001 }, { "content": "export const fetchRoleGroups = (role: Role): AppThunk => async dispatch => {\n\n try {\n\n dispatch(getRoleGroupsStart(role.id));\n\n const groups = await actions.getRoleGroups(role);\n\n return dispatch(getRoleGroupsSuccess({role: role.id, groups}));\n\n } catch (err) {\n\n dispatch(createErrorToast({\n\n message: err.toString() || \"Could not fetch role's groups\"\n\n }));\n\n return dispatch(getRoleGroupsFailure({role: role.id, error: err.toString()}))\n\n }\n", "file_path": "ui/src/app/roleGroups/roleGroupsSlice.ts", "rank": 72, "score": 97221.38811705001 }, { "content": "interface RoleGroupsState {\n\n roleGroups: Record<string, string[]>;\n\n hasRoleGroups: Record<string, boolean>; // Lets you know if it has the *full* list of groups for this role\n\n groupRoles: Record<string, string[]>;\n\n hasGroupRoles: Record<string, boolean>; // Lets you know if it has the *full* list of roles for this group\n\n error: string|null;\n\n isLoadingGroups: Record<string, boolean>;\n\n isCreatingGroup: Record<string, boolean>;\n\n isDeletingGroup: Record<string, boolean>;\n\n isLoadingRoles: Record<string, boolean>;\n\n isCreatingRole: Record<string, boolean>;\n\n isDeletingRole: Record<string, boolean>;\n", "file_path": "ui/src/app/roleGroups/roleGroupsSlice.ts", "rank": 73, "score": 97221.38811705001 }, { "content": "export const fetchGroupRoles = (group: Group): AppThunk => async dispatch => {\n\n try {\n\n dispatch(getGroupRolesStart(group.id));\n\n const roles = await actions.getGroupRoles(group);\n\n return dispatch(getGroupRolesSuccess({group: group.id, roles}));\n\n } catch (err) {\n\n dispatch(createErrorToast({\n\n message: err.toString() || \"Could not fetch role's groups\"\n\n }));\n\n return dispatch(getGroupRolesFailure({group: group.id, error: err.toString()}))\n\n }\n", "file_path": "ui/src/app/roleGroups/roleGroupsSlice.ts", "rank": 74, "score": 97221.38811705001 }, { "content": "export const createRoleGroup = (role: Role, group: Group): AppThunk => async dispatch => {\n\n try {\n\n dispatch(createRoleGroupStart({role: role.id, group: group.id}));\n\n await actions.createRoleGroup(role, group);\n\n dispatch(createSuccessToast({\n\n message: \"Group added to role\"\n\n }));\n\n return dispatch(createRoleGroupSuccess({role: role.id, group: group.id}));\n\n } catch (err) {\n\n dispatch(createErrorToast({\n\n message: err.toString() || 'Could not add group to role'\n\n }));\n\n return dispatch(createRoleGroupFailure({role: role.id, group: group.id, error: err.toString()}));\n\n }\n", "file_path": "ui/src/app/roleGroups/roleGroupsSlice.ts", "rank": 75, "score": 97221.38811705001 }, { "content": "interface UserGroupsState {\n\n userGroups: Record<string, string[]>;\n\n hasUserGroups: Record<string, boolean>; // Lets you know if it has the *full* list of groups for this user\n\n groupUsers: Record<string, string[]>;\n\n hasGroupUsers: Record<string, boolean>; // Lets you know if it has the *full* list of users for this group\n\n error: string|null;\n\n isLoadingGroups: Record<string, boolean>;\n\n isCreatingGroup: Record<string, boolean>;\n\n isDeletingGroup: Record<string, boolean>;\n\n isLoadingUsers: Record<string, boolean>;\n\n isCreatingUser: Record<string, boolean>;\n\n isDeletingUser: Record<string, boolean>;\n", "file_path": "ui/src/app/groupUsers/groupUsersSlice.ts", "rank": 76, "score": 96758.43947396486 }, { "content": "export const fetchGroupUsers = (group: Group): AppThunk => async dispatch => {\n\n try {\n\n dispatch(getGroupUsersStart(group.id));\n\n const users = await actions.getGroupUsers(group);\n\n return dispatch(getGroupUsersSuccess({group: group.id, users}));\n\n } catch (err) {\n\n dispatch(createErrorToast({\n\n message: err.toString() || \"Could not fetch user's groups\"\n\n }));\n\n return dispatch(getGroupUsersFailure({group: group.id, error: err.toString()}))\n\n }\n", "file_path": "ui/src/app/groupUsers/groupUsersSlice.ts", "rank": 77, "score": 96758.43947396486 }, { "content": "export const fetchUserGroups = (user: User): AppThunk => async dispatch => {\n\n try {\n\n dispatch(getUserGroupsStart(user.id));\n\n const groups = await actions.getUserGroups(user);\n\n return dispatch(getUserGroupsSuccess({user: user.id, groups}));\n\n } catch (err) {\n\n dispatch(createErrorToast({\n\n message: err.toString() || \"Could not fetch user's groups\"\n\n }));\n\n return dispatch(getUserGroupsFailure({user: user.id, error: err.toString()}))\n\n }\n", "file_path": "ui/src/app/groupUsers/groupUsersSlice.ts", "rank": 78, "score": 96758.43947396486 }, { "content": "export const deleteUserGroup = (user: User, group: Group): AppThunk => async dispatch => {\n\n try {\n\n dispatch(deleteUserGroupStart({user: user.id, group: group.id}));\n\n await actions.deleteGroupUser(group, user);\n\n dispatch(createSuccessToast({\n\n message: \"Group removed from user\"\n\n }));\n\n return dispatch(deleteUserGroupSuccess({user: user.id, group: group.id}));\n\n } catch (err) {\n\n dispatch(createErrorToast({\n\n message: err.toString() || 'Could not remove group from user'\n\n }));\n\n return dispatch(deleteUserGroupFailure({user: user.id, group: group.id, error: err.toString()}))\n\n }\n", "file_path": "ui/src/app/groupUsers/groupUsersSlice.ts", "rank": 79, "score": 96758.43947396486 }, { "content": "export const createUserGroup = (user: User, group: Group): AppThunk => async dispatch => {\n\n try {\n\n dispatch(createUserGroupStart({user: user.id, group: group.id}));\n\n await actions.createGroupUser(group, user);\n\n dispatch(createSuccessToast({\n\n message: \"Group added to user\"\n\n }));\n\n return dispatch(createUserGroupSuccess({user: user.id, group: group.id}));\n\n } catch (err) {\n\n dispatch(createErrorToast({\n\n message: err.toString() || 'Could not add group to user'\n\n }));\n\n return dispatch(createUserGroupFailure({user: user.id, group: group.id, error: err.toString()}));\n\n }\n", "file_path": "ui/src/app/groupUsers/groupUsersSlice.ts", "rank": 80, "score": 96758.43947396486 }, { "content": "pub fn update(repo: &Postgres, permission: domain::UpdatePermission) -> Result<Permission, Error> {\n\n use crate::schema::permissions::dsl::*;\n\n let r = UpdatePermission::from(permission);\n\n diesel::update(permissions.find(r.id))\n\n .set(&r)\n\n .get_result(&repo.conn())\n\n}\n\n\n", "file_path": "db/src/queries/permissions.rs", "rank": 81, "score": 96632.16365955069 }, { "content": "pub fn update(repo: &Postgres, realm: domain::UpdateRealm) -> Result<Realm, Error> {\n\n use crate::schema::realms::dsl::*;\n\n let r = UpdateRealm::from(realm);\n\n diesel::update(realms.find(r.id))\n\n .set(&r)\n\n .get_result(&repo.conn())\n\n}\n\n\n", "file_path": "db/src/queries/realms.rs", "rank": 82, "score": 96632.16365955069 }, { "content": "pub fn create(repo: &Postgres, realm: domain::NewRealm) -> Result<Realm, Error> {\n\n use crate::schema::realms;\n\n let r = Realm::from_new(realm);\n\n diesel::insert_into(realms::table)\n\n .values(&r)\n\n .get_result(&repo.conn())\n\n}\n\n\n", "file_path": "db/src/queries/realms.rs", "rank": 83, "score": 96632.16365955069 }, { "content": "export const createRoleUser = (role: Role, user: User): AppThunk => async dispatch => {\n\n try {\n\n dispatch(createRoleUserStart({role: role.id, user: user.id}));\n\n await actions.createRoleUser(role, user);\n\n dispatch(createSuccessToast({\n\n message: \"User added to role\"\n\n }));\n\n return dispatch(createRoleUserSuccess({role: role.id, user: user.id}));\n\n } catch (err) {\n\n dispatch(createErrorToast({\n\n message: err.toString() || 'Could not add user to role'\n\n }));\n\n return dispatch(createRoleUserFailure({role: role.id, user: user.id, error: err.toString()}));\n\n }\n", "file_path": "ui/src/app/roleUsers/roleUsersSlice.ts", "rank": 84, "score": 96584.28503458704 }, { "content": "export const deleteRoleUser = (role: Role, user: User): AppThunk => async dispatch => {\n\n try {\n\n dispatch(deleteRoleUserStart({role: role.id, user: user.id}));\n\n await actions.deleteRoleUser(role, user);\n\n dispatch(createSuccessToast({\n\n message: \"User removed from role\"\n\n }));\n\n return dispatch(deleteRoleUserSuccess({role: role.id, user: user.id}));\n\n } catch (err) {\n\n dispatch(createErrorToast({\n\n message: err.toString() || 'Could not remove user from role'\n\n }));\n\n return dispatch(deleteRoleUserFailure({role: role.id, user: user.id, error: err.toString()}))\n\n }\n", "file_path": "ui/src/app/roleUsers/roleUsersSlice.ts", "rank": 85, "score": 96584.28503458704 }, { "content": "export const fetchRoleUsers = (role: Role): AppThunk => async dispatch => {\n\n try {\n\n dispatch(getRoleUsersStart(role.id));\n\n const users = await actions.getRoleUsers(role);\n\n return dispatch(getRoleUsersSuccess({role: role.id, users}));\n\n } catch (err) {\n\n dispatch(createErrorToast({\n\n message: err.toString() || \"Could not fetch role's users\"\n\n }));\n\n return dispatch(getRoleUsersFailure({role: role.id, error: err.toString()}))\n\n }\n", "file_path": "ui/src/app/roleUsers/roleUsersSlice.ts", "rank": 86, "score": 96584.28503458704 }, { "content": "interface RoleUsersState {\n\n roleUsers: Record<string, string[]>;\n\n hasRoleUsers: Record<string, boolean>; // Lets you know if it has the *full* list of users for this role\n\n userRoles: Record<string, string[]>;\n\n hasUserRoles: Record<string, boolean>; // Lets you know if it has the *full* list of roles for this user\n\n error: string|null;\n\n isLoadingUsers: Record<string, boolean>;\n\n isCreatingUser: Record<string, boolean>;\n\n isDeletingUser: Record<string, boolean>;\n\n isLoadingRoles: Record<string, boolean>;\n\n isCreatingRole: Record<string, boolean>;\n\n isDeletingRole: Record<string, boolean>;\n", "file_path": "ui/src/app/roleUsers/roleUsersSlice.ts", "rank": 87, "score": 96584.28503458704 }, { "content": "export const fetchUserRoles = (user: User): AppThunk => async dispatch => {\n\n try {\n\n dispatch(getUserRolesStart(user.id));\n\n const roles = await actions.getUserRoles(user);\n\n return dispatch(getUserRolesSuccess({user: user.id, roles}));\n\n } catch (err) {\n\n dispatch(createErrorToast({\n\n message: err.toString() || \"Could not fetch role's users\"\n\n }));\n\n return dispatch(getUserRolesFailure({user: user.id, error: err.toString()}))\n\n }\n", "file_path": "ui/src/app/roleUsers/roleUsersSlice.ts", "rank": 88, "score": 96584.28503458704 }, { "content": "const roleGroupsInitialState: RoleGroupsState = {\n\n roleGroups: {},\n\n hasRoleGroups: {},\n\n groupRoles: {},\n\n hasGroupRoles: {},\n\n error: null,\n\n isLoadingGroups: {},\n\n isLoadingRoles: {},\n\n isCreatingGroup: {},\n\n isCreatingRole: {},\n\n isDeletingGroup: {},\n\n isDeletingRole: {},\n", "file_path": "ui/src/app/roleGroups/roleGroupsSlice.ts", "rank": 89, "score": 96536.53497032441 }, { "content": "const userGroupsInitialState: UserGroupsState = {\n\n userGroups: {},\n\n hasUserGroups: {},\n\n groupUsers: {},\n\n hasGroupUsers: {},\n\n error: null,\n\n isLoadingGroups: {},\n\n isLoadingUsers: {},\n\n isCreatingGroup: {},\n\n isCreatingUser: {},\n\n isDeletingGroup: {},\n\n isDeletingUser: {},\n", "file_path": "ui/src/app/groupUsers/groupUsersSlice.ts", "rank": 90, "score": 96076.84745980616 }, { "content": "const roleUsersInitialState: RoleUsersState = {\n\n roleUsers: {},\n\n hasRoleUsers: {},\n\n userRoles: {},\n\n hasUserRoles: {},\n\n error: null,\n\n isLoadingUsers: {},\n\n isLoadingRoles: {},\n\n isCreatingUser: {},\n\n isCreatingRole: {},\n\n isDeletingUser: {},\n\n isDeletingRole: {},\n", "file_path": "ui/src/app/roleUsers/roleUsersSlice.ts", "rank": 91, "score": 95903.91981031619 }, { "content": "pub fn create(repo: &Postgres, permission: domain::AddRealmPermission) -> Result<Permission, Error> {\n\n use crate::schema::permissions;\n\n let r = Permission::from(permission);\n\n diesel::insert_into(permissions::table)\n\n .values(&r)\n\n .get_result(&repo.conn())\n\n}\n\n\n", "file_path": "db/src/queries/permissions.rs", "rank": 92, "score": 95577.43224323037 }, { "content": "DROP TABLE groups_roles;", "file_path": "db/migrations/2020-03-12-064349_create_groups_roles/down.sql", "rank": 93, "score": 94097.27741566223 }, { "content": "CREATE TABLE groups_roles (\n\n group_id UUID NOT NULL REFERENCES groups(id) ON DELETE CASCADE,\n\n role_id UUID NOT NULL REFERENCES roles(id) ON DELETE CASCADE,\n\n created_at TIMESTAMPTZ NOT NULL DEFAULT CURRENT_TIMESTAMP,\n\n updated_at TIMESTAMPTZ NOT NULL DEFAULT CURRENT_TIMESTAMP,\n\n PRIMARY KEY(group_id, role_id)\n\n);", "file_path": "db/migrations/2020-03-12-064349_create_groups_roles/up.sql", "rank": 94, "score": 94097.27741566223 }, { "content": "CREATE TABLE users_groups (\n\n user_id UUID NOT NULL REFERENCES users(id) ON DELETE CASCADE,\n\n group_id UUID NOT NULL REFERENCES groups(id) ON DELETE CASCADE,\n\n created_at TIMESTAMPTZ NOT NULL DEFAULT CURRENT_TIMESTAMP,\n\n updated_at TIMESTAMPTZ NOT NULL DEFAULT CURRENT_TIMESTAMP,\n\n PRIMARY KEY(user_id, group_id)\n\n);", "file_path": "db/migrations/2020-03-09-022530_create_users_groups/up.sql", "rank": 95, "score": 93649.20515768189 }, { "content": "DROP TABLE users_groups;", "file_path": "db/migrations/2020-03-09-022530_create_users_groups/down.sql", "rank": 96, "score": 93649.20515768189 }, { "content": "CREATE TABLE users_roles (\n\n user_id UUID NOT NULL REFERENCES users(id) ON DELETE CASCADE,\n\n role_id UUID NOT NULL REFERENCES roles(id) ON DELETE CASCADE,\n\n created_at TIMESTAMPTZ NOT NULL DEFAULT CURRENT_TIMESTAMP,\n\n updated_at TIMESTAMPTZ NOT NULL DEFAULT CURRENT_TIMESTAMP,\n\n PRIMARY KEY(user_id, role_id)\n\n);", "file_path": "db/migrations/2020-03-12-053126_create_users_roles/up.sql", "rank": 97, "score": 93480.6469945792 }, { "content": "DROP TABLE users_roles;", "file_path": "db/migrations/2020-03-12-053126_create_users_roles/down.sql", "rank": 98, "score": 93480.6469945792 }, { "content": "import { createSlice, PayloadAction } from '@reduxjs/toolkit';\n\nimport actions from \"../../http\";\n\nimport {AppThunk} from \"../store\";\n\nimport { createErrorToast, createSuccessToast } from '../toasts/toastsSlice';\n\nimport {Role, Group} from \"../../types\";\n\ninterface RoleGroupsState {\n\n roleGroups: Record<string, string[]>;\n\n hasRoleGroups: Record<string, boolean>; // Lets you know if it has the *full* list of groups for this role\n\n groupRoles: Record<string, string[]>;\n\n hasGroupRoles: Record<string, boolean>; // Lets you know if it has the *full* list of roles for this group\n\n error: string|null;\n\n isLoadingGroups: Record<string, boolean>;\n\n isCreatingGroup: Record<string, boolean>;\n\n isDeletingGroup: Record<string, boolean>;\n\n isLoadingRoles: Record<string, boolean>;\n\n isCreatingRole: Record<string, boolean>;\n\n isDeletingRole: Record<string, boolean>;\n\n}\n\n\n\nconst roleGroupsInitialState: RoleGroupsState = {\n\n roleGroups: {},\n\n hasRoleGroups: {},\n\n groupRoles: {},\n\n hasGroupRoles: {},\n\n error: null,\n\n isLoadingGroups: {},\n\n isLoadingRoles: {},\n\n isCreatingGroup: {},\n\n isCreatingRole: {},\n\n isDeletingGroup: {},\n\n isDeletingRole: {},\n\n};\n\n\n\nfunction startLoadingGroups(state: RoleGroupsState, action: PayloadAction<string>) {\n\n state.roleGroups[action.payload] = [];\n\n state.isLoadingGroups[action.payload] = true\n\n}\n\n\n\nfunction startLoadingRoles(state: RoleGroupsState, action: PayloadAction<string>) {\n\n state.groupRoles[action.payload] = [];\n\n state.isLoadingRoles[action.payload] = true\n\n}\n\n\n\nfunction startCreatingGroup(state: RoleGroupsState, action: PayloadAction<{role: string, group: string}>) {\n\n state.isCreatingGroup[action.payload.role] = true;\n\n state.isCreatingRole[action.payload.group] = true;\n\n}\n\n\n\nfunction startDeletingGroup(state: RoleGroupsState, action: PayloadAction<{role: string, group: string}>) {\n\n state.isDeletingGroup[action.payload.role] = true;\n\n state.isDeletingRole[action.payload.group] = true;\n\n}\n\n\n\nfunction loadingGroupsFailed(state: RoleGroupsState, action: PayloadAction<{role: string, error: string}>) {\n\n state.isLoadingGroups[action.payload.role] = false;\n\n state.error = action.payload.error\n\n}\n\n\n\nfunction loadingRolesFailed(state: RoleGroupsState, action: PayloadAction<{group: string, error: string}>) {\n\n state.isLoadingRoles[action.payload.group] = false;\n\n state.error = action.payload.error\n\n}\n\n\n\nfunction creatingGroupFailed(state: RoleGroupsState, action: PayloadAction<{role: string, group: string, error: string}>) {\n\n state.isCreatingGroup[action.payload.role] = false;\n\n state.isCreatingRole[action.payload.group] = false;\n\n state.error = action.payload.error;\n\n}\n\n\n\nfunction deletingGroupFailed(state: RoleGroupsState, action: PayloadAction<{role: string, group: string, error: string}>) {\n\n state.isCreatingGroup[action.payload.role] = false;\n\n state.isCreatingRole[action.payload.group] = false;\n\n state.error = action.payload.error;\n\n}\n\n\n\nconst roleGroups = createSlice({\n\n initialState: roleGroupsInitialState,\n\n name: 'roleGroups',\n\n reducers: {\n\n getRoleGroupsStart: startLoadingGroups,\n\n getRoleGroupsFailure: loadingGroupsFailed,\n\n getRoleGroupsSuccess(state: RoleGroupsState, {payload}: PayloadAction<{role: string, groups: string[]}>) {\n\n payload.groups.forEach((group) => {\n\n state.groupRoles[group] = state.groupRoles[group] || [];\n\n if (!state.roleGroups[payload.role].includes(group)) {\n\n state.roleGroups[payload.role].push(group);\n\n }\n\n if (!state.groupRoles[group].includes(payload.role)) {\n\n state.groupRoles[group].push(payload.role);\n\n }\n\n });\n\n state.error = null;\n\n state.isLoadingGroups[payload.role] = false;\n\n state.hasRoleGroups[payload.role] = true;\n\n },\n\n deleteRoleGroupStart: startDeletingGroup,\n\n deleteRoleGroupFailure: deletingGroupFailed,\n\n deleteRoleGroupSuccess(state: RoleGroupsState, {payload}: PayloadAction<{role: string, group: string}>) {\n\n const {role, group} = payload;\n\n state.roleGroups[role] = state.roleGroups[role].filter((r) => group !== r);\n\n state.groupRoles[group] = state.groupRoles[group].filter((r) => role !== r);\n\n state.error = null;\n\n state.isDeletingGroup[role] = false;\n\n state.isDeletingRole[group] = false;\n\n },\n\n createRoleGroupStart: startCreatingGroup,\n\n createRoleGroupFailure: creatingGroupFailed,\n\n createRoleGroupSuccess(state: RoleGroupsState, {payload}: PayloadAction<{role: string, group: string}>) {\n\n const {role, group} = payload;\n\n state.roleGroups[role] = state.roleGroups[role] || [];\n\n state.groupRoles[group] = state.groupRoles[group] || [];\n\n state.roleGroups[role].push(group);\n\n state.groupRoles[group].push(role);\n\n state.isCreatingGroup[role] = false;\n\n state.isCreatingRole[group] = false;\n\n state.error = null;\n\n },\n\n getGroupRolesStart: startLoadingRoles,\n\n getGroupRolesFailure: loadingRolesFailed,\n\n getGroupRolesSuccess(state: RoleGroupsState, {payload}: PayloadAction<{group: string, roles: string[]}>) {\n\n payload.roles.forEach((role) => {\n\n state.roleGroups[role] = state.roleGroups[role] || [];\n\n if (!state.groupRoles[payload.group].includes(role)) {\n\n state.groupRoles[payload.group].push(role);\n\n }\n\n if (!state.roleGroups[role].includes(payload.group)) {\n\n state.roleGroups[role].push(payload.group);\n\n }\n\n });\n\n state.error = null;\n\n state.isLoadingRoles[payload.group] = false;\n\n state.hasGroupRoles[payload.group] = true;\n\n },\n\n }\n\n});\n\n\n\nexport const {\n\n getRoleGroupsStart,\n\n getRoleGroupsFailure,\n\n getRoleGroupsSuccess,\n\n createRoleGroupStart,\n\n createRoleGroupFailure,\n\n createRoleGroupSuccess,\n\n deleteRoleGroupStart,\n\n deleteRoleGroupFailure,\n\n deleteRoleGroupSuccess,\n\n getGroupRolesStart,\n\n getGroupRolesFailure,\n\n getGroupRolesSuccess,\n\n} = roleGroups.actions;\n\n\n\nexport default roleGroups.reducer;\n\n\n\nexport const fetchRoleGroups = (role: Role): AppThunk => async dispatch => {\n\n try {\n\n dispatch(getRoleGroupsStart(role.id));\n\n const groups = await actions.getRoleGroups(role);\n\n return dispatch(getRoleGroupsSuccess({role: role.id, groups}));\n\n } catch (err) {\n\n dispatch(createErrorToast({\n\n message: err.toString() || \"Could not fetch role's groups\"\n\n }));\n\n return dispatch(getRoleGroupsFailure({role: role.id, error: err.toString()}))\n\n }\n\n};\n\n\n\nexport const fetchGroupRoles = (group: Group): AppThunk => async dispatch => {\n\n try {\n\n dispatch(getGroupRolesStart(group.id));\n\n const roles = await actions.getGroupRoles(group);\n\n return dispatch(getGroupRolesSuccess({group: group.id, roles}));\n\n } catch (err) {\n\n dispatch(createErrorToast({\n\n message: err.toString() || \"Could not fetch role's groups\"\n\n }));\n\n return dispatch(getGroupRolesFailure({group: group.id, error: err.toString()}))\n\n }\n\n};\n\n\n\nexport const createRoleGroup = (role: Role, group: Group): AppThunk => async dispatch => {\n\n try {\n\n dispatch(createRoleGroupStart({role: role.id, group: group.id}));\n\n await actions.createRoleGroup(role, group);\n\n dispatch(createSuccessToast({\n\n message: \"Group added to role\"\n\n }));\n\n return dispatch(createRoleGroupSuccess({role: role.id, group: group.id}));\n\n } catch (err) {\n\n dispatch(createErrorToast({\n\n message: err.toString() || 'Could not add group to role'\n\n }));\n\n return dispatch(createRoleGroupFailure({role: role.id, group: group.id, error: err.toString()}));\n\n }\n\n};\n\n\n\nexport const deleteRoleGroup = (role: Role, group: Group): AppThunk => async dispatch => {\n\n try {\n\n dispatch(deleteRoleGroupStart({role: role.id, group: group.id}));\n\n await actions.deleteRoleGroup(role, group);\n\n dispatch(createSuccessToast({\n\n message: \"Group removed from role\"\n\n }));\n\n return dispatch(deleteRoleGroupSuccess({role: role.id, group: group.id}));\n\n } catch (err) {\n\n dispatch(createErrorToast({\n\n message: err.toString() || 'Could not remove group from role'\n\n }));\n\n return dispatch(deleteRoleGroupFailure({role: role.id, group: group.id, error: err.toString()}))\n\n }\n", "file_path": "ui/src/app/roleGroups/roleGroupsSlice.ts", "rank": 99, "score": 84521.53788890368 } ]
Rust
src/parser/storage.rs
marirs/msg-parser-rs
cd508394d9a98d22e2b7c0d851bfe36ca6a0d464
use std::{ collections::HashMap, u32::MAX, }; use hex::decode; use crate::ole::{Entry, EntryType, Reader}; use super::{ constants::PropIdNameMap, decode::DataType, stream::Stream }; #[derive(Debug, Clone, PartialEq)] pub enum StorageType { Recipient(u32), Attachment(u32), RootEntry, } impl StorageType { fn convert_id_to_u32(id: &str) -> Option<u32> { if id.len() != 8 { return None; } let decoded = decode(id).ok()?; let mut base = 1u32; let mut sum = 0u32; for &num in decoded.iter().rev() { sum = sum + num as u32 * base; if base >= MAX / 256 { break; } base *= 256; } Some(sum) } pub fn create(name: &str) -> Option<Self> { if name.starts_with("__recip_version1.0_") { let id = name.split("#").collect::<Vec<&str>>()[1]; let id_as_num = StorageType::convert_id_to_u32(id)?; return Some(StorageType::Recipient(id_as_num)); } if name.starts_with("__attach_version1.0_") { let id = name.split("#").collect::<Vec<&str>>()[1]; let id_as_num = StorageType::convert_id_to_u32(id)?; return Some(StorageType::Attachment(id_as_num)); } None } } #[derive(Debug)] struct EntryStorageMap { map: HashMap<u32, StorageType>, } impl EntryStorageMap { pub fn new(parser: &Reader) -> Self { let mut storage_map: HashMap<u32, StorageType> = HashMap::new(); for entry in parser.iterate() { match entry._type() { EntryType::RootStorage => { storage_map.insert(entry.id(), StorageType::RootEntry); } EntryType::UserStorage => { StorageType::create(entry.name()) .and_then(|storage| storage_map.insert(entry.id(), storage)); } _ => { continue; } } } Self { map: storage_map } } pub fn get_storage_type(&self, parent_id: Option<u32>) -> Option<&StorageType> { self.map.get(&parent_id?) } } pub type Properties = HashMap<String, DataType>; pub type Recipients = Vec<Properties>; pub type Attachments = Vec<Properties>; #[derive(Debug)] pub struct Storages { storage_map: EntryStorageMap, prop_map: PropIdNameMap, pub attachments: Attachments, pub recipients: Recipients, pub root: Properties, } impl Storages { fn to_arr(map: HashMap<u32, Properties>) -> Vec<Properties> { let mut tuples: Vec<(u32, Properties)> = map .into_iter() .map(|(k, v)| (k, v)) .collect::<Vec<(u32, Properties)>>(); tuples.sort_by(|a, b| a.0.cmp(&b.0)); tuples.into_iter().map(|x| x.1).collect::<Vec<Properties>>() } fn create_stream(&self, parser: &Reader, entry: &Entry) -> Option<Stream> { let parent = self.storage_map.get_storage_type(entry.parent_node())?; let mut slice = parser.get_entry_slice(entry).ok()?; Stream::create(entry.name(), &mut slice, &self.prop_map, parent) } pub fn process_streams(&mut self, parser: &Reader) { let mut recipients_map: HashMap<u32, Properties> = HashMap::new(); let mut attachments_map: HashMap<u32, Properties> = HashMap::new(); for entry in parser.iterate() { if let EntryType::UserStream = entry._type() { let stream_res = self.create_stream(&parser, &entry); if stream_res.is_none() { continue; } let stream = stream_res.unwrap(); match stream.parent { StorageType::RootEntry => { self.root.insert(stream.key, stream.value); } StorageType::Recipient(id) => { let recipient_map = recipients_map.entry(id).or_insert(HashMap::new()); (*recipient_map).insert(stream.key, stream.value); } StorageType::Attachment(id) => { let attachment_map = attachments_map.entry(id).or_insert(HashMap::new()); (*attachment_map).insert(stream.key, stream.value); } } } } self.recipients = Self::to_arr(recipients_map); self.attachments = Self::to_arr(attachments_map); } pub fn new(parser: &Reader) -> Self { let root: Properties = HashMap::new(); let recipients: Recipients = vec![]; let attachments: Attachments = vec![]; let storage_map = EntryStorageMap::new(parser); let prop_map = PropIdNameMap::init(); Self { storage_map, prop_map, root, recipients, attachments, } } pub fn get_val_from_root_or_default(&self, key: &str) -> String { self.root.get(key).map_or(String::new(), |x| x.into()) } pub fn get_val_from_attachment_or_default(&self, idx: usize, key: &str) -> String { self.attachments .iter() .nth(idx) .map(|attach| attach.get(key).map_or(String::from(""), |x| x.into())) .unwrap_or(String::new()) } } #[cfg(test)] mod tests { use super::super::decode::DataType; use super::{EntryStorageMap, Properties, StorageType, Storages}; use crate::ole::Reader; use std::collections::HashMap; #[test] fn test_storage_type_convert() { use std::u32::MAX; let mut id = StorageType::convert_id_to_u32("00000001"); assert_eq!(id, Some(1u32)); id = StorageType::convert_id_to_u32("0000000A"); assert_eq!(id, Some(10u32)); id = StorageType::convert_id_to_u32("00000101"); assert_eq!(id, Some(257u32)); id = StorageType::convert_id_to_u32("FFFFFFFF"); assert_eq!(id, Some(MAX)); id = StorageType::convert_id_to_u32("HELLO"); assert_eq!(id, None); id = StorageType::convert_id_to_u32("00000000000000"); assert_eq!(id, None); } #[test] fn test_create_storage_type() { let recipient = StorageType::create("__recip_version1.0_#0000000A"); assert_eq!(recipient, Some(StorageType::Recipient(10))); let attachment = StorageType::create("__attach_version1.0_#0000000A"); assert_eq!(attachment, Some(StorageType::Attachment(10))); let unknown_storage = StorageType::create(""); assert_eq!(unknown_storage, None); } #[test] fn test_storage_map() { let parser = Reader::from_path("data/test_email.msg").unwrap(); let storage_map = EntryStorageMap::new(&parser); let mut expected_map = HashMap::new(); expected_map.insert(0, StorageType::RootEntry); expected_map.insert(73, StorageType::Recipient(0)); expected_map.insert(85, StorageType::Recipient(1)); expected_map.insert(97, StorageType::Recipient(2)); expected_map.insert(108, StorageType::Recipient(3)); expected_map.insert(120, StorageType::Recipient(4)); expected_map.insert(132, StorageType::Recipient(5)); expected_map.insert(143, StorageType::Attachment(0)); expected_map.insert(260, StorageType::Recipient(0)); expected_map.insert(310, StorageType::Attachment(1)); expected_map.insert(323, StorageType::Attachment(2)); assert_eq!(storage_map.map, expected_map); } #[test] fn test_storage_to_arr() { let mut map_apple: Properties = HashMap::new(); map_apple.insert("A".to_string(), DataType::PtypString("Apple".to_string())); let mut map_bagel: Properties = HashMap::new(); map_bagel.insert("B".to_string(), DataType::PtypString("Bagel".to_string())); let mut basket: HashMap<u32, Properties> = HashMap::new(); basket.insert(1, map_apple); basket.insert(0, map_bagel); let res = Storages::to_arr(basket); assert_eq!( res[0].get("B"), Some(&DataType::PtypString("Bagel".to_string())) ); assert_eq!( res[1].get("A"), Some(&DataType::PtypString("Apple".to_string())) ); } #[test] fn test_create_storage_test_email() { let parser = Reader::from_path("data/test_email.msg").unwrap(); let mut storages = Storages::new(&parser); storages.process_streams(&parser); let sender = storages.root.get("SenderEmailAddress"); assert!(sender.is_none()); assert_eq!(storages.attachments.len(), 3); assert_eq!(storages.recipients.len(), 6); let display_name = storages.recipients[0].get("DisplayName").unwrap(); assert_eq!( display_name, &DataType::PtypString("[email protected]".to_string()) ); } #[test] fn test_create_storage_outlook_attachments() { let parser = Reader::from_path("data/test_email.msg").unwrap(); let mut storages = Storages::new(&parser); storages.process_streams(&parser); assert_eq!(storages.attachments.len(), 3); let attachment_name = storages.attachments[0].get("DisplayName"); assert_eq!( attachment_name, Some(&DataType::PtypString("1 Days Left\u{14} 35% off cloud space, upgrade now!".to_string())) ); let attachment_name = storages.attachments[1].get("AttachFilename"); assert_eq!( attachment_name, Some(&DataType::PtypString("milky-~1.jpg".to_string())) ); let attachment_name = storages.attachments[2].get("AttachFilename"); assert_eq!( attachment_name, Some(&DataType::PtypString("TestEm~1.msg".to_string())) ); assert_eq!(storages.recipients.len(), 6); let display_name = storages.recipients[1].get("DisplayName").unwrap(); assert_eq!(display_name, &DataType::PtypString("Sriram Govindan".to_string())); } }
use std::{ collections::HashMap, u32::MAX, }; use hex::decode; use crate::ole::{Entry, EntryType, Reader}; use super::{ constants::PropIdNameMap, decode::DataType, stream::Stream }; #[derive(Debug, Clone, PartialEq)] pub enum StorageType { Recipient(u32), Attachment(u32), RootEntry, } impl StorageType { fn convert_id_to_u32(id: &str) -> Option<u32> { if id.len() != 8 { return None; } let decoded = decode(id).ok()?; let mut base = 1u32; let mut sum = 0u32; for &num in decoded.iter().rev() { sum = sum + num as u32 * base; if base >= MAX / 256 { break; } base *= 256; } Some(sum) } pub fn create(name: &str) -> Option<Self> { if name.starts_with("__recip_version1.0_") { let id = name.split("#").collect::<Vec<&str>>()[1]; let id_as_num = StorageType::convert_id_to_u32(id)?; return Some(StorageType::Recipient(id_as_num)); } if name.starts_with("__attach_version1.0_") { let id = name.split("#").collect::<Vec<&str>>()[1]; let id_as_num = StorageType::convert_id_to_u32(id)?; return Some(StorageType::Attachment(id_as_num)); } None } } #[derive(Debug)] struct EntryStorageMap { map: HashMap<u32, StorageType>, } impl EntryStorageMap { pub fn new(parser: &Reader) -> Self { let mut storage_map: HashMap<u32, StorageType> = HashMap::new(); for entry in parser.iterate() { match entry._type() { EntryType::RootStorage => { storage_map.insert(entry.id(), StorageType::RootEntry); } EntryType::UserStorage => { StorageType::create(entry.name()) .and_then(|storage| storage_map.insert(entry.id(), storage)); } _ => { continue; } } } Self { map: storage_map } } pub fn get_storage_type(&self, parent_id: Option<u32>) -> Option<&StorageType> { self.map.get(&parent_id?) } } pub type Properties = HashMap<String, DataType>; pub type Recipients = Vec<Properties>; pub type Attachments = Vec<Properties>; #[derive(Debug)] pub struct Storages { storage_map: EntryStorageMap, prop_map: PropIdNameMap, pub attachments: Attachments, pub recipients: Recipients, pub root: Properties, } impl Storages { fn to_arr(map: HashMap<u32, Properties>) -> Vec<Properties> { let mut tuples: Vec<(u32, Properties)> = map .into_iter() .map(|(k, v)| (k, v)) .collect::<Vec<(u32, Properties)>>(); tuples.sort_by(|a, b| a.0.cmp(&b.0)); tuples.into_iter().map(|x| x.1).collect::<Vec<Properties>>() } fn create_stream(&self, parser: &Reader, entry: &Entry) -> Option<Stream> { let parent = self.storage_map.get_storage_type(entry.parent_node())?; let mut slice = parser.get_entry_slice(entry).ok()?; Stream::create(entry.name(), &mut slice, &self.prop_map, parent) } pub fn process_streams(&mut self, parser: &Reader) { let mut recipients_map: HashMap<u32, Properties> = HashMap::new(); let mut attachments_map: HashMap<u32, Properties> = HashMap::new(); for entry in parser.iterate() { if let EntryType::UserStream = entry._type() { let stream_res = self.create_stream(&parser, &entry); if stream_res.is_none() { continue; } let stream = stream_res.unwrap(); match stream.parent { StorageType::RootEntry => { self.root.insert(stream.key, stream.value); } StorageType::Recipient(id) => { let recipient_map = recipients_map.entry(id).or_insert(HashMap::new()); (*recipient_map).insert(stream.key, stream.value); } StorageType::Attachment(id) => { let attachment_map = attachments_map.entry(id).or_insert(HashMap::new()); (*attachment_map).insert(stream.key, stream.value); } } } } self.recipients = Self::to_arr(recipients_map); self.attachments = Self::to_arr(attachments_map); } pub fn new(parser: &Reader) -> Self { let root: Properties = HashMap::new(); let recipients: Recipients = vec![]; let attachments: Attachments = vec![]; let storage_map = EntryStorageMap::new(parser); let prop_map = PropIdNameMap::init(); Self { storage_map, prop_map, root, recipients, attachments, } } pub fn get_val_from_root_or_default(&self, key: &str) -> String { self.root.get(key).map_or(String::new(), |x| x.into()) } pub fn get_val_from_attachment_or_default(&self, idx: usize, key: &str) -> String { self.attachments .iter() .nth(idx) .map(|attach| attach.get(key).map_or(String::from(""), |x| x.into())) .unwrap_or(String::new()) } } #[cfg(test)] mod tests { use super::super::decode::DataType; use super::{EntryStorageMap, Properties, StorageType, Storages}; use crate::ole::Reader; use std::collections::HashMap; #[test] fn test_storage_type_convert() { use std::u32::MAX; let mut id = StorageType::convert_id_to_u32("00000001"); assert_eq!(id, Some(1u32)); id = StorageType::convert_id_to_u32("0000000A"); assert_eq!(id, Some(10u32)); id = StorageType::convert_id_to_u32("00000101"); assert_eq!(id, Some(257u32)); id = StorageType::convert_id_to_u32("FFFFFFFF"); assert_eq!(id, Some(MAX)); id = StorageType::convert_id_to_u32("HELLO"); assert_eq!(id, None); id = StorageType::convert_id_to_u32("00000000000000"); assert_eq!(id, None); } #[test] fn test_create_storage_type() { let recipient = StorageType::create("__recip_version1.0_#0000000A"); assert_eq!(recipient, Some(StorageType::Recipient(10))); let attachment = StorageType::create("__attach_version1.0_#0000000A"); assert_eq!(attachment, Some(StorageType::Attachment(10))); let unknown_storage = StorageType::create(""); assert_eq!(unknown_storage, None); } #[test] fn test_storage_map() { let parser = Reader::from_path("data/test_email.msg").unwrap(); let storage_map = EntryStorageMap::new(&parser); let mut expected_map = HashMap::new(); expected_map.insert(0, StorageType::RootEntry); expected_map.insert(73, StorageType::Recipient(0)); expected_map.insert(85, StorageType::Recipient(1)); expected_map.insert(97, StorageType::Recipient(2)); expected_map.insert(108, StorageType::Recipient(3)); expected_map.insert(120, StorageType::Recipient(4)); expected_map.insert(132, StorageType::Recipient(5)); expected_map.insert(143, StorageType::Attachment(0)); expected_map.insert(260, StorageType::Recipient(0)); expected_map.insert(310, StorageType::Attachment(1)); expected_map.insert(323, StorageType::Attachment(2)); assert_eq!(storage_map.map, expected_map); } #[test] fn test_storage_to_arr() {
#[test] fn test_create_storage_test_email() { let parser = Reader::from_path("data/test_email.msg").unwrap(); let mut storages = Storages::new(&parser); storages.process_streams(&parser); let sender = storages.root.get("SenderEmailAddress"); assert!(sender.is_none()); assert_eq!(storages.attachments.len(), 3); assert_eq!(storages.recipients.len(), 6); let display_name = storages.recipients[0].get("DisplayName").unwrap(); assert_eq!( display_name, &DataType::PtypString("[email protected]".to_string()) ); } #[test] fn test_create_storage_outlook_attachments() { let parser = Reader::from_path("data/test_email.msg").unwrap(); let mut storages = Storages::new(&parser); storages.process_streams(&parser); assert_eq!(storages.attachments.len(), 3); let attachment_name = storages.attachments[0].get("DisplayName"); assert_eq!( attachment_name, Some(&DataType::PtypString("1 Days Left\u{14} 35% off cloud space, upgrade now!".to_string())) ); let attachment_name = storages.attachments[1].get("AttachFilename"); assert_eq!( attachment_name, Some(&DataType::PtypString("milky-~1.jpg".to_string())) ); let attachment_name = storages.attachments[2].get("AttachFilename"); assert_eq!( attachment_name, Some(&DataType::PtypString("TestEm~1.msg".to_string())) ); assert_eq!(storages.recipients.len(), 6); let display_name = storages.recipients[1].get("DisplayName").unwrap(); assert_eq!(display_name, &DataType::PtypString("Sriram Govindan".to_string())); } }
let mut map_apple: Properties = HashMap::new(); map_apple.insert("A".to_string(), DataType::PtypString("Apple".to_string())); let mut map_bagel: Properties = HashMap::new(); map_bagel.insert("B".to_string(), DataType::PtypString("Bagel".to_string())); let mut basket: HashMap<u32, Properties> = HashMap::new(); basket.insert(1, map_apple); basket.insert(0, map_bagel); let res = Storages::to_arr(basket); assert_eq!( res[0].get("B"), Some(&DataType::PtypString("Bagel".to_string())) ); assert_eq!( res[1].get("A"), Some(&DataType::PtypString("Apple".to_string())) ); }
function_block-function_prefix_line
[ { "content": "fn decode_ptypbinary(buff: &Vec<u8>) -> Result<DataType, Error> {\n\n Ok(DataType::PtypBinary(buff.to_vec()))\n\n}\n\n\n", "file_path": "src/parser/decode.rs", "rank": 1, "score": 97399.3281907708 }, { "content": "fn decode_ptypstring(buff: &Vec<u8>) -> Result<DataType, Error> {\n\n // PtypString\n\n // Byte sequence is in little-endian format\n\n // Use UTF-16 String decode\n\n let buffu16: Vec<u16> = if cfg!(target_endian = \"little\") {\n\n buff.iter().map(|&x| x as u16).collect()\n\n } else {\n\n buff.iter().map(|&x| x as u16).rev().collect()\n\n };\n\n match String::from_utf16(&buffu16) {\n\n // Remove all terminated null character\n\n Ok(decoded) => Ok(DataType::PtypString(decoded.replace(char::from(0), \"\"))),\n\n Err(err) => Err(DataTypeError::Utf16Err(err).into()),\n\n }\n\n}\n\n\n\n#[cfg(test)]\n\nmod tests {\n\n use super::{DataType, PtypDecoder};\n\n use crate::ole::Reader;\n", "file_path": "src/parser/decode.rs", "rank": 2, "score": 97399.32819077079 }, { "content": "type Name = String;\n", "file_path": "src/parser/outlook.rs", "rank": 3, "score": 82131.12790922725 }, { "content": "type Email = String;\n\n\n\n// TransportHeaders contains transport specific message\n\n// envelope information for the email.\n\n#[derive(Debug, PartialEq, Serialize, Deserialize)]\n\npub struct TransportHeaders {\n\n pub content_type: String,\n\n pub date: String,\n\n pub message_id: String,\n\n pub reply_to: String,\n\n}\n\n\n\nimpl TransportHeaders {\n\n fn extract_field(text: &str, re: Regex) -> String {\n\n if text.len() == 0 {\n\n return String::from(\"\");\n\n }\n\n let caps = re.captures(text);\n\n if caps.is_none() {\n\n return String::from(\"\");\n", "file_path": "src/parser/outlook.rs", "rank": 4, "score": 82131.12790922725 }, { "content": "mod constants;\n\nmod decode;\n\nmod storage;\n\nmod stream;\n\n\n\nmod error;\n\npub use error::{DataTypeError, Error};\n\n\n\nmod outlook;\n\npub use outlook::{Attachment, Outlook, Person, TransportHeaders};\n", "file_path": "src/parser/mod.rs", "rank": 5, "score": 48979.30868975953 }, { "content": "use std::io::Read;\n\n\n\nuse hex;\n\n\n\nuse crate::ole::EntrySlice;\n\n\n\nuse super::error::{DataTypeError, Error};\n\n\n\n// DataType corresponds to decoded property values\n\n// as specified in this document.\n\n// https://docs.microsoft.com/en-us/openspecs/exchange_server_protocols/ms-oxcdata/0c77892e-288e-435a-9c49-be1c20c7afdb\n\n#[derive(Clone, Debug, PartialEq)]\n\npub enum DataType {\n\n PtypString(String),\n\n PtypBinary(Vec<u8>),\n\n}\n\n\n\nimpl From<&DataType> for String {\n\n fn from(data: &DataType) -> Self {\n\n match *data {\n", "file_path": "src/parser/decode.rs", "rank": 6, "score": 48920.45365771897 }, { "content": " DataType::PtypBinary(ref bytes) => hex::encode(bytes),\n\n DataType::PtypString(ref string) => string.to_string(),\n\n }\n\n }\n\n}\n\n\n\n// PytpDecoder converts a byte sequence\n\n// into primitive type DataType.\n\npub struct PtypDecoder {}\n\n\n\nimpl PtypDecoder {\n\n pub fn decode(entry_slice: &mut EntrySlice, code: &str) -> Result<DataType, Error> {\n\n let mut buff = vec![0u8; entry_slice.len()];\n\n entry_slice.read(&mut buff)?;\n\n match code {\n\n \"0x001F\" => decode_ptypstring(&buff),\n\n \"0x0102\" => decode_ptypbinary(&buff),\n\n _ => Err(DataTypeError::UnknownCode(code.to_string()).into()),\n\n }\n\n }\n\n}\n\n\n", "file_path": "src/parser/decode.rs", "rank": 7, "score": 48917.22554772949 }, { "content": " let path = \"data/test_email.msg\";\n\n let parser = Reader::from_path(path).unwrap();\n\n\n\n let entry_of_a_ptypstring = parser.iterate().nth(125).unwrap();\n\n let mut ptypstring_slice = parser.get_entry_slice(entry_of_a_ptypstring).unwrap();\n\n let ptypstring_decoded = PtypDecoder::decode(&mut ptypstring_slice, \"0x001F\").unwrap();\n\n assert_eq!(\n\n ptypstring_decoded,\n\n DataType::PtypString(\"[email protected]\".to_string())\n\n );\n\n }\n\n}\n", "file_path": "src/parser/decode.rs", "rank": 8, "score": 48915.484560154495 }, { "content": "\n\n #[test]\n\n fn test_unknown_code() {\n\n // Test with dummy file.\n\n let path = \"data/test_email.msg\";\n\n let parser = Reader::from_path(path).unwrap();\n\n let entry = parser.iterate().next().unwrap();\n\n\n\n let mut slice = parser.get_entry_slice(entry).unwrap();\n\n let res = PtypDecoder::decode(&mut slice, \"1234\");\n\n assert_eq!(res.is_err(), true);\n\n let err = res.unwrap_err();\n\n assert_eq!(\n\n err.to_string(),\n\n \"DataTypeError: Unknown value encoding: 0x1234\"\n\n );\n\n }\n\n\n\n #[test]\n\n fn test_ptypstring() {\n", "file_path": "src/parser/decode.rs", "rank": 9, "score": 48914.31445087005 }, { "content": "use crate::ole::EntrySlice;\n\n\n\nuse super::{\n\n constants::PropIdNameMap,\n\n decode::{DataType, PtypDecoder},\n\n storage::StorageType,\n\n};\n\n\n\n// Stream refer to an element in Message object.\n\n#[derive(Debug, PartialEq)]\n\npub struct Stream {\n\n // Storage that a stream belongs to\n\n pub parent: StorageType,\n\n pub key: String,\n\n pub value: DataType,\n\n}\n\n\n\nimpl Stream {\n\n // __substg1.0__AAAABBBB where AAAA is property id and BBBB is property datatype\n\n fn extract_id_and_datatype(name: &str) -> (String, String) {\n", "file_path": "src/parser/stream.rs", "rank": 10, "score": 48866.9854831596 }, { "content": " &mut slice,\n\n &prop_map,\n\n &StorageType::Recipient(1),\n\n );\n\n assert_eq!(\n\n stream,\n\n Some(Stream {\n\n key: \"DisplayName\".to_string(),\n\n value: DataType::PtypString(\"Sriram Govindan\".to_string()),\n\n parent: StorageType::Recipient(1)\n\n })\n\n )\n\n }\n\n\n\n #[test]\n\n fn test_create_attachment() {\n\n let parser = Reader::from_path(\"data/attachment.msg\").unwrap();\n\n let prop_map = PropIdNameMap::init();\n\n\n\n // Attachment object.\n", "file_path": "src/parser/stream.rs", "rank": 11, "score": 48860.79242893049 }, { "content": " let mut attachment = parser\n\n .iterate()\n\n .find(|x| x.name() == \"__substg1.0_3703001F\" && x.parent_node() == Some(7u32))\n\n .and_then(|entry| parser.get_entry_slice(entry).ok())\n\n .unwrap();\n\n let stream = Stream::create(\n\n \"__substg1.0_3703001F\",\n\n &mut attachment,\n\n &prop_map,\n\n &StorageType::Attachment(0),\n\n );\n\n assert_eq!(\n\n stream,\n\n Some(Stream {\n\n key: \"AttachExtension\".to_string(),\n\n value: DataType::PtypString(\".doc\".to_string()),\n\n parent: StorageType::Attachment(0)\n\n })\n\n )\n\n }\n\n}\n", "file_path": "src/parser/stream.rs", "rank": 12, "score": 48859.55499188108 }, { "content": " let tag = name\n\n .split(\"_\")\n\n .filter(|&x| x.len() > 0)\n\n .collect::<Vec<&str>>()[1];\n\n let prop_id = String::from(\"0x\") + &tag[..4];\n\n let prop_datatype = String::from(\"0x\") + &tag[tag.len() - 4..];\n\n return (prop_id, prop_datatype);\n\n }\n\n\n\n fn is_stream(name: &str) -> bool {\n\n return name.starts_with(\"__substg1.0\");\n\n }\n\n\n\n pub fn create(\n\n name: &str,\n\n entry_slice: &mut EntrySlice,\n\n prop_map: &PropIdNameMap,\n\n parent: &StorageType,\n\n ) -> Option<Self> {\n\n if !Self::is_stream(name) {\n", "file_path": "src/parser/stream.rs", "rank": 13, "score": 48859.00954546485 }, { "content": " return None;\n\n }\n\n // Split name up into property id and datatype\n\n let (prop_id, prop_datatype) = Self::extract_id_and_datatype(name);\n\n let key = prop_map.get_canonical_name(&prop_id)?;\n\n let value_res = PtypDecoder::decode(entry_slice, &prop_datatype);\n\n if value_res.is_err() {\n\n return None;\n\n }\n\n let value = value_res.unwrap();\n\n Some(Self {\n\n parent: parent.clone(),\n\n key,\n\n value,\n\n })\n\n }\n\n}\n\n\n\n#[cfg(test)]\n\nmod tests {\n", "file_path": "src/parser/stream.rs", "rank": 14, "score": 48858.00658368878 }, { "content": " &StorageType::RootEntry,\n\n );\n\n assert_eq!(\n\n stream,\n\n Some(Stream {\n\n key: \"SenderEmailAddress\".to_string(),\n\n value: DataType::PtypString(\"[email protected]\".to_string()),\n\n parent: StorageType::RootEntry,\n\n })\n\n );\n\n\n\n // Recipient object check.\n\n let mut slice = parser\n\n .iterate()\n\n .filter(|x| x.name() == \"__substg1.0_3001001F\")\n\n .nth(0)\n\n .and_then(|entry| parser.get_entry_slice(entry).ok())\n\n .unwrap();\n\n let stream = Stream::create(\n\n \"__substg1.0_3001001F\",\n", "file_path": "src/parser/stream.rs", "rank": 15, "score": 48855.75594321439 }, { "content": " use super::{\n\n super::constants::PropIdNameMap, super::decode::DataType, super::storage::StorageType,\n\n Stream,\n\n };\n\n use crate::ole::Reader;\n\n\n\n #[test]\n\n fn test_extract_id_and_datatype() {\n\n let (prop_id, prop_datatype) = Stream::extract_id_and_datatype(\"__substg1.0_3701000D\");\n\n assert_eq!(prop_id, \"0x3701\");\n\n assert_eq!(prop_datatype, \"0x000D\");\n\n\n\n let (prop_id, prop_datatype) = Stream::extract_id_and_datatype(\"__substg1.0_1016102F\");\n\n assert_eq!(prop_id, \"0x1016\");\n\n assert_eq!(prop_datatype, \"0x102F\");\n\n }\n\n\n\n #[test]\n\n fn test_is_stream() {\n\n assert_eq!(Stream::is_stream(\"__recip_version1.0_#00000000\"), false);\n", "file_path": "src/parser/stream.rs", "rank": 16, "score": 48850.274407550554 }, { "content": " assert_eq!(Stream::is_stream(\"__substg1.0_3701000D\"), true);\n\n }\n\n\n\n #[test]\n\n fn test_create_stream() {\n\n let parser = Reader::from_path(\"data/test_email.msg\").unwrap();\n\n let prop_map = PropIdNameMap::init();\n\n\n\n // Root entry is ok.\n\n let mut slice = parser\n\n .iterate()\n\n .filter(|x| x.name() == \"__substg1.0_0C1F001F\")\n\n .nth(0)\n\n .and_then(|entry| parser.get_entry_slice(entry).ok())\n\n .unwrap();\n\n\n\n let stream = Stream::create(\n\n \"__substg1.0_0C1F001F\",\n\n &mut slice,\n\n &prop_map,\n", "file_path": "src/parser/stream.rs", "rank": 17, "score": 48850.12640972157 }, { "content": "fn main() {\n\n // Create Outlook object\n\n let outlook = Outlook::from_path(\"data/test_email_4.msg\").unwrap();\n\n\n\n // Flush as json string\n\n let _json_string = outlook.to_json();\n\n\n\n println!(\"{:#?}\", outlook);\n\n}\n", "file_path": "examples/parse-email.rs", "rank": 34, "score": 34889.994704265555 }, { "content": "/// Iterator for entries inside an OLE file.\n\npub struct OLEIterator<'a> {\n\n ole: &'a super::ole::Reader<'a>,\n\n curr: usize\n\n}\n\n\n\nimpl<'a> OLEIterator<'a> {\n\n\n\n pub(crate) fn new(ole: &'a super::ole::Reader) -> OLEIterator<'a> {\n\n OLEIterator {\n\n ole: ole,\n\n curr: 0\n\n }\n\n }\n\n}\n\n\n\nimpl<'a> Iterator for OLEIterator<'a> {\n\n type Item = &'a super::entry::Entry;\n\n\n\n fn next(&mut self) -> Option<&'a super::entry::Entry> {\n", "file_path": "src/ole/iterator.rs", "rank": 35, "score": 26769.169774934846 }, { "content": " let entries = self.ole.entries.as_ref().unwrap();\n\n if self.curr < entries.len() {\n\n self.curr += 1;\n\n Some(&entries[self.curr - 1])\n\n } else {\n\n None\n\n }\n\n }\n\n}\n", "file_path": "src/ole/iterator.rs", "rank": 36, "score": 26751.05999877885 }, { "content": "//! }\n\n//!\n\n//! // We're going to extract a file from the OLE storage\n\n//! let entry = parser.iterate().next().unwrap();\n\n//! let mut slice = parser.get_entry_slice(entry).unwrap();\n\n//! let mut buffer = std::vec::Vec::<u8>::with_capacity(slice.len());\n\n//! slice.read_to_end(&mut buffer);\n\n//!\n\n//! // Saves the extracted file\n\n//! let mut extracted_file = std::fs::File::create(\"./file.bin\").unwrap();\n\n//! extracted_file.write_all(&buffer[..]);\n\n//! ```\n\n\n\nmod ole;\n\npub use ole::Reader;\n\n\n\npub(crate) mod iterator;\n\npub(crate) use iterator::OLEIterator;\n\n\n\nmod error;\n", "file_path": "src/ole/mod.rs", "rank": 37, "score": 26709.600150174796 }, { "content": "#![allow(unused_imports, dead_code)]\n\n//! A simple parser and reader for Microsoft Compound Document File.\n\n//!\n\n//! This includes a basic parser, which validates the format of a given file\n\n//! or a given stream.\n\n//! It includes a reader too, for iterating over entries and for extracting\n\n//! files inside the OLE storage.\n\n//!\n\n//! ## Example\n\n//!\n\n//! ```ignore\n\n//! use crate::ole::Reader;\n\n//! use std::io::{Read, Write};\n\n//!\n\n//! let mut file = std::fs::File::open(\"data/Thumbs.db\").unwrap();\n\n//! let mut parser = Reader::new(file).unwrap();\n\n//!\n\n//! // Iterate through the entries\n\n//! for entry in parser.iterate() {\n\n//! println!(\"{}\", entry);\n", "file_path": "src/ole/mod.rs", "rank": 38, "score": 26701.040007617397 }, { "content": "pub use error::Error;\n\n\n\npub(crate) mod header;\n\npub(crate) mod util;\n\npub(crate) mod sat;\n\npub(crate) mod constants;\n\n\n\npub mod entry;\n\npub use entry::Entry;\n\npub use entry::EntrySlice;\n\npub use entry::EntryType;\n\n\n\npub(crate) mod sector;\n", "file_path": "src/ole/mod.rs", "rank": 39, "score": 26696.0315499833 }, { "content": " self.right_child_node\n\n }\n\n\n\n /// Returns the DirID of the parent, if exists\n\n pub fn parent_node(&self) -> Option<u32> {\n\n self.parent_node\n\n }\n\n\n\n /// Returns the DirIDs of the children, if exists\n\n pub fn children_nodes(&self) -> &std::vec::Vec<u32> {\n\n &self.children_nodes\n\n }\n\n}\n\n\n\nimpl std::fmt::Display for Entry {\n\n fn fmt(&self, f: &mut std::fmt::Formatter) -> std::fmt::Result {\n\n write!(f, \"Entry #{}. Type: {}, Color: {}, Name: {},\n\n Size: {}. SecID chain: {:?}\",\n\n self.id, self.entry_type, self.color, &self.name,\n\n self.size, self.sec_id_chain)\n", "file_path": "src/ole/entry.rs", "rank": 40, "score": 25958.363804989818 }, { "content": " self.root_entry = Some(i as u32);\n\n let start_index = entry.sec_id_chain.pop().unwrap();\n\n entry.sec_id_chain = self.build_chain_from_sat(start_index);\n\n },\n\n _ => {}\n\n }\n\n }\n\n self.entries = Some(entries);\n\n self.build_entry_tree(0, None);\n\n Ok(())\n\n }\n\n\n\n fn get_short_stream_slices(&self, chain: &std::vec::Vec<u32>, size: usize)\n\n -> Result<EntrySlice, super::error::Error> {\n\n let ssector_size = *self.short_sec_size.as_ref().unwrap();\n\n let mut entry_slice = EntrySlice::new(ssector_size, size);\n\n let short_stream_chain =\n\n &self.entries.as_ref().unwrap()[0].sec_id_chain.clone();\n\n let n_per_sector = *self.sec_size.as_ref().unwrap() /\n\n ssector_size;\n", "file_path": "src/ole/entry.rs", "rank": 41, "score": 25957.30576968708 }, { "content": " }\n\n}\n\n\n\nimpl std::fmt::Display for EntryType {\n\n fn fmt(&self, f: &mut std::fmt::Formatter) -> std::fmt::Result {\n\n match *self {\n\n EntryType::Empty => write!(f, \"Empty\"),\n\n EntryType::UserStorage => write!(f, \"User storage\"),\n\n EntryType::UserStream => write!(f, \"User stream\"),\n\n EntryType::LockBytes => write!(f, \"?? Lock bytes ??\"),\n\n EntryType::Property => write!(f, \"?? Property ??\"),\n\n EntryType::RootStorage => write!(f, \"Root storage\")\n\n }\n\n }\n\n}\n\n\n\n/// An entry in an OLE file.\n\n///\n\n/// An entry means a stream or a storage.\n\n/// A stream is a file, and a storage is a folder.\n", "file_path": "src/ole/entry.rs", "rank": 42, "score": 25956.829891301255 }, { "content": " /// Name of the stream or the storage.\n\n name: std::string::String,\n\n\n\n /// Type of the entry.\n\n entry_type: EntryType,\n\n\n\n /// Color of the entry (see <https://en.wikipedia.org/wiki/Red%E2%80%93black_tree>)\n\n color: NodeColour,\n\n\n\n /// ID of the left child entry.\n\n left_child_node: u32,\n\n\n\n /// ID of the right child entry.\n\n right_child_node: u32,\n\n\n\n /// ID of the root node\n\n root_node: u32,\n\n\n\n /// UID of the entry.\n\n identifier: std::vec::Vec<u8>, // 16 bytes\n", "file_path": "src/ole/entry.rs", "rank": 43, "score": 25955.813368048948 }, { "content": " }\n\n}\n\n\n\n\n\n/// Slice of the content of the entry.\n\n///\n\n/// This is not an ordinary slice, because OLE files are like FAT system:\n\n/// they are based on sector and SAT. Therefore, a stream can be fragmented\n\n/// through the file.\n\n///\n\n/// # Basic example\n\n///\n\n/// ```ignore\n\n/// use ole::Reader;\n\n/// use std::io::Read;\n\n/// let mut parser =\n\n/// Reader::from_path(\"assets/Thumbs.db\").unwrap();\n\n///\n\n/// let entry = parser.iterate().next().unwrap();\n\n/// let mut slice = parser.get_entry_slice(entry).unwrap();\n", "file_path": "src/ole/entry.rs", "rank": 44, "score": 25955.476117777333 }, { "content": "///\n\n/// # Basic Example\n\n///\n\n/// ```ignore\n\n/// use ole::Reader;\n\n///\n\n/// let mut parser =\n\n/// Reader::from_path(\"assets/Thumbs.db\").unwrap();\n\n///\n\n/// let entry = parser.iterate().next().unwrap();\n\n/// println!(\"Name of the entry: {}\", entry.name());\n\n/// println!(\"Type of the entry: {}\", entry._type());\n\n/// println!(\"Size of the entry: {}\", entry.len());\n\n/// ```\n\n#[derive(Debug)]\n\npub struct Entry {\n\n\n\n /// ID of the entry.\n\n id: u32,\n\n\n", "file_path": "src/ole/entry.rs", "rank": 45, "score": 25954.865526997222 }, { "content": " LockBytes,\n\n\n\n /// Property (unknown usage).\n\n Property,\n\n\n\n /// Root storage.\n\n RootStorage\n\n}\n\n\n\nimpl EntryType {\n\n fn from(t: u8) -> Result<EntryType, super::error::Error> {\n\n match t {\n\n 0 => Ok(EntryType::Empty),\n\n 1 => Ok(EntryType::UserStorage),\n\n 2 => Ok(EntryType::UserStream),\n\n 3 => Ok(EntryType::LockBytes),\n\n 4 => Ok(EntryType::Property),\n\n 5 => Ok(EntryType::RootStorage),\n\n _ => Err(super::error::Error::NodeTypeUnknown)\n\n }\n", "file_path": "src/ole/entry.rs", "rank": 46, "score": 25954.574762018045 }, { "content": " let start = 0usize;\n\n let end = std::cmp::min(sector_size, size - total_read);\n\n entry_slice.add_chunk(&sector[start .. end]);\n\n total_read += end - start;\n\n }\n\n Ok(entry_slice)\n\n }\n\n\n\n fn build_entry_tree(&mut self, id: u32, parent_id: Option<u32>) {\n\n\n\n if id != super::constants::FREE_SECID_U32 {\n\n\n\n // Register the parent id for the current node\n\n self.entries.as_mut().unwrap()[id as usize].parent_node = parent_id;\n\n\n\n // Register as child\n\n if parent_id.is_some() {\n\n self.entries.as_mut().unwrap()[parent_id.unwrap() as usize]\n\n .children_nodes.push(id);\n\n }\n", "file_path": "src/ole/entry.rs", "rank": 47, "score": 25954.201296874253 }, { "content": "\n\n let node_type = self.entries.as_ref().unwrap()[id as usize]._type();\n\n\n\n if node_type == EntryType::RootStorage || node_type ==\n\n EntryType::UserStorage {\n\n let child = self.entries.as_mut().unwrap()[id as usize].root_node;\n\n self.build_entry_tree(child, Some(id));\n\n }\n\n let left_child = self.entries.as_mut().unwrap()[id as usize]\n\n .left_child_node();\n\n let right_child = self.entries.as_mut().unwrap()[id as usize]\n\n .right_child_node();\n\n let n = self.entries.as_ref().unwrap().len() as u32;\n\n if left_child < n {\n\n self.build_entry_tree(left_child, parent_id);\n\n }\n\n if right_child < n {\n\n self.build_entry_tree(right_child, parent_id);\n\n }\n\n }\n\n }\n\n}\n", "file_path": "src/ole/entry.rs", "rank": 48, "score": 25954.179083612617 }, { "content": " let entry = Entry::from_slice(&sector[l\n\n * super::constants::DIRECTORY_ENTRY_SIZE .. (l + 1)\n\n * super::constants::DIRECTORY_ENTRY_SIZE], k as u32)?;\n\n entries.push(entry);\n\n k = k + 1;\n\n }\n\n }\n\n let stream_size = *self.minimum_standard_stream_size.as_ref().unwrap();\n\n for i in 0 .. entries.len() {\n\n let entry = &mut entries[i];\n\n match entry.entry_type {\n\n EntryType::UserStream => {\n\n let start_index = entry.sec_id_chain.pop().unwrap();\n\n if entry.size < stream_size {\n\n entry.sec_id_chain = self.build_chain_from_ssat(start_index);\n\n } else {\n\n entry.sec_id_chain = self.build_chain_from_sat(start_index);\n\n }\n\n },\n\n EntryType::RootStorage => {\n", "file_path": "src/ole/entry.rs", "rank": 49, "score": 25954.13799746213 }, { "content": " parent_node: Option<u32>\n\n}\n\n\n\nimpl Entry {\n\n\n\n fn from_slice(sector: &[u8], dir_id: u32)\n\n -> Result<Entry, super::error::Error> {\n\n let entry = Entry {\n\n id: dir_id,\n\n name: Entry::build_name(&sector[0 .. 64]),\n\n entry_type: EntryType::from(sector[66])?,\n\n color: NodeColour::from(sector[67])?,\n\n left_child_node: u32::from_slice(&sector[68 .. 72]),\n\n right_child_node: u32::from_slice(&sector[72 .. 76]),\n\n root_node: u32::from_slice(&sector[76 .. 80]),\n\n identifier: sector[80 .. 96].to_vec(),\n\n flags: sector[96 .. 100].to_vec(),\n\n creation_time: u64::from_slice(&sector[100 .. 108]),\n\n last_modification_time: u64::from_slice(&sector[108 .. 116]),\n\n sec_id_chain: vec![u32::from_slice(&sector[116 .. 120])],\n", "file_path": "src/ole/entry.rs", "rank": 50, "score": 25954.094580016575 }, { "content": " entry_slice = self.get_short_stream_slices(&entry.sec_id_chain, size)?;\n\n } else {\n\n entry_slice = self.get_stream_slices(&entry.sec_id_chain, size)?;\n\n }\n\n Ok(entry_slice)\n\n }\n\n }\n\n\n\n pub(crate) fn build_directory_entries(&mut self)\n\n -> Result<(), super::error::Error> {\n\n let n_entry_by_sector = self.sec_size.as_ref().unwrap()\n\n / super::constants::DIRECTORY_ENTRY_SIZE;\n\n let mut entries = std::vec::Vec::<Entry>::with_capacity(\n\n self.dsat.as_ref().unwrap().len() * n_entry_by_sector);\n\n\n\n let mut k = 0usize;\n\n for i in 0 .. self.dsat.as_ref().unwrap().len() {\n\n let sector_index = self.dsat.as_ref().unwrap()[i];\n\n let sector = self.read_sector(sector_index as usize)?;\n\n for l in 0 .. n_entry_by_sector {\n", "file_path": "src/ole/entry.rs", "rank": 51, "score": 25953.73889628273 }, { "content": " size: usize::from_slice(&sector[120 .. 124]),\n\n children_nodes: std::vec::Vec::new(),\n\n parent_node: None\n\n };\n\n\n\n\n\n Ok(entry)\n\n\n\n }\n\n\n\n fn build_name(array: &[u8]) -> std::string::String {\n\n let mut name = std::string::String::new();\n\n\n\n let mut i = 0usize;\n\n while i < 64 && array[i] != 0 {\n\n name.push(array[i] as char);\n\n i = i + 2;\n\n }\n\n\n\n name\n", "file_path": "src/ole/entry.rs", "rank": 52, "score": 25953.71893648357 }, { "content": " let mut total_read = 0;\n\n for ssector_id in chain {\n\n let sector_index = short_stream_chain[*ssector_id as usize / n_per_sector];\n\n let sector = self.read_sector(sector_index as usize)?;\n\n let ssector_index = *ssector_id as usize % n_per_sector;\n\n let start = ssector_index as usize * ssector_size;\n\n let end = start + std::cmp::min(ssector_size, size - total_read);\n\n entry_slice.add_chunk(&sector[start .. end]);\n\n total_read += end - start;\n\n }\n\n Ok(entry_slice)\n\n }\n\n\n\n fn get_stream_slices(&self, chain: &std::vec::Vec<u32>, size: usize)\n\n -> Result<EntrySlice, super::error::Error> {\n\n let sector_size = *self.sec_size.as_ref().unwrap();\n\n let mut entry_slice = EntrySlice::new(sector_size, size);\n\n let mut total_read = 0;\n\n for sector_id in chain {\n\n let sector = self.read_sector(*sector_id as usize)?;\n", "file_path": "src/ole/entry.rs", "rank": 53, "score": 25953.255933602228 }, { "content": " real_size: usize\n\n}\n\n\n\nimpl<'s> EntrySlice<'s> {\n\n fn new(max_chunk_size: usize, size: usize) -> EntrySlice<'s> {\n\n EntrySlice {\n\n max_chunk_size: max_chunk_size,\n\n chunks: std::vec::Vec::new(),\n\n read: 0usize,\n\n total_size: size,\n\n real_size: 0\n\n }\n\n }\n\n\n\n fn add_chunk(&mut self, chunk: &'s [u8]) {\n\n self.real_size += chunk.len();\n\n self.chunks.push(chunk);\n\n }\n\n\n\n /// Returns the length of the slice, therefore the length of the entry.\n", "file_path": "src/ole/entry.rs", "rank": 54, "score": 25952.59677224797 }, { "content": "\n\n /// Flags of the entry.\n\n flags: std::vec::Vec<u8>, // 4 bytes\n\n\n\n /// Creation time.\n\n creation_time: u64,\n\n\n\n /// Last modification time.\n\n last_modification_time: u64,\n\n\n\n /// Chain of secID which hold the stream or the storage\n\n sec_id_chain: std::vec::Vec<u32>,\n\n\n\n /// Size of the entry.\n\n size: usize,\n\n\n\n /// Array of the children's DirIDs\n\n children_nodes: std::vec::Vec<u32>,\n\n\n\n /// DirID of the parent\n", "file_path": "src/ole/entry.rs", "rank": 55, "score": 25952.079171455574 }, { "content": " fn fmt(&self, f: &mut std::fmt::Formatter) -> std::fmt::Result {\n\n match *self {\n\n NodeColour::Red => write!(f, \"RED\"),\n\n NodeColour::Black => write!(f, \"BLACK\")\n\n }\n\n }\n\n}\n\n\n\n#[derive(PartialEq, Debug, Clone, Copy)]\n\npub enum EntryType {\n\n /// Empty entry.\n\n Empty,\n\n\n\n /// Storage, i.e. a directory.\n\n UserStorage,\n\n\n\n /// Stream, i.e. a file.\n\n UserStream,\n\n\n\n /// LockBytes (unknown usage).\n", "file_path": "src/ole/entry.rs", "rank": 56, "score": 25950.724960527143 }, { "content": " &self.name\n\n }\n\n\n\n /// Returns the type of the entry.\n\n pub fn _type(&self) -> EntryType {\n\n self.entry_type\n\n }\n\n\n\n /// Returns the size of the entry\n\n pub fn len(&self) -> usize {\n\n self.size\n\n }\n\n\n\n /// Returns the DirID of the left child node\n\n pub fn left_child_node(&self) -> u32 {\n\n self.left_child_node\n\n }\n\n\n\n /// Returns the DirID of the right child node\n\n pub fn right_child_node(&self) -> u32 {\n", "file_path": "src/ole/entry.rs", "rank": 57, "score": 25950.14305421007 }, { "content": " result\n\n }\n\n}\n\n\n\n\n\n\n\n\n\nimpl<'ole> super::ole::Reader<'ole> {\n\n\n\n\n\n /// Returns the slice for the entry.\n\n pub fn get_entry_slice(&self, entry: &Entry) ->\n\n Result<EntrySlice, super::error::Error> {\n\n\n\n let entry_slice: EntrySlice;\n\n let size = entry.size;\n\n if size == 0 {\n\n Err(super::error::Error::EmptyEntry)\n\n } else {\n\n if &size < self.minimum_standard_stream_size.as_ref().unwrap() {\n", "file_path": "src/ole/entry.rs", "rank": 58, "score": 25950.085600937804 }, { "content": "/// // Read the first 42 bytes of the entry;\n\n/// let mut buf = [0u8; 42];\n\n/// let nread = slice.read(&mut buf).unwrap();\n\n///\n\n/// ```\n\npub struct EntrySlice<'s> {\n\n\n\n /// Chunk size, i.e. size of the sector.\n\n max_chunk_size: usize,\n\n\n\n /// List of slices.\n\n chunks: std::vec::Vec<&'s [u8]>,\n\n\n\n /// How many bytes which have been already read.\n\n read: usize,\n\n\n\n /// Total size of slice.\n\n total_size: usize,\n\n\n\n /// Real size of all chunks\n", "file_path": "src/ole/entry.rs", "rank": 59, "score": 25949.72831118832 }, { "content": " pub fn len(&self) -> usize {\n\n self.total_size\n\n }\n\n\n\n /// Returns the real length of all chunks\n\n pub fn real_len(&self) -> usize {\n\n self.real_size\n\n }\n\n}\n\n\n\nimpl<'s> std::io::Read for EntrySlice<'s> {\n\n\n\n fn read(&mut self, buf: &mut [u8]) -> Result<usize, std::io::Error> {\n\n let to_read = std::cmp::min(buf.len(), self.total_size - self.read);\n\n let result: Result<usize, std::io::Error>;\n\n if to_read == 0 {\n\n result = Ok(0usize);\n\n } else {\n\n let mut offset = self.read;\n\n let mut read = 0;\n", "file_path": "src/ole/entry.rs", "rank": 60, "score": 25949.057646015288 }, { "content": "use std;\n\nuse crate::ole::util::FromSlice;\n\n\n\n#[derive(Debug)]\n\npub(crate) enum NodeColour {\n\n Red,\n\n Black\n\n}\n\n\n\nimpl NodeColour {\n\n fn from(t: u8) -> Result<NodeColour, super::error::Error> {\n\n match t {\n\n 0 => Ok(NodeColour::Red),\n\n 1 => Ok(NodeColour::Black),\n\n _ => Err(super::error::Error::NodeTypeUnknown)\n\n }\n\n }\n\n}\n\n\n\nimpl std::fmt::Display for NodeColour {\n", "file_path": "src/ole/entry.rs", "rank": 61, "score": 25948.07672500403 }, { "content": " }\n\n\n\n /// Returns the ID of the entry.\n\n pub fn id(&self) -> u32 {\n\n self.id\n\n }\n\n\n\n /// Returns the creation time of the entry (could be 0)\n\n pub fn creation_time(&self) -> u64 {\n\n self.creation_time\n\n }\n\n\n\n\n\n /// Returns the last modification time of the entry (could be 0)\n\n pub fn last_modification_time(&self) -> u64 {\n\n self.last_modification_time\n\n }\n\n\n\n /// Returns the name of the entry.\n\n pub fn name(&self) -> &str {\n", "file_path": "src/ole/entry.rs", "rank": 62, "score": 25946.87068287997 }, { "content": " while read != to_read {\n\n let chunk_index = offset / self.max_chunk_size;\n\n if chunk_index >= self.chunks.len() {\n\n break;\n\n }\n\n let chunk = &self.chunks[chunk_index];\n\n let local_offset = offset % self.max_chunk_size;\n\n let end = std::cmp::min(local_offset + to_read - read,\n\n self.max_chunk_size);\n\n let slice = &chunk[local_offset .. end];\n\n for u in slice {\n\n buf[read] = *u;\n\n read += 1;\n\n self.read += 1;\n\n }\n\n offset = self.read;\n\n }\n\n result = Ok(read);\n\n }\n\n\n", "file_path": "src/ole/entry.rs", "rank": 63, "score": 25938.155051444177 }, { "content": " .iter()\n\n .map(|&key| props.get(key).map_or(String::new(), |x| x.into()))\n\n .find(|x| x.len() > 0)\n\n .unwrap_or(String::from(\"\"));\n\n Self { name, email }\n\n }\n\n}\n\n\n\n// Attachment represents attachment object in the mail.\n\n#[derive(Debug, PartialEq, Serialize, Deserialize)]\n\npub struct Attachment {\n\n pub display_name: String, // \"DisplayName\"\n\n pub payload: String, // \"AttachDataObject\"\n\n pub extension: String, // \"AttachExtension\"\n\n pub mime_tag: String, // \"AttachMimeTag\"\n\n pub file_name: String, // \"AttachFilename\"\n\n}\n\n\n\nimpl Attachment {\n\n fn create(storages: &Storages, idx: usize) -> Self {\n", "file_path": "src/parser/outlook.rs", "rank": 64, "score": 22310.23943712299 }, { "content": " use super::super::storage::Storages;\n\n use crate::ole::Reader;\n\n\n\n let parser = Reader::from_path(\"data/test_email.msg\").unwrap();\n\n let mut storages = Storages::new(&parser);\n\n storages.process_streams(&parser);\n\n\n\n let transport_text = storages.get_val_from_root_or_default(\"TransportMessageHeaders\");\n\n\n\n let header = TransportHeaders::create_from_headers_text(&transport_text);\n\n\n\n assert_eq!(\n\n header,\n\n TransportHeaders {\n\n content_type: String::new(),\n\n date: String::new(),\n\n message_id: String::new(),\n\n reply_to: String::new()\n\n }\n\n );\n", "file_path": "src/parser/outlook.rs", "rank": 65, "score": 22310.131895293584 }, { "content": " pub fn from_path<P: AsRef<Path>>(path: P) -> Result<Self, Error> {\n\n let file = File::open(path)?;\n\n let parser = ole::Reader::new(file)?;\n\n let mut storages = Storages::new(&parser);\n\n storages.process_streams(&parser);\n\n\n\n let outlook = Self::populate(&storages);\n\n Ok(outlook)\n\n }\n\n\n\n pub fn from_slice(slice: &[u8]) -> Result<Self, Error> {\n\n let parser = ole::Reader::new(slice)?;\n\n let mut storages = Storages::new(&parser);\n\n storages.process_streams(&parser);\n\n\n\n let outlook = Self::populate(&storages);\n\n Ok(outlook)\n\n }\n\n\n\n pub fn to_json(&self) -> Result<String, Error> {\n", "file_path": "src/parser/outlook.rs", "rank": 66, "score": 22307.339918261965 }, { "content": "use std::collections::HashMap;\n\n\n\n// PropIdNameMap refers to mapping between property ID and\n\n// Full list is available in [MS-OXPROPS].\n\n#[derive(Debug)]\n\npub struct PropIdNameMap {\n\n map: HashMap<String, String>,\n\n}\n\n\n\nimpl PropIdNameMap {\n\n pub fn init() -> Self {\n\n let map: HashMap<String, String> = vec![\n\n (\"0x0001\", \"TemplateData\"),\n\n (\"0x0002\", \"AlternateRecipientAllowed\"),\n\n (\"0x0004\", \"ScriptData\"),\n\n (\"0x0005\", \"AutoForwarded\"),\n\n (\"0x000F\", \"DeferredDeliveryTime\"),\n\n (\"0x0010\", \"DeliverTime\"),\n\n (\"0x0015\", \"ExpiryTime\"),\n\n (\"0x0017\", \"Importance\"),\n", "file_path": "src/parser/constants.rs", "rank": 67, "score": 22306.100281581683 }, { "content": " ),\n\n }\n\n }\n\n}\n\n\n\n// Person represents either Sender or Receiver.\n\n#[derive(Debug, PartialEq, Serialize, Deserialize)]\n\npub struct Person {\n\n pub name: Name,\n\n pub email: Email,\n\n}\n\n\n\nimpl Person {\n\n fn new(name: Name, email: Email) -> Self {\n\n Self { name, email }\n\n }\n\n fn create_from_props(props: &Properties, name_key: &str, email_keys: Vec<&str>) -> Self {\n\n let name: String = props.get(name_key).map_or(String::new(), |x| x.into());\n\n // Get the fist email that can be found in props given email_keys.\n\n let email = email_keys\n", "file_path": "src/parser/outlook.rs", "rank": 68, "score": 22303.38690084644 }, { "content": "use std::{\n\n io,\n\n};\n\n\n\nuse serde_json::Error as SerdeError;\n\n\n\nuse thiserror::Error as ThisError;\n\n\n\nuse crate::ole::Error as OleError;\n\n\n\n// DataTypeError is used when decode fails in datatype.rs\n\n#[derive(ThisError, Debug)]\n\npub enum DataTypeError {\n\n UnknownCode(String),\n\n Utf8Err(#[from] std::string::FromUtf8Error),\n\n Utf16Err(#[from] std::string::FromUtf16Error),\n\n}\n\n\n\nimpl std::fmt::Display for DataTypeError {\n\n fn fmt(&self, f: &mut std::fmt::Formatter) -> std::fmt::Result {\n", "file_path": "src/parser/error.rs", "rank": 69, "score": 22303.10478312335 }, { "content": " (\"0xFFFD\", \"AddressBookContainerId\"),\n\n ]\n\n .into_iter()\n\n .map(|(k, v)| (k.to_string(), v.to_string()))\n\n .collect();\n\n\n\n Self { map }\n\n }\n\n\n\n pub fn get_canonical_name(&self, id: &str) -> Option<String> {\n\n self.map.get(id).map(|v| v.to_string())\n\n }\n\n}\n", "file_path": "src/parser/constants.rs", "rank": 70, "score": 22302.155614022307 }, { "content": " );\n\n // Check filenames\n\n let filenames: Vec<String> = outlook\n\n .attachments\n\n .iter()\n\n .map(|x| x.file_name.clone())\n\n .collect();\n\n assert_eq!(\n\n filenames,\n\n vec![\n\n \"\".to_string(),\n\n \"milky-~1.jpg\".to_string(),\n\n \"TestEm~1.msg\".to_string()\n\n ]\n\n );\n\n }\n\n\n\n #[test]\n\n fn test_attachment_msg() {\n\n let path = \"data/attachment.msg\";\n", "file_path": "src/parser/outlook.rs", "rank": 71, "score": 22301.68818052215 }, { "content": " }\n\n caps.and_then(|cap| cap.get(1).map(|x| String::from(x.as_str())))\n\n .unwrap_or(String::from(\"\"))\n\n }\n\n\n\n pub fn create_from_headers_text(text: &str) -> Self {\n\n // Case-insensitive match\n\n Self {\n\n content_type: Self::extract_field(\n\n text,\n\n Regex::new(r\"(?i)Content-Type: (.*(\\n\\s.*)*)\\r\\n\").unwrap(),\n\n ),\n\n date: Self::extract_field(&text, Regex::new(r\"(?i)Date: (.*(\\n\\s.*)*)\\r\\n\").unwrap()),\n\n message_id: Self::extract_field(\n\n text,\n\n Regex::new(r\"(?i)Message-ID: (.*(\\n\\s.*)*)\\r\\n\").unwrap(),\n\n ),\n\n reply_to: Self::extract_field(\n\n text,\n\n Regex::new(r\"(?i)Reply-To: (.*(\\n\\s.*)*)\\r\\n\").unwrap(),\n", "file_path": "src/parser/outlook.rs", "rank": 72, "score": 22300.67981219711 }, { "content": " );\n\n // Check filenames\n\n let filenames: Vec<String> = outlook\n\n .attachments\n\n .iter()\n\n .map(|x| x.file_name.clone())\n\n .collect();\n\n assert_eq!(\n\n filenames,\n\n vec![\n\n \"loan_p~1.doc\".to_string(),\n\n \"image001.png\".to_string(),\n\n \"image002.jpg\".to_string()\n\n ]\n\n );\n\n }\n\n\n\n #[test]\n\n fn test_unicode_msg() {\n\n let path = \"data/unicode.msg\";\n", "file_path": "src/parser/outlook.rs", "rank": 73, "score": 22300.136386285703 }, { "content": " .iter()\n\n .map(|x| x.extension.clone())\n\n .collect();\n\n assert_eq!(\n\n exts,\n\n vec![\"\".to_string(), \".jpg\".to_string(), \".msg\".to_string()]\n\n );\n\n // Check mime tag\n\n let mimes: Vec<String> = outlook\n\n .attachments\n\n .iter()\n\n .map(|x| x.mime_tag.clone())\n\n .collect();\n\n assert_eq!(\n\n mimes,\n\n vec![\n\n \"\".to_string(),\n\n \"\".to_string(),\n\n \"\".to_string()\n\n ]\n", "file_path": "src/parser/outlook.rs", "rank": 74, "score": 22299.62308712529 }, { "content": " );\n\n\n\n assert_eq!(outlook.attachments.len(), 3);\n\n // Check displaynames\n\n let displays: Vec<String> = outlook\n\n .attachments\n\n .iter()\n\n .map(|x| x.display_name.clone())\n\n .collect();\n\n assert_eq!(\n\n displays,\n\n vec![\n\n \"1 Days Left\\u{14} 35% off cloud space, upgrade now!\".to_string(),\n\n \"milky-way-2695569_960_720.jpg\".to_string(),\n\n \"Test Email.msg\".to_string(),\n\n ]\n\n );\n\n // Check extensions\n\n let exts: Vec<String> = outlook\n\n .attachments\n", "file_path": "src/parser/outlook.rs", "rank": 75, "score": 22299.57957854438 }, { "content": " pub cc: Vec<Person>, // \"DisplayCc\"\n\n pub bcc: Name, // \"DisplayBcc\"\n\n pub subject: String, // \"Subject\"\n\n pub body: String, // \"Body\"\n\n pub rtf_compressed: String, // \"RtfCompressed\"\n\n pub attachments: Vec<Attachment>, // See Attachment struct\n\n}\n\n\n\nimpl Outlook {\n\n fn extract_cc_from_headers(header_text: &str) -> Vec<Person> {\n\n // Format in header is:\n\n // CC: NAME <EMAIL>, NAME <EMAIL> \\r\\n\n\n let re = Regex::new(r\"(?i)CC: .*(\\r\\n\\t)?.*\\r\\n\").unwrap();\n\n let caps = re.captures(header_text);\n\n if caps.is_none() {\n\n return vec![];\n\n }\n\n let cap = caps.unwrap().get(0).unwrap().as_str();\n\n // Remove first 3 chars\n\n // Split at \",\", then trim and clean each string\n", "file_path": "src/parser/outlook.rs", "rank": 76, "score": 22299.38619419063 }, { "content": " .iter()\n\n .map(|x| x.extension.clone())\n\n .collect();\n\n assert_eq!(\n\n exts,\n\n vec![\".doc\".to_string(), \".png\".to_string(), \".jpg\".to_string()]\n\n );\n\n // Check mime tag\n\n let mimes: Vec<String> = outlook\n\n .attachments\n\n .iter()\n\n .map(|x| x.mime_tag.clone())\n\n .collect();\n\n assert_eq!(\n\n mimes,\n\n vec![\n\n \"application/msword\".to_string(),\n\n \"image/png\".to_string(),\n\n \"image/jpeg\".to_string()\n\n ]\n", "file_path": "src/parser/outlook.rs", "rank": 77, "score": 22298.99001599807 }, { "content": " cc_persons\n\n }\n\n\n\n fn populate(storages: &Storages) -> Self {\n\n let headers_text = storages.get_val_from_root_or_default(\"TransportMessageHeaders\");\n\n let headers = TransportHeaders::create_from_headers_text(&headers_text);\n\n\n\n // Outlook::extract_cc_from_headers(&headers_text);\n\n Self {\n\n headers,\n\n sender: Person::create_from_props(\n\n &storages.root,\n\n \"SenderName\",\n\n vec![\"SenderSmtpAddress\", \"SenderEmailAddress\"],\n\n ),\n\n to: storages\n\n .recipients\n\n .iter()\n\n .map(|recip_map| {\n\n Person::create_from_props(\n", "file_path": "src/parser/outlook.rs", "rank": 78, "score": 22298.345885371764 }, { "content": " let outlook = Outlook::from_path(path).unwrap();\n\n assert_eq!(outlook.attachments.len(), 3);\n\n\n\n // Check displaynames\n\n let displays: Vec<String> = outlook\n\n .attachments\n\n .iter()\n\n .map(|x| x.display_name.clone())\n\n .collect();\n\n assert_eq!(\n\n displays,\n\n vec![\n\n \"loan_proposal.doc\".to_string(),\n\n \"image001.png\".to_string(),\n\n \"image002.jpg\".to_string()\n\n ]\n\n );\n\n // Check extensions\n\n let exts: Vec<String> = outlook\n\n .attachments\n", "file_path": "src/parser/outlook.rs", "rank": 79, "score": 22297.34830421095 }, { "content": " recip_map,\n\n \"DisplayName\",\n\n vec![\"SmtpAddress\", \"EmailAddress\"],\n\n )\n\n })\n\n .collect(),\n\n cc: Outlook::extract_cc_from_headers(&headers_text),\n\n bcc: storages.get_val_from_root_or_default(\"DisplayBcc\"),\n\n subject: storages.get_val_from_root_or_default(\"Subject\"),\n\n body: storages.get_val_from_root_or_default(\"Body\"),\n\n rtf_compressed: storages.get_val_from_root_or_default(\"RtfCompressed\"),\n\n attachments: storages\n\n .attachments\n\n .iter()\n\n .enumerate()\n\n .map(|(i, _)| Attachment::create(storages, i))\n\n .collect(),\n\n }\n\n }\n\n\n", "file_path": "src/parser/outlook.rs", "rank": 80, "score": 22297.2757627411 }, { "content": " Self {\n\n display_name: storages.get_val_from_attachment_or_default(idx, \"DisplayName\"),\n\n payload: storages.get_val_from_attachment_or_default(idx, \"AttachDataObject\"),\n\n extension: storages.get_val_from_attachment_or_default(idx, \"AttachExtension\"),\n\n mime_tag: storages.get_val_from_attachment_or_default(idx, \"AttachMimeTag\"),\n\n file_name: storages.get_val_from_attachment_or_default(idx, \"AttachFilename\"),\n\n }\n\n }\n\n}\n\n\n\n// Outlook is the Mail container.\n\n// Each field corresponds to a field listed in\n\n// MS-OXPROPS.\n\n// https://docs.microsoft.com/en-us/openspecs/exchange_server_protocols/ms-oxprops/f6ab1613-aefe-447d-a49c-18217230b148\n\n// Note: Prefixes are omitted for brevity.\n\n#[derive(Serialize, Deserialize, Debug)]\n\npub struct Outlook {\n\n pub headers: TransportHeaders, // \"TransportMessageHeader\"\n\n pub sender: Person, // \"SenderName\" , \"SenderSmtpAddress\"/\"SenderEmailAddress\"\n\n pub to: Vec<Person>, // \"DisplayName\", \"SmtpAddress\"/\"EmailAddress\"\n", "file_path": "src/parser/outlook.rs", "rank": 81, "score": 22295.821692641544 }, { "content": "use std::{\n\n fs::File,\n\n path::Path\n\n};\n\n\n\nuse regex::Regex;\n\n\n\nuse serde::{Deserialize, Serialize};\n\nuse serde_json;\n\n\n\nuse crate::ole;\n\n\n\nuse super::{\n\n error::Error,\n\n storage::{\n\n Properties,\n\n Storages\n\n }\n\n};\n\n\n", "file_path": "src/parser/outlook.rs", "rank": 82, "score": 22295.32408718301 }, { "content": " // We should be left with [\"NAME <EMAIL\", \"NAME <EMAIL\"]\n\n let cc_list = &cap[3..]\n\n .split(\",\")\n\n .map(|x| x.trim().replace('>', \"\"))\n\n .collect::<Vec<String>>();\n\n\n\n let mut cc_persons: Vec<Person> = vec![];\n\n for cc in cc_list.iter() {\n\n let name_email_pair: Vec<&str> = cc.split(\"<\").map(|x| x.trim()).collect();\n\n let person = if name_email_pair.len() < 2 {\n\n // In the unlikely event that there's no email provided.\n\n Person::new(name_email_pair[0].to_string(), \"\".to_string())\n\n } else {\n\n Person::new(\n\n name_email_pair[0].replace('\"', \"\"),\n\n name_email_pair[1].to_string(),\n\n )\n\n };\n\n cc_persons.push(person);\n\n }\n", "file_path": "src/parser/outlook.rs", "rank": 83, "score": 22294.86682033196 }, { "content": " (\"0x3705\", \"AttachMethod\"),\n\n (\"0x3707\", \"AttachLongFilename\"),\n\n (\"0x3708\", \"AttachPathname\"),\n\n (\"0x3709\", \"AttachRendering\"),\n\n (\"0x370A\", \"AttachTag\"),\n\n (\"0x370B\", \"RenderingPosition\"),\n\n (\"0x370C\", \"AttachTransportName\"),\n\n (\"0x370D\", \"AttachLongPathname\"),\n\n (\"0x370E\", \"AttachMimeTag\"),\n\n (\"0x370F\", \"AttachAdditionalInformation\"),\n\n (\"0x3711\", \"AttachContentBase\"),\n\n (\"0x3712\", \"AttachContentId\"),\n\n (\"0x3713\", \"AttachContentLocation\"),\n\n (\"0x3714\", \"AttachFlags\"),\n\n (\"0x3719\", \"AttachPayloadProviderGuidString\"),\n\n (\"0x371A\", \"AttachPayloadClass\"),\n\n (\"0x371B\", \"TextAttachmentCharset\"),\n\n (\"0x3900\", \"DisplayType\"),\n\n (\"0x3902\", \"Templateid\"),\n\n (\"0x3905\", \"DisplayTypeEx\"),\n", "file_path": "src/parser/constants.rs", "rank": 84, "score": 22294.17397004494 }, { "content": " (\"0x6619\", \"UserEntryId\"),\n\n (\"0x661B\", \"MailboxOwnerEntryId\"),\n\n (\"0x661C\", \"MailboxOwnerName\"),\n\n (\"0x661D\", \"OutOfOfficeState\"),\n\n (\"0x6622\", \"SchedulePlusFreeBusyEntryId\"),\n\n (\"0x6638\", \"SerializedReplidGuidMap\"),\n\n (\"0x6639\", \"Rights\"),\n\n (\"0x663A\", \"HasRules\"),\n\n (\"0x663B\", \"AddressBookEntryId\"),\n\n (\"0x663E\", \"HierarchyChangeNumber\"),\n\n (\"0x6645\", \"ClientActions\"),\n\n (\"0x6646\", \"DamOriginalEntryId\"),\n\n (\"0x6647\", \"DamBackPatched\"),\n\n (\"0x6648\", \"RuleError\"),\n\n (\"0x6649\", \"RuleActionType\"),\n\n (\"0x664A\", \"HasNamedProperties\"),\n\n (\"0x6650\", \"RuleActionNumber\"),\n\n (\"0x6651\", \"RuleFolderEntryId\"),\n\n (\"0x666A\", \"ProhibitReceiveQuota\"),\n\n (\"0x666C\", \"InConflict\"),\n", "file_path": "src/parser/constants.rs", "rank": 85, "score": 22294.054233762487 }, { "content": " (\"0x0C1B\", \"SupplementaryInfo\"),\n\n (\"0x0C1D\", \"SenderSearchKey\"),\n\n (\"0x0C1E\", \"SenderAddressType\"),\n\n (\"0x0C1F\", \"SenderEmailAddress\"),\n\n (\"0x0C21\", \"RemoteMessageTransferAgent\"),\n\n (\"0x0E01\", \"DeleteAfterSubmit\"),\n\n (\"0x0E02\", \"DisplayBcc\"),\n\n (\"0x0E03\", \"DisplayCc\"),\n\n (\"0x0E04\", \"DisplayTo\"),\n\n (\"0x0E06\", \"MessageDeliveryTime\"),\n\n (\"0x0E07\", \"MessageFlags\"),\n\n (\"0x0E08\", \"MessageSizeExtended\"),\n\n (\"0x0E09\", \"ParentEntryId\"),\n\n (\"0x0E0F\", \"Responsibility\"),\n\n (\"0x0E12\", \"MessageRecipients\"),\n\n (\"0x0E13\", \"MessageAttachments\"),\n\n (\"0x0E17\", \"MessageStatus\"),\n\n (\"0x0E1B\", \"HasAttachments\"),\n\n (\"0x0E1D\", \"NormalizedSubject\"),\n\n (\"0x0E1F\", \"RtfInSync\"),\n", "file_path": "src/parser/constants.rs", "rank": 86, "score": 22293.94556571073 }, { "content": " (\"0x6804\", \"OfflineAddressBookDistinguishedName\"),\n\n (\"0x6805\", \"VoiceMessageAttachmentOrder\"),\n\n (\"0x6806\", \"CallId\"),\n\n (\"0x6820\", \"ReportingMessageTransferAgent\"),\n\n (\"0x6834\", \"SearchFolderLastUsed\"),\n\n (\"0x683A\", \"SearchFolderExpiration\"),\n\n (\"0x6841\", \"SearchFolderTemplateId\"),\n\n (\"0x6842\", \"WlinkGroupHeaderID\"),\n\n (\"0x6843\", \"ScheduleInfoDontMailDelegates\"),\n\n (\"0x6844\", \"SearchFolderRecreateInfo\"),\n\n (\"0x6845\", \"SearchFolderDefinition\"),\n\n (\"0x6846\", \"SearchFolderComponentType\"),\n\n (\"0x6847\", \"WlinkSaveStamp\"),\n\n (\"0x6848\", \"SearchFolderEfpFlags\"),\n\n (\"0x6849\", \"WlinkType\"),\n\n (\"0x684A\", \"WlinkFlags\"),\n\n (\"0x684B\", \"WlinkOrdinal\"),\n\n (\"0x684C\", \"WlinkEntryId\"),\n\n (\"0x684D\", \"WlinkRecordKey\"),\n\n (\"0x684E\", \"WlinkStoreEntryId\"),\n", "file_path": "src/parser/constants.rs", "rank": 87, "score": 22293.8417637935 }, { "content": " (\"0x001A\", \"MessageClass\"),\n\n (\"0x0023\", \"OriginatorDeliveryReportRequested\"),\n\n (\"0x0025\", \"ParentKey\"),\n\n (\"0x0026\", \"Priority\"),\n\n (\"0x0029\", \"ReadReceiptRequested\"),\n\n (\"0x002A\", \"ReceiptTime\"),\n\n (\"0x002B\", \"RecipientReassignmentProhibited\"),\n\n (\"0x002E\", \"OriginalSensitivity\"),\n\n (\"0x0030\", \"ReplyTime\"),\n\n (\"0x0031\", \"ReportTag\"),\n\n (\"0x0032\", \"ReportTime\"),\n\n (\"0x0036\", \"Sensitivity\"),\n\n (\"0x0037\", \"Subject\"),\n\n (\"0x0039\", \"ClientSubmitTime\"),\n\n (\"0x003A\", \"ReportName\"),\n\n (\"0x003B\", \"SentRepresentingSearchKey\"),\n\n (\"0x003D\", \"SubjectPrefix\"),\n\n (\"0x003F\", \"ReceivedByEntryId\"),\n\n (\"0x0040\", \"ReceivedByName\"),\n\n (\"0x0041\", \"SentRepresentingEntryId\"),\n", "file_path": "src/parser/constants.rs", "rank": 88, "score": 22293.74573699265 }, { "content": " Ok(serde_json::to_string(self)?)\n\n }\n\n}\n\n\n\n#[cfg(test)]\n\nmod tests {\n\n use super::{Outlook, Person, TransportHeaders};\n\n\n\n #[test]\n\n fn test_invalid_file() {\n\n let path = \"data/bad_outlook.msg\";\n\n let err = Outlook::from_path(path).unwrap_err();\n\n assert_eq!(\n\n err.to_string(),\n\n \"Error parsing file with ole: failed to fill whole buffer\".to_string()\n\n );\n\n }\n\n\n\n #[test]\n\n fn test_transport_header_test_email_1() {\n", "file_path": "src/parser/outlook.rs", "rank": 89, "score": 22293.726185126612 }, { "content": " (\"0x0042\", \"SentRepresentingName\"),\n\n (\"0x0043\", \"ReceivedRepresentingEntryId\"),\n\n (\"0x0044\", \"ReceivedRepresentingName\"),\n\n (\"0x0045\", \"ReportEntryId\"),\n\n (\"0x0046\", \"ReadReceiptEntryId\"),\n\n (\"0x0047\", \"MessageSubmissionId\"),\n\n (\"0x0049\", \"OriginalSubject\"),\n\n (\"0x004B\", \"OriginalMessageClass\"),\n\n (\"0x004C\", \"OriginalAuthorEntryId\"),\n\n (\"0x004D\", \"OriginalAuthorName\"),\n\n (\"0x004E\", \"OriginalSubmitTime\"),\n\n (\"0x004F\", \"ReplyRecipientEntries\"),\n\n (\"0x0050\", \"ReplyRecipientNames\"),\n\n (\"0x0051\", \"ReceivedBySearchKey\"),\n\n (\"0x0052\", \"ReceivedRepresentingSearchKey\"),\n\n (\"0x0053\", \"ReadReceiptSearchKey\"),\n\n (\"0x0054\", \"ReportSearchKey\"),\n\n (\"0x0055\", \"OriginalDeliveryTime\"),\n\n (\"0x0057\", \"MessageToMe\"),\n\n (\"0x0058\", \"MessageCcMe\"),\n", "file_path": "src/parser/constants.rs", "rank": 90, "score": 22293.672627822536 }, { "content": " (\"0x0059\", \"MessageRecipientMe\"),\n\n (\"0x005A\", \"OriginalSenderName\"),\n\n (\"0x005B\", \"OriginalSenderEntryId\"),\n\n (\"0x005C\", \"OriginalSenderSearchKey\"),\n\n (\"0x005D\", \"OriginalSentRepresentingName\"),\n\n (\"0x005E\", \"OriginalSentRepresentingEntryId\"),\n\n (\"0x005F\", \"OriginalSentRepresentingSearchKey\"),\n\n (\"0x0060\", \"StartDate\"),\n\n (\"0x0061\", \"EndDate\"),\n\n (\"0x0062\", \"OwnerAppointmentId\"),\n\n (\"0x0063\", \"ResponseRequested\"),\n\n (\"0x0064\", \"SentRepresentingAddressType\"),\n\n (\"0x0065\", \"SentRepresentingEmailAddress\"),\n\n (\"0x0066\", \"OriginalSenderAddressType\"),\n\n (\"0x0067\", \"OriginalSenderEmailAddress\"),\n\n (\"0x0068\", \"OriginalSentRepresentingAddressType\"),\n\n (\"0x0069\", \"OriginalSentRepresentingEmailAddress\"),\n\n (\"0x0070\", \"ConversationTopic\"),\n\n (\"0x0071\", \"ConversationIndex\"),\n\n (\"0x0072\", \"OriginalDisplayBcc\"),\n", "file_path": "src/parser/constants.rs", "rank": 91, "score": 22292.944778862642 }, { "content": " match *self {\n\n DataTypeError::UnknownCode(ref value) => {\n\n write!(f, \"DataTypeError: Unknown value encoding: 0x{}\", value)\n\n }\n\n DataTypeError::Utf8Err(ref err) => {\n\n write!(\n\n f,\n\n \"DataTypeError: Unable to decode bytes into UTF-8 string {}\",\n\n err.to_string()\n\n )\n\n }\n\n DataTypeError::Utf16Err(ref err) => {\n\n write!(\n\n f,\n\n \"DataTypeError: Unable to decode bytes into UTF-16 string {}\",\n\n err.to_string()\n\n )\n\n }\n\n }\n\n }\n", "file_path": "src/parser/error.rs", "rank": 92, "score": 22292.10161617954 }, { "content": " (\"0x6704\", \"AddressBookManageDistributionList\"),\n\n (\"0x6705\", \"SortLocaleId\"),\n\n (\"0x6709\", \"LocalCommitTime\"),\n\n (\"0x670A\", \"LocalCommitTimeMax\"),\n\n (\"0x670B\", \"DeletedCountTotal\"),\n\n (\"0x670E\", \"FlatUrlName\"),\n\n (\"0x6740\", \"SentMailSvrEID\"),\n\n (\"0x6741\", \"DeferredActionMessageOriginalEntryId\"),\n\n (\"0x6748\", \"FolderId\"),\n\n (\"0x6749\", \"ParentFolderId\"),\n\n (\"0x674A\", \"Mid\"),\n\n (\"0x674D\", \"InstID\"),\n\n (\"0x674E\", \"InstanceNum\"),\n\n (\"0x674F\", \"AddressBookMessageId\"),\n\n (\"0x67A4\", \"ChangeNumber\"),\n\n (\"0x67AA\", \"Associated\"),\n\n (\"0x6800\", \"OfflineAddressBookName\"),\n\n (\"0x6801\", \"VoiceMessageDuration\"),\n\n (\"0x6802\", \"SenderTelephoneNumber\"),\n\n (\"0x6803\", \"VoiceMessageSenderName\"),\n", "file_path": "src/parser/constants.rs", "rank": 93, "score": 22291.293416635497 }, { "content": " ]\n\n );\n\n\n\n assert_eq!(\n\n outlook.subject,\n\n String::from(\"Test Email\")\n\n );\n\n\n\n assert_eq!(\n\n outlook.headers,\n\n TransportHeaders {\n\n content_type: String::new(),\n\n date: String::new(),\n\n message_id: String::new(),\n\n reply_to: String::new(),\n\n }\n\n );\n\n\n\n assert_eq!(\n\n outlook\n", "file_path": "src/parser/outlook.rs", "rank": 94, "score": 22291.01599774648 }, { "content": " );\n\n\n\n assert_eq!(\n\n outlook.cc,\n\n vec![Person::new(\n\n \"Brian Zhou\".to_string(),\n\n \"[email protected]\".to_string()\n\n ),]\n\n );\n\n assert_eq!(outlook.subject, String::from(\"Test for TIF files\"));\n\n assert_eq!(\n\n outlook.headers,\n\n TransportHeaders {\n\n content_type: \"multipart/mixed; boundary=001a113392ecbd7a5404eb6f4d6a\".to_string(),\n\n date: \"Mon, 18 Nov 2013 10:26:24 +0200\".to_string(),\n\n message_id: \"<CADtJ4eNjQSkGcBtVteCiTF+YFG89+AcHxK3QZ=-Mt48xygkvdQ@mail.gmail.com>\"\n\n .to_string(),\n\n reply_to: String::from(\"\")\n\n }\n\n );\n", "file_path": "src/parser/outlook.rs", "rank": 95, "score": 22290.846437174816 }, { "content": " (\"0x360F\", \"ContainerContents\"),\n\n (\"0x3610\", \"FolderAssociatedContents\"),\n\n (\"0x3613\", \"ContainerClass\"),\n\n (\"0x36D0\", \"IpmAppointmentEntryId\"),\n\n (\"0x36D1\", \"IpmContactEntryId\"),\n\n (\"0x36D2\", \"IpmJournalEntryId\"),\n\n (\"0x36D3\", \"IpmNoteEntryId\"),\n\n (\"0x36D4\", \"IpmTaskEntryId\"),\n\n (\"0x36D5\", \"RemindersOnlineEntryId\"),\n\n (\"0x36D7\", \"IpmDraftsEntryId\"),\n\n (\"0x36D8\", \"AdditionalRenEntryIds\"),\n\n (\"0x36D9\", \"AdditionalRenEntryIdsEx\"),\n\n (\"0x36DA\", \"ExtendedFolderFlags\"),\n\n (\"0x36E2\", \"OrdinalMost\"),\n\n (\"0x36E4\", \"FreeBusyEntryIds\"),\n\n (\"0x36E5\", \"DefaultPostMessageClass\"),\n\n (\"0x3701\", \"AttachDataObject\"),\n\n (\"0x3702\", \"AttachEncoding\"),\n\n (\"0x3703\", \"AttachExtension\"),\n\n (\"0x3704\", \"AttachFilename\"),\n", "file_path": "src/parser/constants.rs", "rank": 96, "score": 22290.03152877293 }, { "content": " (\"0x0E20\", \"AttachSize\"),\n\n (\"0x0E21\", \"AttachNumber\"),\n\n (\"0x0E28\", \"PrimarySendAccount\"),\n\n (\"0x0E29\", \"NextSendAcct\"),\n\n (\"0x0E2B\", \"ToDoItemFlags\"),\n\n (\"0x0E2C\", \"SwappedToDoStore\"),\n\n (\"0x0E2D\", \"SwappedToDoData\"),\n\n (\"0x0E69\", \"Read\"),\n\n (\"0x0E6A\", \"SecurityDescriptorAsXml\"),\n\n (\"0x0E79\", \"TrustSender\"),\n\n (\"0x0E84\", \"ExchangeNTSecurityDescriptor\"),\n\n (\"0x0E99\", \"ExtendedRuleMessageActions\"),\n\n (\"0x0E9A\", \"ExtendedRuleMessageCondition\"),\n\n (\"0x0E9B\", \"ExtendedRuleSizeLimit\"),\n\n (\"0x0FF4\", \"Access\"),\n\n (\"0x0FF5\", \"RowType\"),\n\n (\"0x0FF6\", \"InstanceKey\"),\n\n (\"0x0FF7\", \"AccessLevel\"),\n\n (\"0x0FF8\", \"MappingSignature\"),\n\n (\"0x0FF9\", \"RecordKey\"),\n", "file_path": "src/parser/constants.rs", "rank": 97, "score": 22290.013045493863 }, { "content": " }\n\n\n\n #[test]\n\n fn test_test_email() {\n\n let path = \"data/test_email.msg\";\n\n let outlook = Outlook::from_path(path).unwrap();\n\n assert_eq!(\n\n outlook.sender,\n\n Person {\n\n name: \"\".to_string(),\n\n email: \"\".to_string()\n\n }\n\n );\n\n assert_eq!(\n\n outlook.to,\n\n vec![\n\n Person {\n\n name: \"[email protected]\".to_string(),\n\n email: \"[email protected]\".to_string()\n\n },\n", "file_path": "src/parser/outlook.rs", "rank": 98, "score": 22289.40189960707 }, { "content": " (\"0x7002\", \"ViewDescriptorStrings\"),\n\n (\"0x7006\", \"ViewDescriptorName\"),\n\n (\"0x7007\", \"ViewDescriptorVersion\"),\n\n (\"0x7C06\", \"RoamingDatatypes\"),\n\n (\"0x7C07\", \"RoamingDictionary\"),\n\n (\"0x7C08\", \"RoamingXmlStream\"),\n\n (\"0x7C24\", \"OscSyncEnabled\"),\n\n (\"0x7D01\", \"Processed\"),\n\n (\"0x7FF9\", \"ExceptionReplaceTime\"),\n\n (\"0x7FFA\", \"AttachmentLinkId\"),\n\n (\"0x7FFB\", \"ExceptionStartTime\"),\n\n (\"0x7FFC\", \"ExceptionEndTime\"),\n\n (\"0x7FFD\", \"AttachmentFlags\"),\n\n (\"0x7FFE\", \"AttachmentHidden\"),\n\n (\"0x7FFF\", \"AttachmentContactPhoto\"),\n\n (\"0x8004\", \"AddressBookFolderPathname\"),\n\n (\"0x8005\", \"AddressBookManagerDistinguishedName\"),\n\n (\"0x8006\", \"AddressBookHomeMessageDatabase\"),\n\n (\"0x8008\", \"AddressBookIsMemberOfDistributionList\"),\n\n (\"0x8009\", \"AddressBookMember\"),\n", "file_path": "src/parser/constants.rs", "rank": 99, "score": 22289.095134184212 } ]
Rust
src/librustc_mir/transform/nll/constraint_generation.rs
arshiafaradj/rust
2f47a9eb80bc3474b6e89637269ef1f92cfccb7f
use rustc::hir; use rustc::mir::{Location, Lvalue, Mir, Rvalue}; use rustc::mir::visit::Visitor; use rustc::mir::Lvalue::Projection; use rustc::mir::{LvalueProjection, ProjectionElem}; use rustc::infer::InferCtxt; use rustc::traits::{self, ObligationCause}; use rustc::ty::{self, Ty}; use rustc::ty::fold::TypeFoldable; use rustc::util::common::ErrorReported; use rustc_data_structures::fx::FxHashSet; use syntax::codemap::DUMMY_SP; use super::LivenessResults; use super::ToRegionVid; use super::region_infer::RegionInferenceContext; pub(super) fn generate_constraints<'a, 'gcx, 'tcx>( infcx: &InferCtxt<'a, 'gcx, 'tcx>, regioncx: &mut RegionInferenceContext<'tcx>, mir: &Mir<'tcx>, param_env: ty::ParamEnv<'tcx>, liveness: &LivenessResults, ) { ConstraintGeneration { infcx, regioncx, mir, liveness, param_env, }.add_constraints(); } struct ConstraintGeneration<'cx, 'gcx: 'tcx, 'tcx: 'cx> { infcx: &'cx InferCtxt<'cx, 'gcx, 'tcx>, regioncx: &'cx mut RegionInferenceContext<'tcx>, mir: &'cx Mir<'tcx>, liveness: &'cx LivenessResults, param_env: ty::ParamEnv<'tcx>, } impl<'cx, 'gcx, 'tcx> ConstraintGeneration<'cx, 'gcx, 'tcx> { fn add_constraints(&mut self) { self.add_liveness_constraints(); self.add_borrow_constraints(); } fn add_liveness_constraints(&mut self) { debug!("add_liveness_constraints()"); for bb in self.mir.basic_blocks().indices() { debug!("add_liveness_constraints: bb={:?}", bb); self.liveness .regular .simulate_block(self.mir, bb, |location, live_locals| { for live_local in live_locals.iter() { let live_local_ty = self.mir.local_decls[live_local].ty; self.add_regular_live_constraint(live_local_ty, location); } }); self.liveness .drop .simulate_block(self.mir, bb, |location, live_locals| { for live_local in live_locals.iter() { let live_local_ty = self.mir.local_decls[live_local].ty; self.add_drop_live_constraint(live_local_ty, location); } }); } } fn add_regular_live_constraint<T>(&mut self, live_ty: T, location: Location) where T: TypeFoldable<'tcx>, { debug!( "add_regular_live_constraint(live_ty={:?}, location={:?})", live_ty, location ); self.infcx .tcx .for_each_free_region(&live_ty, |live_region| { let vid = live_region.to_region_vid(); self.regioncx.add_live_point(vid, location); }); } fn add_drop_live_constraint(&mut self, dropped_ty: Ty<'tcx>, location: Location) { debug!( "add_drop_live_constraint(dropped_ty={:?}, location={:?})", dropped_ty, location ); let tcx = self.infcx.tcx; let mut types = vec![(dropped_ty, 0)]; let mut known = FxHashSet(); while let Some((ty, depth)) = types.pop() { let span = DUMMY_SP; let result = match tcx.dtorck_constraint_for_ty(span, dropped_ty, depth, ty) { Ok(result) => result, Err(ErrorReported) => { continue; } }; let ty::DtorckConstraint { outlives, dtorck_types, } = result; for outlive in outlives { if let Some(ty) = outlive.as_type() { self.add_regular_live_constraint(ty, location); } else if let Some(r) = outlive.as_region() { self.add_regular_live_constraint(r, location); } else { bug!() } } for ty in dtorck_types { let cause = ObligationCause::dummy(); match traits::fully_normalize(self.infcx, cause, self.param_env, &ty) { Ok(ty) => match ty.sty { ty::TyParam(..) | ty::TyProjection(..) | ty::TyAnon(..) => { self.add_regular_live_constraint(ty, location); } _ => if known.insert(ty) { types.push((ty, depth + 1)); }, }, Err(errors) => { self.infcx.report_fulfillment_errors(&errors, None); } } } } } fn add_borrow_constraints(&mut self) { self.visit_mir(self.mir); } fn add_reborrow_constraint( &mut self, location: Location, borrow_region: ty::Region<'tcx>, borrowed_lv: &Lvalue<'tcx>, ) { if let Projection(ref proj) = *borrowed_lv { let LvalueProjection { ref base, ref elem } = **proj; if let ProjectionElem::Deref = *elem { let tcx = self.infcx.tcx; let base_ty = base.ty(self.mir, tcx).to_ty(tcx); let base_sty = &base_ty.sty; if let ty::TyRef(base_region, ty::TypeAndMut{ ty: _, mutbl }) = *base_sty { match mutbl { hir::Mutability::MutImmutable => { }, hir::Mutability::MutMutable => { self.add_reborrow_constraint(location, borrow_region, base); }, } let span = self.mir.source_info(location).span; self.regioncx.add_outlives(span, base_region.to_region_vid(), borrow_region.to_region_vid(), location.successor_within_block()); } } } } } impl<'cx, 'gcx, 'tcx> Visitor<'tcx> for ConstraintGeneration<'cx, 'gcx, 'tcx> { fn visit_rvalue(&mut self, rvalue: &Rvalue<'tcx>, location: Location) { debug!("visit_rvalue(rvalue={:?}, location={:?})", rvalue, location); if let Rvalue::Ref(region, _bk, ref borrowed_lv) = *rvalue { self.add_reborrow_constraint(location, region, borrowed_lv); } self.super_rvalue(rvalue, location); } }
use rustc::hir; use rustc::mir::{Location, Lvalue, Mir, Rvalue}; use rustc::mir::visit::Visitor; use rustc::mir::Lvalue::Projection; use rustc::mir::{LvalueProjection, ProjectionElem}; use rustc::infer::InferCtxt; use rustc::traits::{self, ObligationCause}; use rustc::ty::{self, Ty}; use rustc::ty::fold::TypeFoldable; use rustc::util::common::ErrorReported; use rustc_data_structures::fx::FxHashSet; use syntax::codemap::DUMMY_SP; use super::LivenessResults; use super::ToRegionVid; use super::region_infer::RegionInferenceContext; pub(super) fn generate_constraints<'a, 'gcx, 'tcx>( infcx: &InferCtxt<'a, 'gcx, 'tcx>, regioncx: &mut RegionInferenceContext<'tcx>, mir: &Mir<'tcx>, param_env: ty::ParamEnv<'tcx>, liveness: &LivenessResults, ) { ConstraintGeneration { infcx, regioncx, mir, liveness, param_env, }.add_constraints(); } struct ConstraintGeneration<'cx, 'gcx: 'tcx, 'tcx: 'cx> { infcx: &'cx InferCtxt<'cx, 'gcx, 'tcx>, regioncx: &'cx mut RegionInferenceContext<'tcx>, mir: &'cx Mir<'tcx>, liveness: &'cx LivenessResults, param_env: ty::ParamEnv<'tcx>, } impl<'cx, 'gcx, 'tcx> ConstraintGeneration<'cx, 'gcx, 'tcx> { fn add_constraints(&mut self) { self.add_liveness_constraints(); self.add_borrow_constraints(); } fn add_liveness_constraints(&mut self) { debug!("add_liveness_constraints()"); for bb in self.mir.basic_blocks().indices() { debug!("add_liveness_constraints: bb={:?}", bb); self.liveness .regular .simulate_block(self.mir, bb, |location, live_locals| { for live_local in live_locals.iter() { let live_local_ty = self.mir.local_decls[live_local].ty; self.add_regular_live_constraint(live_local_ty, location); } }); self.liveness .drop .simulate_block(self.mir, bb, |location, live_locals| { for live_local in live_locals.iter() { let live_local_ty = self.mir.local_decls[live_local].ty; self.add_drop_live_constraint(live_local_ty, location); } }); } } fn add_regular_live_constraint<T>(&mut self, live_ty: T, location: Location) where T: TypeFoldable<'tcx>, { debug!( "add_regular_live_constraint(live_ty={:?}, location={:?})", live_ty, location ); self.infcx .tcx .for_each_free_region(&live_ty, |live_region| { let vid = live_region.to_region_vid(); self.regioncx.add_live_point(vid, location); }); } fn add_drop_live_constraint(&mut self, dropped_ty: Ty<'tcx>, location: Location) { debug!( "add_drop_live_constraint(dropped_ty={:?}, location={:?})", dropped_ty, location ); let tcx = self.infcx.tcx; let mut types = vec![(dropped_ty, 0)]; let mut known = FxHashSet(); while let Some((ty, depth)) = types.pop() { let span = DUMMY_SP; let result = match tcx.dtorck_constraint_for_ty(span, dropped_ty, depth, ty) { Ok(result) => result, Err(ErrorReported) => { continue; } }; let ty::DtorckConstraint { outlives, dtorck_types, } = result; for outlive in outlives { if let Some(ty) = outlive.as_type() { self.add_regular_live_constraint(ty, location); } else if let Some(r) = outlive.as_region() { self.add_regular_live_constraint(r, location); } else { bug!() } } for ty in dtorck_types { let cause = ObligationCause::dummy(); match traits::fully_normalize(self.infcx, cause, self.param_env, &ty) { Ok(ty) => match ty.sty { ty::TyParam(..) | ty::TyProjection(..) | ty::TyAnon(..) => { self.add_regular_live_constraint(ty, location); } _ => if known.insert(ty) { types.push((ty, depth + 1)); }, }, Err(errors) => { self.infcx.report_fulfillment_errors(&errors, None); } } } } } fn add_borrow_constraints(&mut self) { self.visit_mir(self.mir); } fn add_reborrow_constraint( &mut self, location: Location, borrow_region: ty::Region<'tcx>, borrowed_lv: &Lvalue<'tcx>, ) { if let Projection(ref proj) = *borrowed_lv {
} impl<'cx, 'gcx, 'tcx> Visitor<'tcx> for ConstraintGeneration<'cx, 'gcx, 'tcx> { fn visit_rvalue(&mut self, rvalue: &Rvalue<'tcx>, location: Location) { debug!("visit_rvalue(rvalue={:?}, location={:?})", rvalue, location); if let Rvalue::Ref(region, _bk, ref borrowed_lv) = *rvalue { self.add_reborrow_constraint(location, region, borrowed_lv); } self.super_rvalue(rvalue, location); } }
let LvalueProjection { ref base, ref elem } = **proj; if let ProjectionElem::Deref = *elem { let tcx = self.infcx.tcx; let base_ty = base.ty(self.mir, tcx).to_ty(tcx); let base_sty = &base_ty.sty; if let ty::TyRef(base_region, ty::TypeAndMut{ ty: _, mutbl }) = *base_sty { match mutbl { hir::Mutability::MutImmutable => { }, hir::Mutability::MutMutable => { self.add_reborrow_constraint(location, borrow_region, base); }, } let span = self.mir.source_info(location).span; self.regioncx.add_outlives(span, base_region.to_region_vid(), borrow_region.to_region_vid(), location.successor_within_block()); } } } }
function_block-function_prefixed
[]
Rust
src/xlnet/attention.rs
sftse/rust-bert
5c1c2aa19971a613323fee423c035e0d39d27465
use crate::common::dropout::Dropout; use crate::xlnet::XLNetConfig; use std::borrow::Borrow; use tch::nn::Init; use tch::{nn, Kind, Tensor}; #[derive(Debug)] pub struct LayerState { pub prev_content: Tensor, } impl Clone for LayerState { fn clone(&self) -> Self { LayerState { prev_content: self.prev_content.copy(), } } } impl LayerState { pub(crate) fn reorder_cache(&mut self, new_indices: &Tensor) { self.prev_content = self.prev_content.index_select(1, new_indices); } } #[derive(Debug)] pub struct XLNetRelativeAttention { num_attention_heads: i64, attention_head_size: i64, hidden_size: i64, dropout: Dropout, output_attentions: bool, query: Tensor, key: Tensor, value: Tensor, output: Tensor, pos: Tensor, r_r_bias: Tensor, r_s_bias: Tensor, r_w_bias: Tensor, seg_embed: Tensor, layer_norm: nn::LayerNorm, scale: f64, } impl XLNetRelativeAttention { pub fn new<'p, P>(p: P, config: &XLNetConfig) -> XLNetRelativeAttention where P: Borrow<nn::Path<'p>>, { assert_eq!( config.d_model % config.d_head, 0, "Hidden size not a multiple of attention heads dimension" ); let p = p.borrow(); let query = p.var( "q", &[config.d_model, config.n_head, config.d_head], Init::KaimingUniform, ); let key = p.var( "k", &[config.d_model, config.n_head, config.d_head], Init::KaimingUniform, ); let value = p.var( "v", &[config.d_model, config.n_head, config.d_head], Init::KaimingUniform, ); let output = p.var( "o", &[config.d_model, config.n_head, config.d_head], Init::KaimingUniform, ); let pos = p.var( "r", &[config.d_model, config.n_head, config.d_head], Init::KaimingUniform, ); let r_r_bias = p.var( "r_r_bias", &[config.n_head, config.d_head], Init::KaimingUniform, ); let r_s_bias = p.var( "r_s_bias", &[config.n_head, config.d_head], Init::KaimingUniform, ); let r_w_bias = p.var( "r_w_bias", &[config.n_head, config.d_head], Init::KaimingUniform, ); let seg_embed = p.var( "seg_embed", &[2, config.n_head, config.d_head], Init::KaimingUniform, ); let dropout = Dropout::new(config.dropout); let output_attentions = config.output_attentions.unwrap_or(false); let layer_norm_eps = config.layer_norm_eps.unwrap_or(1e-12); let layer_norm_config = nn::LayerNormConfig { eps: layer_norm_eps, ..Default::default() }; let layer_norm = nn::layer_norm(p / "layer_norm", vec![config.d_model], layer_norm_config); let scale = 1f64 / ((config.d_head as f64).powf(0.5f64)); XLNetRelativeAttention { num_attention_heads: config.n_head, attention_head_size: config.d_head, hidden_size: config.d_model, dropout, output_attentions, query, key, value, output, pos, r_r_bias, r_s_bias, r_w_bias, seg_embed, layer_norm, scale, } } fn rel_shift_bnij(&self, x: &Tensor, klen: i64) -> Tensor { let shape = x.size(); x.reshape(&[shape[0], shape[1], shape[3], shape[2]]) .narrow(2, 1, shape[3] - 1) .reshape(&[shape[0], shape[1], shape[2], shape[3] - 1]) .index_select(3, &Tensor::arange(klen, (Kind::Int64, x.device()))) } fn rel_attention_core( &self, q_head: &Tensor, k_head_h: &Tensor, v_head_h: &Tensor, k_head_r: &Tensor, seg_mat: Option<&Tensor>, attention_mask: Option<&Tensor>, train: bool, ) -> (Tensor, Option<Tensor>) { let ac = Tensor::einsum("ibnd,jbnd->bnij", &[&(q_head + &self.r_w_bias), k_head_h]); let bd = self.rel_shift_bnij( &Tensor::einsum("ibnd,jbnd->bnij", &[&(q_head + &self.r_r_bias), k_head_r]), ac.size()[3], ); let ef = match seg_mat { Some(seg_mat) => { let ef = Tensor::einsum( "ibnd,snd->ibns", &[&(q_head + &self.r_s_bias), &self.seg_embed], ); Tensor::einsum("ijbs,ibns->bnij", &[seg_mat, &ef]) } None => Tensor::zeros(&[1], (Kind::Float, ac.device())), }; let mut attention_score = (ac + bd + ef) * self.scale; if let Some(value) = attention_mask { attention_score = attention_score - value.permute(&[2, 3, 0, 1]) * 1e30; }; let attention_probas = attention_score .softmax(3, Kind::Float) .apply_t(&self.dropout, train); let attention_vector = Tensor::einsum("bnij,jbnd->ibnd", &[&attention_probas, v_head_h]); if self.output_attentions { ( attention_vector, Some(attention_probas.permute(&[2, 3, 0, 1])), ) } else { (attention_vector, None) } } fn post_attention( &self, h: &Tensor, attention_vector: &Tensor, residual: bool, train: bool, ) -> Tensor { let mut attention_out = Tensor::einsum("ibnd,hnd->ibh", &[attention_vector, &self.output]) .apply_t(&self.dropout, train); if residual { attention_out = attention_out + h; }; attention_out.apply(&self.layer_norm) } pub fn forward_t( &self, h: &Tensor, g: Option<&Tensor>, attn_mask_h: Option<&Tensor>, attn_mask_g: Option<&Tensor>, r: &Tensor, seg_mat: Option<&Tensor>, layer_state: Option<LayerState>, target_mapping: Option<&Tensor>, train: bool, ) -> (Tensor, Option<Tensor>, Option<Tensor>, Option<Tensor>) { let cat_value = if let Some(mems) = &layer_state { if mems.prev_content.size().len() > 1 { Some(Tensor::cat(&[&mems.prev_content, h], 0)) } else { None } } else { None }; let cat = match &cat_value { Some(value) => value, None => h, }; let q_head_h = Tensor::einsum("ibh,hnd->ibnd", &[h, &self.query]); let k_head_h = Tensor::einsum("ibh,hnd->ibnd", &[cat, &self.key]); let v_head_h = Tensor::einsum("ibh,hnd->ibnd", &[cat, &self.value]); let k_head_r = Tensor::einsum("ibh,hnd->ibnd", &[r, &self.pos]); let (attention_vec_h, attention_probas_h) = self.rel_attention_core( &q_head_h, &k_head_h, &v_head_h, &k_head_r, seg_mat, attn_mask_h, train, ); let output_h = self.post_attention(h, &attention_vec_h, true, train); let (output_g, attention_probas_g) = if let Some(g) = g { let q_head_g = Tensor::einsum("ibh,hnd->ibnd", &[g, &self.query]); let (attention_vec_g, attention_probas_g) = match target_mapping { Some(target_mapping) => { let q_head_g = Tensor::einsum("mbnd,mlb->lbnd", &[&q_head_g, target_mapping]); let (attention_vec_g, attention_probas_g) = self.rel_attention_core( &q_head_g, &k_head_h, &v_head_h, &k_head_r, seg_mat, attn_mask_g, train, ); let attention_vec_g = Tensor::einsum("lbnd,mlb->mbnd", &[&attention_vec_g, target_mapping]); (attention_vec_g, attention_probas_g) } None => self.rel_attention_core( &q_head_g, &k_head_h, &v_head_h, &k_head_r, seg_mat, attn_mask_g, train, ), }; let output_g = self.post_attention(g, &attention_vec_g, true, train); (Some(output_g), attention_probas_g) } else { (None, None) }; (output_h, output_g, attention_probas_h, attention_probas_g) } }
use crate::common::dropout::Dropout; use crate::xlnet::XLNetConfig; use std::borrow::Borrow; use tch::nn::Init; use tch::{nn, Kind, Tensor}; #[derive(Debug)] pub struct LayerState { pub prev_content: Tensor, } impl Clone for LayerState { fn clone(&self) -> Self { LayerState { prev_content: self.prev_content.copy(), } } } impl LayerState { pub(crate) fn reorder_cache(&mut self, new_indices: &Tensor) { self.prev_content = self.prev_content.index_select(1, new_indices); } } #[derive(Debug)] pub struct XLNetRelativeAttention { num_attention_heads: i64, attention_head_size: i64, hidden_size: i64, dropout: Dropout, output_attentions: bool, query: Tensor, key: Tensor, value: Tensor, output: Tensor, pos: Tensor, r_r_bias: Tensor, r_s_bias: Tensor, r_w_bias: Tensor, seg_embed: Tensor, layer_norm: nn::LayerNorm, scale: f64, } impl XLNetRelativeAttention { pub fn new<'p, P>(p: P, config: &XLNetConfig) -> XLNetRelativeAttention where P: Borrow<nn::Path<'p>>, { assert_eq!( config.d_model % config.d_head, 0, "Hidden size not a multiple of attention heads dimension" ); let p = p.borrow(); let query = p.var( "q", &[config.d_model, config.n_head, config.d_head], Init::KaimingUniform, ); let key = p.var( "k", &[config.d_model, config.n_head, config.d_head], Init::KaimingUniform, ); let value = p.var( "v", &[config.d_model, config.n_head, config.d_head], Init::KaimingUniform, ); let output = p.var( "o", &[config.d_model, config.n_head, config.d_head], Init::KaimingUniform, ); let pos = p.var( "r", &[config.d_model, config.n_head, config.d_head], Init::KaimingUniform, ); let r_r_bias = p.var( "r_r_bias", &[config.n_head, config.d_head], Init::KaimingUniform, ); let r_s_bias = p.var( "r_s_bias", &[config.n_head, config.d_head], Init::KaimingUniform, ); let r_w_bias = p.var( "r_w_bias", &[config.n_head, config.d_head], Init::KaimingUniform, ); let seg_embed = p.var( "seg_embed", &[2, config.n_head, config.d_head], Init::KaimingUniform, ); let dropout = Dropout::new(config.dropout); let output_attentions = config.output_attentions.unwrap_or(false); let layer_norm_eps = config.layer_norm_eps.unwrap_or(1e-12); let layer_norm_config = nn::LayerNormConfig { eps: layer_norm_eps, ..Default::default() }; let layer_norm = nn::layer_norm(p / "layer_norm", vec![config.d_model], layer_norm_config); let scale = 1f64 / ((config.d_head as f64).powf(0.5f64)); XLNetRelativeAttention { num_attention_heads: config.n_head, attention_head_size: config.d_head, hidden_size: config.d_model, dropout, output_attentions, query, key, value, output, pos, r_r_bias, r_s_bias, r_w_bias, seg_embed, layer_norm, scale, } } fn rel_shift_bnij(&self, x: &Tensor, klen: i64) -> Tensor { let shape = x.size(); x.reshape(&[shape[0], shape[1], shape[3], shape[2]]) .narrow(2, 1, shape[3] - 1) .reshape(&[shape[0], shape[1], shape[2], shape[3] - 1]) .index_select(3, &Tensor::arange(klen, (Kind::Int64, x.device()))) } fn rel_attention_core( &self, q_head: &Tensor, k_head_h: &Tensor, v_head_h: &Tensor, k_head_r: &Tensor, seg_mat: Option<&Tensor>, attention_mask: Option<&Tensor>, train: bool, ) -> (Tensor, Option<Tensor>) { let ac = Tensor::einsum("ibnd,jbnd->bnij", &[&(q_head + &self.r_w_bias), k_head_h]); let bd = self.rel_shift_bnij( &Tensor::einsum("ibnd,jbnd->bnij", &[&(q_head + &self.r_r_bias), k_head_r]), ac.size()[3], ); let ef = match seg_mat { Some(seg_mat) => { let ef = Tensor::einsum( "ibnd,snd->ibns", &[&(q_head + &self.r_s_bias), &self.seg_embed], ); Tensor::einsum("ijbs,ibns->bnij", &[seg_mat, &ef]) } None => Tensor::zeros(&[1], (Kind::Float, ac.device())), }; let mut attention_score = (ac + bd + ef) * self.scale; if let Some(value) = attention_mask { attention_score = attention_score - value.permute(&[2, 3, 0, 1]) * 1e30; }; let attention_probas = attention_score .softmax(3, Kind::Float) .apply_t(&self.dropout, train); let attention_vector = Tensor::einsum("bnij,jbnd->ibnd", &[&attention_probas, v_head_h]); if self.output_attentions { ( attention_vector, Some(attention_probas.permute(&[2, 3, 0, 1])), ) } else { (attention_vector, None) } }
pub fn forward_t( &self, h: &Tensor, g: Option<&Tensor>, attn_mask_h: Option<&Tensor>, attn_mask_g: Option<&Tensor>, r: &Tensor, seg_mat: Option<&Tensor>, layer_state: Option<LayerState>, target_mapping: Option<&Tensor>, train: bool, ) -> (Tensor, Option<Tensor>, Option<Tensor>, Option<Tensor>) { let cat_value = if let Some(mems) = &layer_state { if mems.prev_content.size().len() > 1 { Some(Tensor::cat(&[&mems.prev_content, h], 0)) } else { None } } else { None }; let cat = match &cat_value { Some(value) => value, None => h, }; let q_head_h = Tensor::einsum("ibh,hnd->ibnd", &[h, &self.query]); let k_head_h = Tensor::einsum("ibh,hnd->ibnd", &[cat, &self.key]); let v_head_h = Tensor::einsum("ibh,hnd->ibnd", &[cat, &self.value]); let k_head_r = Tensor::einsum("ibh,hnd->ibnd", &[r, &self.pos]); let (attention_vec_h, attention_probas_h) = self.rel_attention_core( &q_head_h, &k_head_h, &v_head_h, &k_head_r, seg_mat, attn_mask_h, train, ); let output_h = self.post_attention(h, &attention_vec_h, true, train); let (output_g, attention_probas_g) = if let Some(g) = g { let q_head_g = Tensor::einsum("ibh,hnd->ibnd", &[g, &self.query]); let (attention_vec_g, attention_probas_g) = match target_mapping { Some(target_mapping) => { let q_head_g = Tensor::einsum("mbnd,mlb->lbnd", &[&q_head_g, target_mapping]); let (attention_vec_g, attention_probas_g) = self.rel_attention_core( &q_head_g, &k_head_h, &v_head_h, &k_head_r, seg_mat, attn_mask_g, train, ); let attention_vec_g = Tensor::einsum("lbnd,mlb->mbnd", &[&attention_vec_g, target_mapping]); (attention_vec_g, attention_probas_g) } None => self.rel_attention_core( &q_head_g, &k_head_h, &v_head_h, &k_head_r, seg_mat, attn_mask_g, train, ), }; let output_g = self.post_attention(g, &attention_vec_g, true, train); (Some(output_g), attention_probas_g) } else { (None, None) }; (output_h, output_g, attention_probas_h, attention_probas_g) } }
fn post_attention( &self, h: &Tensor, attention_vector: &Tensor, residual: bool, train: bool, ) -> Tensor { let mut attention_out = Tensor::einsum("ibnd,hnd->ibh", &[attention_vector, &self.output]) .apply_t(&self.dropout, train); if residual { attention_out = attention_out + h; }; attention_out.apply(&self.layer_norm) }
function_block-full_function
[ { "content": "pub fn stable_argsort(input_tensor: &Tensor, dim: i64) -> Tensor {\n\n let scaling_dim = input_tensor.size()[dim as usize];\n\n let scaled_offset = Tensor::arange(scaling_dim, (Kind::Int, input_tensor.device()))\n\n .view([1, 1, -1])\n\n .expand(&input_tensor.size(), true);\n\n let scaled_tensor = scaling_dim * input_tensor + (scaled_offset / scaling_dim);\n\n scaled_tensor.argsort(dim, false)\n\n}\n\n\n", "file_path": "src/reformer/attention_utils.rs", "rank": 0, "score": 276703.5336581665 }, { "content": "pub fn look_adjacent(vectors: Tensor, num_chunks_before: i64, num_chunks_after: i64) -> Tensor {\n\n if (num_chunks_before == 0) & (num_chunks_after == 0) {\n\n vectors\n\n } else {\n\n let mut calc_slices =\n\n Vec::with_capacity((num_chunks_before + num_chunks_after + 1) as usize);\n\n let mut ref_slices =\n\n Vec::with_capacity((num_chunks_before + num_chunks_after + 1) as usize);\n\n for i in -num_chunks_before..num_chunks_after + 1 {\n\n calc_slices.push(Tensor::cat(\n\n &[\n\n &vectors.slice(2, i, vectors.size()[2], 1),\n\n &vectors.slice(2, 0, i, 1),\n\n ],\n\n 2,\n\n ))\n\n }\n\n for i in -num_chunks_before..num_chunks_after + 1 {\n\n if i == 0 {\n\n ref_slices.push(&vectors)\n\n } else {\n\n ref_slices.push(&calc_slices[(i + num_chunks_before) as usize])\n\n }\n\n }\n\n Tensor::cat(ref_slices.as_slice(), 3)\n\n }\n\n}\n\n\n", "file_path": "src/reformer/attention_utils.rs", "rank": 1, "score": 269286.04451421543 }, { "content": "pub fn lcm(a: i64, b: i64) -> i64 {\n\n a * (b / gcd(a, b))\n\n}\n\n\n", "file_path": "src/reformer/attention_utils.rs", "rank": 2, "score": 244904.1278329044 }, { "content": "pub fn split_hidden_size_dim(\n\n input: &Tensor,\n\n num_attention_heads: i64,\n\n attention_head_size: i64,\n\n) -> Tensor {\n\n let mut new_x_shape = input.size();\n\n let _ = new_x_shape.pop();\n\n new_x_shape.push(num_attention_heads);\n\n new_x_shape.push(attention_head_size);\n\n input.view(new_x_shape.as_slice()).transpose(2, 1)\n\n}\n\n\n", "file_path": "src/reformer/attention_utils.rs", "rank": 3, "score": 244647.5989448039 }, { "content": "pub fn merge_hidden_size_dim(\n\n input: &Tensor,\n\n num_attention_heads: i64,\n\n attention_head_size: i64,\n\n) -> Tensor {\n\n let new_shape = [\n\n input.size()[0],\n\n -1,\n\n num_attention_heads * attention_head_size,\n\n ];\n\n input.permute(&[0, 2, 1, 3]).reshape(&new_shape)\n\n}\n\n\n", "file_path": "src/reformer/attention_utils.rs", "rank": 4, "score": 244647.5989448039 }, { "content": "pub fn _tanh(x: &Tensor) -> Tensor {\n\n x.tanh()\n\n}\n\n\n\npub struct TensorFunction(Box<fn(&Tensor) -> Tensor>);\n\n\n\nimpl TensorFunction {\n\n pub fn new(fun: Box<fn(&Tensor) -> Tensor>) -> Self {\n\n Self(fun)\n\n }\n\n\n\n pub fn get_fn(&self) -> &fn(&Tensor) -> Tensor {\n\n &self.0\n\n }\n\n}\n\nimpl std::fmt::Debug for TensorFunction {\n\n fn fmt(&self, f: &mut std::fmt::Formatter) -> Result<(), std::fmt::Error> {\n\n write!(f, \"TensorFunction\")\n\n }\n\n}\n", "file_path": "src/common/activations.rs", "rank": 5, "score": 234991.58939437784 }, { "content": "pub fn _swish(x: &Tensor) -> Tensor {\n\n x * x.sigmoid()\n\n}\n\n\n", "file_path": "src/common/activations.rs", "rank": 6, "score": 234991.5893943778 }, { "content": "pub fn _gelu(x: &Tensor) -> Tensor {\n\n x * 0.5 * (1.0 + (x / ((2.0_f64).sqrt())).erf())\n\n}\n\n\n", "file_path": "src/common/activations.rs", "rank": 7, "score": 234991.5893943778 }, { "content": "pub fn _relu(x: &Tensor) -> Tensor {\n\n x.relu()\n\n}\n\n\n", "file_path": "src/common/activations.rs", "rank": 8, "score": 234991.58939437784 }, { "content": "pub fn _mish(x: &Tensor) -> Tensor {\n\n x * (x.softplus().tanh())\n\n}\n\n\n", "file_path": "src/common/activations.rs", "rank": 9, "score": 234991.58939437784 }, { "content": "pub fn _gelu_new(x: &Tensor) -> Tensor {\n\n x * 0.5 * (((x.pow_tensor_scalar(3.0f64) * 0.044715 + x) * ((2f64 / PI).sqrt())).tanh() + 1)\n\n}\n\n\n", "file_path": "src/common/activations.rs", "rank": 10, "score": 230856.28160318514 }, { "content": "fn ngram_attention_bias(sequence_length: i64, ngram: i64, device: Device) -> Tensor {\n\n let left_block = Tensor::ones(\n\n &[ngram, sequence_length, sequence_length],\n\n (Kind::Float, device),\n\n ) * f64::NEG_INFINITY;\n\n let right_block = left_block.copy();\n\n for stream_idx in 0..ngram {\n\n let _ = right_block.get(stream_idx).fill_diagonal_(0, false);\n\n let _ = left_block.get(stream_idx).triu_(-stream_idx + 1);\n\n }\n\n let _ = left_block.slice(2, 0, sequence_length, 1).fill_(0);\n\n Tensor::cat(&[left_block, right_block], 2)\n\n}\n\n\n\npub struct ProphetNetDecoderLayer {\n\n self_attention: ProphetNetNgramAttention,\n\n self_attention_layer_norm: nn::LayerNorm,\n\n cross_attention: Option<ProphetNetAttention>,\n\n cross_attention_layer_norm: Option<nn::LayerNorm>,\n\n feed_forward: ProphetNetFeedForward,\n", "file_path": "src/prophetnet/decoder.rs", "rank": 11, "score": 207772.4523577933 }, { "content": "pub fn retrieve_relevant_hidden_states(\n\n previous_hidden_states: &Tensor,\n\n chunk_length: i64,\n\n num_chunks_before: i64,\n\n) -> Tensor {\n\n let end_position = previous_hidden_states.size()[1];\n\n let start_position = ((end_position / chunk_length) - num_chunks_before) * chunk_length;\n\n previous_hidden_states.slice(1, start_position, end_position, 1)\n\n}\n\n\n\n#[cfg(test)]\n\nmod test {\n\n use crate::reformer::attention::AttentionType;\n\n use crate::reformer::attention_utils::{\n\n get_least_common_mult_chunk_len, get_min_chunk_len, lcm,\n\n };\n\n\n\n #[test]\n\n fn test_lcm_calculation() {\n\n let test_pairs = [(7, 3), (1, 1), (8, 9), (48, 32), (-1, -1), (1, 0), (0, 1)];\n", "file_path": "src/reformer/attention_utils.rs", "rank": 12, "score": 206270.07926528668 }, { "content": "fn gcd(a: i64, b: i64) -> i64 {\n\n if b == 0 {\n\n a\n\n } else {\n\n gcd(b, a % b)\n\n }\n\n}\n\n\n", "file_path": "src/reformer/attention_utils.rs", "rank": 13, "score": 192189.31811462116 }, { "content": "fn _shift_tokens_right(input_ids: &Tensor, pad_token_id: i64) -> Tensor {\n\n let output = input_ids.masked_fill(&input_ids.eq(-100), pad_token_id);\n\n let index_eos: Tensor = input_ids\n\n .ne(pad_token_id)\n\n .sum_dim_intlist(&[1], true, Int64)\n\n - 1;\n\n output\n\n .select(1, 0)\n\n .copy_(&input_ids.gather(1, &index_eos, true).squeeze());\n\n output\n\n .slice(1, 1, *output.size().last().unwrap(), 1)\n\n .copy_(&input_ids.slice(1, 0, *output.size().last().unwrap() - 1, 1));\n\n output\n\n}\n\n\n\npub struct MBartClassificationHead {\n\n dense: nn::Linear,\n\n dropout: Dropout,\n\n out_proj: nn::Linear,\n\n}\n", "file_path": "src/mbart/mbart_model.rs", "rank": 14, "score": 179999.27405422134 }, { "content": "fn _shift_tokens_right(input_ids: &Tensor, pad_token_id: i64) -> Tensor {\n\n let index_eos: Tensor = input_ids\n\n .ne(pad_token_id)\n\n .sum_dim_intlist(&[-1], true, Int64)\n\n - 1;\n\n let output = input_ids.empty_like().to_kind(Int64);\n\n output\n\n .select(1, 0)\n\n .copy_(&input_ids.gather(1, &index_eos, true).squeeze());\n\n output\n\n .slice(1, 1, *output.size().last().unwrap(), 1)\n\n .copy_(&input_ids.slice(1, 0, *output.size().last().unwrap() - 1, 1));\n\n output\n\n}\n\n\n\n/// # BART Base model\n\n/// Base architecture for BART model. Usually complemented with a task-specific head, such as a language model head.\n\n/// It is made of the following blocks:\n\n/// - `encoder`: `BartEncoder` (transformer) made of a vector of encoding layers\n\n/// - `decoder`: `BartDecoder` (transformer) made of a vector of decoding layers with self attention and encoder cross-attention.\n", "file_path": "src/bart/bart_model.rs", "rank": 15, "score": 179999.27405422134 }, { "content": "fn get_question_end_index(input_ids: &Tensor, sep_token_id: i64) -> Tensor {\n\n input_ids\n\n .eq(sep_token_id)\n\n .nonzero()\n\n .view([input_ids.size()[0], 3, 2])\n\n .select(2, 1)\n\n .select(1, 0)\n\n}\n\n\n", "file_path": "src/longformer/longformer_model.rs", "rank": 16, "score": 177365.92982299137 }, { "content": "pub fn reverse_sort(\n\n out_vectors: &Tensor,\n\n logits: &Tensor,\n\n undo_sorted_bucket_idx: &Tensor,\n\n) -> (Tensor, Tensor) {\n\n let expanded_undo_sort_indices = undo_sorted_bucket_idx\n\n .unsqueeze(-1)\n\n .expand(out_vectors.size().as_slice(), true);\n\n let out_vectors = out_vectors.gather(2, &expanded_undo_sort_indices, true);\n\n let logits = logits.gather(2, undo_sorted_bucket_idx, true);\n\n (out_vectors, logits)\n\n}\n\n\n", "file_path": "src/reformer/attention_utils.rs", "rank": 17, "score": 176185.74524024237 }, { "content": "fn bench_tensor_ops(c: &mut Criterion) {\n\n // Set-up summarization model\n\n unsafe {\n\n torch_sys::dummy_cuda_dependency();\n\n }\n\n let input = Tensor::rand(&[32, 128, 512], (Float, Device::cuda_if_available()));\n\n let weights = Tensor::rand(&[512, 512], (Float, Device::cuda_if_available()));\n\n\n\n let _ = &input.matmul(&weights);\n\n c.bench_function(\"Matrix multiply \", |b| {\n\n b.iter_custom(|iters| black_box(matrix_multiply(iters, &input, &weights)))\n\n });\n\n}\n\n\n\ncriterion_group! {\n\nname = benches;\n\nconfig = Criterion::default().sample_size(100);\n\ntargets = bench_tensor_ops\n\n}\n\n\n\ncriterion_main!(benches);\n", "file_path": "benches/tensor_operations_benchmark.rs", "rank": 18, "score": 173914.5679151807 }, { "content": "pub fn split_seq_length_dim_to(\n\n vectors: &Tensor,\n\n dim_factor_1: i64,\n\n dim_factor_2: i64,\n\n num_attention_heads: i64,\n\n attention_head_size: Option<i64>,\n\n) -> Result<Tensor, RustBertError> {\n\n let input_size = vectors.size();\n\n let batch_size = input_size[0];\n\n let mut split_dim_shape = vec![batch_size, num_attention_heads, dim_factor_1, dim_factor_2];\n\n\n\n if input_size.len() == 4 {\n\n let attention_head_size = if let Some(attention_head_size_value) = attention_head_size {\n\n attention_head_size_value\n\n } else {\n\n return Err(RustBertError::ValueError(\n\n \"attention_head_size must be provided for inputs of dimension 4\".to_string(),\n\n ));\n\n };\n\n split_dim_shape.push(attention_head_size);\n\n };\n\n Ok(vectors.reshape(split_dim_shape.as_slice()))\n\n}\n\n\n", "file_path": "src/reformer/attention_utils.rs", "rank": 19, "score": 167892.55958576946 }, { "content": "pub fn get_min_chunk_len(\n\n attention_types: &[AttentionType],\n\n lsh_attn_chunk_length: Option<i64>,\n\n local_attn_chunk_length: Option<i64>,\n\n) -> i64 {\n\n let num_unique_attention_type = attention_types\n\n .iter()\n\n .collect::<HashSet<&AttentionType>>()\n\n .len();\n\n match num_unique_attention_type {\n\n 1 => {\n\n if attention_types[0] == AttentionType::lsh {\n\n lsh_attn_chunk_length.unwrap_or(64)\n\n } else {\n\n local_attn_chunk_length.unwrap_or(64)\n\n }\n\n }\n\n 2 => min(\n\n lsh_attn_chunk_length.unwrap_or(64),\n\n local_attn_chunk_length.unwrap_or(64),\n\n ),\n\n _ => panic!(\"Impossible scenario - only 2 attention types supported\"),\n\n }\n\n}\n\n\n", "file_path": "src/reformer/attention_utils.rs", "rank": 20, "score": 167892.55958576946 }, { "content": "pub fn get_shape_and_device_from_ids_embeddings_pair(\n\n input_ids: Option<&Tensor>,\n\n input_embeddings: Option<&Tensor>,\n\n) -> Result<(Vec<i64>, Device), RustBertError> {\n\n Ok(match (input_ids, input_embeddings) {\n\n (Some(_), Some(_)) => {\n\n return Err(RustBertError::ValueError(\n\n \"Only one of input ids or input embeddings may be set\".into(),\n\n ));\n\n }\n\n (Some(input_value), None) => (input_value.size(), input_value.device()),\n\n (None, Some(embeds)) => {\n\n let size = vec![embeds.size()[0], embeds.size()[1]];\n\n (size, embeds.device())\n\n }\n\n (None, None) => {\n\n return Err(RustBertError::ValueError(\n\n \"At least one of input ids or input embeddings must be set\".into(),\n\n ));\n\n }\n\n })\n\n}\n", "file_path": "src/common/embeddings.rs", "rank": 21, "score": 164661.25005018263 }, { "content": "/// # Utility to deserialize JSON config files\n\npub trait Config\n\nwhere\n\n for<'de> Self: Deserialize<'de>,\n\n{\n\n /// Loads a `Config` object from a JSON file. The format is expected to be aligned with the [Transformers library](https://github.com/huggingface/transformers) configuration files for each model.\n\n /// The parsing will fail if non-optional keys expected by the model are missing.\n\n ///\n\n /// # Arguments\n\n ///\n\n /// * `path` - `Path` to the configuration JSON file.\n\n ///\n\n /// # Example\n\n ///\n\n /// ```no_run\n\n /// use rust_bert::gpt2::Gpt2Config;\n\n /// use rust_bert::Config;\n\n /// use std::path::Path;\n\n ///\n\n /// let config_path = Path::new(\"path/to/config.json\");\n\n /// let config = Gpt2Config::from_file(config_path);\n\n /// ```\n\n fn from_file<P: AsRef<Path>>(path: P) -> Self {\n\n let f = File::open(path).expect(\"Could not open configuration file.\");\n\n let br = BufReader::new(f);\n\n let config: Self = serde_json::from_reader(br).expect(\"could not parse configuration\");\n\n config\n\n }\n\n}\n", "file_path": "src/common/config.rs", "rank": 22, "score": 161604.37161111186 }, { "content": "pub fn get_least_common_mult_chunk_len(\n\n attention_types: &[AttentionType],\n\n lsh_attn_chunk_length: Option<i64>,\n\n local_attn_chunk_length: Option<i64>,\n\n) -> i64 {\n\n let num_unique_attention_type = attention_types\n\n .iter()\n\n .collect::<HashSet<&AttentionType>>()\n\n .len();\n\n match num_unique_attention_type {\n\n 1 => {\n\n if attention_types[0] == AttentionType::lsh {\n\n lsh_attn_chunk_length.unwrap_or(64)\n\n } else {\n\n local_attn_chunk_length.unwrap_or(64)\n\n }\n\n }\n\n 2 => lcm(\n\n lsh_attn_chunk_length.unwrap_or(64),\n\n local_attn_chunk_length.unwrap_or(64),\n\n ),\n\n _ => panic!(\"Impossible scenario - only 2 attention types supported\"),\n\n }\n\n}\n\n\n", "file_path": "src/reformer/attention_utils.rs", "rank": 23, "score": 160650.473517621 }, { "content": "pub fn main() -> Result<(), RustBertError> {\n\n let args: Vec<_> = std::env::args().collect();\n\n assert_eq!(\n\n args.len(),\n\n 3,\n\n \"usage: {} source.npz destination.ot\",\n\n args[0].as_str()\n\n );\n\n\n\n let source_file = &args[1];\n\n let destination_file = &args[2];\n\n let tensors = tch::Tensor::read_npz(source_file)?;\n\n tch::Tensor::save_multi(&tensors, destination_file)?;\n\n\n\n Ok(())\n\n}\n", "file_path": "src/convert-tensor.rs", "rank": 24, "score": 160081.15723961103 }, { "content": "fn remove_duplicates<T: PartialEq + Clone>(vector: &mut Vec<T>) -> &mut Vec<T> {\n\n let mut potential_duplicates = vec![];\n\n vector.retain(|item| {\n\n if potential_duplicates.contains(item) {\n\n false\n\n } else {\n\n potential_duplicates.push(item.clone());\n\n true\n\n }\n\n });\n\n vector\n\n}\n\n\n\n/// # Configuration for question answering\n\n/// Contains information regarding the model to load and device to place the model on.\n\npub struct QuestionAnsweringConfig {\n\n /// Model weights resource (default: pretrained DistilBERT model on SQuAD)\n\n pub model_resource: Resource,\n\n /// Config resource (default: pretrained DistilBERT model on SQuAD)\n\n pub config_resource: Resource,\n", "file_path": "src/pipelines/question_answering.rs", "rank": 25, "score": 159146.20013506635 }, { "content": "/// # Common trait for text generation models.\n\n/// Main API for text generation\n\npub trait LanguageGenerator<T: LMHeadModel, V: Vocab, U: Tokenizer<V>>:\n\n PrivateLanguageGenerator<T, V, U>\n\n{\n\n /// Generate text based on a vector of promp texts.\n\n ///\n\n /// # Arguments\n\n ///\n\n /// * `prompt_texts` - `Option<Vec<&str>>` Optional vector of text prompts. An empty prompt to the model may be passed if the model implement a `bos_id`.\n\n /// * `attention_mask` - `Option<Tensor>` Optional attention mask to hide portions of the prompt.\n\n /// * `min_length` - `impl Into<Option<i64>>` Optional minimum output sequence length\n\n /// * `max_length` - `impl Into<Option<i64>>` Optional maximum output sequence length\n\n /// * `decoder_start_token_id` - `impl Into<Option<i64>>` Optional decoder start token id\n\n /// * `prefix_allowed_tokens_fn` - `Option<&dyn Fn(i64, &Tensor) -> Vec<i64>>` Optional function to control the generation process. The function should take a `batch_id` (i64) and a tensor of token_ids already generated and returns a `Vec<i64>` of allowed tokens.\n\n ///\n\n /// # Returns\n\n /// * `Vec<TextOutput>` Vector of length *number_of_prompts* x *num_return_sequences* containing TextOutput with the generated texts and the generation score if `output_scores` is true.\n\n ///\n\n /// # Example\n\n ///\n\n /// ```no_run\n", "file_path": "src/pipelines/generation_utils.rs", "rank": 26, "score": 152541.26231919508 }, { "content": " pub trait PrivateLanguageGenerator<T: LMHeadModel, V: Vocab, U: Tokenizer<V>> {\n\n fn get_model(&self) -> &T;\n\n fn _get_tokenizer(&self) -> &TokenizerOption;\n\n fn get_var_store(&self) -> &nn::VarStore;\n\n fn get_config(&self) -> &GenerateConfig;\n\n fn get_bos_id(&self) -> &Option<i64>;\n\n fn get_eos_ids(&self) -> &Option<Vec<i64>>;\n\n fn get_pad_id(&self) -> &Option<i64>;\n\n fn is_encoder_decoder(&self) -> bool;\n\n fn get_vocab_size(&self) -> i64;\n\n fn get_decoder_start_id(&self) -> Option<i64>;\n\n fn get_max_positions_embeddings(&self) -> i64;\n\n\n\n fn prepare_scores_for_generation(\n\n &self,\n\n _scores: &mut Tensor,\n\n _current_length: i64,\n\n _max_length: i64,\n\n _forced_bos_token_id: Option<i64>,\n\n ) {\n", "file_path": "src/pipelines/generation_utils.rs", "rank": 27, "score": 150028.87207467516 }, { "content": "pub fn process_ids_embeddings_pair(\n\n input_ids: Option<&Tensor>,\n\n input_embeddings: Option<&Tensor>,\n\n embeddings_matrix: &Embedding,\n\n) -> Result<(Option<Tensor>, Vec<i64>, Device), RustBertError> {\n\n Ok(match (input_ids, input_embeddings) {\n\n (Some(_), Some(_)) => {\n\n return Err(RustBertError::ValueError(\n\n \"Only one of input ids or input embeddings may be set\".into(),\n\n ));\n\n }\n\n (Some(input_value), None) => (\n\n Some(input_value.apply(embeddings_matrix)),\n\n input_value.size(),\n\n input_value.device(),\n\n ),\n\n (None, Some(embeds)) => {\n\n let size = vec![embeds.size()[0], embeds.size()[1]];\n\n (None, size, embeds.device())\n\n }\n\n (None, None) => {\n\n return Err(RustBertError::ValueError(\n\n \"At least one of input ids or input embeddings must be set\".into(),\n\n ));\n\n }\n\n })\n\n}\n\n\n", "file_path": "src/common/embeddings.rs", "rank": 28, "score": 132712.63217551887 }, { "content": "fn matrix_multiply(iters: u64, input: &Tensor, weights: &Tensor) -> Duration {\n\n let mut duration = Duration::new(0, 0);\n\n for _i in 0..iters {\n\n let start = Instant::now();\n\n let _ = input.matmul(weights);\n\n duration = duration.checked_add(start.elapsed()).unwrap();\n\n }\n\n duration\n\n}\n\n\n", "file_path": "benches/tensor_operations_benchmark.rs", "rank": 29, "score": 132295.26363157076 }, { "content": "struct GlobalAttentionIndices {\n\n max_num_global_attention_indices: i64,\n\n is_index_global_attn_nonzero: Vec<Option<Tensor>>,\n\n is_local_index_global_attention_nonzero: Vec<Option<Tensor>>,\n\n is_local_index_no_global_attention_nonzero: Vec<Option<Tensor>>,\n\n}\n", "file_path": "src/longformer/attention.rs", "rank": 30, "score": 130893.17419583412 }, { "content": "fn bench_squad(c: &mut Criterion) {\n\n // Set-up QA model\n\n let model = create_qa_model();\n\n unsafe {\n\n torch_sys::dummy_cuda_dependency();\n\n }\n\n // Define input\n\n let mut squad_path = PathBuf::from(env::var(\"squad_dataset\")\n\n .expect(\"Please set the \\\"squad_dataset\\\" environment variable pointing to the SQuAD dataset folder\"));\n\n squad_path.push(\"dev-v2.0.json\");\n\n let mut qa_inputs = squad_processor(squad_path);\n\n qa_inputs.truncate(1000);\n\n\n\n c.bench_function(\"SQuAD forward pass\", |b| {\n\n b.iter_custom(|iters| black_box(squad_forward_pass(iters, &model, &qa_inputs)))\n\n });\n\n\n\n c.bench_function(\"Load model\", |b| {\n\n b.iter_custom(|iters| black_box(qa_load_model(iters)))\n\n });\n\n}\n\n\n\ncriterion_group! {\n\nname = benches;\n\nconfig = Criterion::default().sample_size(10);\n\ntargets = bench_squad\n\n}\n\n\n\ncriterion_main!(benches);\n", "file_path": "benches/squad_benchmark.rs", "rank": 31, "score": 127738.4883930778 }, { "content": "fn bench_sst2(c: &mut Criterion) {\n\n // Set-up classifier\n\n let model = create_sentiment_model();\n\n unsafe {\n\n torch_sys::dummy_cuda_dependency();\n\n }\n\n // Define input\n\n let mut sst2_path = PathBuf::from(env::var(\"SST2_PATH\")\n\n .expect(\"Please set the \\\"squad_dataset\\\" environment variable pointing to the SQuAD dataset folder\"));\n\n sst2_path.push(\"train.tsv\");\n\n let mut inputs = ss2_processor(sst2_path).unwrap();\n\n inputs.truncate(2000);\n\n\n\n c.bench_function(\"SST2 forward pass\", |b| {\n\n b.iter_custom(|iters| sst2_forward_pass(iters, &model, &inputs))\n\n });\n\n\n\n c.bench_function(\"Load model\", |b| b.iter_custom(sst2_load_model));\n\n}\n\n\n\ncriterion_group! {\n\n name = benches;\n\n config = Criterion::default().sample_size(10);\n\n targets = bench_sst2\n\n}\n\n\n\ncriterion_main!(benches);\n", "file_path": "benches/sst2_benchmark.rs", "rank": 32, "score": 127738.4883930778 }, { "content": "fn bench_squad(c: &mut Criterion) {\n\n // Set-up summarization model\n\n unsafe {\n\n torch_sys::dummy_cuda_dependency();\n\n }\n\n let model = create_summarization_model();\n\n\n\n // Define input\n\n let input = [\"In findings published Tuesday in Cornell University's arXiv by a team of scientists \\\n\nfrom the University of Montreal and a separate report published Wednesday in Nature Astronomy by a team \\\n\nfrom University College London (UCL), the presence of water vapour was confirmed in the atmosphere of K2-18b, \\\n\na planet circling a star in the constellation Leo. This is the first such discovery in a planet in its star's \\\n\nhabitable zone — not too hot and not too cold for liquid water to exist. The Montreal team, led by Björn Benneke, \\\n\nused data from the NASA's Hubble telescope to assess changes in the light coming from K2-18b's star as the planet \\\n\npassed between it and Earth. They found that certain wavelengths of light, which are usually absorbed by water, \\\n\nweakened when the planet was in the way, indicating not only does K2-18b have an atmosphere, but the atmosphere \\\n\ncontains water in vapour form. The team from UCL then analyzed the Montreal team's data using their own software \\\n\nand confirmed their conclusion. This was not the first time scientists have found signs of water on an exoplanet, \\\n\nbut previous discoveries were made on planets with high temperatures or other pronounced differences from Earth. \\\n\n\\\"This is the first potentially habitable planet where the temperature is right and where we now know there is water,\\\" \\\n", "file_path": "benches/summarization_benchmark.rs", "rank": 33, "score": 127738.4883930778 }, { "content": "fn bench_generation(c: &mut Criterion) {\n\n // Set-up summarization model\n\n unsafe {\n\n torch_sys::dummy_cuda_dependency();\n\n }\n\n let model = create_text_generation_model();\n\n\n\n // Define input\n\n let input = [\"Hello, I'm a language model,\"];\n\n c.bench_function(\"Generation\", |b| {\n\n b.iter_custom(|iters| black_box(generation_forward_pass(iters, &model, &input)))\n\n });\n\n}\n\n\n\ncriterion_group! {\n\nname = benches;\n\nconfig = Criterion::default().sample_size(10);\n\ntargets = bench_generation\n\n}\n\n\n\ncriterion_main!(benches);\n", "file_path": "benches/generation_benchmark.rs", "rank": 34, "score": 127738.4883930778 }, { "content": "fn bench_squad(c: &mut Criterion) {\n\n // Set-up translation model\n\n unsafe {\n\n torch_sys::dummy_cuda_dependency();\n\n }\n\n let model = create_translation_model();\n\n\n\n // Define input\n\n let input = [\n\n \"In findings published Tuesday in Cornell University's arXiv by a team of scientists from the University of Montreal and a separate report published Wednesday in Nature Astronomy by a team from University College London (UCL), the presence of water vapour was confirmed in the atmosphere of K2-18b, a planet circling a star in the constellation Leo.\",\n\n \"This is the first such discovery in a planet in its star's habitable zone — not too hot and not too cold for liquid water to exist. The Montreal team, led by Björn Benneke, used data from the NASA\\'s Hubble telescope to assess changes in the light coming from K2-18b's star as the planet passed between it and Earth.\",\n\n \"They found that certain wavelengths of light, which are usually absorbed by water, weakened when the planet was in the way, indicating not only does K2-18b have an atmosphere, but the atmosphere contains water in vapour form.\",\n\n \"The team from UCL then analyzed the Montreal team's data using their own software and confirmed their conclusion.\",\n\n \"This was not the first time scientists have found signs of water on an exoplanet, but previous discoveries were made on planets with high temperatures or other pronounced differences from Earth.\",\n\n \"This is the first potentially habitable planet where the temperature is right and where we now know there is water,\\\" said UCL astronomer Angelos Tsiaras.\",\n\n \"It's the best candidate for habitability right now.\\\" \\\"It's a good sign\\\", said Ryan Cloutier of the Harvard–Smithsonian Center for Astrophysics, who was not one of either study's authors.\",\n\n \"Overall,\\\" he continued, \\\"the presence of water in its atmosphere certainly improves the prospect of K2-18b being a potentially habitable planet, but further observations will be required to say for sure. \\\"\",\n\n \"K2-18b was first identified in 2015 by the Kepler space telescope.\",\n\n \"It is about 110 light-years from Earth and larger but less dense.\",\n\n ];\n", "file_path": "benches/translation_benchmark.rs", "rank": 35, "score": 127738.4883930778 }, { "content": "fn create_sinusoidal_embeddings(config: &DistilBertConfig, device: Device) -> nn::Embedding {\n\n let mut sinusoidal_embedding: Vec<Tensor> =\n\n Vec::with_capacity(config.max_position_embeddings as usize);\n\n for pos in 0..config.max_position_embeddings {\n\n let mut temp_vec: Vec<f64> = Vec::with_capacity(config.dim as usize);\n\n for j in 0..config.dim {\n\n if j % 2 == 0 {\n\n temp_vec.push(\n\n (pos as f64 / 10000f64.powf((2 * (j / 2)) as f64 / config.dim as f64)).sin(),\n\n );\n\n } else {\n\n temp_vec.push(\n\n (pos as f64 / 10000f64.powf((2 * (j / 2)) as f64 / config.dim as f64)).cos(),\n\n );\n\n }\n\n }\n\n let temp_vec = Tensor::of_slice(&temp_vec);\n\n sinusoidal_embedding.push(temp_vec);\n\n }\n\n let sinusoidal_embedding = Tensor::stack(&sinusoidal_embedding, 0)\n", "file_path": "src/distilbert/embeddings.rs", "rank": 36, "score": 116221.08886101107 }, { "content": "pub fn linear_no_bias<'a, T: Borrow<Path<'a>>>(\n\n vs: T,\n\n in_dim: i64,\n\n out_dim: i64,\n\n c: LinearNoBiasConfig,\n\n) -> LinearNoBias {\n\n let vs = vs.borrow();\n\n LinearNoBias {\n\n ws: vs.var(\"weight\", &[out_dim, in_dim], c.ws_init),\n\n }\n\n}\n\n\n\nimpl Module for LinearNoBias {\n\n fn forward(&self, xs: &Tensor) -> Tensor {\n\n xs.matmul(&self.ws.tr())\n\n }\n\n}\n", "file_path": "src/common/linear.rs", "rank": 37, "score": 113182.61442929316 }, { "content": "/// # Language Model trait\n\n/// Shared trait between language generation models (e.g. GPT2, GPT, BART) used in language generation pipelines.\n\npub trait LMHeadModel {\n\n /// Forward pass through the model. Example provided for GPT2.\n\n ///\n\n /// # Arguments\n\n ///\n\n /// * `input_ids` - Optional input tensor of shape (*batch size*, *sequence_length*). If None, pre-computed embeddings must be provided (see `input_embeds`)\n\n /// * `layer_past` - Optional vector of size *n_layer* containing the past keys and values of each layer of shape (*2*, *batch size*, *number of heads*, *past_sequence_length*, *hidden size per head*). When provided, these are concatenated with the current input keys and values.\n\n /// * `attention_mask` - Optional mask of shape (*batch size*, *sequence_length*). Masked position have value 0, non-masked value 1. If None set to 1\n\n /// * `input_embeds` - Optional pre-computed input embeddings of shape (*batch size*, *sequence_length*, *hidden_size*). If None, input ids must be provided (see `input_ids`)\n\n /// * `token_type_ids` - Optional token type ids used to indicate the portion of the input the token belongs to. If not None, token type embeddings will be added to the token and position embeddings.\n\n /// * `position_ids` - Optional position ids of shape (*batch size*, *sequence_length*). If None, will be incremented starting from the length of the past input.\n\n /// * `train` - boolean flag to turn on/off the dropout layers in the model. Should be set to false for inference.\n\n ///\n\n /// # Returns\n\n ///\n\n /// * `output` - `Tensor` of shape (*batch size*, *sequence_length*, *vocab_size*) representing the logits for each vocab item and position\n\n /// * `past` - `Option<Vec<Tensor>>` of length *n_layer* containing the past keys and values of each layer of shape (*2*, *batch size*, *number of heads*, *past_sequence_length*, *hidden size per head*)\n\n /// * `hidden_states` - `Option<Vec<Tensor>>` of length *num_hidden_layers* with shape (*batch size*, *sequence_length*, *hidden_size*)\n\n /// * `attentions` - `Option<Vec<Tensor>>` of length *num_hidden_layers* with shape (*batch size*, *sequence_length*, *hidden_size*)\n\n ///\n", "file_path": "src/pipelines/generation_utils.rs", "rank": 38, "score": 109247.81993922542 }, { "content": "type LabelAggregationFunction = Box<fn(&[Token]) -> (i64, String)>;\n\n\n\n/// # Enum defining the label aggregation method for sub tokens\n\n/// Defines the behaviour for labels aggregation if the consolidation of sub-tokens is enabled.\n\npub enum LabelAggregationOption {\n\n /// The label of the first sub token is assigned to the entire token\n\n First,\n\n /// The label of the last sub token is assigned to the entire token\n\n Last,\n\n /// The most frequent sub- token is assigned to the entire token\n\n Mode,\n\n /// The user can provide a function mapping a `&Vec<Token>` to a `(i64, String)` tuple corresponding to the label index, label String to return\n\n Custom(LabelAggregationFunction),\n\n}\n\n\n\n/// # Configuration for TokenClassificationModel\n\n/// Contains information regarding the model to load and device to place the model on.\n\npub struct TokenClassificationConfig {\n\n /// Model type\n\n pub model_type: ModelType,\n", "file_path": "src/pipelines/token_classification.rs", "rank": 39, "score": 108969.96897336561 }, { "content": "fn compute_global_attention_mask(\n\n input_ids: &Tensor,\n\n sep_token_id: i64,\n\n before_sep_token: bool,\n\n) -> Tensor {\n\n let question_end_index = get_question_end_index(input_ids, sep_token_id).unsqueeze(1);\n\n let attention_mask = Tensor::arange(input_ids.size()[1], (Kind::Int64, input_ids.device()));\n\n\n\n if before_sep_token {\n\n attention_mask\n\n .expand_as(input_ids)\n\n .lt_tensor(&question_end_index)\n\n } else {\n\n attention_mask\n\n .expand_as(input_ids)\n\n .gt_tensor(&(question_end_index + 1))\n\n * attention_mask\n\n .expand_as(input_ids)\n\n .lt(*input_ids.size().last().unwrap())\n\n }\n", "file_path": "src/longformer/longformer_model.rs", "rank": 40, "score": 104772.39783620537 }, { "content": "pub fn squad_processor(file_path: PathBuf) -> Vec<QaInput> {\n\n let file = fs::File::open(file_path).expect(\"unable to open file\");\n\n let json: serde_json::Value =\n\n serde_json::from_reader(file).expect(\"JSON not properly formatted\");\n\n let data = json\n\n .get(\"data\")\n\n .expect(\"SQuAD file does not contain data field\")\n\n .as_array()\n\n .expect(\"Data array not properly formatted\");\n\n\n\n let mut qa_inputs: Vec<QaInput> = Vec::with_capacity(data.len());\n\n for qa_input in data.iter() {\n\n let qa_input = qa_input.as_object().unwrap();\n\n let paragraphs = qa_input.get(\"paragraphs\").unwrap().as_array().unwrap();\n\n for paragraph in paragraphs.iter() {\n\n let paragraph = paragraph.as_object().unwrap();\n\n let context = paragraph.get(\"context\").unwrap().as_str().unwrap();\n\n let qas = paragraph.get(\"qas\").unwrap().as_array().unwrap();\n\n for qa in qas.iter() {\n\n let question = qa\n", "file_path": "src/pipelines/question_answering.rs", "rank": 41, "score": 104592.04932187824 }, { "content": "#[test]\n\nfn bert_for_multiple_choice() -> anyhow::Result<()> {\n\n // Resources paths\n\n let config_resource =\n\n Resource::Remote(RemoteResource::from_pretrained(BertConfigResources::BERT));\n\n let vocab_resource =\n\n Resource::Remote(RemoteResource::from_pretrained(BertVocabResources::BERT));\n\n let config_path = config_resource.get_local_path()?;\n\n let vocab_path = vocab_resource.get_local_path()?;\n\n\n\n // Set-up model\n\n let device = Device::Cpu;\n\n let vs = nn::VarStore::new(device);\n\n let tokenizer: BertTokenizer =\n\n BertTokenizer::from_file(vocab_path.to_str().unwrap(), true, true)?;\n\n let mut config = BertConfig::from_file(config_path);\n\n config.output_attentions = Some(true);\n\n config.output_hidden_states = Some(true);\n\n let bert_model = BertForMultipleChoice::new(&vs.root(), &config);\n\n\n\n // Define input\n", "file_path": "tests/bert.rs", "rank": 42, "score": 103767.19654537368 }, { "content": "#[test]\n\nfn roberta_for_multiple_choice() -> anyhow::Result<()> {\n\n // Resources paths\n\n let config_resource = Resource::Remote(RemoteResource::from_pretrained(\n\n RobertaConfigResources::DISTILROBERTA_BASE,\n\n ));\n\n let vocab_resource = Resource::Remote(RemoteResource::from_pretrained(\n\n RobertaVocabResources::DISTILROBERTA_BASE,\n\n ));\n\n let merges_resource = Resource::Remote(RemoteResource::from_pretrained(\n\n RobertaMergesResources::DISTILROBERTA_BASE,\n\n ));\n\n let config_path = config_resource.get_local_path()?;\n\n let vocab_path = vocab_resource.get_local_path()?;\n\n let merges_path = merges_resource.get_local_path()?;\n\n\n\n // Set-up model\n\n let device = Device::Cpu;\n\n let vs = nn::VarStore::new(device);\n\n let tokenizer: RobertaTokenizer = RobertaTokenizer::from_file(\n\n vocab_path.to_str().unwrap(),\n", "file_path": "tests/roberta.rs", "rank": 43, "score": 103767.19654537368 }, { "content": "#[test]\n\nfn albert_for_multiple_choice() -> anyhow::Result<()> {\n\n // Resources paths\n\n let config_resource = Resource::Remote(RemoteResource::from_pretrained(\n\n AlbertConfigResources::ALBERT_BASE_V2,\n\n ));\n\n let vocab_resource = Resource::Remote(RemoteResource::from_pretrained(\n\n AlbertVocabResources::ALBERT_BASE_V2,\n\n ));\n\n let config_path = config_resource.get_local_path()?;\n\n let vocab_path = vocab_resource.get_local_path()?;\n\n\n\n // Set-up model\n\n let device = Device::Cpu;\n\n let vs = nn::VarStore::new(device);\n\n let tokenizer: AlbertTokenizer =\n\n AlbertTokenizer::from_file(vocab_path.to_str().unwrap(), true, false)?;\n\n let mut config = AlbertConfig::from_file(config_path);\n\n config.output_attentions = Some(true);\n\n config.output_hidden_states = Some(true);\n\n let albert_model = AlbertForMultipleChoice::new(&vs.root(), &config);\n", "file_path": "tests/albert.rs", "rank": 44, "score": 103767.19654537368 }, { "content": "#[test]\n\nfn xlnet_for_multiple_choice() -> anyhow::Result<()> {\n\n // Resources paths\n\n let config_resource = Resource::Remote(RemoteResource::from_pretrained(\n\n XLNetConfigResources::XLNET_BASE_CASED,\n\n ));\n\n let vocab_resource = Resource::Remote(RemoteResource::from_pretrained(\n\n XLNetVocabResources::XLNET_BASE_CASED,\n\n ));\n\n let config_path = config_resource.get_local_path()?;\n\n let vocab_path = vocab_resource.get_local_path()?;\n\n\n\n // Set-up model\n\n let device = Device::Cpu;\n\n let vs = nn::VarStore::new(device);\n\n let tokenizer = XLNetTokenizer::from_file(vocab_path.to_str().unwrap(), true, true)?;\n\n let config = XLNetConfig::from_file(config_path);\n\n let xlnet_model = XLNetForMultipleChoice::new(&vs.root(), &config)?;\n\n\n\n // Define input\n\n let prompt = \"In Italy, pizza served in formal settings, such as at a restaurant, is presented unsliced.\";\n", "file_path": "tests/xlnet.rs", "rank": 45, "score": 103767.19654537368 }, { "content": "#[test]\n\nfn longformer_for_multiple_choice() -> anyhow::Result<()> {\n\n // Resources paths\n\n let config_resource = Resource::Remote(RemoteResource::from_pretrained(\n\n LongformerConfigResources::LONGFORMER_BASE_4096,\n\n ));\n\n let vocab_resource = Resource::Remote(RemoteResource::from_pretrained(\n\n LongformerVocabResources::LONGFORMER_BASE_4096,\n\n ));\n\n let merges_resource = Resource::Remote(RemoteResource::from_pretrained(\n\n LongformerMergesResources::LONGFORMER_BASE_4096,\n\n ));\n\n let config_path = config_resource.get_local_path()?;\n\n let vocab_path = vocab_resource.get_local_path()?;\n\n let merges_path = merges_resource.get_local_path()?;\n\n\n\n // Set-up model\n\n let device = Device::Cpu;\n\n let vs = nn::VarStore::new(device);\n\n let tokenizer = RobertaTokenizer::from_file(\n\n vocab_path.to_str().unwrap(),\n", "file_path": "tests/longformer.rs", "rank": 46, "score": 103767.19654537368 }, { "content": "#[test]\n\nfn mobilebert_for_multiple_choice() -> anyhow::Result<()> {\n\n // Resources paths\n\n let config_resource = Resource::Remote(RemoteResource::from_pretrained(\n\n MobileBertConfigResources::MOBILEBERT_UNCASED,\n\n ));\n\n let vocab_resource = Resource::Remote(RemoteResource::from_pretrained(\n\n MobileBertVocabResources::MOBILEBERT_UNCASED,\n\n ));\n\n let config_path = config_resource.get_local_path()?;\n\n let vocab_path = vocab_resource.get_local_path()?;\n\n\n\n // Set-up model\n\n let device = Device::cuda_if_available();\n\n let vs = nn::VarStore::new(device);\n\n let tokenizer = BertTokenizer::from_file(vocab_path.to_str().unwrap(), true, true)?;\n\n let config = MobileBertConfig::from_file(config_path);\n\n let model = MobileBertForMultipleChoice::new(&vs.root(), &config);\n\n\n\n // Define input\n\n let prompt = \"In Italy, pizza served in formal settings, such as at a restaurant, is presented unsliced.\";\n", "file_path": "tests/mobilebert.rs", "rank": 47, "score": 103767.19654537368 }, { "content": "/// # (Download) the resource and return a path to its local path\n\n/// This function will download remote resource to their local path if they do not exist yet.\n\n/// Then for both `LocalResource` and `RemoteResource`, it will the local path to the resource.\n\n/// For `LocalResource` only the resource path is returned.\n\n///\n\n/// # Arguments\n\n///\n\n/// * `resource` - Pointer to the `&Resource` to optionally download and get the local path.\n\n///\n\n/// # Returns\n\n///\n\n/// * `&PathBuf` Local path for the resource\n\n///\n\n/// # Example\n\n///\n\n/// ```no_run\n\n/// use rust_bert::resources::{RemoteResource, Resource};\n\n/// let model_resource = Resource::Remote(RemoteResource::from_pretrained((\n\n/// \"distilbert-sst2/model.ot\",\n\n/// \"https://huggingface.co/distilbert-base-uncased-finetuned-sst-2-english/resolve/main/rust_model.ot\",\n\n/// )));\n\n/// let local_path = model_resource.get_local_path();\n\n/// ```\n\npub fn download_resource(resource: &Resource) -> Result<PathBuf, RustBertError> {\n\n resource.get_local_path()\n\n}\n", "file_path": "src/common/resources.rs", "rank": 48, "score": 102134.27305125893 }, { "content": "#[test]\n\nfn bert_pre_trained_ner() -> anyhow::Result<()> {\n\n // Set-up model\n\n let ner_model = NERModel::new(Default::default())?;\n\n\n\n // Define input\n\n let input = [\n\n \"My name is Amy. I live in Paris.\",\n\n \"Paris is a city in France.\",\n\n ];\n\n\n\n // Run model\n\n let output = ner_model.predict(&input);\n\n\n\n assert_eq!(output.len(), 2);\n\n assert_eq!(output[0].len(), 2);\n\n assert_eq!(output[1].len(), 2);\n\n\n\n assert_eq!(output[0][0].word, \"Amy\");\n\n assert!((output[0][0].score - 0.9986).abs() < 1e-4);\n\n assert_eq!(output[0][0].label, \"I-PER\");\n", "file_path": "tests/bert.rs", "rank": 49, "score": 100919.82291144322 }, { "content": "#[test]\n\n#[cfg_attr(not(feature = \"all-tests\"), ignore)]\n\nfn dialogpt_multiple_multi_turn_conversation() -> anyhow::Result<()> {\n\n // Set-up conversation model\n\n let conversation_config = ConversationConfig {\n\n do_sample: false,\n\n device: Device::Cpu,\n\n ..Default::default()\n\n };\n\n let conversation_model = ConversationModel::new(conversation_config)?;\n\n\n\n // Set-up conversation manager and add a conversation\n\n let mut conversation_manager = ConversationManager::new();\n\n let conversation_1_id =\n\n conversation_manager.create(\"Going to the movies tonight - any suggestions?\");\n\n let conversation_2_id = conversation_manager.create(\"What's the last book you have read?\");\n\n\n\n // Turn 1\n\n let output = conversation_model.generate_responses(&mut conversation_manager);\n\n assert_eq!(output.len(), 2);\n\n assert_eq!(output.get(&conversation_1_id).unwrap(), &\"The Big Lebowski\");\n\n assert_eq!(\n", "file_path": "tests/gpt2.rs", "rank": 50, "score": 98219.54039467673 }, { "content": "#[test]\n\n#[cfg_attr(not(feature = \"all-tests\"), ignore)]\n\nfn dialogpt_multiple_multi_turn_conversation_with_truncation() -> anyhow::Result<()> {\n\n // Set-up conversation model\n\n let conversation_config = ConversationConfig {\n\n max_length: 36,\n\n min_length_for_response: 24,\n\n do_sample: false,\n\n device: Device::Cpu,\n\n ..Default::default()\n\n };\n\n let conversation_model = ConversationModel::new(conversation_config)?;\n\n\n\n // Set-up conversation manager and add a conversation\n\n let mut conversation_manager = ConversationManager::new();\n\n let conversation_1_id =\n\n conversation_manager.create(\"Going to the movies tonight - any suggestions?\");\n\n let conversation_2_id = conversation_manager.create(\"Hello how are you?\");\n\n\n\n // Turn 1\n\n let output = conversation_model.generate_responses(&mut conversation_manager);\n\n assert_eq!(output.len(), 2);\n", "file_path": "tests/gpt2.rs", "rank": 51, "score": 95718.01185951702 }, { "content": "#[test]\n\nfn gpt2_generation_beam_search_multiple_prompts_with_padding() -> anyhow::Result<()> {\n\n // Resources definition\n\n let config_resource =\n\n Resource::Remote(RemoteResource::from_pretrained(Gpt2ConfigResources::GPT2));\n\n let vocab_resource =\n\n Resource::Remote(RemoteResource::from_pretrained(Gpt2VocabResources::GPT2));\n\n let merges_resource =\n\n Resource::Remote(RemoteResource::from_pretrained(Gpt2MergesResources::GPT2));\n\n let model_resource =\n\n Resource::Remote(RemoteResource::from_pretrained(Gpt2ModelResources::GPT2));\n\n\n\n let generate_config = TextGenerationConfig {\n\n model_type: ModelType::GPT2,\n\n model_resource,\n\n config_resource,\n\n vocab_resource,\n\n merges_resource,\n\n max_length: 20,\n\n do_sample: false,\n\n num_beams: 5,\n", "file_path": "tests/gpt2.rs", "rank": 52, "score": 93375.0083904799 }, { "content": "#[test]\n\n#[cfg_attr(not(feature = \"all-tests\"), ignore)]\n\nfn dialogpt_multiple_multi_turn_conversation_with_conversation_deletion() -> anyhow::Result<()> {\n\n // Set-up conversation model\n\n let conversation_config = ConversationConfig {\n\n do_sample: false,\n\n device: Device::Cpu,\n\n ..Default::default()\n\n };\n\n let conversation_model = ConversationModel::new(conversation_config)?;\n\n\n\n // Set-up conversation manager and add a conversation\n\n let mut conversation_manager = ConversationManager::new();\n\n let conversation_1_id =\n\n conversation_manager.create(\"Going to the movies tonight - any suggestions?\");\n\n let conversation_2_id = conversation_manager.create(\"What's the last book you have read?\");\n\n\n\n // Turn 1\n\n let output = conversation_model.generate_responses(&mut conversation_manager);\n\n assert_eq!(output.len(), 2);\n\n assert_eq!(output.get(&conversation_1_id).unwrap(), &\"The Big Lebowski\");\n\n assert_eq!(\n", "file_path": "tests/gpt2.rs", "rank": 53, "score": 93375.0083904799 }, { "content": "#[test]\n\nfn gpt2_diverse_beam_search_multiple_prompts_with_padding() -> anyhow::Result<()> {\n\n // Resources definition\n\n let config_resource =\n\n Resource::Remote(RemoteResource::from_pretrained(Gpt2ConfigResources::GPT2));\n\n let vocab_resource =\n\n Resource::Remote(RemoteResource::from_pretrained(Gpt2VocabResources::GPT2));\n\n let merges_resource =\n\n Resource::Remote(RemoteResource::from_pretrained(Gpt2MergesResources::GPT2));\n\n let model_resource =\n\n Resource::Remote(RemoteResource::from_pretrained(Gpt2ModelResources::GPT2));\n\n\n\n let generate_config = TextGenerationConfig {\n\n model_type: ModelType::GPT2,\n\n model_resource,\n\n config_resource,\n\n vocab_resource,\n\n merges_resource,\n\n min_length: 10,\n\n max_length: 20,\n\n do_sample: false,\n", "file_path": "tests/gpt2.rs", "rank": 54, "score": 93375.0083904799 }, { "content": "#[test]\n\nfn gpt2_generation_beam_search_multiple_prompts_without_padding() -> anyhow::Result<()> {\n\n // Resources definition\n\n let config_resource =\n\n Resource::Remote(RemoteResource::from_pretrained(Gpt2ConfigResources::GPT2));\n\n let vocab_resource =\n\n Resource::Remote(RemoteResource::from_pretrained(Gpt2VocabResources::GPT2));\n\n let merges_resource =\n\n Resource::Remote(RemoteResource::from_pretrained(Gpt2MergesResources::GPT2));\n\n let model_resource =\n\n Resource::Remote(RemoteResource::from_pretrained(Gpt2ModelResources::GPT2));\n\n\n\n let generate_config = TextGenerationConfig {\n\n model_type: ModelType::GPT2,\n\n model_resource,\n\n config_resource,\n\n vocab_resource,\n\n merges_resource,\n\n max_length: 20,\n\n do_sample: false,\n\n num_beams: 5,\n", "file_path": "tests/gpt2.rs", "rank": 55, "score": 91175.92388661133 }, { "content": "#[test]\n\nfn openai_gpt_generation_beam_search_multiple_prompts_with_padding() -> anyhow::Result<()> {\n\n // Resources paths\n\n let config_resource = Resource::Remote(RemoteResource::from_pretrained(\n\n OpenAiGptConfigResources::GPT,\n\n ));\n\n let vocab_resource = Resource::Remote(RemoteResource::from_pretrained(\n\n OpenAiGptVocabResources::GPT,\n\n ));\n\n let merges_resource = Resource::Remote(RemoteResource::from_pretrained(\n\n OpenAiGptMergesResources::GPT,\n\n ));\n\n let model_resource = Resource::Remote(RemoteResource::from_pretrained(\n\n OpenAiGptModelResources::GPT,\n\n ));\n\n\n\n // Set-up model\n\n let generate_config = TextGenerationConfig {\n\n model_type: ModelType::OpenAiGpt,\n\n model_resource,\n\n config_resource,\n", "file_path": "tests/openai_gpt.rs", "rank": 56, "score": 89107.8931390344 }, { "content": "#[test]\n\nfn openai_gpt_generation_beam_search_multiple_prompts_without_padding() -> anyhow::Result<()> {\n\n // Resources paths\n\n let config_resource = Resource::Remote(RemoteResource::from_pretrained(\n\n OpenAiGptConfigResources::GPT,\n\n ));\n\n let vocab_resource = Resource::Remote(RemoteResource::from_pretrained(\n\n OpenAiGptVocabResources::GPT,\n\n ));\n\n let merges_resource = Resource::Remote(RemoteResource::from_pretrained(\n\n OpenAiGptMergesResources::GPT,\n\n ));\n\n let model_resource = Resource::Remote(RemoteResource::from_pretrained(\n\n OpenAiGptModelResources::GPT,\n\n ));\n\n\n\n // Set-up model\n\n let generate_config = TextGenerationConfig {\n\n model_type: ModelType::OpenAiGpt,\n\n model_resource,\n\n config_resource,\n", "file_path": "tests/openai_gpt.rs", "rank": 57, "score": 87159.53996605102 }, { "content": "#[derive(Debug, Deserialize)]\n\nstruct Record {\n\n sentence: String,\n\n label: i8,\n\n}\n\n\n", "file_path": "benches/sst2_benchmark.rs", "rank": 58, "score": 79566.33195776751 }, { "content": "#[derive(Debug, Deserialize)]\n\nstruct Record {\n\n sentence: String,\n\n label: i8,\n\n}\n\n\n", "file_path": "examples/sentiment_analysis_sst2.rs", "rank": 59, "score": 77759.60354319964 }, { "content": "#[derive(Debug)]\n\nstruct InputFeature {\n\n /// Encoded input ids\n\n input_ids: Vec<i64>,\n\n /// Offsets reference to the original string\n\n offsets: Vec<Option<Offset>>,\n\n /// Token category (mask)\n\n mask: Vec<Mask>,\n\n /// per-token flag indicating if this feature carries the output label for this token\n\n reference_feature: Vec<bool>,\n\n /// Reference example index (long inputs may be broken into multiple input features)\n\n example_index: usize,\n\n}\n\n\n", "file_path": "src/pipelines/token_classification.rs", "rank": 60, "score": 76088.92376168953 }, { "content": "#[derive(Debug)]\n\nstruct QaFeature {\n\n pub input_ids: Vec<i64>,\n\n pub offsets: Vec<Option<Offset>>,\n\n pub p_mask: Vec<i8>,\n\n pub example_index: i64,\n\n}\n\n\n\n#[derive(Debug, Clone)]\n\n/// # Output for Question Answering\n\npub struct Answer {\n\n /// Confidence score\n\n pub score: f64,\n\n /// Start position of answer span\n\n pub start: usize,\n\n /// End position of answer span\n\n pub end: usize,\n\n /// Answer span\n\n pub answer: String,\n\n}\n\n\n\nimpl PartialEq for Answer {\n\n fn eq(&self, other: &Self) -> bool {\n\n (self.start == other.start) && (self.end == other.end) && (self.answer == other.answer)\n\n }\n\n}\n\n\n", "file_path": "src/pipelines/question_answering.rs", "rank": 61, "score": 76088.92376168953 }, { "content": "#[derive(Debug)]\n\nstruct BeamHypotheses {\n\n max_length: i64,\n\n length_penalty: f64,\n\n early_stopping: bool,\n\n num_beams: i64,\n\n beams: Vec<(f64, Tensor)>,\n\n worst_score: f64,\n\n}\n\n\n\nimpl Clone for BeamHypotheses {\n\n fn clone(&self) -> Self {\n\n BeamHypotheses {\n\n max_length: self.max_length,\n\n length_penalty: self.length_penalty,\n\n early_stopping: self.early_stopping,\n\n num_beams: self.num_beams,\n\n beams: self\n\n .beams\n\n .iter()\n\n .map(|(score, tensor)| (*score, tensor.copy()))\n", "file_path": "src/pipelines/generation_utils.rs", "rank": 62, "score": 76088.92376168953 }, { "content": "struct PaddedInput {\n\n input_ids: Option<Tensor>,\n\n position_ids: Option<Tensor>,\n\n inputs_embeds: Option<Tensor>,\n\n attention_mask: Option<Tensor>,\n\n token_type_ids: Option<Tensor>,\n\n}\n\n\n\n/// # LongformerModel Base model\n\n/// Base architecture for LongformerModel models. Task-specific models will be built from this common base model\n\n/// It is made of the following blocks:\n\n/// - `embeddings`: LongformerEmbeddings containing word, position and segment id embeddings\n\n/// - `encoder`: LongformerEncoder\n\n/// - `pooler`: Optional pooling layer extracting the representation of the first token for each batch item\n\npub struct LongformerModel {\n\n embeddings: LongformerEmbeddings,\n\n encoder: LongformerEncoder,\n\n pooler: Option<LongformerPooler>,\n\n max_attention_window: i64,\n\n pad_token_id: i64,\n", "file_path": "src/longformer/longformer_model.rs", "rank": 63, "score": 76088.92376168953 }, { "content": "struct TranslationResources {\n\n model_type: ModelType,\n\n model_resource: Resource,\n\n config_resource: Resource,\n\n vocab_resource: Resource,\n\n merges_resource: Resource,\n\n source_languages: Vec<Language>,\n\n target_languages: Vec<Language>,\n\n}\n\n\n", "file_path": "src/pipelines/translation/translation_builder.rs", "rank": 64, "score": 74539.48327578438 }, { "content": "/// # BertEmbedding trait (for use in BertModel or RoBERTaModel)\n\n/// Defines an interface for the embedding layers in BERT-based models\n\npub trait BertEmbedding {\n\n fn new<'p, P>(p: P, config: &BertConfig) -> Self\n\n where\n\n P: Borrow<nn::Path<'p>>;\n\n\n\n fn forward_t(\n\n &self,\n\n input_ids: Option<&Tensor>,\n\n token_type_ids: Option<&Tensor>,\n\n position_ids: Option<&Tensor>,\n\n input_embeds: Option<&Tensor>,\n\n train: bool,\n\n ) -> Result<Tensor, RustBertError>;\n\n}\n\n\n\n#[derive(Debug)]\n\n/// # BertEmbeddings implementation for BERT model\n\n/// Implementation of the `BertEmbedding` trait for BERT models\n\npub struct BertEmbeddings {\n\n word_embeddings: nn::Embedding,\n", "file_path": "src/bert/embeddings.rs", "rank": 65, "score": 72514.30392265666 }, { "content": "fn squad_forward_pass(\n\n iters: u64,\n\n model: &QuestionAnsweringModel,\n\n squad_data: &[QaInput],\n\n) -> Duration {\n\n let mut duration = Duration::new(0, 0);\n\n let batch_size = BATCH_SIZE;\n\n let mut output = vec![];\n\n for _i in 0..iters {\n\n let start = Instant::now();\n\n for batch in squad_data.chunks(batch_size) {\n\n output.push(model.predict(batch, 1, 64));\n\n }\n\n duration = duration.checked_add(start.elapsed()).unwrap();\n\n }\n\n duration\n\n}\n\n\n", "file_path": "benches/squad_benchmark.rs", "rank": 66, "score": 68559.58193653589 }, { "content": "fn _shift_tokens_right(\n\n input_ids: &Tensor,\n\n pad_token_id: i64,\n\n decoder_start_token_id: i64,\n\n) -> Tensor {\n\n let input_ids_length = input_ids.size()[1];\n\n let mut shifted_input_ids = Tensor::zeros(\n\n input_ids.size().as_slice(),\n\n (input_ids.kind(), input_ids.device()),\n\n );\n\n let _ = shifted_input_ids\n\n .slice(1, 1, input_ids_length, 1)\n\n .copy_(&input_ids.slice(1, 0, input_ids_length - 1, 1));\n\n\n\n let _ = shifted_input_ids.select(1, 0).fill_(decoder_start_token_id);\n\n let _ = shifted_input_ids.masked_fill_(&shifted_input_ids.eq(-100), pad_token_id);\n\n\n\n shifted_input_ids\n\n}\n\n\n", "file_path": "src/pegasus/pegasus_model.rs", "rank": 67, "score": 67021.46864779457 }, { "content": "fn _shift_tokens_right(\n\n input_ids: &Tensor,\n\n pad_token_id: i64,\n\n decoder_start_token_id: i64,\n\n) -> Tensor {\n\n let shifted_input_ids = Tensor::zeros(\n\n input_ids.size().as_slice(),\n\n (Kind::Int64, input_ids.device()),\n\n );\n\n let _ = shifted_input_ids.select(1, 0).fill_(decoder_start_token_id);\n\n let _ = shifted_input_ids\n\n .slice(1, 1, *shifted_input_ids.size().last().unwrap(), 1)\n\n .copy_(&input_ids.slice(1, 0, *input_ids.size().last().unwrap() - 1, 1));\n\n shifted_input_ids.masked_fill(&shifted_input_ids.eq(-100), pad_token_id)\n\n}\n\n\n\n/// # M2M100 Base model\n\n/// Base architecture for M2M100 model. Usually complemented with a task-specific head, such as a language model head.\n\n/// It is made of the following blocks:\n\n/// - `encoder`: `M2M100Encoder` (transformer) made of a vector of encoding layers\n", "file_path": "src/m2m_100/m2m_100_model.rs", "rank": 68, "score": 67021.46864779457 }, { "content": "fn main() -> anyhow::Result<()> {\n\n let config = ConversationConfig {\n\n do_sample: false,\n\n num_beams: 3,\n\n ..Default::default()\n\n };\n\n let conversation_model = ConversationModel::new(config)?;\n\n let mut conversation_manager = ConversationManager::new();\n\n\n\n let conversation_1_id =\n\n conversation_manager.create(\"Going to the movies tonight - any suggestions?\");\n\n let _conversation_2_id = conversation_manager.create(\"What's the last book you have read?\");\n\n\n\n let output = conversation_model.generate_responses(&mut conversation_manager);\n\n\n\n println!(\"{:?}\", output);\n\n\n\n let _ = conversation_manager\n\n .get(&conversation_1_id)\n\n .unwrap()\n", "file_path": "examples/conversation.rs", "rank": 69, "score": 65821.66049753517 }, { "content": "// #[cfg_attr(not(feature = \"all-tests\"), ignore)]\n\nfn test_translation() -> anyhow::Result<()> {\n\n // Set-up translation model\n\n let model_resource = Resource::Remote(RemoteResource::from_pretrained(\n\n MarianModelResources::ENGLISH2ROMANCE,\n\n ));\n\n let config_resource = Resource::Remote(RemoteResource::from_pretrained(\n\n MarianConfigResources::ENGLISH2ROMANCE,\n\n ));\n\n let vocab_resource = Resource::Remote(RemoteResource::from_pretrained(\n\n MarianVocabResources::ENGLISH2ROMANCE,\n\n ));\n\n let merges_resource = Resource::Remote(RemoteResource::from_pretrained(\n\n MarianSpmResources::ENGLISH2ROMANCE,\n\n ));\n\n\n\n let source_languages = MarianSourceLanguages::ENGLISH2ROMANCE;\n\n let target_languages = MarianTargetLanguages::ENGLISH2ROMANCE;\n\n\n\n let translation_config = TranslationConfig::new(\n\n ModelType::Marian,\n", "file_path": "tests/marian.rs", "rank": 70, "score": 64163.19423403684 }, { "content": "fn main() -> anyhow::Result<()> {\n\n // Set-up Question Answering model\n\n let qa_model = QuestionAnsweringModel::new(Default::default())?;\n\n\n\n // Define input\n\n let question_1 = String::from(\"Where does Amy live ?\");\n\n let context_1 = String::from(\"Amy lives in Amsterdam\");\n\n let question_2 = String::from(\"Where does Eric live\");\n\n let context_2 = String::from(\"While Amy lives in Amsterdam, Eric is in The Hague.\");\n\n let qa_input_1 = QaInput {\n\n question: question_1,\n\n context: context_1,\n\n };\n\n let qa_input_2 = QaInput {\n\n question: question_2,\n\n context: context_2,\n\n };\n\n\n\n // Get answer\n\n let answers = qa_model.predict(&[qa_input_1, qa_input_2], 1, 32);\n\n println!(\"{:?}\", answers);\n\n Ok(())\n\n}\n", "file_path": "examples/question_answering.rs", "rank": 71, "score": 64163.19423403684 }, { "content": "fn main() -> anyhow::Result<()> {\n\n // let summarization_model = SummarizationModel::new(Default::default())?;\n\n\n\n let config_resource =\n\n Resource::Remote(RemoteResource::from_pretrained(T5ConfigResources::T5_SMALL));\n\n let vocab_resource =\n\n Resource::Remote(RemoteResource::from_pretrained(T5VocabResources::T5_SMALL));\n\n let weights_resource =\n\n Resource::Remote(RemoteResource::from_pretrained(T5ModelResources::T5_SMALL));\n\n let summarization_config = SummarizationConfig::new(\n\n ModelType::T5,\n\n weights_resource,\n\n config_resource,\n\n vocab_resource.clone(),\n\n vocab_resource,\n\n );\n\n let summarization_model = SummarizationModel::new(summarization_config)?;\n\n\n\n let input = [\"In findings published Tuesday in Cornell University's arXiv by a team of scientists \\\n\nfrom the University of Montreal and a separate report published Wednesday in Nature Astronomy by a team \\\n", "file_path": "examples/summarization_t5.rs", "rank": 72, "score": 64163.19423403684 }, { "content": "fn main() -> anyhow::Result<()> {\n\n let model_resource =\n\n Resource::Remote(RemoteResource::from_pretrained(T5ModelResources::T5_BASE));\n\n let config_resource =\n\n Resource::Remote(RemoteResource::from_pretrained(T5ConfigResources::T5_BASE));\n\n let vocab_resource =\n\n Resource::Remote(RemoteResource::from_pretrained(T5VocabResources::T5_BASE));\n\n let merges_resource =\n\n Resource::Remote(RemoteResource::from_pretrained(T5VocabResources::T5_BASE));\n\n\n\n let source_languages = [\n\n Language::English,\n\n Language::French,\n\n Language::German,\n\n Language::Romanian,\n\n ];\n\n let target_languages = [\n\n Language::English,\n\n Language::French,\n\n Language::German,\n", "file_path": "examples/translation_t5.rs", "rank": 73, "score": 64163.19423403684 }, { "content": "fn main() -> anyhow::Result<()> {\n\n let config_resource = Resource::Remote(RemoteResource::from_pretrained(\n\n ProphetNetConfigResources::PROPHETNET_LARGE_CNN_DM,\n\n ));\n\n let vocab_resource = Resource::Remote(RemoteResource::from_pretrained(\n\n ProphetNetVocabResources::PROPHETNET_LARGE_CNN_DM,\n\n ));\n\n let weights_resource = Resource::Remote(RemoteResource::from_pretrained(\n\n ProphetNetModelResources::PROPHETNET_LARGE_CNN_DM,\n\n ));\n\n\n\n let summarization_config = SummarizationConfig {\n\n model_type: ModelType::ProphetNet,\n\n model_resource: weights_resource,\n\n config_resource,\n\n vocab_resource: vocab_resource.clone(),\n\n merges_resource: vocab_resource,\n\n length_penalty: 1.2,\n\n num_beams: 4,\n\n no_repeat_ngram_size: 3,\n", "file_path": "examples/summarization_prophetnet.rs", "rank": 74, "score": 64163.19423403684 }, { "content": "fn main() -> anyhow::Result<()> {\n\n let model_resource = Resource::Remote(RemoteResource::from_pretrained(\n\n MBartModelResources::MBART50_MANY_TO_MANY,\n\n ));\n\n let config_resource = Resource::Remote(RemoteResource::from_pretrained(\n\n MBartConfigResources::MBART50_MANY_TO_MANY,\n\n ));\n\n let vocab_resource = Resource::Remote(RemoteResource::from_pretrained(\n\n MBartVocabResources::MBART50_MANY_TO_MANY,\n\n ));\n\n let merges_resource = Resource::Remote(RemoteResource::from_pretrained(\n\n MBartVocabResources::MBART50_MANY_TO_MANY,\n\n ));\n\n\n\n let source_languages = MBartSourceLanguages::MBART50_MANY_TO_MANY;\n\n let target_languages = MBartTargetLanguages::MBART50_MANY_TO_MANY;\n\n\n\n let translation_config = TranslationConfig::new(\n\n ModelType::MBart,\n\n model_resource,\n", "file_path": "examples/translation_mbart.rs", "rank": 75, "score": 64163.19423403684 }, { "content": "fn main() -> anyhow::Result<()> {\n\n let config_resource = Resource::Remote(RemoteResource::from_pretrained(\n\n PegasusConfigResources::CNN_DAILYMAIL,\n\n ));\n\n let vocab_resource = Resource::Remote(RemoteResource::from_pretrained(\n\n PegasusVocabResources::CNN_DAILYMAIL,\n\n ));\n\n let weights_resource = Resource::Remote(RemoteResource::from_pretrained(\n\n PegasusModelResources::CNN_DAILYMAIL,\n\n ));\n\n\n\n let summarization_config = SummarizationConfig {\n\n model_type: ModelType::Pegasus,\n\n model_resource: weights_resource,\n\n config_resource,\n\n vocab_resource: vocab_resource.clone(),\n\n merges_resource: vocab_resource,\n\n length_penalty: 1.0,\n\n num_beams: 4,\n\n no_repeat_ngram_size: 3,\n", "file_path": "examples/summarization_pegasus.rs", "rank": 76, "score": 64163.19423403684 }, { "content": "#[test]\n\nfn electra_discriminator() -> anyhow::Result<()> {\n\n // Resources paths\n\n let config_resource = Resource::Remote(RemoteResource::from_pretrained(\n\n ElectraConfigResources::BASE_DISCRIMINATOR,\n\n ));\n\n let vocab_resource = Resource::Remote(RemoteResource::from_pretrained(\n\n ElectraVocabResources::BASE_DISCRIMINATOR,\n\n ));\n\n let weights_resource = Resource::Remote(RemoteResource::from_pretrained(\n\n ElectraModelResources::BASE_DISCRIMINATOR,\n\n ));\n\n let config_path = config_resource.get_local_path()?;\n\n let vocab_path = vocab_resource.get_local_path()?;\n\n let weights_path = weights_resource.get_local_path()?;\n\n\n\n // Set-up masked LM model\n\n let device = Device::Cpu;\n\n let mut vs = nn::VarStore::new(device);\n\n let tokenizer: BertTokenizer =\n\n BertTokenizer::from_file(vocab_path.to_str().unwrap(), true, true)?;\n", "file_path": "tests/electra.rs", "rank": 77, "score": 64163.19423403684 }, { "content": "fn main() -> anyhow::Result<()> {\n\n // Set-up model\n\n let sequence_classification_model = SequenceClassificationModel::new(Default::default())?;\n\n\n\n // Define input\n\n let input = [\n\n \"Probably my all-time favorite movie, a story of selflessness, sacrifice and dedication to a noble cause, but it's not preachy or boring.\",\n\n \"This film tried to be too many things all at once: stinging political satire, Hollywood blockbuster, sappy romantic comedy, family values promo...\",\n\n \"If you like original gut wrenching laughter you will like this movie. If you are young or old then you will love this movie, hell even my mom liked it.\",\n\n ];\n\n\n\n // Run model\n\n let output = sequence_classification_model.predict(&input);\n\n for label in output {\n\n println!(\"{:?}\", label);\n\n }\n\n\n\n Ok(())\n\n}\n", "file_path": "examples/sequence_classification.rs", "rank": 78, "score": 64163.19423403684 }, { "content": "#[test]\n\nfn mbart_translation() -> anyhow::Result<()> {\n\n let model = TranslationModelBuilder::new()\n\n .with_device(Device::cuda_if_available())\n\n .with_model_type(ModelType::MBart)\n\n .create_model()?;\n\n\n\n let source_sentence = \"This sentence will be translated in multiple languages.\";\n\n\n\n let mut outputs = Vec::new();\n\n outputs.extend(model.translate([source_sentence], Language::English, Language::French)?);\n\n outputs.extend(model.translate([source_sentence], Language::English, Language::Spanish)?);\n\n outputs.extend(model.translate([source_sentence], Language::English, Language::Hindi)?);\n\n\n\n assert_eq!(outputs.len(), 3);\n\n assert_eq!(\n\n outputs[0],\n\n \" Cette phrase sera traduite en plusieurs langues.\"\n\n );\n\n assert_eq!(\n\n outputs[1],\n\n \" Esta frase será traducida en múltiples idiomas.\"\n\n );\n\n assert_eq!(outputs[2], \" यह वाक्य कई भाषाओं में अनुवाद किया जाएगा.\");\n\n\n\n Ok(())\n\n}\n", "file_path": "tests/mbart.rs", "rank": 79, "score": 64163.19423403684 }, { "content": "fn main() -> anyhow::Result<()> {\n\n let config_resource = Resource::Remote(RemoteResource::from_pretrained(\n\n BartConfigResources::DISTILBART_CNN_6_6,\n\n ));\n\n let vocab_resource = Resource::Remote(RemoteResource::from_pretrained(\n\n BartVocabResources::DISTILBART_CNN_6_6,\n\n ));\n\n let merges_resource = Resource::Remote(RemoteResource::from_pretrained(\n\n BartMergesResources::DISTILBART_CNN_6_6,\n\n ));\n\n let model_resource = Resource::Remote(RemoteResource::from_pretrained(\n\n BartModelResources::DISTILBART_CNN_6_6,\n\n ));\n\n\n\n let summarization_config = SummarizationConfig {\n\n model_resource,\n\n config_resource,\n\n vocab_resource,\n\n merges_resource,\n\n num_beams: 1,\n", "file_path": "examples/summarization_bart.rs", "rank": 80, "score": 64163.19423403684 }, { "content": "fn main() -> anyhow::Result<()> {\n\n // Set-up model\n\n let generate_config = TextGenerationConfig {\n\n model_type: ModelType::GPT2,\n\n max_length: 30,\n\n do_sample: false,\n\n num_beams: 1,\n\n temperature: 1.0,\n\n num_return_sequences: 1,\n\n ..Default::default()\n\n };\n\n let model = TextGenerationModel::new(generate_config)?;\n\n\n\n let input_context = \"The dog\";\n\n // let second_input_context = \"The cat was\";\n\n let output = model.generate(&[input_context], None);\n\n\n\n for sentence in output {\n\n println!(\"{:?}\", sentence);\n\n }\n\n Ok(())\n\n}\n", "file_path": "examples/generation_gpt2.rs", "rank": 81, "score": 64163.19423403684 }, { "content": "fn main() -> anyhow::Result<()> {\n\n // Set-up model\n\n // Resources paths\n\n let config_resource = Resource::Remote(RemoteResource::from_pretrained(\n\n XLNetConfigResources::XLNET_BASE_CASED,\n\n ));\n\n let vocab_resource = Resource::Remote(RemoteResource::from_pretrained(\n\n XLNetVocabResources::XLNET_BASE_CASED,\n\n ));\n\n let merges_resource = Resource::Remote(RemoteResource::from_pretrained(\n\n XLNetVocabResources::XLNET_BASE_CASED,\n\n ));\n\n let model_resource = Resource::Remote(RemoteResource::from_pretrained(\n\n XLNetModelResources::XLNET_BASE_CASED,\n\n ));\n\n\n\n let generate_config = TextGenerationConfig {\n\n model_type: ModelType::XLNet,\n\n model_resource,\n\n config_resource,\n", "file_path": "examples/generation_xlnet.rs", "rank": 82, "score": 64163.19423403684 }, { "content": "#[test]\n\nfn m2m100_translation() -> anyhow::Result<()> {\n\n let model_resource = Resource::Remote(RemoteResource::from_pretrained(\n\n M2M100ModelResources::M2M100_418M,\n\n ));\n\n let config_resource = Resource::Remote(RemoteResource::from_pretrained(\n\n M2M100ConfigResources::M2M100_418M,\n\n ));\n\n let vocab_resource = Resource::Remote(RemoteResource::from_pretrained(\n\n M2M100VocabResources::M2M100_418M,\n\n ));\n\n let merges_resource = Resource::Remote(RemoteResource::from_pretrained(\n\n M2M100MergesResources::M2M100_418M,\n\n ));\n\n\n\n let source_languages = M2M100SourceLanguages::M2M100_418M;\n\n let target_languages = M2M100TargetLanguages::M2M100_418M;\n\n\n\n let translation_config = TranslationConfig::new(\n\n ModelType::M2M100,\n\n model_resource,\n", "file_path": "tests/m2m100.rs", "rank": 83, "score": 64163.19423403684 }, { "content": "fn main() -> anyhow::Result<()> {\n\n let model_resource = Resource::Remote(RemoteResource::from_pretrained(\n\n MarianModelResources::ENGLISH2CHINESE,\n\n ));\n\n let config_resource = Resource::Remote(RemoteResource::from_pretrained(\n\n MarianConfigResources::ENGLISH2CHINESE,\n\n ));\n\n let vocab_resource = Resource::Remote(RemoteResource::from_pretrained(\n\n MarianVocabResources::ENGLISH2CHINESE,\n\n ));\n\n let merges_resource = Resource::Remote(RemoteResource::from_pretrained(\n\n MarianSpmResources::ENGLISH2CHINESE,\n\n ));\n\n\n\n let source_languages = MarianSourceLanguages::ENGLISH2CHINESE;\n\n let target_languages = MarianTargetLanguages::ENGLISH2CHINESE;\n\n\n\n let translation_config = TranslationConfig::new(\n\n ModelType::Marian,\n\n model_resource,\n", "file_path": "examples/translation_marian.rs", "rank": 84, "score": 64163.19423403684 }, { "content": "fn main() -> anyhow::Result<()> {\n\n let model_resource = Resource::Remote(RemoteResource::from_pretrained(\n\n M2M100ModelResources::M2M100_418M,\n\n ));\n\n let config_resource = Resource::Remote(RemoteResource::from_pretrained(\n\n M2M100ConfigResources::M2M100_418M,\n\n ));\n\n let vocab_resource = Resource::Remote(RemoteResource::from_pretrained(\n\n M2M100VocabResources::M2M100_418M,\n\n ));\n\n let merges_resource = Resource::Remote(RemoteResource::from_pretrained(\n\n M2M100MergesResources::M2M100_418M,\n\n ));\n\n\n\n let source_languages = M2M100SourceLanguages::M2M100_418M;\n\n let target_languages = M2M100TargetLanguages::M2M100_418M;\n\n\n\n let translation_config = TranslationConfig::new(\n\n ModelType::M2M100,\n\n model_resource,\n", "file_path": "examples/translation_m2m100.rs", "rank": 85, "score": 64163.19423403684 }, { "content": "fn main() -> anyhow::Result<()> {\n\n // Set-up classifier\n\n let sentiment_classifier = SentimentModel::new(Default::default())?;\n\n\n\n // Define input\n\n let input = [\n\n \"Probably my all-time favorite movie, a story of selflessness, sacrifice and dedication to a noble cause, but it's not preachy or boring.\",\n\n \"This film tried to be too many things all at once: stinging political satire, Hollywood blockbuster, sappy romantic comedy, family values promo...\",\n\n \"If you like original gut wrenching laughter you will like this movie. If you are young or old then you will love this movie, hell even my mom liked it.\",\n\n ];\n\n\n\n // Run model\n\n let output = sentiment_classifier.predict(&input);\n\n for sentiment in output {\n\n println!(\"{:?}\", sentiment);\n\n }\n\n\n\n Ok(())\n\n}\n", "file_path": "examples/sentiment_analysis.rs", "rank": 86, "score": 64163.19423403684 }, { "content": "fn main() -> anyhow::Result<()> {\n\n // Set-up model\n\n // Resources paths\n\n let config_resource = Resource::Remote(RemoteResource::from_pretrained(\n\n ReformerConfigResources::CRIME_AND_PUNISHMENT,\n\n ));\n\n let vocab_resource = Resource::Remote(RemoteResource::from_pretrained(\n\n ReformerVocabResources::CRIME_AND_PUNISHMENT,\n\n ));\n\n let merges_resource = Resource::Remote(RemoteResource::from_pretrained(\n\n ReformerVocabResources::CRIME_AND_PUNISHMENT,\n\n ));\n\n let model_resource = Resource::Remote(RemoteResource::from_pretrained(\n\n ReformerModelResources::CRIME_AND_PUNISHMENT,\n\n ));\n\n let generate_config = TextGenerationConfig {\n\n model_type: ModelType::Reformer,\n\n model_resource,\n\n config_resource,\n\n vocab_resource,\n", "file_path": "examples/generation_reformer.rs", "rank": 87, "score": 64163.19423403684 }, { "content": "fn main() -> anyhow::Result<()> {\n\n let model = TranslationModelBuilder::new()\n\n .with_device(Device::cuda_if_available())\n\n .with_model_type(ModelType::Marian)\n\n // .with_large_model()\n\n .with_source_languages(vec![Language::English])\n\n .with_target_languages(vec![Language::Spanish])\n\n .create_model()?;\n\n\n\n let input_context_1 = \"This is a sentence to be translated\";\n\n let input_context_2 = \"The dog did not wake up.\";\n\n\n\n let output = model.translate(&[input_context_1, input_context_2], None, Language::Spanish)?;\n\n\n\n for sentence in output {\n\n println!(\"{}\", sentence);\n\n }\n\n Ok(())\n\n}\n", "file_path": "examples/translation_builder.rs", "rank": 88, "score": 64163.19423403684 }, { "content": "fn main() -> anyhow::Result<()> {\n\n // Load a configuration\n\n let config = TokenClassificationConfig::new(\n\n ModelType::Bert,\n\n Resource::Remote(RemoteResource::from_pretrained(\n\n BertModelResources::BERT_NER,\n\n )),\n\n Resource::Remote(RemoteResource::from_pretrained(\n\n BertConfigResources::BERT_NER,\n\n )),\n\n Resource::Remote(RemoteResource::from_pretrained(\n\n BertVocabResources::BERT_NER,\n\n )),\n\n None, //merges resource only relevant with ModelType::Roberta\n\n false, //lowercase\n\n false,\n\n None,\n\n LabelAggregationOption::Mode,\n\n );\n\n\n", "file_path": "examples/token_classification.rs", "rank": 89, "score": 64163.19423403684 }, { "content": "fn _get_cache_directory() -> PathBuf {\n\n match env::var(\"RUSTBERT_CACHE\") {\n\n Ok(value) => PathBuf::from(value),\n\n Err(_) => {\n\n let mut home = dirs::home_dir().unwrap();\n\n home.push(\".cache\");\n\n home.push(\".rustbert\");\n\n home\n\n }\n\n }\n\n}\n\n\n\n#[deprecated(\n\n since = \"0.9.1\",\n\n note = \"Please use `Resource.get_local_path()` instead\"\n\n)]\n", "file_path": "src/common/resources.rs", "rank": 90, "score": 63191.29252260292 }, { "content": "fn create_summarization_model() -> SummarizationModel {\n\n let config = SummarizationConfig {\n\n device: Device::cuda_if_available(),\n\n ..Default::default()\n\n };\n\n SummarizationModel::new(config).unwrap()\n\n}\n\n\n", "file_path": "benches/summarization_benchmark.rs", "rank": 91, "score": 63191.29252260292 }, { "content": "fn create_translation_model() -> TranslationModel {\n\n let model = TranslationModelBuilder::new()\n\n .with_device(Device::cuda_if_available())\n\n .with_model_type(ModelType::Marian)\n\n // .with_model_type(ModelType::T5)\n\n .with_source_languages(vec![Language::English])\n\n .with_target_languages(vec![Language::French])\n\n .create_model()\n\n .unwrap();\n\n\n\n // let model_resource = Resource::Local(LocalResource {\n\n // local_path: \"E:/Coding/cache/rustbert/marian-mt-en-es/model.ot\".into(),\n\n // });\n\n // let config_resource = Resource::Local(LocalResource {\n\n // local_path: \"E:/Coding/cache/rustbert/marian-mt-en-es/config.json\".into(),\n\n // });\n\n // let vocab_resource = Resource::Local(LocalResource {\n\n // local_path: \"E:/Coding/cache/rustbert/marian-mt-en-es/vocab.json\".into(),\n\n // });\n\n // let merges_resource = Resource::Local(LocalResource {\n", "file_path": "benches/translation_benchmark.rs", "rank": 92, "score": 63191.29252260292 }, { "content": "fn create_sentiment_model() -> SentimentModel {\n\n let config = SequenceClassificationConfig {\n\n device: Device::cuda_if_available(),\n\n ..Default::default()\n\n };\n\n SentimentModel::new(config).unwrap()\n\n}\n\n\n", "file_path": "benches/sst2_benchmark.rs", "rank": 93, "score": 63191.29252260292 }, { "content": "#[test]\n\nfn albert_masked_lm() -> anyhow::Result<()> {\n\n // Resources paths\n\n let config_resource = Resource::Remote(RemoteResource::from_pretrained(\n\n AlbertConfigResources::ALBERT_BASE_V2,\n\n ));\n\n let vocab_resource = Resource::Remote(RemoteResource::from_pretrained(\n\n AlbertVocabResources::ALBERT_BASE_V2,\n\n ));\n\n let weights_resource = Resource::Remote(RemoteResource::from_pretrained(\n\n AlbertModelResources::ALBERT_BASE_V2,\n\n ));\n\n let config_path = config_resource.get_local_path()?;\n\n let vocab_path = vocab_resource.get_local_path()?;\n\n let weights_path = weights_resource.get_local_path()?;\n\n\n\n // Set-up masked LM model\n\n let device = Device::Cpu;\n\n let mut vs = nn::VarStore::new(device);\n\n let tokenizer: AlbertTokenizer =\n\n AlbertTokenizer::from_file(vocab_path.to_str().unwrap(), true, false)?;\n", "file_path": "tests/albert.rs", "rank": 94, "score": 62625.08094529552 }, { "content": "#[test]\n\nfn albert_for_question_answering() -> anyhow::Result<()> {\n\n // Resources paths\n\n let config_resource = Resource::Remote(RemoteResource::from_pretrained(\n\n AlbertConfigResources::ALBERT_BASE_V2,\n\n ));\n\n let vocab_resource = Resource::Remote(RemoteResource::from_pretrained(\n\n AlbertVocabResources::ALBERT_BASE_V2,\n\n ));\n\n let config_path = config_resource.get_local_path()?;\n\n let vocab_path = vocab_resource.get_local_path()?;\n\n\n\n // Set-up model\n\n let device = Device::Cpu;\n\n let vs = nn::VarStore::new(device);\n\n let tokenizer: AlbertTokenizer =\n\n AlbertTokenizer::from_file(vocab_path.to_str().unwrap(), true, false)?;\n\n let mut config = AlbertConfig::from_file(config_path);\n\n config.output_attentions = Some(true);\n\n config.output_hidden_states = Some(true);\n\n let albert_model = AlbertForQuestionAnswering::new(&vs.root(), &config);\n", "file_path": "tests/albert.rs", "rank": 95, "score": 62625.08094529552 }, { "content": "#[test]\n\nfn albert_for_sequence_classification() -> anyhow::Result<()> {\n\n // Resources paths\n\n let config_resource = Resource::Remote(RemoteResource::from_pretrained(\n\n AlbertConfigResources::ALBERT_BASE_V2,\n\n ));\n\n let vocab_resource = Resource::Remote(RemoteResource::from_pretrained(\n\n AlbertVocabResources::ALBERT_BASE_V2,\n\n ));\n\n let config_path = config_resource.get_local_path()?;\n\n let vocab_path = vocab_resource.get_local_path()?;\n\n\n\n // Set-up model\n\n let device = Device::Cpu;\n\n let vs = nn::VarStore::new(device);\n\n let tokenizer: AlbertTokenizer =\n\n AlbertTokenizer::from_file(vocab_path.to_str().unwrap(), true, false)?;\n\n let mut config = AlbertConfig::from_file(config_path);\n\n let mut dummy_label_mapping = HashMap::new();\n\n dummy_label_mapping.insert(0, String::from(\"Positive\"));\n\n dummy_label_mapping.insert(1, String::from(\"Negative\"));\n", "file_path": "tests/albert.rs", "rank": 96, "score": 62625.08094529552 }, { "content": "#[test]\n\nfn albert_for_token_classification() -> anyhow::Result<()> {\n\n // Resources paths\n\n let config_resource = Resource::Remote(RemoteResource::from_pretrained(\n\n AlbertConfigResources::ALBERT_BASE_V2,\n\n ));\n\n let vocab_resource = Resource::Remote(RemoteResource::from_pretrained(\n\n AlbertVocabResources::ALBERT_BASE_V2,\n\n ));\n\n let config_path = config_resource.get_local_path()?;\n\n let vocab_path = vocab_resource.get_local_path()?;\n\n\n\n // Set-up model\n\n let device = Device::Cpu;\n\n let vs = nn::VarStore::new(device);\n\n let tokenizer: AlbertTokenizer =\n\n AlbertTokenizer::from_file(vocab_path.to_str().unwrap(), true, false)?;\n\n let mut config = AlbertConfig::from_file(config_path);\n\n let mut dummy_label_mapping = HashMap::new();\n\n dummy_label_mapping.insert(0, String::from(\"O\"));\n\n dummy_label_mapping.insert(1, String::from(\"LOC\"));\n", "file_path": "tests/albert.rs", "rank": 97, "score": 62625.08094529552 }, { "content": "#[test]\n\nfn bert_masked_lm() -> anyhow::Result<()> {\n\n // Resources paths\n\n let config_resource =\n\n Resource::Remote(RemoteResource::from_pretrained(BertConfigResources::BERT));\n\n let vocab_resource =\n\n Resource::Remote(RemoteResource::from_pretrained(BertVocabResources::BERT));\n\n let weights_resource =\n\n Resource::Remote(RemoteResource::from_pretrained(BertModelResources::BERT));\n\n let config_path = config_resource.get_local_path()?;\n\n let vocab_path = vocab_resource.get_local_path()?;\n\n let weights_path = weights_resource.get_local_path()?;\n\n\n\n // Set-up masked LM model\n\n let device = Device::Cpu;\n\n let mut vs = nn::VarStore::new(device);\n\n let tokenizer: BertTokenizer =\n\n BertTokenizer::from_file(vocab_path.to_str().unwrap(), true, true)?;\n\n let config = BertConfig::from_file(config_path);\n\n let bert_model = BertForMaskedLM::new(&vs.root(), &config);\n\n vs.load(weights_path)?;\n", "file_path": "tests/bert.rs", "rank": 98, "score": 62625.08094529552 }, { "content": "#[test]\n\nfn bert_for_sequence_classification() -> anyhow::Result<()> {\n\n // Resources paths\n\n let config_resource =\n\n Resource::Remote(RemoteResource::from_pretrained(BertConfigResources::BERT));\n\n let vocab_resource =\n\n Resource::Remote(RemoteResource::from_pretrained(BertVocabResources::BERT));\n\n let config_path = config_resource.get_local_path()?;\n\n let vocab_path = vocab_resource.get_local_path()?;\n\n\n\n // Set-up model\n\n let device = Device::Cpu;\n\n let vs = nn::VarStore::new(device);\n\n let tokenizer: BertTokenizer =\n\n BertTokenizer::from_file(vocab_path.to_str().unwrap(), true, true)?;\n\n let mut config = BertConfig::from_file(config_path);\n\n let mut dummy_label_mapping = HashMap::new();\n\n dummy_label_mapping.insert(0, String::from(\"Positive\"));\n\n dummy_label_mapping.insert(1, String::from(\"Negative\"));\n\n dummy_label_mapping.insert(3, String::from(\"Neutral\"));\n\n config.id2label = Some(dummy_label_mapping);\n", "file_path": "tests/bert.rs", "rank": 99, "score": 62625.08094529552 } ]
Rust
src/kernel.rs
Mic92/vmsh
296a09102abece5df0135afb9678261d5a7b6c20
use log::{debug, info}; use nix::sys::mman::ProtFlags; use simple_error::{require_with, try_with, SimpleError}; use std::collections::HashMap; use std::ffi::CStr; use std::mem::{self, size_of}; use std::ops::Range; use vm_memory::remote_mem::process_read_bytes; use crate::guest_mem::{GuestMem, MappedMemory}; use crate::kvm::hypervisor::Hypervisor; use crate::result::Result; pub const LINUX_KERNEL_KASLR_RANGE: Range<usize> = 0xFFFFFFFF80000000..0xFFFFFFFFC0000000; fn find_subsequence(haystack: &[u8], needle: &[u8]) -> Option<usize> { haystack .windows(needle.len()) .position(|window| window == needle) } fn not_printable(byte: u8) -> bool { !(0x20 < byte && byte < 0x7E) } fn round_up(num: usize, align: usize) -> usize { ((num + align - 1) / align) * align } fn find_ksymtab_strings_section(mem: &[u8]) -> Option<Range<usize>> { let idx = find_subsequence(mem, b"init_task")?; let start_offset = mem[..idx] .windows(2) .rev() .position(|b| not_printable(b[0]) && not_printable(b[1]))?; let start = round_up(idx - start_offset, 4); let end_offset = mem[idx..] .windows(2) .position(|b| not_printable(b[0]) && not_printable(b[1]))?; let end = idx + end_offset + 1; Some(start..end) } #[repr(C)] #[derive(Debug)] pub struct kernel_symbol { pub value_offset: libc::c_int, pub name_offset: libc::c_int, pub namespace_offset: libc::c_int, } #[repr(C)] #[derive(Debug)] pub struct kernel_symbol_5_3 { pub value_offset: libc::c_int, pub name_offset: libc::c_int, } #[repr(C)] #[derive(Debug)] pub struct kernel_symbol_4_18 { pub value: libc::c_ulong, pub name: libc::c_ulong, } unsafe fn cast_kernel_sym(mem: &[u8]) -> &kernel_symbol { &*mem::transmute::<_, *const kernel_symbol>(mem.as_ptr()) } fn check_single_kernel_sym( mem: &[u8], ii: usize, sym_size: usize, strings_range: &Range<usize>, ) -> Option<usize> { let start = ii - sym_size; let sym = unsafe { cast_kernel_sym(&mem[start..ii]) }; let field_offset = &sym.name_offset as *const i32 as usize - sym as *const kernel_symbol as usize; let sum = start .checked_add(sym.name_offset as usize) .and_then(|s| s.checked_add(field_offset)); if let Some(name_idx) = sum { if strings_range.contains(&name_idx) { return Some(name_idx); } } None } fn check_kernel_sym( mem: &[u8], strings_range: &Range<usize>, sym_size: usize, ii: usize, ) -> Option<usize> { if 2 * sym_size > ii { return None; } if let Some(addr1) = check_single_kernel_sym(mem, ii, sym_size, strings_range) { if let Some(addr2) = check_single_kernel_sym(mem, ii - sym_size, sym_size, strings_range) { if addr1 != addr2 { return Some(sym_size); } } } None } fn get_kernel_symbol_legacy(mem: &[u8]) -> &kernel_symbol_4_18 { unsafe { &*(mem.as_ptr() as *const kernel_symbol_4_18) } } fn check_kernel_sym_legacy( mem: &[u8], mem_base: usize, strings_range: &Range<usize>, ii: usize, ) -> Option<usize> { let sym_size = size_of::<kernel_symbol_4_18>(); if sym_size > ii { return None; } let sym = get_kernel_symbol_legacy(&mem[ii - sym_size..ii]); let virt_range = strings_range.start + mem_base..strings_range.end + mem_base; if virt_range.contains(&(sym.name as usize)) { let sym2 = get_kernel_symbol_legacy(&mem[ii - 2 * sym_size..ii - sym_size]); if virt_range.contains(&(sym2.name as usize)) { return Some(sym_size); } } None } fn get_ksymtab_start( mem: &[u8], mem_base: usize, strings_range: &Range<usize>, ) -> Option<(usize, usize)> { let step_size = size_of::<u32>(); for ii in (0..strings_range.start + 1).rev().step_by(step_size) { let sym_size = check_kernel_sym(mem, strings_range, size_of::<kernel_symbol>(), ii) .or_else(|| check_kernel_sym(mem, strings_range, size_of::<kernel_symbol_5_3>(), ii)) .or_else(|| check_kernel_sym_legacy(mem, mem_base, strings_range, ii)); if let Some(sym_size) = sym_size { return Some((ii, sym_size)); } } None } fn apply_offset(addr: usize, offset: libc::c_int) -> usize { if offset < 0 { addr - (-offset as usize) } else { addr - offset as usize } } fn symbol_name(mem: &[u8], idx: usize) -> Result<String> { let len = require_with!( mem[idx..].iter().position(|c| *c == 0), "symbol name does not end" ); let name = try_with!( CStr::from_bytes_with_nul(&mem[idx..idx + len + 1]), "invalid symbol name" ); Ok(try_with!(name.to_str(), "invalid encoding for symbol name").to_owned()) } fn get_kernel_symbols( mem: &[u8], mem_base: usize, ksymtab_strings: Range<usize>, ) -> Result<HashMap<String, usize>> { let mut syms = HashMap::new(); let (start, sym_size) = require_with!( get_ksymtab_start(mem, mem_base, &ksymtab_strings), "no ksymtab found" ); info!( "found ksymtab {} bytes before ksymtab_strings at 0x{:x}", ksymtab_strings.start - start, start + mem_base ); let mut sym_count = 0; if sym_size == size_of::<kernel_symbol_4_18>() { let virt_range = ksymtab_strings.start + mem_base..ksymtab_strings.end + mem_base; for ii in (0..start + 1).rev().step_by(sym_size) { let sym = get_kernel_symbol_legacy(&mem[ii - sym_size..ii]); if !virt_range.contains(&(sym.name as usize)) { break; } let name = symbol_name(mem, sym.name as usize - mem_base)?; sym_count += 1; debug!("{} @ {:x}", name, sym.value); syms.insert(name, sym.value as usize); } } else { for ii in (0..start + 1).rev().step_by(sym_size) { let sym_start = ii - sym_size; let sym = unsafe { cast_kernel_sym(&mem[sym_start..ii]) }; let name_offset = &sym.name_offset as *const i32 as usize - sym as *const kernel_symbol as usize; let value_offset = &sym.value_offset as *const i32 as usize - sym as *const kernel_symbol as usize; let name_idx = match sym_start .checked_add(name_offset) .and_then(|s| s.checked_add(sym.name_offset as usize)) { Some(idx) => idx, None => break, }; if !ksymtab_strings.contains(&name_idx) { break; } let value_ptr = apply_offset(mem_base + sym_start + value_offset, sym.value_offset); let name = symbol_name(mem, name_idx)?; sym_count += 1; debug!("{} @ {:x}", name, value_ptr); syms.insert(name, value_ptr); } } info!("found {} kernel symbols", sym_count); Ok(syms) } pub struct Kernel { pub range: Range<usize>, pub memory_sections: Vec<MappedMemory>, pub symbols: HashMap<String, usize>, pub largest_gap: Range<usize>, } impl Kernel { pub fn space_before(&self) -> usize { self.range.start - LINUX_KERNEL_KASLR_RANGE.start } pub fn space_after(&self) -> usize { LINUX_KERNEL_KASLR_RANGE.end - self.range.end } } pub fn find_kernel(guest_mem: &GuestMem, hv: &Hypervisor) -> Result<Kernel> { let (memory_sections, largest_gap) = try_with!( guest_mem.find_kernel_sections(hv, LINUX_KERNEL_KASLR_RANGE), "could not find Linux kernel in VM memory" ); let kernel_last = require_with!(memory_sections.last(), "no sections found"); let kernel_start = require_with!(memory_sections.first(), "no sections found").virt_start; let kernel_end = kernel_last.virt_start + kernel_last.len; info!( "found linux kernel at {:#x}-{:#x}", kernel_start, kernel_end ); let symbols = memory_sections.iter().find_map(|s| { if s.prot != ProtFlags::PROT_READ { return None; } let mut mem = vec![0; s.len]; let mem_base = s.phys_start.host_addr() as *const libc::c_void; if let Err(e) = process_read_bytes(hv.pid, &mut mem, mem_base) { return Some(Err(SimpleError::new(format!( "failed to read linux kernel from hypervisor memory: {}", e )))); } let strings_range = find_ksymtab_strings_section(&mem)?; let from_addr = s.phys_start.add(strings_range.start); let to_addr = s.phys_start.add(strings_range.end - 1); let string_num = mem[strings_range.clone()] .iter() .filter(|c| **c == 0) .count(); info!( "found ksymtab_string at physical {:#x}:{:#x} with {} strings", from_addr.value, to_addr.value, string_num ); match get_kernel_symbols(&mem, s.virt_start, strings_range) { Err(e) => Some(Err(SimpleError::new(format!( "failed to parse kernel symbols: {}", e )))), Ok(syms) => Some(Ok(syms)), } }); let symbols = require_with!(symbols, "could not find section with kernel symbols")?; Ok(Kernel { range: kernel_start..kernel_end, memory_sections, symbols, largest_gap, }) }
use log::{debug, info}; use nix::sys::mman::ProtFlags; use simple_error::{require_with, try_with, SimpleError}; use std::collections::HashMap; use std::ffi::CStr; use std::mem::{self, size_of}; use std::ops::Range; use vm_memory::remote_mem::process_read_bytes; use crate::guest_mem::{GuestMem, MappedMemory}; use crate::kvm::hypervisor::Hypervisor; use crate::result::Result; pub const LINUX_KERNEL_KASLR_RANGE: Range<usize> = 0xFFFFFFFF80000000..0xFFFFFFFFC0000000; fn find_subsequence(haystack: &[u8], needle: &[u8]) -> Option<usize> { haystack .windows(needle.len()) .position(|window| window == needle) } fn not_printable(byte: u8) -> bool { !(0x20 < byte && byte < 0x7E) } fn round_up(num: usize, align: usize) -> usize { ((num + align - 1) / align) * align } fn find_ksymtab_strings_section(mem: &[u8]) -> Optio
end = idx + end_offset + 1; Some(start..end) } #[repr(C)] #[derive(Debug)] pub struct kernel_symbol { pub value_offset: libc::c_int, pub name_offset: libc::c_int, pub namespace_offset: libc::c_int, } #[repr(C)] #[derive(Debug)] pub struct kernel_symbol_5_3 { pub value_offset: libc::c_int, pub name_offset: libc::c_int, } #[repr(C)] #[derive(Debug)] pub struct kernel_symbol_4_18 { pub value: libc::c_ulong, pub name: libc::c_ulong, } unsafe fn cast_kernel_sym(mem: &[u8]) -> &kernel_symbol { &*mem::transmute::<_, *const kernel_symbol>(mem.as_ptr()) } fn check_single_kernel_sym( mem: &[u8], ii: usize, sym_size: usize, strings_range: &Range<usize>, ) -> Option<usize> { let start = ii - sym_size; let sym = unsafe { cast_kernel_sym(&mem[start..ii]) }; let field_offset = &sym.name_offset as *const i32 as usize - sym as *const kernel_symbol as usize; let sum = start .checked_add(sym.name_offset as usize) .and_then(|s| s.checked_add(field_offset)); if let Some(name_idx) = sum { if strings_range.contains(&name_idx) { return Some(name_idx); } } None } fn check_kernel_sym( mem: &[u8], strings_range: &Range<usize>, sym_size: usize, ii: usize, ) -> Option<usize> { if 2 * sym_size > ii { return None; } if let Some(addr1) = check_single_kernel_sym(mem, ii, sym_size, strings_range) { if let Some(addr2) = check_single_kernel_sym(mem, ii - sym_size, sym_size, strings_range) { if addr1 != addr2 { return Some(sym_size); } } } None } fn get_kernel_symbol_legacy(mem: &[u8]) -> &kernel_symbol_4_18 { unsafe { &*(mem.as_ptr() as *const kernel_symbol_4_18) } } fn check_kernel_sym_legacy( mem: &[u8], mem_base: usize, strings_range: &Range<usize>, ii: usize, ) -> Option<usize> { let sym_size = size_of::<kernel_symbol_4_18>(); if sym_size > ii { return None; } let sym = get_kernel_symbol_legacy(&mem[ii - sym_size..ii]); let virt_range = strings_range.start + mem_base..strings_range.end + mem_base; if virt_range.contains(&(sym.name as usize)) { let sym2 = get_kernel_symbol_legacy(&mem[ii - 2 * sym_size..ii - sym_size]); if virt_range.contains(&(sym2.name as usize)) { return Some(sym_size); } } None } fn get_ksymtab_start( mem: &[u8], mem_base: usize, strings_range: &Range<usize>, ) -> Option<(usize, usize)> { let step_size = size_of::<u32>(); for ii in (0..strings_range.start + 1).rev().step_by(step_size) { let sym_size = check_kernel_sym(mem, strings_range, size_of::<kernel_symbol>(), ii) .or_else(|| check_kernel_sym(mem, strings_range, size_of::<kernel_symbol_5_3>(), ii)) .or_else(|| check_kernel_sym_legacy(mem, mem_base, strings_range, ii)); if let Some(sym_size) = sym_size { return Some((ii, sym_size)); } } None } fn apply_offset(addr: usize, offset: libc::c_int) -> usize { if offset < 0 { addr - (-offset as usize) } else { addr - offset as usize } } fn symbol_name(mem: &[u8], idx: usize) -> Result<String> { let len = require_with!( mem[idx..].iter().position(|c| *c == 0), "symbol name does not end" ); let name = try_with!( CStr::from_bytes_with_nul(&mem[idx..idx + len + 1]), "invalid symbol name" ); Ok(try_with!(name.to_str(), "invalid encoding for symbol name").to_owned()) } fn get_kernel_symbols( mem: &[u8], mem_base: usize, ksymtab_strings: Range<usize>, ) -> Result<HashMap<String, usize>> { let mut syms = HashMap::new(); let (start, sym_size) = require_with!( get_ksymtab_start(mem, mem_base, &ksymtab_strings), "no ksymtab found" ); info!( "found ksymtab {} bytes before ksymtab_strings at 0x{:x}", ksymtab_strings.start - start, start + mem_base ); let mut sym_count = 0; if sym_size == size_of::<kernel_symbol_4_18>() { let virt_range = ksymtab_strings.start + mem_base..ksymtab_strings.end + mem_base; for ii in (0..start + 1).rev().step_by(sym_size) { let sym = get_kernel_symbol_legacy(&mem[ii - sym_size..ii]); if !virt_range.contains(&(sym.name as usize)) { break; } let name = symbol_name(mem, sym.name as usize - mem_base)?; sym_count += 1; debug!("{} @ {:x}", name, sym.value); syms.insert(name, sym.value as usize); } } else { for ii in (0..start + 1).rev().step_by(sym_size) { let sym_start = ii - sym_size; let sym = unsafe { cast_kernel_sym(&mem[sym_start..ii]) }; let name_offset = &sym.name_offset as *const i32 as usize - sym as *const kernel_symbol as usize; let value_offset = &sym.value_offset as *const i32 as usize - sym as *const kernel_symbol as usize; let name_idx = match sym_start .checked_add(name_offset) .and_then(|s| s.checked_add(sym.name_offset as usize)) { Some(idx) => idx, None => break, }; if !ksymtab_strings.contains(&name_idx) { break; } let value_ptr = apply_offset(mem_base + sym_start + value_offset, sym.value_offset); let name = symbol_name(mem, name_idx)?; sym_count += 1; debug!("{} @ {:x}", name, value_ptr); syms.insert(name, value_ptr); } } info!("found {} kernel symbols", sym_count); Ok(syms) } pub struct Kernel { pub range: Range<usize>, pub memory_sections: Vec<MappedMemory>, pub symbols: HashMap<String, usize>, pub largest_gap: Range<usize>, } impl Kernel { pub fn space_before(&self) -> usize { self.range.start - LINUX_KERNEL_KASLR_RANGE.start } pub fn space_after(&self) -> usize { LINUX_KERNEL_KASLR_RANGE.end - self.range.end } } pub fn find_kernel(guest_mem: &GuestMem, hv: &Hypervisor) -> Result<Kernel> { let (memory_sections, largest_gap) = try_with!( guest_mem.find_kernel_sections(hv, LINUX_KERNEL_KASLR_RANGE), "could not find Linux kernel in VM memory" ); let kernel_last = require_with!(memory_sections.last(), "no sections found"); let kernel_start = require_with!(memory_sections.first(), "no sections found").virt_start; let kernel_end = kernel_last.virt_start + kernel_last.len; info!( "found linux kernel at {:#x}-{:#x}", kernel_start, kernel_end ); let symbols = memory_sections.iter().find_map(|s| { if s.prot != ProtFlags::PROT_READ { return None; } let mut mem = vec![0; s.len]; let mem_base = s.phys_start.host_addr() as *const libc::c_void; if let Err(e) = process_read_bytes(hv.pid, &mut mem, mem_base) { return Some(Err(SimpleError::new(format!( "failed to read linux kernel from hypervisor memory: {}", e )))); } let strings_range = find_ksymtab_strings_section(&mem)?; let from_addr = s.phys_start.add(strings_range.start); let to_addr = s.phys_start.add(strings_range.end - 1); let string_num = mem[strings_range.clone()] .iter() .filter(|c| **c == 0) .count(); info!( "found ksymtab_string at physical {:#x}:{:#x} with {} strings", from_addr.value, to_addr.value, string_num ); match get_kernel_symbols(&mem, s.virt_start, strings_range) { Err(e) => Some(Err(SimpleError::new(format!( "failed to parse kernel symbols: {}", e )))), Ok(syms) => Some(Ok(syms)), } }); let symbols = require_with!(symbols, "could not find section with kernel symbols")?; Ok(Kernel { range: kernel_start..kernel_end, memory_sections, symbols, largest_gap, }) }
n<Range<usize>> { let idx = find_subsequence(mem, b"init_task")?; let start_offset = mem[..idx] .windows(2) .rev() .position(|b| not_printable(b[0]) && not_printable(b[1]))?; let start = round_up(idx - start_offset, 4); let end_offset = mem[idx..] .windows(2) .position(|b| not_printable(b[0]) && not_printable(b[1]))?; let
function_block-random_span
[ { "content": "pub fn is_page_aligned(v: usize) -> bool {\n\n v & (page_size() - 1) == 0\n\n}\n\n\n", "file_path": "src/page_math.rs", "rank": 2, "score": 253724.61583958115 }, { "content": "pub fn use_ioregionfd() -> bool {\n\n USE_IOREGIONFD.load(Ordering::Relaxed)\n\n}\n\n\n\npub type Block = block::Block<Arc<GuestMemoryMmap>>;\n\npub type Console = console::Console<Arc<GuestMemoryMmap>>;\n\n\n", "file_path": "src/devices/mod.rs", "rank": 3, "score": 235714.76627342642 }, { "content": "pub fn huge_page_size(level: u8) -> usize {\n\n page_size() << (9 * (3 - level))\n\n}\n\n\n", "file_path": "src/page_math.rs", "rank": 5, "score": 209212.26542721724 }, { "content": "pub fn page_align(v: usize) -> usize {\n\n (v + page_size() - 1) & !(page_size() - 1)\n\n}\n\n\n", "file_path": "src/page_math.rs", "rank": 6, "score": 203037.38898888935 }, { "content": "pub fn table_align(pages: usize) -> usize {\n\n (pages + (ENTRY_COUNT - 1)) & !(ENTRY_COUNT - 1)\n\n}\n\n\n", "file_path": "src/page_table.rs", "rank": 7, "score": 198773.76174156673 }, { "content": "pub fn get_irq_num(pid: Pid) -> Result<usize> {\n\n let mut comm_path = PathBuf::from(\"/proc\");\n\n comm_path.push(pid.as_raw().to_string());\n\n comm_path.push(\"comm\");\n\n let comm = try_with!(\n\n read_to_string(&comm_path),\n\n \"failed to read {}\",\n\n comm_path.display()\n\n );\n\n // dirty hack until we have a better way to find out what IRQs we can use\n\n if comm.contains(\"crosvm\") {\n\n Ok(4)\n\n } else {\n\n Ok(6)\n\n }\n\n}\n\n\n", "file_path": "src/attach.rs", "rank": 8, "score": 179901.84925610275 }, { "content": "/// re-implementation of IS_ERR_VALUE\n\nfn is_err_value(x: *const c_void) -> bool {\n\n x as c_long >= -(ffi::MAX_ERRNO as c_long)\n\n}\n\n\n", "file_path": "src/stage1/src/lib.rs", "rank": 9, "score": 179652.22275928519 }, { "content": "pub fn page_size() -> usize {\n\n sysconf(SysconfVar::PAGE_SIZE)\n\n .expect(\"sysconf failed\")\n\n .expect(\"page size unknown\") as usize\n\n}\n\n\n", "file_path": "src/page_math.rs", "rank": 10, "score": 168027.94375151471 }, { "content": "pub fn page_start(v: usize) -> usize {\n\n v & !(page_size() - 1)\n\n}\n\n\n", "file_path": "src/page_math.rs", "rank": 11, "score": 167148.45626870022 }, { "content": "pub fn note_size<T>() -> usize {\n\n // name is 4 bit aligned, we write CORE\\0 to it\n\n let name_size = 8;\n\n size_of::<Nhdr>() + name_size + size_of::<T>()\n\n}\n\n\n", "file_path": "src/coredump.rs", "rank": 12, "score": 163403.38996241943 }, { "content": "/// Upper bound of page tables memory we need to map physical memory of given size\n\npub fn estimate_page_table_size(size: usize) -> usize {\n\n let pages = page_align(size as usize) / page_size();\n\n let mut tables = pages;\n\n let mut total_tables = 0;\n\n for _ in 0..LEVEL_COUNT {\n\n tables = table_align(tables) / ENTRY_COUNT;\n\n total_tables += tables;\n\n }\n\n total_tables * size_of::<u64>() * ENTRY_COUNT\n\n}\n\n\n\npub struct VirtMem {\n\n hv: Arc<Hypervisor>,\n\n /// List of tables we need to restore to their old state before exiting\n\n old_tables: Vec<PageTable>,\n\n /// physical memory used to hold page tables and bake virtual memory\n\n #[allow(unused)]\n\n phys_mem: PhysMem<u8>,\n\n /// Mapping between virtual and physical memory\n\n pub mappings: Vec<MappedMemory>,\n", "file_path": "src/page_table.rs", "rank": 13, "score": 158190.68349014345 }, { "content": "pub fn get_syscall_info(pid: Pid) -> Result<SyscallInfo> {\n\n let mut info = MaybeUninit::<RawInfo>::zeroed();\n\n // Safe, because the kernel writes at most size_of::<RawInfo>() bytes and at least `ret` bytes.\n\n // We check he has written size_of::<RawInfo>() bytes. We also allow him to omit the trailing\n\n // `data: RawData` field if he marks its absence in the op field, because in that case the\n\n // parser (`parse_raw_info()`) will ignore the data and never access it.\n\n let ret = unsafe {\n\n libc::ptrace(\n\n PTRACE_GET_SYSCALL_INFO,\n\n pid,\n\n size_of::<RawInfo>(),\n\n info.as_mut_ptr(),\n\n )\n\n };\n\n if ret <= 0 {\n\n bail!(\"ptrace get syscall info error: {}\", ret);\n\n }\n\n let info = unsafe { info.assume_init() };\n\n if !((info.op == OpType::PTRACE_SYSCALL_INFO_NONE\n\n && size_of::<RawInfo>() - size_of::<RawData>() == ret as usize)\n", "file_path": "src/tracer/ptrace_syscall_info.rs", "rank": 14, "score": 153442.8473545827 }, { "content": "fn get_start_idx(virt_addr: usize, idx: usize, level: u8) -> usize {\n\n if idx != 0 {\n\n 0\n\n } else {\n\n get_index(virt_addr as u64, level) as usize\n\n }\n\n}\n\n\n", "file_path": "src/page_table.rs", "rank": 15, "score": 148404.26510665478 }, { "content": "fn get_shift(level: u8) -> u8 {\n\n assert!(level <= 3);\n\n 12 + 9 * (3 - level)\n\n}\n\n\n", "file_path": "src/page_table.rs", "rank": 16, "score": 146371.9559072896 }, { "content": "pub fn compute_host_offset(host_addr: usize, phys_addr: usize) -> isize {\n\n if host_addr > phys_addr {\n\n (host_addr - phys_addr) as isize\n\n } else {\n\n -((phys_addr - host_addr) as isize)\n\n }\n\n}\n", "file_path": "src/page_math.rs", "rank": 17, "score": 144169.26619629207 }, { "content": "#[allow(dead_code)]\n\npub fn gdb_break() {\n\n let tid = unsafe { gettid() }.to_string();\n\n\n\n println!(\"GDB PROBE HIT, WAITING\");\n\n // 1. finish: wait4\n\n // 2. finish: Process::wait\n\n // 3. finish: gdb::break\n\n // 4. finish: caller\n\n let args = vec![\n\n \"-c\", \"tmux new-window sudo -E gdb --pid \\\"$0\\\" -ex \\\"shell kill -9 $$\\\" -ex finish -ex finish -ex finish -ex finish; kill -STOP $$\", &tid\n\n ];\n\n let _ = Command::new(\"sh\").args(args.as_slice()).status();\n\n}\n\n\n\n#[macro_export]\n\nmacro_rules! dbg_hex {\n\n // NOTE: We cannot use `concat!` to make a static string as a format argument\n\n // of `eprintln!` because `file!` could contain a `{` or\n\n // `$val` expression could be a block (`{ .. }`), in which case the `eprintln!`\n\n // will be malformed.\n", "file_path": "src/debug.rs", "rank": 20, "score": 141709.81858867063 }, { "content": "/// Maps a list of physical memory chunks at phys_addr with a length of u64 to virt_addr.\n\n/// The list must to be physical continous and sorted.\n\n/// To allocate page tables it uses space at the end of given physical memory address.\n\n/// There must be enough space after the last mapping to store these pagetable.\n\npub fn map_memory(\n\n hv: Arc<Hypervisor>,\n\n phys_mem: PhysMem<u8>,\n\n pml4_addr: &mut PhysAddr,\n\n mappings: &[MappedMemory],\n\n phys_host_map: &PhysHostMap,\n\n) -> Result<VirtMem> {\n\n // New/modified tables to be written to guest\n\n let mut upsert_tables: UpsertTable = HashMap::new();\n\n // Tables that we need to revert to their old content\n\n let mut old_tables: Vec<PageTable> = vec![];\n\n let pml4 = try_with!(\n\n read_page_table(\n\n &hv,\n\n pml4_addr.value,\n\n &mut old_tables,\n\n &mut upsert_tables,\n\n phys_host_map\n\n ),\n\n \"cannot read pml4 page table\"\n", "file_path": "src/page_table.rs", "rank": 21, "score": 139047.751329033 }, { "content": "pub fn setup(\n\n device: &BlockDevice,\n\n container_namespace: namespace::Namespace,\n\n mount_label: &Option<String>,\n\n) -> Result<MountNamespace> {\n\n let ns = MountNamespace::new(container_namespace)?;\n\n\n\n try_with!(\n\n mount::mount(\n\n Some(\"none\"),\n\n \"/\",\n\n NONE,\n\n MsFlags::MS_REC | MsFlags::MS_PRIVATE,\n\n NONE,\n\n ),\n\n \"unable to mark mounts as private\"\n\n );\n\n\n\n // prepare bind mounts\n\n try_with!(\n", "file_path": "src/stage2/src/mountns.rs", "rank": 22, "score": 139044.6722156186 }, { "content": "pub fn stop_vmsh() {\n\n _stop_vmsh(false);\n\n}\n\n\n\nextern \"C\" fn signal_handler(_: ::libc::c_int) {\n\n _stop_vmsh(true);\n\n}\n\n\n", "file_path": "src/signal_handler.rs", "rank": 23, "score": 139044.6722156186 }, { "content": "fn sme_sev_bits() -> u8 {\n\n // get AMD Encrypted Memory Capabilities information according to AMD doc 24594—Rev. 3.32\n\n let host_cpuid = unsafe { core::arch::x86_64::__cpuid(ENCRYPTED_MEMORY_CAPABILITIES) };\n\n //host_cpuid(0x8000001f, 0, &eax, &ebx, NULL, NULL);\n\n // bits:\n\n // 0:1 SME\n\n // 1:2 SEV\n\n // ...\n\n if host_cpuid.eax & 1 != 0 || host_cpuid.eax & 2 != 0 {\n\n // bits:\n\n // 11:6 PhysAddrReduction\n\n ((host_cpuid.ebx >> 6) & 0x3f) as u8\n\n } else {\n\n 0\n\n }\n\n}\n\n\n", "file_path": "src/kvm/allocator.rs", "rank": 24, "score": 137440.33434216634 }, { "content": "pub fn register_ioeventfd(\n\n vmm: &Arc<Hypervisor>,\n\n mmio_cfg: &MmioConfig,\n\n queue_idx: u64,\n\n) -> Result<IoEventFd> {\n\n let ioeventfd = vmm.ioeventfd_(\n\n mmio_cfg.range.base().0 + VIRTIO_MMIO_QUEUE_NOTIFY_OFFSET,\n\n 4,\n\n Some(queue_idx),\n\n )?;\n\n\n\n Ok(ioeventfd)\n\n}\n", "file_path": "src/devices/virtio/mod.rs", "rank": 25, "score": 136555.5951878709 }, { "content": "#[must_use]\n\npub fn find_mapping(mappings: &[Mapping], ip: usize) -> Option<Mapping> {\n\n mappings\n\n .iter()\n\n .find(|m| m.start <= ip && ip < m.end)\n\n .cloned()\n\n}\n\n\n\npub struct PidHandle {\n\n pub pid: Pid,\n\n file: File,\n\n}\n\n\n", "file_path": "src/tracer/proc.rs", "rank": 26, "score": 134918.03956877376 }, { "content": "pub fn attach_all_threads(pid: Pid) -> Result<(Vec<Thread>, usize)> {\n\n let dir = proc::pid_path(pid).join(\"task\");\n\n let threads_dir = try_with!(\n\n fs::read_dir(&dir),\n\n \"failed to open directory {}\",\n\n dir.display()\n\n );\n\n let mut process_idx = 0;\n\n\n\n let mut threads = vec![];\n\n\n\n for (i, thread_name) in threads_dir.enumerate() {\n\n let entry = try_with!(thread_name, \"failed to read directory {}\", dir.display());\n\n let file_name = entry.file_name();\n\n let file_name = require_with!(file_name.to_str(), \"cannot convert filename to string\");\n\n let raw_tid = try_with!(file_name.parse::<pid_t>(), \"invalid tid {}\", file_name);\n\n let tid = Pid::from_raw(raw_tid);\n\n if tid == pid {\n\n process_idx = i;\n\n }\n", "file_path": "src/tracer/ptrace.rs", "rank": 27, "score": 134913.52581038757 }, { "content": "pub fn process_read<T: Sized + Copy>(pid: Pid, addr: *const c_void) -> Result<T> {\n\n remote_mem::process_read(pid, addr).map_err(|e| simple_error!(\"{}\", e))\n\n}\n\n\n", "file_path": "src/kvm/hypervisor/memory.rs", "rank": 28, "score": 132609.91822820203 }, { "content": "/// Apply an operation on a process\n\n/// [prctl(2)](http://man7.org/linux/man-pages/man2/prctl.2.html)\n\n///\n\n/// prctl is called with a first argument describing what to do,\n\n/// further arguments with a significance depending on the first one.\n\npub fn prctl(\n\n option: c_int,\n\n arg2: c_ulong,\n\n arg3: c_ulong,\n\n arg4: c_ulong,\n\n arg5: c_ulong,\n\n) -> Result<()> {\n\n let res = unsafe { libc::prctl(option, arg2, arg3, arg4, arg5) };\n\n\n\n Errno::result(res).map(drop)\n\n}\n", "file_path": "src/stage2/src/sys_ext/internal/prctl.rs", "rank": 29, "score": 132040.1833590808 }, { "content": "fn _stop_vmsh(is_signal: bool) {\n\n let sender = match SIGNAL_SENDER.lock().expect(\"cannot lock sender\").take() {\n\n Some(s) => {\n\n info!(\"shutdown vmsh\");\n\n s\n\n }\n\n None => {\n\n if is_signal {\n\n info!(\"received sigterm. stopping already in progress\");\n\n }\n\n return;\n\n }\n\n };\n\n if let Err(e) = sender.send(()) {\n\n error!(\"cannot notify main process: {}\", e);\n\n }\n\n}\n\n\n", "file_path": "src/signal_handler.rs", "rank": 30, "score": 131976.3737720182 }, { "content": "pub fn setup() -> Result<()> {\n\n let monitor_console = find_vmsh_consoles()?;\n\n try_with!(\n\n unistd::dup2(monitor_console.as_raw_fd(), libc::STDIN_FILENO),\n\n \"cannot replace stdin with monitor connection\"\n\n );\n\n try_with!(\n\n unistd::dup2(monitor_console.as_raw_fd(), libc::STDOUT_FILENO),\n\n \"cannot replace stdout with monitor connection\"\n\n );\n\n try_with!(\n\n unistd::dup2(monitor_console.as_raw_fd(), libc::STDERR_FILENO),\n\n \"cannot replace stderr with monitor connection\"\n\n );\n\n\n\n Ok(())\n\n}\n", "file_path": "src/stage2/src/console.rs", "rank": 31, "score": 131057.10997406469 }, { "content": "fn is_selinux_enabled() -> Result<bool> {\n\n let file = try_with!(\n\n File::open(\"/proc/filesystems\"),\n\n \"failed to open /proc/filesystems\"\n\n );\n\n let reader = BufReader::new(file);\n\n for line in reader.lines() {\n\n let l = try_with!(line, \"failed to read from /proc/filesystems\");\n\n if l.contains(\"selinuxfs\") {\n\n return Ok(true);\n\n }\n\n }\n\n Ok(false)\n\n}\n\n\n", "file_path": "src/stage2/src/lsm.rs", "rank": 32, "score": 129637.1028854686 }, { "content": "fn is_apparmor_enabled() -> Result<bool> {\n\n let aa_path = \"/sys/module/apparmor/parameters/enabled\";\n\n match File::open(aa_path) {\n\n Ok(mut file) => {\n\n let mut contents = String::new();\n\n try_with!(\n\n file.read_to_string(&mut contents),\n\n \"failed to read {}\",\n\n aa_path\n\n );\n\n Ok(contents == \"Y\\n\")\n\n }\n\n Err(err) => {\n\n if err.kind() != ErrorKind::NotFound {\n\n try_with!(Err(err), \"failed to open {}\", aa_path);\n\n }\n\n Ok(false)\n\n }\n\n }\n\n}\n\n\n", "file_path": "src/stage2/src/lsm.rs", "rank": 33, "score": 129637.1028854686 }, { "content": "fn parse_raw_data(info: RawInfo) -> Result<SyscallOp> {\n\n let op = unsafe {\n\n match info.op {\n\n OpType::PTRACE_SYSCALL_INFO_NONE => SyscallOp::None,\n\n OpType::PTRACE_SYSCALL_INFO_ENTRY => SyscallOp::Entry {\n\n nr: info.data.entry.nr,\n\n args: info.data.entry.args,\n\n },\n\n OpType::PTRACE_SYSCALL_INFO_EXIT => SyscallOp::Exit {\n\n rval: info.data.exit.rval,\n\n is_error: info.data.exit.is_error,\n\n },\n\n OpType::PTRACE_SYSCALL_INFO_SECCOMP => SyscallOp::Seccomp {\n\n nr: info.data.seccomp.nr,\n\n args: info.data.seccomp.args,\n\n ret_data: info.data.seccomp.ret_data,\n\n },\n\n OpType::unknown => bail!(\"unknown ptrace_syscall_info.op: {:?}\", info.op),\n\n }\n\n };\n\n\n\n Ok(op)\n\n}\n\n\n", "file_path": "src/tracer/ptrace_syscall_info.rs", "rank": 34, "score": 127606.75018513888 }, { "content": "fn build_config_space() -> Vec<u8> {\n\n // FIXME think about terminal size\n\n let config = virtio_console_config {\n\n cols: 80,\n\n rows: 24,\n\n max_nr_ports: 2,\n\n emerg_wr: 0,\n\n };\n\n unsafe { any_as_u8_slice(&config) }.to_vec()\n\n}\n\n\n\n// Arguments required when building a console device.\n\npub struct ConsoleArgs<'a, M, B> {\n\n pub common: CommonArgs<'a, M, B>,\n\n /// None shall be interpreted as \"sane default\".\n\n pub pts: Option<PathBuf>,\n\n}\n", "file_path": "src/devices/virtio/console/mod.rs", "rank": 35, "score": 125294.89508361083 }, { "content": "// TODO: This came for cntr we might even want to mount our own procfs\n\npub fn get_path() -> PathBuf {\n\n PathBuf::from(&env::var_os(\"CNTR_PROC\").unwrap_or_else(|| OsString::from(\"/proc\")))\n\n}\n\n\n\npub struct ProcStatus {\n\n pub global_pid: Pid,\n\n pub local_pid: Pid,\n\n pub inherited_capabilities: u64,\n\n pub effective_capabilities: u64,\n\n}\n\n\n", "file_path": "src/stage2/src/procfs/mod.rs", "rank": 36, "score": 124487.54915629161 }, { "content": "pub fn tempdir() -> Result<TempDir> {\n\n let tmp = env::temp_dir();\n\n let templates = &[\n\n tmp.as_path(),\n\n Path::new(\"/dev/shm\"),\n\n Path::new(\"/tmp\"),\n\n Path::new(\"/dev\"),\n\n ];\n\n let mut last_err = None;\n\n for t in templates {\n\n match _tempdir(t.into()) {\n\n Ok(v) => return Ok(v),\n\n Err(e) => last_err = Some(e),\n\n };\n\n }\n\n Err(last_err.unwrap())\n\n}\n\n\n\nimpl Drop for TempDir {\n\n fn drop(&mut self) {\n\n if let Some(ref p) = self.name {\n\n let _ = fs::remove_dir_all(p);\n\n }\n\n }\n\n}\n", "file_path": "src/ioutils/src/tmp.rs", "rank": 37, "score": 121917.14435617931 }, { "content": "pub fn kmsg_log(msg: &str) {\n\n let mut v = match OpenOptions::new().write(true).open(\"/dev/kmsg\") {\n\n Ok(v) => v,\n\n Err(_) => return,\n\n };\n\n let _ = v.write_all(msg.as_bytes());\n\n}\n", "file_path": "src/stage2/src/kmsg.rs", "rank": 38, "score": 121917.14435617931 }, { "content": "pub fn copy_out(source: &Path) {\n\n let out_dir = env::var_os(\"OUT_DIR\").expect(\"OUT_DIR is not set\");\n\n let target = Path::new(&out_dir).join(source.file_name().expect(\"source has no filename\"));\n\n println!(\"cp {} {}\", source.display(), target.display());\n\n fs::copy(source, target)\n\n .unwrap_or_else(|e| panic!(\"failed to copy {}: {}\", source.display(), e));\n\n}\n\n\n", "file_path": "src/build-utils/src/lib.rs", "rank": 39, "score": 121917.14435617931 }, { "content": "pub fn inspect(opts: &InspectOptions) -> Result<()> {\n\n let vm = try_with!(\n\n kvm::hypervisor::get_hypervisor(opts.pid),\n\n \"cannot get vms for process {}\",\n\n opts.pid\n\n );\n\n vm.stop()?;\n\n\n\n for map in vm.get_maps()? {\n\n info!(\n\n \"vm mem: {:#x} -> {:#x} (physical: {:#x}, flags: {:?} | {:?}) @@ {}\",\n\n map.start, map.end, map.phys_addr, map.prot_flags, map.map_flags, map.pathname\n\n )\n\n }\n\n\n\n info!(\"vcpu maps\");\n\n for map in vm.get_vcpu_maps()? {\n\n info!(\n\n \"vm cpu mem: {:#x} -> {:#x} (physical: {:#x}, flags: {:?} | {:?}) @@ {}\",\n\n map.start, map.end, map.phys_addr, map.prot_flags, map.map_flags, map.pathname\n", "file_path": "src/inspect.rs", "rank": 41, "score": 120159.02082898581 }, { "content": "pub fn attach(opts: &AttachOptions) -> Result<()> {\n\n info!(\"attaching\");\n\n\n\n let (sender, receiver) = sync_channel(1);\n\n\n\n signal_handler::setup(&sender)?;\n\n\n\n let mut vm = try_with!(\n\n kvm::hypervisor::get_hypervisor(opts.pid),\n\n \"cannot get vms for process {}\",\n\n opts.pid\n\n );\n\n vm.stop()?;\n\n try_with!(\n\n vm.setup_transfer_sockets(),\n\n \"failed to setup unix sockets for fd transfer\"\n\n );\n\n let vm = Arc::new(vm);\n\n\n\n let mut allocator = try_with!(\n", "file_path": "src/attach.rs", "rank": 42, "score": 120159.02082898581 }, { "content": "// Linux assigns consoles linear so later added devices get a higher number.\n\n// In theory just assuming vmsh is the last console added is racy however\n\n// in practice it seems unlikely to have consoles added at runtime (famous last words).\n\npub fn find_vmsh_consoles() -> Result<File> {\n\n let entries = try_with!(\n\n fs::read_dir(PathBuf::from(\"/dev/\")),\n\n \"failed to open directory /dev\"\n\n );\n\n let mut heap = BinaryHeap::new();\n\n\n\n for entry in entries {\n\n let entry = try_with!(entry, \"failed to read /dev\");\n\n if let Some(name) = entry.file_name().to_str() {\n\n if let Some(stripped) = name.strip_prefix(\"hvc\") {\n\n if let Ok(num) = stripped.parse::<usize>() {\n\n heap.push(num);\n\n }\n\n }\n\n }\n\n }\n\n for num in heap {\n\n let name = format!(\"/dev/hvc{}\", num);\n\n match fcntl::open(name.as_str(), OFlag::O_RDWR, stat::Mode::empty()) {\n\n Ok(fd) => return Ok(unsafe { File::from_raw_fd(fd) }),\n\n Err(Errno::ENODEV) => {}\n\n e => {\n\n try_with!(e, \"failed to open {}\", &name);\n\n }\n\n };\n\n }\n\n bail!(\"cannot find vmsh console device in /dev\");\n\n}\n\n\n", "file_path": "src/stage2/src/console.rs", "rank": 43, "score": 119862.99536719633 }, { "content": "pub fn attach_seize(tid: Pid) -> Result<()> {\n\n // seize seems to be more modern and versatile than `ptrace::attach()`: continue, stop and\n\n // detach from tracees at (almost) any time\n\n try_with!(\n\n ptrace::seize(tid, ptrace::Options::PTRACE_O_TRACESYSGOOD),\n\n \"cannot seize the process\"\n\n );\n\n try_with!(interrupt(tid), \"cannot interrupt/stop the tracee\");\n\n\n\n try_with!(waitpid(tid, Some(WaitPidFlag::WSTOPPED)), \"waitpid failed\");\n\n\n\n Ok(())\n\n}\n\n\n", "file_path": "src/tracer/ptrace.rs", "rank": 44, "score": 117973.50646241095 }, { "content": "pub fn setup(sender: &SyncSender<()>) -> Result<()> {\n\n try_with!(SIGNAL_SENDER.lock(), \"cannot get lock\").replace(sender.clone());\n\n\n\n let sig_action = signal::SigAction::new(\n\n signal::SigHandler::Handler(signal_handler),\n\n signal::SaFlags::empty(),\n\n signal::SigSet::empty(),\n\n );\n\n\n\n unsafe {\n\n try_with!(\n\n signal::sigaction(signal::SIGINT, &sig_action),\n\n \"unable to register SIGINT handler\"\n\n );\n\n try_with!(\n\n signal::sigaction(signal::SIGTERM, &sig_action),\n\n \"unable to register SIGTERM handler\"\n\n );\n\n }\n\n Ok(())\n\n}\n", "file_path": "src/signal_handler.rs", "rank": 45, "score": 117973.50646241095 }, { "content": "pub fn generate_coredump(opts: &CoredumpOptions) -> Result<()> {\n\n println!(\"Write {}\", opts.path.display());\n\n let mut core_file = try_with!(\n\n OpenOptions::new()\n\n .read(true)\n\n .write(true)\n\n .create(true)\n\n .open(&opts.path),\n\n \"cannot open core_file: {}\",\n\n opts.path.display()\n\n );\n\n let vm = try_with!(\n\n kvm::hypervisor::get_hypervisor(opts.pid),\n\n \"cannot get vms for process {}\",\n\n opts.pid\n\n );\n\n vm.stop()?;\n\n let maps = vm.get_maps()?;\n\n let res = vm\n\n .vcpus\n", "file_path": "src/coredump.rs", "rank": 46, "score": 117973.50646241095 }, { "content": "pub fn rebuild_if_dir_changed(dir: &Path) {\n\n visit_dirs(dir, &|e| {\n\n println!(\"cargo:rerun-if-changed={}\", e.path().display())\n\n })\n\n .expect(\"failed to list dir\");\n\n}\n", "file_path": "src/build-utils/src/lib.rs", "rank": 47, "score": 117928.71329831431 }, { "content": "pub fn find_vmsh_blockdev() -> Result<BlockDevice> {\n\n let dir = try_with!(\n\n fs::read_dir(\"/sys/block\"),\n\n \"failed to read /sys/block directory\"\n\n );\n\n\n\n for entry in dir {\n\n let entry = try_with!(entry, \"error while reading /proc\");\n\n let serial_path = entry.path().join(\"serial\");\n\n match fs::read_to_string(&serial_path) {\n\n // not all block devices implement serial\n\n Ok(s) if s == \"vmsh0\" => s,\n\n _ => continue,\n\n };\n\n let dev_path = entry.path().join(\"dev\");\n\n let major_minor = try_with!(\n\n fs::read_to_string(&dev_path),\n\n \"cannot read device number from {}\",\n\n dev_path.display()\n\n );\n", "file_path": "src/stage2/src/block.rs", "rank": 48, "score": 117928.71329831431 }, { "content": "/// Retrieves error value from pointer\n\nfn err_value(ptr: *const c_void) -> c_long {\n\n ptr as c_long\n\n}\n\n\n", "file_path": "src/stage1/src/lib.rs", "rank": 49, "score": 116812.1644750963 }, { "content": "#[must_use]\n\npub fn pid_path(pid: Pid) -> PathBuf {\n\n PathBuf::from(\"/proc\").join(pid.as_raw().to_string())\n\n}\n\n\n", "file_path": "src/tracer/proc.rs", "rank": 50, "score": 115923.87123181416 }, { "content": "pub fn setup_bindmounts(mounts: &[&str]) -> Result<()> {\n\n for m in mounts {\n\n let mountpoint_buf = PathBuf::from(\"/\").join(m);\n\n let mountpoint = mountpoint_buf.as_path();\n\n let source_buf = PathBuf::from(\"/var/lib/vmsh\").join(m);\n\n let source = source_buf.as_path();\n\n\n\n let source_stat = match metadata(source) {\n\n Err(e) => {\n\n if e.kind() == io::ErrorKind::NotFound {\n\n continue;\n\n }\n\n return try_with!(\n\n Err(e),\n\n \"failed to get metadata of path {}\",\n\n source.display()\n\n );\n\n }\n\n Ok(data) => data,\n\n };\n", "file_path": "src/stage2/src/mountns.rs", "rank": 51, "score": 115919.35747342795 }, { "content": "pub fn drop(inheritable_capabilities: u64) -> Result<()> {\n\n // we need chroot at the moment for `exec` command\n\n let inheritable = inheritable_capabilities | 1 << CAP_SYS_CHROOT | 1 << CAP_SYS_PTRACE;\n\n let last_capability = try_with!(last_capability(), \"failed to read capability limit\");\n\n\n\n for cap in 0..last_capability {\n\n if (inheritable & (1 << cap)) == 0 {\n\n // TODO: do not ignore result\n\n let _ = prctl(libc::PR_CAPBSET_DROP, cap, 0, 0, 0);\n\n }\n\n }\n\n Ok(())\n\n}\n", "file_path": "src/stage2/src/capabilities.rs", "rank": 52, "score": 115919.35747342795 }, { "content": "fn parse_flags(fields: &[u8]) -> (ProtFlags, MapFlags) {\n\n assert!(fields.len() == 4);\n\n (\n\n (if fields[0] == b'r' {\n\n ProtFlags::PROT_READ\n\n } else {\n\n ProtFlags::empty()\n\n }) | (if fields[1] == b'w' {\n\n ProtFlags::PROT_WRITE\n\n } else {\n\n ProtFlags::empty()\n\n }) | (if fields[2] == b'x' {\n\n ProtFlags::PROT_EXEC\n\n } else {\n\n ProtFlags::empty()\n\n }),\n\n if fields[3] == b'p' {\n\n MapFlags::MAP_PRIVATE\n\n } else {\n\n MapFlags::MAP_SHARED\n\n },\n\n )\n\n}\n\n\n", "file_path": "src/tracer/proc.rs", "rank": 53, "score": 114701.95550008089 }, { "content": "pub fn from_tracer(t: Tracer) -> Result<Process> {\n\n let (saved_regs, saved_text) = init(&t.threads, t.process_idx)?;\n\n\n\n Ok(Process {\n\n process_idx: t.process_idx,\n\n saved_regs,\n\n saved_text,\n\n threads: Some(t.threads),\n\n owner: t.owner,\n\n })\n\n}\n\n\n", "file_path": "src/tracer/inject_syscall.rs", "rank": 54, "score": 114570.71033693082 }, { "content": "pub fn supported_namespaces() -> Result<HashSet<String>> {\n\n let mut namespaces = HashSet::new();\n\n let entries = try_with!(\n\n fs::read_dir(PathBuf::from(\"/proc/self/ns\")),\n\n \"failed to open directory /proc/self/ns\"\n\n );\n\n for entry in entries {\n\n let entry = try_with!(entry, \"failed to read directory /proc/self/ns\");\n\n if let Ok(name) = entry.file_name().into_string() {\n\n namespaces.insert(name);\n\n }\n\n }\n\n Ok(namespaces)\n\n}\n\n\n\nimpl Kind {\n\n pub fn open(&'static self, pid: unistd::Pid) -> Result<Namespace> {\n\n let buf = self.path(pid);\n\n let path = buf.to_str().unwrap();\n\n let file = try_with!(File::open(path), \"failed to open namespace file '{}'\", path);\n", "file_path": "src/stage2/src/namespace.rs", "rank": 55, "score": 113985.07540454593 }, { "content": "fn get_index(virt: u64, level: u8) -> u64 {\n\n virt >> get_shift(level) & 0x1FF\n\n}\n\n\n", "file_path": "src/page_table.rs", "rank": 56, "score": 113207.32190331368 }, { "content": "pub fn openpid(pid: Pid) -> Result<PidHandle> {\n\n let path = pid_path(pid);\n\n let fd = try_with!(\n\n fcntl::open(\n\n &path,\n\n OFlag::O_PATH | OFlag::O_NOFOLLOW | OFlag::O_CLOEXEC,\n\n stat::Mode::empty(),\n\n ),\n\n \"failed to open: {}\",\n\n path.display()\n\n );\n\n let file = unsafe { File::from_raw_fd(fd) };\n\n\n\n Ok(PidHandle { pid, file })\n\n}\n\n\n", "file_path": "src/tracer/proc.rs", "rank": 57, "score": 112516.56134794782 }, { "content": "pub fn attach(pid: Pid) -> Result<Process> {\n\n let (threads, process_idx) = ptrace::attach_all_threads(pid)?;\n\n let (saved_regs, saved_text) = init(&threads, process_idx)?;\n\n\n\n Ok(Process {\n\n process_idx,\n\n saved_regs,\n\n saved_text,\n\n threads: Some(threads),\n\n owner: Some(current().id()),\n\n })\n\n}\n\n\n\nmacro_rules! syscall_args {\n\n ($regs:expr, $nr:expr) => {\n\n ($regs).prepare_syscall(&[$nr, 0, 0, 0, 0, 0, 0])\n\n };\n\n\n\n ($regs:expr, $nr:expr, $a1:expr) => {\n\n ($regs).prepare_syscall(&[$nr, $a1 as c_ulong, 0, 0, 0, 0, 0])\n", "file_path": "src/tracer/inject_syscall.rs", "rank": 58, "score": 112516.56134794782 }, { "content": "pub fn stage_dir(name: &str) -> PathBuf {\n\n let mut dir = env::current_dir().expect(\"cannot get current working directory\");\n\n dir.push(\"src\");\n\n dir.push(name);\n\n dir\n\n}\n\n\n\n#[macro_export]\n\nmacro_rules! ok(($expression:expr) => ($expression.unwrap()));\n\n\n\n#[macro_export]\n\nmacro_rules! log {\n\n ($fmt:expr) => (println!(concat!(\"vmsh/build.rs:{}: \", $fmt), line!()));\n\n ($fmt:expr, $($arg:tt)*) => (println!(concat!(\"vmsh/build.rs:{}: \", $fmt),\n\n line!(), $($arg)*));\n\n}\n\n\n", "file_path": "src/build-utils/src/lib.rs", "rank": 59, "score": 112160.46570644087 }, { "content": "fn set_blocking(file: &File, blocking: bool) -> Result<()> {\n\n let fd = file.as_raw_fd();\n\n let flags = try_with!(fcntl::fcntl(fd, fcntl::F_GETFL), \"fnctl(F_GETFL) failed\");\n\n let flags = OFlag::from_bits_truncate(flags);\n\n\n\n let flags = if blocking {\n\n flags & !OFlag::O_NONBLOCK\n\n } else {\n\n flags | OFlag::O_NONBLOCK\n\n };\n\n try_with!(\n\n fcntl::fcntl(fd, fcntl::F_SETFL(flags)),\n\n \"fcntl(F_SETFL) failed\"\n\n );\n\n\n\n Ok(())\n\n}\n\n\n", "file_path": "src/stage2/src/block.rs", "rank": 60, "score": 111338.52919108648 }, { "content": "pub fn get_hypervisor(pid: Pid) -> Result<Hypervisor> {\n\n let handle = try_with!(openpid(pid), \"cannot open handle in proc\");\n\n\n\n let (vm_fds, mut vcpus) = try_with!(find_vm_fd(&handle), \"failed to access kvm fds\");\n\n if vm_fds.is_empty() {\n\n bail!(\"no KVM-VMs found. If this is qemu, does it enable KVM?\");\n\n }\n\n if vm_fds.len() > 1 {\n\n bail!(\"multiple VMs found, this is not supported yet.\");\n\n }\n\n\n\n let tracee = Hypervisor::attach(pid, vm_fds[0]);\n\n let vcpu_maps = try_with!(tracee.get_vcpu_maps(), \"cannot get vcpufd memory maps\");\n\n if vcpus.is_empty() {\n\n bail!(\"found KVM instance but no VCPUs\");\n\n }\n\n if vcpu_maps.is_empty() {\n\n bail!(\"found VCPUs but no mappings of their fds\");\n\n }\n\n VCPU::match_maps(&mut vcpus, &vcpu_maps);\n\n Ok(Hypervisor {\n\n pid,\n\n tracee: Arc::new(RwLock::new(tracee)),\n\n vm_fd: vm_fds[0],\n\n vcpus,\n\n wrapper: Mutex::new(None),\n\n transfer_ctx: Mutex::new(None),\n\n })\n\n}\n", "file_path": "src/kvm/hypervisor/hypervisor.rs", "rank": 61, "score": 110582.2792790658 }, { "content": "#[allow(dead_code)]\n\npub fn read_open_sockets() -> Result<Vec<PathBuf>> {\n\n let file = try_with!(File::open(\"/proc/net/unix\"), \"cannot open /proc/net/unix\");\n\n\n\n let mut paths = vec![];\n\n\n\n for line in BufReader::new(file).lines().skip(1) {\n\n let line = try_with!(line, \"failed to read /proc/net/unix\");\n\n let fields: Vec<&str> = line.splitn(7, ' ').collect();\n\n if fields.len() != 8 || fields[7].starts_with('@') {\n\n continue;\n\n }\n\n paths.push(PathBuf::from(fields[7]));\n\n }\n\n\n\n Ok(paths)\n\n}\n", "file_path": "src/stage2/src/procfs/unix.rs", "rank": 62, "score": 110436.45800668567 }, { "content": "#[panic_handler]\n\nfn panic(_info: &PanicInfo) -> ! {\n\n // static assertion to make sure our code never uses a panic\n\n extern \"C\" {\n\n #[cfg_attr(\n\n target_family = \"unix\",\n\n link_name = \"\\n\\n\\x1b[s\\x1b[1000D\\x1b[0;31m\\x1b[1merror\\x1b[0m\\x1b[1m: the static assertion that no panics are present has failed\\x1b[0m\\x1b[u\\n\\n\"\n\n )]\n\n #[cfg_attr(\n\n not(target_family = \"unix\"),\n\n link_name = \"\\n\\nerror: the static assertion that no panics are present has failed\\n\\n\"\n\n )]\n\n fn never_panic() -> !;\n\n }\n\n\n\n unsafe { never_panic() }\n\n}\n\n\n", "file_path": "src/stage1/src/lib.rs", "rank": 63, "score": 110318.9375942028 }, { "content": "pub fn parse_selinux_context(p: Pid) -> Result<String> {\n\n let options = try_with!(find_mount_options(p), \"failed to parse mount options of /\");\n\n let needle = \"context=\\\"\";\n\n if let Some(index) = options.find(needle) {\n\n if let Some(context) = options[(index + needle.len())..].splitn(2, '\"').next() {\n\n return Ok(String::from(context));\n\n } else {\n\n bail!(\"missing quotes selinux context: {}\", options);\n\n };\n\n }\n\n bail!(\"no selinux mount option found for / entry: {}\", options)\n\n}\n", "file_path": "src/stage2/src/mount_context.rs", "rank": 64, "score": 108757.66958096073 }, { "content": "fn guest_add_mem(pid: Pid, re_get_slots: bool) -> Result<()> {\n\n let memslots_a_len;\n\n\n\n {\n\n let vm = try_with!(get_hypervisor(pid), \"cannot get vms for process {}\", pid);\n\n vm.stop()?;\n\n\n\n // count memslots\n\n let memslots_a = vm.get_maps()?;\n\n memslots_a_len = memslots_a.len();\n\n memslots_a.iter().for_each(|map| {\n\n println!(\n\n \"vm mem: {:#x} -> {:#x} (physical: {:#x}, flags: {:?} | {:?})\",\n\n map.start, map.end, map.phys_addr, map.prot_flags, map.map_flags,\n\n )\n\n });\n\n\n\n // add memslot\n\n let vm_mem: PhysMem<u64> = vm.vm_add_mem::<u64>(0xd0000000, size_of::<u64>(), false)?;\n\n println!(\"--\");\n", "file_path": "examples/test_ioctls.rs", "rank": 65, "score": 107775.63532947196 }, { "content": "pub fn fetch_mappings(pid: Pid) -> Result<Vec<Mapping>> {\n\n let handle = try_with!(openpid(pid), \"cannot open handle in proc\");\n\n let mappings = try_with!(handle.maps(), \"cannot read process maps\");\n\n Ok(mappings)\n\n}\n\n\n", "file_path": "src/kvm/memslots.rs", "rank": 66, "score": 107616.2056509735 }, { "content": "pub fn get_maps(tracee: &Tracee) -> Result<Vec<Mapping>> {\n\n let mut module = bpf_prog(tracee.pid())?;\n\n try_with!(\n\n Kprobe::new()\n\n .handler(\"kvm_vm_ioctl\")\n\n .function(\"kvm_vm_ioctl\")\n\n .attach(&mut module),\n\n \"failed to install kprobe\"\n\n );\n\n let table = try_with!(module.table(\"memslots\"), \"failed to get perf event table\");\n\n\n\n let (sender, receiver) = channel();\n\n let builder = PerfMapBuilder::new(table, move || {\n\n let sender = sender.clone();\n\n Box::new(move |x| {\n\n let head = x.as_ptr() as *const size_t;\n\n let size = unsafe { ptr::read(head) };\n\n let memslots_slice = unsafe { make_slice(head.add(1) as *const MemSlot, size) };\n\n sender\n\n .send(memslots_slice.to_vec())\n", "file_path": "src/kvm/memslots.rs", "rank": 67, "score": 107616.2056509735 }, { "content": "pub fn status(target_pid: Pid) -> Result<ProcStatus> {\n\n let path = get_path().join(target_pid.to_string()).join(\"status\");\n\n let file = try_with!(File::open(&path), \"failed to open {}\", path.display());\n\n\n\n let mut ns_pid: Option<Pid> = None;\n\n let mut inherited_caps: Option<u64> = None;\n\n let mut effective_caps: Option<u64> = None;\n\n\n\n let reader = BufReader::new(file);\n\n for line in reader.lines() {\n\n let line = try_with!(line, \"could not read {}\", path.display());\n\n let columns: Vec<&str> = line.split('\\t').collect();\n\n assert!(columns.len() >= 2);\n\n if columns[0] == \"NSpid:\" {\n\n if let Some(pid_string) = columns.last() {\n\n let pid = try_with!(\n\n pid_string.parse::<pid_t>(),\n\n \"read invalid pid from proc: '{}'\",\n\n columns[1]\n\n );\n", "file_path": "src/stage2/src/procfs/mod.rs", "rank": 68, "score": 107033.66188120554 }, { "content": "/// ordered list of the hypervisor memory mapped to [vcpu0fd, vcpu1fd, ...]\n\npub fn get_vcpu_maps(pid: Pid) -> Result<Vec<Mapping>> {\n\n let mappings = fetch_mappings(pid)?;\n\n let vcpu_maps = mappings.into_iter().filter(|m| {\n\n m.pathname\n\n .starts_with(hypervisor::VCPUFD_INODE_NAME_STARTS_WITH)\n\n });\n\n\n\n // we need a for loop, because we can not return errors from within a .sort() lambda.\n\n let mut taged_maps = vec![]; // (vcpunr, vcpu_map)\n\n for vcpu_map in vcpu_maps {\n\n let ao: Option<&str> = vcpu_map\n\n .pathname\n\n .strip_prefix(hypervisor::VCPUFD_INODE_NAME_STARTS_WITH);\n\n let astr: &str = require_with!(\n\n ao,\n\n \"vcpufd {} does not start with expected prefix\",\n\n vcpu_map.pathname,\n\n );\n\n let ai = try_with!(\n\n astr.parse::<u64>(),\n", "file_path": "src/kvm/memslots.rs", "rank": 69, "score": 105791.59595286843 }, { "content": "#[cfg(not(any(target_os = \"ios\", target_os = \"macos\")))]\n\npub fn mknodat<P: ?Sized + nix::NixPath>(\n\n dirfd: RawFd,\n\n path: &P,\n\n kind: stat::SFlag,\n\n perm: stat::Mode,\n\n dev: libc::dev_t,\n\n) -> nix::Result<()> {\n\n let res = path.with_nix_path(|cstr| unsafe {\n\n libc::mknodat(\n\n dirfd,\n\n cstr.as_ptr(),\n\n kind.bits() | perm.bits() as libc::mode_t,\n\n dev,\n\n )\n\n })?;\n\n\n\n Errno::result(res).map(drop)\n\n}\n", "file_path": "src/stage2/src/sys_ext/internal/mknodat.rs", "rank": 70, "score": 105402.15918449796 }, { "content": "fn parse_raw_info(raw: RawInfo) -> Result<SyscallInfo> {\n\n let info = SyscallInfo {\n\n arch: raw.arch,\n\n instruction_pointer: raw.instruction_pointer,\n\n stack_pointer: raw.stack_pointer,\n\n op: parse_raw_data(raw)?,\n\n };\n\n Ok(info)\n\n}\n\n\n", "file_path": "src/tracer/ptrace_syscall_info.rs", "rank": 71, "score": 105380.01576301386 }, { "content": "/// Simple trait to model the operation of signalling the driver about used events\n\n/// for the specified queue.\n\n// TODO: Does this need renaming to be relevant for packed queues as well?\n\npub trait SignalUsedQueue {\n\n // TODO: Should this return an error? This failing is not really recoverable at the interface\n\n // level so the expectation is the implementation handles that transparently somehow.\n\n fn signal_used_queue(&self, index: u16);\n\n}\n\n\n\n/// Uses a single irqfd as the basis of signalling any queue (useful for the MMIO transport,\n\n/// where a single interrupt is shared for everything).\n\npub struct SingleFdSignalQueue {\n\n pub irqfd: Arc<EventFd>,\n\n pub interrupt_status: Arc<AtomicU8>,\n\n pub ack_handler: Arc<Mutex<IrqAckHandler>>,\n\n}\n\n\n\nimpl SignalUsedQueue for SingleFdSignalQueue {\n\n fn signal_used_queue(&self, _index: u16) {\n\n log::trace!(\"irqfd << {}\", _index);\n\n self.interrupt_status\n\n .fetch_or(VIRTIO_MMIO_INT_VRING, Ordering::SeqCst);\n\n if let Err(e) = self.irqfd.write(1) {\n", "file_path": "src/devices/virtio/mod.rs", "rank": 72, "score": 104204.73535182598 }, { "content": "pub fn read_profile(pid: Pid) -> Result<Option<LSMProfile>> {\n\n let kind = check_type()?;\n\n\n\n if let Some(kind) = kind {\n\n let target_path = kind.profile_path(Some(pid));\n\n let target_label = try_with!(\n\n read_proclabel(&target_path, &kind),\n\n \"failed to get security label of target process\"\n\n );\n\n\n\n let own_path = kind.profile_path(None);\n\n let own_label = try_with!(\n\n read_proclabel(&own_path, &kind),\n\n \"failed to get own security label\"\n\n );\n\n\n\n if target_label == own_label {\n\n // nothing to do\n\n return Ok(None);\n\n }\n", "file_path": "src/stage2/src/lsm.rs", "rank": 73, "score": 104067.58825311324 }, { "content": "pub fn _tempdir(mut template: PathBuf) -> Result<TempDir> {\n\n template.push(\"vmsh.XXXXXX\");\n\n let mut bytes = template.into_os_string().into_vec();\n\n // null byte\n\n bytes.push(0);\n\n let res = unsafe { libc::mkdtemp(bytes.as_mut_ptr().cast()) };\n\n if res.is_null() {\n\n Err(Errno::last())\n\n } else {\n\n // remove null byte\n\n bytes.pop();\n\n let name = PathBuf::from(OsString::from_vec(bytes));\n\n Ok(TempDir { name: Some(name) })\n\n }\n\n}\n\n\n", "file_path": "src/ioutils/src/tmp.rs", "rank": 74, "score": 104067.58825311324 }, { "content": "pub fn run<F>(name: &str, mut configure: F)\n\nwhere\n\n F: FnMut(&mut Command) -> &mut Command,\n\n{\n\n let mut command = Command::new(name);\n\n let configured = configure(&mut command);\n\n log!(\"Executing {:?}\", configured);\n\n if !ok!(configured.status()).success() {\n\n panic!(\"failed to execute {:?}\", configured);\n\n }\n\n log!(\"Command {:?} finished successfully\", configured);\n\n}\n\n\n", "file_path": "src/build-utils/src/lib.rs", "rank": 75, "score": 101459.23204750443 }, { "content": "pub fn mkdir_p<P: AsRef<Path>>(path: &P) -> io::Result<()> {\n\n if let Err(e) = create_dir_all(path) {\n\n if e.kind() != io::ErrorKind::AlreadyExists {\n\n return Err(e);\n\n }\n\n }\n\n Ok(())\n\n}\n", "file_path": "src/stage2/src/dir.rs", "rank": 77, "score": 99147.56090793642 }, { "content": "fn parse_version_part(split: Option<&[u8]>, full_version: &str) -> Result<u16, ()> {\n\n if let Some(number) = split {\n\n if let Ok(num_str) = str::from_utf8(number) {\n\n if let Ok(num) = num_str.parse::<u16>() {\n\n return Ok(num);\n\n }\n\n }\n\n }\n\n printkln!(\"stage1: cannot parse version %s\", full_version.as_ptr());\n\n Err(())\n\n}\n\n\n\nunsafe fn get_kernel_version() -> Result<KernelVersion, ()> {\n\n let path = c_str!(\"/proc/sys/kernel/osrelease\").as_ptr() as *const i8;\n\n // might fail if the older kernel version has TCP disabled...\n\n let is_4_13_or_older =\n\n !ffi::__symbol_get(c_str!(\"tcp_prequeue\").as_ptr() as *const c_char).is_null();\n\n printkln!(\n\n \"stage1: detected old linux 4.13 version: %d\",\n\n is_4_13_or_older as c_int\n", "file_path": "src/stage1/src/lib.rs", "rank": 79, "score": 98886.519197643 }, { "content": "pub fn move_to(pid: unistd::Pid, target_pid: unistd::Pid) -> Result<()> {\n\n let cgroups = try_with!(\n\n get_cgroups(target_pid),\n\n \"failed to get cgroups of {}\",\n\n target_pid\n\n );\n\n let mountpoints = try_with!(get_mounts(), \"failed to get cgroup mountpoints\");\n\n for cgroup in cgroups {\n\n let p = cgroup_path(&cgroup, &mountpoints);\n\n if let Some(path) = p {\n\n match File::create(&path) {\n\n Ok(mut buffer) => {\n\n try_with!(\n\n write!(buffer, \"{}\", pid),\n\n \"failed to enter {} cgroup\",\n\n cgroup\n\n );\n\n }\n\n Err(err) => {\n\n eprintln!(\"failed to enter {} namespace: {}\", cgroup, err);\n\n }\n\n }\n\n }\n\n }\n\n Ok(())\n\n}\n", "file_path": "src/stage2/src/cgroup.rs", "rank": 80, "score": 97516.05821122884 }, { "content": "pub fn into_tracer(mut p: Process, vcpus: Vec<VCPU>) -> Result<Tracer> {\n\n let process_idx = p.process_idx;\n\n let threads = deinit(&mut p).expect(\"Process was deinited before it was dropped!\");\n\n Ok(Tracer {\n\n process_idx,\n\n threads,\n\n vcpus,\n\n owner: p.owner,\n\n })\n\n}\n\n\n", "file_path": "src/tracer/inject_syscall.rs", "rank": 81, "score": 97084.67948742508 }, { "content": "// TODO: Add a helper abstraction to rust-vmm for building the device configuration space.\n\n// The one we build below for the block device contains the minimally required `capacity` member,\n\n// but other fields can be present as well depending on the negotiated features.\n\nfn build_config_space<P: AsRef<Path>>(path: P) -> Result<Vec<u8>> {\n\n // TODO: right now, the file size is computed by the StdioBackend as well. Maybe we should\n\n // create the backend as early as possible, and get the size information from there.\n\n let file_size = File::open(path)\n\n .map_err(Error::OpenFile)?\n\n .seek(SeekFrom::End(0))\n\n .map_err(Error::Seek)?;\n\n // If the file size is actually not a multiple of sector size, then data at the very end\n\n // will be ignored.\n\n let num_sectors = file_size >> SECTOR_SHIFT;\n\n // This has to be in little endian btw.\n\n Ok(num_sectors.to_le_bytes().to_vec())\n\n}\n\n\n\n// Arguments required when building a block device.\n\npub struct BlockArgs<'a, M, B> {\n\n pub common: CommonArgs<'a, M, B>,\n\n pub file_path: PathBuf,\n\n pub read_only: bool,\n\n pub root_device: bool,\n", "file_path": "src/devices/virtio/block/mod.rs", "rank": 82, "score": 95079.50201103266 }, { "content": "fn get_first_allocation(hv: &Arc<Hypervisor>) -> Result<usize> {\n\n let host_cpuid = unsafe { core::arch::x86_64::__cpuid(ADDRESS_SIZE_FUNCTION) };\n\n let vm_cpuid = try_with!(hv.get_cpuid2(&hv.vcpus[0]), \"cannot get cpuid2\");\n\n // Get Extended Processor Info and Feature Bits\n\n let extended_cpu_info_entry = vm_cpuid\n\n .entries\n\n .iter()\n\n .find(|c| c.function == EXTEND_CPU_INFO_FUNCTION);\n\n let extended_cpu_info_entry = require_with!(\n\n extended_cpu_info_entry,\n\n \"could not get the vm's cpuid entry for extended processor info and features bits ({})\",\n\n EXTEND_CPU_INFO_FUNCTION\n\n );\n\n if extended_cpu_info_entry.edx & LONG_MODE == 0 {\n\n bail!(\"VM is not 64-bit\");\n\n }\n\n\n\n // Get Virtual and Physical address sizes\n\n let address_size_entry = vm_cpuid\n\n .entries\n", "file_path": "src/kvm/allocator.rs", "rank": 83, "score": 87030.35100592494 }, { "content": "fn get_page_table_addr(sregs: &kvmb::kvm_sregs) -> usize {\n\n (if sregs.cr4 & X86_CR4_PCIDE != 0 {\n\n sregs.cr3 & PHYS_ADDR_MASK\n\n } else {\n\n sregs.cr3\n\n }) as usize\n\n}\n\n\n\n/// Contineous physical memory that is mapped virtual contineous\n\n#[derive(Clone, Debug)]\n\npub struct MappedMemory {\n\n pub phys_start: PhysAddr,\n\n pub virt_start: usize,\n\n pub len: usize,\n\n pub prot: ProtFlags,\n\n}\n\n\n\nimpl MappedMemory {\n\n pub fn contains(&self, addr: usize) -> bool {\n\n self.virt_start < addr && addr < self.virt_start + self.len\n\n }\n\n}\n\n\n", "file_path": "src/guest_mem.rs", "rank": 84, "score": 86855.5096953691 }, { "content": "pub fn process_write<T: Sized + Copy>(pid: Pid, addr: *mut c_void, val: &T) -> Result<()> {\n\n remote_mem::process_write(pid, addr, val).map_err(|e| simple_error!(\"{}\", e))\n\n}\n\n\n\n#[derive(Debug)]\n\npub struct SendPhantom<T> {\n\n phantom: PhantomData<T>,\n\n}\n\n\n\nimpl<T> Default for SendPhantom<T> {\n\n fn default() -> Self {\n\n Self {\n\n phantom: PhantomData,\n\n }\n\n }\n\n}\n\n\n\nunsafe impl<T> Send for SendPhantom<T> {}\n\nunsafe impl<T> Sync for SendPhantom<T> {}\n\n\n", "file_path": "src/kvm/hypervisor/memory.rs", "rank": 85, "score": 84676.0269249647 }, { "content": "fn find_loadable(loadables: &mut [Loadable], addr: usize) -> Option<&mut Loadable> {\n\n loadables\n\n .iter_mut()\n\n .find(|loadable| loadable.mapping.contains(addr))\n\n}\n\n\n\nimpl<'a> Loader<'a> {\n\n pub fn new(\n\n binary: &'a [u8],\n\n kernel: &'a Kernel,\n\n return_address: usize,\n\n allocator: &'a mut PhysMemAllocator,\n\n ) -> Result<Loader<'a>> {\n\n let elf = try_core_res!(ElfBinary::new(binary), \"cannot parse elf binary\");\n\n let dyn_symbol_section = require_with!(\n\n elf.file.find_section_by_name(\".dynsym\"),\n\n \"binary has no .dynsym section\"\n\n );\n\n let dyn_symbol_table = dyn_symbol_section.get_data(&elf.file)?;\n\n let dyn_syms = match dyn_symbol_table {\n", "file_path": "src/loader.rs", "rank": 86, "score": 81364.68755169699 }, { "content": "/// save and overwrite main thread state\n\nfn init(threads: &[ptrace::Thread], process_idx: usize) -> Result<(Regs, c_long)> {\n\n let saved_regs = try_with!(\n\n threads[process_idx].getregs(),\n\n \"cannot get registers for main process ({})\",\n\n threads[process_idx].tid\n\n );\n\n let ip = saved_regs.ip();\n\n let saved_text = try_with!(\n\n threads[process_idx].read(ip as *mut c_void),\n\n \"cannot get text for main process\"\n\n );\n\n try_with!(\n\n unsafe { threads[process_idx].write(ip as *mut c_void, cpu::SYSCALL_TEXT as *mut c_void) },\n\n \"cannot patch syscall instruction\"\n\n );\n\n\n\n Ok((saved_regs, saved_text))\n\n}\n\n\n", "file_path": "src/tracer/inject_syscall.rs", "rank": 87, "score": 77999.38931402906 }, { "content": "fn main() {\n\n let srcs = [\"build.rs\", \"trampoline.S\"];\n\n\n\n for src in &srcs {\n\n println!(\"cargo:rerun-if-changed=src/stage1/{}\", src);\n\n }\n\n\n\n let stage1_dir = stage_dir(\"stage1\");\n\n rebuild_if_dir_changed(&stage1_dir.join(\"src\"));\n\n\n\n let stage2_dir = stage_dir(\"stage2\");\n\n rebuild_if_dir_changed(&stage2_dir.join(\"src\"));\n\n\n\n run(\"cargo\", |command| {\n\n command\n\n .arg(\"build\")\n\n .arg(\"--release\")\n\n .current_dir(&stage1_dir)\n\n });\n\n copy_out(\n\n &stage1_dir\n\n .join(\"target\")\n\n .join(\"release\")\n\n .join(\"libstage1.so\"),\n\n );\n\n}\n", "file_path": "build.rs", "rank": 88, "score": 77460.78610536792 }, { "content": "fn dump_mappings(\n\n pid: Pid,\n\n core_file: &mut File,\n\n core_size: off_t,\n\n file_offset: off_t,\n\n maps: &[Mapping],\n\n) -> Result<()> {\n\n let buf_size = core_size - file_offset;\n\n let res = unsafe {\n\n mmap(\n\n ptr::null_mut::<c_void>(),\n\n buf_size as usize,\n\n ProtFlags::PROT_WRITE,\n\n MapFlags::MAP_SHARED,\n\n core_file.as_raw_fd(),\n\n file_offset,\n\n )\n\n };\n\n let raw_buf = try_with!(res, \"cannot mmap core file\");\n\n let buf = unsafe { from_raw_parts_mut(raw_buf as *mut u8, buf_size as usize) };\n", "file_path": "src/coredump.rs", "rank": 89, "score": 74289.27786738465 }, { "content": "fn main() {\n\n env_logger::Builder::from_env(env_logger::Env::default().default_filter_or(\"info\")).init();\n\n\n\n let app = App::new(\"test_ioctls\")\n\n .about(\"Something between integration and unit test to be used by pytest.\")\n\n .subcommand(subtest(\"alloc_mem\"))\n\n .subcommand(subtest(\"inject\"))\n\n .subcommand(subtest(\"guest_add_mem\"))\n\n .subcommand(subtest(\"guest_add_mem_get_maps\"))\n\n .subcommand(subtest(\"fd_transfer\"))\n\n .subcommand(subtest(\"cpuid2\"))\n\n .subcommand(subtest(\"guest_userfaultfd\"))\n\n .subcommand(subtest(\"guest_kvm_exits\"))\n\n .subcommand(subtest(\"vcpu_maps\"))\n\n .subcommand(subtest(\"ioregionfd\"))\n\n .subcommand(subtest(\"guest_ioeventfd\"));\n\n\n\n let matches = app.get_matches();\n\n let subcommand_name = matches.subcommand_name().expect(\"subcommad required\");\n\n let subcommand_matches = matches.subcommand_matches(subcommand_name).expect(\"foo\");\n", "file_path": "examples/test_ioctls.rs", "rank": 90, "score": 74289.27786738465 }, { "content": "fn stage1_thread(\n\n driver_status: DriverStatus,\n\n hv: &Hypervisor,\n\n should_stop: Arc<AtomicBool>,\n\n) -> Result<()> {\n\n let mut initialized = false;\n\n loop {\n\n match try_with!(driver_status.check(hv), \"cannot check driver state\") {\n\n DeviceState::Initializing => {\n\n if !initialized {\n\n info!(\"stage1 driver initializing...\");\n\n }\n\n initialized = true;\n\n }\n\n DeviceState::Undefined => {}\n\n DeviceState::Terminating => {\n\n bail!(\"guest driver is in unexpecting terminating state\");\n\n }\n\n DeviceState::Error => {\n\n bail!(\"guest driver failed with error\");\n", "file_path": "src/stage1.rs", "rank": 91, "score": 74289.27786738465 }, { "content": "fn write_corefile(\n\n pid: Pid,\n\n core_file: &mut File,\n\n maps: &[Mapping],\n\n vcpus: &[VcpuState],\n\n) -> Result<()> {\n\n // +1 == PT_NOTE section\n\n let ehdr = elf_header((maps.len() + 1) as Elf_Half);\n\n\n\n let metadata_size = size_of::<Ehdr>() + (size_of::<Phdr>() * ehdr.e_phnum as usize);\n\n let mut core_size = metadata_size;\n\n\n\n let pt_note_size = note_size::<elf_prpsinfo>()\n\n + vcpus.len()\n\n * (note_size::<core_user>() + note_size::<elf_prstatus>() + note_size::<FpuRegs>());\n\n let mut section_headers = vec![pt_note_header(core_size as Elf_Off, pt_note_size as u64)];\n\n core_size += pt_note_size;\n\n core_size = page_align(core_size);\n\n\n\n for m in maps {\n", "file_path": "src/coredump.rs", "rank": 92, "score": 74289.27786738465 }, { "content": "fn main() {\n\n let stage2_dir = stage_dir(\"../../stage2\");\n\n let target_arch = env::var(\"CARGO_CFG_TARGET_ARCH\").expect(\"CARGO_CFG_TARGET_ARCH not set\");\n\n let target = format!(\"{}-unknown-linux-musl\", target_arch);\n\n rebuild_if_dir_changed(&stage2_dir.join(\"src\"));\n\n\n\n let out_var = env::var_os(\"OUT_DIR\").expect(\"OUT_DIR is not set\");\n\n let out_dir = Path::new(&out_var);\n\n println!(\"cargo:rustc-link-search={}\", out_dir.display());\n\n\n\n Build::new().file(\"trampoline.S\").compile(\"trampoline\");\n\n println!(\"cargo:rerun-if-changed=trampoline.S\");\n\n\n\n run(\"cargo\", |command| {\n\n command\n\n .arg(\"build\")\n\n .arg(\"--release\")\n\n .arg(format!(\"--target={}\", target))\n\n .current_dir(&stage2_dir)\n\n });\n\n let bin = stage2_dir\n\n .join(\"target\")\n\n .join(target)\n\n .join(\"release\")\n\n .join(\"stage2\");\n\n copy_out(&bin);\n\n}\n", "file_path": "src/stage1/build.rs", "rank": 93, "score": 74289.27786738465 }, { "content": "fn main() {\n\n kmsg_log(\"[stage2] start\\n\");\n\n let args = env::args().collect::<Vec<_>>();\n\n let command = if args.len() > 2 {\n\n Some(args[1].clone())\n\n } else {\n\n None\n\n };\n\n // TODO\n\n let opts = Options {\n\n command,\n\n target_pid: Pid::from_raw(1),\n\n args: (&args[2..]).to_vec(),\n\n home: None,\n\n };\n\n if let Err(e) = run_stage2(&opts) {\n\n // print to both allocated pty and kmsg\n\n kmsg_log(&format!(\"[stage2] {}\\n\", e));\n\n eprintln!(\"{}\", &e);\n\n exit(1);\n\n }\n\n}\n", "file_path": "src/stage2/src/main.rs", "rank": 95, "score": 72871.78050768487 }, { "content": "fn event_thread(\n\n mut event_mgr: SubscriberEventManager,\n\n device_space: &DeviceContext,\n\n err_sender: &SyncSender<()>,\n\n) -> Result<InterrutableThread<(), Option<Arc<DeviceContext>>>> {\n\n let blkdev = device_space.blkdev.clone();\n\n let ack_handler = {\n\n let blkdev = try_with!(blkdev.lock(), \"cannot unlock thread\");\n\n blkdev.irq_ack_handler.clone()\n\n };\n\n log::debug!(\"event thread started\");\n\n\n\n let res = InterrutableThread::spawn(\n\n \"event-manager\",\n\n err_sender,\n\n move |_ctx: &Option<Arc<DeviceContext>>, should_stop: Arc<AtomicBool>| {\n\n loop {\n\n match event_mgr.run_with_timeout(EVENT_LOOP_TIMEOUT_MS) {\n\n Ok(nr) => {\n\n if nr != 0 {\n", "file_path": "src/devices/threads.rs", "rank": 98, "score": 72871.78050768487 }, { "content": "fn allocate_page_table(\n\n entry: &mut PageTableEntry,\n\n phys_addr: &mut PhysAddr,\n\n upsert_tables: &mut UpsertTable,\n\n) -> PageTableRef {\n\n let table = Rc::new(RefCell::new(PageTable::empty(phys_addr.clone())));\n\n // we just use the same flags the linux kernel expects for page tables\n\n entry.set_addr(\n\n phys_addr,\n\n PageTableFlags::PRESENT\n\n | PageTableFlags::ACCESSED\n\n | PageTableFlags::DIRTY\n\n | PageTableFlags::WRITABLE,\n\n );\n\n upsert_tables.insert(phys_addr.value, Rc::clone(&table));\n\n phys_addr.value += size_of_val(&RefCell::borrow(&table).entries);\n\n table\n\n}\n\n\n", "file_path": "src/page_table.rs", "rank": 99, "score": 71551.12715829871 } ]
Rust
nucleus/src/main.rs
metta-systems/vesper
7d03ea85a2d5ee77b7e8b36e5c9bf1ce41b77084
/* * SPDX-License-Identifier: BlueOak-1.0.0 * Copyright (c) Berkus Decker <[email protected]> */ #![no_std] #![no_main] #![feature(decl_macro)] #![feature(allocator_api)] #![feature(ptr_internals)] #![feature(format_args_nl)] #![feature(nonnull_slice_from_raw_parts)] #![feature(custom_test_frameworks)] #![test_runner(crate::tests::test_runner)] #![reexport_test_harness_main = "test_main"] #![deny(missing_docs)] #![deny(warnings)] #![allow(clippy::nonstandard_macro_braces)] #![allow(clippy::upper_case_acronyms)] #![allow(clippy::enum_variant_names)] #[cfg(not(target_arch = "aarch64"))] use architecture_not_supported_sorry; #[macro_use] pub mod arch; pub use arch::*; mod devices; mod macros; mod mm; mod panic; mod platform; #[cfg(feature = "qemu")] mod qemu; mod sync; #[cfg(test)] mod tests; mod write_to; use { crate::platform::rpi3::{ display::{Color, DrawError}, mailbox::{channel, Mailbox, MailboxOps}, vc::VC, }, cfg_if::cfg_if, }; entry!(kmain); static CONSOLE: sync::NullLock<devices::Console> = sync::NullLock::new(devices::Console::new()); static DMA_ALLOCATOR: sync::NullLock<mm::BumpAllocator> = sync::NullLock::new(mm::BumpAllocator::new( memory::map::virt::DMA_HEAP_START as usize, memory::map::virt::DMA_HEAP_END as usize, "Global DMA Allocator", )); fn print_mmu_state_and_features() { memory::mmu::print_features(); } fn init_mmu() { unsafe { memory::mmu::init().unwrap(); } println!("[!] MMU initialised"); print_mmu_state_and_features(); } fn init_exception_traps() { extern "C" { static __exception_vectors_start: u64; } unsafe { let exception_vectors_start: u64 = &__exception_vectors_start as *const _ as u64; arch::traps::set_vbar_el1_checked(exception_vectors_start) .expect("Vector table properly aligned!"); } println!("[!] Exception traps set up"); } #[cfg(not(feature = "noserial"))] fn init_uart_serial() { use crate::platform::rpi3::{gpio::GPIO, mini_uart::MiniUart, pl011_uart::PL011Uart}; let gpio = GPIO::default(); let uart = MiniUart::default(); let uart = uart.prepare(&gpio); CONSOLE.lock(|c| { c.replace_with(uart.into()); }); println!("[0] MiniUART is live!"); let uart = PL011Uart::default(); let mbox = Mailbox::default(); use crate::devices::console::ConsoleOps; CONSOLE.lock(|c| c.flush()); match uart.prepare(mbox, &gpio) { Ok(uart) => { CONSOLE.lock(|c| { c.replace_with(uart.into()); }); println!("[0] UART0 is live!"); } Err(_) => println!("[0] Error switching to PL011 UART, continue with MiniUART"), } } #[inline] pub fn kmain() -> ! { #[cfg(feature = "jtag")] jtag::wait_debugger(); init_mmu(); init_exception_traps(); #[cfg(not(feature = "noserial"))] init_uart_serial(); #[cfg(test)] test_main(); command_prompt(); reboot() } fn command_prompt() { 'cmd_loop: loop { let mut buf = [0u8; 64]; match CONSOLE.lock(|c| c.command_prompt(&mut buf)) { b"mmu" => init_mmu(), b"feats" => print_mmu_state_and_features(), #[cfg(not(feature = "noserial"))] b"uart" => init_uart_serial(), b"disp" => check_display_init(), b"trap" => check_data_abort_trap(), b"map" => arch::memory::print_layout(), b"led on" => set_led(true), b"led off" => set_led(false), b"help" => print_help(), b"end" => break 'cmd_loop, x => println!("[!] Unknown command {:?}, try 'help'", x), } } } fn print_help() { println!("Supported console commands:"); println!(" mmu - initialize MMU"); println!(" feats - print MMU state and supported features"); #[cfg(not(feature = "noserial"))] println!(" uart - try to reinitialize UART serial"); println!(" disp - try to init VC framebuffer and draw some text"); println!(" trap - trigger and recover from a data abort exception"); println!(" map - show kernel memory layout"); println!(" led [on|off] - change RPi LED status"); println!(" end - leave console and reset board"); } fn set_led(enable: bool) { let mut mbox = Mailbox::default(); let index = mbox.request(); let index = mbox.set_led_on(index, enable); let mbox = mbox.end(index); mbox.call(channel::PropertyTagsArmToVc) .map_err(|e| { println!("Mailbox call returned error {}", e); println!("Mailbox contents: {:?}", mbox); }) .ok(); } fn reboot() -> ! { cfg_if! { if #[cfg(feature = "qemu")] { println!("Bye, shutting down QEMU"); qemu::semihosting::exit_success() } else { use crate::platform::rpi3::power::Power; println!("Bye, going to reset now"); Power::new().reset() } } } fn check_display_init() { display_graphics() .map_err(|e| { println!("Error in display: {}", e); }) .ok(); } fn display_graphics() -> Result<(), DrawError> { if let Ok(mut display) = VC::init_fb(800, 600, 32) { println!("Display created"); display.clear(Color::black()); println!("Display cleared"); display.rect(10, 10, 250, 250, Color::rgb(32, 96, 64)); display.draw_text(50, 50, "Hello there!", Color::rgb(128, 192, 255))?; let mut buf = [0u8; 64]; let s = write_to::show(&mut buf, format_args!("Display width {}", display.width)); if s.is_err() { display.draw_text(50, 150, "Error displaying", Color::red())? } else { display.draw_text(50, 150, s.unwrap(), Color::white())? } display.draw_text(150, 50, "RED", Color::red())?; display.draw_text(160, 60, "GREEN", Color::green())?; display.draw_text(170, 70, "BLUE", Color::blue())?; } Ok(()) } fn check_data_abort_trap() { let big_addr: u64 = 3 * 1024 * 1024 * 1024; unsafe { core::ptr::read_volatile(big_addr as *mut u64) }; println!("[i] Whoa! We recovered from an exception."); } #[cfg(test)] mod main_tests { use super::*; #[test_case] fn test_data_abort_trap() { check_data_abort_trap() } }
/* * SPDX-License-Identifier: BlueOak-1.0.0 * Copyright (c) Berkus Decker <[email protected]> */ #![no_std] #![no_main] #![feature(decl_macro)] #![feature(allocator_api)] #![feature(ptr_internals)] #![feature(format_args_nl)] #![feature(nonnull_slice_from_raw_parts)] #![feature(custom_test_frameworks)] #![test_runner(crate::tests::test_runner)] #![reexport_test_harness_main = "test_main"] #![deny(missing_docs)] #![deny(warnings)] #![allow(clippy::nonstandard_macro_braces)] #![allow(clippy::upper_case_acronyms)] #![allow(clippy::enum_variant_names)] #[cfg(not(target_arch = "aarch64"))] use architecture_not_supported_sorry; #[macro_use] pub mod arch; pub use arch::*; mod devices; mod macros; mod mm; mod panic; mod platform; #[cfg(feature = "qemu")] mod qemu; mod sync; #[cfg(test)] mod tests; mod write_to; use { crate::platform::rpi3::{ display::{Color, DrawError}, mailbox::{channel, Mailbox, MailboxOps}, vc::VC, }, cfg_if::cfg_if, }; entry!(kmain); static CONSOLE: sync::NullLock<devices::Console> = sync::NullLock::new(devices::Console::new()); static DMA_ALLOCATOR: sync::NullLock<mm::BumpAllocator> = sync::NullLock::new(mm::BumpAllocator::new( memory::map::virt::DMA_HEAP_START as usize, memory::map::virt::DMA_HEAP_END as usize, "Global DMA Allocator", )); fn print_mmu_state_and_features() { memory::mmu::print_features(); } fn init_mmu() { unsafe { memory::mmu::init().unwrap(); } println!("[!] MMU initialised"); print_mmu_state_and_features(); } fn init_exception_traps() { extern "C" { static __exception_vectors_start: u64; } unsafe { let exception_vectors_start: u64 = &__exception_vectors_start as *const _ as u64; arch::traps::set_vbar_el1_checked(exception_vectors_start) .expect("Vector table properly aligned!"); } println!("[!] Exception traps set up"); } #[cfg(not(feature = "noserial"))] fn init_uart_serial() { use crate::platform::rpi3::{gpio::GPIO, mini_uart::MiniUart, pl011_uart::PL011Uart}; let gpio = GPIO::default(); let uart = MiniUart::default(); let uart = uart.prepare(&gpio); CONSOLE.lock(|c| { c.replace_with(uart.into()); }); println!("[0] MiniUART is live!"); let uart = PL011Uart::default(); let mbox = Mailbox::default(); use crate::devices::console::ConsoleOps; CONSOLE.lock(|c| c.flush()); match uart.prepare(mbox, &gpio) { Ok(uart) => { CONSOLE.lock(|c| { c.replace_with(uart.into()); }); println!("[0] UART0 is live!"); } Err(_) => println!("[0] Error switching to PL011 UART, continue with MiniUART"), } } #[inline] pub fn kmain() -> ! { #[cfg(feature = "jtag")] jtag::wait_debugger(); init_mmu(); init_exception_traps(); #[cfg(not(feature = "noserial"))] init_uart_serial(); #[cfg(test)] test_main(); command_prompt(); reboot() } fn command_prompt() { 'cmd_loop: loop { let mut buf = [0u8; 64]; match CONSOLE.lock(|c| c.command_prompt(&mut buf)) { b"mmu" => init_mmu(), b"feats" => print_mmu_state_and_features(), #[cfg(not(feature = "noserial"))] b"uart" => init_uart_serial(), b"disp" => check_display_init(), b"trap" => check_data_abort_trap(), b"map" => arch::memory::print_layout(), b"led on" => set_led(true), b"led off" => set_led(false), b"help" => print_help(), b"end" => break 'cmd_loop, x => println!("[!] Unknown command {:?}, try 'help'", x), } } } fn print_help() { println!("Supported console commands:"); println!(" mmu - initialize MMU"); println!(" feats - print MMU state and supported features"); #[cfg(not(feature = "noserial"))] println!(" uart - try to reinitialize UART serial"); println!(" disp - try to init VC framebuffer and draw some text"); println!(" trap - trigger and recover from a data abort exception"); println!(" map - show kernel memory layout"); println!(" led [on|off] - change RPi LED status"); println!(" end - leave console and reset board"); } fn set_led(enable: bool) { let mut mbox = Mailbox::default(); let index = m
println!("Mailbox call returned error {}", e); println!("Mailbox contents: {:?}", mbox); }) .ok(); } fn reboot() -> ! { cfg_if! { if #[cfg(feature = "qemu")] { println!("Bye, shutting down QEMU"); qemu::semihosting::exit_success() } else { use crate::platform::rpi3::power::Power; println!("Bye, going to reset now"); Power::new().reset() } } } fn check_display_init() { display_graphics() .map_err(|e| { println!("Error in display: {}", e); }) .ok(); } fn display_graphics() -> Result<(), DrawError> { if let Ok(mut display) = VC::init_fb(800, 600, 32) { println!("Display created"); display.clear(Color::black()); println!("Display cleared"); display.rect(10, 10, 250, 250, Color::rgb(32, 96, 64)); display.draw_text(50, 50, "Hello there!", Color::rgb(128, 192, 255))?; let mut buf = [0u8; 64]; let s = write_to::show(&mut buf, format_args!("Display width {}", display.width)); if s.is_err() { display.draw_text(50, 150, "Error displaying", Color::red())? } else { display.draw_text(50, 150, s.unwrap(), Color::white())? } display.draw_text(150, 50, "RED", Color::red())?; display.draw_text(160, 60, "GREEN", Color::green())?; display.draw_text(170, 70, "BLUE", Color::blue())?; } Ok(()) } fn check_data_abort_trap() { let big_addr: u64 = 3 * 1024 * 1024 * 1024; unsafe { core::ptr::read_volatile(big_addr as *mut u64) }; println!("[i] Whoa! We recovered from an exception."); } #[cfg(test)] mod main_tests { use super::*; #[test_case] fn test_data_abort_trap() { check_data_abort_trap() } }
box.request(); let index = mbox.set_led_on(index, enable); let mbox = mbox.end(index); mbox.call(channel::PropertyTagsArmToVc) .map_err(|e| {
function_block-random_span
[ { "content": "/// Print the kernel memory layout.\n\npub fn print_layout() {\n\n println!(\"[i] Kernel memory layout:\");\n\n\n\n for i in KERNEL_VIRTUAL_LAYOUT.iter() {\n\n println!(\"{}\", i);\n\n }\n\n}\n", "file_path": "nucleus/src/arch/aarch64/memory/mod.rs", "rank": 0, "score": 275727.9262218696 }, { "content": "/// Parse the ID_AA64MMFR0_EL1 register for runtime information about supported MMU features.\n\n/// Print the current state of TCR register.\n\npub fn print_features() {\n\n // use crate::cortex_a::regs::RegisterReadWrite;\n\n let sctlr = SCTLR_EL1.extract();\n\n\n\n if let Some(SCTLR_EL1::M::Value::Enable) = sctlr.read_as_enum(SCTLR_EL1::M) {\n\n println!(\"[i] MMU currently enabled\");\n\n }\n\n\n\n if let Some(SCTLR_EL1::I::Value::Cacheable) = sctlr.read_as_enum(SCTLR_EL1::I) {\n\n println!(\"[i] MMU I-cache enabled\");\n\n }\n\n\n\n if let Some(SCTLR_EL1::C::Value::Cacheable) = sctlr.read_as_enum(SCTLR_EL1::C) {\n\n println!(\"[i] MMU D-cache enabled\");\n\n }\n\n\n\n let mmfr = ID_AA64MMFR0_EL1.extract();\n\n\n\n if let Some(ID_AA64MMFR0_EL1::TGran4::Value::Supported) =\n\n mmfr.read_as_enum(ID_AA64MMFR0_EL1::TGran4)\n", "file_path": "nucleus/src/arch/aarch64/memory/mmu.rs", "rank": 1, "score": 275587.20107546455 }, { "content": "/// Align address downwards.\n\n///\n\n/// Returns the greatest x with alignment `align` so that x <= addr.\n\n/// The alignment must be a power of 2.\n\npub fn align_down(addr: u64, align: u64) -> u64 {\n\n assert!(align.is_power_of_two(), \"`align` must be a power of two\");\n\n addr & !(align - 1)\n\n}\n\n\n", "file_path": "nucleus/src/mm/mod.rs", "rank": 2, "score": 267325.7454085894 }, { "content": "/// Align address upwards.\n\n///\n\n/// Returns the smallest x with alignment `align` so that x >= addr.\n\n/// The alignment must be a power of 2.\n\npub fn align_up(addr: u64, align: u64) -> u64 {\n\n assert!(align.is_power_of_two(), \"`align` must be a power of two\");\n\n let align_mask = align - 1;\n\n if addr & align_mask == 0 {\n\n addr // already aligned\n\n } else {\n\n (addr | align_mask) + 1\n\n }\n\n}\n\n\n\n/// Calculate the next possible aligned address without sanity checking the\n\n/// input parameters.\n", "file_path": "nucleus/src/mm/mod.rs", "rank": 3, "score": 267325.7454085894 }, { "content": "#[inline]\n\npub fn loop_until<F: Fn() -> bool>(f: F) {\n\n loop {\n\n if f() {\n\n break;\n\n }\n\n asm::nop();\n\n }\n\n}\n", "file_path": "nucleus/src/arch/aarch64/mod.rs", "rank": 4, "score": 255755.8363233154 }, { "content": "fn cause_to_string(cause: u64) -> &'static str {\n\n if cause == ESR_EL1::EC::DataAbortCurrentEL.read(ESR_EL1::EC) {\n\n \"Data Alignment Check\"\n\n } else {\n\n \"Unknown\"\n\n }\n\n}\n\n\n\nregister_bitfields! {\n\n u64,\n\n /// ISS structure for Data Abort exceptions\n\n ISS_DA [\n\n /// Instruction Syndrome Valid. Indicates whether the syndrome information in ISS[23:14] is valid.\n\n /// (This includes SAS, SSE, SRT, SF, and AR)\n\n ISV OFFSET(24) NUMBITS(1) [],\n\n SAS OFFSET(22) NUMBITS(2) [\n\n Byte = 0b00,\n\n Halfword = 0b01,\n\n Word = 0b10,\n\n DoubleWord = 0b11\n", "file_path": "nucleus/src/arch/aarch64/traps.rs", "rank": 5, "score": 220766.80896847098 }, { "content": "fn iss_dfsc_to_string(iss: IssForDataAbort) -> &'static str {\n\n match iss.read_as_enum(ISS_DA::DFSC) {\n\n Some(ISS_DA::DFSC::Value::AddressSizeTL0) => \"Address size fault, level 0 of translation or translation table base register\",\n\n Some(ISS_DA::DFSC::Value::AddressSizeTL1) => \"Address size fault, level 1\",\n\n Some(ISS_DA::DFSC::Value::AddressSizeTL2) => \"Address size fault, level 2\",\n\n Some(ISS_DA::DFSC::Value::AddressSizeTL3) => \"Address size fault, level 3\",\n\n Some(ISS_DA::DFSC::Value::TranslationFaultTL0) => \"Translation fault, level 0\",\n\n Some(ISS_DA::DFSC::Value::TranslationFaultTL1) => \"Translation fault, level 1\",\n\n Some(ISS_DA::DFSC::Value::TranslationFaultTL2) => \"Translation fault, level 2\",\n\n Some(ISS_DA::DFSC::Value::TranslationFaultTL3) => \"Translation fault, level 3\",\n\n Some(ISS_DA::DFSC::Value::AccessFaultTL1) => \"Access flag fault, level 1\",\n\n Some(ISS_DA::DFSC::Value::AccessFaultTL2) => \"Access flag fault, level 2\",\n\n Some(ISS_DA::DFSC::Value::AccessFaultTL3) => \"Access flag fault, level 3\",\n\n Some(ISS_DA::DFSC::Value::PermissionFaultTL1) => \"Permission fault, level 1\",\n\n Some(ISS_DA::DFSC::Value::PermissionFaultTL2) => \"Permission fault, level 2\",\n\n Some(ISS_DA::DFSC::Value::PermissionFaultTL3) => \"Permission fault, level 3\",\n\n Some(ISS_DA::DFSC::Value::SyncExternalAbort) => \"Synchronous External abort, not on translation table walk or hardware update of translation table\",\n\n Some(ISS_DA::DFSC::Value::SyncTagCheckFault) => \"Synchronous Tag Check Fault\",\n\n Some(ISS_DA::DFSC::Value::SyncAbortOnTranslationTL0) => \"Synchronous External abort on translation table walk or hardware update of translation table, level 0\",\n\n Some(ISS_DA::DFSC::Value::SyncAbortOnTranslationTL1) => \"Synchronous External abort on translation table walk or hardware update of translation table, level 1\",\n", "file_path": "nucleus/src/arch/aarch64/traps.rs", "rank": 6, "score": 218043.01842449073 }, { "content": "pub fn enable_uart_pins(gpio: &GPIO) {\n\n gpio.PUD.set(0);\n\n\n\n loop_delay(150);\n\n\n\n // enable pins 14 and 15\n\n gpio.PUDCLK[0].write(PUDCLK0::PUDCLK14::AssertClock + PUDCLK0::PUDCLK15::AssertClock);\n\n\n\n loop_delay(150);\n\n\n\n gpio.PUDCLK[0].set(0);\n\n}\n\n\n\n/// An alternative GPIO function.\n\n#[repr(u8)]\n\npub enum Function {\n\n Input = 0b000,\n\n Output = 0b001,\n\n Alt0 = 0b100,\n\n Alt1 = 0b101,\n", "file_path": "nucleus/src/platform/rpi3/gpio.rs", "rank": 7, "score": 214873.279670865 }, { "content": "/// Helper function to 1) display current exception, 2) skip the offending asm instruction.\n\n/// Not for production use!\n\nfn synchronous_common(e: &mut ExceptionContext) {\n\n println!(\" ESR_EL1: {:#010x} (syndrome)\", ESR_EL1.get());\n\n let cause = ESR_EL1.read(ESR_EL1::EC);\n\n println!(\n\n \" EC: {:#06b} (cause) -- {}\",\n\n cause,\n\n cause_to_string(cause)\n\n );\n\n\n\n // Print more details about Data Alignment Check\n\n if cause == ESR_EL1::EC::DataAbortCurrentEL.read(ESR_EL1::EC) {\n\n let iss = ESR_EL1.read(ESR_EL1::ISS);\n\n let iss = IssForDataAbort::new(iss);\n\n if iss.is_set(ISS_DA::ISV) {\n\n println!(\n\n \" Access size: {} bytes ({}signed) to {}{}\",\n\n 2u64.pow(iss.read(ISS_DA::SAS) as u32),\n\n if iss.is_set(ISS_DA::SSE) { \"\" } else { \"un\" },\n\n if iss.is_set(ISS_DA::SF) { \"x\" } else { \"r\" },\n\n iss.read(ISS_DA::SRT)\n", "file_path": "nucleus/src/arch/aarch64/traps.rs", "rank": 8, "score": 209017.22914259756 }, { "content": "#[inline]\n\npub fn loop_delay(rounds: u32) {\n\n for _ in 0..rounds {\n\n asm::nop();\n\n }\n\n}\n\n\n\n/// Loop until a passed function returns `true`.\n", "file_path": "nucleus/src/arch/aarch64/mod.rs", "rank": 9, "score": 205617.46551628393 }, { "content": "/// For a given virtual address, find and return the output address and\n\n/// according attributes.\n\n///\n\n/// If the address is not covered in VIRTUAL_LAYOUT, return a default for normal\n\n/// cacheable DRAM.\n\npub fn get_virt_addr_properties(\n\n virt_addr: usize,\n\n) -> Result<(usize, AttributeFields), &'static str> {\n\n if virt_addr > map::END {\n\n return Err(\"Address out of range.\");\n\n }\n\n\n\n for i in KERNEL_VIRTUAL_LAYOUT.iter() {\n\n if (i.virtual_range)().contains(&virt_addr) {\n\n let output_addr = match i.translation {\n\n Translation::Identity => virt_addr,\n\n Translation::Offset(a) => a + (virt_addr - (i.virtual_range)().start()),\n\n };\n\n\n\n return Ok((output_addr, i.attribute_fields));\n\n }\n\n }\n\n\n\n Ok((virt_addr, AttributeFields::default()))\n\n}\n", "file_path": "nucleus/src/arch/aarch64/memory/mod.rs", "rank": 10, "score": 204506.9903215713 }, { "content": "pub fn write(regs: &RegisterBlock, buf: *const u32, channel: u32) -> Result<()> {\n\n let mut count: u32 = 0;\n\n let buf_ptr: u32 = buf as u32;\n\n\n\n // This address adjustment will be performed from the outside when necessary\n\n // (see FrameBuffer for example).\n\n // let buf_ptr = BcmHost::phys2bus(buf_ptr); not used for PropertyTags channel\n\n\n\n println!(\"Mailbox::write {:#08x}/{:#x}\", buf_ptr, channel);\n\n\n\n // Insert a compiler fence that ensures that all stores to the\n\n // mailbox buffer are finished before the GPU is signaled (which is\n\n // done by a store operation as well).\n\n compiler_fence(Ordering::Release);\n\n\n\n while regs.STATUS.is_set(STATUS::FULL) {\n\n count += 1;\n\n if count > (1 << 25) {\n\n return Err(MailboxError::Timeout);\n\n }\n\n }\n\n unsafe {\n\n barrier::dmb(barrier::SY);\n\n }\n\n regs.WRITE\n\n .set((buf_ptr & !CHANNEL_MASK) | (channel & CHANNEL_MASK));\n\n Ok(())\n\n}\n\n\n", "file_path": "nucleus/src/platform/rpi3/mailbox.rs", "rank": 11, "score": 204029.76026298886 }, { "content": "/// Shared trait for specific table levels.\n\npub trait TableLevel {}\n\n\n", "file_path": "nucleus/src/arch/aarch64/memory/mmu.rs", "rank": 12, "score": 198302.28205734186 }, { "content": "/// Wait for debugger to attach.\n\n/// Then in gdb issue `> set var *(&WAIT_FLAG) = 0`\n\n/// from inside this function's frame to contiue running.\n\npub fn wait_debugger() {\n\n use core::ptr::{read_volatile, write_volatile};\n\n\n\n while unsafe { read_volatile(&WAIT_FLAG) } {\n\n asm::nop();\n\n }\n\n // Reset the flag so that next jtag::wait_debugger() would block again.\n\n unsafe { write_volatile(&mut WAIT_FLAG, true) }\n\n}\n", "file_path": "nucleus/src/arch/aarch64/jtag.rs", "rank": 13, "score": 188571.13681638267 }, { "content": "#[inline]\n\npub fn endless_sleep() -> ! {\n\n loop {\n\n asm::wfe();\n\n }\n\n}\n\n\n\n/// Loop for a given number of `nop` instructions.\n", "file_path": "nucleus/src/arch/aarch64/mod.rs", "rank": 14, "score": 188076.35367865366 }, { "content": "/// Shared trait for hierarchical table levels.\n\n///\n\n/// Specifies what is the next level of page table hierarchy.\n\npub trait HierarchicalLevel: TableLevel {\n\n /// Level of the next translation table below this one.\n\n type NextLevel: TableLevel;\n\n}\n\n\n\nimpl TableLevel for PageGlobalDirectory {}\n\nimpl TableLevel for PageUpperDirectory {}\n\nimpl TableLevel for PageDirectory {}\n\nimpl TableLevel for PageTable {}\n\n\n\nimpl HierarchicalLevel for PageGlobalDirectory {\n\n type NextLevel = PageUpperDirectory;\n\n}\n\nimpl HierarchicalLevel for PageUpperDirectory {\n\n type NextLevel = PageDirectory;\n\n}\n\nimpl HierarchicalLevel for PageDirectory {\n\n type NextLevel = PageTable;\n\n}\n\n// PageTables do not have next level, therefore they are not HierarchicalLevel\n", "file_path": "nucleus/src/arch/aarch64/memory/mmu.rs", "rank": 15, "score": 187856.97482950156 }, { "content": "#[allow(unused)]\n\npub fn show<'a>(buffer: &'a mut [u8], args: fmt::Arguments) -> Result<&'a str, fmt::Error> {\n\n let mut w = WriteTo::new(buffer);\n\n fmt::write(&mut w, args)?;\n\n w.into_str().ok_or(fmt::Error)\n\n}\n\n\n\n// Return a zero-terminated str\n", "file_path": "nucleus/src/write_to.rs", "rank": 16, "score": 184358.802477561 }, { "content": "#[inline]\n\nfn aligned_addr_unchecked(addr: usize, alignment: usize) -> usize {\n\n (addr + (alignment - 1)) & !(alignment - 1)\n\n}\n\n\n\n#[cfg(test)]\n\nmod tests {\n\n use super::*;\n\n\n\n #[test_case]\n\n pub fn test_align_up() {\n\n // align 1\n\n assert_eq!(align_up(0, 1), 0);\n\n assert_eq!(align_up(1234, 1), 1234);\n\n assert_eq!(align_up(0xffff_ffff_ffff_ffff, 1), 0xffff_ffff_ffff_ffff);\n\n // align 2\n\n assert_eq!(align_up(0, 2), 0);\n\n assert_eq!(align_up(1233, 2), 1234);\n\n assert_eq!(align_up(0xffff_ffff_ffff_fffe, 2), 0xffff_ffff_ffff_fffe);\n\n // address 0\n\n assert_eq!(align_up(0, 128), 0);\n\n assert_eq!(align_up(0, 1), 0);\n\n assert_eq!(align_up(0, 2), 0);\n\n assert_eq!(align_up(0, 0x8000_0000_0000_0000), 0);\n\n }\n\n}\n", "file_path": "nucleus/src/mm/mod.rs", "rank": 18, "score": 178590.80465055458 }, { "content": "/// A function that maps the generic memory range attributes to HW-specific\n\n/// attributes of the MMU.\n\nfn into_mmu_attributes(\n\n attribute_fields: AttributeFields,\n\n) -> FieldValue<u64, STAGE1_DESCRIPTOR::Register> {\n\n use super::{AccessPermissions, MemAttributes};\n\n\n\n // Memory attributes\n\n let mut desc = match attribute_fields.mem_attributes {\n\n MemAttributes::CacheableDRAM => {\n\n STAGE1_DESCRIPTOR::SH::InnerShareable\n\n + STAGE1_DESCRIPTOR::AttrIndx.val(mair::attr::NORMAL)\n\n }\n\n MemAttributes::NonCacheableDRAM => {\n\n STAGE1_DESCRIPTOR::SH::InnerShareable\n\n + STAGE1_DESCRIPTOR::AttrIndx.val(mair::attr::NORMAL_NON_CACHEABLE)\n\n }\n\n MemAttributes::Device => {\n\n STAGE1_DESCRIPTOR::SH::OuterShareable\n\n + STAGE1_DESCRIPTOR::AttrIndx.val(mair::attr::DEVICE_NGNRE)\n\n }\n\n };\n", "file_path": "nucleus/src/arch/aarch64/memory/mmu.rs", "rank": 19, "score": 177002.0916456079 }, { "content": "type IssForDataAbort = LocalRegisterCopy<u64, ISS_DA::Register>;\n\n\n", "file_path": "nucleus/src/arch/aarch64/traps.rs", "rank": 20, "score": 174546.97683133688 }, { "content": "#[allow(unused)]\n\npub fn c_show<'a>(buffer: &'a mut [u8], args: fmt::Arguments) -> Result<&'a str, fmt::Error> {\n\n let mut w = WriteTo::new(buffer);\n\n fmt::write(&mut w, args)?;\n\n w.into_cstr().ok_or(fmt::Error)\n\n}\n\n\n\n#[cfg(test)]\n\nmod tests {\n\n use super::*;\n\n\n\n #[test_case]\n\n pub fn write_to_works() {\n\n let mut buf = [0u8; 64];\n\n let s: &str = show(\n\n &mut buf,\n\n format_args!(\"write some stuff {:?}: {}\", \"foo\", 42),\n\n )\n\n .unwrap();\n\n assert_eq!(s, \"write some stuff \\\"foo\\\": 42\");\n\n assert_eq!(s.as_ptr(), buf.as_ptr());\n", "file_path": "nucleus/src/write_to.rs", "rank": 21, "score": 173076.0413844373 }, { "content": "/// This trait is implemented for 4KiB, 16KiB, and 2MiB pages, but not for 1GiB pages.\n\npub trait NotGiantPageSize: PageSize {} // @todo doesn't have to be pub??\n\n\n\n/// A standard 4KiB page.\n\n#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord)]\n\npub enum Size4KiB {}\n\n\n\nimpl PageSize for Size4KiB {\n\n const SIZE: u64 = 4096;\n\n const SIZE_AS_DEBUG_STR: &'static str = \"4KiB\";\n\n const SHIFT: usize = 12;\n\n const MASK: u64 = 0xfff;\n\n}\n\n\n\nimpl NotGiantPageSize for Size4KiB {}\n\n\n\n/// A “huge” 2MiB page.\n\n#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord)]\n\npub enum Size2MiB {}\n\n\n\nimpl PageSize for Size2MiB {\n\n const SIZE: u64 = Size4KiB::SIZE * NUM_ENTRIES_4KIB;\n\n const SIZE_AS_DEBUG_STR: &'static str = \"2MiB\";\n\n const SHIFT: usize = 21;\n\n const MASK: u64 = 0x1fffff;\n\n}\n\n\n\nimpl NotGiantPageSize for Size2MiB {}\n\n\n", "file_path": "nucleus/src/arch/aarch64/memory/mmu.rs", "rank": 25, "score": 155137.0543280508 }, { "content": "#[doc(hidden)]\n\n#[cfg(any(test, qemu))] // qemu feature not enabled here?? we pass --features=qemu to cargo test\n\npub fn _print(args: core::fmt::Arguments) {\n\n use crate::{qemu, write_to};\n\n\n\n let mut buf = [0u8; 2048]; // Increase this buffer size to allow dumping larger panic texts.\n\n qemu::semihosting::sys_write0_call(write_to::c_show(&mut buf, args).unwrap());\n\n}\n", "file_path": "nucleus/src/macros.rs", "rank": 28, "score": 150196.3521396782 }, { "content": "// #[repr(transparent)]\n\nenum PageTableEntry {\n\n /// Empty page table entry.\n\n Invalid,\n\n /// Table descriptor is a L0, L1 or L2 table pointing to another table.\n\n /// L0 tables can only point to L1 tables.\n\n /// A descriptor pointing to the next page table.\n\n TableDescriptor(EntryFlags),\n\n /// A Level2 block descriptor with 2 MiB aperture.\n\n ///\n\n /// The output points to physical memory.\n\n Lvl2BlockDescriptor(EntryFlags),\n\n /// A page PageTableEntry::descriptor with 4 KiB aperture.\n\n ///\n\n /// The output points to physical memory.\n\n PageDescriptor(EntryFlags),\n\n}\n\n\n\n/// A descriptor pointing to the next page table. (within PageTableEntry enum)\n\n// struct TableDescriptor(register::FieldValue<u64, STAGE1_DESCRIPTOR::Register>);\n\n\n", "file_path": "nucleus/src/arch/aarch64/memory/mmu.rs", "rank": 29, "score": 147789.1991887155 }, { "content": "/// Trait for abstracting over the possible page sizes, 4KiB, 16KiB, 2MiB, 1GiB.\n\npub trait PageSize: Copy + Eq + PartialOrd + Ord {\n\n /// The page size in bytes.\n\n const SIZE: u64;\n\n\n\n /// A string representation of the page size for debug output.\n\n const SIZE_AS_DEBUG_STR: &'static str;\n\n\n\n /// The page shift in bits.\n\n const SHIFT: usize;\n\n\n\n /// The page mask in bits.\n\n const MASK: u64;\n\n}\n\n\n", "file_path": "nucleus/src/arch/aarch64/memory/mmu.rs", "rank": 32, "score": 145099.3338609713 }, { "content": "#[cfg(test)]\n\npub fn test_runner(tests: &[&dyn TestFn]) {\n\n println!(\"Running {} tests\", tests.len());\n\n for test in tests {\n\n test.run();\n\n }\n\n println!(\"\\n[success]\\n\");\n\n qemu::semihosting::exit_success();\n\n}\n", "file_path": "nucleus/src/tests.rs", "rank": 33, "score": 143958.9448072898 }, { "content": "type EntryFlags = tock_registers::fields::FieldValue<u64, STAGE1_DESCRIPTOR::Register>;\n\n// type EntryRegister = register::LocalRegisterCopy<u64, STAGE1_DESCRIPTOR::Register>;\n\n\n\n/// L0 table -- only pointers to L1 tables\n\npub enum PageGlobalDirectory {}\n\n/// L1 tables -- pointers to L2 tables or giant 1GiB pages\n\npub enum PageUpperDirectory {}\n\n/// L2 tables -- pointers to L3 tables or huge 2MiB pages\n\npub enum PageDirectory {}\n\n/// L3 tables -- only pointers to 4/16KiB pages\n\npub enum PageTable {}\n\n\n", "file_path": "nucleus/src/arch/aarch64/memory/mmu.rs", "rank": 34, "score": 138148.87422377954 }, { "content": "pub trait TestFn {\n\n fn run(&self) -> ();\n\n}\n\n\n\nimpl<T> TestFn for T\n\nwhere\n\n T: Fn(),\n\n{\n\n fn run(&self) {\n\n print!(\"*TEST* {}...\\t\", core::any::type_name::<T>());\n\n self();\n\n println!(\"[ok]\\n\");\n\n }\n\n}\n\n\n", "file_path": "nucleus/src/tests.rs", "rank": 36, "score": 128661.47699457598 }, { "content": " /// Base address of ARM<->VC mailbox area.\n\n pub const VIDEOCORE_MBOX_BASE: usize = MMIO_BASE + 0x0000_B880;\n\n /// Base address of GPIO registers.\n\n pub const GPIO_BASE: usize = MMIO_BASE + 0x0020_0000;\n\n /// Base address of regular UART.\n\n pub const PL011_UART_BASE: usize = MMIO_BASE + 0x0020_1000;\n\n /// Base address of MiniUART.\n\n pub const MINI_UART_BASE: usize = MMIO_BASE + 0x0021_5000;\n\n /// End of MMIO memory.\n\n pub const MMIO_END: usize = super::END;\n\n }\n\n\n\n /// Virtual (mapped) addresses.\n\n pub mod virt {\n\n /// Start (top) of kernel stack.\n\n pub const KERN_STACK_START: usize = super::START;\n\n /// End (bottom) of kernel stack. SP starts at KERN_STACK_END + 1.\n\n pub const KERN_STACK_END: usize = 0x0007_FFFF;\n\n\n\n /// Location of DMA-able memory region (in the second 2 MiB block).\n", "file_path": "nucleus/src/arch/aarch64/memory/mod.rs", "rank": 37, "score": 126848.85474468116 }, { "content": " pub const DMA_HEAP_START: usize = 0x0020_0000;\n\n /// End of DMA-able memory region.\n\n pub const DMA_HEAP_END: usize = 0x005F_FFFF;\n\n }\n\n}\n\n\n\n/// Types used for compiling the virtual memory layout of the kernel using address ranges.\n\npub mod kernel_mem_range {\n\n use core::ops::RangeInclusive;\n\n\n\n /// Memory region attributes.\n\n #[derive(Copy, Clone)]\n\n pub enum MemAttributes {\n\n /// Regular memory\n\n CacheableDRAM,\n\n /// Memory without caching\n\n NonCacheableDRAM,\n\n /// Device memory\n\n Device,\n\n }\n", "file_path": "nucleus/src/arch/aarch64/memory/mod.rs", "rank": 38, "score": 126844.85950544619 }, { "content": " },\n\n },\n\n Descriptor {\n\n name: \"Kernel data and BSS\",\n\n virtual_range: || {\n\n extern \"C\" {\n\n static __DATA_START: u64;\n\n static __BSS_END: u64;\n\n }\n\n\n\n unsafe {\n\n RangeInclusive::new(\n\n &__DATA_START as *const _ as usize,\n\n &__BSS_END as *const _ as usize - 1,\n\n )\n\n }\n\n },\n\n translation: Translation::Identity,\n\n attribute_fields: AttributeFields {\n\n mem_attributes: MemAttributes::CacheableDRAM,\n", "file_path": "nucleus/src/arch/aarch64/memory/mod.rs", "rank": 39, "score": 126840.82957878141 }, { "content": "\n\n/// Default page size used by the kernel.\n\npub const PAGE_SIZE: usize = 4096;\n\n\n\n/// System memory map.\n\n/// This is a fixed memory map for RasPi3,\n\n/// @todo we need to infer the memory map from the provided DTB.\n\n#[rustfmt::skip]\n\npub mod map {\n\n /// Beginning of memory.\n\n pub const START: usize = 0x0000_0000;\n\n /// End of memory.\n\n pub const END: usize = 0x3FFF_FFFF;\n\n\n\n /// Physical RAM addresses.\n\n pub mod phys {\n\n /// Base address of video (VC) memory.\n\n pub const VIDEOMEM_BASE: usize = 0x3e00_0000;\n\n /// Base address of MMIO register range.\n\n pub const MMIO_BASE: usize = 0x3F00_0000;\n", "file_path": "nucleus/src/arch/aarch64/memory/mod.rs", "rank": 40, "score": 126840.62906457581 }, { "content": "\n\n /// Memory region descriptor.\n\n ///\n\n /// Used to construct iterable kernel memory ranges.\n\n pub struct Descriptor {\n\n /// Name of the region\n\n pub name: &'static str,\n\n /// Virtual memory range\n\n pub virtual_range: fn() -> RangeInclusive<usize>,\n\n /// Mapping translation\n\n pub translation: Translation,\n\n /// Attributes\n\n pub attribute_fields: AttributeFields,\n\n }\n\n}\n\n\n\npub use kernel_mem_range::*;\n\n\n\n/// A virtual memory layout that is agnostic of the paging granularity that the\n\n/// hardware MMU will use.\n", "file_path": "nucleus/src/arch/aarch64/memory/mod.rs", "rank": 41, "score": 126839.3050141553 }, { "content": "/*\n\n * SPDX-License-Identifier: BlueOak-1.0.0\n\n * Copyright (c) Berkus Decker <[email protected]>\n\n */\n\n\n\n//! Memory management functions for aarch64.\n\n\n\nuse {\n\n crate::println,\n\n core::{fmt, ops::RangeInclusive},\n\n};\n\n\n\nmod addr;\n\npub mod mmu;\n\n\n\npub use addr::PhysAddr;\n\npub use addr::VirtAddr;\n\n\n\n// aarch64 granules and page sizes howto:\n\n// https://stackoverflow.com/questions/34269185/simultaneous-existence-of-different-sized-pages-on-aarch64\n", "file_path": "nucleus/src/arch/aarch64/memory/mod.rs", "rank": 42, "score": 126838.2075327254 }, { "content": " // KiB aligned, and we export the boundaries via symbols:\n\n //\n\n // [__BOOT_START, __BOOT_END)\n\n extern \"C\" {\n\n // The inclusive start of the boot area, aka the address of the\n\n // first byte of the area.\n\n static __BOOT_START: u64;\n\n\n\n // The exclusive end of the boot area, aka the address of\n\n // the first byte _after_ the RO area.\n\n static __BOOT_END: u64;\n\n }\n\n\n\n unsafe {\n\n // Notice the subtraction to turn the exclusive end into an\n\n // inclusive end\n\n RangeInclusive::new(\n\n &__BOOT_START as *const _ as usize,\n\n &__BOOT_END as *const _ as usize - 1,\n\n )\n", "file_path": "nucleus/src/arch/aarch64/memory/mod.rs", "rank": 43, "score": 126835.0040809701 }, { "content": " }\n\n },\n\n translation: Translation::Identity,\n\n attribute_fields: AttributeFields {\n\n mem_attributes: MemAttributes::CacheableDRAM,\n\n acc_perms: AccessPermissions::ReadOnly,\n\n execute_never: false,\n\n },\n\n },\n\n Descriptor {\n\n name: \"Kernel code and RO data\",\n\n virtual_range: || {\n\n // Using the linker script, we ensure that the RO area is consecutive and 4\n\n // KiB aligned, and we export the boundaries via symbols:\n\n //\n\n // [__RO_START, __RO_END)\n\n extern \"C\" {\n\n // The inclusive start of the read-only area, aka the address of the\n\n // first byte of the area.\n\n static __RO_START: u64;\n", "file_path": "nucleus/src/arch/aarch64/memory/mod.rs", "rank": 44, "score": 126832.1628005869 }, { "content": "///\n\n/// Contains only special ranges, aka anything that is _not_ normal cacheable\n\n/// DRAM.\n\nstatic KERNEL_VIRTUAL_LAYOUT: [Descriptor; 6] = [\n\n Descriptor {\n\n name: \"Kernel stack\",\n\n virtual_range: || {\n\n RangeInclusive::new(map::virt::KERN_STACK_START, map::virt::KERN_STACK_END)\n\n },\n\n translation: Translation::Identity,\n\n attribute_fields: AttributeFields {\n\n mem_attributes: MemAttributes::CacheableDRAM,\n\n acc_perms: AccessPermissions::ReadWrite,\n\n execute_never: true,\n\n },\n\n },\n\n Descriptor {\n\n name: \"Boot code and data\",\n\n virtual_range: || {\n\n // Using the linker script, we ensure that the boot area is consecutive and 4\n", "file_path": "nucleus/src/arch/aarch64/memory/mod.rs", "rank": 45, "score": 126828.30881267243 }, { "content": "\n\n // The exclusive end of the read-only area, aka the address of\n\n // the first byte _after_ the RO area.\n\n static __RO_END: u64;\n\n }\n\n\n\n unsafe {\n\n // Notice the subtraction to turn the exclusive end into an\n\n // inclusive end\n\n RangeInclusive::new(\n\n &__RO_START as *const _ as usize,\n\n &__RO_END as *const _ as usize - 1,\n\n )\n\n }\n\n },\n\n translation: Translation::Identity,\n\n attribute_fields: AttributeFields {\n\n mem_attributes: MemAttributes::CacheableDRAM,\n\n acc_perms: AccessPermissions::ReadOnly,\n\n execute_never: false,\n", "file_path": "nucleus/src/arch/aarch64/memory/mod.rs", "rank": 46, "score": 126825.06100814836 }, { "content": "\n\n /// Memory region access permissions.\n\n #[derive(Copy, Clone)]\n\n pub enum AccessPermissions {\n\n /// Read-only access\n\n ReadOnly,\n\n /// Read-write access\n\n ReadWrite,\n\n }\n\n\n\n /// Memory region translation.\n\n #[allow(dead_code)]\n\n #[derive(Copy, Clone)]\n\n pub enum Translation {\n\n /// One-to-one address mapping\n\n Identity,\n\n /// Mapping with a specified offset\n\n Offset(usize),\n\n }\n\n\n", "file_path": "nucleus/src/arch/aarch64/memory/mod.rs", "rank": 47, "score": 126823.85566982631 }, { "content": " acc_perms: AccessPermissions::ReadWrite,\n\n execute_never: true,\n\n },\n\n },\n\n Descriptor {\n\n name: \"DMA heap pool\",\n\n virtual_range: || RangeInclusive::new(map::virt::DMA_HEAP_START, map::virt::DMA_HEAP_END),\n\n translation: Translation::Identity,\n\n attribute_fields: AttributeFields {\n\n mem_attributes: MemAttributes::NonCacheableDRAM,\n\n acc_perms: AccessPermissions::ReadWrite,\n\n execute_never: true,\n\n },\n\n },\n\n Descriptor {\n\n name: \"Device MMIO\",\n\n virtual_range: || RangeInclusive::new(map::phys::VIDEOMEM_BASE, map::phys::MMIO_END),\n\n translation: Translation::Identity,\n\n attribute_fields: AttributeFields {\n\n mem_attributes: MemAttributes::Device,\n", "file_path": "nucleus/src/arch/aarch64/memory/mod.rs", "rank": 48, "score": 126823.82619381022 }, { "content": " } else {\n\n (size, \"Byte\")\n\n };\n\n\n\n let attr = match self.attribute_fields.mem_attributes {\n\n MemAttributes::CacheableDRAM => \"C\",\n\n MemAttributes::NonCacheableDRAM => \"NC\",\n\n MemAttributes::Device => \"Dev\",\n\n };\n\n\n\n let acc_p = match self.attribute_fields.acc_perms {\n\n AccessPermissions::ReadOnly => \"RO\",\n\n AccessPermissions::ReadWrite => \"RW\",\n\n };\n\n\n\n let xn = if self.attribute_fields.execute_never {\n\n \"PXN\"\n\n } else {\n\n \"PX\"\n\n };\n\n\n\n write!(\n\n f,\n\n \" {:#010X} - {:#010X} | {: >3} {} | {: <3} {} {: <3} | {}\",\n\n start, end, size, unit, attr, acc_p, xn, self.name\n\n )\n\n }\n\n}\n\n\n", "file_path": "nucleus/src/arch/aarch64/memory/mod.rs", "rank": 49, "score": 126822.10864757879 }, { "content": " /// Summary structure of memory region properties.\n\n #[derive(Copy, Clone)]\n\n pub struct AttributeFields {\n\n /// Attributes\n\n pub mem_attributes: MemAttributes,\n\n /// Permissions\n\n pub acc_perms: AccessPermissions,\n\n /// Disable executable code in this region\n\n pub execute_never: bool,\n\n }\n\n\n\n impl Default for AttributeFields {\n\n fn default() -> AttributeFields {\n\n AttributeFields {\n\n mem_attributes: MemAttributes::CacheableDRAM,\n\n acc_perms: AccessPermissions::ReadWrite,\n\n execute_never: true,\n\n }\n\n }\n\n }\n", "file_path": "nucleus/src/arch/aarch64/memory/mod.rs", "rank": 50, "score": 126819.00982731215 }, { "content": " acc_perms: AccessPermissions::ReadWrite,\n\n execute_never: true,\n\n },\n\n },\n\n];\n\n\n\n/// For a given virtual address, find and return the output address and\n\n/// according attributes.\n\n///\n\n/// If the address is not covered in VIRTUAL_LAYOUT, return a default for normal\n\n/// cacheable DRAM.\n", "file_path": "nucleus/src/arch/aarch64/memory/mod.rs", "rank": 51, "score": 126813.06238826104 }, { "content": "\n\n/// Human-readable output of a Descriptor.\n\nimpl fmt::Display for Descriptor {\n\n fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {\n\n // Call the function to which self.range points, and dereference the\n\n // result, which causes Rust to copy the value.\n\n let start = *(self.virtual_range)().start();\n\n let end = *(self.virtual_range)().end();\n\n let size = end - start + 1;\n\n\n\n // log2(1024)\n\n const KIB_RSHIFT: u32 = 10;\n\n\n\n // log2(1024 * 1024)\n\n const MIB_RSHIFT: u32 = 20;\n\n\n\n let (size, unit) = if (size >> MIB_RSHIFT) > 0 {\n\n (size >> MIB_RSHIFT, \"MiB\")\n\n } else if (size >> KIB_RSHIFT) > 0 {\n\n (size >> KIB_RSHIFT, \"KiB\")\n", "file_path": "nucleus/src/arch/aarch64/memory/mod.rs", "rank": 52, "score": 126812.19821401716 }, { "content": " pub mod attr {\n\n pub const NORMAL: u64 = 0;\n\n pub const NORMAL_NON_CACHEABLE: u64 = 1;\n\n pub const DEVICE_NGNRE: u64 = 2;\n\n // DEVICE_GRE\n\n // DEVICE_NGNRNE\n\n }\n\n}\n\n\n\n/// Parse the ID_AA64MMFR0_EL1 register for runtime information about supported MMU features.\n\n/// Print the current state of TCR register.\n", "file_path": "nucleus/src/arch/aarch64/memory/mmu.rs", "rank": 53, "score": 126708.49794019123 }, { "content": "\n\n/// MMU address translation table.\n\n/// Contains just u64 internally, provides enum interface on top\n\n#[repr(C)]\n\n#[repr(align(4096))]\n\npub struct Table<L: TableLevel> {\n\n entries: [u64; NUM_ENTRIES_4KIB as usize],\n\n level: PhantomData<L>,\n\n}\n\n\n\n// Implementation code shared for all levels of page tables\n\nimpl<L> Table<L>\n\nwhere\n\n L: TableLevel,\n\n{\n\n /// Zero out entire table.\n\n pub fn zero(&mut self) {\n\n for entry in self.entries.iter_mut() {\n\n *entry = 0;\n\n }\n", "file_path": "nucleus/src/arch/aarch64/memory/mmu.rs", "rank": 54, "score": 126705.2888535055 }, { "content": "/*\n\n * SPDX-License-Identifier: MIT OR BlueOak-1.0.0\n\n * Copyright (c) 2018-2019 Andre Richter <[email protected]>\n\n * Copyright (c) Berkus Decker <[email protected]>\n\n * Original code distributed under MIT, additional changes are under BlueOak-1.0.0\n\n */\n\n\n\n//! MMU initialisation.\n\n//!\n\n//! Paging is mostly based on [previous version](https://os.phil-opp.com/page-tables/) of\n\n//! Phil Opp's [paging guide](https://os.phil-opp.com/paging-implementation/) and\n\n//! [ARMv8 ARM memory addressing](https://static.docs.arm.com/100940/0100/armv8_a_address%20translation_100940_0100_en.pdf).\n\n\n\nuse {\n\n crate::{\n\n arch::aarch64::memory::{\n\n get_virt_addr_properties, AttributeFields, /*FrameAllocator, PhysAddr, VirtAddr,*/\n\n },\n\n println,\n\n },\n", "file_path": "nucleus/src/arch/aarch64/memory/mmu.rs", "rank": 55, "score": 126704.5298721399 }, { "content": "/// Completely unsafe, we're in the hardware land! Incorrectly initialised tables will just\n\n/// restart the CPU.\n\npub unsafe fn init() -> Result<(), &'static str> {\n\n // Prepare the memory attribute indirection register.\n\n mair::set_up();\n\n\n\n // Point the first 2 MiB of virtual addresses to the follow-up LVL3\n\n // page-table.\n\n LVL2_TABLE.entries[0] =\n\n PageTableEntry::new_table_descriptor(LVL3_TABLE.entries.base_addr_usize())?.into();\n\n\n\n // Fill the rest of the LVL2 (2 MiB) entries as block descriptors.\n\n //\n\n // Notice the skip(1) which makes the iteration start at the second 2 MiB\n\n // block (0x20_0000).\n\n for (block_descriptor_nr, entry) in LVL2_TABLE.entries.iter_mut().enumerate().skip(1) {\n\n let virt_addr = block_descriptor_nr << Size2MiB::SHIFT;\n\n\n\n let (output_addr, attribute_fields) = match get_virt_addr_properties(virt_addr) {\n\n Err(s) => return Err(s),\n", "file_path": "nucleus/src/arch/aarch64/memory/mmu.rs", "rank": 56, "score": 126699.82433852107 }, { "content": " }\n\n}\n\n\n\nimpl<L> Index<usize> for Table<L>\n\nwhere\n\n L: TableLevel,\n\n{\n\n type Output = u64;\n\n\n\n fn index(&self, index: usize) -> &u64 {\n\n &self.entries[index]\n\n }\n\n}\n\n\n\nimpl<L> IndexMut<usize> for Table<L>\n\nwhere\n\n L: TableLevel,\n\n{\n\n fn index_mut(&mut self, index: usize) -> &mut u64 {\n\n &mut self.entries[index]\n\n }\n\n}\n\n\n\n/// Type-safe enum wrapper covering Table<L>'s 64-bit entries.\n\n#[derive(Clone)]\n", "file_path": "nucleus/src/arch/aarch64/memory/mmu.rs", "rank": 57, "score": 126699.4229933782 }, { "content": "mod mair {\n\n use cortex_a::registers::MAIR_EL1;\n\n use tock_registers::interfaces::Writeable;\n\n\n\n /// Setup function for the MAIR_EL1 register.\n\n pub fn set_up() {\n\n // Define the three memory types that we will map. Normal DRAM, Uncached and device.\n\n MAIR_EL1.write(\n\n // Attribute 2 -- Device Memory\n\n MAIR_EL1::Attr2_Device::nonGathering_nonReordering_EarlyWriteAck\n\n // Attribute 1 -- Non Cacheable DRAM\n\n + MAIR_EL1::Attr1_Normal_Outer::NonCacheable\n\n + MAIR_EL1::Attr1_Normal_Inner::NonCacheable\n\n // Attribute 0 -- Regular Cacheable\n\n + MAIR_EL1::Attr0_Normal_Outer::WriteBack_NonTransient_ReadWriteAlloc\n\n + MAIR_EL1::Attr0_Normal_Inner::WriteBack_NonTransient_ReadWriteAlloc,\n\n );\n\n }\n\n\n\n // Three descriptive consts for indexing into the correct MAIR_EL1 attributes.\n", "file_path": "nucleus/src/arch/aarch64/memory/mmu.rs", "rank": 58, "score": 126699.21864456713 }, { "content": " match val {\n\n PageTableEntry::Invalid => 0,\n\n PageTableEntry::TableDescriptor(x)\n\n | PageTableEntry::Lvl2BlockDescriptor(x)\n\n | PageTableEntry::PageDescriptor(x) => x.value,\n\n }\n\n }\n\n}\n\n\n\nstatic mut LVL2_TABLE: Table<PageDirectory> = Table::<PageDirectory> {\n\n entries: [0; NUM_ENTRIES_4KIB as usize],\n\n level: PhantomData,\n\n};\n\n\n\nstatic mut LVL3_TABLE: Table<PageTable> = Table::<PageTable> {\n\n entries: [0; NUM_ENTRIES_4KIB as usize],\n\n level: PhantomData,\n\n};\n\n\n", "file_path": "nucleus/src/arch/aarch64/memory/mmu.rs", "rank": 59, "score": 126698.32488857277 }, { "content": " + TCR_EL1::TG0::KiB_4 // 4 KiB granule\n\n + TCR_EL1::SH0::Inner\n\n + TCR_EL1::ORGN0::WriteBack_ReadAlloc_WriteAlloc_Cacheable\n\n + TCR_EL1::IRGN0::WriteBack_ReadAlloc_WriteAlloc_Cacheable\n\n + TCR_EL1::EPD0::EnableTTBR0Walks\n\n + TCR_EL1::T0SZ.val(34) // ARMv8ARM Table D5-11 minimum TxSZ for starting table level 2\n\n // ttbr1 kernel memory addresses\n\n + TCR_EL1::TG1::KiB_4 // 4 KiB granule\n\n + TCR_EL1::SH1::Inner\n\n + TCR_EL1::ORGN1::WriteBack_ReadAlloc_WriteAlloc_Cacheable\n\n + TCR_EL1::IRGN1::WriteBack_ReadAlloc_WriteAlloc_Cacheable\n\n + TCR_EL1::EPD1::EnableTTBR1Walks\n\n + TCR_EL1::T1SZ.val(34), // ARMv8ARM Table D5-11 minimum TxSZ for starting table level 2\n\n );\n\n\n\n // Switch the MMU on.\n\n //\n\n // First, force all previous changes to be seen before the MMU is enabled.\n\n barrier::isb(barrier::SY);\n\n\n", "file_path": "nucleus/src/arch/aarch64/memory/mmu.rs", "rank": 60, "score": 126694.61713230691 }, { "content": " *\n\n * _______________________________________________\n\n * | | | | | | |\n\n * | signx | Lv0 | Lv1 | Lv2 | Lv3 | off |\n\n * |_______|_______|_______|_______|_______|_______|\n\n * 63-48 47-39 38-30 29-21 20-12 11-00\n\n *\n\n * mask page size\n\n *\n\n * Lv0: FF8000000000 --\n\n * Lv1: 7FC0000000 1G\n\n * Lv2: 3FE00000 2M\n\n * Lv3: 1FF000 4K\n\n * off: FFF\n\n *\n\n * RPi3 supports 64K and 4K granules, also 40-bit physical addresses.\n\n * It also can address only 1G physical memory, so these 40-bit phys addresses are a fake.\n\n *\n\n * 48-bit virtual address space; different mappings in VBAR0 (EL0) and VBAR1 (EL1+).\n\n */\n\n\n\n/// Number of entries in a 4KiB mmu table.\n\npub const NUM_ENTRIES_4KIB: u64 = 512;\n\n\n", "file_path": "nucleus/src/arch/aarch64/memory/mmu.rs", "rank": 61, "score": 126694.31475429794 }, { "content": "impl PageTableEntry {\n\n fn new_table_descriptor(next_lvl_table_addr: usize) -> Result<PageTableEntry, &'static str> {\n\n if next_lvl_table_addr % Size4KiB::SIZE as usize != 0 {\n\n // @todo SIZE must be usize\n\n return Err(\"TableDescriptor: Address is not 4 KiB aligned.\");\n\n }\n\n\n\n let shifted = next_lvl_table_addr >> Size4KiB::SHIFT;\n\n\n\n Ok(PageTableEntry::TableDescriptor(\n\n STAGE1_DESCRIPTOR::VALID::True\n\n + STAGE1_DESCRIPTOR::TYPE::Table\n\n + STAGE1_DESCRIPTOR::NEXT_LVL_TABLE_ADDR_4KiB.val(shifted as u64),\n\n ))\n\n }\n\n}\n\n\n\n/// A Level2 block descriptor with 2 MiB aperture.\n\n///\n\n/// The output points to physical memory.\n", "file_path": "nucleus/src/arch/aarch64/memory/mmu.rs", "rank": 62, "score": 126694.12792786589 }, { "content": "\n\n let page_desc = match PageTableEntry::new_page_descriptor(output_addr, attribute_fields) {\n\n Err(s) => return Err(s),\n\n Ok(desc) => desc,\n\n };\n\n\n\n *entry = page_desc.into();\n\n }\n\n\n\n // Point to the LVL2 table base address in TTBR0.\n\n TTBR0_EL1.set_baddr(LVL2_TABLE.entries.base_addr_u64()); // User (lo-)space addresses\n\n\n\n // TTBR1_EL1.set_baddr(LVL2_TABLE.entries.base_addr_u64()); // Kernel (hi-)space addresses\n\n\n\n // Configure various settings of stage 1 of the EL1 translation regime.\n\n let ips = ID_AA64MMFR0_EL1.read(ID_AA64MMFR0_EL1::PARange);\n\n TCR_EL1.write(\n\n TCR_EL1::TBI0::Ignored // @todo TBI1 also set to Ignored??\n\n + TCR_EL1::IPS.val(ips) // Intermediate Physical Address Size\n\n // ttbr0 user memory addresses\n", "file_path": "nucleus/src/arch/aarch64/memory/mmu.rs", "rank": 63, "score": 126693.51001950078 }, { "content": "// struct Lvl2BlockDescriptor(register::FieldValue<u64, STAGE1_DESCRIPTOR::Register>);\n\n\n\nimpl PageTableEntry {\n\n fn new_lvl2_block_descriptor(\n\n output_addr: usize,\n\n attribute_fields: AttributeFields,\n\n ) -> Result<PageTableEntry, &'static str> {\n\n if output_addr % Size2MiB::SIZE as usize != 0 {\n\n return Err(\"BlockDescriptor: Address is not 2 MiB aligned.\");\n\n }\n\n\n\n let shifted = output_addr >> Size2MiB::SHIFT;\n\n\n\n Ok(PageTableEntry::Lvl2BlockDescriptor(\n\n STAGE1_DESCRIPTOR::VALID::True\n\n + STAGE1_DESCRIPTOR::AF::True\n\n + into_mmu_attributes(attribute_fields)\n\n + STAGE1_DESCRIPTOR::TYPE::Block\n\n + STAGE1_DESCRIPTOR::LVL2_OUTPUT_ADDR_4KiB.val(shifted as u64),\n\n ))\n", "file_path": "nucleus/src/arch/aarch64/memory/mmu.rs", "rank": 64, "score": 126693.14830015722 }, { "content": " println!(\"[i] MMU: Up to 44 Bit physical address range supported!\")\n\n }\n\n Some(ID_AA64MMFR0_EL1::PARange::Value::Bits_48) => {\n\n println!(\"[i] MMU: Up to 48 Bit physical address range supported!\")\n\n }\n\n Some(ID_AA64MMFR0_EL1::PARange::Value::Bits_52) => {\n\n println!(\"[i] MMU: Up to 52 Bit physical address range supported!\")\n\n }\n\n _ => println!(\"[i] MMU: Invalid PARange specified!\"),\n\n }\n\n\n\n let tcr = TCR_EL1.extract();\n\n\n\n match tcr.read_as_enum(TCR_EL1::IPS) {\n\n Some(TCR_EL1::IPS::Value::Bits_32) => {\n\n println!(\"[i] MMU: 32 Bit intermediate physical address size supported!\")\n\n }\n\n Some(TCR_EL1::IPS::Value::Bits_36) => {\n\n println!(\"[i] MMU: 36 Bit intermediate physical address size supported!\")\n\n }\n", "file_path": "nucleus/src/arch/aarch64/memory/mmu.rs", "rank": 65, "score": 126692.46637543172 }, { "content": " Some(TCR_EL1::IPS::Value::Bits_40) => {\n\n println!(\"[i] MMU: 40 Bit intermediate physical address size supported!\")\n\n }\n\n Some(TCR_EL1::IPS::Value::Bits_42) => {\n\n println!(\"[i] MMU: 42 Bit intermediate physical address size supported!\")\n\n }\n\n Some(TCR_EL1::IPS::Value::Bits_44) => {\n\n println!(\"[i] MMU: 44 Bit intermediate physical address size supported!\")\n\n }\n\n Some(TCR_EL1::IPS::Value::Bits_48) => {\n\n println!(\"[i] MMU: 48 Bit intermediate physical address size supported!\")\n\n }\n\n Some(TCR_EL1::IPS::Value::Bits_52) => {\n\n println!(\"[i] MMU: 52 Bit intermediate physical address size supported!\")\n\n }\n\n _ => println!(\"[i] MMU: Invalid IPS specified!\"),\n\n }\n\n\n\n match tcr.read_as_enum(TCR_EL1::TG0) {\n\n Some(TCR_EL1::TG0::Value::KiB_4) => println!(\"[i] MMU: TTBR0 4 KiB granule active!\"),\n", "file_path": "nucleus/src/arch/aarch64/memory/mmu.rs", "rank": 66, "score": 126692.26323521766 }, { "content": " {\n\n println!(\"[i] MMU: 4 KiB granule supported!\");\n\n }\n\n\n\n if let Some(ID_AA64MMFR0_EL1::TGran16::Value::Supported) =\n\n mmfr.read_as_enum(ID_AA64MMFR0_EL1::TGran16)\n\n {\n\n println!(\"[i] MMU: 16 KiB granule supported!\");\n\n }\n\n\n\n if let Some(ID_AA64MMFR0_EL1::TGran64::Value::Supported) =\n\n mmfr.read_as_enum(ID_AA64MMFR0_EL1::TGran64)\n\n {\n\n println!(\"[i] MMU: 64 KiB granule supported!\");\n\n }\n\n\n\n match mmfr.read_as_enum(ID_AA64MMFR0_EL1::ASIDBits) {\n\n Some(ID_AA64MMFR0_EL1::ASIDBits::Value::Bits_16) => {\n\n println!(\"[i] MMU: 16 bit ASIDs supported!\")\n\n }\n", "file_path": "nucleus/src/arch/aarch64/memory/mmu.rs", "rank": 67, "score": 126692.2066150285 }, { "content": " // use cortex_a::regs::RegisterReadWrite;\n\n // Enable the MMU and turn on data and instruction caching.\n\n SCTLR_EL1.modify(SCTLR_EL1::M::Enable + SCTLR_EL1::C::Cacheable + SCTLR_EL1::I::Cacheable);\n\n\n\n // Force MMU init to complete before next instruction\n\n /*\n\n * Invalidate the local I-cache so that any instructions fetched\n\n * speculatively from the PoC are discarded, since they may have\n\n * been dynamically patched at the PoU.\n\n */\n\n barrier::isb(barrier::SY);\n\n\n\n Ok(())\n\n}\n", "file_path": "nucleus/src/arch/aarch64/memory/mmu.rs", "rank": 68, "score": 126692.11713632868 }, { "content": " Some(ID_AA64MMFR0_EL1::ASIDBits::Value::Bits_8) => {\n\n println!(\"[i] MMU: 8 bit ASIDs supported!\")\n\n }\n\n _ => println!(\"[i] MMU: Invalid ASID bits specified!\"),\n\n }\n\n\n\n match mmfr.read_as_enum(ID_AA64MMFR0_EL1::PARange) {\n\n Some(ID_AA64MMFR0_EL1::PARange::Value::Bits_32) => {\n\n println!(\"[i] MMU: Up to 32 Bit physical address range supported!\")\n\n }\n\n Some(ID_AA64MMFR0_EL1::PARange::Value::Bits_36) => {\n\n println!(\"[i] MMU: Up to 36 Bit physical address range supported!\")\n\n }\n\n Some(ID_AA64MMFR0_EL1::PARange::Value::Bits_40) => {\n\n println!(\"[i] MMU: Up to 40 Bit physical address range supported!\")\n\n }\n\n Some(ID_AA64MMFR0_EL1::PARange::Value::Bits_42) => {\n\n println!(\"[i] MMU: Up to 42 Bit physical address range supported!\")\n\n }\n\n Some(ID_AA64MMFR0_EL1::PARange::Value::Bits_44) => {\n", "file_path": "nucleus/src/arch/aarch64/memory/mmu.rs", "rank": 69, "score": 126691.9470835162 }, { "content": " }\n\n}\n\n\n\n/// A page descriptor with 4 KiB aperture.\n\n///\n\n/// The output points to physical memory.\n\n\n\nimpl PageTableEntry {\n\n fn new_page_descriptor(\n\n output_addr: usize,\n\n attribute_fields: AttributeFields,\n\n ) -> Result<PageTableEntry, &'static str> {\n\n if output_addr % Size4KiB::SIZE as usize != 0 {\n\n return Err(\"PageDescriptor: Address is not 4 KiB aligned.\");\n\n }\n\n\n\n let shifted = output_addr >> Size4KiB::SHIFT;\n\n\n\n Ok(PageTableEntry::PageDescriptor(\n\n STAGE1_DESCRIPTOR::VALID::True\n", "file_path": "nucleus/src/arch/aarch64/memory/mmu.rs", "rank": 70, "score": 126691.8423959618 }, { "content": "pub fn read(regs: &RegisterBlock, expected: u32, channel: u32) -> Result<()> {\n\n loop {\n\n let mut count: u32 = 0;\n\n while regs.STATUS.is_set(STATUS::EMPTY) {\n\n count += 1;\n\n if count > (1 << 25) {\n\n println!(\"Timed out waiting for mailbox response\");\n\n return Err(MailboxError::Timeout);\n\n }\n\n }\n\n\n\n /* Read the data\n\n * Data memory barriers as we've switched peripheral\n\n */\n\n unsafe {\n\n barrier::dmb(barrier::SY);\n\n }\n\n let data: u32 = regs.READ.get();\n\n unsafe {\n\n barrier::dmb(barrier::SY);\n", "file_path": "nucleus/src/platform/rpi3/mailbox.rs", "rank": 71, "score": 126691.73544585443 }, { "content": " // bitflags::bitflags,\n\n core::{\n\n // convert::TryInto,\n\n // fmt,\n\n marker::PhantomData,\n\n ops::{Index, IndexMut},\n\n // ptr::Unique,\n\n },\n\n cortex_a::{\n\n asm::barrier,\n\n registers::{ID_AA64MMFR0_EL1, SCTLR_EL1, TCR_EL1, TTBR0_EL1},\n\n },\n\n tock_registers::{\n\n fields::FieldValue,\n\n interfaces::{ReadWriteable, Readable, Writeable},\n\n register_bitfields,\n\n },\n\n // ux::*,\n\n};\n\n\n", "file_path": "nucleus/src/arch/aarch64/memory/mmu.rs", "rank": 72, "score": 126689.50748128141 }, { "content": " + STAGE1_DESCRIPTOR::AF::True\n\n + into_mmu_attributes(attribute_fields)\n\n + STAGE1_DESCRIPTOR::TYPE::Table\n\n + STAGE1_DESCRIPTOR::NEXT_LVL_TABLE_ADDR_4KiB.val(shifted as u64),\n\n ))\n\n }\n\n}\n\n\n\nimpl From<u64> for PageTableEntry {\n\n fn from(_val: u64) -> PageTableEntry {\n\n // xxx0 -> Invalid\n\n // xx11 -> TableDescriptor on L0, L1 and L2\n\n // xx10 -> Block Entry L1 and L2\n\n // xx11 -> PageDescriptor L3\n\n PageTableEntry::Invalid\n\n }\n\n}\n\n\n\nimpl From<PageTableEntry> for u64 {\n\n fn from(val: PageTableEntry) -> u64 {\n", "file_path": "nucleus/src/arch/aarch64/memory/mmu.rs", "rank": 73, "score": 126688.59495647065 }, { "content": " Some(TCR_EL1::TG0::Value::KiB_16) => println!(\"[i] MMU: TTBR0 16 KiB granule active!\"),\n\n Some(TCR_EL1::TG0::Value::KiB_64) => println!(\"[i] MMU: TTBR0 64 KiB granule active!\"),\n\n _ => println!(\"[i] MMU: Invalid TTBR0 granule size specified!\"),\n\n }\n\n\n\n let t0sz = tcr.read(TCR_EL1::T0SZ);\n\n println!(\"[i] MMU: T0sz = 64-{} = {} bits\", t0sz, 64 - t0sz);\n\n\n\n match tcr.read_as_enum(TCR_EL1::TG1) {\n\n Some(TCR_EL1::TG1::Value::KiB_4) => println!(\"[i] MMU: TTBR1 4 KiB granule active!\"),\n\n Some(TCR_EL1::TG1::Value::KiB_16) => println!(\"[i] MMU: TTBR1 16 KiB granule active!\"),\n\n Some(TCR_EL1::TG1::Value::KiB_64) => println!(\"[i] MMU: TTBR1 64 KiB granule active!\"),\n\n _ => println!(\"[i] MMU: Invalid TTBR1 granule size specified!\"),\n\n }\n\n\n\n let t1sz = tcr.read(TCR_EL1::T1SZ);\n\n println!(\"[i] MMU: T1sz = 64-{} = {} bits\", t1sz, 64 - t1sz);\n\n}\n\n\n\nregister_bitfields! {\n", "file_path": "nucleus/src/arch/aarch64/memory/mmu.rs", "rank": 74, "score": 126687.90479365567 }, { "content": " Ok((a, b)) => (a, b),\n\n };\n\n\n\n let block_desc =\n\n match PageTableEntry::new_lvl2_block_descriptor(output_addr, attribute_fields) {\n\n Err(s) => return Err(s),\n\n Ok(desc) => desc,\n\n };\n\n\n\n *entry = block_desc.into();\n\n }\n\n\n\n // Finally, fill the single LVL3 table (4 KiB granule).\n\n for (page_descriptor_nr, entry) in LVL3_TABLE.entries.iter_mut().enumerate() {\n\n let virt_addr = page_descriptor_nr << Size4KiB::SHIFT;\n\n\n\n let (output_addr, attribute_fields) = match get_virt_addr_properties(virt_addr) {\n\n Err(s) => return Err(s),\n\n Ok((a, b)) => (a, b),\n\n };\n", "file_path": "nucleus/src/arch/aarch64/memory/mmu.rs", "rank": 75, "score": 126686.66270297875 }, { "content": " RW_EL1 = 0b00,\n\n RW_EL1_EL0 = 0b01,\n\n RO_EL1 = 0b10,\n\n RO_EL1_EL0 = 0b11\n\n ],\n\n\n\n NS_EL3 OFFSET(5) NUMBITS(1) [],\n\n\n\n /// Memory attributes index into the MAIR_EL1 register\n\n AttrIndx OFFSET(2) NUMBITS(3) [],\n\n\n\n TYPE OFFSET(1) NUMBITS(1) [\n\n Block = 0,\n\n Table = 1\n\n ],\n\n\n\n VALID OFFSET(0) NUMBITS(1) [\n\n False = 0,\n\n True = 1\n\n ]\n\n ]\n\n}\n\n\n", "file_path": "nucleus/src/arch/aarch64/memory/mmu.rs", "rank": 76, "score": 126685.85244704127 }, { "content": "\n\n /// Privileged execute-never for subsequent tables\n\n PXNTable OFFSET(59) NUMBITS(1) [\n\n Execute = 0,\n\n NeverExecute = 1\n\n ],\n\n\n\n // In block descriptors\n\n\n\n // OS-specific data\n\n OSData OFFSET(55) NUMBITS(4) [],\n\n\n\n // User execute-never\n\n UXN OFFSET(54) NUMBITS(1) [\n\n Execute = 0,\n\n NeverExecute = 1\n\n ],\n\n\n\n /// Privileged execute-never\n\n PXN OFFSET(53) NUMBITS(1) [\n", "file_path": "nucleus/src/arch/aarch64/memory/mmu.rs", "rank": 77, "score": 126684.76331794249 }, { "content": " u64,\n\n // AArch64 Reference Manual page 2150, D5-2445\n\n STAGE1_DESCRIPTOR [\n\n // In table descriptors\n\n\n\n NSTable_EL3 OFFSET(63) NUMBITS(1) [],\n\n\n\n /// Access Permissions for subsequent tables\n\n APTable OFFSET(61) NUMBITS(2) [\n\n RW_EL1 = 0b00,\n\n RW_EL1_EL0 = 0b01,\n\n RO_EL1 = 0b10,\n\n RO_EL1_EL0 = 0b11\n\n ],\n\n\n\n // User execute-never for subsequent tables\n\n UXNTable OFFSET(60) NUMBITS(1) [\n\n Execute = 0,\n\n NeverExecute = 1\n\n ],\n", "file_path": "nucleus/src/arch/aarch64/memory/mmu.rs", "rank": 78, "score": 126684.38497922335 }, { "content": " Execute = 0,\n\n NeverExecute = 1\n\n ],\n\n\n\n // @fixme ?? where is this described\n\n CONTIGUOUS OFFSET(52) NUMBITS(1) [\n\n False = 0,\n\n True = 1\n\n ],\n\n\n\n // @fixme ?? where is this described\n\n DIRTY OFFSET(51) NUMBITS(1) [\n\n False = 0,\n\n True = 1\n\n ],\n\n\n\n /// Various address fields, depending on use case\n\n LVL2_OUTPUT_ADDR_4KiB OFFSET(21) NUMBITS(27) [], // [47:21]\n\n NEXT_LVL_TABLE_ADDR_4KiB OFFSET(12) NUMBITS(36) [], // [47:12]\n\n\n", "file_path": "nucleus/src/arch/aarch64/memory/mmu.rs", "rank": 79, "score": 126682.78660722058 }, { "content": " // @fixme ?? where is this described\n\n NON_GLOBAL OFFSET(11) NUMBITS(1) [\n\n False = 0,\n\n True = 1\n\n ],\n\n\n\n /// Access flag\n\n AF OFFSET(10) NUMBITS(1) [\n\n False = 0,\n\n True = 1\n\n ],\n\n\n\n /// Shareability field\n\n SH OFFSET(8) NUMBITS(2) [\n\n OuterShareable = 0b10,\n\n InnerShareable = 0b11\n\n ],\n\n\n\n /// Access Permissions\n\n AP OFFSET(6) NUMBITS(2) [\n", "file_path": "nucleus/src/arch/aarch64/memory/mmu.rs", "rank": 80, "score": 126680.1555810293 }, { "content": "\n\n // Access Permissions\n\n desc += match attribute_fields.acc_perms {\n\n AccessPermissions::ReadOnly => STAGE1_DESCRIPTOR::AP::RO_EL1,\n\n AccessPermissions::ReadWrite => STAGE1_DESCRIPTOR::AP::RW_EL1,\n\n };\n\n\n\n // Execute Never\n\n desc += if attribute_fields.execute_never {\n\n STAGE1_DESCRIPTOR::PXN::NeverExecute\n\n } else {\n\n STAGE1_DESCRIPTOR::PXN::Execute\n\n };\n\n\n\n desc\n\n}\n\n\n\n/*\n\n * With 4k page granule, a virtual address is split into 4 lookup parts\n\n * spanning 9 bits each:\n", "file_path": "nucleus/src/arch/aarch64/memory/mmu.rs", "rank": 81, "score": 126679.66509183259 }, { "content": "#[allow(unused_variables)]\n\npub trait ConsoleOps {\n\n fn putc(&self, c: char) {}\n\n fn puts(&self, string: &str) {}\n\n fn getc(&self) -> char {\n\n ' '\n\n }\n\n fn flush(&self) {}\n\n}\n\n\n\n/// A dummy console that just ignores its inputs.\n\npub struct NullConsole;\n\nimpl Drop for NullConsole {\n\n fn drop(&mut self) {}\n\n}\n\nimpl ConsoleOps for NullConsole {}\n\n\n\n/// Possible outputs which the console can store.\n\npub enum Output {\n\n None(NullConsole),\n\n MiniUart(platform::rpi3::mini_uart::PreparedMiniUart),\n", "file_path": "nucleus/src/devices/console.rs", "rank": 82, "score": 126596.19925410027 }, { "content": "/*\n\n * SPDX-License-Identifier: BlueOak-1.0.0\n\n * Copyright (c) Berkus Decker <[email protected]>\n\n */\n\n\n\nmod asid;\n\nmod phys_addr;\n\nmod virt_addr;\n\n\n\npub use asid::*;\n\npub use phys_addr::*;\n\npub use virt_addr::*;\n", "file_path": "nucleus/src/arch/aarch64/memory/addr/mod.rs", "rank": 83, "score": 123292.86632582436 }, { "content": "/// Typical operations with a mailbox.\n\npub trait MailboxOps {\n\n /// Deref from self to a mailbox RegisterBlock. Used by Deref implementations.\n\n fn ptr(&self) -> *const RegisterBlock;\n\n fn write(&self, channel: u32) -> Result<()>;\n\n fn read(&self, channel: u32) -> Result<()>;\n\n fn call(&self, channel: u32) -> Result<()> {\n\n self.write(channel)?;\n\n self.read(channel)\n\n }\n\n}\n\n\n\n/*\n\n * Source https://elinux.org/RPi_Framebuffer\n\n * Source for channels 8 and 9: https://github.com/raspberrypi/firmware/wiki/Mailboxes\n\n */\n\n#[allow(non_upper_case_globals)]\n\npub mod channel {\n\n pub const Power: u32 = 0;\n\n pub const FrameBuffer: u32 = 1;\n\n pub const VirtualUart: u32 = 2;\n", "file_path": "nucleus/src/platform/rpi3/mailbox.rs", "rank": 84, "score": 121230.65708347355 }, { "content": "trait BaseAddr {\n\n fn base_addr_u64(&self) -> u64;\n\n fn base_addr_usize(&self) -> usize;\n\n}\n\n\n\nimpl BaseAddr for [u64; 512] {\n\n fn base_addr_u64(&self) -> u64 {\n\n self as *const u64 as u64\n\n }\n\n\n\n fn base_addr_usize(&self) -> usize {\n\n self as *const u64 as usize\n\n }\n\n}\n\n\n\n/// Set up identity mapped page tables for the first 1 gigabyte of address space.\n\n/// default: 880 MB ARM ram, 128MB VC\n\n///\n\n/// # Safety\n\n///\n", "file_path": "nucleus/src/arch/aarch64/memory/mmu.rs", "rank": 85, "score": 119804.09233555637 }, { "content": "#[cfg(test)]\n\n#[panic_handler]\n\nfn panicked(info: &core::panic::PanicInfo) -> ! {\n\n crate::println!(\"\\n[failed]\\n\");\n\n // @todo This may fail to print if the panic message is too long for local print buffer.\n\n crate::println!(\"\\nError: {}\\n\", info);\n\n crate::qemu::semihosting::exit_failure()\n\n}\n", "file_path": "nucleus/src/panic.rs", "rank": 89, "score": 106321.92095277783 }, { "content": "#[cfg(qemu)]\n\n#[link_section = \".text.boot\"]\n\n#[inline]\n\nfn setup_and_enter_el1_from_el3() -> ! {\n\n // Set Secure Configuration Register (EL3)\n\n SCR_EL3.write(SCR_EL3::RW::NextELIsAarch64 + SCR_EL3::NS::NonSecure);\n\n\n\n // Set Saved Program Status Register (EL3)\n\n // Set up a simulated exception return.\n\n //\n\n // Fake a saved program status, where all interrupts were\n\n // masked and SP_EL1 was used as a stack pointer.\n\n SPSR_EL3.write(\n\n SPSR_EL3::D::Masked\n\n + SPSR_EL3::A::Masked\n\n + SPSR_EL3::I::Masked\n\n + SPSR_EL3::F::Masked\n\n + SPSR_EL3::M::EL1h, // Use SP_EL1\n\n );\n\n\n\n // Make the Exception Link Register (EL3) point to reset().\n\n ELR_EL3.set(reset as *const () as u64);\n\n\n", "file_path": "nucleus/src/arch/aarch64/boot.rs", "rank": 90, "score": 104367.89047122347 }, { "content": "#[link_section = \".text.boot\"]\n\n#[inline]\n\nfn shared_setup_and_enter_post() -> ! {\n\n // Set up SP_EL1 (stack pointer), which will be used by EL1 once\n\n // we \"return\" to it.\n\n SP_EL1.set(STACK_START);\n\n\n\n // Use `eret` to \"return\" to EL1. This will result in execution of\n\n // `reset()` in EL1.\n\n asm::eret()\n\n}\n\n\n\n/// Real hardware boot-up sequence.\n\n///\n\n/// Prepare and execute transition from EL2 to EL1.\n", "file_path": "nucleus/src/arch/aarch64/boot.rs", "rank": 91, "score": 104364.0727782558 }, { "content": "#[link_section = \".text.boot\"]\n\n#[inline]\n\nfn shared_setup_and_enter_pre() {\n\n // Enable timer counter registers for EL1\n\n CNTHCTL_EL2.write(CNTHCTL_EL2::EL1PCEN::SET + CNTHCTL_EL2::EL1PCTEN::SET);\n\n\n\n // No virtual offset for reading the counters\n\n CNTVOFF_EL2.set(0);\n\n\n\n // Set System Control Register (EL1)\n\n // Make memory non-cacheable and disable MMU mapping.\n\n // Disable alignment checks, because Rust fmt module uses a little optimization\n\n // that happily reads and writes half-words (ldrh/strh) from/to unaligned addresses.\n\n SCTLR_EL1.write(\n\n SCTLR_EL1::I::NonCacheable\n\n + SCTLR_EL1::C::NonCacheable\n\n + SCTLR_EL1::M::Disable\n\n + SCTLR_EL1::A::Disable\n\n + SCTLR_EL1::SA::Disable\n\n + SCTLR_EL1::SA0::Disable,\n\n );\n\n\n\n // enable_armv6_unaligned_access();\n\n\n\n // Set Hypervisor Configuration Register (EL2)\n\n // Set EL1 execution state to AArch64\n\n // @todo Explain the SWIO bit (SWIO hardwired on Pi3)\n\n HCR_EL2.write(HCR_EL2::RW::EL1IsAarch64 + HCR_EL2::SWIO::SET);\n\n}\n\n\n", "file_path": "nucleus/src/arch/aarch64/boot.rs", "rank": 92, "score": 104364.0727782558 }, { "content": "#[link_section = \".text.boot\"]\n\n#[inline]\n\nfn setup_and_enter_el1_from_el2() -> ! {\n\n // Set Saved Program Status Register (EL2)\n\n // Set up a simulated exception return.\n\n //\n\n // Fake a saved program status, where all interrupts were\n\n // masked and SP_EL1 was used as a stack pointer.\n\n SPSR_EL2.write(\n\n SPSR_EL2::D::Masked\n\n + SPSR_EL2::A::Masked\n\n + SPSR_EL2::I::Masked\n\n + SPSR_EL2::F::Masked\n\n + SPSR_EL2::M::EL1h, // Use SP_EL1\n\n );\n\n\n\n // Make the Exception Link Register (EL2) point to reset().\n\n ELR_EL2.set(reset as *const () as u64);\n\n\n\n shared_setup_and_enter_post()\n\n}\n\n\n\n/// QEMU boot-up sequence.\n\n///\n\n/// Processors enter EL3 after reset.\n\n/// ref: http://infocenter.arm.com/help/topic/com.arm.doc.dai0527a/DAI0527A_baremetal_boot_code_for_ARMv8_A_processors.pdf\n\n/// section: 5.5.1\n\n/// However, GPU init code must be switching it down to EL2.\n\n/// QEMU can't emulate Raspberry Pi properly (no VC boot code), so it starts in EL3.\n\n///\n\n/// Prepare and execute transition from EL3 to EL1.\n\n/// (from https://github.com/s-matyukevich/raspberry-pi-os/blob/master/docs/lesson02/rpi-os.md)\n", "file_path": "nucleus/src/arch/aarch64/boot.rs", "rank": 93, "score": 104364.0727782558 }, { "content": "//! JTAG helper functions.\n\n\n\nuse cortex_a::asm;\n\n\n\n#[no_mangle]\n\nstatic mut WAIT_FLAG: bool = true;\n\n\n\n/// Wait for debugger to attach.\n\n/// Then in gdb issue `> set var *(&WAIT_FLAG) = 0`\n\n/// from inside this function's frame to contiue running.\n", "file_path": "nucleus/src/arch/aarch64/jtag.rs", "rank": 94, "score": 98256.00431566584 }, { "content": " ) -> Result<PreparedPL011Uart> {\n\n // turn off UART0\n\n self.CR.set(0);\n\n\n\n // set up clock for consistent divisor values\n\n let index = mbox.request();\n\n let index = mbox.set_clock_rate(index, mailbox::clock::UART, 4_000_000 /* 4Mhz */);\n\n let mbox = mbox.end(index);\n\n\n\n if mbox.call(mailbox::channel::PropertyTagsArmToVc).is_err() {\n\n return Err(PL011UartError::MailboxError); // Abort if UART clocks couldn't be set\n\n };\n\n\n\n // Pin 14\n\n const UART_TXD: gpio::Function = gpio::Function::Alt0;\n\n // Pin 15\n\n const UART_RXD: gpio::Function = gpio::Function::Alt0;\n\n\n\n // map UART0 to GPIO pins\n\n gpio.get_pin(14).into_alt(UART_TXD);\n", "file_path": "nucleus/src/platform/rpi3/pl011_uart.rs", "rank": 95, "score": 98173.04907708893 }, { "content": " const UART0_BASE: usize = BcmHost::get_peripheral_address() + 0x20_1000;\n\n PL011Uart::new(UART0_BASE)\n\n }\n\n}\n\n\n\nimpl PL011Uart {\n\n pub fn new(base_addr: usize) -> PL011Uart {\n\n PL011Uart { base_addr }\n\n }\n\n\n\n /// Returns a pointer to the register block\n\n fn ptr(&self) -> *const RegisterBlock {\n\n self.base_addr as *const _\n\n }\n\n\n\n /// Set baud rate and characteristics (115200 8N1) and map to GPIO\n\n pub fn prepare(\n\n self,\n\n mut mbox: mailbox::Mailbox,\n\n gpio: &gpio::GPIO,\n", "file_path": "nucleus/src/platform/rpi3/pl011_uart.rs", "rank": 96, "score": 98168.69552428336 }, { "content": "/*\n\n * SPDX-License-Identifier: MIT OR BlueOak-1.0.0\n\n * Copyright (c) 2018-2019 Andre Richter <[email protected]>\n\n * Copyright (c) Berkus Decker <[email protected]>\n\n * Original code distributed under MIT, additional changes are under BlueOak-1.0.0\n\n *\n\n * http://infocenter.arm.com/help/topic/com.arm.doc.ddi0183g/DDI0183G_uart_pl011_r1p5_trm.pdf\n\n * https://docs.rs/embedded-serial/0.5.0/embedded_serial/\n\n */\n\n\n\nuse {\n\n super::{\n\n gpio,\n\n mailbox::{self, MailboxOps},\n\n BcmHost,\n\n },\n\n crate::{arch::loop_until, devices::ConsoleOps},\n\n core::ops,\n\n snafu::Snafu,\n\n tock_registers::{\n", "file_path": "nucleus/src/platform/rpi3/pl011_uart.rs", "rank": 97, "score": 98167.06817614479 } ]
Rust
src/render/pipeline_2d.rs
RomainMazB/bevy_svg
da7acfe562a77151c33e995240d7ef40f803a5ff
use bevy::{ asset::Handle, core::FloatOrd, core_pipeline::Transparent2d, ecs::{entity::Entity, query::With, world::{FromWorld, World}, system::{Query, Res, ResMut},}, log::debug, render::{ mesh::Mesh, render_asset::RenderAssets, render_phase::{DrawFunctions, RenderPhase, SetItemPipeline}, render_resource::{ BlendState, ColorTargetState, ColorWrites, FragmentState, FrontFace, MultisampleState, PolygonMode, PrimitiveState, RenderPipelineCache, RenderPipelineDescriptor, Shader, SpecializedPipeline, SpecializedPipelines, TextureFormat, VertexAttribute, VertexBufferLayout, VertexFormat, VertexState, VertexStepMode, }, texture::BevyDefault, view::{ComputedVisibility, Msaa}, RenderWorld, }, sprite::{ DrawMesh2d, Mesh2dHandle, Mesh2dPipeline, Mesh2dPipelineKey, SetMesh2dBindGroup, SetMesh2dViewBindGroup, }, transform::components::GlobalTransform, }; use copyless::VecHelper; use crate::{render::SVG_2D_SHADER_HANDLE, svg::Svg}; #[derive(Default)] pub struct ExtractedSvgs2d { svgs: Vec<ExtractedSvg2d>, } #[derive(Clone)] pub struct ExtractedSvg2d { pub entity: Entity, pub mesh2d_handle: Mesh2dHandle, pub global_transform: GlobalTransform } pub fn extract_svg_2d( mut render_world: ResMut<RenderWorld>, query: Query<(Entity, &ComputedVisibility, &Mesh2dHandle, &GlobalTransform), With<Handle<Svg>>>, ) { debug!("Extracting `Svg`s from `World`."); let mut extracted_svgs = render_world.get_resource_mut::<ExtractedSvgs2d>().unwrap(); extracted_svgs.svgs.clear(); for (entity, computed_visibility, mesh2d_handle, global_transform) in query.iter() { if !computed_visibility.is_visible { continue; } extracted_svgs.svgs.alloc().init(ExtractedSvg2d { entity, mesh2d_handle: mesh2d_handle.clone(), global_transform: global_transform.clone(), }); } debug!("Extracted {} `Svg2d`s from `World` and inserted them into `RenderWorld`.", extracted_svgs.svgs.len()); } #[allow(clippy::too_many_arguments)] pub fn queue_svg_2d( transparent_draw_functions: Res<DrawFunctions<Transparent2d>>, svg_2d_pipeline: Res<Svg2dPipeline>, mut pipelines: ResMut<SpecializedPipelines<Svg2dPipeline>>, mut pipeline_cache: ResMut<RenderPipelineCache>, msaa: Res<Msaa>, render_meshes: Res<RenderAssets<Mesh>>, svgs_2d: ResMut<ExtractedSvgs2d>, mut views: Query<&mut RenderPhase<Transparent2d>>, ) { if svgs_2d.svgs.is_empty() { debug!("No `Svg2d`s found to queue."); return; } debug!("Queuing {} `Svg2d`s for drawing/rendering.", svgs_2d.svgs.len()); let mesh_key = Mesh2dPipelineKey::from_msaa_samples(msaa.samples); let draw_svg_2d = transparent_draw_functions .read() .get_id::<DrawSvg2d>() .unwrap(); for mut transparent_phase in views.iter_mut() { for svg2d in &svgs_2d.svgs { let mut mesh2d_key = mesh_key; if let Some(mesh) = render_meshes.get(&svg2d.mesh2d_handle.0) { mesh2d_key |= Mesh2dPipelineKey::from_primitive_topology(mesh.primitive_topology); } let pipeline_id = pipelines.specialize(&mut pipeline_cache, &svg_2d_pipeline, mesh2d_key); let mesh_z = svg2d.global_transform.translation.z; transparent_phase.add(Transparent2d { entity: svg2d.entity, draw_function: draw_svg_2d, pipeline: pipeline_id, sort_key: FloatOrd(mesh_z), batch_range: None, }); } } } pub type DrawSvg2d = ( SetItemPipeline, SetMesh2dViewBindGroup<0>, SetMesh2dBindGroup<1>, DrawMesh2d, ); pub struct Svg2dPipeline { mesh2d_pipeline: Mesh2dPipeline, } impl FromWorld for Svg2dPipeline { fn from_world(world: &mut World) -> Self { Self { mesh2d_pipeline: Mesh2dPipeline::from_world(world), } } } impl SpecializedPipeline for Svg2dPipeline { type Key = Mesh2dPipelineKey; fn specialize(&self, key: Self::Key) -> RenderPipelineDescriptor { let vertex_attributes = vec![ VertexAttribute { format: VertexFormat::Float32x3, offset: 16, shader_location: 0, }, VertexAttribute { format: VertexFormat::Float32x4, offset: 0, shader_location: 1, }, ]; let vertex_array_stride = 28; RenderPipelineDescriptor { vertex: VertexState { shader: SVG_2D_SHADER_HANDLE.typed::<Shader>(), entry_point: "vertex".into(), shader_defs: Vec::new(), buffers: vec![VertexBufferLayout { array_stride: vertex_array_stride, step_mode: VertexStepMode::Vertex, attributes: vertex_attributes, }], }, fragment: Some(FragmentState { shader: SVG_2D_SHADER_HANDLE.typed::<Shader>(), shader_defs: Vec::new(), entry_point: "fragment".into(), targets: vec![ColorTargetState { format: TextureFormat::bevy_default(), blend: Some(BlendState::ALPHA_BLENDING), write_mask: ColorWrites::ALL, }], }), layout: Some(vec![ self.mesh2d_pipeline.view_layout.clone(), self.mesh2d_pipeline.mesh_layout.clone(), ]), primitive: PrimitiveState { front_face: FrontFace::Cw, cull_mode: None, unclipped_depth: false, polygon_mode: PolygonMode::Fill, conservative: false, topology: key.primitive_topology(), strip_index_format: None, }, depth_stencil: None, multisample: MultisampleState { count: key.msaa_samples(), mask: !0, alpha_to_coverage_enabled: false, }, label: Some("svg_2d_pipeline".into()), } } }
use bevy::{ asset::Handle, core::FloatOrd, core_pipeline::Transparent2d, ecs::{entity::Entity, query::With, world::{FromWorld, World}, system::{Query, Res, ResMut},}, log::debug, render::{ mesh::Mesh, render_asset::RenderAssets, render_phase::{DrawFunctions, RenderPhase, SetItemPipeline}, render_resource::{ BlendState, ColorTargetState, ColorWrites, FragmentState, FrontFace, MultisampleState, PolygonMode, PrimitiveState, RenderPipelineCache, RenderPipelineDescriptor, Shader, SpecializedPipeline, SpecializedPipelines, TextureFormat, VertexAttribute, VertexBufferLayout, VertexFormat, VertexState, VertexStepMode, }, texture::BevyDefault, view::{ComputedVisibility, Msaa}, RenderWorld, }, sprite::{ DrawMesh2d, Mesh2dHandle, Mesh2dPipeline, Mesh2dPipelineKey, SetMesh2dBindGroup, SetMesh2dViewBindGroup, }, transform::components::GlobalTransform, }; use copyless::VecHelper; use crate::{render::SVG_2D_SHADER_HANDLE, svg::Svg}; #[derive(Default)] pub struct ExtractedSvgs2d { svgs: Vec<ExtractedSvg2d>, } #[derive(Clone)] pub struct ExtractedSvg2d { pub entity: Entity, pub mesh2d_handle: Mesh2dHandle, pub global_transform: GlobalTransform } pub fn extract_svg_2d( mut render_world: ResMut<RenderWorld>, query: Query<(Entity, &ComputedVisibility, &Mesh2dHandle, &GlobalTransform), With<Handle<Svg>>>, ) { debug!("Extracting `Svg`s from `World`."); let mut extracted_svgs = render_world.get_resource_mut::<ExtractedSvgs2d>().unwrap(); extracted_svgs.svgs.clear(); for (entity, computed_visibility, mesh2d_handle, global_transform) in query.iter() { if !computed_visibility.is_visible { continue; } extracted_svgs.svgs.alloc().init(ExtractedSvg2d { entity, mesh2d_handle: mesh2d_handle.clone(), global_transform: global_transform.clone(), }); } debug!("Extracted {} `Svg2d`s from `World` and inserted them into `RenderWorld`.", extracted_svgs.svgs.len()); } #[allow(clippy::too_many_arguments)] pub fn queue_svg_2d( transparent_draw_functions: Res<DrawFunctions<Transparent2d>>, svg_2d_pipeline: Res<Svg2dPipeline>, mut pipelines: ResMut<SpecializedPipelines<Svg2dPipeline>>, mut pipeline_cache: ResMut<RenderPipelineCache>, msaa: Res<Msaa>, render_meshes: Res<RenderAssets<Mesh>>, svgs_2d: ResMut<ExtractedSvgs2d>, mut views: Query<&mut RenderPhase<Transparent2d>>, ) { if svgs_2d.svgs.is_empty() { debug!("No `Svg2d`s found to queue."); return; } debug!("Queuing {} `Svg2d`s for drawing/rendering.", svgs_2d.svgs.len()); let mesh_key = Mesh2dPipelineKey::from_msaa_samples(msaa.samples); let draw_svg_2d = transparent_draw_functions .read() .get_id::<DrawSvg2d>() .unwrap(); for mut transparent_phase in views.iter_mut() { for svg2d in &svgs_2d.svgs { let mut mesh2d_key = mesh_key; if let Some(mesh) = render_meshes.get(&svg2d.mesh2d_handle.0) { mesh2d_key |= Mesh2dPipelineKey::from_primitive_topology(mesh.primitive_topology); } let pipeline_id = pipelines.specialize(&mut pipeline_cache, &svg_2d_pipeline, mesh2d_key); let mesh_z = svg2d.global_transform.translation.z; transparent_phase.add(Transparent2d { entity: svg2d.entity, draw_function: draw_svg_2d, pipeline: pipeline_id, sort_key: FloatOrd(mesh_z), batch_range: None, }); } } } pub type DrawSvg2d = ( SetItemPipeline, SetMesh2dViewBindGroup<0>, SetMesh2dBindGroup<1>, DrawMesh2d, ); pub struct Svg2dPipeline { mesh2d_pipeline: Mesh2dPipeline, } impl FromWorld for Svg2dPipeline { fn from_world(world: &mut World) -> Self { Self { mesh2d_pipeline: Mesh2dPipeline::from_world(world), } } } impl SpecializedPipeline for Svg2dPipeline { type Key = Mesh2dPipelineKey; fn specialize(&self, key: Self::Key) -> RenderPipelineDescriptor { let vertex_attributes = vec![ VertexAttribute { format: VertexFormat::Float32x3, offset: 16, shader_location: 0, }, VertexAttribute { format: VertexFormat::Float32x4, offset: 0, shader_location: 1, }, ]; let vertex_array_stride = 28; RenderPipelineDescriptor { vertex: VertexState { shader: SVG_2D_SHADER_HANDLE.typed::<Shader>(), entry_point: "vertex".into(), shader_defs: Vec::new(), buffers: vec![VertexBufferLayout { array_stride: vertex_array_stride, step_mode: VertexStepMode::Vertex, attributes: vertex_attributes, }], }, fragment: Some(FragmentState { shader: SVG_2D_SHADER_HANDLE.typed::<Shader>(), shader_defs: Vec::new(), entry_point: "fragment".into(), targets: vec![ColorTargetState { format: TextureFormat::bevy_default(), blend: Some(BlendState::ALPHA_BLENDING), write_mask: ColorWrites::ALL, }], }), layout:
, primitive: PrimitiveState { front_face: FrontFace::Cw, cull_mode: None, unclipped_depth: false, polygon_mode: PolygonMode::Fill, conservative: false, topology: key.primitive_topology(), strip_index_format: None, }, depth_stencil: None, multisample: MultisampleState { count: key.msaa_samples(), mask: !0, alpha_to_coverage_enabled: false, }, label: Some("svg_2d_pipeline".into()), } } }
Some(vec![ self.mesh2d_pipeline.view_layout.clone(), self.mesh2d_pipeline.mesh_layout.clone(), ])
call_expression
[ { "content": "#[allow(clippy::too_many_arguments)]\n\npub fn queue_svg_3d(\n\n transparent_draw_functions: Res<DrawFunctions<Transparent3d>>,\n\n svg_3d_pipeline: Res<Svg3dPipeline>,\n\n mut pipelines: ResMut<SpecializedPipelines<Svg3dPipeline>>,\n\n mut pipeline_cache: ResMut<RenderPipelineCache>,\n\n msaa: Res<Msaa>,\n\n render_meshes: Res<RenderAssets<Mesh>>,\n\n svgs_3d: ResMut<ExtractedSvgs3d>,\n\n mut views: Query<&mut RenderPhase<Transparent3d>>,\n\n) {\n\n if svgs_3d.svgs.is_empty() {\n\n debug!(\"No `Svg3d`s found to queue.\");\n\n return;\n\n }\n\n debug!(\"Queuing {} `Svg3d`s for drawing/rendering.\", svgs_3d.svgs.len());\n\n let mesh_key = MeshPipelineKey::from_msaa_samples(msaa.samples);\n\n let draw_svg_3d = transparent_draw_functions\n\n .read()\n\n .get_id::<DrawSvg3d>()\n\n .unwrap();\n", "file_path": "src/render/pipeline_3d.rs", "rank": 1, "score": 147089.05632616213 }, { "content": "/// Extract [`Svg`]s with a [`Handle`] to a [`Mesh`] component into [`RenderWorld`].\n\npub fn extract_svg_3d(\n\n mut render_world: ResMut<RenderWorld>,\n\n query: Query<(Entity, &ComputedVisibility, &Handle<Mesh>, &GlobalTransform), With<Handle<Svg>>>,\n\n) {\n\n debug!(\"Extracting `Svg`s from `World`.\");\n\n let mut extracted_svgs = render_world.get_resource_mut::<ExtractedSvgs3d>().unwrap();\n\n extracted_svgs.svgs.clear();\n\n for (entity, computed_visibility, mesh3d_handle, global_transform) in query.iter() {\n\n if !computed_visibility.is_visible {\n\n continue;\n\n }\n\n extracted_svgs.svgs.alloc().init(ExtractedSvg3d {\n\n entity,\n\n mesh3d_handle: mesh3d_handle.clone(),\n\n global_transform: global_transform.clone(),\n\n });\n\n }\n\n\n\n debug!(\"Extracted {} `Svg3d`s from `World` and inserted them into `RenderWorld`.\", extracted_svgs.svgs.len());\n\n}\n\n\n\n/// Queue all extraced 3D [`Svg`]s for rendering with the [`Svg3dPipeline`] custom pipeline and [`DrawSvg3d`] draw function\n", "file_path": "src/render/pipeline_3d.rs", "rank": 3, "score": 125353.8636739541 }, { "content": "\n\n/// The index type of a Bevy [`Mesh`](bevy::render::mesh::Mesh).\n\npub(crate) type IndexType = u32;\n\n\n\n/// Lyon's [`VertexBuffers`] generic data type defined for [`Vertex`].\n\npub(crate) type VertexBuffers = lyon_tessellation::VertexBuffers<Vertex, IndexType>;\n\n\n\nimpl Convert<Mesh> for VertexBuffers {\n\n fn convert(self) -> Mesh {\n\n let mut positions = Vec::with_capacity(self.vertices.len());\n\n let mut colors = Vec::with_capacity(self.vertices.len());\n\n\n\n self.vertices.iter().for_each(|v| {\n\n positions.push(v.position);\n\n colors.push(v.color);\n\n });\n\n\n\n let mut mesh = Mesh::new(PrimitiveTopology::TriangleList);\n\n mesh.set_indices(Some(Indices::U32(self.indices.clone())));\n\n mesh.set_attribute(\n", "file_path": "src/render/vertex_buffer.rs", "rank": 4, "score": 69444.11660316086 }, { "content": "use bevy::{\n\n math::Vec3,\n\n render::{\n\n color::Color, mesh::{Indices, Mesh},\n\n render_resource::PrimitiveTopology,\n\n },\n\n transform::components::Transform,\n\n};\n\nuse lyon_tessellation::{self, FillVertex, FillVertexConstructor, StrokeVertex, StrokeVertexConstructor};\n\n\n\nuse crate::Convert;\n\n\n\n\n\n/// A vertex with all the necessary attributes to be inserted into a Bevy\n\n/// [`Mesh`](bevy::render::mesh::Mesh).\n\n#[derive(Debug, Clone, Copy, PartialEq)]\n\npub(crate) struct Vertex {\n\n position: [f32; 3],\n\n color: [f32; 4],\n\n}\n", "file_path": "src/render/vertex_buffer.rs", "rank": 5, "score": 69439.89127267906 }, { "content": " vertex.x,\n\n vertex.y,\n\n 0.0,\n\n );\n\n\n\n Vertex {\n\n position: [pos.x, pos.y, pos.z],\n\n color: self.color.as_linear_rgba_f32(),\n\n }\n\n }\n\n}\n\n\n\npub(crate) trait BufferExt<A> {\n\n fn extend_one(&mut self, item: A);\n\n fn extend<T: IntoIterator<Item = A>>(&mut self, iter: T);\n\n}\n\n\n\nimpl BufferExt<VertexBuffers> for VertexBuffers {\n\n\n\n fn extend_one(&mut self, item: VertexBuffers) {\n", "file_path": "src/render/vertex_buffer.rs", "rank": 6, "score": 69437.7129774267 }, { "content": " Mesh::ATTRIBUTE_POSITION,\n\n positions\n\n );\n\n mesh.set_attribute(\n\n Mesh::ATTRIBUTE_COLOR,\n\n colors\n\n );\n\n\n\n mesh\n\n }\n\n}\n\n\n\n/// Zero-sized type used to implement various vertex construction traits from Lyon.\n\npub(crate) struct VertexConstructor {\n\n pub(crate) color: Color,\n\n pub(crate) transform: Transform,\n\n}\n\n\n\n/// Enables the construction of a [`Vertex`] when using a `FillTessellator`.\n\nimpl FillVertexConstructor<Vertex> for VertexConstructor {\n", "file_path": "src/render/vertex_buffer.rs", "rank": 7, "score": 69437.55647331399 }, { "content": " fn new_vertex(&mut self, vertex: FillVertex) -> Vertex {\n\n let vertex = vertex.position();\n\n let pos = self.transform * Vec3::new(\n\n vertex.x,\n\n vertex.y,\n\n 0.0,\n\n );\n\n\n\n Vertex {\n\n position: [pos.x, pos.y, pos.z],\n\n color: self.color.as_linear_rgba_f32(),\n\n }\n\n }\n\n}\n\n\n\n/// Enables the construction of a [`Vertex`] when using a `StrokeTessellator`.\n\nimpl StrokeVertexConstructor<Vertex> for VertexConstructor {\n\n fn new_vertex(&mut self, vertex: StrokeVertex) -> Vertex {\n\n let vertex = vertex.position();\n\n let pos = self.transform * Vec3::new(\n", "file_path": "src/render/vertex_buffer.rs", "rank": 8, "score": 69433.84834412007 }, { "content": " let offset = self.vertices.len() as u32;\n\n\n\n self.vertices.extend(&item.vertices);\n\n self.indices.extend(item.indices.iter().map(|i| i + offset));\n\n }\n\n\n\n fn extend<T: IntoIterator<Item = VertexBuffers>>(&mut self, iter: T) {\n\n let mut offset = self.vertices.len() as u32;\n\n\n\n for buf in iter {\n\n self.vertices.extend(&buf.vertices);\n\n self.indices.extend(buf.indices.iter().map(|i| i + offset));\n\n\n\n offset += buf.vertices.len() as u32;\n\n }\n\n }\n\n}\n", "file_path": "src/render/vertex_buffer.rs", "rank": 9, "score": 69433.7564992741 }, { "content": "// Taken from https://github.com/nical/lyon/blob/74e6b137fea70d71d3b537babae22c6652f8843e/examples/wgpu_svg/src/main.rs\n\nstruct PathConvIter<'a> {\n\n iter: std::slice::Iter<'a, usvg::PathSegment>,\n\n prev: Point,\n\n first: Point,\n\n needs_end: bool,\n\n deferred: Option<PathEvent>,\n\n scale: Transform2D<f32>,\n\n}\n\n\n\nimpl<'l> Iterator for PathConvIter<'l> {\n\n type Item = PathEvent;\n\n\n\n fn next(&mut self) -> Option<Self::Item> {\n\n if self.deferred.is_some() {\n\n return self.deferred.take();\n\n }\n\n let mut return_event = None;\n\n let next = self.iter.next();\n\n match next {\n\n Some(usvg::PathSegment::MoveTo { x, y }) => {\n", "file_path": "src/svg.rs", "rank": 10, "score": 60682.07161469472 }, { "content": "/// Bevy system which queries for all [`Svg`](crate::svg::Svg)s and tessellates them into a mesh.\n\nfn svg_mesh_maker(\n\n mut svg_events: EventReader<AssetEvent<Svg>>,\n\n svgs: Res<Assets<Svg>>,\n\n mut meshes: ResMut<Assets<Mesh>>,\n\n mut fill_tess: ResMut<FillTessellator>,\n\n mut stroke_tess: ResMut<StrokeTessellator>,\n\n mut query: Query<\n\n (Entity, &Handle<Svg>, Option<&mut Mesh2dHandle>, Option<&mut Handle<Mesh>>, &Origin, &mut Transform),\n\n >,\n\n) {\n\n for event in svg_events.iter() {\n\n match event {\n\n AssetEvent::Created { handle } | AssetEvent::Modified { handle } => {\n\n let mut tesselated_mesh = None;\n\n for (_, _, mesh_2d, mesh_3d, origin, mut transform) in query.iter_mut().filter(|(_, svg, _, _, _, _)| svg == &handle) {\n\n let svg = svgs.get(handle).unwrap();\n\n if tesselated_mesh.is_none() {\n\n debug!(\"Make mesh for SVG: {}\", svg.name);\n\n let buffer = tessellation::generate_buffer(&svg, &mut fill_tess, &mut stroke_tess);\n\n tesselated_mesh = Some(meshes.add(buffer.convert()));\n", "file_path": "src/plugin.rs", "rank": 11, "score": 51012.74609306459 }, { "content": "use bevy::{\n\n asset::Handle,\n\n core_pipeline::Transparent3d,\n\n ecs::{entity::Entity, query::With, world::{FromWorld, World}, system::{Query, Res, ResMut},},\n\n log::debug,\n\n render::{\n\n mesh::Mesh,\n\n render_asset::RenderAssets,\n\n render_phase::{DrawFunctions, RenderPhase, SetItemPipeline},\n\n render_resource::{\n\n BlendState, ColorTargetState, ColorWrites, FragmentState, FrontFace,\n\n MultisampleState, PolygonMode, PrimitiveState, RenderPipelineCache,\n\n RenderPipelineDescriptor, Shader, SpecializedPipeline, SpecializedPipelines, TextureFormat,\n\n VertexAttribute, VertexBufferLayout, VertexFormat, VertexState, VertexStepMode,\n\n },\n\n texture::BevyDefault,\n\n view::{ComputedVisibility, Msaa}, RenderWorld,\n\n },\n\n transform::components::GlobalTransform, pbr::{MeshPipeline, MeshPipelineKey, SetMeshViewBindGroup, SetMeshBindGroup, DrawMesh},\n\n};\n", "file_path": "src/render/pipeline_3d.rs", "rank": 14, "score": 47184.741279197464 }, { "content": " entry_point: \"vertex\".into(),\n\n shader_defs: Vec::new(),\n\n // Use our custom vertex buffer\n\n buffers: vec![VertexBufferLayout {\n\n array_stride: vertex_array_stride,\n\n step_mode: VertexStepMode::Vertex,\n\n attributes: vertex_attributes,\n\n }],\n\n },\n\n fragment: Some(FragmentState {\n\n // Use our custom shader\n\n shader: SVG_3D_SHADER_HANDLE.typed::<Shader>(),\n\n shader_defs: Vec::new(),\n\n entry_point: \"fragment\".into(),\n\n targets: vec![ColorTargetState {\n\n format: TextureFormat::bevy_default(),\n\n blend: Some(BlendState::ALPHA_BLENDING),\n\n write_mask: ColorWrites::ALL,\n\n }],\n\n }),\n", "file_path": "src/render/pipeline_3d.rs", "rank": 15, "score": 47182.962499064146 }, { "content": "}\n\n\n\nimpl FromWorld for Svg3dPipeline {\n\n fn from_world(world: &mut World) -> Self {\n\n Self {\n\n mesh3d_pipeline: MeshPipeline::from_world(world),\n\n }\n\n }\n\n}\n\n\n\n// Specializie the `Mesh2dPipeline` to draw [`Svg`]s in 2D.\n\nimpl SpecializedPipeline for Svg3dPipeline {\n\n type Key = MeshPipelineKey;\n\n\n\n fn specialize(&self, key: Self::Key) -> RenderPipelineDescriptor {\n\n // Customize how to store the meshes' vertex attributes in the vertex buffer\n\n // Meshes for our Svgs only have position and color\n\n let vertex_attributes = vec![\n\n // Position (GOTCHA! Vertex_Position isn't first in the buffer due to how Mesh sorts attributes (alphabetically))\n\n VertexAttribute {\n", "file_path": "src/render/pipeline_3d.rs", "rank": 17, "score": 47181.97201967229 }, { "content": " format: VertexFormat::Float32x3,\n\n // this offset is the size of the color attribute, which is stored first\n\n offset: 16,\n\n // position is available at location 0 in the shader\n\n shader_location: 0,\n\n },\n\n // Color\n\n VertexAttribute {\n\n format: VertexFormat::Float32x4,\n\n offset: 0,\n\n shader_location: 1,\n\n },\n\n ];\n\n // Sum of the size of position and color attributes (12 + 16 = 28)\n\n let vertex_array_stride = 28;\n\n\n\n RenderPipelineDescriptor {\n\n vertex: VertexState {\n\n // Use our custom shader\n\n shader: SVG_3D_SHADER_HANDLE.typed::<Shader>(),\n", "file_path": "src/render/pipeline_3d.rs", "rank": 20, "score": 47175.649615374925 }, { "content": "\n\n // Iterate each view (a camera is a view)\n\n for mut transparent_phase in views.iter_mut() {\n\n // Queue all entities visible to that view\n\n for svg3d in &svgs_3d.svgs {\n\n // Get our specialized pipeline\n\n let mut mesh3d_key = mesh_key;\n\n if let Some(mesh) = render_meshes.get(&svg3d.mesh3d_handle) {\n\n mesh3d_key |= MeshPipelineKey::from_primitive_topology(mesh.primitive_topology);\n\n }\n\n\n\n let pipeline_id = pipelines.specialize(&mut pipeline_cache, &svg_3d_pipeline, mesh3d_key);\n\n let mesh_z = svg3d.global_transform.translation.z;\n\n transparent_phase.add(Transparent3d {\n\n entity: svg3d.entity,\n\n draw_function: draw_svg_3d,\n\n pipeline: pipeline_id,\n\n // The 2d render items are sorted according to their z value before rendering,\n\n // in order to get correct transparency\n\n distance: mesh_z,\n", "file_path": "src/render/pipeline_3d.rs", "rank": 22, "score": 47173.36693261605 }, { "content": "use copyless::VecHelper;\n\n\n\nuse crate::{render::SVG_3D_SHADER_HANDLE, svg::Svg};\n\n\n\n\n\n#[derive(Default)]\n\npub struct ExtractedSvgs3d {\n\n svgs: Vec<ExtractedSvg3d>,\n\n}\n\n\n\n#[derive(Clone)]\n\npub struct ExtractedSvg3d {\n\n pub entity: Entity,\n\n pub mesh3d_handle: Handle<Mesh>,\n\n pub global_transform: GlobalTransform\n\n}\n\n\n\n/// Extract [`Svg`]s with a [`Handle`] to a [`Mesh`] component into [`RenderWorld`].\n", "file_path": "src/render/pipeline_3d.rs", "rank": 23, "score": 47173.188195017196 }, { "content": " // Use the two standard uniforms for 2d meshes\n\n layout: Some(vec![\n\n // Bind group 0 is the view uniform\n\n self.mesh3d_pipeline.view_layout.clone(),\n\n // Bind group 1 is the mesh uniform\n\n self.mesh3d_pipeline.mesh_layout.clone(),\n\n ]),\n\n primitive: PrimitiveState {\n\n front_face: FrontFace::Cw,\n\n cull_mode: None,\n\n unclipped_depth: false,\n\n polygon_mode: PolygonMode::Fill,\n\n conservative: false,\n\n topology: key.primitive_topology(),\n\n strip_index_format: None,\n\n },\n\n depth_stencil: Some(bevy::render::render_resource::DepthStencilState {\n\n format: TextureFormat::Depth32Float,\n\n depth_write_enabled: false,\n\n depth_compare: bevy::render::render_resource::CompareFunction::Greater,\n", "file_path": "src/render/pipeline_3d.rs", "rank": 24, "score": 47172.99849189879 }, { "content": " stencil: bevy::render::render_resource::StencilState {\n\n front: bevy::render::render_resource::StencilFaceState::IGNORE,\n\n back: bevy::render::render_resource::StencilFaceState::IGNORE,\n\n read_mask: 0,\n\n write_mask: 0,\n\n },\n\n bias: bevy::render::render_resource::DepthBiasState {\n\n constant: 0,\n\n slope_scale: 0.0,\n\n clamp: 0.0,\n\n },\n\n }),\n\n multisample: MultisampleState {\n\n count: key.msaa_samples(),\n\n mask: !0,\n\n alpha_to_coverage_enabled: false,\n\n },\n\n label: Some(\"svg_3d_pipeline\".into()),\n\n }\n\n }\n\n}\n", "file_path": "src/render/pipeline_3d.rs", "rank": 27, "score": 47168.43015875048 }, { "content": " });\n\n }\n\n }\n\n}\n\n\n\n/// Specifies how to render a [`Svg`] in 2d.\n\npub type DrawSvg3d = (\n\n // Set the pipeline\n\n SetItemPipeline,\n\n // Set the view uniform as bind group 0\n\n SetMeshViewBindGroup<0>,\n\n // Set the mesh uniform as bind group 1\n\n SetMeshBindGroup<1>,\n\n // Draw the mesh\n\n DrawMesh,\n\n);\n\n\n\n// Pipeline for 2d [`Svg`]s.\n\npub struct Svg3dPipeline {\n\n mesh3d_pipeline: MeshPipeline,\n", "file_path": "src/render/pipeline_3d.rs", "rank": 28, "score": 47166.9115682029 }, { "content": "/// A locally defined [`std::convert::Into`] surrogate to overcome orphan rules.\n\npub trait Convert<T>: Sized {\n\n /// Converts the value to `T`.\n\n fn convert(self) -> T;\n\n}\n", "file_path": "src/lib.rs", "rank": 29, "score": 33934.44812393222 }, { "content": "fn setup(\n\n mut commands: Commands,\n\n asset_server: Res<AssetServer>,\n\n) {\n\n let svg = asset_server.load(\"twinkle.svg\");\n\n commands.spawn_bundle(PerspectiveCameraBundle {\n\n transform: Transform::from_xyz(5.0, 8.0, 8.0).looking_at(Vec3::ZERO, Vec3::Y),\n\n ..Default::default()\n\n });\n\n commands.spawn_bundle(Svg3dBundle {\n\n svg,\n\n origin: Origin::Center,\n\n transform: Transform {\n\n translation: Vec3::new(0.0, 0.0, -1.0),\n\n scale: Vec3::new(0.01, 0.01, 1.0),\n\n rotation: Quat::from_rotation_x(-std::f32::consts::PI / 5.0),\n\n },\n\n ..Default::default()\n\n });\n\n}\n", "file_path": "examples/3d/twinkle.rs", "rank": 30, "score": 31758.472578699522 }, { "content": "fn setup(\n\n mut commands: Commands,\n\n asset_server: Res<AssetServer>,\n\n) {\n\n let svg = asset_server.load(\"twinkle.svg\");\n\n commands.spawn_bundle(OrthographicCameraBundle::new_2d());\n\n let mut transform = Transform::from_xyz(0.0, 0.0, 0.0);\n\n transform.scale = Vec3::new(0.75, 0.75, 1.0);\n\n commands.spawn_bundle(Svg2dBundle {\n\n svg,\n\n origin: Origin::Center,\n\n transform,\n\n ..Default::default()\n\n });\n\n}\n", "file_path": "examples/2d/twinkle.rs", "rank": 31, "score": 31758.472578699522 }, { "content": "fn main() {\n\n App::new()\n\n .insert_resource(Msaa { samples: 4 })\n\n .insert_resource(WindowDescriptor {\n\n title: \"twinkle\".to_string(),\n\n width: 400.0,\n\n height: 400.0,\n\n ..Default::default()\n\n })\n\n .add_plugins(DefaultPlugins)\n\n .add_plugin(bevy_svg::prelude::SvgPlugin)\n\n .add_startup_system(setup)\n\n .run();\n\n}\n\n\n", "file_path": "examples/3d/twinkle.rs", "rank": 32, "score": 31758.472578699522 }, { "content": "fn main() {\n\n App::new()\n\n .insert_resource(Msaa { samples: 4 })\n\n .insert_resource(WindowDescriptor {\n\n title: \"twinkle\".to_string(),\n\n width: 400.0,\n\n height: 400.0,\n\n ..Default::default()\n\n })\n\n .add_plugins(DefaultPlugins)\n\n .add_plugin(bevy_svg::prelude::SvgPlugin)\n\n .add_startup_system(setup)\n\n .run();\n\n}\n\n\n", "file_path": "examples/2d/twinkle.rs", "rank": 33, "score": 31758.472578699522 }, { "content": "fn setup(\n\n mut commands: Commands,\n\n asset_server: Res<AssetServer>,\n\n) {\n\n let svg = asset_server.load(\"neutron_star.svg\");\n\n commands.spawn_bundle(PerspectiveCameraBundle {\n\n transform: Transform::from_xyz(5.0, 8.0, 8.0).looking_at(Vec3::ZERO, Vec3::Y),\n\n ..Default::default()\n\n });\n\n commands.spawn_bundle(Svg3dBundle {\n\n svg: svg.clone(),\n\n origin: Origin::Center,\n\n transform: Transform {\n\n translation: Vec3::new(0.0, 0.0, 1.5),\n\n scale: Vec3::new(0.05, 0.05, 1.0),\n\n rotation: Quat::from_rotation_x(-std::f32::consts::PI / 5.0),\n\n },\n\n ..Default::default()\n\n });\n\n commands.spawn_bundle(Svg3dBundle {\n", "file_path": "examples/3d/two_colors.rs", "rank": 34, "score": 30502.846905842394 }, { "content": "fn setup(\n\n mut commands: Commands,\n\n asset_server: Res<AssetServer>,\n\n) {\n\n let svg = asset_server.load(\"neutron_star.svg\");\n\n commands.spawn_bundle(OrthographicCameraBundle::new_2d());\n\n commands.spawn_bundle(Svg2dBundle {\n\n svg,\n\n origin: Origin::Center,\n\n ..Default::default()\n\n });\n\n}\n", "file_path": "examples/2d/two_colors.rs", "rank": 35, "score": 30502.846905842394 }, { "content": "fn main() {\n\n App::new()\n\n .insert_resource(Msaa { samples: 4 })\n\n .insert_resource(WindowDescriptor {\n\n title: \"two_colors\".to_string(),\n\n width: 400.0,\n\n height: 400.0,\n\n ..Default::default()\n\n })\n\n .add_plugins(DefaultPlugins)\n\n .add_plugin(bevy_svg::prelude::SvgPlugin)\n\n .add_startup_system(setup)\n\n .run();\n\n}\n\n\n", "file_path": "examples/2d/two_colors.rs", "rank": 36, "score": 30502.846905842394 }, { "content": "fn main() {\n\n App::new()\n\n .insert_resource(Msaa { samples: 4 })\n\n .insert_resource(WindowDescriptor {\n\n title: \"two_colors\".to_string(),\n\n width: 400.0,\n\n height: 400.0,\n\n ..Default::default()\n\n })\n\n .add_plugins(DefaultPlugins)\n\n .add_plugin(bevy_svg::prelude::SvgPlugin)\n\n .add_startup_system(setup)\n\n .run();\n\n}\n\n\n", "file_path": "examples/3d/two_colors.rs", "rank": 37, "score": 30502.846905842394 }, { "content": "# Stable\n\nbevy_svg = \"0.6\"\n\n\n\n# 2D and 3D are available on default, if you only want/need one, use the following\n\nbevy_svg = { version = \"0.6\", default-features = false, features = \"2d\" }\n\n# or\n\nbevy_svg = { version = \"0.6\", default-features = false, features = \"3d\" }\n\n\n\n# Living on the edge (at your own risk 😅)\n\nbevy_svg = { git = \"https://github.com/Weasy666/bevy_svg\", branch = \"main\" }\n\n```\n\n\n\nThen use it like this.\n\n\n\n### 2D\n\n```rust\n\nfn main() {\n\n App::new()\n\n .insert_resource(Msaa { samples: 4 })\n\n .insert_resource(WindowDescriptor {\n\n title: \"SVG Plugin\".to_string(),\n\n ..Default::default()\n\n })\n\n .add_plugins(DefaultPlugins)\n\n .add_plugin(bevy_svg::prelude::SvgPlugin)\n\n .add_startup_system(setup.system());\n\n .run();\n\n}\n\n\n\nfn setup(\n\n mut commands: Commands,\n\n asset_server: Res<AssetServer>,\n\n) {\n\n let svg = asset_server.load(\"path/to/file.svg\");\n\n commands.spawn_bundle(OrthographicCameraBundle::new_2d());\n\n commands.spawn_bundle(SvgBundle {\n\n svg,\n\n origin: Origin::Center,\n\n ..Default::default()\n\n });\n\n}\n\n```\n\n\n", "file_path": "README.md", "rank": 38, "score": 29614.2163041176 }, { "content": "### 3D\n\n```rust\n\nfn main() {\n\n App::new()\n\n .insert_resource(Msaa { samples: 4 })\n\n .insert_resource(WindowDescriptor {\n\n title: \"SVG Plugin\".to_string(),\n\n ..Default::default()\n\n })\n\n .add_plugins(DefaultPlugins)\n\n .add_plugin(bevy_svg::prelude::SvgPlugin)\n\n .add_startup_system(setup.system());\n\n .run();\n\n}\n\n\n\nfn setup(\n\n mut commands: Commands,\n\n asset_server: Res<AssetServer>,\n\n) {\n\n let svg = asset_server.load(\"path/to/file.svg\");\n\n commands.spawn_bundle(PerspectiveCameraBundle::new_3d());\n\n commands.spawn_bundle(SvgBundle {\n\n svg,\n\n origin: Origin::Center,\n\n transform: Transform {\n\n translation: Vec3::new(0.0, 0.0, 1.5),\n\n scale: Vec3::new(0.05, 0.05, 1.0), // The scale you need depends a lot on your SVG and camera distance\n\n rotation: Quat::from_rotation_x(-std::f32::consts::PI / 5.0),\n\n },\n\n ..Default::default()\n\n });\n\n}\n\n```\n\n\n\n\n\n[`Bevy`]: https://bevyengine.org\n\n[`bevy_prototype_lyon`]: https://github.com/Nilirad/bevy_prototype_lyon\n\n[`Lyon`]: https://github.com/nical/lyon\n\n[`usvg`]: https://github.com/RazrFalcon/resvg\n\n[`AssetLoader`]: https://docs.rs/bevy/0.6/bevy/asset/trait.AssetLoader.html\n", "file_path": "README.md", "rank": 39, "score": 29611.72525832797 }, { "content": "# Changelog\n\nAll notable changes to this project will be documented in this file.\n\n\n\nThe format is based on [Keep a Changelog](https://keepachangelog.com/en/1.0.0/),\n\nand this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0.html).\n\n\n\n## [Unreleased]\n\n\n\n\n\n## [0.6.0] - 2022-01-09\n\n### Added\n\n- Added features `2d` and `3d`, both are activae on default, but can be used separately if needed.\n\n\n\n### Changed\n\n- Rendering now uses the new renderer introduced in Bevy `0.6`\n\n- `SvgBundle` is replaced by `Svg2dBundle` and `Svg3dBundle`\n\n- Updated `usvg` to version `0.20`\n\n\n\n## [0.5.0]\n\nSkipped this version number to be in sync with bevy.\n\n\n\n## [0.4.0] - 2021-12-20\n\n### Added\n\n- Implement AssetLoader for SVG\n\n- Support for displaying SVGs with 3D cameras\n\n- New 3D examples\n\n- This file! 🚀\n\n\n\n### Changed\n\n- Refactored and changed some internal, like how an when the different `y`-axis origin gets changed.\n\n\n\n### Fixed\n\n- Fix problem with drawing a SVG multiple times\n\n- Fix washed out colors\n\n\n\n### Removed\n\n- Ability to load a `SVG` file directly from the file system, you now need to use `asset_server.load(\"path/to/file.svg\")`\n", "file_path": "CHANGELOG.md", "rank": 40, "score": 29610.483238520064 }, { "content": "# bevy_svg\n\n[![Crates.io](https://img.shields.io/crates/v/bevy_svg.svg)](https://crates.io/crates/bevy_svg)\n\n[![license](https://img.shields.io/badge/license-Apache-blue.svg)](./LICENSE)\n\n\n\nFor one of my personal projects i needed a way to load and display some simple SVG files/shapes in [`Bevy`],\n\nso i took inspiration from [`bevy_prototype_lyon`] and modified and extended it to...well...load and display\n\nsimple SVG files. SVGs can be used/displayed in `2D` as well as in `3D`.\n\n\n\nFiles are loaded through [`AssetLoader`], then parsed and simplified with [`usvg`] and then tessellated with [`Lyon`]\n\ninto a vertex buffer, which lastly is convert into a [`Bevy`] mesh and drawn with custom [shaders].\n\n\n\n[shaders]: src/plugin.rs#L91-L119\n\n\n\n\n\n## Compatibility\n\n| `Bevy` version | `bevy_svg` version | Branch |\n\n|----------------|--------------------|-------------|\n\n| [![Crates.io](https://img.shields.io/badge/crates.io-v0.6.0-orange)](https://crates.io/crates/bevy/0.6.0) | [![Crates.io](https://img.shields.io/badge/crates.io-v0.6.0-orange)](https://crates.io/crates/bevy-svg/0.6.0) | [`bevy-0.6`](https://github.com/Weasy666/bevy_svg/tree/bevy-0.6) |\n\n| [![Crates.io](https://img.shields.io/badge/crates.io-v0.5.0-orange)](https://crates.io/crates/bevy/0.5.0) | [![Crates.io](https://img.shields.io/badge/crates.io-v0.4.0-orange)](https://crates.io/crates/bevy-svg/0.4.0) | [`bevy-0.5`](https://github.com/Weasy666/bevy_svg/tree/bevy-0.5) |\n\n| [![Crates.io](https://img.shields.io/badge/branch-main-yellow)](https://github.com/bevyengine/bevy) | [![Crates.io](https://img.shields.io/badge/branch-main-yellow)](https://github.com/Weasy666/bevy_svg/) | [`main`](https://github.com/Weasy666/bevy_svg) |\n\n\n\n\n\n## Examples\n\n\n\n| Complex shapes | Multiple colors | Fonts |\n\n|----------------------|-----------------|------------|\n\n| ![complex_one_color] | ![two_colors] | ![twinkle] |\n\n\n\n[complex_one_color]: assets/complex_one_color.png\n\n[two_colors]: assets/two_colors.png\n\n[twinkle]: assets/twinkle.png\n\n\n\n## Usage\n\n\n\nCopy this to your `Cargo.toml`\n\n\n\n```toml\n", "file_path": "README.md", "rank": 41, "score": 29609.19112952642 }, { "content": "fn setup(\n\n mut commands: Commands,\n\n asset_server: Res<AssetServer>,\n\n) {\n\n let svg = asset_server.load(\"neutron_star.svg\");\n\n commands.spawn_bundle(PerspectiveCameraBundle::new_3d());\n\n commands.spawn_bundle(Svg3dBundle {\n\n svg,\n\n origin: Origin::Center,\n\n visibility: Visibility { is_visible: false },\n\n transform: Transform {\n\n translation: Vec3::new(0.0, 0.0, -1.0),\n\n scale: Vec3::new(0.005, 0.005, 1.0),\n\n ..Default::default()\n\n },\n\n ..Default::default()\n\n });\n\n}\n\n\n", "file_path": "examples/3d/two_colors_visibility.rs", "rank": 42, "score": 29372.313257355232 }, { "content": "fn setup(\n\n mut commands: Commands,\n\n asset_server: Res<AssetServer>,\n\n) {\n\n let svg = asset_server.load(\"neutron_star.svg\");\n\n commands.spawn_bundle(OrthographicCameraBundle::new_2d());\n\n commands.spawn_bundle(Svg2dBundle {\n\n svg,\n\n origin: Origin::Center,\n\n visibility: Visibility { is_visible: false },\n\n ..Default::default()\n\n });\n\n}\n\n\n", "file_path": "examples/2d/two_colors_visibility.rs", "rank": 43, "score": 29372.313257355232 }, { "content": "fn setup(\n\n mut commands: Commands,\n\n asset_server: Res<AssetServer>,\n\n) {\n\n let svg = asset_server.load(\"asteroid_field.svg\");\n\n commands.spawn_bundle(PerspectiveCameraBundle::new_3d());\n\n commands.spawn_bundle(Svg3dBundle {\n\n svg,\n\n origin: Origin::Center,\n\n transform: Transform {\n\n translation: Vec3::new(0.0, 0.0, -1.0),\n\n scale: Vec3::new(0.005, 0.005, 1.0),\n\n ..Default::default()\n\n },\n\n ..Default::default()\n\n });\n\n}\n", "file_path": "examples/3d/complex_one_color.rs", "rank": 44, "score": 29372.313257355232 }, { "content": "fn main() {\n\n App::new()\n\n .insert_resource(Msaa { samples: 4 })\n\n .insert_resource(WindowDescriptor {\n\n title: \"complex_one_color\".to_string(),\n\n width: 400.0,\n\n height: 400.0,\n\n ..Default::default()\n\n })\n\n .add_plugins(DefaultPlugins)\n\n .add_plugin(bevy_svg::prelude::SvgPlugin)\n\n .add_startup_system(setup)\n\n .run();\n\n}\n\n\n", "file_path": "examples/2d/complex_one_color.rs", "rank": 45, "score": 29372.313257355232 }, { "content": "fn main() {\n\n App::new()\n\n .insert_resource(Msaa { samples: 4 })\n\n .insert_resource(WindowDescriptor {\n\n title: \"two_colors_visibility\".to_string(),\n\n width: 400.0,\n\n height: 400.0,\n\n ..Default::default()\n\n })\n\n .add_plugins(DefaultPlugins)\n\n .add_plugin(bevy_svg::prelude::SvgPlugin)\n\n .add_startup_system(setup)\n\n .add_system(keyboard_input_system)\n\n .run();\n\n}\n\n\n", "file_path": "examples/3d/two_colors_visibility.rs", "rank": 46, "score": 29372.313257355232 }, { "content": "fn main() {\n\n App::new()\n\n .insert_resource(Msaa { samples: 4 })\n\n .insert_resource(WindowDescriptor {\n\n title: \"complex_one_color\".to_string(),\n\n width: 400.0,\n\n height: 400.0,\n\n ..Default::default()\n\n })\n\n .add_plugins(DefaultPlugins)\n\n .add_plugin(bevy_svg::prelude::SvgPlugin)\n\n .add_startup_system(setup)\n\n .run();\n\n}\n\n\n", "file_path": "examples/3d/complex_one_color.rs", "rank": 47, "score": 29372.313257355232 }, { "content": "fn main() {\n\n App::new()\n\n .insert_resource(Msaa { samples: 4 })\n\n .insert_resource(WindowDescriptor {\n\n title: \"two_colors_visibility\".to_string(),\n\n width: 400.0,\n\n height: 400.0,\n\n ..Default::default()\n\n })\n\n .add_plugins(DefaultPlugins)\n\n .add_plugin(bevy_svg::prelude::SvgPlugin)\n\n .add_startup_system(setup)\n\n .add_system(keyboard_input_system)\n\n .run();\n\n}\n\n\n", "file_path": "examples/2d/two_colors_visibility.rs", "rank": 48, "score": 29372.313257355232 }, { "content": "fn setup(\n\n mut commands: Commands,\n\n asset_server: Res<AssetServer>,\n\n) {\n\n let svg = asset_server.load(\"asteroid_field.svg\");\n\n commands.spawn_bundle(OrthographicCameraBundle::new_2d());\n\n let mut transform = Transform::from_xyz(0.0, 0.0, 0.0);\n\n transform.scale = Vec3::new(2.0, 2.0, 1.0);\n\n commands.spawn_bundle(Svg2dBundle {\n\n svg,\n\n origin: Origin::Center,\n\n transform,\n\n ..Default::default()\n\n });\n\n}\n", "file_path": "examples/2d/complex_one_color.rs", "rank": 49, "score": 29372.313257355232 }, { "content": "/// This system toggles SVG visibility when 'V' is pressed\n\nfn keyboard_input_system(\n\n keyboard_input: Res<Input<KeyCode>>,\n\n mut query: Query<\n\n (&Handle<Svg>, &mut Visibility),\n\n >,\n\n) {\n\n if keyboard_input.just_pressed(KeyCode::V) {\n\n for (_, mut visible) in query.iter_mut() {\n\n visible.is_visible = !visible.is_visible;\n\n }\n\n }\n\n}\n", "file_path": "examples/2d/two_colors_visibility.rs", "rank": 50, "score": 27420.6669611037 }, { "content": "/// This system toggles SVG visibility when 'V' is pressed\n\nfn keyboard_input_system(\n\n keyboard_input: Res<Input<KeyCode>>,\n\n mut query: Query<\n\n (&Handle<Svg>, &mut Visibility),\n\n >,\n\n) {\n\n if keyboard_input.just_pressed(KeyCode::V) {\n\n for (_, mut visible) in query.iter_mut() {\n\n visible.is_visible = !visible.is_visible;\n\n }\n\n }\n\n}\n", "file_path": "examples/3d/two_colors_visibility.rs", "rank": 51, "score": 27420.6669611037 }, { "content": "use bevy::{ecs::component::Component, math::Mat4, reflect::TypeUuid, render::color::Color, transform::components::Transform};\n\nuse lyon_geom::euclid::default::Transform2D;\n\nuse lyon_svg::{parser::ViewBox, path::PathEvent};\n\nuse lyon_tessellation::math::Point;\n\n\n\nuse crate::Convert;\n\n\n\n\n\n/// A loaded and deserialized SVG file.\n\n#[derive(Debug, TypeUuid)]\n\n#[uuid = \"d2c5985d-e221-4257-9e3b-ff0fb87e28ba\"]\n\npub struct Svg {\n\n /// The name of the file.\n\n pub name: String,\n\n /// Width of the SVG.\n\n pub width: f64,\n\n /// Height of the SVG.\n\n pub height: f64,\n\n /// ViewBox of the SVG.\n\n pub view_box: ViewBox,\n", "file_path": "src/svg.rs", "rank": 52, "score": 25447.60399611076 }, { "content": " /// All paths that make up the SVG.\n\n pub paths: Vec<PathDescriptor>,\n\n}\n\n\n\nimpl Svg {\n\n pub(crate) fn from_tree(tree: usvg::Tree) -> Svg {\n\n let view_box = tree.svg_node().view_box;\n\n let size = tree.svg_node().size;\n\n let mut descriptors = Vec::new();\n\n\n\n for node in tree.root().descendants() {\n\n if let usvg::NodeKind::Path(ref path) = *node.borrow() {\n\n let t = path.transform;\n\n let abs_t = Transform::from_matrix(\n\n Mat4::from_cols(\n\n [t.a.abs() as f32, t.b as f32, 0.0, 0.0].into(),\n\n [t.c as f32, t.d.abs() as f32, 0.0, 0.0].into(),\n\n [0.0, 0.0, 1.0, 0.0].into(),\n\n [t.e as f32, t.f as f32, 0.0, 1.0].into()\n\n )\n", "file_path": "src/svg.rs", "rank": 53, "score": 25444.691022080115 }, { "content": "#[derive(Debug)]\n\npub struct PathDescriptor {\n\n pub segments: Vec<PathEvent>,\n\n pub abs_transform: Transform,\n\n pub color: Color,\n\n pub draw_type: DrawType,\n\n}\n\n\n\n#[derive(Debug)]\n\npub enum DrawType {\n\n Fill,\n\n Stroke(lyon_tessellation::StrokeOptions),\n\n}\n\n\n\n// Taken from https://github.com/nical/lyon/blob/74e6b137fea70d71d3b537babae22c6652f8843e/examples/wgpu_svg/src/main.rs\n", "file_path": "src/svg.rs", "rank": 54, "score": 25442.018092499915 }, { "content": " paths: descriptors,\n\n }\n\n }\n\n}\n\n\n\n#[derive(Clone, Component, Copy, Debug, PartialEq)]\n\n/// Origin of the coordinate system.\n\npub enum Origin {\n\n /// Top left of the image or viewbox, this is the default for a SVG.\n\n TopLeft,\n\n /// Center of the image or viewbox.\n\n Center,\n\n}\n\n\n\nimpl Default for Origin {\n\n fn default() -> Self {\n\n Origin::TopLeft\n\n }\n\n}\n\n\n", "file_path": "src/svg.rs", "rank": 55, "score": 25440.229454375007 }, { "content": " descriptors.push(PathDescriptor {\n\n segments: path.convert().collect(),\n\n abs_transform: abs_t,\n\n color,\n\n draw_type,\n\n });\n\n }\n\n }\n\n }\n\n\n\n Svg {\n\n name: Default::default(),\n\n width: size.width(),\n\n height: size.height(),\n\n view_box: ViewBox {\n\n x: view_box.rect.x(),\n\n y: view_box.rect.y(),\n\n w: view_box.rect.width(),\n\n h: view_box.rect.height(),\n\n },\n", "file_path": "src/svg.rs", "rank": 56, "score": 25439.593590830413 }, { "content": " iter: self.data.iter(),\n\n first: Point::new(0.0, 0.0),\n\n prev: Point::new(0.0, 0.0),\n\n deferred: None,\n\n needs_end: false,\n\n // For some reason the local transform of some paths has negative scale values.\n\n // Here we correct to positive values.\n\n scale: lyon_geom::Transform::scale(\n\n if self.transform.a < 0.0 { -1.0 } else { 1.0 },\n\n if self.transform.d < 0.0 { -1.0 } else { 1.0 }\n\n )\n\n }\n\n }\n\n}\n\n\n\nimpl Convert<(Color, DrawType)> for &usvg::Stroke {\n\n fn convert(self) -> (Color, DrawType) {\n\n let color = match self.paint {\n\n usvg::Paint::Color(c) =>\n\n Color::rgba_u8(c.red, c.green, c.blue, self.opacity.to_u8()),\n", "file_path": "src/svg.rs", "rank": 57, "score": 25438.40035642781 }, { "content": " );\n\n\n\n if let Some(ref fill) = path.fill {\n\n let color = match fill.paint {\n\n usvg::Paint::Color(c) =>\n\n Color::rgba_u8(c.red, c.green, c.blue, fill.opacity.to_u8()),\n\n _ => Color::default(),\n\n };\n\n\n\n descriptors.push(PathDescriptor {\n\n segments: path.convert().collect(),\n\n abs_transform: abs_t,\n\n color,\n\n draw_type: DrawType::Fill,\n\n });\n\n }\n\n\n\n if let Some(ref stroke) = path.stroke {\n\n let (color, draw_type) = stroke.convert();\n\n\n", "file_path": "src/svg.rs", "rank": 58, "score": 25435.92601585324 }, { "content": " first,\n\n close: false,\n\n });\n\n }\n\n }\n\n }\n\n\n\n return return_event.map(|event| event.transformed(&self.scale));\n\n }\n\n}\n\n\n\nimpl Convert<Point> for (&f64, &f64) {\n\n fn convert(self) -> Point {\n\n Point::new((*self.0) as f32, (*self.1) as f32)\n\n }\n\n}\n\n\n\nimpl<'a> Convert<PathConvIter<'a>> for &'a usvg::Path {\n\n fn convert(self) -> PathConvIter<'a> {\n\n PathConvIter {\n", "file_path": "src/svg.rs", "rank": 59, "score": 25435.7566322679 }, { "content": " ctrl2: (x2, y2).convert(),\n\n to: self.prev,\n\n });\n\n }\n\n Some(usvg::PathSegment::ClosePath) => {\n\n self.needs_end = false;\n\n self.prev = self.first;\n\n return_event = Some(PathEvent::End {\n\n last: self.prev,\n\n first: self.first,\n\n close: true,\n\n });\n\n }\n\n None => {\n\n if self.needs_end {\n\n self.needs_end = false;\n\n let last = self.prev;\n\n let first = self.first;\n\n return_event = Some(PathEvent::End {\n\n last,\n", "file_path": "src/svg.rs", "rank": 60, "score": 25434.97626895509 }, { "content": " _ => Color::default(),\n\n };\n\n\n\n let linecap = match self.linecap {\n\n usvg::LineCap::Butt => lyon_tessellation::LineCap::Butt,\n\n usvg::LineCap::Square => lyon_tessellation::LineCap::Square,\n\n usvg::LineCap::Round => lyon_tessellation::LineCap::Round,\n\n };\n\n let linejoin = match self.linejoin {\n\n usvg::LineJoin::Miter => lyon_tessellation::LineJoin::Miter,\n\n usvg::LineJoin::Bevel => lyon_tessellation::LineJoin::Bevel,\n\n usvg::LineJoin::Round => lyon_tessellation::LineJoin::Round,\n\n };\n\n\n\n let opt = lyon_tessellation::StrokeOptions::tolerance(0.01)\n\n .with_line_width(self.width.value() as f32)\n\n .with_line_cap(linecap)\n\n .with_line_join(linejoin);\n\n\n\n (color, DrawType::Stroke(opt))\n\n }\n\n}\n", "file_path": "src/svg.rs", "rank": 61, "score": 25434.348766410098 }, { "content": " if self.needs_end {\n\n let last = self.prev;\n\n let first = self.first;\n\n self.needs_end = false;\n\n self.prev = (x, y).convert();\n\n self.deferred = Some(PathEvent::Begin { at: self.prev });\n\n self.first = self.prev;\n\n return_event = Some(PathEvent::End {\n\n last,\n\n first,\n\n close: false,\n\n });\n\n } else {\n\n self.first = (x, y).convert();\n\n return_event = Some(PathEvent::Begin { at: self.first });\n\n }\n\n }\n\n Some(usvg::PathSegment::LineTo { x, y }) => {\n\n self.needs_end = true;\n\n let from = self.prev;\n", "file_path": "src/svg.rs", "rank": 62, "score": 25433.163519329384 }, { "content": " self.prev = (x, y).convert();\n\n return_event = Some(PathEvent::Line {\n\n from,\n\n to: self.prev,\n\n });\n\n }\n\n Some(usvg::PathSegment::CurveTo {\n\n x1,\n\n y1,\n\n x2,\n\n y2,\n\n x,\n\n y,\n\n }) => {\n\n self.needs_end = true;\n\n let from = self.prev;\n\n self.prev = (x, y).convert();\n\n return_event = Some(PathEvent::Cubic {\n\n from,\n\n ctrl1: (x1, y1).convert(),\n", "file_path": "src/svg.rs", "rank": 63, "score": 25433.163519329384 }, { "content": "pub(crate) mod tessellation;\n\nmod vertex_buffer;\n\n\n\n\n\n/// Plugin that renders [`Svg`](crate::svg::Svg)s in 2D\n\npub struct SvgPlugin;\n\n\n\n/// Handle to the custom shader with a unique random ID\n\n#[cfg(feature = \"2d\")]\n\npub const SVG_2D_SHADER_HANDLE: HandleUntyped = HandleUntyped::weak_from_u64(Shader::TYPE_UUID, 8514826620251853414);\n\n#[cfg(feature = \"3d\")]\n\npub const SVG_3D_SHADER_HANDLE: HandleUntyped = HandleUntyped::weak_from_u64(Shader::TYPE_UUID, 8514826640451853414);\n\n\n\nimpl Plugin for SvgPlugin {\n\n fn build(&self, app: &mut App) {\n\n let fill_tess = FillTessellator::new();\n\n let stroke_tess = StrokeTessellator::new();\n\n // Load SVG shader\n\n let mut shaders = app.world.get_resource_mut::<Assets<Shader>>().unwrap();\n\n #[cfg(feature = \"2d\")]\n", "file_path": "src/render/mod.rs", "rank": 64, "score": 23074.222395631547 }, { "content": "use bevy::{\n\n log::{error, debug},\n\n math::Vec3,\n\n transform::components::Transform,\n\n};\n\nuse lyon_tessellation::{FillTessellator, StrokeTessellator, FillOptions, BuffersBuilder};\n\n\n\nuse crate::{\n\n render::vertex_buffer::{VertexBuffers, VertexConstructor, BufferExt},\n\n svg::{DrawType, Svg},\n\n};\n\n\n\n\n\npub(crate) fn generate_buffer(\n\n svg: &Svg,\n\n fill_tess: &mut FillTessellator,\n\n stroke_tess: &mut StrokeTessellator,\n\n) -> VertexBuffers {\n\n debug!(\"Tessellating SVG: {}\", svg.name);\n\n\n", "file_path": "src/render/tessellation.rs", "rank": 65, "score": 23073.916964229247 }, { "content": " shaders.set_untracked(\n\n SVG_2D_SHADER_HANDLE,\n\n Shader::from_wgsl(include_str!(\"svg_2d.wgsl\")),\n\n );\n\n #[cfg(feature = \"3d\")]\n\n shaders.set_untracked(\n\n SVG_3D_SHADER_HANDLE,\n\n Shader::from_wgsl(include_str!(\"svg_3d.wgsl\")),\n\n );\n\n app\n\n .insert_resource(fill_tess)\n\n .insert_resource(stroke_tess);\n\n // Register our custom draw function and pipeline, and add our render systems\n\n let render_app = app.get_sub_app_mut(RenderApp).unwrap();\n\n #[cfg(feature = \"2d\")]\n\n render_app\n\n .add_render_command::<Transparent2d, pipeline_2d::DrawSvg2d>()\n\n .init_resource::<pipeline_2d::Svg2dPipeline>()\n\n .init_resource::<SpecializedPipelines<pipeline_2d::Svg2dPipeline>>()\n\n .init_resource::<pipeline_2d::ExtractedSvgs2d>()\n", "file_path": "src/render/mod.rs", "rank": 66, "score": 23072.761092669432 }, { "content": " let flip_y = Transform::from_scale(Vec3::new(1.0, -1.0, 1.0));\n\n let mut buffers = VertexBuffers::new();\n\n\n\n let mut color = None;\n\n for path in &svg.paths {\n\n let mut buffer = VertexBuffers::new();\n\n\n\n if color.is_none() {\n\n color = Some(path.color);\n\n }\n\n\n\n // Bevy has a different y-axis origin, so we need to flip that axis\n\n let transform = flip_y * path.abs_transform;\n\n match path.draw_type {\n\n DrawType::Fill => {\n\n if let Err(e) = fill_tess.tessellate(\n\n path.segments.clone(),\n\n &FillOptions::tolerance(0.001),\n\n &mut BuffersBuilder::new(&mut buffer, VertexConstructor { color: path.color, transform })\n\n ) {\n", "file_path": "src/render/tessellation.rs", "rank": 67, "score": 23070.296034826046 }, { "content": "use bevy::{\n\n app::{App, Plugin},\n\n asset::{Assets, HandleUntyped},\n\n reflect::TypeUuid,\n\n render::{\n\n render_phase::AddRenderCommand,\n\n render_resource::{Shader, SpecializedPipelines},\n\n RenderApp, RenderStage,\n\n },\n\n};\n\n#[cfg(feature = \"2d\")]\n\nuse bevy::core_pipeline::Transparent2d;\n\n#[cfg(feature = \"3d\")]\n\nuse bevy::core_pipeline::Transparent3d;\n\nuse lyon_tessellation::{FillTessellator, StrokeTessellator};\n\n\n\n#[cfg(feature = \"2d\")]\n\nmod pipeline_2d;\n\n#[cfg(feature = \"3d\")]\n\nmod pipeline_3d;\n", "file_path": "src/render/mod.rs", "rank": 68, "score": 23069.71058958741 }, { "content": " .add_system_to_stage(RenderStage::Extract, pipeline_2d::extract_svg_2d)\n\n .add_system_to_stage(RenderStage::Queue, pipeline_2d::queue_svg_2d);\n\n #[cfg(feature = \"3d\")]\n\n render_app\n\n .add_render_command::<Transparent3d, pipeline_3d::DrawSvg3d>()\n\n .init_resource::<pipeline_3d::Svg3dPipeline>()\n\n .init_resource::<SpecializedPipelines<pipeline_3d::Svg3dPipeline>>()\n\n .init_resource::<pipeline_3d::ExtractedSvgs3d>()\n\n .add_system_to_stage(RenderStage::Extract, pipeline_3d::extract_svg_3d)\n\n .add_system_to_stage(RenderStage::Queue, pipeline_3d::queue_svg_3d);\n\n }\n\n}\n", "file_path": "src/render/mod.rs", "rank": 69, "score": 23066.951364160162 }, { "content": " error!(\"FillTessellator error: {:?}\", e)\n\n }\n\n },\n\n DrawType::Stroke(opts) => {\n\n if let Err(e) = stroke_tess.tessellate(\n\n path.segments.clone(),\n\n &opts,\n\n &mut BuffersBuilder::new(&mut buffer, VertexConstructor { color: path.color, transform })\n\n ) {\n\n error!(\"StrokeTessellator error: {:?}\", e)\n\n }\n\n }\n\n }\n\n buffers.extend_one(buffer);\n\n }\n\n debug!(\"Tessellating SVG: {} ... Done\", svg.name);\n\n\n\n buffers\n\n}\n", "file_path": "src/render/tessellation.rs", "rank": 70, "score": 23066.313173122104 }, { "content": "//! Bevy [`Bundle`] representing an SVG entity.\n\n\n\nuse bevy::{\n\n asset::Handle,\n\n ecs::bundle::Bundle,\n\n render::{\n\n mesh::Mesh,\n\n view::{ComputedVisibility, Visibility}\n\n },\n\n sprite::Mesh2dHandle,\n\n transform::components::{GlobalTransform, Transform},\n\n};\n\n\n\nuse crate::svg::{Origin, Svg};\n\n\n\n\n\n/// A Bevy [`Bundle`] representing an SVG entity.\n\n#[allow(missing_docs)]\n\n#[derive(Bundle)]\n\npub struct Svg2dBundle {\n", "file_path": "src/bundle.rs", "rank": 71, "score": 17.749962940957356 }, { "content": "//! Contains the plugin and its helper types.\n\n//!\n\n//! The [`Svg2dBundle`](crate::bundle::Svg2dBundle) provides a way to display an `SVG`-file\n\n//! with minimal boilerplate.\n\n//!\n\n//! ## How it works\n\n//! The user creates/loades a [`Svg2dBundle`](crate::bundle::Svg2dBundle) in a system.\n\n//!\n\n//! Then, in the [`Stage::SVG`](Stage::SVG), a mesh is created for each loaded [`Svg`] bundle.\n\n//! Each mesh is then extracted in the [`RenderStage::Extract`](bevy::render::RenderStage) and added to the\n\n//! [`RenderWorld`](bevy::render::RenderWorld).\n\n//! Afterwards it is queued in the [`RenderStage::Queue`](bevy::render::RenderStage) for actual drawing/rendering.\n\n\n\nuse bevy::{\n\n app::{App, Plugin},\n\n asset::{AddAsset, AssetEvent, Assets, Handle},\n\n ecs::{\n\n entity::Entity,\n\n event::EventReader,\n\n schedule::{StageLabel, SystemStage},\n", "file_path": "src/plugin.rs", "rank": 72, "score": 15.791682160132703 }, { "content": " system::{Query, Res, ResMut}\n\n },\n\n log::debug,\n\n math::Vec3,\n\n render::mesh::Mesh,\n\n sprite::Mesh2dHandle,\n\n transform::components::Transform,\n\n};\n\nuse lyon_tessellation::{FillTessellator, StrokeTessellator};\n\n\n\nuse crate::{Convert, loader::SvgAssetLoader, render::tessellation, svg::{Origin, Svg}};\n\n\n\n\n\n/// Stages for this plugin.\n\n#[derive(Debug, Hash, PartialEq, Eq, Clone, StageLabel)]\n\npub enum Stage {\n\n /// Stage in which [`Svg2dBundle`](crate::bundle::Svg2dBundle)s get drawn.\n\n SVG,\n\n}\n\n\n", "file_path": "src/plugin.rs", "rank": 73, "score": 14.010594446564813 }, { "content": "/// A plugin that provides resources and a system to draw [`Svg`]s.\n\npub struct SvgPlugin;\n\n\n\nimpl Plugin for SvgPlugin {\n\n fn build(&self, app: &mut App) {\n\n let fill_tess = FillTessellator::new();\n\n let stroke_tess = StrokeTessellator::new();\n\n app\n\n .add_asset::<Svg>()\n\n .init_asset_loader::<SvgAssetLoader>()\n\n .insert_resource(fill_tess)\n\n .insert_resource(stroke_tess)\n\n .add_stage_after(\n\n bevy::app::CoreStage::Update,\n\n Stage::SVG,\n\n SystemStage::parallel(),\n\n )\n\n .add_system_to_stage(Stage::SVG, svg_mesh_maker)\n\n .add_plugin(crate::render::SvgPlugin);\n\n }\n\n}\n\n\n\n/// Bevy system which queries for all [`Svg`](crate::svg::Svg)s and tessellates them into a mesh.\n", "file_path": "src/plugin.rs", "rank": 74, "score": 12.182438990195845 }, { "content": " pub svg: Handle<Svg>,\n\n pub mesh_2d: Mesh2dHandle,\n\n /// [`Origin`] of the coordinate system and as such the origin for the Bevy position.\n\n pub origin: Origin,\n\n pub transform: Transform,\n\n pub global_transform: GlobalTransform,\n\n pub visibility: Visibility,\n\n pub computed_visibility: ComputedVisibility,\n\n}\n\n\n\nimpl Default for Svg2dBundle {\n\n /// Creates a default [`Svg2dBundle`].\n\n fn default() -> Self {\n\n Self {\n\n svg: Default::default(),\n\n mesh_2d: Default::default(),\n\n origin: Default::default(),\n\n transform: Transform::default(),\n\n global_transform: GlobalTransform::default(),\n\n visibility: Visibility::default(),\n", "file_path": "src/bundle.rs", "rank": 75, "score": 11.907474163962176 }, { "content": "pub struct FileSvgError {\n\n error: SvgError,\n\n path: String,\n\n}\n\nimpl std::fmt::Display for FileSvgError {\n\n fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::result::Result<(), std::fmt::Error> {\n\n write!(\n\n f,\n\n \"Error reading SVG file {}: {}, this is an error in `bevy_svg`.\",\n\n self.path, self.error\n\n )\n\n }\n\n}\n", "file_path": "src/loader.rs", "rank": 76, "score": 11.382410724223455 }, { "content": "#![warn(\n\n clippy::all,\n\n clippy::restriction,\n\n clippy::pedantic,\n\n clippy::nursery,\n\n clippy::cargo\n\n)]\n\n\n\nmod bundle;\n\nmod loader;\n\nmod plugin;\n\nmod render;\n\nmod svg;\n\n\n\n/// Import this module as `use bevy_svg::prelude::*` to get convenient imports.\n\npub mod prelude {\n\n pub use crate::{plugin::SvgPlugin, svg::{Svg, Origin}};\n\n #[cfg(feature = \"2d\")]\n\n pub use crate::bundle::Svg2dBundle;\n\n #[cfg(feature = \"3d\")]\n\n pub use crate::bundle::Svg3dBundle;\n\n pub use lyon_tessellation::{\n\n FillOptions, FillRule, LineCap, LineJoin, Orientation, StrokeOptions,\n\n };\n\n}\n\n\n\n/// A locally defined [`std::convert::Into`] surrogate to overcome orphan rules.\n", "file_path": "src/lib.rs", "rank": 77, "score": 10.956599209457593 }, { "content": "use bevy::{\n\n input::{keyboard::KeyCode, Input},\n\n prelude::*\n\n};\n\nuse bevy_svg::prelude::*;\n\n\n", "file_path": "examples/3d/two_colors_visibility.rs", "rank": 78, "score": 10.46068161198798 }, { "content": "use bevy::{\n\n input::{keyboard::KeyCode, Input},\n\n prelude::*\n\n};\n\nuse bevy_svg::prelude::*;\n\n\n", "file_path": "examples/2d/two_colors_visibility.rs", "rank": 79, "score": 10.46068161198798 }, { "content": "use anyhow;\n\nuse bevy::{asset::{AssetLoader, BoxedFuture, LoadContext, LoadedAsset}, log::debug};\n\nuse thiserror::Error;\n\n\n\nuse crate::svg::Svg;\n\n\n\n\n\n#[derive(Default)]\n\npub struct SvgAssetLoader;\n\n\n\nimpl AssetLoader for SvgAssetLoader {\n\n fn load<'a>(\n\n &'a self,\n\n bytes: &'a [u8],\n\n load_context: &'a mut LoadContext,\n\n ) -> BoxedFuture<'a, Result<(), anyhow::Error>> {\n\n Box::pin(async move {\n\n let mut opts = usvg::Options::default();\n\n opts.fontdb.load_system_fonts();\n\n opts.fontdb.load_fonts_dir(\"./assets\");\n", "file_path": "src/loader.rs", "rank": 80, "score": 10.446738687020758 }, { "content": " computed_visibility: ComputedVisibility::default(),\n\n }\n\n }\n\n}\n\n\n\n\n\n/// A Bevy [`Bundle`] representing an SVG entity.\n\n#[allow(missing_docs)]\n\n#[derive(Bundle)]\n\npub struct Svg3dBundle {\n\n pub svg: Handle<Svg>,\n\n pub mesh: Handle<Mesh>,\n\n /// [`Origin`] of the coordinate system and as such the origin for the Bevy position.\n\n pub origin: Origin,\n\n pub transform: Transform,\n\n pub global_transform: GlobalTransform,\n\n pub visibility: Visibility,\n\n pub computed_visibility: ComputedVisibility,\n\n}\n\n\n", "file_path": "src/bundle.rs", "rank": 81, "score": 9.040644726480915 }, { "content": "use bevy::prelude::*;\n\nuse bevy_svg::prelude::*;\n\n\n", "file_path": "examples/2d/two_colors.rs", "rank": 82, "score": 8.342126590946737 }, { "content": "use bevy::prelude::*;\n\nuse bevy_svg::prelude::*;\n\n\n", "file_path": "examples/2d/complex_one_color.rs", "rank": 83, "score": 8.342126590946735 }, { "content": "use bevy::prelude::*;\n\nuse bevy_svg::prelude::*;\n\n\n", "file_path": "examples/3d/complex_one_color.rs", "rank": 84, "score": 8.342126590946737 }, { "content": "use bevy::prelude::*;\n\nuse bevy_svg::prelude::*;\n\n\n", "file_path": "examples/3d/two_colors.rs", "rank": 85, "score": 8.342126590946737 }, { "content": "use bevy::prelude::*;\n\nuse bevy_svg::prelude::*;\n\n\n", "file_path": "examples/2d/twinkle.rs", "rank": 86, "score": 8.342126590946735 }, { "content": "use bevy::prelude::*;\n\nuse bevy_svg::prelude::*;\n\n\n", "file_path": "examples/3d/twinkle.rs", "rank": 87, "score": 8.342126590946737 }, { "content": " }\n\n }\n\n },\n\n AssetEvent::Removed { handle } => {\n\n let _bundle = query.iter_mut().filter(|(_, svg, _, _, _, _)| svg == &handle).next();\n\n //TODO:\n\n },\n\n }\n\n }\n\n}\n", "file_path": "src/plugin.rs", "rank": 88, "score": 7.311572511170663 }, { "content": "impl Default for Svg3dBundle {\n\n /// Creates a default [`Svg3dBundle`].\n\n fn default() -> Self {\n\n Self {\n\n svg: Default::default(),\n\n mesh: Default::default(),\n\n origin: Default::default(),\n\n transform: Transform::default(),\n\n global_transform: GlobalTransform::default(),\n\n visibility: Visibility::default(),\n\n computed_visibility: ComputedVisibility::default(),\n\n }\n\n }\n\n}\n", "file_path": "src/bundle.rs", "rank": 89, "score": 5.8610214653469175 }, { "content": " } else {\n\n debug!(\"Mesh for SVG `{}` already available, copying handle\", svg.name);\n\n }\n\n\n\n let translation = match origin {\n\n Origin::Center => transform.translation + Vec3::new(\n\n -svg.width as f32 * transform.scale.x / 2.0,\n\n svg.height as f32 * transform.scale.y / 2.0,\n\n 0.0\n\n ),\n\n Origin::TopLeft => transform.translation,\n\n };\n\n transform.translation = translation;\n\n\n\n let new_mesh = tesselated_mesh.as_ref().unwrap().clone();\n\n if let Some(mut mesh_2d) = mesh_2d {\n\n mesh_2d.0 = new_mesh.clone();\n\n }\n\n if let Some(mut mesh_3d) = mesh_3d {\n\n *mesh_3d = new_mesh;\n", "file_path": "src/plugin.rs", "rank": 90, "score": 5.8155492825134765 }, { "content": "//! Load and disply simple SVG files in Bevy.\n\n//!\n\n//! This crate provides a Bevy `Plugin` to easily load and display a simple SVG file.\n\n//!\n\n//! ## Usage\n\n//! Simply add the crate in your `Cargo.toml` and add the plugin to your app\n\n//!\n\n//! ```rust\n\n//! fn main() {\n\n//! App::new()\n\n//! .add_plugin(bevy_svg::prelude::SvgPlugin)\n\n//! .run();\n\n//! }\n\n//! ```\n\n\n\n// rustc\n\n#![deny(future_incompatible, nonstandard_style)]\n\n#![warn(missing_docs, rust_2018_idioms, unused)]\n\n#![allow(elided_lifetimes_in_paths)]\n\n// clippy\n", "file_path": "src/lib.rs", "rank": 91, "score": 4.603461703454771 }, { "content": " Ok(())\n\n })\n\n }\n\n\n\n fn extensions(&self) -> &[&str] {\n\n &[\"svg\", \"svgz\"]\n\n }\n\n}\n\n\n\n/// An error that occurs when loading a texture\n\n#[derive(Error, Debug)]\n\npub enum SvgError {\n\n #[error(\"invalid file name\")]\n\n InvalidFileName(String),\n\n #[error(\"failed to load an SVG: {0}\")]\n\n SvgError(#[from] usvg::Error),\n\n}\n\n\n\n/// An error that occurs when loading a texture from a file.\n\n#[derive(Error, Debug)]\n", "file_path": "src/loader.rs", "rank": 92, "score": 4.059047262705352 }, { "content": "\n\n debug!(\"Parsing SVG: {}\", load_context.path().display());\n\n let svg_tree = usvg::Tree::from_data(&bytes, &opts.to_ref()).map_err(|err| {\n\n FileSvgError {\n\n error: err.into(),\n\n path: format!(\"{}\", load_context.path().display()),\n\n }\n\n })?;\n\n\n\n let mut svg = Svg::from_tree(svg_tree);\n\n let name = &load_context.path().file_name().ok_or_else(||\n\n FileSvgError {\n\n error: SvgError::InvalidFileName(load_context.path().display().to_string()),\n\n path: format!(\"{}\", load_context.path().display()),\n\n }\n\n )?.to_string_lossy();\n\n svg.name = name.to_string();\n\n\n\n load_context.set_default_asset(LoadedAsset::new(svg));\n\n debug!(\"Parsing SVG: {} ... Done\", load_context.path().display());\n", "file_path": "src/loader.rs", "rank": 93, "score": 3.6412897743132944 }, { "content": " svg: svg.clone(),\n\n origin: Origin::Center,\n\n transform: Transform {\n\n translation: Vec3::new(0.0, 0.0, 0.0),\n\n scale: Vec3::new(0.05, 0.05, 1.0),\n\n rotation: Quat::from_rotation_x(-std::f32::consts::PI / 5.0),\n\n },\n\n ..Default::default()\n\n });\n\n commands.spawn_bundle(Svg3dBundle {\n\n svg,\n\n origin: Origin::Center,\n\n transform: Transform {\n\n translation: Vec3::new(0.0, 0.0, -1.5),\n\n scale: Vec3::new(0.05, 0.05, 1.0),\n\n rotation: Quat::from_rotation_x(-std::f32::consts::PI / 5.0),\n\n },\n\n ..Default::default()\n\n });\n\n}\n", "file_path": "examples/3d/two_colors.rs", "rank": 94, "score": 2.057788655428429 } ]
Rust
src/cmd/env.rs
wang-q/garr
50c1ecc08e2e4f854fe4186882a738aaa3d3e41d
use clap::*; use garr::*; use std::collections::HashMap; use std::fs; use tera::{Context, Tera}; pub fn make_subcommand<'a, 'b>() -> App<'a, 'b> { SubCommand::with_name("env") .about("Create a .env file") .after_help( r#" Default values: * REDIS_HOST - localhost * REDIS_PORT - 6379 * REDIS_PASSWORD - * REDIS_TLS - false "#, ) .arg(Arg::with_name("all").long("all").help("Create all scripts")) .arg( Arg::with_name("outfile") .short("o") .long("outfile") .takes_value(true) .default_value("garr.env") .empty_values(false) .help("Output filename. [stdout] for screen"), ) } pub fn execute(args: &ArgMatches) -> std::result::Result<(), std::io::Error> { let mut context = Context::new(); match envy::from_env::<Config>() { Ok(config) => { context.insert("host", &config.redis_host); context.insert("port", &config.redis_port); context.insert("password", &config.redis_password); context.insert("tls", &config.redis_tls); } Err(error) => panic!("{:#?}", error), } let mut opt = HashMap::new(); opt.insert("outfile", args.value_of("outfile").unwrap()); context.insert("opt", &opt); eprintln!("Create {}", opt.get("outfile").unwrap()); let mut tera = Tera::default(); tera.add_raw_templates(vec![("t", include_str!("../../templates/garr.tera.env"))]) .unwrap(); let rendered = tera.render("t", &context).unwrap(); intspan::write_lines(opt.get("outfile").unwrap(), &vec![rendered.as_str()])?; if args.is_present("all") { gen_peak(&context)?; gen_plot_xy(&context)?; fs::create_dir_all("sqls/ddl")?; gen_ddl_ctg(&context)?; gen_ddl_rsw(&context)?; gen_dql_summary(&context)?; gen_dql_rsw(&context)?; } Ok(()) } fn gen_peak(context: &Context) -> std::result::Result<(), std::io::Error> { let outname = "peak.R"; eprintln!("Create {}", outname); let mut tera = Tera::default(); tera.add_raw_templates(vec![("t", include_str!("../../templates/peak.tera.R"))]) .unwrap(); let rendered = tera.render("t", &context).unwrap(); intspan::write_lines(outname, &vec![rendered.as_str()])?; Ok(()) } fn gen_plot_xy(context: &Context) -> std::result::Result<(), std::io::Error> { let outname = "plot_xy.R"; eprintln!("Create {}", outname); let mut tera = Tera::default(); tera.add_raw_templates(vec![("t", include_str!("../../templates/plot_xy.tera.R"))]) .unwrap(); let rendered = tera.render("t", &context).unwrap(); intspan::write_lines(outname, &vec![rendered.as_str()])?; Ok(()) } fn gen_ddl_ctg(context: &Context) -> std::result::Result<(), std::io::Error> { let outname = "sqls/ddl/ctg.sql"; eprintln!("Create {}", outname); let mut tera = Tera::default(); tera.add_raw_templates(vec![( "t", include_str!("../../templates/ddl/ctg.tera.sql"), )]) .unwrap(); let rendered = tera.render("t", &context).unwrap(); intspan::write_lines(outname, &vec![rendered.as_str()])?; Ok(()) } fn gen_ddl_rsw(context: &Context) -> std::result::Result<(), std::io::Error> { let outname = "sqls/ddl/rsw.sql"; eprintln!("Create {}", outname); let mut tera = Tera::default(); tera.add_raw_templates(vec![( "t", include_str!("../../templates/ddl/rsw.tera.sql"), )]) .unwrap(); let rendered = tera.render("t", &context).unwrap(); intspan::write_lines(outname, &vec![rendered.as_str()])?; Ok(()) } fn gen_dql_summary(context: &Context) -> std::result::Result<(), std::io::Error> { let outname = "sqls/summary.sql"; eprintln!("Create {}", outname); let mut tera = Tera::default(); tera.add_raw_templates(vec![( "t", include_str!("../../templates/dql/summary.tera.sql"), )]) .unwrap(); let rendered = tera.render("t", &context).unwrap(); intspan::write_lines(outname, &vec![rendered.as_str()])?; let outname = "sqls/summary-type.sql"; eprintln!("Create {}", outname); let mut tera = Tera::default(); tera.add_raw_templates(vec![( "t", include_str!("../../templates/dql/summary-type.tera.sql"), )]) .unwrap(); let rendered = tera.render("t", &context).unwrap(); intspan::write_lines(outname, &vec![rendered.as_str()])?; Ok(()) } fn gen_dql_rsw(context: &Context) -> std::result::Result<(), std::io::Error> { let outname = "sqls/rsw-distance.sql"; eprintln!("Create {}", outname); let mut tera = Tera::default(); tera.add_raw_templates(vec![( "t", include_str!("../../templates/dql/rsw-distance.tera.sql"), )]) .unwrap(); let rendered = tera.render("t", &context).unwrap(); intspan::write_lines(outname, &vec![rendered.as_str()])?; let outname = "sqls/rsw-distance-tag.sql"; eprintln!("Create {}", outname); let mut tera = Tera::default(); tera.add_raw_templates(vec![( "t", include_str!("../../templates/dql/rsw-distance-tag.tera.sql"), )]) .unwrap(); let rendered = tera.render("t", &context).unwrap(); intspan::write_lines(outname, &vec![rendered.as_str()])?; Ok(()) }
use clap::*; use garr::*; use std::collections::HashMap; use std::fs; use tera::{Context, Tera}; pub fn make_subcommand<'a, 'b>() -> App<'a, 'b> { SubCommand::with_name("env") .about("Create a .env file") .after_help( r#" Default values: * REDIS_HOST - localhost * REDIS_PORT - 6379 * REDIS_PASSWORD - * REDIS_TLS - false "#, ) .arg(Arg::with_name("all").long("all").help("Create all scripts")) .arg( Arg::with_name("outfile") .short("o") .long("outfile") .takes_value(true) .default_value("garr.env") .empty_values(false) .help("Output filename. [stdout] for screen"), ) } pub fn execute(args: &ArgMatches) -> std::result::Result<(), std::io::Error> { let mut context = Context::new(); match envy::from_env::<Config>() { Ok(config) => { context.insert("host", &config.redis_host); context.insert("port", &config.redis_port); context.insert("password", &config.redis_password); context.insert("tls", &config.redis_tls); } Err(error) => panic!("{:#?}", error), } let mut opt = HashMap::new(); opt.insert("outfile", args.value_of("outfile").unwrap()); context.insert("opt", &opt); eprintln!("Create {}", opt.get("outfile").unwrap()); let mut tera = Tera::default(); tera.add_raw_templates(vec![("t", include_str!("../../templates/garr.tera.env"))]) .unwrap(); let rendered = tera.render("t", &context).unwrap(); intspan::write_lines(opt.get("outfile").unwrap(), &vec![rendered.as_str()])?; if args.is_present("all") { gen_peak(&context)?; gen_plot_xy(&context)?; fs::create_dir_all("sqls/ddl")?; gen_ddl_ctg(&context)?; gen_ddl_rsw(&context)?; gen_dql_summary(&context)?; gen_dql_rsw(&context)?; } Ok(()) } fn gen_peak(context: &Context) -> std::result::Result<(), std::io::Error> { let outname = "peak.R"; eprintln!("Create {}", outname); let mut tera = Tera::default(); tera.add_raw_templates(vec![("t", include_str!("../../templates/peak.tera.R"))]) .unwrap(); let rendered = tera.render("t", &context).unwrap(); intspan::write_lines(outname, &vec![rendered.as_str()])?; Ok(()) } fn gen_plot_xy(context: &Context) -> std::result::Result<(), std::io::Error> { let outname = "plot_xy.R"; eprintln!("Create {}", outname); let mut tera = Tera::default(); tera.add_raw_templates(vec![("t", include_str!("../../templates/plot_xy.tera.R"))]) .unwrap(); let rendered = tera.render("t", &context).unwrap(); intspan::write_lines(outname, &vec![rendered.as_str()])?; Ok(()) } fn gen_ddl_ctg(context: &Context) -> std::result::Result<(), std::io::Error> { let outname = "sqls/ddl/ctg.sql"; eprintln!("Create {}", outname); let mut tera = Tera::default(); tera.add_raw_templates(vec![( "t", include_str!("../../templates/ddl/ctg.tera.sql"), )]) .unwrap(); let rendered = tera.render("t", &context).unwrap(); intspan::write_lines(outname, &vec![rendered.as_str()])?; Ok(()) } fn gen_ddl_rsw(context: &Context) -> std::result::Result<(), std::io::Error> { let out
ec![( "t", include_str!("../../templates/ddl/rsw.tera.sql"), )]) .unwrap(); let rendered = tera.render("t", &context).unwrap(); intspan::write_lines(outname, &vec![rendered.as_str()])?; Ok(()) } fn gen_dql_summary(context: &Context) -> std::result::Result<(), std::io::Error> { let outname = "sqls/summary.sql"; eprintln!("Create {}", outname); let mut tera = Tera::default(); tera.add_raw_templates(vec![( "t", include_str!("../../templates/dql/summary.tera.sql"), )]) .unwrap(); let rendered = tera.render("t", &context).unwrap(); intspan::write_lines(outname, &vec![rendered.as_str()])?; let outname = "sqls/summary-type.sql"; eprintln!("Create {}", outname); let mut tera = Tera::default(); tera.add_raw_templates(vec![( "t", include_str!("../../templates/dql/summary-type.tera.sql"), )]) .unwrap(); let rendered = tera.render("t", &context).unwrap(); intspan::write_lines(outname, &vec![rendered.as_str()])?; Ok(()) } fn gen_dql_rsw(context: &Context) -> std::result::Result<(), std::io::Error> { let outname = "sqls/rsw-distance.sql"; eprintln!("Create {}", outname); let mut tera = Tera::default(); tera.add_raw_templates(vec![( "t", include_str!("../../templates/dql/rsw-distance.tera.sql"), )]) .unwrap(); let rendered = tera.render("t", &context).unwrap(); intspan::write_lines(outname, &vec![rendered.as_str()])?; let outname = "sqls/rsw-distance-tag.sql"; eprintln!("Create {}", outname); let mut tera = Tera::default(); tera.add_raw_templates(vec![( "t", include_str!("../../templates/dql/rsw-distance-tag.tera.sql"), )]) .unwrap(); let rendered = tera.render("t", &context).unwrap(); intspan::write_lines(outname, &vec![rendered.as_str()])?; Ok(()) }
name = "sqls/ddl/rsw.sql"; eprintln!("Create {}", outname); let mut tera = Tera::default(); tera.add_raw_templates(v
function_block-random_span
[ { "content": "// command implementation\n\npub fn execute(args: &ArgMatches) -> std::result::Result<(), std::io::Error> {\n\n // redis connection\n\n let mut conn = connect();\n\n\n\n // processing each file\n\n for infile in args.values_of(\"infiles\").unwrap() {\n\n let reader = reader(infile);\n\n\n\n for line in reader.lines().filter_map(|r| r.ok()) {\n\n let mut rg = Range::from_str(&line);\n\n if !rg.is_valid() {\n\n continue;\n\n }\n\n *rg.strand_mut() = \"\".to_string();\n\n\n\n let ctg_id = garr::find_one(&mut conn, &rg);\n\n if ctg_id.is_empty() {\n\n continue;\n\n }\n\n\n", "file_path": "src/cmd/pos.rs", "rank": 1, "score": 136813.92717859 }, { "content": "// command implementation\n\npub fn execute(args: &ArgMatches) -> std::result::Result<(), std::io::Error> {\n\n // opts\n\n let common_name = args.value_of(\"name\").unwrap();\n\n let piece: i32 = value_t!(args.value_of(\"piece\"), i32).unwrap_or_else(|e| {\n\n eprintln!(\"Need a integer for --piece\\n{}\", e);\n\n std::process::exit(1)\n\n });\n\n\n\n let fill: i32 = value_t!(args.value_of(\"fill\"), i32).unwrap_or_else(|e| {\n\n eprintln!(\"Need a integer for --fill\\n{}\", e);\n\n std::process::exit(1)\n\n });\n\n\n\n let min: i32 = value_t!(args.value_of(\"min\"), i32).unwrap_or_else(|e| {\n\n eprintln!(\"Need a integer for --min\\n{}\", e);\n\n std::process::exit(1)\n\n });\n\n\n\n // redis connection\n\n let mut conn = connect();\n", "file_path": "src/cmd/gen.rs", "rank": 2, "score": 136813.92717859 }, { "content": "// command implementation\n\npub fn execute(args: &ArgMatches) -> std::result::Result<(), std::io::Error> {\n\n // opts\n\n let infile = args.value_of(\"infile\").unwrap();\n\n\n\n // redis connection\n\n let mut conn = connect();\n\n\n\n // processing each line\n\n let reader = reader(infile);\n\n for line in reader.lines().filter_map(|r| r.ok()) {\n\n let parts: Vec<&str> = line.split('\\t').collect();\n\n\n\n let mut rg = Range::from_str(parts[0]);\n\n if !rg.is_valid() {\n\n continue;\n\n }\n\n *rg.strand_mut() = \"\".to_string();\n\n\n\n let signal = parts[2];\n\n\n", "file_path": "src/cmd/wave.rs", "rank": 3, "score": 136813.92717859 }, { "content": "// command implementation\n\npub fn execute(args: &ArgMatches) -> std::result::Result<(), std::io::Error> {\n\n // opts\n\n let size: i32 = value_t!(args.value_of(\"size\"), i32).unwrap_or_else(|e| {\n\n eprintln!(\"Need a integer for --size\\n{}\", e);\n\n std::process::exit(1)\n\n });\n\n let max: i32 = value_t!(args.value_of(\"max\"), i32).unwrap_or_else(|e| {\n\n eprintln!(\"Need a integer for --max\\n{}\", e);\n\n std::process::exit(1)\n\n });\n\n let resize: i32 = value_t!(args.value_of(\"resize\"), i32).unwrap_or_else(|e| {\n\n eprintln!(\"Need a integer for --resize\\n{}\", e);\n\n std::process::exit(1)\n\n });\n\n\n\n // redis connection\n\n let mut conn = connect();\n\n\n\n // headers\n\n let mut writer = writer(args.value_of(\"outfile\").unwrap());\n", "file_path": "src/cmd/rsw.rs", "rank": 4, "score": 136813.92717859 }, { "content": "// command implementation\n\npub fn execute(args: &ArgMatches) -> std::result::Result<(), std::io::Error> {\n\n match args.value_of(\"action\").unwrap() {\n\n \"cli\" => {\n\n cli();\n\n }\n\n \"test\" => {\n\n basics();\n\n hash();\n\n list();\n\n set();\n\n sorted_set();\n\n pipe_atomic();\n\n script();\n\n }\n\n \"info\" => {\n\n info();\n\n }\n\n \"drop\" => {\n\n drop();\n\n }\n", "file_path": "src/cmd/status.rs", "rank": 5, "score": 136813.92717859 }, { "content": "// command implementation\n\npub fn execute(args: &ArgMatches) -> std::result::Result<(), std::io::Error> {\n\n // opts\n\n let size: i32 = value_t!(args.value_of(\"size\"), i32).unwrap_or_else(|e| {\n\n eprintln!(\"Need a integer for --size\\n{}\", e);\n\n std::process::exit(1)\n\n });\n\n let step: i32 = value_t!(args.value_of(\"step\"), i32).unwrap_or_else(|e| {\n\n eprintln!(\"Need a integer for --step\\n{}\", e);\n\n std::process::exit(1)\n\n });\n\n let lag: usize = value_t!(args.value_of(\"lag\"), usize).unwrap_or_else(|e| {\n\n eprintln!(\"Need a integer for --lag\\n{}\", e);\n\n std::process::exit(1)\n\n });\n\n let threshold: f32 = value_t!(args.value_of(\"threshold\"), f32).unwrap_or_else(|e| {\n\n eprintln!(\"Need a float for --threshold\\n{}\", e);\n\n std::process::exit(1)\n\n });\n\n let influence: f32 = value_t!(args.value_of(\"influence\"), f32).unwrap_or_else(|e| {\n\n eprintln!(\"Need a float for --influence\\n{}\", e);\n", "file_path": "src/cmd/sliding.rs", "rank": 6, "score": 136813.92717859 }, { "content": "// command implementation\n\npub fn execute(args: &ArgMatches) -> std::result::Result<(), std::io::Error> {\n\n // opts\n\n let infile = args.value_of(\"infile\").unwrap();\n\n let sql_file = args.value_of(\"sql\").unwrap();\n\n let sql = std::fs::read_to_string(sql_file).expect(\"failed to read query\");\n\n\n\n let writer = writer(args.value_of(\"outfile\").unwrap());\n\n\n\n let runtime = tokio::runtime::Runtime::new().unwrap();\n\n\n\n runtime.block_on(async {\n\n // Initialize query interface\n\n let mut ctx = ExecutionContext::new();\n\n\n\n // Register data sources\n\n let schema = ctg_schema();\n\n let options = CsvReadOptions::new()\n\n .schema(&schema)\n\n .file_extension(\".tsv\")\n\n .has_header(true)\n", "file_path": "src/cmd/stat.rs", "rank": 7, "score": 136813.92717859 }, { "content": "// command implementation\n\npub fn execute(args: &ArgMatches) -> std::result::Result<(), std::io::Error> {\n\n // opts\n\n let pattern = args.value_of(\"scan\").unwrap();\n\n let fields: Vec<String> = if args.is_present(\"field\") {\n\n args.values_of(\"field\")\n\n .unwrap()\n\n .map(|s| s.to_string())\n\n .collect()\n\n } else {\n\n Vec::new()\n\n };\n\n\n\n // redis connection\n\n let mut conn = connect();\n\n let mut conn2 = connect(); // can't use one same `conn` inside an iter\n\n\n\n // headers\n\n let mut writer = writer(args.value_of(\"outfile\").unwrap());\n\n\n\n // scan\n", "file_path": "src/cmd/tsv.rs", "rank": 8, "score": 136813.92717859 }, { "content": "// command implementation\n\npub fn execute(args: &ArgMatches) -> std::result::Result<(), std::io::Error> {\n\n // opts\n\n let infile = args.value_of(\"infile\").unwrap();\n\n let tag = args.value_of(\"tag\").unwrap();\n\n\n\n // redis connection\n\n let mut conn = connect();\n\n\n\n // processing each line\n\n let reader = reader(infile);\n\n for line in reader.lines().filter_map(|r| r.ok()) {\n\n let mut rg = Range::from_str(&line);\n\n if !rg.is_valid() {\n\n continue;\n\n }\n\n *rg.strand_mut() = \"\".to_string();\n\n\n\n let ctg_id = garr::find_one(&mut conn, &rg);\n\n if ctg_id.is_empty() {\n\n continue;\n", "file_path": "src/cmd/range.rs", "rank": 9, "score": 136813.92717859 }, { "content": "#[test]\n\nfn command_env_env() -> Result<(), Box<dyn std::error::Error>> {\n\n let mut cmd = Command::cargo_bin(\"garr\")?;\n\n let output = cmd\n\n .env(\"REDIS_PASSWORD\", \"mYpa$$\")\n\n .arg(\"env\")\n\n .arg(\"--outfile\")\n\n .arg(\"stdout\")\n\n .output()\n\n .unwrap();\n\n let stdout = String::from_utf8(output.stdout).unwrap();\n\n\n\n assert_eq!(stdout.lines().count(), 6);\n\n assert!(\n\n stdout.contains(\"REDIS_PASSWORD='mYpa$$'\"),\n\n \"modified values\"\n\n );\n\n\n\n Ok(())\n\n}\n\n\n", "file_path": "tests/cli.rs", "rank": 17, "score": 109510.69963696768 }, { "content": "#[test]\n\nfn command_env() -> Result<(), Box<dyn std::error::Error>> {\n\n let mut cmd = Command::cargo_bin(\"garr\")?;\n\n let output = cmd\n\n .arg(\"env\")\n\n .arg(\"--outfile\")\n\n .arg(\"stdout\")\n\n .output()\n\n .unwrap();\n\n let stdout = String::from_utf8(output.stdout).unwrap();\n\n\n\n assert_eq!(stdout.lines().count(), 6);\n\n assert!(stdout.contains(\"REDIS_PASSWORD=''\"), \"original values\");\n\n\n\n Ok(())\n\n}\n\n\n", "file_path": "tests/cli.rs", "rank": 18, "score": 103003.25713852869 }, { "content": "// Create clap subcommand arguments\n\npub fn make_subcommand<'a, 'b>() -> App<'a, 'b> {\n\n SubCommand::with_name(\"stat\")\n\n .about(\"Add range files to positions\")\n\n .arg(\n\n Arg::with_name(\"infile\")\n\n .help(\"Sets the input file to use\")\n\n .required(true)\n\n .index(1),\n\n )\n\n .arg(\n\n Arg::with_name(\"sql\")\n\n .long(\"sql\")\n\n .short(\"s\")\n\n .takes_value(true)\n\n .empty_values(false)\n\n .help(\"SQL query file\"),\n\n )\n\n .arg(\n\n Arg::with_name(\"outfile\")\n\n .short(\"o\")\n\n .long(\"outfile\")\n\n .takes_value(true)\n\n .default_value(\"stdout\")\n\n .empty_values(false)\n\n .help(\"Output filename. [stdout] for screen\"),\n\n )\n\n}\n\n\n", "file_path": "src/cmd/stat.rs", "rank": 19, "score": 95056.21401469933 }, { "content": "// Create clap subcommand arguments\n\npub fn make_subcommand<'a, 'b>() -> App<'a, 'b> {\n\n SubCommand::with_name(\"wave\")\n\n .about(\"Add peaks of GC-waves\")\n\n .after_help(\n\n \"\\\n\n left-/right- wave length may be negative \\\n\n \",\n\n )\n\n .arg(\n\n Arg::with_name(\"infile\")\n\n .help(\"Sets the input file to use\")\n\n .required(true)\n\n .index(1),\n\n )\n\n}\n\n\n", "file_path": "src/cmd/wave.rs", "rank": 20, "score": 95056.21401469933 }, { "content": "// Create clap subcommand arguments\n\npub fn make_subcommand<'a, 'b>() -> App<'a, 'b> {\n\n SubCommand::with_name(\"sliding\")\n\n .about(\"Sliding windows along a chromosome\")\n\n .after_help(\n\n \"\\\n\n --step and --lag should be adjust simultaneously. \\\n\n \",\n\n )\n\n .arg(\n\n Arg::with_name(\"ctg\")\n\n .long(\"ctg\")\n\n .takes_value(true)\n\n .default_value(\"ctg:*\")\n\n .empty_values(false)\n\n .help(\"Sets full name or prefix of contigs, `ctg:I:*` or `ctg:I:2`\"),\n\n )\n\n .arg(\n\n Arg::with_name(\"size\")\n\n .long(\"size\")\n\n .takes_value(true)\n", "file_path": "src/cmd/sliding.rs", "rank": 21, "score": 95056.21401469933 }, { "content": "// Create clap subcommand arguments\n\npub fn make_subcommand<'a, 'b>() -> App<'a, 'b> {\n\n SubCommand::with_name(\"gen\")\n\n .about(\"Generate the database from (gzipped) fasta files\")\n\n .arg(\n\n Arg::with_name(\"infiles\")\n\n .help(\"Sets the input files to use\")\n\n .required(true)\n\n .min_values(1)\n\n .index(1),\n\n )\n\n .arg(\n\n Arg::with_name(\"name\")\n\n .long(\"name\")\n\n .short(\"n\")\n\n .takes_value(true)\n\n .default_value(\"target\")\n\n .empty_values(false)\n\n .help(\"The common name, e.g. S288c\"),\n\n )\n\n .arg(\n", "file_path": "src/cmd/gen.rs", "rank": 22, "score": 95056.21401469933 }, { "content": "// Create clap subcommand arguments\n\npub fn make_subcommand<'a, 'b>() -> App<'a, 'b> {\n\n SubCommand::with_name(\"pos\")\n\n .about(\"Add range files to positions\")\n\n .arg(\n\n Arg::with_name(\"infiles\")\n\n .help(\"Sets the input file to use\")\n\n .required(true)\n\n .min_values(1)\n\n .index(1),\n\n )\n\n}\n\n\n", "file_path": "src/cmd/pos.rs", "rank": 23, "score": 95056.21401469933 }, { "content": "// Create clap subcommand arguments\n\npub fn make_subcommand<'a, 'b>() -> App<'a, 'b> {\n\n SubCommand::with_name(\"range\")\n\n .about(\"Add ranges\")\n\n .arg(\n\n Arg::with_name(\"infile\")\n\n .help(\"Sets the input file to use\")\n\n .required(true)\n\n .index(1),\n\n )\n\n .arg(\n\n Arg::with_name(\"tag\")\n\n .long(\"tag\")\n\n .short(\"t\")\n\n .takes_value(true)\n\n .default_value(\"range\")\n\n .empty_values(false)\n\n .help(\"Range tags\"),\n\n )\n\n}\n\n\n", "file_path": "src/cmd/range.rs", "rank": 24, "score": 95056.21401469933 }, { "content": "// Create clap subcommand arguments\n\npub fn make_subcommand<'a, 'b>() -> App<'a, 'b> {\n\n SubCommand::with_name(\"tsv\")\n\n .about(\"Exports Redis hashes to a tsv file\")\n\n .after_help(\n\n \"\\\n\n All hashes should have the same structure. \\\n\n ID, chr_name, chr_start, chr_end will always be included. \\\n\n \",\n\n )\n\n .arg(\n\n Arg::with_name(\"scan\")\n\n .long(\"scan\")\n\n .short(\"s\")\n\n .takes_value(true)\n\n .default_value(\"ctg:*\")\n\n .empty_values(false)\n\n .help(\"Sets the pattern to scan, `ctg:*`\"),\n\n )\n\n .arg(\n\n Arg::with_name(\"field\")\n", "file_path": "src/cmd/tsv.rs", "rank": 25, "score": 95056.21401469933 }, { "content": "// Create clap subcommand arguments\n\npub fn make_subcommand<'a, 'b>() -> App<'a, 'b> {\n\n SubCommand::with_name(\"status\")\n\n .about(\"Test Redis config and connection\")\n\n .after_help(\n\n r#\"\n\nList of actions:\n\n\n\n* cli: find `redis-cli` in $PATH\n\n* test: redis.rs functionality\n\n* info: Command INFO - memory usage of the database\n\n* drop: Command FLUSHDB - drop the database for accepting new data\n\n* dump: Command SAVE - export of the contents of the database\n\n* stop: Command SHUTDOWN - quit the server\n\n\n\n\"#,\n\n )\n\n .arg(\n\n Arg::with_name(\"action\")\n\n .help(\"What to do\")\n\n .required(true)\n", "file_path": "src/cmd/status.rs", "rank": 26, "score": 95056.21401469933 }, { "content": "// Create clap subcommand arguments\n\npub fn make_subcommand<'a, 'b>() -> App<'a, 'b> {\n\n SubCommand::with_name(\"rsw\")\n\n .about(\"Sliding windows around a range\")\n\n .after_help(\n\n \"\\\n\n --step and --lag should be adjust simultaneously \\\n\n \",\n\n )\n\n .arg(\n\n Arg::with_name(\"ctg\")\n\n .long(\"ctg\")\n\n .takes_value(true)\n\n .default_value(\"ctg:*\")\n\n .empty_values(false)\n\n .help(\"Sets full name or prefix of contigs, `ctg:I:*` or `ctg:I:2`\"),\n\n )\n\n .arg(\n\n Arg::with_name(\"style\")\n\n .long(\"style\")\n\n .takes_value(true)\n", "file_path": "src/cmd/rsw.rs", "rank": 27, "score": 95056.21401469933 }, { "content": "pub fn get_seq(conn: &mut redis::Connection, rg: &Range) -> String {\n\n let ctg_id = find_one(conn, rg);\n\n\n\n if ctg_id.is_empty() {\n\n return \"\".to_string();\n\n }\n\n\n\n let chr_start: i32 = conn.hget(&ctg_id, \"chr_start\").unwrap();\n\n\n\n let ctg_start = (rg.start() - chr_start + 1) as isize;\n\n let ctg_end = (rg.end() - chr_start + 1) as isize;\n\n\n\n let seq: String = conn\n\n .getrange(format!(\"seq:{}\", ctg_id), ctg_start - 1, ctg_end - 1)\n\n .unwrap();\n\n\n\n seq\n\n}\n\n\n", "file_path": "src/libs/redis.rs", "rank": 28, "score": 94772.00878452786 }, { "content": "pub fn find_one(conn: &mut redis::Connection, rg: &Range) -> String {\n\n // MULTI\n\n // ZRANGESTORE tmp-s:I ctg-s:I 0 1000 BYSCORE\n\n // ZRANGESTORE tmp-e:I ctg-e:I 1100 +inf BYSCORE\n\n // ZINTERSTORE tmp-ctg:I 2 tmp-s:I tmp-e:I AGGREGATE MIN\n\n // DEL tmp-s:I tmp-e:I\n\n // ZPOPMIN tmp-ctg:I\n\n // EXEC\n\n\n\n let res: Vec<BTreeMap<String, isize>> = redis::pipe()\n\n .atomic()\n\n .cmd(\"ZRANGESTORE\")\n\n .arg(format!(\"tmp-s:{}\", rg.chr()))\n\n .arg(format!(\"ctg-s:{}\", rg.chr()))\n\n .arg(0)\n\n .arg(*rg.start())\n\n .arg(\"BYSCORE\")\n\n .ignore()\n\n .cmd(\"ZRANGESTORE\")\n\n .arg(format!(\"tmp-e:{}\", rg.chr()))\n", "file_path": "src/libs/redis.rs", "rank": 29, "score": 94772.00878452786 }, { "content": "/// This is an expensive operation\n\npub fn get_gc_content(conn: &mut redis::Connection, rg: &Range) -> f32 {\n\n let bucket = format!(\"cache:{}:{}\", rg.chr(), rg.start() / 1000);\n\n let field = rg.to_string();\n\n let expire = 180;\n\n let res = conn.hget(&bucket, &field).unwrap();\n\n\n\n return match res {\n\n Some(res) => {\n\n let _: () = conn.expire(&bucket, expire).unwrap();\n\n\n\n res\n\n }\n\n None => {\n\n let seq = get_seq(conn, rg);\n\n\n\n let gc_content = if seq.is_empty() {\n\n 0.\n\n } else {\n\n bio::seq_analysis::gc::gc_content(seq.bytes())\n\n };\n\n let _: () = conn.hset(&bucket, &field, gc_content).unwrap();\n\n let _: () = conn.expire(&bucket, expire).unwrap();\n\n\n\n gc_content\n\n }\n\n };\n\n}\n\n\n", "file_path": "src/libs/redis.rs", "rank": 30, "score": 92946.99789506898 }, { "content": "pub fn get_scan_count(conn: &mut redis::Connection, scan: String) -> i32 {\n\n // number of matches\n\n let mut count = 0;\n\n let iter: redis::Iter<'_, String> = conn.scan_match(scan).unwrap();\n\n for _ in iter {\n\n count += 1;\n\n }\n\n\n\n count\n\n}\n\n\n", "file_path": "src/libs/redis.rs", "rank": 31, "score": 92946.99789506898 }, { "content": "fn script() {\n\n let mut conn = connect();\n\n println!(\"******* Running Lua Scripts *******\");\n\n\n\n let script = redis::Script::new(\n\n r#\"\n\nreturn tonumber(ARGV[1]) + tonumber(ARGV[2]);\n\n\n\n\"#,\n\n );\n\n let res: RedisResult<i32> = script.arg(1).arg(2).invoke(&mut conn);\n\n eprintln!(\"res = {:#?}\", res);\n\n\n\n // https://github.com/redis/redis/issues/7#issuecomment-596464166\n\n}\n", "file_path": "src/cmd/status.rs", "rank": 32, "score": 91525.41962147129 }, { "content": "pub fn get_scan_vec(conn: &mut redis::Connection, scan: String) -> Vec<String> {\n\n // number of matches\n\n let mut keys: Vec<String> = Vec::new();\n\n let iter: redis::Iter<'_, String> = conn.scan_match(scan).unwrap();\n\n for x in iter {\n\n keys.push(x);\n\n }\n\n\n\n keys\n\n}\n\n\n", "file_path": "src/libs/redis.rs", "rank": 33, "score": 89512.65115197015 }, { "content": "pub fn get_key_pos(conn: &mut redis::Connection, key: &str) -> (String, i32, i32) {\n\n let chr_name: String = conn.hget(key, \"chr_name\").unwrap();\n\n let chr_start: i32 = conn.hget(key, \"chr_start\").unwrap();\n\n let chr_end: i32 = conn.hget(key, \"chr_end\").unwrap();\n\n\n\n (chr_name, chr_start, chr_end)\n\n}\n\n\n", "file_path": "src/libs/redis.rs", "rank": 34, "score": 86331.3156318595 }, { "content": "#[test]\n\nfn command_status() -> Result<(), Box<dyn std::error::Error>> {\n\n // env\n\n let mut cmd = Command::cargo_bin(\"garr\")?;\n\n cmd.arg(\"env\").unwrap();\n\n\n\n // drop\n\n let mut cmd = Command::cargo_bin(\"garr\")?;\n\n cmd.arg(\"status\").arg(\"drop\").unwrap();\n\n\n\n // test\n\n let mut cmd = Command::cargo_bin(\"garr\")?;\n\n let output = cmd.arg(\"status\").arg(\"test\").output().unwrap();\n\n let stdout = String::from_utf8(output.stdout).unwrap();\n\n\n\n assert!(stdout.lines().count() > 20);\n\n assert!(stdout.contains(\"Running SET commands\"));\n\n\n\n // dump\n\n let mut cmd = Command::cargo_bin(\"garr\")?;\n\n let output = cmd.arg(\"status\").arg(\"dump\").output().unwrap();\n\n let stdout = String::from_utf8(output.stdout).unwrap();\n\n\n\n assert_eq!(stdout.lines().count(), 1);\n\n assert!(stdout.contains(\"OK\"));\n\n\n\n Ok(())\n\n}\n\n\n", "file_path": "tests/cli.rs", "rank": 35, "score": 81108.89930143906 }, { "content": "#[test]\n\nfn command_invalid() -> Result<(), Box<dyn std::error::Error>> {\n\n let mut cmd = Command::cargo_bin(\"garr\")?;\n\n cmd.arg(\"foobar\");\n\n cmd.assert().failure().stderr(predicate::str::contains(\n\n \"which wasn't expected, or isn't valid in this context\",\n\n ));\n\n\n\n Ok(())\n\n}\n\n\n", "file_path": "tests/cli.rs", "rank": 36, "score": 81108.89930143906 }, { "content": "#[test]\n\nfn command_gen() -> Result<(), Box<dyn std::error::Error>> {\n\n // env\n\n let mut cmd = Command::cargo_bin(\"garr\")?;\n\n cmd.arg(\"env\").unwrap();\n\n\n\n // drop\n\n let mut cmd = Command::cargo_bin(\"garr\")?;\n\n cmd.arg(\"status\").arg(\"drop\").unwrap();\n\n\n\n // gen\n\n let mut cmd = Command::cargo_bin(\"garr\")?;\n\n let output = cmd\n\n .arg(\"gen\")\n\n .arg(\"tests/S288c/genome.fa.gz\")\n\n .arg(\"--piece\")\n\n .arg(\"100000\")\n\n .output()\n\n .unwrap();\n\n let stdout = String::from_utf8(output.stdout).unwrap();\n\n\n", "file_path": "tests/cli.rs", "rank": 37, "score": 81108.89930143906 }, { "content": "#[test]\n\nfn command_wave() -> Result<(), Box<dyn std::error::Error>> {\n\n // env\n\n let mut cmd = Command::cargo_bin(\"garr\")?;\n\n cmd.arg(\"env\").unwrap();\n\n\n\n // drop\n\n let mut cmd = Command::cargo_bin(\"garr\")?;\n\n cmd.arg(\"status\").arg(\"drop\").unwrap();\n\n\n\n // gen\n\n let mut cmd = Command::cargo_bin(\"garr\")?;\n\n cmd.arg(\"gen\")\n\n .arg(\"tests/S288c/genome.fa.gz\")\n\n .arg(\"--piece\")\n\n .arg(\"500000\")\n\n .unwrap();\n\n\n\n // wave\n\n let mut cmd = Command::cargo_bin(\"garr\")?;\n\n let output = cmd\n", "file_path": "tests/cli.rs", "rank": 38, "score": 81108.89930143906 }, { "content": "#[test]\n\nfn command_pos() -> Result<(), Box<dyn std::error::Error>> {\n\n // env\n\n let mut cmd = Command::cargo_bin(\"garr\")?;\n\n cmd.arg(\"env\").unwrap();\n\n\n\n // drop\n\n let mut cmd = Command::cargo_bin(\"garr\")?;\n\n cmd.arg(\"status\").arg(\"drop\").unwrap();\n\n\n\n // gen\n\n let mut cmd = Command::cargo_bin(\"garr\")?;\n\n cmd.arg(\"gen\")\n\n .arg(\"tests/S288c/genome.fa.gz\")\n\n .arg(\"--piece\")\n\n .arg(\"100000\")\n\n .unwrap();\n\n\n\n // pos\n\n let mut cmd = Command::cargo_bin(\"garr\")?;\n\n let output = cmd\n", "file_path": "tests/cli.rs", "rank": 39, "score": 81108.89930143906 }, { "content": "#[test]\n\nfn command_range() -> Result<(), Box<dyn std::error::Error>> {\n\n // env\n\n let mut cmd = Command::cargo_bin(\"garr\")?;\n\n cmd.arg(\"env\").unwrap();\n\n\n\n // drop\n\n let mut cmd = Command::cargo_bin(\"garr\")?;\n\n cmd.arg(\"status\").arg(\"drop\").unwrap();\n\n\n\n // gen\n\n let mut cmd = Command::cargo_bin(\"garr\")?;\n\n cmd.arg(\"gen\")\n\n .arg(\"tests/S288c/genome.fa.gz\")\n\n .arg(\"--piece\")\n\n .arg(\"100000\")\n\n .unwrap();\n\n\n\n // range\n\n let mut cmd = Command::cargo_bin(\"garr\")?;\n\n let output = cmd\n", "file_path": "tests/cli.rs", "rank": 40, "score": 81108.89930143906 }, { "content": "pub fn center_sw(\n\n parent: &IntSpan,\n\n start: i32,\n\n end: i32,\n\n size: i32,\n\n max: i32,\n\n) -> Vec<(IntSpan, String, i32)> {\n\n let mut windows = vec![];\n\n\n\n let w0 = crate::center_resize(parent, &IntSpan::from_pair(start, end), size);\n\n windows.push((w0.clone(), \"M\".to_string(), 0));\n\n\n\n for sw_type in [\"L\", \"R\"] {\n\n // sw_start and sw_end are both index of parent\n\n let mut sw_start;\n\n let mut sw_end;\n\n\n\n if sw_type == \"R\" {\n\n sw_start = parent.index(w0.max()) + 1;\n\n sw_end = sw_start + size - 1;\n", "file_path": "src/libs/window.rs", "rank": 41, "score": 78967.7792064228 }, { "content": "pub fn ctg_gc_stat(\n\n conn: &mut redis::Connection,\n\n rg: &Range,\n\n size: i32,\n\n step: i32,\n\n parent: &IntSpan,\n\n seq: &String,\n\n) -> (f32, f32, f32, f32) {\n\n let intspan = rg.intspan();\n\n let windows = sliding(&intspan, size, step);\n\n\n\n let mut gcs = Vec::new();\n\n\n\n for w in windows {\n\n let gc_content =\n\n ctg_gc_content(conn, &Range::from(rg.chr(), w.min(), w.max()), parent, seq);\n\n gcs.push(gc_content);\n\n }\n\n\n\n gc_stat(&gcs)\n\n}\n", "file_path": "src/libs/redis.rs", "rank": 42, "score": 76975.24765256236 }, { "content": "pub fn ctg_gc_content(\n\n conn: &mut redis::Connection,\n\n rg: &Range,\n\n parent: &IntSpan,\n\n seq: &String,\n\n) -> f32 {\n\n let bucket = format!(\"cache:{}:{}\", rg.chr(), rg.start() / 1000);\n\n let field = rg.to_string();\n\n let expire = 180;\n\n let res = conn.hget(&bucket, &field).unwrap();\n\n\n\n return match res {\n\n Some(res) => {\n\n let _: () = conn.expire(&bucket, expire).unwrap();\n\n\n\n res\n\n }\n\n None => {\n\n // converted to ctg index\n\n let from = parent.index(*rg.start()) as usize;\n", "file_path": "src/libs/redis.rs", "rank": 43, "score": 76975.24765256236 }, { "content": "pub fn get_gc_stat(\n\n conn: &mut redis::Connection,\n\n rg: &Range,\n\n size: i32,\n\n step: i32,\n\n) -> (f32, f32, f32, f32) {\n\n let intspan = rg.intspan();\n\n let windows = sliding(&intspan, size, step);\n\n\n\n let mut gcs = Vec::new();\n\n\n\n for w in windows {\n\n let gc_content = get_gc_content(conn, &Range::from(rg.chr(), w.min(), w.max()));\n\n gcs.push(gc_content);\n\n }\n\n\n\n gc_stat(&gcs)\n\n}\n\n\n", "file_path": "src/libs/redis.rs", "rank": 44, "score": 76975.24765256236 }, { "content": "pub fn get_scan_str(\n\n conn: &mut redis::Connection,\n\n scan: String,\n\n field: String,\n\n) -> HashMap<String, String> {\n\n // number of matches\n\n let keys: Vec<String> = get_scan_vec(conn, scan);\n\n\n\n let mut hash: HashMap<String, _> = HashMap::new();\n\n for key in keys {\n\n let val: String = conn.hget(&key, &field).unwrap();\n\n hash.insert(key.clone(), val);\n\n }\n\n\n\n hash\n\n}\n\n\n", "file_path": "src/libs/redis.rs", "rank": 45, "score": 76975.24765256236 }, { "content": "pub fn get_scan_int(\n\n conn: &mut redis::Connection,\n\n scan: String,\n\n field: String,\n\n) -> HashMap<String, i32> {\n\n // number of matches\n\n let keys: Vec<String> = get_scan_vec(conn, scan);\n\n\n\n let mut hash: HashMap<String, _> = HashMap::new();\n\n for key in keys {\n\n let val: i32 = conn.hget(&key, &field).unwrap();\n\n hash.insert(key.clone(), val);\n\n }\n\n\n\n hash\n\n}\n\n\n", "file_path": "src/libs/redis.rs", "rank": 46, "score": 76975.24765256236 }, { "content": "pub fn connect() -> redis::Connection {\n\n dotenv::from_filename(\"garr.env\").expect(\"Failed to read garr.env file\");\n\n\n\n let redis_host = dotenv::var(\"REDIS_HOST\").unwrap();\n\n let redis_port = dotenv::var(\"REDIS_PORT\").unwrap();\n\n let redis_password = dotenv::var(\"REDIS_PASSWORD\").unwrap_or_default();\n\n let redis_tls = dotenv::var(\"REDIS_TLS\").unwrap();\n\n\n\n // if Redis server needs secure connection\n\n let uri_scheme = match redis_tls.as_ref() {\n\n \"true\" => \"rediss\",\n\n \"false\" => \"redis\",\n\n _ => \"redis\",\n\n };\n\n\n\n let redis_conn_url = format!(\n\n \"{}://:{}@{}:{}\",\n\n uri_scheme, redis_password, redis_host, redis_port\n\n );\n\n //println!(\"{}\", redis_conn_url);\n\n\n\n redis::Client::open(redis_conn_url)\n\n .expect(\"Invalid connection URL\")\n\n .get_connection()\n\n .expect(\"Failed to connect to Redis\")\n\n}\n\n\n", "file_path": "src/libs/redis.rs", "rank": 47, "score": 73122.02572647107 }, { "content": "pub fn stddev(data: &[f32]) -> f32 {\n\n let len = data.len() as f32;\n\n let mean = mean(data);\n\n\n\n let sq_sum = data.iter().map(|x| (x - mean) * (x - mean)).sum::<f32>();\n\n (sq_sum / (len - 1.)).sqrt()\n\n}\n\n\n", "file_path": "src/libs/stat.rs", "rank": 48, "score": 69701.15673053882 }, { "content": "pub fn mean(data: &[f32]) -> f32 {\n\n let len = data.len() as f32;\n\n let sum = data.iter().sum::<f32>();\n\n\n\n sum / len\n\n}\n\n\n", "file_path": "src/libs/stat.rs", "rank": 49, "score": 69701.15673053882 }, { "content": "pub fn gc_stat(gcs: &Vec<f32>) -> (f32, f32, f32, f32) {\n\n let mean = mean(gcs);\n\n let stddev = stddev(gcs);\n\n\n\n // coefficient of variation\n\n let cv = if mean == 0. || mean == 1. {\n\n 0.\n\n } else if mean <= 0.5 {\n\n stddev / mean\n\n } else {\n\n stddev / (1. - mean)\n\n };\n\n\n\n // Signal-to-noise ratio\n\n let snr = if stddev == 0. {\n\n 0.\n\n } else if mean <= 0.5 {\n\n mean / stddev\n\n } else {\n\n (1. - mean) / stddev\n\n };\n\n\n\n (mean, stddev, cv, snr)\n\n}\n\n\n", "file_path": "src/libs/stat.rs", "rank": 50, "score": 57518.98340982945 }, { "content": "fn main() -> std::io::Result<()> {\n\n let app = App::new(\"garr\")\n\n .version(crate_version!())\n\n .author(crate_authors!())\n\n .about(\"Genome Analyst with Rust and Redis\")\n\n .setting(AppSettings::ArgRequiredElseHelp)\n\n .subcommand(cmd::env::make_subcommand())\n\n .subcommand(cmd::status::make_subcommand())\n\n .subcommand(cmd::gen::make_subcommand())\n\n .subcommand(cmd::pos::make_subcommand())\n\n .subcommand(cmd::range::make_subcommand())\n\n .subcommand(cmd::sliding::make_subcommand())\n\n // .subcommand(cmd::stat::make_subcommand())\n\n .subcommand(cmd::rsw::make_subcommand())\n\n .subcommand(cmd::tsv::make_subcommand())\n\n .subcommand(cmd::wave::make_subcommand());\n\n\n\n // Check which subcomamnd the user ran...\n\n match app.get_matches().subcommand() {\n\n (\"env\", Some(sub_matches)) => cmd::env::execute(sub_matches),\n", "file_path": "src/garr.rs", "rank": 51, "score": 56272.34441130533 }, { "content": "fn default_redis_host() -> String {\n\n \"localhost\".to_string()\n\n}\n\n\n", "file_path": "src/libs/redis.rs", "rank": 52, "score": 55640.65759874083 }, { "content": "fn default_redis_tls() -> bool {\n\n false\n\n}\n\n\n", "file_path": "src/libs/redis.rs", "rank": 53, "score": 55640.65759874083 }, { "content": "fn default_redis_port() -> u32 {\n\n 6379\n\n}\n\n\n", "file_path": "src/libs/redis.rs", "rank": 54, "score": 55640.65759874083 }, { "content": "pub fn sliding(intspan: &IntSpan, size: i32, step: i32) -> Vec<IntSpan> {\n\n let mut windows = vec![];\n\n\n\n let mut start = 1;\n\n loop {\n\n let end = start + size - 1;\n\n if end > intspan.size() {\n\n break;\n\n }\n\n let window = intspan.slice(start, end);\n\n start += step;\n\n\n\n windows.push(window);\n\n }\n\n\n\n windows\n\n}\n\n\n", "file_path": "src/libs/window.rs", "rank": 55, "score": 54285.9440043739 }, { "content": "pub fn center_resize(parent: &IntSpan, intspan: &IntSpan, resize: i32) -> IntSpan {\n\n // find the middles of intspan\n\n let half_size = intspan.size() / 2;\n\n let mid_left = if half_size == 0 {\n\n intspan.at(1)\n\n } else {\n\n intspan.at(half_size)\n\n };\n\n let mid_right = if half_size == 0 {\n\n intspan.at(1)\n\n } else {\n\n intspan.at(half_size + 1)\n\n };\n\n let mid_left_idx = parent.index(mid_left);\n\n let mid_right_idx = parent.index(mid_right);\n\n\n\n // map to parent\n\n let half_resize = resize / 2;\n\n let mut left_idx = mid_left_idx - half_resize + 1;\n\n if left_idx < 1 {\n\n left_idx = 1;\n\n }\n\n let mut right_idx = mid_right_idx + half_resize - 1;\n\n if right_idx > parent.size() {\n\n right_idx = parent.size();\n\n }\n\n\n\n parent.slice(left_idx, right_idx)\n\n}\n\n\n", "file_path": "src/libs/window.rs", "rank": 56, "score": 54174.99610370833 }, { "content": "pub fn thresholding_algo(data: &Vec<f32>, lag: usize, threshold: f32, influence: f32) -> Vec<i32> {\n\n // the results (peaks, 1 or -1)\n\n let mut signals: Vec<i32> = vec![0; data.len()];\n\n\n\n // filter out the signals (peaks) from original list (using influence arg)\n\n let mut filtered_data: Vec<f32> = data.clone();\n\n\n\n // the current average of the rolling window\n\n let mut avg_filter: Vec<f32> = vec![0.; data.len()];\n\n\n\n // the current standard deviation of the rolling window\n\n let mut std_filter: Vec<f32> = vec![0.; data.len()];\n\n\n\n // init avg_filter & std_filter\n\n avg_filter[lag - 1] = mean(&data[0..lag]);\n\n std_filter[lag - 1] = stddev(&data[0..lag]);\n\n\n\n // loop input starting at end of rolling window\n\n for i in lag..data.len() {\n\n // if the distance between the current value and average is enough standard deviations (threshold) away\n", "file_path": "src/libs/stat.rs", "rank": 57, "score": 49901.724225238206 }, { "content": "## EXAMPLES\n\n\n\n```shell script\n\nREDIS_TLS=true REDIS_PASSWORD='mYpa$$' garr env -o stdout\n\n\n\ngarr env\n\n\n\ngarr status test\n\n\n\n```\n\n\n\n## AUTHOR\n\n\n\nQiang Wang <[email protected]>\n\n\n\n## LICENSE\n\n\n\nMIT.\n\n\n\nCopyright by Qiang Wang.\n\n\n\nWritten by Qiang Wang <[email protected]>, 2021.\n", "file_path": "README.md", "rank": 58, "score": 40671.335275610334 }, { "content": "# `garr`\n\n\n\n![Publish](https://github.com/wang-q/garr/workflows/Publish/badge.svg)\n\n![Build](https://github.com/wang-q/garr/workflows/Build/badge.svg)\n\n\n\nGenome Analyst with Rust and Redis\n\n\n\n## INSTALL\n\n\n\nCurrent release: 0.1.0\n\n\n\n```shell script\n\ncargo install --force --offline --path .\n\n\n\n```\n\n\n\n\n\n## SYNOPSIS\n\n\n\n```\n\n$ garr help\n\ngarr 0.1.1-alpha.0\n\nwang-q <[email protected]>\n\nGenome Analyst with Rust and Redis\n\n\n\nUSAGE:\n\n garr [SUBCOMMAND]\n\n\n\nFLAGS:\n\n -h, --help Prints help information\n\n -V, --version Prints version information\n\n\n\nSUBCOMMANDS:\n\n env Create a .env file\n\n gen Generate the database from (gzipped) fasta files\n\n help Prints this message or the help of the given subcommand(s)\n\n pos Add range files to positions\n\n range Add ranges\n\n rsw Sliding windows around a range\n\n sliding Sliding windows along a chromosome\n\n status Test Redis config and connection\n\n tsv Exports Redis hashes to a tsv file\n\n wave Add peaks of GC-waves\n\n\n\n```\n\n\n\n## RUNTIME DEPENDENCIES\n\n\n\n* Command line tools managed by `Linuxbrew`\n\n\n\n```shell script\n\nbrew install redis\n\n\n\nbrew install parallel wget pigz\n\nbrew install datamash miller\n\n\n\nbrew tap wang-q/tap\n\nbrew install wang-q/tap/tsv-utils wang-q/tap/intspan\n\n\n\n```\n\n\n\n* R (4.1) packages\n\n\n\n```shell script\n\n# R packages\n\nparallel -j 1 -k --line-buffer '\n\n Rscript -e '\\'' if (!requireNamespace(\"{}\", quietly = TRUE)) { install.packages(\"{}\", repos=\"https://mirrors.tuna.tsinghua.edu.cn/CRAN\") } '\\''\n\n ' ::: \\\n\n getopt \\\n\n extrafont ggplot2 gridExtra \\\n\n tidyverse\n\n\n\n```\n\n\n\n* Other tools\n\n\n\n```shell script\n\n\n\n# Redis GUI\n\n# winget install qishibo.AnotherRedisDesktopManager\n\n\n\n# Clickhouse\n\nexport LTS=21.8.4.51\n\ncurl -LO https://repo.clickhouse.tech/tgz/lts/clickhouse-common-static-${LTS}.tgz\n\n\n\ntar -xzvf clickhouse-common-static-${LTS}.tgz\n\nsudo bash clickhouse-common-static-${LTS}/install/doinst.sh\n\n\n\n# Clickhouse GUI\n\ngit clone https://github.com/VKCOM/lighthouse\n\nbrowser lighthouse/index.html\n\n\n\n```\n\n\n", "file_path": "README.md", "rank": 59, "score": 40668.59740037858 }, { "content": "# Change Log\n\n\n\n## Unreleased - ReleaseDate\n\n\n\n* Add `garr status stop`\n\n\n\n* Queries done by clickhouse\n\n * `garr env` creates sqls\n\n * Stats of ctg and rsw\n\n\n\n* `garr stat` - await makes the compilation extremely slow\n\n\n\n## 0.1.0 - 2021-08-27\n\n\n\n* Skeletons, need to be filled\n\n\n\n* Subcommands\n\n * env\n\n * gen\n\n * pos\n\n * range\n\n * rsw\n\n * sliding\n\n * status\n\n * tsv\n\n * wave\n\n\n", "file_path": "CHANGELOG.md", "rank": 60, "score": 40667.08943223281 }, { "content": "# From cli\n\n\n\n## `redis-cli`\n\n\n\n```shell script\n\n# Inside WSL\n\n# cd /mnt/c/Users/wangq/Scripts/garr\n\n\n\n# start redis-server\n\nredis-server --appendonly no --dir tests/S288c/\n\n\n\n# start with dump file\n\n# redis-server --appendonly no --dir ~/Scripts/rust/garr/tests/S288c/ --dbfilename dump.rdb\n\n\n\n# check config\n\necho \"CONFIG GET *\" | redis-cli | grep -e \"dir\" -e \"dbfilename\" -A1\n\n\n\n# create garr.env\n\ngarr env\n\n\n\n# check DB\n\ngarr status test\n\n\n\n# drop DB\n\nredis-cli FLUSHDB\n\n\n\n# chr.sizes\n\nfaops size tests/S288c/genome.fa.gz > tests/S288c/chr.sizes\n\n\n\n# generate DB\n\n#garr gen tests/S288c/chr.sizes\n\nredis-cli SET common_name S288c\n\n\n\ncat tests/S288c/chr.sizes |\n\n parallel -k -r --col-sep '\\t' '\n\n redis-cli HSET chr {1} {2}\n\n '\n\nredis-cli --raw HLEN chr |\n\n xargs -I{} echo There are {} chromosomes\n\n\n\ncat tests/S288c/chr.sizes |\n\n parallel -k -r --col-sep '\\t' '\n\n redis-cli HSET ctg:{1}:1 chr_name {1} chr_start 1 chr_end {2} chr_strand \"+\" chr_runlist \"1-{2}\"\n\n redis-cli ZADD ctg-start:{1} 1 ctg:{1}:1\n\n redis-cli ZADD ctg-end:{1} {2} ctg:{1}:1\n\n '\n\n\n\n# find a contig contains 1000\n\nredis-cli --raw ZRANGEBYSCORE ctg-start:I 0 1000\n\nredis-cli --raw ZRANGEBYSCORE ctg-end:I 1000 +inf\n\n\n\nredis-cli --raw <<EOF\n\nMULTI\n\nZRANGESTORE tmp:start:I ctg-start:I 0 1000 BYSCORE\n\nZRANGESTORE tmp:end:I ctg-end:I 1000 +inf BYSCORE\n\nSET comment \"ZINTERSTORE tmp:ctg:I 2 tmp:start:I tmp:end:I AGGREGATE MIN\"\n\nZINTER 2 tmp:start:I tmp:end:I AGGREGATE MIN\n\nDEL tmp:start:I tmp:end:I\n\nEXEC\n\nEOF\n\n\n\nfaops filter -l 0 tests/S288c/genome.fa.gz stdout |\n\n paste - - |\n\n sed 's/^>//' |\n\n parallel -k -r --col-sep '\\t' '\n\n redis-cli HSET ctg:{1}:1 seq {2}\n\n '\n\n#redis-cli --raw HSTRLEN ctg:I:1 seq\n\n#redis-cli --raw scan 0 match ctg:I:* type hash\n\n\n\n# dump DB to redis-server start dir as dump.rdb\n\nredis-cli SAVE\n\n\n\nps -e | grep redis-server\n\n\n\n```\n\n\n\n## `gen`\n\n\n\n```shell script\n\n# start redis-server\n\nredis-server --appendonly no --dir tests/S288c/\n\n\n\n# create garr.env\n\ngarr env\n\n\n\n# check DB\n\ngarr status test\n\n\n\n# drop DB\n\ngarr status drop\n\n\n", "file_path": "results/example.md", "rank": 61, "score": 39319.6326564387 }, { "content": "## Benchmarks\n\n\n\n```shell script\n\nredis-server --appendonly no --dir ~/data/garr/Atha/\n\n\n\ncd ~/data/garr/Atha/\n\n\n\ngarr env\n\n\n\nhyperfine --warmup 1 --export-markdown garr.md.tmp \\\n\n '\n\n garr status drop;\n\n garr gen genome/genome.fa.gz --piece 500000;\n\n ' \\\n\n '\n\n garr status drop;\n\n garr gen genome/genome.fa.gz --piece 500000;\n\n garr pos features/T-DNA.CSHL.pos.txt;\n\n ' \\\n\n '\n\n garr status drop;\n\n garr gen genome/genome.fa.gz --piece 500000;\n\n garr range features/T-DNA.CSHL.pos.txt --tag CSHL;\n\n ' \\\n\n '\n\n garr status drop;\n\n garr gen genome/genome.fa.gz --piece 500000;\n\n garr sliding --size 100 --step 20 --lag 50 |\n\n tsv-filter -H --ne signal:0 > /dev/null;\n\n '\n\n\n\ncat garr.md.tmp\n\n\n\n```\n\n\n\n| Command | Mean [ms] | Min [ms] | Max [ms] | Relative |\n\n|:----------------------|----------------:|---------:|---------:|-------------:|\n\n| `drop; gen;` | 813.8 ± 18.5 | 783.4 | 834.4 | 1.00 |\n\n| `drop; gen; pos;` | 8203.5 ± 166.7 | 8051.7 | 8475.7 | 10.08 ± 0.31 |\n\n| `drop; gen; range;` | 20045.7 ± 474.6 | 19218.6 | 21041.7 | 24.63 ± 0.81 |\n\n| `drop; gen; sliding;` | 7580.7 ± 72.6 | 7467.1 | 7705.8 | 9.31 ± 0.23 |\n\n\n\n## clickhouse\n\n\n\n* server\n\n\n\n```shell script\n\ncd ~/data/garr/Atha/\n\n\n\nmkdir -p clickhouse\n\ncd clickhouse\n\nclickhouse server\n\n\n\n```\n\n\n\n* load\n\n\n\n```shell script\n\ncd ~/data/garr/Atha/\n\n\n\nfor q in ctg rsw; do\n\n clickhouse client --query \"DROP TABLE IF EXISTS ${q}\"\n\n clickhouse client --query \"$(cat sqls/ddl/${q}.sql)\"\n\ndone\n\n\n\nfor q in ctg rsw; do\n\n echo ${q}\n\n cat tsvs/${q}.tsv |\n\n clickhouse client --query \"INSERT INTO ${q} FORMAT TSVWithNames\"\n\ndone\n\n\n\n```\n\n\n\n* queries\n\n\n\n```shell script\n\ncd ~/data/garr/Atha/\n\n\n\nmkdir -p stats\n\n\n", "file_path": "results/Atha.md", "rank": 62, "score": 39319.02702558995 }, { "content": "## T-DNA\n\n\n\n```shell script\n\nmkdir -p ~/data/garr/Atha/features/\n\ncd ~/data/garr/Atha/features/\n\n\n\nfor name in CSHL FLAG MX RATM; do\n\n aria2c -j 4 -x 4 -s 2 --file-allocation=none -c \\\n\n http://natural.salk.edu/database/tdnaexpress/T-DNA.${name}\n\ndone\n\n\n\n# Convert to positions\n\nfor name in CSHL FLAG MX RATM; do\n\n cat T-DNA.${name} |\n\n perl -nla -e '\n\n @F >= 2 or next;\n\n next unless $F[1];\n\n\n\n my ( $chr, $pos ) = split /:/, $F[1];\n\n $chr =~ s/chr0?//i;\n\n $pos =~ s/^0+//;\n\n next unless $chr =~ /^\\d+$/;\n\n\n\n print \"$chr:$pos\";\n\n ' \\\n\n > T-DNA.${name}.pos.txt;\n\ndone\n\n\n\n```\n\n\n\n## `garr`\n\n\n\n### Contigs\n\n\n\n```shell script\n\n# start redis-server\n\nredis-server --appendonly no --dir ~/data/garr/Atha/\n\n\n\ncd ~/data/garr/Atha/\n\n\n\ngarr env --all\n\n\n\ngarr status drop\n\n\n\ngarr gen genome/genome.fa.gz --piece 500000\n\n\n\n# redis dumps\n\nmkdir -p ~/data/garr/Atha/dumps/\n\n\n\nwhile true; do\n\n garr status dump\n\n if [ $? -eq 0 ]; then\n\n cp dump.rdb dumps/ctg.dump.rdb\n\n break\n\n fi\n\n sleep 5\n\ndone\n\n\n\n# tsv exports\n\nmkdir -p tsvs\n\n\n\ngarr tsv -s 'ctg:*' -f length | head\n\n\n\ngarr tsv -s 'ctg:*' |\n\n keep-header -- tsv-sort -k2,2 -k3,3n -k4,4n \\\n\n > tsvs/ctg.tsv\n\n\n\ncat tsvs/ctg.tsv |\n\n sed '1d' |\n\n cut -f 1 \\\n\n > ctg.lst\n\n\n\n# positions\n\nparallel -j 4 -k --line-buffer '\n\n echo {}\n\n garr pos features/T-DNA.{}.pos.txt\n\n ' ::: CSHL FLAG MX RATM\n\n\n\ngarr tsv -s 'pos:*' |\n\n keep-header -- tsv-sort -k2,2 -k3,3n -k4,4n \\\n\n > tsvs/pos.tsv\n\n\n\n# dumps\n\nwhile true; do\n\n garr status dump\n\n if [ $? -eq 0 ]; then\n\n mkdir -p dumps\n\n cp dump.rdb dumps/pos.dump.rdb\n\n break\n\n fi\n\n sleep 5\n\ndone\n\n\n\n# stop the server\n\ngarr status stop\n\n\n\nsudo /etc/init.d/clickhouse-server start\n\n\n\n```\n\n\n\n### Ranges and rsw\n\n\n\nBenchmarks keydb against redis\n\n\n\n```shell script\n\ncd ~/data/garr/Atha/\n\n\n\nrm ./dump.rdb\n\n\n\nredis-server --appendonly no --dir ~/data/garr/Atha/\n\n#keydb-server --appendonly no --dir ~/data/garr/Atha/\n", "file_path": "results/Atha.md", "rank": 63, "score": 39318.517770291604 }, { "content": "# Atha\n\n\n\n## genome\n\n\n\n```shell script\n\nmkdir -p ~/data/garr/Atha/genome\n\ncd ~/data/garr/Atha/genome\n\n\n\n# download\n\naria2c -j 4 -x 4 -s 2 -c --file-allocation=none \\\n\n ftp://ftp.ensemblgenomes.org/pub/release-45/plants/fasta/arabidopsis_thaliana/dna/Arabidopsis_thaliana.TAIR10.dna_sm.toplevel.fa.gz\n\n\n\naria2c -j 4 -x 4 -s 2 -c --file-allocation=none \\\n\n ftp://ftp.ensemblgenomes.org/pub/release-45/plants/gff3/arabidopsis_thaliana/Arabidopsis_thaliana.TAIR10.45.gff3.gz\n\n\n\n# chromosomes\n\ngzip -d -c *dna_sm.toplevel* > toplevel.fa\n\n\n\nfaops count toplevel.fa |\n\n perl -nla -e '\n\n next if $F[0] eq 'total';\n\n print $F[0] if $F[1] > 50000;\n\n print $F[0] if $F[1] > 5000 and $F[6]/$F[1] < 0.05;\n\n ' |\n\n uniq > listFile\n\nfaops some toplevel.fa listFile stdout |\n\n faops filter -N stdin stdout |\n\n faops split-name stdin .\n\nrm toplevel.fa listFile\n\n\n\n# .fa.gz\n\ncat {1..5}.fa Mt.fa Pt.fa |\n\n gzip -9 \\\n\n > genome.fa.gz\n\nfaops size genome.fa.gz > chr.sizes\n\n\n\n# annotaions\n\ngzip -dcf Arabidopsis_thaliana.TAIR10.45.gff3.gz |\n\n grep -v '^#' |\n\n cut -f 1 |\n\n sort | uniq -c\n\n# 213207 1\n\n# 122450 2\n\n# 152568 3\n\n# 121665 4\n\n# 180531 5\n\n# 615 Mt\n\n# 528 Pt\n\n\n\ngzip -dcf Arabidopsis_thaliana.TAIR10.45.gff3.gz |\n\n grep -v '^#' |\n\n cut -f 3 |\n\n sort | uniq -c\n\n# 286067 CDS\n\n# 7 chromosome\n\n# 313952 exon\n\n# 56384 five_prime_UTR\n\n# 27655 gene\n\n# 3879 lnc_RNA\n\n# 48359 mRNA\n\n# 325 miRNA\n\n# 377 ncRNA\n\n# 5178 ncRNA_gene\n\n# 15 rRNA\n\n# 82 snRNA\n\n# 287 snoRNA\n\n# 689 tRNA\n\n# 48308 three_prime_UTR\n\n\n\nspanr gff Arabidopsis_thaliana.TAIR10.45.gff3.gz --tag CDS -o cds.yml\n\n\n\nfaops masked *.fa |\n\n spanr cover stdin -o repeats.yml\n\n\n\nspanr merge repeats.yml cds.yml -o anno.yml\n\nrm repeats.yml cds.yml\n\n\n\nspanr stat chr.sizes anno.yml --all\n\n#key,chrLength,size,coverage\n\n#cds,119667750,33775569,0.2822\n\n#repeats,119667750,28237829,0.2360\n\n\n\n```\n\n\n", "file_path": "results/Atha.md", "rank": 64, "score": 39318.490860109465 }, { "content": "# keydb is as fast/slow as redis\n\n\n\ngarr env\n\n\n\ngarr status drop\n\n\n\ntime garr gen genome/genome.fa.gz --piece 500000\n\n#real 0m1.520s\n\n#user 0m0.582s\n\n#sys 0m0.407s\n\n\n\ntime parallel -j 4 -k --line-buffer '\n\n echo {}\n\n garr range features/T-DNA.{}.pos.txt --tag {}\n\n ' ::: CSHL FLAG MX RATM\n\n# redis\n\n# RATM\n\n#real 0m14.055s\n\n#user 0m1.819s\n\n#sys 0m6.357s\n\n# 4 files\n\n#real 0m40.654s\n\n#user 0m11.503s\n\n#sys 0m21.387s\n\n\n\n# keydb\n\n# RATM\n\n#real 0m14.228s\n\n#user 0m1.792s\n\n#sys 0m6.314s\n\n# 4 files\n\n#real 0m42.186s\n\n#user 0m11.481s\n\n#sys 0m21.391s\n\n\n\ngarr tsv -s \"range:*\" |\n\n keep-header -- tsv-sort -k2,2 -k3,3n -k4,4n \\\n\n > tsvs/range.tsv\n\n\n\nwhile true; do\n\n garr status dump\n\n if [ $? -eq 0 ]; then\n\n mkdir -p dumps\n\n cp dump.rdb dumps/range.dump.rdb\n\n break\n\n fi\n\n sleep 5\n\ndone\n\n\n\n# rsw\n\ntime cat ctg.lst |\n\n parallel -j 4 -k --line-buffer '\n\n garr rsw --ctg {}\n\n ' |\n\n tsv-uniq |\n\n keep-header -- tsv-sort -k2,2 -k3,3n -k4,4n \\\n\n > tsvs/rsw.tsv\n\n# CSHL\n\n# -j 4\n\n#real 7m43.384s\n\n#user 24m58.916s\n\n#sys 3m42.415s\n\n# -j 2\n\n#real 13m38.805s\n\n#user 21m56.417s\n\n#sys 4m34.154s\n\n\n\ngarr status stop\n\n\n\n```\n\n\n", "file_path": "results/Atha.md", "rank": 65, "score": 39318.035493048395 }, { "content": "# generate DB\n\ngarr gen tests/S288c/genome.fa.gz --piece 100000\n\n\n\ngarr tsv -s 'ctg:*' > tests/S288c/ctg.tsv\n\n\n\n#cargo run stat tests/S288c/ctg.tsv -s templates/ctg-1.sql\n\n#cargo run stat tests/S288c/ctg.tsv -s templates/ctg-2.sql\n\n\n\ntextql -dlm=tab -header -output-dlm=tab -output-header \\\n\n -sql \"$(cat templates/ctg-1.sql)\" \\\n\n tests/S288c/ctg.tsv\n\n\n\n# add ranges\n\ngarr range tests/S288c/spo11_hot.pos.txt\n\n\n\ntime garr rsw > /dev/null\n\n# w/o gc_stat()\n\n# get_gc_content()\n\n#real 0m1.444s\n\n#user 0m0.174s\n\n#sys 0m0.838s\n\n\n\n# ctg_gc_content()\n\n#real 0m0.774s\n\n#user 0m0.406s\n\n#sys 0m0.289s\n\n\n\n# w/ gc_stat()\n\n# get_gc_content()\n\n#real 0m3.476s\n\n#user 0m0.436s\n\n#sys 0m2.037s\n\n\n\n# ctg_gc_content()\n\n#real 0m2.349s\n\n#user 0m1.041s\n\n#sys 0m1.102s\n\n\n\n# add pos\n\ngarr pos tests/S288c/spo11_hot.pos.txt tests/S288c/spo11_hot.pos.txt\n\n\n\n# dump DB to redis-server start dir as dump.rdb\n\ngarr status dump\n\n\n\n```\n\n\n\n## GC-wave\n\n\n\n```shell script\n\nredis-server --appendonly no --dir tests/S288c/\n\n\n\ngarr status drop\n\n\n\ngarr gen tests/S288c/genome.fa.gz --piece 500000\n\n\n\ngarr sliding \\\n\n --ctg 'ctg:I:' \\\n\n --size 100 --step 1 \\\n\n --lag 1000 \\\n\n --threshold 3.0 \\\n\n --influence 1.0 \\\n\n -o tests/S288c/I.gc.tsv\n\n\n\nRscript templates/peak.tera.R \\\n\n --lag 1000 \\\n\n --threshold 3.0 \\\n\n --influence 1.0 \\\n\n --infile tests/S288c/I.gc.tsv \\\n\n --outfile tests/S288c/I.R.tsv\n\n\n\ntsv-summarize tests/S288c/I.gc.tsv \\\n\n -H --group-by signal --count\n\n#signal count\n\n#0 227242\n\n#-1 2124\n\n#1 753\n\n\n\ntsv-summarize tests/S288c/I.R.tsv \\\n\n -H --group-by signal --count\n\n#signal count\n\n#0 227317\n\n#-1 2079\n\n#1 723\n\n\n\ntsv-filter tests/S288c/I.gc.tsv -H --ne signal:0 |\n\n cut -f 1 |\n\n linkr merge -c 0.8 stdin -o tests/S288c/I.replace.tsv\n\n\n\ntsv-filter tests/S288c/I.gc.tsv -H --ne signal:0 |\n\n ovlpr replace stdin tests/S288c/I.replace.tsv |\n\n tsv-uniq -H -f 1 \\\n\n > tests/S288c/I.peaks.tsv\n\n\n\ntsv-summarize tests/S288c/I.peaks.tsv \\\n\n -H --group-by signal --count\n\n#signal count\n\n#-1 94\n", "file_path": "results/example.md", "rank": 66, "score": 39317.45221220618 }, { "content": "### GC-wave\n\n\n\nRestores from ctg.dump.rdb\n\n\n\n```shell script\n\ncd ~/data/garr/Atha/\n\n\n\ncp dumps/ctg.dump.rdb ./dump.rdb\n\n\n\nredis-server --appendonly no --dir ~/data/garr/Atha/ &\n\n\n\ngarr env\n\n\n\ntime cat ctg.lst |\n\n parallel -j 4 -k --line-buffer '\n\n garr sliding \\\n\n --ctg {} \\\n\n --size 100 --step 1 \\\n\n --lag 1000 \\\n\n --threshold 3.0 \\\n\n --influence 1.0 \\\n\n -o stdout |\n\n tsv-filter -H --ne signal:0 \\\n\n > {.}.gc.tsv\n\n\n\n cat {.}.gc.tsv |\n\n cut -f 1 |\n\n linkr merge -c 0.8 stdin -o {.}.replace.tsv\n\n\n\n cat {.}.gc.tsv |\n\n ovlpr replace stdin {.}.replace.tsv |\n\n tsv-uniq -H -f 1 \\\n\n > tsvs/{.}.peak.tsv\n\n\n\n tsv-summarize tsvs/{.}.peak.tsv \\\n\n -H --group-by signal --count\n\n\n\n rm {.}.gc.tsv {.}.replace.tsv\n\n '\n\n#real 5m58.731s\n\n#user 23m47.703s\n\n#sys 0m16.114s\n\n\n\n# Don't need to be sorted\n\ntsv-append -f <(cat ctg.lst | sed 's/$/.peak.tsv/') -H \\\n\n > tsvs/peak.tsv\n\nrm tsvs/ctg:*.peak.tsv\n\n\n\ntsv-summarize tsvs/peak.tsv \\\n\n -H --group-by signal --count\n\n#signal count\n\n#1 32211\n\n#-1 26821\n\n\n\ntime garr wave tsvs/peak.tsv\n\n#real 4m27.902s\n\n#user 0m26.255s\n\n#sys 2m31.036s\n\n\n\ngarr tsv -s \"peak:*\" |\n\n keep-header -- tsv-sort -k2,2 -k3,3n -k4,4n \\\n\n > tsvs/wave.tsv\n\n\n\ncat tsvs/wave.tsv |\n\n tsv-summarize -H --count\n\n# 59032\n\n\n\ncat tsvs/wave.tsv |\n\n tsv-filter -H --gt left_wave_length:0 |\n\n tsv-summarize -H --mean left_wave_length\n\n\n\ncat tsvs/wave.tsv |\n\n tsv-filter -H --gt right_wave_length:0 |\n\n tsv-summarize -H --mean right_wave_length\n\n\n\ntsv-filter tsvs/wave.tsv -H --or \\\n\n --le left_wave_length:0 --le right_wave_length:0 |\n\n tsv-summarize -H --count\n\n# 12927\n\n\n\n```\n\n\n", "file_path": "results/Atha.md", "rank": 67, "score": 39316.79655594287 }, { "content": "#1 61\n\n\n\ngarr wave tests/S288c/I.peaks.tsv\n\n\n\n```\n", "file_path": "results/example.md", "rank": 68, "score": 39315.999222669525 }, { "content": "# summary\n\nARRAY=(\n\n 'ctg::length'\n\n 'rsw::gc_content'\n\n)\n\n\n\nfor item in \"${ARRAY[@]}\"; do\n\n echo ${item} 1>&2\n\n TABLE=\"${item%%::*}\"\n\n COLUMN=\"${item##*::}\"\n\n\n\n clickhouse client --query \"$(\n\n cat sqls/summary.sql | sed \"s/_TABLE_/${TABLE}/\" | sed \"s/_COLUMN_/${COLUMN}/\"\n\n )\"\n\ndone |\n\n tsv-uniq \\\n\n > stats/summary.tsv\n\n\n\nfor t in rsw; do\n\n echo ${t} 1>&2\n\n clickhouse client --query \"$(cat sqls/summary-type.sql | sed \"s/_TABLE_/${t}/\")\"\n\ndone |\n\n tsv-uniq \\\n\n > stats/summary-type.tsv\n\n\n\n# rsw\n\nfor q in rsw-distance rsw-distance-tag; do\n\n echo ${q}\n\n clickhouse client --query \"$(cat sqls/${q}.sql)\" > stats/${q}.tsv\n\ndone\n\n\n\n```\n\n\n\n## plots\n\n\n\n* rsw-distance-tag\n\n\n\n```shell script\n\ncd ~/data/garr/Atha/\n\n\n\nmkdir -p plots\n\n\n\ncat stats/rsw-distance-tag.tsv |\n\n cut -f 1 |\n\n grep -v \"^tag$\" |\n\n tsv-uniq \\\n\n > plots/tag.lst\n\n\n\nfor tag in $(cat plots/tag.lst); do\n\n echo ${tag}\n\n base=\"rsw-distance-tag.${tag}\"\n\n\n\n cat stats/rsw-distance-tag.tsv |\n\n tsv-filter -H --str-eq tag:${tag} |\n\n tsv-select -H --exclude tag \\\n\n > plots/${base}.tsv\n\n\n\n for y in {2..6}; do\n\n echo ${y}\n\n Rscript plot_xy.R --infile plots/${base}.tsv --ycol ${y} --yacc 0.002 --outfile plots/${base}.${y}.pdf\n\n done\n\n\n\n gs -q -dNOPAUSE -dBATCH -sDEVICE=pdfwrite -sOutputFile=plots/${base}.pdf \\\n\n $( for y in {2..6}; do echo plots/${base}.${y}.pdf; done )\n\n\n\n for y in {2..6}; do\n\n rm plots/${base}.${y}.pdf\n\n done\n\n\n\n pdfjam plots/${base}.pdf --nup 5x1 --suffix nup -o plots\n\n\n\n pdfcrop plots/${base}-nup.pdf\n\n mv plots/${base}-nup-crop.pdf plots/${base}-nup.pdf\n\n\n\n rm plots/${base}.tsv\n\ndone\n\n\n\n```\n\n\n", "file_path": "results/Atha.md", "rank": 69, "score": 39315.48501661387 }, { "content": "fn cli() {\n\n match Command::new(\"redis-cli\").arg(\"--version\").output() {\n\n Ok(o) => println!(\"Find `{:#?}` in $PATH\", String::from_utf8(o.stdout)),\n\n Err(_) => println!(\"`redis-cli` was not found! Check your $PATH!\"),\n\n }\n\n}\n\n\n", "file_path": "src/cmd/status.rs", "rank": 70, "score": 34521.226186346146 }, { "content": "fn info() {\n\n let mut conn = connect();\n\n let info: redis::InfoDict = redis::cmd(\"INFO\")\n\n .query(&mut conn)\n\n .expect(\"Failed to execute INFO\");\n\n\n\n let mut output: BTreeMap<&str, String> = BTreeMap::new();\n\n for key in &[\n\n \"redis_version\",\n\n \"os\",\n\n \"used_memory_human\",\n\n \"total_system_memory_human\",\n\n \"maxmemory_human\",\n\n \"total_connections_received\",\n\n \"total_commands_processed\",\n\n ] {\n\n output.insert(key, info.get(key).unwrap());\n\n }\n\n\n\n eprintln!(\"output = {:#?}\", output);\n\n}\n\n\n", "file_path": "src/cmd/status.rs", "rank": 71, "score": 34521.226186346146 }, { "content": "fn set() {\n\n let mut conn = connect();\n\n println!(\"******* Running SET commands *******\");\n\n\n\n let set_name = \"users\";\n\n\n\n let _: () = conn\n\n .sadd(set_name, \"user1\")\n\n .expect(\"Failed to execute SADD for 'users'\");\n\n let _: () = conn\n\n .sadd(set_name, \"user2\")\n\n .expect(\"Failed to execute SADD for 'users'\");\n\n\n\n let ismember: bool = redis::cmd(\"SISMEMBER\")\n\n .arg(set_name)\n\n .arg(\"user1\")\n\n .query(&mut conn)\n\n .expect(\"Failed to execute SISMEMBER for 'users'\");\n\n println!(\"does user1 exist in the set? {}\", ismember); //true\n\n\n\n let users: Vec<String> = conn.smembers(set_name).expect(\"Failed to execute SMEMBERS\");\n\n println!(\"listing users in set\"); //true\n\n\n\n for user in users {\n\n println!(\"user: {}\", user)\n\n }\n\n}\n\n\n", "file_path": "src/cmd/status.rs", "rank": 72, "score": 34521.226186346146 }, { "content": "fn drop() {\n\n let mut conn = connect();\n\n let output: String = redis::cmd(\"FLUSHDB\")\n\n .query(&mut conn)\n\n .expect(\"Failed to execute FLUSHDB\");\n\n println!(\"{}\", output);\n\n}\n\n\n", "file_path": "src/cmd/status.rs", "rank": 73, "score": 34521.226186346146 }, { "content": "fn basics() {\n\n let mut conn = connect();\n\n println!(\"******* Running SET, GET, INCR commands *******\");\n\n\n\n let _: () = redis::cmd(\"SET\")\n\n .arg(\"foo\")\n\n .arg(\"bar\")\n\n .query(&mut conn)\n\n .expect(\"Failed to execute SET for 'foo'\");\n\n\n\n let bar: String = redis::cmd(\"GET\")\n\n .arg(\"foo\")\n\n .query(&mut conn)\n\n .expect(\"Failed to execute GET for 'foo'\");\n\n println!(\"value for 'foo' = {}\", bar);\n\n\n\n //INCR and GET using high-level commands\n\n let _: () = conn\n\n .incr(\"counter\", 2)\n\n .expect(\"Failed to execute INCR for 'counter'\");\n\n\n\n let val: i32 = conn\n\n .get(\"counter\")\n\n .expect(\"Failed to execute GET for 'counter'\");\n\n\n\n println!(\"counter = {}\", val);\n\n}\n\n\n", "file_path": "src/cmd/status.rs", "rank": 74, "score": 34521.226186346146 }, { "content": "fn dump() {\n\n let mut conn = connect();\n\n let output: String = redis::cmd(\"SAVE\")\n\n .query(&mut conn)\n\n .expect(\"Failed to execute SAVE\");\n\n println!(\"{}\", output);\n\n}\n\n\n", "file_path": "src/cmd/status.rs", "rank": 75, "score": 34521.226186346146 }, { "content": "fn hash() {\n\n let mut conn = connect();\n\n\n\n println!(\"******* Running HASH commands *******\");\n\n\n\n let mut driver: BTreeMap<String, String> = BTreeMap::new();\n\n let prefix = \"redis-driver\";\n\n\n\n driver.insert(String::from(\"name\"), String::from(\"redis-rs\"));\n\n driver.insert(String::from(\"version\"), String::from(\"0.20.0\"));\n\n driver.insert(\n\n String::from(\"repo\"),\n\n String::from(\"https://github.com/mitsuhiko/redis-rs\"),\n\n );\n\n\n\n let _: () = redis::cmd(\"HSET\")\n\n .arg(format!(\"{}:{}\", prefix, \"rust\"))\n\n .arg(driver)\n\n .query(&mut conn)\n\n .expect(\"Failed to execute HSET\");\n", "file_path": "src/cmd/status.rs", "rank": 76, "score": 34521.226186346146 }, { "content": "fn list() {\n\n let mut conn = connect();\n\n println!(\"******* Running LIST commands *******\");\n\n\n\n let list_name = \"items\";\n\n\n\n let _: () = redis::cmd(\"LPUSH\")\n\n .arg(list_name)\n\n .arg(\"item-1\")\n\n .query(&mut conn)\n\n .expect(\"Failed to execute LPUSH for 'items'\");\n\n\n\n let item: String = conn\n\n .lpop(list_name)\n\n .expect(\"Failed to execute LPOP for 'items'\");\n\n println!(\"first item: {}\", item);\n\n\n\n let _: () = conn.rpush(list_name, \"item-2\").expect(\"RPUSH failed\");\n\n let _: () = conn.rpush(list_name, \"item-3\").expect(\"RPUSH failed\");\n\n\n", "file_path": "src/cmd/status.rs", "rank": 77, "score": 34521.226186346146 }, { "content": "fn stop() {\n\n let mut conn = connect();\n\n\n\n let output = redis::cmd(\"SHUTDOWN\")\n\n .arg(\"SAVE\")\n\n .query::<()>(&mut conn)\n\n .unwrap_err();\n\n eprintln!(\"output = {:#?}\", output);\n\n eprintln!(\"Executed SHUTDOWN SAVE\");\n\n}\n\n\n", "file_path": "src/cmd/status.rs", "rank": 78, "score": 34521.226186346146 }, { "content": "fn sorted_set() {\n\n let mut conn = connect();\n\n println!(\"******* Running SORTED SET commands *******\");\n\n\n\n let sorted_set = \"leaderboard\";\n\n\n\n let _: () = redis::cmd(\"ZADD\")\n\n .arg(sorted_set)\n\n .arg(rand::thread_rng().gen_range(1..10))\n\n .arg(\"player-1\")\n\n .query(&mut conn)\n\n .expect(\"Failed to execute ZADD for 'leaderboard'\");\n\n\n\n //add many players\n\n for num in 2..=5 {\n\n let _: () = conn\n\n .zadd(\n\n sorted_set,\n\n String::from(\"player-\") + &num.to_string(),\n\n rand::thread_rng().gen_range(1..10),\n", "file_path": "src/cmd/status.rs", "rank": 79, "score": 33370.82427026182 }, { "content": "#[test]\n\nfn test_gc_stat() {\n\n let tests = vec![\n\n (vec![0.5, 0.5], (0.5, 0., 0., 0.)),\n\n (\n\n vec![0.4, 0.5, 0.5, 0.6],\n\n (0.5, 0.08164966, 0.16329932, 6.123724),\n\n ),\n\n ];\n\n for (gcs, exp) in tests {\n\n let (mean, stddev, cv, snr) = garr::gc_stat(&gcs);\n\n assert_relative_eq!(mean, exp.0);\n\n assert_relative_eq!(stddev, exp.1);\n\n assert_relative_eq!(cv, exp.2);\n\n assert_relative_eq!(snr, exp.3);\n\n }\n\n}\n", "file_path": "tests/cli.rs", "rank": 80, "score": 33370.82427026182 }, { "content": "fn pipe_atomic() {\n\n let mut conn = connect();\n\n println!(\"******* Running MULTI EXEC commands *******\");\n\n\n\n redis::pipe()\n\n .cmd(\"ZADD\")\n\n .arg(\"ctg-s:I\")\n\n .arg(1)\n\n .arg(\"ctg:I:1\")\n\n .ignore()\n\n .cmd(\"ZADD\")\n\n .arg(\"ctg-s:I\")\n\n .arg(100001)\n\n .arg(\"ctg:I:2\")\n\n .ignore()\n\n .cmd(\"ZADD\")\n\n .arg(\"ctg-e:I\")\n\n .arg(100000)\n\n .arg(\"ctg:I:1\")\n\n .ignore()\n", "file_path": "src/cmd/status.rs", "rank": 81, "score": 33370.82427026182 }, { "content": "#[test]\n\nfn test_polymer() {\n\n let tests = vec![\n\n (\n\n 37.0,\n\n 1.0,\n\n \"TAACAAGCAATGAGATAGAGAAAGAAATATATCCA\".to_string(),\n\n Some(-39.2702),\n\n ),\n\n (\n\n 30.0,\n\n 0.1,\n\n \"TAACAAGCAATGAGATAGAGAAAGAAATATATCCA\".to_string(),\n\n Some(-35.6605),\n\n ),\n\n (37.0, 1.0, \"GAATTC\".to_string(), Some(-1.1399)),\n\n (37.0, 1.0, \"NAATTC\".to_string(), None),\n\n ];\n\n for (temp, salt, seq, expected) in tests {\n\n let dg = DeltaG::from(temp, salt);\n\n match expected {\n\n Some(res) => assert!((dg.polymer(&seq).unwrap() - res).abs() < 0.001),\n\n None => assert!(dg.polymer(&seq).is_none()),\n\n }\n\n }\n\n}\n", "file_path": "src/libs/delta_g.rs", "rank": 82, "score": 33370.82427026182 }, { "content": "#[test]\n\nfn thresholding_sample() {\n\n let input: Vec<f32> = vec![\n\n 1.0, 1.0, 1.1, 1.0, 0.9, 1.0, 1.0, 1.1, 1.0, 0.9, //\n\n 1.0, 1.1, 1.0, 1.0, 0.9, 1.0, 1.0, 1.1, 1.0, 1.0, //\n\n 1.0, 1.0, 1.1, 0.9, 1.0, 1.1, 1.0, 1.0, 0.9, 1.0, //\n\n 1.1, 1.0, 1.0, 1.1, 1.0, 0.8, 0.9, 1.0, 1.2, 0.9, //\n\n 1.0, 1.0, 1.1, 1.2, 1.0, 1.5, 1.0, 3.0, 2.0, 5.0, //\n\n 3.0, 2.0, 1.0, 1.0, 1.0, 0.9, 1.0, 1.0, 3.0, 2.6, //\n\n 4.0, 3.0, 3.2, 2.0, 1.0, 1.0, 0.8, 4.0, 4.0, 2.0, //\n\n 2.5, 1.0, 1.0, 1.0,\n\n ];\n\n let exp = vec![\n\n 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, //\n\n 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, //\n\n 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, //\n\n 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, //\n\n 0, 0, 0, 0, 0, 1, 0, 1, 1, 1, //\n\n 1, 1, 0, 0, 0, 0, 0, 0, 1, 1, //\n\n 1, 1, 1, 1, 0, 0, 0, 1, 1, 1, //\n\n 1, 0, 0, 0,\n\n ];\n\n assert_eq!(thresholding_algo(&input, 30, 5., 0.), exp);\n\n}\n", "file_path": "src/libs/stat.rs", "rank": 83, "score": 33370.82427026182 }, { "content": "#[test]\n\nfn test_center_resize() {\n\n // parent, runlist, resize, exp\n\n let tests = vec![\n\n (\"1-500\", \"201\", 100, \"152-250\"),\n\n (\"1-500\", \"200\", 100, \"151-249\"),\n\n (\"1-500\", \"200-201\", 100, \"151-250\"),\n\n (\"1-500\", \"199-201\", 100, \"150-249\"),\n\n (\"1-500\", \"199-202\", 100, \"151-250\"),\n\n (\"1-500\", \"100-301\", 100, \"151-250\"),\n\n (\"1-500\", \"1\", 100, \"1-50\"),\n\n (\"1-500\", \"500\", 100, \"451-500\"),\n\n (\"1001-1500\", \"1200-1201\", 100, \"1151-1250\"),\n\n ];\n\n\n\n for (parent, runlist, resize, exp) in tests {\n\n let intspan = IntSpan::from(runlist);\n\n let resized = center_resize(&IntSpan::from(parent), &intspan, resize);\n\n\n\n assert_eq!(resized.to_string(), exp);\n\n }\n\n}\n", "file_path": "src/libs/window.rs", "rank": 84, "score": 32319.790132533053 }, { "content": "#[test]\n\nfn test_center_sw() {\n\n // parent, start, end, exp\n\n let tests = vec![\n\n (\"1-9999\", 500, 500, (\"451-549\", \"M\", 0, 3)),\n\n (\"1-9999\", 500, 800, (\"600-699\", \"M\", 0, 3)),\n\n (\"1-9999\", 101, 101, (\"52-150\", \"M\", 0, 2)),\n\n (\"10001-19999\", 10101, 10101, (\"10052-10150\", \"M\", 0, 2)),\n\n ];\n\n\n\n for (parent, start, end, exp) in tests {\n\n let windows = center_sw(&IntSpan::from(parent), start, end, 100, 1);\n\n\n\n assert_eq!(windows[0].0.to_string(), exp.0);\n\n assert_eq!(windows[0].1, exp.1);\n\n assert_eq!(windows[0].2, exp.2);\n\n assert_eq!(windows.len(), exp.3);\n\n }\n\n}\n\n\n", "file_path": "src/libs/window.rs", "rank": 85, "score": 32319.790132533053 }, { "content": "fn ctg_schema() -> Schema {\n\n Schema::new(vec![\n\n Field::new(\"ID\", DataType::Utf8, true),\n\n Field::new(\"chr_name\", DataType::Utf8, true),\n\n Field::new(\"chr_start\", DataType::Int32, true),\n\n Field::new(\"chr_end\", DataType::Int32, true),\n\n Field::new(\"chr_strand\", DataType::Utf8, true),\n\n Field::new(\"length\", DataType::Int32, true),\n\n ])\n\n}\n", "file_path": "src/cmd/stat.rs", "rank": 86, "score": 31674.776093334083 }, { "content": "extern crate clap;\n\nuse clap::*;\n\n\n\nmod cmd;\n\n\n", "file_path": "src/garr.rs", "rank": 87, "score": 31008.252505952092 }, { "content": " (\"status\", Some(sub_matches)) => cmd::status::execute(sub_matches),\n\n (\"gen\", Some(sub_matches)) => cmd::gen::execute(sub_matches),\n\n (\"pos\", Some(sub_matches)) => cmd::pos::execute(sub_matches),\n\n (\"range\", Some(sub_matches)) => cmd::range::execute(sub_matches),\n\n (\"rsw\", Some(sub_matches)) => cmd::rsw::execute(sub_matches),\n\n (\"sliding\", Some(sub_matches)) => cmd::sliding::execute(sub_matches),\n\n // (\"stat\", Some(sub_matches)) => cmd::stat::execute(sub_matches),\n\n (\"tsv\", Some(sub_matches)) => cmd::tsv::execute(sub_matches),\n\n (\"wave\", Some(sub_matches)) => cmd::wave::execute(sub_matches),\n\n (_, _) => unreachable!(),\n\n }?;\n\n\n\n Ok(())\n\n}\n\n\n\n// TODO: annotations - coding and repeats\n", "file_path": "src/garr.rs", "rank": 88, "score": 31006.85901308136 }, { "content": "SELECT '_TABLE_' TABLE,\n\n '_COLUMN_' COLUMN,\n\n count(`ID`) COUNT,\n\n round(avg(`_COLUMN_`), 4) AVG,\n\n round(stddevPop(`_COLUMN_`), 4) STDDEV,\n\n min(`_COLUMN_`) MIN,\n\n max(`_COLUMN_`) MAX,\n\n sum(`_COLUMN_`) SUM\n\nFROM _TABLE_\n\n FORMAT TSVWithNames\n", "file_path": "templates/dql/summary.tera.sql", "rank": 93, "score": 28367.985871038003 }, { "content": "SELECT `distance`,\n\n round(avg(gc_content), 4) AVG_gc_content,\n\n round(avg(gc_mean), 4) AVG_gc_mean,\n\n round(avg(gc_stddev), 4) AVG_gc_stddev,\n\n round(avg(gc_cv), 4) AVG_gc_cv,\n\n round(avg(gc_snr), 4) AVG_gc_snr,\n\n count(ID) COUNT\n\nFROM rsw\n\nGROUP BY distance\n\nORDER BY distance\n\n FORMAT TSVWithNames\n", "file_path": "templates/dql/rsw-distance.tera.sql", "rank": 94, "score": 27087.520000796485 }, { "content": "SELECT '_TABLE_' TABLE,\n\n `type` TYPE,\n\n count(`ID`) COUNT,\n\n round(avg(chr_end - chr_start + 1), 2) AVG_length,\n\n sum(chr_end - chr_start + 1) SUM_length\n\nFROM _TABLE_\n\nGROUP BY `type`\n\nORDER BY `type`\n\n FORMAT TSVWithNames\n", "file_path": "templates/dql/summary-type.tera.sql", "rank": 95, "score": 27087.520000796485 }, { "content": "CREATE TABLE ctg\n\n(\n\n `ID` String,\n\n `chr_name` String,\n\n `chr_start` UInt32,\n\n `chr_end` UInt32,\n\n `chr_strand` String,\n\n `length` UInt32\n\n)\n\n ENGINE = MergeTree()\n\n PRIMARY KEY (`ID`)\n\n ORDER BY (`ID`, `chr_name`, `chr_start`, `chr_end`);\n", "file_path": "templates/ddl/ctg.tera.sql", "rank": 96, "score": 25917.656387911335 }, { "content": "CREATE TABLE rsw\n\n(\n\n `ID` String,\n\n `chr_name` String,\n\n `chr_start` UInt32,\n\n `chr_end` UInt32,\n\n `type` String,\n\n `distance` UInt32,\n\n `tag` String,\n\n `gc_content` Float32,\n\n `gc_mean` Float32,\n\n `gc_stddev` Float32,\n\n `gc_cv` Float32,\n\n `gc_snr` Float32\n\n)\n\n ENGINE = MergeTree()\n\n PRIMARY KEY (`ID`)\n\n ORDER BY (`ID`, `chr_name`, `chr_start`, `chr_end`);\n", "file_path": "templates/ddl/rsw.tera.sql", "rank": 97, "score": 25917.656387911335 }, { "content": "SELECT `tag`,\n\n `distance`,\n\n round(avg(gc_content), 4) AVG_gc_content,\n\n round(avg(gc_mean), 4) AVG_gc_mean,\n\n round(avg(gc_stddev), 4) AVG_gc_stddev,\n\n round(avg(gc_cv), 4) AVG_gc_cv,\n\n round(avg(gc_snr), 4) AVG_gc_snr,\n\n count(ID) COUNT\n\nFROM rsw\n\nGROUP BY tag, distance\n\nORDER BY tag, distance\n\n FORMAT TSVWithNames\n", "file_path": "templates/dql/rsw-distance-tag.tera.sql", "rank": 98, "score": 25917.656387911335 }, { "content": "fn init_delta_g(temp: f32, salt: f32) -> HashMap<String, f32> {\n\n // deltaH (kcal/mol)\n\n let delta_h: HashMap<String, f32> = [\n\n (\"AA\", -7.6),\n\n (\"TT\", -7.6),\n\n (\"AT\", -7.2),\n\n (\"TA\", -7.2),\n\n (\"CA\", -8.5),\n\n (\"TG\", -8.5),\n\n (\"GT\", -8.4),\n\n (\"AC\", -8.4),\n\n (\"CT\", -7.8),\n\n (\"AG\", -7.8),\n\n (\"GA\", -8.2),\n\n (\"TC\", -8.2),\n\n (\"CG\", -10.6),\n\n (\"GC\", -9.8),\n\n (\"GG\", -8.0),\n\n (\"CC\", -8.0),\n\n (\"iC\", 0.2),\n", "file_path": "src/libs/delta_g.rs", "rank": 99, "score": 23753.389300269977 } ]
Rust
cita-chain/types/src/receipt.rs
Pencil-Yao/cita
bcd00dc848fd2ca4b1e72d57f5f0e059bb2d3828
use super::Bytes; use std::str::FromStr; use crate::block_number::BlockNumber; use crate::errors::ReceiptError; use crate::log::{LocalizedLog, Log}; use cita_types::traits::LowerHex; use cita_types::{Address, Bloom as LogBloom, H256, U256}; use jsonrpc_types::rpc_types::Receipt as RpcReceipt; use libproto::executor::{Receipt as ProtoReceipt, ReceiptErrorWithOption, StateRoot}; use rlp::{Decodable, DecoderError, Encodable, RlpStream, UntrustedRlp}; #[derive(Serialize, Deserialize, Default, Debug, Clone, PartialEq, Eq)] pub struct Receipt { pub state_root: Option<H256>, pub quota_used: U256, pub log_bloom: LogBloom, pub logs: Vec<Log>, pub error: Option<ReceiptError>, pub account_nonce: U256, pub transaction_hash: H256, } impl Receipt { pub fn new( state_root: Option<H256>, quota_used: U256, logs: Vec<Log>, error: Option<ReceiptError>, account_nonce: U256, transaction_hash: H256, ) -> Receipt { Receipt { state_root, quota_used, log_bloom: logs.iter().fold(LogBloom::default(), |b, l| b | l.bloom()), logs, error, account_nonce, transaction_hash, } } pub fn protobuf(&self) -> ProtoReceipt { let mut receipt_proto = ProtoReceipt::new(); let mut state_root_option = StateRoot::new(); let mut receipt_error_with_option = ReceiptErrorWithOption::new(); if let Some(state_root) = self.state_root { state_root_option.set_state_root(state_root.to_vec()); receipt_proto.set_state_root(state_root_option); } if let Some(error) = self.error { receipt_error_with_option.set_error(error.protobuf()); receipt_proto.set_error(receipt_error_with_option); } receipt_proto.set_quota_used(self.quota_used.lower_hex()); receipt_proto.set_log_bloom(self.log_bloom.to_vec()); receipt_proto.logs = self .logs .clone() .into_iter() .map(|log_entry| log_entry.protobuf()) .collect(); receipt_proto.set_account_nonce(self.account_nonce.as_u64()); receipt_proto.set_transaction_hash(self.transaction_hash.to_vec()); receipt_proto } } impl From<ProtoReceipt> for Receipt { fn from(receipt: ProtoReceipt) -> Self { let state_root = if receipt.state_root.is_some() { Some(H256::from_slice( receipt.clone().take_state_root().get_state_root(), )) } else { None }; let quota_used: U256 = U256::from_str(receipt.get_quota_used()).unwrap(); let account_nonce: U256 = U256::from(receipt.get_account_nonce()); let transaction_hash: H256 = H256::from_slice(receipt.get_transaction_hash()); let mut error = None; let logs = receipt .get_logs() .iter() .map(|log_entry| { let address: Address = Address::from_slice(log_entry.get_address()); let topics: Vec<H256> = log_entry .get_topics() .iter() .map(|topic| H256::from_slice(topic)) .collect(); let data: Bytes = Bytes::from(log_entry.get_data()); Log { address, topics, data, } }) .collect(); if receipt.error.is_some() { error = Some(ReceiptError::from_proto( receipt.clone().take_error().get_error(), )); } Receipt::new( state_root, quota_used, logs, error, account_nonce, transaction_hash, ) } } impl Encodable for Receipt { fn rlp_append(&self, s: &mut RlpStream) { if let Some(ref root) = self.state_root { s.begin_list(7); s.append(root); } else { s.begin_list(6); } s.append(&self.quota_used); s.append(&self.log_bloom); s.append_list(&self.logs); s.append(&self.error); s.append(&self.account_nonce); s.append(&self.transaction_hash); } } impl Decodable for Receipt { fn decode(rlp: &UntrustedRlp) -> Result<Self, DecoderError> { if rlp.item_count()? == 6 { Ok(Receipt { state_root: None, quota_used: rlp.val_at(0)?, log_bloom: rlp.val_at(1)?, logs: rlp.list_at(2)?, error: rlp.val_at(3)?, account_nonce: rlp.val_at(4)?, transaction_hash: rlp.val_at(5)?, }) } else { Ok(Receipt { state_root: Some(rlp.val_at(0)?), quota_used: rlp.val_at(1)?, log_bloom: rlp.val_at(2)?, logs: rlp.list_at(3)?, error: rlp.val_at(4)?, account_nonce: rlp.val_at(5)?, transaction_hash: rlp.val_at(6)?, }) } } } #[derive(Debug, Clone)] pub struct RichReceipt { pub transaction_hash: H256, pub transaction_index: usize, pub block_hash: H256, pub block_number: BlockNumber, pub cumulative_quota_used: U256, pub quota_used: U256, pub contract_address: Option<Address>, pub logs: Vec<LocalizedLog>, pub log_bloom: LogBloom, pub state_root: Option<H256>, pub error: Option<ReceiptError>, } impl Into<RpcReceipt> for RichReceipt { fn into(self) -> RpcReceipt { RpcReceipt { transaction_hash: Some(self.transaction_hash), transaction_index: Some(self.transaction_index.into()), block_hash: Some(self.block_hash), block_number: Some(self.block_number.into()), cumulative_quota_used: self.cumulative_quota_used, quota_used: Some(self.quota_used), contract_address: self.contract_address.map(Into::into), logs: self.logs.into_iter().map(Into::into).collect(), state_root: self.state_root.map(Into::into), logs_bloom: self.log_bloom, error_message: self.error.map(ReceiptError::description), } } } #[cfg(test)] mod tests { use super::*; use crate::log::Log; #[test] fn test_no_state_root() { let r = Receipt::new( None, 0x40cae.into(), vec![Log { address: "dcf421d093428b096ca501a7cd1a740855a7976f".into(), topics: vec![], data: vec![0u8; 32], }], None, 1.into(), "2f697d671e9ae4ee24a43c4b0d7e15f1cb4ba6de1561120d43b9a4e8c4a8a6ee".into(), ); let encoded = ::rlp::encode(&r); println!("encode ok"); let decoded: Receipt = ::rlp::decode(&encoded); println!("decoded: {:?}", decoded); assert_eq!(decoded, r); } #[test] fn test_basic() { let r = Receipt::new( Some("2f697d671e9ae4ee24a43c4b0d7e15f1cb4ba6de1561120d43b9a4e8c4a8a6ee".into()), 0x40cae.into(), vec![Log { address: "dcf421d093428b096ca501a7cd1a740855a7976f".into(), topics: vec![], data: vec![0u8; 32], }], None, 1.into(), "2f697d671e9ae4ee24a43c4b0d7e15f1cb4ba6de1561120d43b9a4e8c4a8a6ee".into(), ); let encoded = ::rlp::encode(&r); let decoded: Receipt = ::rlp::decode(&encoded); println!("decoded: {:?}", decoded); assert_eq!(decoded, r); } #[test] fn test_with_error() { let r = Receipt::new( Some("2f697d671e9ae4ee24a43c4b0d7e15f1cb4ba6de1561120d43b9a4e8c4a8a6ee".into()), 0x40cae.into(), vec![Log { address: "dcf421d093428b096ca501a7cd1a740855a7976f".into(), topics: vec![], data: vec![0u8; 32], }], Some(ReceiptError::NoTransactionPermission), 1.into(), "2f697d671e9ae4ee24a43c4b0d7e15f1cb4ba6de1561120d43b9a4e8c4a8a6ee".into(), ); let encoded = ::rlp::encode(&r); let decoded: Receipt = ::rlp::decode(&encoded); println!("decoded: {:?}", decoded); assert_eq!(decoded, r); } }
use super::Bytes; use std::str::FromStr; use crate::block_number::BlockNumber; use crate::errors::ReceiptError; use crate::log::{LocalizedLog, Log}; use cita_types::traits::LowerHex; use cita_types::{Address, Bloom as LogBloom, H256, U256}; use jsonrpc_types::rpc_types::Receipt as RpcReceipt; use libproto::executor::{Receipt as ProtoReceipt, ReceiptErrorWithOption, StateRoot}; use rlp::{Decodable, DecoderError, Encodable, RlpStream, UntrustedRlp}; #[derive(Serialize, Deserialize, Default, Debug, Clone, PartialEq, Eq)] pub struct Receipt { pub state_root: Option<H256>, pub quota_used: U256, pub log_bloom: LogBloom, pub logs: Vec<Log>, pub error: Option<ReceiptError>, pub account_nonce: U256, pub transaction_hash: H256, } impl Receipt { pub fn new( state_root: Option<H256>, quota_used: U256, logs: Vec<Log>, error: Option<ReceiptError>, account_nonce: U256, transaction_hash: H256, ) -> Receipt { Receipt { state_root, quota_used, log_bloom: logs.iter().fold(LogBloom::default(), |b, l| b | l.bloom()), logs, error, account_nonce, transaction_hash, } } pub fn protobuf(&self) -> ProtoReceipt { let mut receipt_proto = ProtoReceipt::new(); let mut state_root_option = StateRoot::new(); let mut receipt_error_with_option = ReceiptErrorWithOption::new(); if let Some(state_root) = self.state_root { state_root_option.set_state_root(state_root.to_vec()); receipt_proto.set_state_root(state_root_option); } if let Some(error) = self.error { receipt_error_with_option.set_error(error.protobuf()); receipt_proto.set_error(receipt_error_with_option); } receipt_proto.set_quota_used(self.quota_used.lower_hex()); receipt_proto.set_log_bloom(self.log_bloom.to_vec()); receipt_proto.logs = self .
} impl From<ProtoReceipt> for Receipt { fn from(receipt: ProtoReceipt) -> Self { let state_root = if receipt.state_root.is_some() { Some(H256::from_slice( receipt.clone().take_state_root().get_state_root(), )) } else { None }; let quota_used: U256 = U256::from_str(receipt.get_quota_used()).unwrap(); let account_nonce: U256 = U256::from(receipt.get_account_nonce()); let transaction_hash: H256 = H256::from_slice(receipt.get_transaction_hash()); let mut error = None; let logs = receipt .get_logs() .iter() .map(|log_entry| { let address: Address = Address::from_slice(log_entry.get_address()); let topics: Vec<H256> = log_entry .get_topics() .iter() .map(|topic| H256::from_slice(topic)) .collect(); let data: Bytes = Bytes::from(log_entry.get_data()); Log { address, topics, data, } }) .collect(); if receipt.error.is_some() { error = Some(ReceiptError::from_proto( receipt.clone().take_error().get_error(), )); } Receipt::new( state_root, quota_used, logs, error, account_nonce, transaction_hash, ) } } impl Encodable for Receipt { fn rlp_append(&self, s: &mut RlpStream) { if let Some(ref root) = self.state_root { s.begin_list(7); s.append(root); } else { s.begin_list(6); } s.append(&self.quota_used); s.append(&self.log_bloom); s.append_list(&self.logs); s.append(&self.error); s.append(&self.account_nonce); s.append(&self.transaction_hash); } } impl Decodable for Receipt { fn decode(rlp: &UntrustedRlp) -> Result<Self, DecoderError> { if rlp.item_count()? == 6 { Ok(Receipt { state_root: None, quota_used: rlp.val_at(0)?, log_bloom: rlp.val_at(1)?, logs: rlp.list_at(2)?, error: rlp.val_at(3)?, account_nonce: rlp.val_at(4)?, transaction_hash: rlp.val_at(5)?, }) } else { Ok(Receipt { state_root: Some(rlp.val_at(0)?), quota_used: rlp.val_at(1)?, log_bloom: rlp.val_at(2)?, logs: rlp.list_at(3)?, error: rlp.val_at(4)?, account_nonce: rlp.val_at(5)?, transaction_hash: rlp.val_at(6)?, }) } } } #[derive(Debug, Clone)] pub struct RichReceipt { pub transaction_hash: H256, pub transaction_index: usize, pub block_hash: H256, pub block_number: BlockNumber, pub cumulative_quota_used: U256, pub quota_used: U256, pub contract_address: Option<Address>, pub logs: Vec<LocalizedLog>, pub log_bloom: LogBloom, pub state_root: Option<H256>, pub error: Option<ReceiptError>, } impl Into<RpcReceipt> for RichReceipt { fn into(self) -> RpcReceipt { RpcReceipt { transaction_hash: Some(self.transaction_hash), transaction_index: Some(self.transaction_index.into()), block_hash: Some(self.block_hash), block_number: Some(self.block_number.into()), cumulative_quota_used: self.cumulative_quota_used, quota_used: Some(self.quota_used), contract_address: self.contract_address.map(Into::into), logs: self.logs.into_iter().map(Into::into).collect(), state_root: self.state_root.map(Into::into), logs_bloom: self.log_bloom, error_message: self.error.map(ReceiptError::description), } } } #[cfg(test)] mod tests { use super::*; use crate::log::Log; #[test] fn test_no_state_root() { let r = Receipt::new( None, 0x40cae.into(), vec![Log { address: "dcf421d093428b096ca501a7cd1a740855a7976f".into(), topics: vec![], data: vec![0u8; 32], }], None, 1.into(), "2f697d671e9ae4ee24a43c4b0d7e15f1cb4ba6de1561120d43b9a4e8c4a8a6ee".into(), ); let encoded = ::rlp::encode(&r); println!("encode ok"); let decoded: Receipt = ::rlp::decode(&encoded); println!("decoded: {:?}", decoded); assert_eq!(decoded, r); } #[test] fn test_basic() { let r = Receipt::new( Some("2f697d671e9ae4ee24a43c4b0d7e15f1cb4ba6de1561120d43b9a4e8c4a8a6ee".into()), 0x40cae.into(), vec![Log { address: "dcf421d093428b096ca501a7cd1a740855a7976f".into(), topics: vec![], data: vec![0u8; 32], }], None, 1.into(), "2f697d671e9ae4ee24a43c4b0d7e15f1cb4ba6de1561120d43b9a4e8c4a8a6ee".into(), ); let encoded = ::rlp::encode(&r); let decoded: Receipt = ::rlp::decode(&encoded); println!("decoded: {:?}", decoded); assert_eq!(decoded, r); } #[test] fn test_with_error() { let r = Receipt::new( Some("2f697d671e9ae4ee24a43c4b0d7e15f1cb4ba6de1561120d43b9a4e8c4a8a6ee".into()), 0x40cae.into(), vec![Log { address: "dcf421d093428b096ca501a7cd1a740855a7976f".into(), topics: vec![], data: vec![0u8; 32], }], Some(ReceiptError::NoTransactionPermission), 1.into(), "2f697d671e9ae4ee24a43c4b0d7e15f1cb4ba6de1561120d43b9a4e8c4a8a6ee".into(), ); let encoded = ::rlp::encode(&r); let decoded: Receipt = ::rlp::decode(&encoded); println!("decoded: {:?}", decoded); assert_eq!(decoded, r); } }
logs .clone() .into_iter() .map(|log_entry| log_entry.protobuf()) .collect(); receipt_proto.set_account_nonce(self.account_nonce.as_u64()); receipt_proto.set_transaction_hash(self.transaction_hash.to_vec()); receipt_proto }
function_block-function_prefix_line
[ { "content": "fn accrue_log(bloom: &mut Bloom, log: &Log) {\n\n bloom.accrue(BloomInput::Raw(&log.address.0));\n\n for topic in &log.topics {\n\n let input = BloomInput::Hash(&topic.0);\n\n bloom.accrue(input);\n\n }\n\n}\n\n\n", "file_path": "cita-executor/core/src/cita_executive.rs", "rank": 0, "score": 318619.9537105009 }, { "content": "pub fn cita_block_number(upstream: &UpStream) -> Result<U256, Error> {\n\n let req = rpc_request::BlockNumberParams::new().into_request(1);\n\n let result = rpc_send_and_get_result_from_reply!(upstream, req, U256);\n\n Ok(result)\n\n}\n\n\n", "file_path": "tools/relayer-parser/src/communication.rs", "rank": 1, "score": 255502.17289800686 }, { "content": "fn logs_to_bloom(logs: &[Log]) -> Bloom {\n\n let mut bloom = Bloom::default();\n\n\n\n logs.iter().for_each(|log| accrue_log(&mut bloom, log));\n\n bloom\n\n}\n\n\n", "file_path": "cita-executor/core/src/cita_executive.rs", "rank": 2, "score": 246087.10103837214 }, { "content": "pub fn cita_get_transaction_proof(upstream: &UpStream, tx_hash: H256) -> Result<Vec<u8>, Error> {\n\n let req = rpc_request::GetTransactionProofParams::new(tx_hash.into()).into_request(1);\n\n let result = rpc_send_and_get_result_from_reply!(upstream, req, rpc_types::Data);\n\n Ok(result.into())\n\n}\n\n\n", "file_path": "tools/relayer-parser/src/communication.rs", "rank": 3, "score": 226485.36904778105 }, { "content": "pub fn string_2_u256(value: String) -> U256 {\n\n let v = Box::leak(value.into_boxed_str());\n\n let v = clean_0x(v);\n\n U256::from(v)\n\n}\n\n\n", "file_path": "tests/json-test/src/helper.rs", "rank": 4, "score": 220947.6579880907 }, { "content": "pub fn string_2_h256(value: String) -> H256 {\n\n let v = Box::leak(value.into_boxed_str());\n\n let v = clean_0x(v);\n\n if v.len() < 64 {\n\n let mut s = String::from(\"0\").repeat(64 - v.len());\n\n s.push_str(v);\n\n let s: &'static str = Box::leak(s.into_boxed_str());\n\n return H256::from(s);\n\n }\n\n H256::from(v)\n\n}\n\n\n", "file_path": "tests/json-test/src/helper.rs", "rank": 5, "score": 220923.57394728987 }, { "content": "/// Parse solidity return data `uint256` to rust `U256`\n\npub fn to_u256(output: &[u8]) -> Option<U256> {\n\n decode(&[ParamType::Uint(256)], output)\n\n .ok()\n\n .and_then(|decoded| decoded.first().cloned())\n\n .and_then(Token::to_uint)\n\n .map(H256::from)\n\n .map(U256::from)\n\n}\n\n\n", "file_path": "cita-executor/core/src/contracts/tools/decode.rs", "rank": 6, "score": 210624.1188578105 }, { "content": "/// Function create creates a new contract.\n\npub fn create<B: DB + 'static>(\n\n block_provider: Arc<dyn BlockDataProvider>,\n\n state_provider: Arc<RefCell<State<B>>>,\n\n store: Arc<RefCell<VMSubState>>,\n\n request: &InterpreterParams,\n\n create_kind: CreateKind,\n\n) -> Result<evm::InterpreterResult, VMError> {\n\n debug!(\"create request={:?}\", request);\n\n let address = match create_kind {\n\n CreateKind::FromAddressAndNonce => {\n\n // Generate new address created from address, nonce\n\n create_address_from_address_and_nonce(&request.sender, &request.nonce)\n\n }\n\n CreateKind::FromSaltAndCodeHash => {\n\n // Generate new address created from sender salt and code hash\n\n create_address_from_salt_and_code_hash(\n\n &request.sender,\n\n request.extra,\n\n request.input.clone(),\n\n )\n", "file_path": "cita-executor/core/src/cita_executive.rs", "rank": 7, "score": 209050.5012373802 }, { "content": "/// Function call enters into the specific contract.\n\npub fn call<B: DB + 'static>(\n\n block_provider: Arc<dyn BlockDataProvider>,\n\n state_provider: Arc<RefCell<State<B>>>,\n\n store: Arc<RefCell<VMSubState>>,\n\n request: &InterpreterParams,\n\n) -> Result<evm::InterpreterResult, VMError> {\n\n // Here not need check twice,becauce prepay is subed ,but need think call_static\n\n /*if !request.disable_transfer_value && state_provider.borrow_mut().balance(&request.sender)? < request.value {\n\n return Err(err::Error::NotEnoughBalance);\n\n }*/\n\n // Run\n\n state_provider.borrow_mut().checkpoint();\n\n let store_son = Arc::new(RefCell::new(store.borrow_mut().clone()));\n\n let native_factory = NativeFactory::default();\n\n // Check and call Native Contract.\n\n if let Some(mut native_contract) = native_factory.new_contract(request.contract.code_address) {\n\n let mut vm_data_provider = DataProvider::new(\n\n block_provider.clone(),\n\n state_provider.clone(),\n\n store.clone(),\n", "file_path": "cita-executor/core/src/cita_executive.rs", "rank": 8, "score": 209045.31699791068 }, { "content": "/// If a contract creation is attempted, due to either a creation transaction\n\n/// or the CREATE (or future CREATE2) opcode, and the destination address\n\n/// already has either nonzero nonce, or nonempty code, then the creation\n\n/// throws immediately, with exactly the same behavior as would arise if the\n\n/// first byte in the init code were an invalid opcode. This applies\n\n/// retroactively starting from genesis.\n\n///\n\n/// See: EIP 684\n\npub fn can_create<B: DB + 'static>(\n\n state_provider: Arc<RefCell<State<B>>>,\n\n address: &Address,\n\n) -> Result<bool, VMError> {\n\n let a = state_provider.borrow_mut().nonce(&address)?;\n\n let b = state_provider.borrow_mut().code(&address)?;\n\n Ok(a.is_zero() && b.is_empty())\n\n}\n\n\n\n#[derive(Clone, Debug)]\n\npub struct ExecutiveParams {\n\n /// Address of currently executed code.\n\n pub code_address: Option<Address>,\n\n /// Sender of current part of the transaction.\n\n pub sender: Address,\n\n /// Receive address. Usually equal to code_address,\n\n pub to_address: Option<Address>,\n\n /// Gas paid up front for transaction execution\n\n pub gas: U256,\n\n /// Gas price.\n", "file_path": "cita-executor/core/src/cita_executive.rs", "rank": 9, "score": 206587.20111825602 }, { "content": "/// Split the logs with the limit filter.\n\nfn split_logs(mut logs: Vec<Log>, limit: Option<usize>) -> Vec<Log> {\n\n let len = logs.len();\n\n match limit {\n\n Some(limit) if len >= limit => logs.split_off(len - limit),\n\n _ => logs,\n\n }\n\n}\n", "file_path": "cita-chain/core/src/filters/rpc_filter.rs", "rank": 10, "score": 205041.54251445495 }, { "content": "/// Function call_pure enters into the specific contract with no check or checkpoints.\n\npub fn call_pure<B: DB + 'static>(\n\n block_provider: Arc<dyn BlockDataProvider>,\n\n state_provider: Arc<RefCell<State<B>>>,\n\n store: Arc<RefCell<VMSubState>>,\n\n request: &InterpreterParams,\n\n) -> Result<evm::InterpreterResult, VMError> {\n\n let evm_context = store.borrow().evm_context.clone();\n\n let evm_cfg = store.borrow().evm_cfg.clone();\n\n let evm_params = request.clone();\n\n let evm_data_provider = DataProvider::new(\n\n block_provider.clone(),\n\n state_provider.clone(),\n\n store.clone(),\n\n );\n\n // Transfer value\n\n if !request.disable_transfer_value {\n\n state_provider.borrow_mut().transfer_balance(\n\n &request.sender,\n\n &request.receiver,\n\n request.value,\n", "file_path": "cita-executor/core/src/cita_vm_helper.rs", "rank": 11, "score": 204217.24259660958 }, { "content": "pub fn clone_executor_reader(\n\n command_req_sender: &Sender<Command>,\n\n command_resp_receiver: &Receiver<CommandResp>,\n\n) -> Executor {\n\n let _ = command_req_sender.send(Command::CloneExecutorReader);\n\n match command_resp_receiver.recv().unwrap() {\n\n CommandResp::CloneExecutorReader(r) => r,\n\n _ => unimplemented!(),\n\n }\n\n}\n", "file_path": "cita-executor/core/src/libexecutor/command.rs", "rank": 12, "score": 203064.1864058222 }, { "content": "pub fn build_vm_exec_params<B: DB + 'static>(\n\n params: &ExecutiveParams,\n\n state_provider: Arc<RefCell<State<B>>>,\n\n) -> VmExecParams {\n\n let mut vm_exec_params = VmExecParams::default();\n\n vm_exec_params.origin = params.sender;\n\n vm_exec_params.sender = params.sender;\n\n if let Some(data) = params.to_address {\n\n vm_exec_params.to_address = data;\n\n vm_exec_params.storage_address = data;\n\n vm_exec_params.code_address = data;\n\n vm_exec_params.code_data = state_provider.borrow_mut().code(&data).unwrap_or_default();\n\n }\n\n\n\n vm_exec_params.gas_price = params.gas_price;\n\n vm_exec_params.gas = params.gas.as_u64();\n\n vm_exec_params.value = params.value;\n\n vm_exec_params.data = params.data.clone().unwrap_or_default();\n\n vm_exec_params.nonce = params.nonce;\n\n vm_exec_params\n", "file_path": "cita-executor/core/src/cita_executive.rs", "rank": 13, "score": 201930.7824908375 }, { "content": "/// Parse solidity return data `uint256[]` to rust `Vec<u256>`\n\npub fn to_u256_vec(output: &[u8]) -> Option<Vec<U256>> {\n\n if output.is_empty() {\n\n Some(Vec::new())\n\n } else {\n\n decode(&[ParamType::Array(Box::new(ParamType::Uint(256)))], output)\n\n .ok()\n\n .and_then(|decoded| decoded.first().cloned())\n\n .and_then(Token::to_array)\n\n .and_then(|uints| {\n\n let mut v = Vec::new();\n\n for x in uints {\n\n if let Some(x) = x.to_uint() {\n\n let h = H256::from(x);\n\n v.push(U256::from(h))\n\n } else {\n\n return None;\n\n }\n\n }\n\n Some(v)\n\n })\n\n }\n\n}\n\n\n", "file_path": "cita-executor/core/src/contracts/tools/decode.rs", "rank": 14, "score": 201417.61182468018 }, { "content": "pub fn network_message_to_pubsub_message(buf: &mut BytesMut) -> Option<NetMessageUnit> {\n\n if buf.len() < CITA_FRAME_HEADER_LEN {\n\n return None;\n\n }\n\n\n\n let head_buf = buf.split_to(CITA_FRAME_HEADER_LEN);\n\n\n\n let request_id = NetworkEndian::read_u64(&head_buf);\n\n let netmsg_start = request_id & 0xffff_ffff_0000_0000;\n\n let length_full = (request_id & 0x0000_0000_ffff_ffff) as usize;\n\n if netmsg_start != NETMSG_START {\n\n return None;\n\n }\n\n if length_full > buf.len() || length_full == 0 {\n\n return None;\n\n }\n\n\n\n let addr = Address::from_slice(&head_buf[HEAD_ADDRESS_OFFSET..]);\n\n let version = NetworkEndian::read_u64(&head_buf[HEAD_VERSION_OFFSET..]);\n\n\n", "file_path": "cita-network/src/cita_protocol.rs", "rank": 15, "score": 195470.02036593057 }, { "content": "pub fn generate_default_block() -> OpenBlock {\n\n let block_body = generate_block_body();\n\n let block_header = generate_block_header();\n\n OpenBlock {\n\n body: block_body,\n\n header: block_header,\n\n }\n\n}\n", "file_path": "cita-executor/core/src/tests/helpers.rs", "rank": 16, "score": 191335.17922871857 }, { "content": "pub fn contract_address(address: &Address, nonce: &U256) -> Address {\n\n let mut stream = RlpStream::new_list(2);\n\n stream.append(address);\n\n stream.append(nonce);\n\n From::from(stream.out().crypt_hash())\n\n}\n\n\n\nimpl Chain {\n\n pub fn init_chain(db: Arc<RocksDB>, chain_config: Config) -> Chain {\n\n info!(\"chain config: {:?}\", chain_config);\n\n\n\n let blooms_config = BloomChainConfig {\n\n levels: LOG_BLOOMS_LEVELS,\n\n elements_per_index: LOG_BLOOMS_ELEMENTS_PER_INDEX,\n\n };\n\n\n\n let header = get_chain(&*db).unwrap_or_default();\n\n debug!(\"get chain head is : {:?}\", header);\n\n let current_height = AtomicUsize::new(header.number() as usize);\n\n let max_store_height = AtomicUsize::new(0);\n", "file_path": "cita-chain/core/src/libchain/chain.rs", "rank": 17, "score": 191175.40477464756 }, { "content": "pub fn generate_postman(current_height: u64, current_hash: H256) -> Postman {\n\n let (_mq_req_sender, mq_req_receiver) = crossbeam_channel::unbounded();\n\n let (mq_resp_sender, _mq_resp_receiver) = crossbeam_channel::unbounded();\n\n let (fsm_req_sender, _fsm_req_receiver) = crossbeam_channel::unbounded();\n\n let (_fsm_resp_sender, fsm_resp_receiver) = crossbeam_channel::unbounded();\n\n let (command_req_sender, _command_req_receiver) = crossbeam_channel::bounded(0);\n\n let (_command_resp_sender, command_resp_receiver) = crossbeam_channel::bounded(0);\n\n Postman::new(\n\n current_height,\n\n current_hash,\n\n mq_req_receiver,\n\n mq_resp_sender,\n\n fsm_req_sender,\n\n fsm_resp_receiver,\n\n command_req_sender,\n\n command_resp_receiver,\n\n )\n\n}\n\n\n", "file_path": "cita-executor/src/tests/helpers.rs", "rank": 18, "score": 188948.57805382577 }, { "content": "/// Returns new address created from address and nonce.\n\npub fn create_address_from_address_and_nonce(address: &Address, nonce: &U256) -> Address {\n\n let mut stream = RlpStream::new_list(2);\n\n stream.append(address);\n\n stream.append(nonce);\n\n Address::from(H256::from(summary(stream.as_raw()).as_slice()))\n\n}\n\n\n", "file_path": "cita-executor/core/src/cita_executive.rs", "rank": 19, "score": 186840.90206346672 }, { "content": "pub fn generate_block_with_proof(height: u64, parent_hash: H256) -> libproto::BlockWithProof {\n\n // - Block\n\n let to_address = Address::from(0);\n\n let data = generate_contract();\n\n let mut proto_block = generate_block(\n\n height,\n\n parent_hash,\n\n to_address,\n\n data,\n\n (0, 10),\n\n generate_signer().keypair.privkey().clone(),\n\n );\n\n\n\n // - Proof\n\n let present_proof = generate_proof(generate_signer(), height, H256::from(0));\n\n let previous_proof = generate_proof(generate_signer(), height - 1, H256::from(0));\n\n proto_block.mut_header().set_proof(previous_proof.into());\n\n\n\n // - BlockWithProof\n\n let mut block_with_proof = libproto::BlockWithProof::new();\n\n block_with_proof.set_proof(present_proof.into());\n\n block_with_proof.set_blk(proto_block);\n\n block_with_proof\n\n}\n\n\n", "file_path": "cita-executor/src/tests/helpers.rs", "rank": 20, "score": 180458.41882515384 }, { "content": "pub fn generate_signed_proposal(height: u64, parent_hash: H256) -> libproto::SignedProposal {\n\n // - Block\n\n let to_address = Address::from(0);\n\n let data = generate_contract();\n\n let proto_block = generate_block(\n\n height,\n\n parent_hash,\n\n to_address,\n\n data,\n\n (0, 10),\n\n generate_signer().keypair.privkey().clone(),\n\n );\n\n\n\n // - Proof\n\n let signer = generate_signer();\n\n let signer_address = signer.address.clone();\n\n let proof = generate_proof(signer, height, H256::from(0));\n\n let bft_proof = proof::BftProof::from(proof.clone());\n\n let signature = bft_proof\n\n .commits\n", "file_path": "cita-executor/src/tests/helpers.rs", "rank": 21, "score": 180458.41882515384 }, { "content": "pub fn cita_get_metadata(upstream: &UpStream) -> Result<rpc_types::MetaData, Error> {\n\n let height = rpc_types::BlockNumber::latest();\n\n let req = rpc_request::GetMetaDataParams::new(height).into_request(1);\n\n let result = rpc_send_and_get_result_from_reply!(upstream, req, rpc_types::MetaData);\n\n Ok(result)\n\n}\n\n\n", "file_path": "tools/relayer-parser/src/communication.rs", "rank": 22, "score": 180432.95984245025 }, { "content": "pub fn encode_to_u32(name: &[u8]) -> u32 {\n\n BigEndian::read_u32(&sha3::keccak256(name)[..])\n\n}\n\n\n", "file_path": "cita-executor/core/src/contracts/tools/method.rs", "rank": 23, "score": 178950.0413143651 }, { "content": "pub fn generate_proof(signer: Signer, height: u64, proposal: H256) -> libproto::Proof {\n\n let serialized = bincode::serialize(\n\n &(\n\n height as usize,\n\n PROOF_ROUND,\n\n PROOF_STEP,\n\n signer.address,\n\n proposal,\n\n ),\n\n bincode::Infinite,\n\n )\n\n .expect(\"serialize into bytes\");\n\n let signature = Signature::sign(signer.keypair.privkey(), &serialized.crypt_hash())\n\n .expect(\"signature message\");\n\n\n\n let mut commits = ::std::collections::HashMap::new();\n\n commits.insert(signer.address, signature);\n\n let bft_proof = proof::BftProof::new(height as usize, PROOF_ROUND, proposal, commits);\n\n bft_proof.into()\n\n}\n\n\n", "file_path": "cita-executor/src/tests/helpers.rs", "rank": 24, "score": 175458.37578530662 }, { "content": "pub fn encode_to_array(name: &[u8]) -> [u8; 4] {\n\n let mut ret = [0u8; 4];\n\n ret.copy_from_slice(&sha3::keccak256(name)[0..4]);\n\n ret\n\n}\n\n\n", "file_path": "cita-executor/core/src/contracts/tools/method.rs", "rank": 25, "score": 175114.1080258371 }, { "content": "pub fn shuffle<T>(items: &mut Vec<T>, rng_seed: u64) {\n\n let seed: &[_] = &[rng_seed as usize];\n\n let mut rng: StdRng = SeedableRng::from_seed(seed);\n\n\n\n for i in 0..items.len() {\n\n let j: usize = rng.gen::<usize>() % (i + 1);\n\n items.swap(i, j);\n\n }\n\n}\n\n\n\n/// Configuration items from system contract\n\npub struct NodeManager<'a> {\n\n executor: &'a Executor,\n\n rng_seed: u64,\n\n}\n\n\n\nimpl<'a> NodeManager<'a> {\n\n pub fn new(executor: &'a Executor, rng_seed: u64) -> Self {\n\n NodeManager { executor, rng_seed }\n\n }\n", "file_path": "cita-executor/core/src/contracts/solc/node_manager.rs", "rank": 26, "score": 174682.55603347035 }, { "content": "pub fn encode_to_vec(name: &[u8]) -> Vec<u8> {\n\n sha3::keccak256(name)[0..4].to_vec()\n\n}\n\n\n", "file_path": "cita-executor/core/src/contracts/tools/method.rs", "rank": 27, "score": 172827.47271223844 }, { "content": "#[bench]\n\nfn test_block_with_50000_tx(b: &mut Bencher) {\n\n // One block with 50000 tx bench test takes 1424.51ms\n\n let mut executor = helpers::init_executor();\n\n let block = generate_block(&executor, 50000);\n\n\n\n b.iter(|| {\n\n executor.into_fsm(block.clone());\n\n });\n\n}\n\n\n", "file_path": "cita-executor/core/src/benches/executor.rs", "rank": 28, "score": 171698.3200588571 }, { "content": "#[bench]\n\nfn test_block_with_30000_tx(b: &mut Bencher) {\n\n // One block with 30000 tx bench test takes 886.39ms\n\n let mut executor = helpers::init_executor();\n\n let block = generate_block(&executor, 30000);\n\n\n\n b.iter(|| {\n\n executor.into_fsm(block.clone());\n\n });\n\n}\n\n\n", "file_path": "cita-executor/core/src/benches/executor.rs", "rank": 29, "score": 171698.3200588571 }, { "content": "#[bench]\n\nfn test_block_with_10000_tx(b: &mut Bencher) {\n\n // One block with 10000 tx bench test takes 271.51ms\n\n let mut executor = helpers::init_executor();\n\n let block = generate_block(&executor, 10000);\n\n\n\n b.iter(|| {\n\n executor.into_fsm(block.clone());\n\n });\n\n}\n\n\n", "file_path": "cita-executor/core/src/benches/executor.rs", "rank": 30, "score": 171698.3200588571 }, { "content": "#[bench]\n\nfn test_block_with_10000_tx_write_db(b: &mut Bencher) {\n\n // One block with 10000 tx bench test takes 1551.8ms\n\n let mut executor = helpers::init_executor();\n\n let block = generate_block(&executor, 10000);\n\n\n\n b.iter(|| {\n\n let mut closed_block = executor.into_fsm(block.clone());\n\n executor.grow(&closed_block);\n\n closed_block.clear_cache();\n\n });\n\n}\n", "file_path": "cita-executor/core/src/benches/executor.rs", "rank": 31, "score": 168477.8579347845 }, { "content": "// verify signature\n\npub fn verify_tx_sig(crypto: Crypto, hash: &H256, sig_bytes: &[u8]) -> Result<Vec<u8>, ()> {\n\n if sig_bytes.len() != SIGNATURE_BYTES_LEN {\n\n return Err(());\n\n }\n\n\n\n let sig = Signature::from(sig_bytes);\n\n match crypto {\n\n Crypto::DEFAULT => sig\n\n .recover(&hash)\n\n .map(|pubkey| pubkey.to_vec())\n\n .map_err(|_| ()),\n\n _ => {\n\n warn!(\"Unexpected crypto\");\n\n Err(())\n\n }\n\n }\n\n}\n\n\n\npub struct SysConfigInfo {\n\n pub block_quota_limit: u64,\n\n pub account_quota_limit: AccountGasLimit,\n\n pub check_quota: bool,\n\n pub admin_address: Option<Address>,\n\n pub version: Option<u32>,\n\n}\n\n\n", "file_path": "cita-auth/src/handler.rs", "rank": 32, "score": 168468.82729713304 }, { "content": "fn send_proofed_block(config: &mut Config, tx_pub: &Sender<PubType>, rich_status: &RichStatus) {\n\n let height = rich_status.get_height() + 1;\n\n let hash = H256::from_slice(&rich_status.get_hash());\n\n let transactions = make_transactions(config, rich_status);\n\n let (body, _) = BuildBlock::build_block_with_proof(\n\n &transactions,\n\n hash,\n\n height,\n\n &config.private_key,\n\n GENESIS_TIMESTAMP + height * 3,\n\n );\n\n let key = routing_key!(Consensus >> BlockWithProof).into();\n\n tx_pub.send((key, body)).unwrap();\n\n}\n", "file_path": "tests/box-executor/src/runner.rs", "rank": 33, "score": 165234.25608613106 }, { "content": "fn send_signed_proposal(config: &mut Config, tx_pub: &Sender<PubType>, rich_status: &RichStatus) {\n\n let height = rich_status.get_height() + 1;\n\n let hash = H256::from_slice(&rich_status.get_hash());\n\n let transactions = make_transactions(config, rich_status);\n\n let (body, _) = BuildBlock::build_signed_proposal(\n\n &transactions,\n\n hash,\n\n height,\n\n &config.private_key,\n\n GENESIS_TIMESTAMP + height * 3,\n\n );\n\n let key = routing_key!(Consensus >> SignedProposal).into();\n\n tx_pub.send((key, body)).unwrap();\n\n}\n\n\n", "file_path": "tests/box-executor/src/runner.rs", "rank": 34, "score": 165234.25608613106 }, { "content": "// Extract first four bytes (function signature hash) as u32.\n\npub fn extract_to_u32(data: &[u8]) -> Result<u32, NativeError> {\n\n if let Some(ref bytes4) = data.get(0..4) {\n\n Ok(BigEndian::read_u32(bytes4))\n\n } else {\n\n Err(NativeError::Internal(\"out of gas\".to_string()))\n\n }\n\n}\n\n\n\n#[cfg(test)]\n\nmod tests {\n\n\n\n use byteorder::{BigEndian, ByteOrder};\n\n\n\n #[test]\n\n fn all() {\n\n let testdata = vec![\n\n (\"thisIsAMethodName(uint256)\", vec![0xa8, 0x67, 0x12, 0xe7]),\n\n (\"aMethodNameAgain(bool)\", vec![0xa1, 0xbe, 0xa0, 0xac]),\n\n (\n\n \"thisIsAlsoAMethodName(bytes32)\",\n", "file_path": "cita-executor/core/src/contracts/tools/method.rs", "rank": 35, "score": 165146.11280755483 }, { "content": "fn do_loop(mut config: Config, rx_sub: &Receiver<SubType>, tx_pub: &Sender<PubType>) {\n\n while config.blocks.len() > 1 {\n\n if let Some(rich_status) = receive_rich_status(&rx_sub) {\n\n info!(\">> receive RichStatus.height: {}\", rich_status.get_height(),);\n\n validate_rich_status(&mut config, &rich_status);\n\n match config.blocks.len() % 4 {\n\n 0 => send_proofed_block(&mut config, &tx_pub, &rich_status),\n\n 1 => {\n\n send_signed_proposal(&mut config, &tx_pub, &rich_status);\n\n send_proofed_block(&mut config, &tx_pub, &rich_status)\n\n }\n\n 2 => {\n\n send_signed_proposal(&mut config, &tx_pub, &rich_status);\n\n thread::sleep(time::Duration::from_secs(4));\n\n send_proofed_block(&mut config, &tx_pub, &rich_status);\n\n }\n\n 3 => {\n\n send_signed_proposal(&mut config, &tx_pub, &rich_status);\n\n thread::sleep(time::Duration::from_secs(4));\n\n\n", "file_path": "tests/box-executor/src/runner.rs", "rank": 36, "score": 164821.37329456527 }, { "content": "pub fn grow(\n\n command_req_sender: &Sender<Command>,\n\n command_resp_receiver: &Receiver<CommandResp>,\n\n closed_block: ClosedBlock,\n\n) -> ExecutedResult {\n\n let _ = command_req_sender.send(Command::Grow(closed_block));\n\n match command_resp_receiver.recv().unwrap() {\n\n CommandResp::Grow(r) => r,\n\n _ => unimplemented!(),\n\n }\n\n}\n\n\n", "file_path": "cita-executor/core/src/libexecutor/command.rs", "rank": 37, "score": 160669.88478092873 }, { "content": "pub fn abi_at(\n\n command_req_sender: &Sender<Command>,\n\n command_resp_receiver: &Receiver<CommandResp>,\n\n address: Address,\n\n block_tag: BlockTag,\n\n) -> Option<Bytes> {\n\n let _ = command_req_sender.send(Command::ABIAt(address, block_tag));\n\n match command_resp_receiver.recv().unwrap() {\n\n CommandResp::ABIAt(r) => r,\n\n _ => unimplemented!(),\n\n }\n\n}\n\n\n", "file_path": "cita-executor/core/src/libexecutor/command.rs", "rank": 38, "score": 160669.88478092873 }, { "content": "pub fn nonce_at(\n\n command_req_sender: &Sender<Command>,\n\n command_resp_receiver: &Receiver<CommandResp>,\n\n address: Address,\n\n block_tag: BlockTag,\n\n) -> Option<U256> {\n\n let _ = command_req_sender.send(Command::NonceAt(address, block_tag));\n\n match command_resp_receiver.recv().unwrap() {\n\n CommandResp::NonceAt(r) => r,\n\n _ => unimplemented!(),\n\n }\n\n}\n\n\n", "file_path": "cita-executor/core/src/libexecutor/command.rs", "rank": 39, "score": 160669.88478092873 }, { "content": "pub fn exit(\n\n command_req_sender: &Sender<Command>,\n\n command_resp_receiver: &Receiver<CommandResp>,\n\n rollback_id: BlockTag,\n\n) {\n\n let _ = command_req_sender.send(Command::Exit(rollback_id));\n\n match command_resp_receiver.recv().unwrap() {\n\n CommandResp::Exit => {}\n\n _ => unimplemented!(),\n\n }\n\n}\n\n\n", "file_path": "cita-executor/core/src/libexecutor/command.rs", "rank": 40, "score": 160669.88478092873 }, { "content": "#[cfg(any(target_os = \"macos\", target_os = \"ios\"))]\n\npub fn set_fd_limit() {\n\n use std::cmp;\n\n use std::io;\n\n use std::mem::size_of_val;\n\n use std::ptr::null_mut;\n\n\n\n unsafe {\n\n static KERN_MAXFILESPERPROC: libc::c_int = 29;\n\n static CTL_KERN: libc::c_int = 1;\n\n let mut mib: [libc::c_int; 2] = [CTL_KERN, KERN_MAXFILESPERPROC];\n\n let mut maxfiles: libc::c_int = 0;\n\n let mut size: libc::size_t = size_of_val(&maxfiles) as libc::size_t;\n\n\n\n if libc::sysctl(\n\n &mut mib[0],\n\n 2,\n\n &mut maxfiles as *mut _ as *mut _,\n\n &mut size,\n\n null_mut(),\n\n 0,\n", "file_path": "cita-jsonrpc/src/fdlimit.rs", "rank": 41, "score": 160669.88478092873 }, { "content": "pub fn call(\n\n command_req_sender: &Sender<Command>,\n\n command_resp_receiver: &Receiver<CommandResp>,\n\n signed_transaction: SignedTransaction,\n\n\n\n block_tag: BlockTag,\n\n) -> Result<CitaExecuted, CallError> {\n\n let _ = command_req_sender.send(Command::Call(signed_transaction, block_tag));\n\n match command_resp_receiver.recv().unwrap() {\n\n CommandResp::Call(r) => r,\n\n _ => unimplemented!(),\n\n }\n\n}\n\n\n", "file_path": "cita-executor/core/src/libexecutor/command.rs", "rank": 42, "score": 160669.88478092873 }, { "content": "pub fn construct_transaction(\n\n pkey: &PrivKey,\n\n tx_proof_rlp: &[u8],\n\n dest_hasher: [u8; 4],\n\n dest_contract: H160,\n\n chain_id: U256,\n\n height: U256,\n\n) -> UnverifiedTransaction {\n\n let code = encode(dest_hasher, tx_proof_rlp);\n\n sign(pkey, dest_contract, code, chain_id, height)\n\n}\n\n\n", "file_path": "tools/relayer-parser/src/transaction.rs", "rank": 43, "score": 160669.88478092873 }, { "content": "// generate OpenBlock without proof\n\npub fn generate_block(\n\n height: u64,\n\n parent_hash: H256,\n\n to: Address,\n\n data: Vec<u8>,\n\n nonce: (u32, u32),\n\n privkey: PrivKey,\n\n) -> libproto::Block {\n\n let body = {\n\n let mut body = libproto::BlockBody::default();\n\n // fn generate_signed_transaction(to: Address, data: Vec<u8>, nonce: u32, privkey: PrivKey) -> SignedTransaction {\n\n let mut transactions = Vec::new();\n\n for i in nonce.0..nonce.1 {\n\n let transaction = generate_signed_transaction(to, data.clone(), i, privkey);\n\n transactions.push(transaction);\n\n }\n\n body.set_transactions(transactions.into());\n\n body\n\n };\n\n let mut proto_block = libproto::Block::new();\n", "file_path": "cita-executor/src/tests/helpers.rs", "rank": 44, "score": 160669.88478092873 }, { "content": "pub fn code_at(\n\n command_req_sender: &Sender<Command>,\n\n command_resp_receiver: &Receiver<CommandResp>,\n\n address: Address,\n\n block_tag: BlockTag,\n\n) -> Option<Bytes> {\n\n let _ = command_req_sender.send(Command::CodeAt(address, block_tag));\n\n match command_resp_receiver.recv().unwrap() {\n\n CommandResp::CodeAt(r) => r,\n\n _ => unimplemented!(),\n\n }\n\n}\n\n\n", "file_path": "cita-executor/core/src/libexecutor/command.rs", "rank": 45, "score": 160669.88478092873 }, { "content": "pub fn state_at(\n\n command_req_sender: &Sender<Command>,\n\n command_resp_receiver: &Receiver<CommandResp>,\n\n block_tag: BlockTag,\n\n) -> Option<CitaState<CitaTrieDB>> {\n\n let _ = command_req_sender.send(Command::StateAt(block_tag));\n\n match command_resp_receiver.recv().unwrap() {\n\n CommandResp::StateAt(r) => r,\n\n _ => unimplemented!(),\n\n }\n\n}\n\n\n", "file_path": "cita-executor/core/src/libexecutor/command.rs", "rank": 46, "score": 160669.88478092873 }, { "content": "pub fn metadata(\n\n command_req_sender: &Sender<Command>,\n\n command_resp_receiver: &Receiver<CommandResp>,\n\n data: String,\n\n) -> Result<MetaData, String> {\n\n let _ = command_req_sender.send(Command::Metadata(data));\n\n match command_resp_receiver.recv().unwrap() {\n\n CommandResp::Metadata(r) => r,\n\n _ => unimplemented!(),\n\n }\n\n}\n\n\n", "file_path": "cita-executor/core/src/libexecutor/command.rs", "rank": 47, "score": 160669.88478092873 }, { "content": "#[cfg(not(any(target_os = \"macos\", target_os = \"ios\", target_os = \"linux\")))]\n\npub fn set_fd_limit() {}\n", "file_path": "cita-jsonrpc/src/fdlimit.rs", "rank": 48, "score": 160669.88478092873 }, { "content": "pub fn balance_at(\n\n command_req_sender: &Sender<Command>,\n\n command_resp_receiver: &Receiver<CommandResp>,\n\n address: Address,\n\n block_tag: BlockTag,\n\n) -> Option<Bytes> {\n\n let _ = command_req_sender.send(Command::BalanceAt(address, block_tag));\n\n match command_resp_receiver.recv().unwrap() {\n\n CommandResp::BalanceAt(r) => r,\n\n _ => unimplemented!(),\n\n }\n\n}\n\n\n", "file_path": "cita-executor/core/src/libexecutor/command.rs", "rank": 49, "score": 160669.88478092873 }, { "content": "#[allow(unknown_lints, clippy::implicit_hasher)] // TODO clippy\n\npub fn check_permission(\n\n group_accounts: &HashMap<Address, Vec<Address>>,\n\n account_permissions: &HashMap<Address, Vec<Resource>>,\n\n t: &SignedTransaction,\n\n options: CheckOptions,\n\n) -> Result<(), AuthenticationError> {\n\n let sender = *t.sender();\n\n // It's eth_call when the account is zero.\n\n // No need to check the options in case that the option is true.\n\n if sender == Address::zero() {\n\n return Ok(());\n\n }\n\n\n\n if options.send_tx_permission {\n\n check_send_tx(group_accounts, account_permissions, &sender)?;\n\n }\n\n\n\n match t.action {\n\n Action::Create => {\n\n if options.create_contract_permission {\n", "file_path": "cita-executor/core/src/authentication.rs", "rank": 50, "score": 160669.88478092873 }, { "content": "pub fn eth_call(\n\n command_req_sender: &Sender<Command>,\n\n command_resp_receiver: &Receiver<CommandResp>,\n\n call_request: CallRequest,\n\n block_tag: BlockTag,\n\n) -> Result<Bytes, String> {\n\n let _ = command_req_sender.send(Command::ETHCall(call_request, block_tag));\n\n match command_resp_receiver.recv().unwrap() {\n\n CommandResp::ETHCall(r) => r,\n\n _ => unimplemented!(),\n\n }\n\n}\n\n\n", "file_path": "cita-executor/core/src/libexecutor/command.rs", "rank": 51, "score": 158838.72749839627 }, { "content": "pub fn generate_signed_transaction(\n\n to: Address,\n\n data: Vec<u8>,\n\n nonce: u32,\n\n privkey: PrivKey,\n\n) -> libproto::SignedTransaction {\n\n let mut transaction = libproto::Transaction::new();\n\n transaction.set_nonce(U256::from(nonce).lower_hex());\n\n transaction.set_data(data);\n\n transaction.set_valid_until_block(100);\n\n transaction.set_quota(1844674);\n\n if to == Address::from(0) {\n\n // create or call contract\n\n transaction.set_to(String::from(\"\"));\n\n } else {\n\n // transfer to someone\n\n transaction.set_to(to.lower_hex());\n\n }\n\n\n\n let proto_signed_transaction: libproto::SignedTransaction = transaction.sign(privkey);\n\n proto_signed_transaction\n\n}\n\n\n", "file_path": "cita-executor/src/tests/helpers.rs", "rank": 52, "score": 158838.72749839627 }, { "content": "pub fn economical_model(\n\n command_req_sender: &Sender<Command>,\n\n command_resp_receiver: &Receiver<CommandResp>,\n\n) -> EconomicalModel {\n\n let _ = command_req_sender.send(Command::EconomicalModel);\n\n match command_resp_receiver.recv().unwrap() {\n\n CommandResp::EconomicalModel(r) => r,\n\n _ => unimplemented!(),\n\n }\n\n}\n\n\n", "file_path": "cita-executor/core/src/libexecutor/command.rs", "rank": 53, "score": 158838.72749839627 }, { "content": "pub fn sign_call(\n\n command_req_sender: &Sender<Command>,\n\n command_resp_receiver: &Receiver<CommandResp>,\n\n call_request: CallRequest,\n\n) -> SignedTransaction {\n\n let _ = command_req_sender.send(Command::SignCall(call_request));\n\n match command_resp_receiver.recv().unwrap() {\n\n CommandResp::SignCall(r) => r,\n\n _ => unimplemented!(),\n\n }\n\n}\n\n\n", "file_path": "cita-executor/core/src/libexecutor/command.rs", "rank": 54, "score": 158838.72749839627 }, { "content": "pub fn cita_send_transaction(\n\n upstream: &UpStream,\n\n utx: &UnverifiedTransaction,\n\n) -> Result<H256, Error> {\n\n let tx_bytes: Vec<u8> = utx.try_into().unwrap();\n\n let req = rpc_request::SendRawTransactionParams::new(tx_bytes.into()).into_request(1);\n\n let result = rpc_send_and_get_result_from_reply!(upstream, req, rpc_types::TxResponse);\n\n if result.status.to_uppercase() == \"OK\" {\n\n Ok(result.hash)\n\n } else {\n\n Err(Error::BadStatus)\n\n }\n\n}\n", "file_path": "tools/relayer-parser/src/communication.rs", "rank": 55, "score": 158838.72749839627 }, { "content": "pub fn create_block(\n\n executor: &Executor,\n\n to: Address,\n\n data: &Vec<u8>,\n\n nonce: (u32, u32),\n\n privkey: &PrivKey,\n\n) -> OpenBlock {\n\n let mut block = OpenBlock::default();\n\n\n\n block.set_parent_hash(executor.get_current_hash());\n\n block.set_timestamp(AsMillis::as_millis(&UNIX_EPOCH.elapsed().unwrap()));\n\n block.set_number(executor.get_current_height() + 1);\n\n // header.proof= ?;\n\n\n\n let mut body = BlockBody::default();\n\n let mut txs = Vec::new();\n\n\n\n for i in nonce.0..nonce.1 {\n\n let mut tx = blockchain::Transaction::new();\n\n if to == Address::from(0) {\n", "file_path": "cita-executor/core/src/tests/helpers.rs", "rank": 56, "score": 158838.72749839627 }, { "content": "pub fn init_executor2(\n\n fsm_req_receiver: Receiver<OpenBlock>,\n\n fsm_resp_sender: Sender<ClosedBlock>,\n\n command_req_receiver: Receiver<command::Command>,\n\n command_resp_sender: Sender<command::CommandResp>,\n\n) -> Executor {\n\n // FIXME temp dir should be removed automatically, but at present it is not\n\n let tempdir = TempDir::new(\"init_executor\").unwrap().into_path();\n\n let genesis_path = Path::new(SCRIPTS_DIR).join(\"config_tool/genesis/genesis.json\");\n\n\n\n let mut data_path = tempdir.clone();\n\n data_path.push(\"data\");\n\n env::set_var(\"DATA_PATH\", data_path);\n\n let executor = Executor::init(\n\n genesis_path.to_str().unwrap(),\n\n tempdir.to_str().unwrap().to_string(),\n\n fsm_req_receiver,\n\n fsm_resp_sender,\n\n command_req_receiver,\n\n command_resp_sender,\n\n false,\n\n );\n\n executor\n\n}\n\n\n", "file_path": "cita-executor/core/src/tests/helpers.rs", "rank": 57, "score": 158838.72749839627 }, { "content": "pub fn estimate_quota(\n\n command_req_sender: &Sender<Command>,\n\n command_resp_receiver: &Receiver<CommandResp>,\n\n call_request: CallRequest,\n\n block_tag: BlockTag,\n\n) -> Result<Bytes, String> {\n\n let _ = command_req_sender.send(Command::EstimateQuota(call_request, block_tag));\n\n match command_resp_receiver.recv().unwrap() {\n\n CommandResp::EstimateQuota(r) => r,\n\n _ => unimplemented!(),\n\n }\n\n}\n\n\n", "file_path": "cita-executor/core/src/libexecutor/command.rs", "rank": 58, "score": 158838.72749839627 }, { "content": "pub fn gen_state(\n\n command_req_sender: &Sender<Command>,\n\n command_resp_receiver: &Receiver<CommandResp>,\n\n root: H256,\n\n parent_hash: H256,\n\n) -> Option<CitaState<CitaTrieDB>> {\n\n let _ = command_req_sender.send(Command::GenState(root, parent_hash));\n\n match command_resp_receiver.recv().unwrap() {\n\n CommandResp::GenState(r) => r,\n\n _ => unimplemented!(),\n\n }\n\n}\n\n\n", "file_path": "cita-executor/core/src/libexecutor/command.rs", "rank": 59, "score": 158838.72749839627 }, { "content": "pub fn chain_id(\n\n command_req_sender: &Sender<Command>,\n\n command_resp_receiver: &Receiver<CommandResp>,\n\n) -> Option<ChainId> {\n\n let _ = command_req_sender.send(Command::ChainID);\n\n match command_resp_receiver.recv().unwrap() {\n\n CommandResp::ChainID(r) => r,\n\n _ => unimplemented!(),\n\n }\n\n}\n\n\n", "file_path": "cita-executor/core/src/libexecutor/command.rs", "rank": 60, "score": 158838.72749839627 }, { "content": "pub fn load_executed_result(\n\n command_req_sender: &Sender<Command>,\n\n command_resp_receiver: &Receiver<CommandResp>,\n\n height: u64,\n\n) -> ExecutedResult {\n\n let _ = command_req_sender.send(Command::LoadExecutedResult(height));\n\n match command_resp_receiver.recv().unwrap() {\n\n CommandResp::LoadExecutedResult(r) => r,\n\n _ => unimplemented!(),\n\n }\n\n}\n\n\n", "file_path": "cita-executor/core/src/libexecutor/command.rs", "rank": 61, "score": 157076.97620372527 }, { "content": "pub fn auto_exec(\n\n state: Arc<RefCell<CitaState<CitaTrieDB>>>,\n\n auto_exec_quota_limit: u64,\n\n context: Context,\n\n) {\n\n let hash = &*AUTO_EXEC_HASH;\n\n let params = ExecutiveParams {\n\n code_address: Some(*AUTO_EXEC_ADDR),\n\n sender: Address::from(0x0),\n\n to_address: Some(*AUTO_EXEC_ADDR),\n\n gas: U256::from(auto_exec_quota_limit),\n\n gas_price: U256::from(1),\n\n value: U256::from(0),\n\n nonce: U256::from(0),\n\n data: Some(hash.to_vec()),\n\n };\n\n let block_provider = EVMBlockDataProvider::new(context.clone());\n\n let vm_exec_params = build_vm_exec_params(&params, state.clone());\n\n let mut sub_state = VMSubState::default();\n\n\n", "file_path": "cita-executor/core/src/libexecutor/auto_exec.rs", "rank": 62, "score": 157076.97620372527 }, { "content": "pub fn create_transfer_meta(\n\n network_client: NetworkClient,\n\n nodes_mgr_client: NodesManagerClient,\n\n self_address: Address,\n\n) -> ProtocolMeta {\n\n MetaBuilder::default()\n\n .id(TRANSFER_PROTOCOL_ID)\n\n .codec(|| {\n\n let mut lcodec = LengthDelimitedCodec::new();\n\n lcodec.set_max_frame_length(MAX_FRAME_LENGTH);\n\n Box::new(lcodec)\n\n })\n\n .service_handle(move || {\n\n let handle = Box::new(TransferProtocol {\n\n proto_id: TRANSFER_PROTOCOL_ID,\n\n connected_session_ids: Vec::default(),\n\n network_client: network_client.clone(),\n\n nodes_mgr_client: nodes_mgr_client.clone(),\n\n self_address,\n\n });\n\n ProtocolHandle::Callback(handle)\n\n })\n\n .name(|_| \"/cita/transfer\".to_owned())\n\n .support_versions(vec![\"0.0.2\".to_owned()])\n\n .build()\n\n}\n", "file_path": "cita-network/src/p2p_protocol/transfer.rs", "rank": 63, "score": 157076.97620372527 }, { "content": "#[allow(unknown_lints, clippy::implicit_hasher)] // TODO clippy\n\npub fn contains_resource(\n\n account_permissions: &HashMap<Address, Vec<Resource>>,\n\n account: &Address,\n\n cont: Address,\n\n func: &[u8],\n\n) -> bool {\n\n match account_permissions.get(account) {\n\n Some(resources) => {\n\n let resource = Resource {\n\n cont,\n\n func: func.to_owned(),\n\n };\n\n resources.iter().any(|res| *res == resource)\n\n }\n\n None => false,\n\n }\n\n}\n\n\n\n#[cfg(test)]\n\nmod tests {\n", "file_path": "cita-executor/core/src/contracts/solc/permission_management.rs", "rank": 64, "score": 155380.75826678486 }, { "content": "/// Returns new address created from sender salt and code hash.\n\n/// See: EIP 1014.\n\npub fn create_address_from_salt_and_code_hash(\n\n address: &Address,\n\n salt: H256,\n\n code: Vec<u8>,\n\n) -> Address {\n\n let code_hash = &summary(&code[..])[..];\n\n let mut buffer = [0u8; 1 + 20 + 32 + 32];\n\n buffer[0] = 0xff;\n\n buffer[1..=20].copy_from_slice(&address[..]);\n\n buffer[(1 + 20)..(1 + 20 + 32)].copy_from_slice(&salt[..]);\n\n buffer[(1 + 20 + 32)..].copy_from_slice(code_hash);\n\n Address::from(H256::from(summary(&buffer[..]).as_slice()))\n\n}\n\n\n", "file_path": "cita-executor/core/src/cita_executive.rs", "rank": 65, "score": 153751.44547931373 }, { "content": "fn transform_logs(logs: Vec<EVMLog>) -> Vec<Log> {\n\n logs.into_iter()\n\n .map(|log| {\n\n let EVMLog(address, topics, data) = log;\n\n\n\n Log {\n\n address,\n\n topics,\n\n data,\n\n }\n\n })\n\n .collect()\n\n}\n\n\n", "file_path": "cita-executor/core/src/cita_executive.rs", "rank": 66, "score": 152428.55578377348 }, { "content": "pub fn generate_signer() -> Signer {\n\n let private_key: PrivKey = PrivKey::from_str(PRIVATE_KEY).unwrap();\n\n let signer: Signer = Signer::from(private_key);\n\n signer\n\n}\n\n\n", "file_path": "cita-executor/src/tests/helpers.rs", "rank": 67, "score": 152124.72676380372 }, { "content": "pub fn init_executor() -> Executor {\n\n let (_fsm_req_sender, fsm_req_receiver) = crossbeam_channel::unbounded();\n\n let (fsm_resp_sender, _fsm_resp_receiver) = crossbeam_channel::unbounded();\n\n let (_command_req_sender, command_req_receiver) = crossbeam_channel::bounded(0);\n\n let (command_resp_sender, _command_resp_receiver) = crossbeam_channel::bounded(0);\n\n init_executor2(\n\n fsm_req_receiver,\n\n fsm_resp_sender,\n\n command_req_receiver,\n\n command_resp_sender,\n\n )\n\n}\n\n\n", "file_path": "cita-executor/core/src/tests/helpers.rs", "rank": 68, "score": 150362.9754691327 }, { "content": "pub fn generate_block_header() -> OpenHeader {\n\n OpenHeader::default()\n\n}\n\n\n", "file_path": "cita-executor/core/src/tests/helpers.rs", "rank": 69, "score": 147032.48316923107 }, { "content": "pub fn generate_block_body() -> BlockBody {\n\n let mut stx = SignedTransaction::default();\n\n stx.data = vec![1; 200];\n\n let transactions = vec![stx; 200];\n\n BlockBody { transactions }\n\n}\n\n\n", "file_path": "cita-executor/core/src/tests/helpers.rs", "rank": 70, "score": 147032.48316923107 }, { "content": "pub fn run(config: Config) {\n\n let (tx_sub, rx_sub) = channel::unbounded();\n\n let (tx_pub, rx_pub) = channel::unbounded();\n\n start_pubsub(\n\n \"consensus\",\n\n routing_key!([Chain >> RichStatus]),\n\n tx_sub,\n\n rx_pub,\n\n );\n\n\n\n do_loop(config, &rx_sub, &tx_pub);\n\n info!(\"PASS\");\n\n}\n\n\n", "file_path": "tests/box-executor/src/runner.rs", "rank": 71, "score": 146652.68958300454 }, { "content": "/// Liquidtion for a transaction.\n\nfn liquidtion<B: DB + 'static>(\n\n state_provider: Arc<RefCell<State<B>>>,\n\n store: Arc<RefCell<VMSubState>>,\n\n sender: Address,\n\n gas_price: U256,\n\n gas_limit: u64,\n\n gas_left: u64,\n\n) -> Result<(), VMError> {\n\n trace!(\n\n \"gas_price: {:?}, gas limit:{:?}, gas left: {:?}\",\n\n gas_price,\n\n gas_limit,\n\n gas_left,\n\n );\n\n state_provider\n\n .borrow_mut()\n\n .add_balance(&sender, gas_price * gas_left)?;\n\n state_provider.borrow_mut().add_balance(\n\n &store.borrow().evm_context.coinbase,\n\n gas_price * (gas_limit - gas_left),\n\n )?;\n\n Ok(())\n\n}\n\n\n", "file_path": "cita-executor/core/src/cita_executive.rs", "rank": 72, "score": 145821.64056239295 }, { "content": "/// Returns the default interpreter configs for Constantinople.\n\npub fn get_interpreter_conf() -> InterpreterConf {\n\n let mut evm_cfg = InterpreterConf::default();\n\n evm_cfg.eip1283 = false;\n\n evm_cfg\n\n}\n", "file_path": "cita-executor/core/src/cita_vm_helper.rs", "rank": 73, "score": 145462.2308876273 }, { "content": "pub fn generate_contract() -> Vec<u8> {\n\n // let source = r#\"\n\n // pragma solidity ^0.4.8;\n\n // contract ConstructSol {\n\n // uint a;\n\n // event LogCreate(address contractAddr);\n\n // event A(uint);\n\n // function ConstructSol(){\n\n // LogCreate(this);\n\n // }\n\n // function set(uint _a) {\n\n // a = _a;\n\n // A(a);\n\n // }\n\n // function get() returns (uint) {\n\n // return a;\n\n // }\n\n // }\n\n // \"#;\n\n let bin_code = \"\\\n", "file_path": "cita-executor/src/tests/helpers.rs", "rank": 74, "score": 144890.9382883335 }, { "content": "pub fn generate_contract() -> Vec<u8> {\n\n let source = r#\"\n\n pragma solidity ^0.4.8;\n\n contract ConstructSol {\n\n uint a;\n\n event LogCreate(address contractAddr);\n\n event A(uint);\n", "file_path": "cita-executor/core/src/tests/helpers.rs", "rank": 75, "score": 143194.72035139313 }, { "content": "pub fn test_json_path(p: &str) {\n\n let info = fs::metadata(p).unwrap();\n\n if info.is_dir() {\n\n for entry in fs::read_dir(p).unwrap() {\n\n let entry = entry.unwrap();\n\n let p = entry.path();\n\n test_json_path(p.to_str().unwrap());\n\n }\n\n } else {\n\n test_json_file(p);\n\n }\n\n}\n\n\n", "file_path": "tests/json-test/src/state_test.rs", "rank": 76, "score": 143194.72035139313 }, { "content": "pub fn test_json_file(p: &str) {\n\n let f = fs::File::open(p).unwrap();\n\n let t = Test::load(f).unwrap();\n\n\n\n for (name, data) in t.into_iter() {\n\n let data_post_homestead = data.post.unwrap().homestead;\n\n if data_post_homestead.is_none() {\n\n continue;\n\n }\n\n\n\n for (i, postdata) in data_post_homestead.unwrap().iter().enumerate() {\n\n println!(\"{}::{}::{}\\n\", p, name, i);\n\n let d = Arc::new(cita_trie::MemoryDB::new(false));\n\n let mut state_provider = State::new(d).unwrap();\n\n\n\n for (address, account) in data.pre.clone().unwrap() {\n\n let balance = string_2_u256(account.balance);\n\n let code = string_2_bytes(account.code);\n\n let nonce = string_2_u256(account.nonce);\n\n if code.is_empty() {\n", "file_path": "tests/json-test/src/state_test.rs", "rank": 77, "score": 143194.72035139313 }, { "content": "pub fn clean_0x(s: &str) -> &str {\n\n if s.starts_with(\"0x\") {\n\n &s[2..]\n\n } else {\n\n s\n\n }\n\n}\n\n\n", "file_path": "tests/json-test/src/helper.rs", "rank": 78, "score": 142107.18095669197 }, { "content": "// System Convention: 0-th block's proof is `::std::usize::MAX`\n\n// Ok, I know it is tricky, but ... just keep it in mind, it is tricky ...\n\npub fn wrap_height(height: usize) -> u64 {\n\n match height {\n\n ::std::usize::MAX => 0,\n\n _ => height as u64,\n\n }\n\n}\n\n\n\n#[cfg(test)]\n\nmod tests {\n\n use super::{wrap_height, Backlog, Backlogs, Priority};\n\n use crate::core::header::OpenHeader;\n\n use crate::core::libexecutor::block::{BlockBody, ClosedBlock, ExecutedBlock, OpenBlock};\n\n use crate::core::libexecutor::sys_config::BlockSysConfig;\n\n use crate::core::TrieDB;\n\n use cita_database::{Config, RocksDB, NUM_COLUMNS};\n\n use hashable::HASH_NULL_RLP;\n\n use std::sync::Arc;\n\n\n\n fn generate_block_body() -> BlockBody {\n\n let mut stx = SignedTransaction::default();\n", "file_path": "cita-executor/src/backlogs.rs", "rank": 79, "score": 140345.42966202094 }, { "content": "pub fn select_topic(method: &str) -> String {\n\n match method {\n\n \"peerCount\" => routing_key!(Jsonrpc >> RequestNet).into(),\n\n \"peersInfo\" => routing_key!(Jsonrpc >> RequestPeersInfo).into(),\n\n \"sendRawTransaction\" | \"sendTransaction\" => routing_key!(Jsonrpc >> RequestNewTx).into(),\n\n \"getVersion\" | \"estimateQuota\" => routing_key!(Jsonrpc >> RequestRpc).into(),\n\n _ => routing_key!(Jsonrpc >> Request).into(),\n\n }\n\n}\n\n\n\n#[cfg(test)]\n\nmod test {\n\n use super::select_topic;\n\n\n\n #[test]\n\n fn test_get_topic() {\n\n assert_eq!(select_topic(\"peerCount\"), \"jsonrpc.request_net\".to_string());\n\n assert_eq!(\n\n select_topic(\"sendTransaction\"),\n\n \"jsonrpc.request_new_tx\".to_string()\n\n );\n\n assert_eq!(select_topic(\"blockNumber\"), \"jsonrpc.request\".to_string());\n\n assert_eq!(\n\n select_topic(\"getBlockByNumber\"),\n\n \"jsonrpc.request\".to_string()\n\n );\n\n assert_eq!(select_topic(\"error\"), \"jsonrpc.request\".to_string());\n\n }\n\n}\n", "file_path": "cita-jsonrpc/src/helper.rs", "rank": 80, "score": 140345.42966202094 }, { "content": "pub fn get_temp_state() -> State<MemoryDB> {\n\n let db = Arc::new(MemoryDB::new(false));\n\n State::new(db).unwrap()\n\n}\n\n\n", "file_path": "cita-executor/core/src/tests/helpers.rs", "rank": 81, "score": 139984.78290221782 }, { "content": "fn handle_preflighted(mut headers: Headers) -> Headers {\n\n use crate::http_header::{HeaderMapExt, X_REQUESTED_WITH_STR};\n\n\n\n let x_requested_with = HeaderName::from_static(X_REQUESTED_WITH_STR);\n\n let plain_text = HeaderValue::from_static(CONTENT_TYPE_PLAIN_TEXT_STR);\n\n let cors_cache = HeaderValue::from(CORS_CACHE);\n\n let allow_methods = vec![Method::POST, Method::OPTIONS];\n\n let allow_headers = vec![ORIGIN, CONTENT_TYPE, x_requested_with, USER_AGENT, ACCEPT];\n\n\n\n headers.insert(CONTENT_TYPE, plain_text);\n\n headers.insert_vec(ACCESS_CONTROL_ALLOW_METHODS, allow_methods);\n\n headers.insert_vec(ACCESS_CONTROL_ALLOW_HEADERS, allow_headers);\n\n headers.insert(ACCESS_CONTROL_MAX_AGE, cors_cache);\n\n\n\n headers\n\n}\n\n\n\npub type JsonrpcServer = hyper::Server<hyper::server::conn::AddrIncoming, JsonrpcMakeService>;\n\npub struct Server {\n\n addr: SocketAddr,\n", "file_path": "cita-jsonrpc/src/http_server.rs", "rank": 82, "score": 139487.38568493305 }, { "content": "pub fn secret_2_address(secret: &str) -> Address {\n\n let a = hex::decode(clean_0x(secret)).unwrap();\n\n let secret_key = secp256k1::SecretKey::parse_slice(a.as_slice()).unwrap();\n\n let public_key = secp256k1::PublicKey::from_secret_key(&secret_key);\n\n let serialized = public_key.serialize();\n\n let mut public = Public::default();\n\n public.copy_from_slice(&serialized[1..65]);\n\n public_2_address(&public)\n\n}\n", "file_path": "tests/json-test/src/helper.rs", "rank": 83, "score": 138649.21172508056 }, { "content": "pub fn parse_configfile(path: &str) -> Config {\n\n let config = FileConfig::load(path);\n\n let pkey = config.private_key;\n\n let servers = config\n\n .chains\n\n .into_iter()\n\n .map(|c| (c.id, c.servers))\n\n .collect();\n\n Config { pkey, servers }\n\n}\n", "file_path": "tools/relayer-parser/src/configuration.rs", "rank": 84, "score": 138649.21172508056 }, { "content": "pub fn public_2_address(public: &Public) -> Address {\n\n let hash = tiny_keccak::keccak256(&public.0);\n\n let mut result = Address::default();\n\n result.copy_from_slice(&hash[12..]);\n\n result\n\n}\n\n\n", "file_path": "tests/json-test/src/helper.rs", "rank": 85, "score": 138649.21172508056 }, { "content": "// only verify if tx.version > 2\n\npub fn verify_base_quota_required(tx: &Transaction) -> bool {\n\n match tx.get_version() {\n\n 0..=2 => true,\n\n _ => {\n\n let to = tx.get_to_v1();\n\n if to.is_empty() || Address::from(to) == Address::zero() {\n\n tx.get_quota() as usize\n\n >= tx.data.len() * G_TX_DATA_NON_ZERO + G_TRANSACTION + G_CREATE\n\n } else {\n\n tx.get_quota() as usize >= tx.data.len() * G_TX_DATA_NON_ZERO + G_TRANSACTION\n\n }\n\n }\n\n }\n\n}\n", "file_path": "cita-auth/src/handler.rs", "rank": 86, "score": 137014.93736211932 }, { "content": "struct AccessLog {\n\n user_agent: String,\n\n http_method: Method,\n\n http_path: String,\n\n rpc_info: Option<RpcAccessLog>,\n\n}\n\n\n", "file_path": "cita-jsonrpc/src/http_server.rs", "rank": 87, "score": 135668.76154495508 }, { "content": "pub fn build_commandline<'a>() -> clap::ArgMatches<'a> {\n\n let matches = clap_app!(RelayerParser =>\n\n (version: \"0.1\")\n\n (author: \"Rivtower Technologies\")\n\n (about: \"CITA Relay Info Parser by Rust\")\n\n (@arg ConfigFile: -f --config_file +takes_value +required \"Input a toml configuration file.\")\n\n (@arg ChainId: -c --chain_id +takes_value +required \"Input a chain id for the transaction hash.\")\n\n (@arg TxHash: -t --tx_hash +takes_value +required \"Input a hex string of the transaction hash.\")\n\n ).get_matches();\n\n trace!(\"matches = {:?}\", matches);\n\n matches\n\n}\n\n\n", "file_path": "tools/relayer-parser/src/arguments.rs", "rank": 88, "score": 134813.27843655256 }, { "content": "pub fn build_evm_context(context: &Context) -> EVMContext {\n\n EVMContext {\n\n gas_limit: context.block_quota_limit.as_u64(),\n\n coinbase: context.coin_base,\n\n number: U256::from(context.block_number),\n\n timestamp: context.timestamp,\n\n difficulty: context.difficulty,\n\n }\n\n}\n\n\n", "file_path": "cita-executor/core/src/cita_executive.rs", "rank": 89, "score": 133919.12497630352 }, { "content": "pub fn string_2_bytes(value: String) -> Vec<u8> {\n\n let v = Box::leak(value.into_boxed_str());\n\n let v = clean_0x(v);\n\n hex::decode(v).unwrap()\n\n}\n\n\n", "file_path": "tests/json-test/src/helper.rs", "rank": 90, "score": 133179.00407359132 }, { "content": "pub fn string_2_bytes(value: String) -> Vec<u8> {\n\n let v = Box::leak(value.into_boxed_str());\n\n let v = cita_types::clean_0x(v);\n\n hex::decode(v).unwrap()\n\n}\n", "file_path": "tools/create-genesis/src/common.rs", "rank": 91, "score": 133179.00407359132 }, { "content": "fn batch_forward_new_tx(\n\n new_tx_request_buffer: &mut Vec<reqlib::Request>,\n\n time_stamp: &mut SystemTime,\n\n tx_pub: &Sender<(String, Vec<u8>)>,\n\n) {\n\n trace!(\n\n \"Going to send new tx batch to auth with {} new tx and buffer time cost is {:?} \",\n\n new_tx_request_buffer.len(),\n\n time_stamp.elapsed().unwrap()\n\n );\n\n let mut batch_request = BatchRequest::new();\n\n batch_request.set_new_tx_requests(new_tx_request_buffer.clone().into());\n\n\n\n let request_id = Uuid::new_v4().as_bytes().to_vec();\n\n let mut request = reqlib::Request::new();\n\n request.set_batch_req(batch_request);\n\n request.set_request_id(request_id);\n\n\n\n let data: Message = request.into();\n\n tx_pub\n\n .send((\n\n routing_key!(Jsonrpc >> RequestNewTxBatch).into(),\n\n data.try_into().unwrap(),\n\n ))\n\n .unwrap();\n\n *time_stamp = SystemTime::now();\n\n new_tx_request_buffer.clear();\n\n}\n\n\n", "file_path": "cita-jsonrpc/src/main.rs", "rank": 92, "score": 132035.31672907047 }, { "content": "struct SingleRpcAccessLog {\n\n id: RpcId,\n\n method: Option<String>,\n\n}\n\n\n", "file_path": "cita-jsonrpc/src/http_server.rs", "rank": 93, "score": 131904.66869742435 }, { "content": "struct BatchRpcAccessLog {\n\n count: Option<usize>,\n\n}\n\n\n\nimpl From<MQAccessLog> for RpcAccessLog {\n\n fn from(mq_log: MQAccessLog) -> Self {\n\n match mq_log {\n\n MQAccessLog::Single { id, method } => {\n\n RpcAccessLog::Single(SingleRpcAccessLog { id, method })\n\n }\n\n MQAccessLog::Batch { count } => RpcAccessLog::Batch(BatchRpcAccessLog { count }),\n\n }\n\n }\n\n}\n\n\n\nimpl AccessLog {\n\n pub fn new(http_method: &Method, http_path: &str, http_headers: &Headers) -> Self {\n\n let user_agent = http_headers\n\n .get(USER_AGENT)\n\n .and_then(|u| u.to_str().ok())\n", "file_path": "cita-jsonrpc/src/http_server.rs", "rank": 94, "score": 131904.66869742435 }, { "content": "/// Parse solidity return data `uint256` to rust `u64`\n\npub fn to_u64(output: &[u8]) -> Option<u64> {\n\n to_u256(output).map(|x| x.low_u64())\n\n}\n\n\n", "file_path": "cita-executor/core/src/contracts/tools/decode.rs", "rank": 95, "score": 131603.34098737728 }, { "content": "/// Parse solidity return data `uint256` to rust `u32`\n\npub fn to_u32(output: &[u8]) -> Option<u32> {\n\n to_u256(output).map(|x| x.low_u32())\n\n}\n\n\n", "file_path": "cita-executor/core/src/contracts/tools/decode.rs", "rank": 96, "score": 131603.34098737728 }, { "content": "/// Parse solidity return data `Address` to rust `Address`\n\npub fn to_address(output: &[u8]) -> Option<Address> {\n\n decode(&[ParamType::Address], output)\n\n .ok()\n\n .and_then(|decoded| decoded.first().cloned())\n\n .and_then(Token::to_address)\n\n .map(Address::from)\n\n}\n", "file_path": "cita-executor/core/src/contracts/tools/decode.rs", "rank": 97, "score": 131603.34098737728 }, { "content": "pub fn skip_json_path(_reason: &str, _name: &str) {}\n\n\n\n#[cfg(test)]\n\nmod tests {\n\n\n\n #[cfg(feature = \"sha3hash\")]\n\n #[test]\n\n fn test_json_state() {\n\n use super::{skip_json_path, test_json_path};\n\n skip_json_path(\n\n \"version above homestead\",\n\n r\"../jsondata/GeneralStateTests/stArgsZeroOneBalance\",\n\n );\n\n skip_json_path(\n\n \"version above homestead\",\n\n r\"../jsondata/GeneralStateTests/stPreCompiledContracts\",\n\n );\n\n skip_json_path(\n\n \"version above homestead\",\n\n r\"../jsondata/GeneralStateTests/stSStoreTest\",\n", "file_path": "tests/json-test/src/state_test.rs", "rank": 98, "score": 130083.19168777553 } ]
Rust
src/gameboy/cpu/register.rs
Hanaasagi/NGC-224
24a3c439148ffef0930e19c9d88c68a9164a5459
use super::super::Term; #[derive(Default, Debug, Clone)] #[allow(non_snake_case)] pub struct Register { A: u8, B: u8, C: u8, D: u8, E: u8, F: u8, H: u8, L: u8, PC: u16, SP: u16, } impl Register { pub fn new() -> Self { Self::default() } pub fn new_from_debug_string(s: &str) -> Self { let mut reg = Self::new(); let s = &s[11..s.len() - 2]; for field in s.split(", ") { let tmp: Vec<&str> = field.split(": ").collect(); let name = tmp[0].to_uppercase(); let value: u16 = tmp[1].parse().unwrap(); match &name as &str { "A" => reg.A = value as u8, "B" => reg.B = value as u8, "C" => reg.C = value as u8, "D" => reg.D = value as u8, "E" => reg.E = value as u8, "F" => reg.F = value as u8, "H" => reg.H = value as u8, "L" => reg.L = value as u8, "PC" => reg.PC = value, "SP" => reg.SP = value, _ => panic!("{} is unknown field", name), } } reg } pub fn init(&mut self, term: Term) { match term { Term::GB => { self.A = 0x01; } Term::GBP => { self.A = 0xff; } Term::GBC => { self.A = 0x11; } Term::SGB => { self.A = 0x01; } } self.B = 0x00; self.C = 0x13; self.D = 0x00; self.E = 0xD8; self.F = 0xB0; self.H = 0x01; self.L = 0x4D; self.PC = 0x0100; self.SP = 0xFFFE; } } #[allow(non_snake_case)] impl Register { #[inline] pub fn get_A(&self) -> u8 { self.A } #[inline] pub fn get_B(&self) -> u8 { self.B } #[inline] pub fn get_C(&self) -> u8 { self.C } #[inline] pub fn get_D(&self) -> u8 { self.D } #[inline] pub fn get_E(&self) -> u8 { self.E } #[inline] pub fn get_H(&self) -> u8 { self.H } #[inline] pub fn get_L(&self) -> u8 { self.L } #[inline] pub fn get_PC(&self) -> u16 { self.PC } #[inline] pub fn get_SP(&self) -> u16 { self.SP } #[inline] pub fn incr_PC(&mut self) { self.PC += 1; } #[inline] pub fn get_AF(&self) -> u16 { (u16::from(self.A) << 8) | u16::from(self.F) } #[inline] pub fn get_BC(&self) -> u16 { (u16::from(self.B) << 8) | u16::from(self.C) } #[inline] pub fn get_DE(&self) -> u16 { (u16::from(self.D) << 8) | u16::from(self.E) } #[inline] pub fn get_HL(&self) -> u16 { (u16::from(self.H) << 8) | u16::from(self.L) } } #[allow(non_snake_case)] impl Register { #[inline] pub fn set_A(&mut self, v: u8) { self.A = v } #[inline] pub fn set_B(&mut self, v: u8) { self.B = v } #[inline] pub fn set_C(&mut self, v: u8) { self.C = v } #[inline] pub fn set_D(&mut self, v: u8) { self.D = v } #[inline] pub fn set_E(&mut self, v: u8) { self.E = v } #[inline] pub fn set_H(&mut self, v: u8) { self.H = v } #[inline] pub fn set_L(&mut self, v: u8) { self.L = v } #[inline] pub fn set_AF(&mut self, v: u16) { self.A = (v >> 8) as u8; self.F = (v & 0x00f0) as u8; } #[inline] pub fn set_BC(&mut self, v: u16) { self.B = (v >> 8) as u8; self.C = (v & 0x00ff) as u8; } #[inline] pub fn set_DE(&mut self, v: u16) { self.D = (v >> 8) as u8; self.E = (v & 0x00ff) as u8; } #[inline] pub fn set_HL(&mut self, v: u16) { self.H = (v >> 8) as u8; self.L = (v & 0x00ff) as u8; } #[inline] pub fn incr_HL(&mut self) { self.set_HL(self.get_HL().wrapping_add(1)); } #[inline] pub fn set_PC(&mut self, v: u16) { self.PC = v } #[inline] pub fn set_SP(&mut self, v: u16) { self.SP = v } } impl Register { #[inline] pub fn is_flag_set(&self, flag: Flag) -> bool { (self.F & flag.value()) != 0 } pub fn set_flag(&mut self, flag: Flag) { self.F = self.F | (flag.value()); } pub fn unset_flag(&mut self, flag: Flag) { self.F = self.F & !(flag.value()) } pub fn reverse_flag(&mut self, flag: Flag) { if self.is_flag_set(flag.clone()) { self.unset_flag(flag); } else { self.set_flag(flag); } } } #[derive(Clone, Debug)] pub enum Flag { Zero = 0b1000_0000, Sub = 0b0100_0000, HalfCarry = 0b0010_0000, Carry = 0b0001_0000, } impl Flag { pub fn into_value(self) -> u8 { self as u8 } pub fn value(&self) -> u8 { self.clone() as u8 } } #[rustfmt::skip] #[derive(Clone)] pub enum IntFlag { VBlank = 0b0000, LCDStat = 0b0001, Timer = 0b0010, Serial = 0b0011, Joypad = 0b0100, } pub struct IntReg { pub data: u8, } impl IntReg { pub fn new() -> Self { Self { data: 0x00 } } pub fn req(&mut self, flag: IntFlag) { self.data |= 1 << flag as u8; } }
use super::super::Term; #[derive(Default, Debug, Clone)] #[allow(non_snake_case)] pub struct Register { A: u8, B: u8, C: u8, D: u8, E: u8, F: u8, H: u8, L: u8, PC: u16, SP: u16, } impl Register { pub fn new() -> Self { Self::default() } pub fn new_from_debug_string(s: &str) -> Self { let mut reg = Self::new(); let s = &s[11..s.len() - 2]; for field in s.split(", ") { let tmp: Vec<&str> = field.split(": ").collect(); let name = tmp[0].to_uppercase(); let value: u16 = tmp[1].parse().unwrap(); match &name as &str { "A" => reg.A = value as u8, "B" => reg.B = value as u8, "C" => reg.C = value as u8, "D" => reg.D = value as u8, "E" => reg.E = value as u8, "F" => reg.F = value as u8, "H" => reg.H = value as u8, "L" => reg.L = value as u8, "PC" => reg.PC = value, "SP" => reg.SP = value, _ => panic!("{} is unknown field", name), } } reg } pub fn init(&mut self, term: Term) { match term { Term::GB => { self.A = 0x01; } Term::GBP => { self.A = 0xff; } Term::GBC => { self.A = 0x11; } Term::SGB => { self.A = 0x01; } } self.B = 0x00; self.C = 0x13; self.D = 0x00; self.E = 0xD8; self.F = 0xB0; self.H = 0x01; self.L = 0x4D; self.PC = 0x0100; self.SP = 0xFFFE; } } #[allow(non_snake_case)] impl Register { #[inline] pub fn get_A(&self) -> u8 { self.A } #[inline] pub fn get_B(&self) -> u8 { self.B } #[inline] pub fn get_C(&self) -> u8 { self.C } #[inline] pub fn get_D(&self) -> u8 { self.D } #[inline] pub fn get_E(&self) -> u8 { self.E } #[inline] pub fn get_H(&self) -> u8 { self.H } #[inline] pub fn get_L(&self) -> u8 { self.L } #[inline] pub fn get_PC(&self) -> u16 { self.PC } #[inline] pub fn get_SP(&self) -> u16 { self.SP } #[inline] pub fn incr_PC(&mut self) { self.PC += 1; } #[inline] pub fn get_AF(&self) -> u16 { (u16::from(self.A) << 8) | u16::from(self.F) } #[inline] pub fn get_BC(&self) -> u16 { (u16::from(self.B) << 8) | u16::from(self.C) } #[inline] pub fn get_DE(&self) -> u16 { (u16::from(self.D) << 8) | u16::from(self.E) } #[inline] pub fn get_HL(&self) -> u16 { (u16::from(self.H) << 8) | u16::from(self.L) } } #[allow(non_snake_case)] impl Register { #[inline] pub fn set_A(&mut self, v: u8) { self.A = v } #[inline] pub fn set_B(&mut self, v: u8) { self.B = v } #[inline] pub fn set_C(&mut self, v: u8) { self.C = v } #[inline] pub fn set_D(&mut self, v: u8) { self.D = v } #[inline] pub fn set_E(&mut self, v: u8) { self.E = v } #[inline] pub fn set_H(&mut self, v: u8) { self.H = v } #[inline] pub fn set_L(&mut self, v: u8) { self.L = v } #[inline] pub fn set_AF(&mut self, v: u16) { self.A = (v >> 8) as u8; self.F = (v & 0x00f0) as u8; } #[inline] pub fn set_BC(&mut self, v: u16) { self.B = (v >> 8) as u8; self.C = (v & 0x00ff) as u8; } #[inline] pub fn set_DE(&mut self, v: u16) { self.D = (v >> 8) as u8; self.E = (v & 0x00ff) as u8; } #[inline] pub fn set_HL(&mut self, v: u16) { self.H = (v >> 8) as u8; self.L = (v & 0x00ff) as u8; } #[inline] pub fn incr_HL(&mut self) { self.set_HL(self.get_HL().wrapping_add(1)); } #[inline] pub fn set_PC(&mut self, v: u16) { self.PC = v } #[inline] pub fn set_SP(&mut self, v: u16) { self.SP = v } } impl Register { #[inline] pub fn is_flag_set(&self, flag: Flag) -> bool { (self.F & flag.value()) != 0 } pub fn set_flag(&mut self, flag: Flag) { self.F = self.F | (flag.value()); } pub fn unset_flag(&mut self, flag: Flag) { self.F = self.F & !(flag.value()) }
} #[derive(Clone, Debug)] pub enum Flag { Zero = 0b1000_0000, Sub = 0b0100_0000, HalfCarry = 0b0010_0000, Carry = 0b0001_0000, } impl Flag { pub fn into_value(self) -> u8 { self as u8 } pub fn value(&self) -> u8 { self.clone() as u8 } } #[rustfmt::skip] #[derive(Clone)] pub enum IntFlag { VBlank = 0b0000, LCDStat = 0b0001, Timer = 0b0010, Serial = 0b0011, Joypad = 0b0100, } pub struct IntReg { pub data: u8, } impl IntReg { pub fn new() -> Self { Self { data: 0x00 } } pub fn req(&mut self, flag: IntFlag) { self.data |= 1 << flag as u8; } }
pub fn reverse_flag(&mut self, flag: Flag) { if self.is_flag_set(flag.clone()) { self.unset_flag(flag); } else { self.set_flag(flag); } }
function_block-full_function
[ { "content": "#[inline]\n\npub fn test_bit(v: u8, b: u8) -> bool {\n\n assert!(b <= 7);\n\n v & (1 << b) != 0\n\n}\n\n\n\n/// modify the bit to 0.\n", "file_path": "src/gameboy/util.rs", "rank": 0, "score": 184909.29057740478 }, { "content": "#[inline]\n\npub fn clear_bit(v: u8, b: u8) -> u8 {\n\n assert!(b <= 7);\n\n\n\n v & !(1 << b)\n\n}\n\n\n\n/// modify the bit to 1.\n", "file_path": "src/gameboy/util.rs", "rank": 1, "score": 157091.57038745974 }, { "content": "#[inline]\n\npub fn set_bit(v: u8, b: u8) -> u8 {\n\n assert!(b <= 7);\n\n v | (1 << b)\n\n}\n\n\n\n#[cfg(test)]\n\nmod tests {\n\n use super::*;\n\n\n\n #[test]\n\n fn test_clear_bit() {\n\n assert!(clear_bit(0b0011, 1) == 0b0001);\n\n }\n\n #[test]\n\n fn test_test_bit() {\n\n assert!(test_bit(0b0011, 1) == true);\n\n }\n\n\n\n #[test]\n\n fn test_set_bit() {\n\n assert!(set_bit(0b0011, 3) == 0b1011);\n\n }\n\n}\n", "file_path": "src/gameboy/util.rs", "rank": 2, "score": 157091.57038745974 }, { "content": "pub fn get_global_term() -> Term {\n\n unsafe { NOW_TERM }\n\n}\n\n\n", "file_path": "src/gameboy/spec.rs", "rank": 3, "score": 134497.43630046753 }, { "content": "pub fn set_global_term(t: Term) {\n\n unsafe {\n\n warn!(\n\n \"Change the Emulator from {:?} to {:?}, it will affect global\",\n\n NOW_TERM, t\n\n );\n\n NOW_TERM = t\n\n }\n\n}\n", "file_path": "src/gameboy/spec.rs", "rank": 4, "score": 129667.05205114128 }, { "content": "pub fn dump_cpu_record(file_path: impl AsRef<Path>) {\n\n let f = File::create(file_path).unwrap();\n\n let mut f = LineWriter::new(f);\n\n let data = CPU_RECORD.lock().unwrap();\n\n for line in data.iter() {\n\n f.write(format!(\"{:?}\\n\", line).as_bytes())\n\n .expect(\"write file failed\");\n\n }\n\n f.flush().expect(\"flush file failed\");\n\n}\n\n\n\npub struct Inspector {\n\n rl: Editor<()>,\n\n flag: Arc<AtomicBool>,\n\n}\n\n\n\nimpl Inspector {\n\n pub fn new() -> Self {\n\n Self {\n\n rl: Editor::new(),\n", "file_path": "src/gameboy/debug.rs", "rank": 5, "score": 124120.92822990663 }, { "content": "pub fn insert_cpu_record(record: CPUDebugInfo) {\n\n let data = CPU_RECORD.lock();\n\n if data.is_err() {\n\n error!(\"insert the cpu debug info failed {:?}, skip\", data.err());\n\n return;\n\n }\n\n let mut q = data.unwrap();\n\n\n\n if q.len() >= RECORE_LIMIT {\n\n q.pop_front();\n\n }\n\n q.push_back(record);\n\n}\n\n\n", "file_path": "src/gameboy/debug.rs", "rank": 6, "score": 105176.11180774379 }, { "content": "#[derive(Default)]\n\nstruct TimerRegister {\n\n // This register is incremented at rate of 16384Hz (~16779Hz on SGB). Writing any value to this register resets it\n\n // to 00h.\n\n // Note: The divider is affected by CGB double speed mode, and will increment at 32768Hz in double speed.\n\n div: u8,\n\n // This timer is incremented by a clock frequency specified by the TAC register ($FF07). When the value overflows\n\n // (gets bigger than FFh) then it will be reset to the value specified in TMA (FF06), and an interrupt will be\n\n // requested, as described below.\n\n tima: u8,\n\n // When the TIMA overflows, this data will be loaded.\n\n tma: u8,\n\n // Bit 2 - Timer Enable\n\n // Bits 1-0 - Input Clock Select\n\n // 00: CPU Clock / 1024 (DMG, CGB: 4096 Hz, SGB: ~4194 Hz)\n\n // 01: CPU Clock / 16 (DMG, CGB: 262144 Hz, SGB: ~268400 Hz)\n\n // 10: CPU Clock / 64 (DMG, CGB: 65536 Hz, SGB: ~67110 Hz)\n\n // 11: CPU Clock / 256 (DMG, CGB: 16384 Hz, SGB: ~16780 Hz)\n\n tac: u8,\n\n}\n\n\n", "file_path": "src/gameboy/timer.rs", "rank": 7, "score": 86835.01845520044 }, { "content": "pub fn load_cartridge_from_file(file_path: impl AsRef<Path>) -> Box<dyn Cartridge> {\n\n info!(\"Loading cartridge from {:?}\", file_path.as_ref().to_str());\n\n CartridgeFactory::new_catridge(file_path)\n\n}\n", "file_path": "src/gameboy/cartridge/mod.rs", "rank": 8, "score": 84931.34385695145 }, { "content": "#[test]\n\nfn test_opcode_0X4F() {\n\n let mem = Rc::new(RefCell::new(FakeMemory::new()));\n\n let reg = Register::new_from_debug_string(\n\n \"register { a: 0, b: 12, c: 0, d: 62, e: 141, f: 0, h: 86, l: 130, pc: 16044, sp: 57327 }\",\n\n );\n\n mem.borrow_mut().fake_data(65295, 0);\n\n mem.borrow_mut().fake_data(65535, 13);\n\n mem.borrow_mut().fake_data(16044, 201);\n\n let mut cpu = CPU::new(mem, false);\n\n cpu.set_reg(reg);\n\n cpu.op_0x4F();\n\n assert_eq!(\n\n format!(\"{:?}\", cpu.get_reg_snapshot()).to_lowercase(),\n\n \"register { a: 0, b: 12, c: 0, d: 62, e: 141, f: 0, h: 86, l: 130, pc: 16044, sp: 57327 }\"\n\n );\n\n}\n", "file_path": "tests/opcodes.rs", "rank": 9, "score": 69080.93015713694 }, { "content": "#[test]\n\nfn test_opcode_0X0C() {\n\n let mem = Rc::new(RefCell::new(FakeMemory::new()));\n\n let reg = Register::new_from_debug_string(\n\n \"register { a: 62, b: 10, c: 128, d: 0, e: 216, f: 192, h: 75, l: 252, pc: 19447, sp: 57341 }\",\n\n );\n\n mem.borrow_mut().fake_data(19447, 5);\n\n let mut cpu = CPU::new(mem, false);\n\n cpu.set_reg(reg);\n\n cpu.op_0x0C();\n\n assert_eq!(\n\n format!(\"{:?}\", cpu.get_reg_snapshot()).to_lowercase(),\n\n \"register { a: 62, b: 10, c: 129, d: 0, e: 216, f: 0, h: 75, l: 252, pc: 19447, sp: 57341 }\"\n\n );\n\n}\n", "file_path": "tests/opcodes.rs", "rank": 10, "score": 69080.93015713694 }, { "content": "#[test]\n\nfn test_opcode_0X0B() {\n\n let mem = Rc::new(RefCell::new(FakeMemory::new()));\n\n let reg = Register::new_from_debug_string(\n\n \"register { a: 0, b: 32, c: 0, d: 0, e: 216, f: 160, h: 192, l: 1, pc: 8068, sp: 57343 }\",\n\n );\n\n mem.borrow_mut().fake_data(8068, 120);\n\n let mut cpu = CPU::new(mem, false);\n\n cpu.set_reg(reg);\n\n cpu.op_0x0B();\n\n assert_eq!(\n\n format!(\"{:?}\", cpu.get_reg_snapshot()).to_lowercase(),\n\n \"register { a: 0, b: 31, c: 255, d: 0, e: 216, f: 160, h: 192, l: 1, pc: 8068, sp: 57343 }\"\n\n );\n\n}\n", "file_path": "tests/opcodes.rs", "rank": 11, "score": 69080.93015713694 }, { "content": "#[test]\n\nfn test_opcode_0X3C() {\n\n let mem = Rc::new(RefCell::new(FakeMemory::new()));\n\n let reg = Register::new_from_debug_string(\n\n \"register { a: 128, b: 20, c: 13, d: 0, e: 12, f: 192, h: 152, l: 1, pc: 24886, sp: 57333 }\",\n\n );\n\n mem.borrow_mut().fake_data(24886, 5);\n\n let mut cpu = CPU::new(mem, false);\n\n cpu.set_reg(reg);\n\n cpu.op_0x3C();\n\n assert_eq!(\n\n format!(\"{:?}\", cpu.get_reg_snapshot()).to_lowercase(),\n\n \"register { a: 129, b: 20, c: 13, d: 0, e: 12, f: 0, h: 152, l: 1, pc: 24886, sp: 57333 }\"\n\n );\n\n}\n", "file_path": "tests/opcodes.rs", "rank": 12, "score": 69080.93015713694 }, { "content": "#[test]\n\nfn test_opcode_0X7B() {\n\n let mem = Rc::new(RefCell::new(FakeMemory::new()));\n\n let reg = Register::new_from_debug_string(\n\n \"register { a: 0, b: 0, c: 138, d: 0, e: 0, f: 192, h: 204, l: 82, pc: 32343, sp: 57337 }\",\n\n );\n\n mem.borrow_mut().fake_data(65295, 0);\n\n mem.borrow_mut().fake_data(65535, 13);\n\n mem.borrow_mut().fake_data(32343, 34);\n\n let mut cpu = CPU::new(mem, false);\n\n cpu.set_reg(reg);\n\n cpu.op_0x7B();\n\n assert_eq!(\n\n format!(\"{:?}\", cpu.get_reg_snapshot()).to_lowercase(),\n\n \"register { a: 0, b: 0, c: 138, d: 0, e: 0, f: 192, h: 204, l: 82, pc: 32343, sp: 57337 }\"\n\n );\n\n}\n", "file_path": "tests/opcodes.rs", "rank": 13, "score": 69080.93015713694 }, { "content": "#[test]\n\nfn test_opcode_0X1E() {\n\n let mem = Rc::new(RefCell::new(FakeMemory::new()));\n\n let reg = Register::new_from_debug_string(\n\n \"register { a: 48, b: 16, c: 138, d: 62, e: 141, f: 128, h: 100, l: 248, pc: 24575, sp: 57331 }\",\n\n );\n\n mem.borrow_mut().fake_data(24575, 8);\n\n mem.borrow_mut().fake_data(24576, 42);\n\n let mut cpu = CPU::new(mem, false);\n\n cpu.set_reg(reg);\n\n cpu.op_0x1E();\n\n assert_eq!(\n\n format!(\"{:?}\", cpu.get_reg_snapshot()).to_lowercase(),\n\n \"register { a: 48, b: 16, c: 138, d: 62, e: 8, f: 128, h: 100, l: 248, pc: 24576, sp: 57331 }\"\n\n );\n\n}\n", "file_path": "tests/opcodes.rs", "rank": 14, "score": 69080.93015713694 }, { "content": "#[test]\n\nfn test_opcode_0X7C() {\n\n let mem = Rc::new(RefCell::new(FakeMemory::new()));\n\n let reg = Register::new_from_debug_string(\n\n \"register { a: 19, b: 0, c: 138, d: 0, e: 0, f: 192, h: 160, l: 0, pc: 32330, sp: 57337 }\",\n\n );\n\n mem.borrow_mut().fake_data(65295, 0);\n\n mem.borrow_mut().fake_data(65535, 13);\n\n mem.borrow_mut().fake_data(32330, 234);\n\n let mut cpu = CPU::new(mem, false);\n\n cpu.set_reg(reg);\n\n cpu.op_0x7C();\n\n assert_eq!(\n\n format!(\"{:?}\", cpu.get_reg_snapshot()).to_lowercase(),\n\n \"register { a: 160, b: 0, c: 138, d: 0, e: 0, f: 192, h: 160, l: 0, pc: 32330, sp: 57337 }\"\n\n );\n\n}\n", "file_path": "tests/opcodes.rs", "rank": 15, "score": 69080.93015713694 }, { "content": "#[test]\n\nfn test_opcode_0X3E() {\n\n let mem = Rc::new(RefCell::new(FakeMemory::new()));\n\n let reg = Register::new_from_debug_string(\n\n \"register { a: 0, b: 0, c: 19, d: 0, e: 216, f: 128, h: 1, l: 77, pc: 8049, sp: 65534 }\",\n\n );\n\n mem.borrow_mut().fake_data(8049, 128);\n\n mem.borrow_mut().fake_data(8050, 224);\n\n let mut cpu = CPU::new(mem, false);\n\n cpu.set_reg(reg);\n\n cpu.op_0x3E();\n\n assert_eq!(\n\n format!(\"{:?}\", cpu.get_reg_snapshot()).to_lowercase(),\n\n \"register { a: 128, b: 0, c: 19, d: 0, e: 216, f: 128, h: 1, l: 77, pc: 8050, sp: 65534 }\"\n\n );\n\n}\n", "file_path": "tests/opcodes.rs", "rank": 16, "score": 69080.93015713694 }, { "content": "#[test]\n\nfn test_opcode_0X2F() {\n\n let mem = Rc::new(RefCell::new(FakeMemory::new()));\n\n let reg = Register::new_from_debug_string(\n\n \"register { a: 47, b: 2, c: 0, d: 25, e: 108, f: 160, h: 77, l: 238, pc: 370, sp: 57315 }\",\n\n );\n\n mem.borrow_mut().fake_data(370, 230);\n\n let mut cpu = CPU::new(mem, false);\n\n cpu.set_reg(reg);\n\n cpu.op_0x2F();\n\n assert_eq!(\n\n format!(\"{:?}\", cpu.get_reg_snapshot()).to_lowercase(),\n\n \"register { a: 208, b: 2, c: 0, d: 25, e: 108, f: 224, h: 77, l: 238, pc: 370, sp: 57315 }\"\n\n );\n\n}\n", "file_path": "tests/opcodes.rs", "rank": 17, "score": 69080.93015713694 }, { "content": "#[test]\n\nfn test_opcode_0X1B() {\n\n let mem = Rc::new(RefCell::new(FakeMemory::new()));\n\n let reg = Register::new_from_debug_string(\n\n \"register { a: 0, b: 0, c: 138, d: 27, e: 88, f: 128, h: 101, l: 8, pc: 24913, sp: 57329 }\",\n\n );\n\n mem.borrow_mut().fake_data(24913, 122);\n\n let mut cpu = CPU::new(mem, false);\n\n cpu.set_reg(reg);\n\n cpu.op_0x1B();\n\n assert_eq!(\n\n format!(\"{:?}\", cpu.get_reg_snapshot()).to_lowercase(),\n\n \"register { a: 0, b: 0, c: 138, d: 27, e: 87, f: 128, h: 101, l: 8, pc: 24913, sp: 57329 }\"\n\n );\n\n}\n", "file_path": "tests/opcodes.rs", "rank": 18, "score": 69080.93015713694 }, { "content": "#[test]\n\nfn test_opcode_0X6F() {\n\n let mem = Rc::new(RefCell::new(FakeMemory::new()));\n\n let reg = Register::new_from_debug_string(\n\n \"register { a: 43, b: 0, c: 138, d: 127, e: 58, f: 0, h: 127, l: 57, pc: 32373, sp: 57337 }\",\n\n );\n\n mem.borrow_mut().fake_data(65295, 0);\n\n mem.borrow_mut().fake_data(65535, 13);\n\n mem.borrow_mut().fake_data(32373, 19);\n\n let mut cpu = CPU::new(mem, false);\n\n cpu.set_reg(reg);\n\n cpu.op_0x6F();\n\n assert_eq!(\n\n format!(\"{:?}\", cpu.get_reg_snapshot()).to_lowercase(),\n\n \"register { a: 43, b: 0, c: 138, d: 127, e: 58, f: 0, h: 127, l: 43, pc: 32373, sp: 57337 }\"\n\n );\n\n}\n", "file_path": "tests/opcodes.rs", "rank": 19, "score": 69080.93015713694 }, { "content": "#[test]\n\nfn test_opcode_0X7E() {\n\n let mem = Rc::new(RefCell::new(FakeMemory::new()));\n\n let reg = Register::new_from_debug_string(\n\n \"register { a: 0, b: 0, c: 138, d: 62, e: 141, f: 128, h: 100, l: 248, pc: 24556, sp: 57333 }\",\n\n );\n\n mem.borrow_mut().fake_data(25848, 137);\n\n mem.borrow_mut().fake_data(24556, 230);\n\n let mut cpu = CPU::new(mem, false);\n\n cpu.set_reg(reg);\n\n cpu.op_0x7E();\n\n assert_eq!(\n\n format!(\"{:?}\", cpu.get_reg_snapshot()).to_lowercase(),\n\n \"register { a: 137, b: 0, c: 138, d: 62, e: 141, f: 128, h: 100, l: 248, pc: 24556, sp: 57333 }\"\n\n );\n\n}\n", "file_path": "tests/opcodes.rs", "rank": 20, "score": 69080.93015713694 }, { "content": "#[test]\n\nfn test_opcode_0X6B() {\n\n let mem = Rc::new(RefCell::new(FakeMemory::new()));\n\n let reg = Register::new_from_debug_string(\n\n \"register { a: 127, b: 0, c: 138, d: 4, e: 0, f: 128, h: 152, l: 5, pc: 7417, sp: 57341 }\",\n\n );\n\n mem.borrow_mut().fake_data(7417, 34);\n\n let mut cpu = CPU::new(mem, false);\n\n cpu.set_reg(reg);\n\n cpu.op_0x6B();\n\n assert_eq!(\n\n format!(\"{:?}\", cpu.get_reg_snapshot()).to_lowercase(),\n\n \"register { a: 127, b: 0, c: 138, d: 4, e: 0, f: 128, h: 152, l: 0, pc: 7417, sp: 57341 }\"\n\n );\n\n}\n", "file_path": "tests/opcodes.rs", "rank": 21, "score": 69080.93015713694 }, { "content": "#[test]\n\nfn test_opcode_0X5F() {\n\n let mem = Rc::new(RefCell::new(FakeMemory::new()));\n\n let reg = Register::new_from_debug_string(\n\n \"register { a: 64, b: 0, c: 138, d: 0, e: 0, f: 192, h: 126, l: 121, pc: 32357, sp: 57337 }\",\n\n );\n\n mem.borrow_mut().fake_data(65295, 0);\n\n mem.borrow_mut().fake_data(65535, 13);\n\n mem.borrow_mut().fake_data(32357, 135);\n\n let mut cpu = CPU::new(mem, false);\n\n cpu.set_reg(reg);\n\n cpu.op_0x5F();\n\n assert_eq!(\n\n format!(\"{:?}\", cpu.get_reg_snapshot()).to_lowercase(),\n\n \"register { a: 64, b: 0, c: 138, d: 0, e: 64, f: 192, h: 126, l: 121, pc: 32357, sp: 57337 }\"\n\n );\n\n}\n", "file_path": "tests/opcodes.rs", "rank": 22, "score": 69080.93015713694 }, { "content": "#[test]\n\nfn test_opcode_0X0E() {\n\n let mem = Rc::new(RefCell::new(FakeMemory::new()));\n\n let reg = Register::new_from_debug_string(\n\n \"register { a: 1, b: 0, c: 0, d: 0, e: 216, f: 192, h: 195, l: 160, pc: 19438, sp: 57341 }\",\n\n );\n\n mem.borrow_mut().fake_data(19438, 128);\n\n mem.borrow_mut().fake_data(19439, 6);\n\n let mut cpu = CPU::new(mem, false);\n\n cpu.set_reg(reg);\n\n cpu.op_0x0E();\n\n assert_eq!(\n\n format!(\"{:?}\", cpu.get_reg_snapshot()).to_lowercase(),\n\n \"register { a: 1, b: 0, c: 128, d: 0, e: 216, f: 192, h: 195, l: 160, pc: 19439, sp: 57341 }\"\n\n );\n\n}\n", "file_path": "tests/opcodes.rs", "rank": 23, "score": 69080.93015713694 }, { "content": "#[test]\n\nfn test_opcode_0X2C() {\n\n let mem = Rc::new(RefCell::new(FakeMemory::new()));\n\n let reg = Register::new_from_debug_string(\n\n \"register { a: 1, b: 6, c: 0, d: 0, e: 0, f: 160, h: 156, l: 0, pc: 7585, sp: 50082 }\",\n\n );\n\n mem.borrow_mut().fake_data(7585, 114);\n\n let mut cpu = CPU::new(mem, false);\n\n cpu.set_reg(reg);\n\n cpu.op_0x2C();\n\n assert_eq!(\n\n format!(\"{:?}\", cpu.get_reg_snapshot()).to_lowercase(),\n\n \"register { a: 1, b: 6, c: 0, d: 0, e: 0, f: 0, h: 156, l: 1, pc: 7585, sp: 50082 }\"\n\n );\n\n}\n", "file_path": "tests/opcodes.rs", "rank": 24, "score": 69080.93015713694 }, { "content": "struct FakeMemory<'a> {\n\n records: Vec<&'a str>,\n\n data: HashMap<u16, u16>,\n\n}\n\n\n\nimpl<'a> FakeMemory<'a> {\n\n fn new() -> FakeMemory<'a> {\n\n Self {\n\n records: vec![],\n\n data: HashMap::new(),\n\n }\n\n }\n\n\n\n fn fake_data(&mut self, a: u16, v: u16) {\n\n self.data.insert(a, v);\n\n }\n\n}\n\n\n\nimpl IOHandler for FakeMemory<'_> {\n\n fn read_byte(&self, a: u16) -> u8 {\n", "file_path": "tests/opcodes.rs", "rank": 25, "score": 53424.167325993556 }, { "content": "pub trait IOHandler {\n\n /// Read a byte.\n\n fn read_byte(&self, a: u16) -> u8;\n\n\n\n /// Write a byte.\n\n fn write_byte(&mut self, a: u16, v: u8);\n\n\n\n /// Read a double byte.\n\n fn read_word(&self, a: u16) -> u16 {\n\n u16::from(self.read_byte(a)) | (u16::from(self.read_byte(a + 1)) << 8)\n\n }\n\n\n\n /// Write a double byte.\n\n fn write_word(&mut self, a: u16, v: u16) {\n\n self.write_byte(a, (v & 0xFF) as u8);\n\n self.write_byte(a + 1, (v >> 8) as u8)\n\n }\n\n}\n\n\n\n///\n", "file_path": "src/gameboy/mmu.rs", "rank": 26, "score": 49978.32936460979 }, { "content": "pub trait MemoryBank {\n\n /// Returns the current num of rom bank reg.\n\n fn get_rom_bank_num(&self) -> usize;\n\n\n\n /// Returns the current num of ram bank reg.\n\n fn get_ram_bank_num(&self) -> usize;\n\n\n\n /// Read a byte from given address via bank controller.\n\n fn read_via_rom_bank(&self, addr: u16) -> u8;\n\n\n\n /// Read a byte from given address via bank controller.\n\n fn read_via_ram_bank(&self, addr: u16) -> u8;\n\n\n\n /// Write a byte from given address via bank controller.\n\n fn write_via_ram_bank(&mut self, addr: u16, value: u8);\n\n}\n", "file_path": "src/gameboy/cartridge/bank.rs", "rank": 27, "score": 48672.654966620656 }, { "content": "#[test]\n\nfn test_opcode_0X66() {\n\n let mem = Rc::new(RefCell::new(FakeMemory::new()));\n\n let reg = Register::new_from_debug_string(\n\n \"register { a: 40, b: 0, c: 9, d: 0, e: 0, f: 160, h: 96, l: 138, pc: 24702, sp: 57331 }\",\n\n );\n\n mem.borrow_mut().fake_data(24714, 101);\n\n mem.borrow_mut().fake_data(24702, 111);\n\n let mut cpu = CPU::new(mem, false);\n\n cpu.set_reg(reg);\n\n cpu.op_0x66();\n\n assert_eq!(\n\n format!(\"{:?}\", cpu.get_reg_snapshot()).to_lowercase(),\n\n \"register { a: 40, b: 0, c: 9, d: 0, e: 0, f: 160, h: 101, l: 138, pc: 24702, sp: 57331 }\"\n\n );\n\n}\n", "file_path": "tests/opcodes.rs", "rank": 28, "score": 40106.949245661934 }, { "content": "#[test]\n\nfn test_opcode_0X16() {\n\n let mem = Rc::new(RefCell::new(FakeMemory::new()));\n\n let reg = Register::new_from_debug_string(\n\n \"register { a: 0, b: 255, c: 138, d: 0, e: 0, f: 128, h: 160, l: 0, pc: 23148, sp: 57333 }\",\n\n );\n\n mem.borrow_mut().fake_data(23148, 160);\n\n mem.borrow_mut().fake_data(23149, 33);\n\n let mut cpu = CPU::new(mem, false);\n\n cpu.set_reg(reg);\n\n cpu.op_0x16();\n\n assert_eq!(\n\n format!(\"{:?}\", cpu.get_reg_snapshot()).to_lowercase(),\n\n \"register { a: 0, b: 255, c: 138, d: 160, e: 0, f: 128, h: 160, l: 0, pc: 23149, sp: 57333 }\"\n\n );\n\n}\n", "file_path": "tests/opcodes.rs", "rank": 29, "score": 40106.949245661934 }, { "content": "#[test]\n\nfn test_opcode_0X98() {\n\n let mem = Rc::new(RefCell::new(FakeMemory::new()));\n\n let reg = Register::new_from_debug_string(\n\n \"register { a: 0, b: 130, c: 228, d: 0, e: 4, f: 0, h: 122, l: 143, pc: 31389, sp: 57311 }\",\n\n );\n\n mem.borrow_mut().fake_data(31389, 224);\n\n let mut cpu = CPU::new(mem, false);\n\n cpu.set_reg(reg);\n\n cpu.op_0x98();\n\n assert_eq!(\n\n format!(\"{:?}\", cpu.get_reg_snapshot()).to_lowercase(),\n\n \"register { a: 126, b: 130, c: 228, d: 0, e: 4, f: 112, h: 122, l: 143, pc: 31389, sp: 57311 }\"\n\n );\n\n}\n", "file_path": "tests/opcodes.rs", "rank": 30, "score": 40106.949245661934 }, { "content": "#[test]\n\nfn test_opcode_0X04() {\n\n let mem = Rc::new(RefCell::new(FakeMemory::new()));\n\n let reg = Register::new_from_debug_string(\n\n \"register { a: 0, b: 1, c: 104, d: 0, e: 0, f: 128, h: 69, l: 56, pc: 6419, sp: 57327 }\",\n\n );\n\n mem.borrow_mut().fake_data(65295, 0);\n\n mem.borrow_mut().fake_data(65535, 13);\n\n mem.borrow_mut().fake_data(6419, 33);\n\n let mut cpu = CPU::new(mem, false);\n\n cpu.set_reg(reg);\n\n cpu.op_0x04();\n\n assert_eq!(\n\n format!(\"{:?}\", cpu.get_reg_snapshot()).to_lowercase(),\n\n \"register { a: 0, b: 2, c: 104, d: 0, e: 0, f: 0, h: 69, l: 56, pc: 6419, sp: 57327 }\"\n\n );\n\n}\n", "file_path": "tests/opcodes.rs", "rank": 31, "score": 40106.949245661934 }, { "content": "#[test]\n\nfn test_opcode_0X54() {\n\n let mem = Rc::new(RefCell::new(FakeMemory::new()));\n\n let reg = Register::new_from_debug_string(\n\n \"register { a: 192, b: 0, c: 138, d: 0, e: 192, f: 0, h: 127, l: 57, pc: 32365, sp: 57337 }\",\n\n );\n\n mem.borrow_mut().fake_data(65295, 0);\n\n mem.borrow_mut().fake_data(65535, 13);\n\n mem.borrow_mut().fake_data(32365, 93);\n\n let mut cpu = CPU::new(mem, false);\n\n cpu.set_reg(reg);\n\n cpu.op_0x54();\n\n assert_eq!(\n\n format!(\"{:?}\", cpu.get_reg_snapshot()).to_lowercase(),\n\n \"register { a: 192, b: 0, c: 138, d: 127, e: 192, f: 0, h: 127, l: 57, pc: 32365, sp: 57337 }\"\n\n );\n\n}\n", "file_path": "tests/opcodes.rs", "rank": 32, "score": 40106.949245661934 }, { "content": "#[test]\n\nfn test_opcode_0X67() {\n\n let mem = Rc::new(RefCell::new(FakeMemory::new()));\n\n let reg = Register::new_from_debug_string(\n\n \"register { a: 96, b: 0, c: 138, d: 127, e: 59, f: 0, h: 127, l: 43, pc: 32376, sp: 57337 }\",\n\n );\n\n mem.borrow_mut().fake_data(65295, 0);\n\n mem.borrow_mut().fake_data(65535, 13);\n\n mem.borrow_mut().fake_data(32376, 201);\n\n let mut cpu = CPU::new(mem, false);\n\n cpu.set_reg(reg);\n\n cpu.op_0x67();\n\n assert_eq!(\n\n format!(\"{:?}\", cpu.get_reg_snapshot()).to_lowercase(),\n\n \"register { a: 96, b: 0, c: 138, d: 127, e: 59, f: 0, h: 96, l: 43, pc: 32376, sp: 57337 }\"\n\n );\n\n}\n", "file_path": "tests/opcodes.rs", "rank": 33, "score": 40106.949245661934 }, { "content": "#[test]\n\nfn test_opcode_0X1A() {\n\n let mem = Rc::new(RefCell::new(FakeMemory::new()));\n\n let reg = Register::new_from_debug_string(\n\n \"register { a: 192, b: 0, c: 138, d: 127, e: 57, f: 0, h: 127, l: 57, pc: 32367, sp: 57337 }\",\n\n );\n\n mem.borrow_mut().fake_data(32569, 28);\n\n mem.borrow_mut().fake_data(65295, 0);\n\n mem.borrow_mut().fake_data(65535, 13);\n\n mem.borrow_mut().fake_data(32367, 234);\n\n let mut cpu = CPU::new(mem, false);\n\n cpu.set_reg(reg);\n\n cpu.op_0x1A();\n\n assert_eq!(\n\n format!(\"{:?}\", cpu.get_reg_snapshot()).to_lowercase(),\n\n \"register { a: 28, b: 0, c: 138, d: 127, e: 57, f: 0, h: 127, l: 57, pc: 32367, sp: 57337 }\"\n\n );\n\n}\n", "file_path": "tests/opcodes.rs", "rank": 34, "score": 40106.949245661934 }, { "content": "#[test]\n\nfn test_opcode_0X18() {\n\n let mem = Rc::new(RefCell::new(FakeMemory::new()));\n\n let reg = Register::new_from_debug_string(\n\n \"register { a: 0, b: 0, c: 19, d: 0, e: 216, f: 128, h: 1, l: 77, pc: 342, sp: 65534 }\",\n\n );\n\n mem.borrow_mut().fake_data(342, 2);\n\n mem.borrow_mut().fake_data(65295, 0);\n\n mem.borrow_mut().fake_data(65535, 0);\n\n mem.borrow_mut().fake_data(345, 234);\n\n let mut cpu = CPU::new(mem, false);\n\n cpu.set_reg(reg);\n\n cpu.op_0x18();\n\n assert_eq!(\n\n format!(\"{:?}\", cpu.get_reg_snapshot()).to_lowercase(),\n\n \"register { a: 0, b: 0, c: 19, d: 0, e: 216, f: 128, h: 1, l: 77, pc: 345, sp: 65534 }\"\n\n );\n\n}\n", "file_path": "tests/opcodes.rs", "rank": 35, "score": 40106.949245661934 }, { "content": "#[test]\n\nfn test_opcode_0XC3() {\n\n let mem = Rc::new(RefCell::new(FakeMemory::new()));\n\n let reg = Register::new_from_debug_string(\n\n \"register { a: 1, b: 0, c: 19, d: 0, e: 216, f: 176, h: 1, l: 77, pc: 258, sp: 65534 }\",\n\n );\n\n mem.borrow_mut().fake_data(258, 336);\n\n mem.borrow_mut().fake_data(65295, 0);\n\n mem.borrow_mut().fake_data(65535, 0);\n\n mem.borrow_mut().fake_data(336, 254);\n\n let mut cpu = CPU::new(mem, false);\n\n cpu.set_reg(reg);\n\n cpu.op_0xC3();\n\n assert_eq!(\n\n format!(\"{:?}\", cpu.get_reg_snapshot()).to_lowercase(),\n\n \"register { a: 1, b: 0, c: 19, d: 0, e: 216, f: 176, h: 1, l: 77, pc: 336, sp: 65534 }\"\n\n );\n\n}\n", "file_path": "tests/opcodes.rs", "rank": 36, "score": 40106.949245661934 }, { "content": "#[test]\n\nfn test_opcode_0XAF() {\n\n let mem = Rc::new(RefCell::new(FakeMemory::new()));\n\n let reg = Register::new_from_debug_string(\n\n \"register { a: 1, b: 0, c: 19, d: 0, e: 216, f: 80, h: 1, l: 77, pc: 341, sp: 65534 }\",\n\n );\n\n mem.borrow_mut().fake_data(65295, 0);\n\n mem.borrow_mut().fake_data(65535, 0);\n\n mem.borrow_mut().fake_data(341, 24);\n\n let mut cpu = CPU::new(mem, false);\n\n cpu.set_reg(reg);\n\n cpu.op_0xAF();\n\n assert_eq!(\n\n format!(\"{:?}\", cpu.get_reg_snapshot()).to_lowercase(),\n\n \"register { a: 0, b: 0, c: 19, d: 0, e: 216, f: 128, h: 1, l: 77, pc: 341, sp: 65534 }\"\n\n );\n\n}\n", "file_path": "tests/opcodes.rs", "rank": 37, "score": 40106.949245661934 }, { "content": "#[test]\n\nfn test_opcode_0XD0() {\n\n let mem = Rc::new(RefCell::new(FakeMemory::new()));\n\n let reg = Register::new_from_debug_string(\n\n \"register { a: 0, b: 0, c: 138, d: 0, e: 0, f: 144, h: 100, l: 248, pc: 24627, sp: 57337 }\",\n\n );\n\n mem.borrow_mut().fake_data(65295, 0);\n\n mem.borrow_mut().fake_data(65535, 13);\n\n mem.borrow_mut().fake_data(24627, 62);\n\n let mut cpu = CPU::new(mem, false);\n\n cpu.set_reg(reg);\n\n cpu.op_0xD0();\n\n assert_eq!(\n\n format!(\"{:?}\", cpu.get_reg_snapshot()).to_lowercase(),\n\n \"register { a: 0, b: 0, c: 138, d: 0, e: 0, f: 144, h: 100, l: 248, pc: 24627, sp: 57337 }\"\n\n );\n\n}\n", "file_path": "tests/opcodes.rs", "rank": 38, "score": 40106.949245661934 }, { "content": "#[test]\n\nfn test_opcode_0XA7() {\n\n let mem = Rc::new(RefCell::new(FakeMemory::new()));\n\n let reg = Register::new_from_debug_string(\n\n \"register { a: 0, b: 255, c: 138, d: 0, e: 0, f: 96, h: 160, l: 0, pc: 9145, sp: 57335 }\",\n\n );\n\n mem.borrow_mut().fake_data(9145, 40);\n\n let mut cpu = CPU::new(mem, false);\n\n cpu.set_reg(reg);\n\n cpu.op_0xA7();\n\n assert_eq!(\n\n format!(\"{:?}\", cpu.get_reg_snapshot()).to_lowercase(),\n\n \"register { a: 0, b: 255, c: 138, d: 0, e: 0, f: 160, h: 160, l: 0, pc: 9145, sp: 57335 }\"\n\n );\n\n}\n", "file_path": "tests/opcodes.rs", "rank": 39, "score": 40106.949245661934 }, { "content": "#[test]\n\nfn test_opcode_0XE9() {\n\n let mem = Rc::new(RefCell::new(FakeMemory::new()));\n\n let reg = Register::new_from_debug_string(\n\n \"register { a: 28, b: 0, c: 138, d: 62, e: 141, f: 0, h: 96, l: 43, pc: 16013, sp: 57337 }\",\n\n );\n\n mem.borrow_mut().fake_data(65295, 0);\n\n mem.borrow_mut().fake_data(65535, 13);\n\n mem.borrow_mut().fake_data(24619, 175);\n\n let mut cpu = CPU::new(mem, false);\n\n cpu.set_reg(reg);\n\n cpu.op_0xE9();\n\n assert_eq!(\n\n format!(\"{:?}\", cpu.get_reg_snapshot()).to_lowercase(),\n\n \"register { a: 28, b: 0, c: 138, d: 62, e: 141, f: 0, h: 96, l: 43, pc: 24619, sp: 57337 }\"\n\n );\n\n}\n", "file_path": "tests/opcodes.rs", "rank": 40, "score": 40106.949245661934 }, { "content": "#[test]\n\nfn test_opcode_0XD5() {\n\n let mem = Rc::new(RefCell::new(FakeMemory::new()));\n\n let reg = Register::new_from_debug_string(\n\n \"register { a: 0, b: 32, c: 0, d: 0, e: 216, f: 128, h: 128, l: 0, pc: 14049, sp: 57341 }\",\n\n );\n\n mem.borrow_mut().fake_data(14049, 87);\n\n let mut cpu = CPU::new(mem, false);\n\n cpu.set_reg(reg);\n\n cpu.op_0xD5();\n\n assert_eq!(\n\n format!(\"{:?}\", cpu.get_reg_snapshot()).to_lowercase(),\n\n \"register { a: 0, b: 32, c: 0, d: 0, e: 216, f: 128, h: 128, l: 0, pc: 14049, sp: 57339 }\"\n\n );\n\n}\n", "file_path": "tests/opcodes.rs", "rank": 41, "score": 40106.949245661934 }, { "content": "#[test]\n\nfn test_opcode_0X77() {\n\n let mem = Rc::new(RefCell::new(FakeMemory::new()));\n\n let reg = Register::new_from_debug_string(\n\n \"register { a: 160, b: 40, c: 138, d: 0, e: 4, f: 192, h: 195, l: 0, pc: 152, sp: 57323 }\",\n\n );\n\n mem.borrow_mut().fake_data(152, 25);\n\n let mut cpu = CPU::new(mem, false);\n\n cpu.set_reg(reg);\n\n cpu.op_0x77();\n\n assert_eq!(\n\n format!(\"{:?}\", cpu.get_reg_snapshot()).to_lowercase(),\n\n \"register { a: 160, b: 40, c: 138, d: 0, e: 4, f: 192, h: 195, l: 0, pc: 152, sp: 57323 }\"\n\n );\n\n}\n", "file_path": "tests/opcodes.rs", "rank": 42, "score": 40106.949245661934 }, { "content": "#[test]\n\nfn test_opcode_0XC0() {\n\n let mem = Rc::new(RefCell::new(FakeMemory::new()));\n\n let reg = Register::new_from_debug_string(\n\n \"register { a: 255, b: 0, c: 138, d: 0, e: 0, f: 192, h: 101, l: 8, pc: 19224, sp: 57323 }\",\n\n );\n\n mem.borrow_mut().fake_data(19224, 234);\n\n let mut cpu = CPU::new(mem, false);\n\n cpu.set_reg(reg);\n\n cpu.op_0xC0();\n\n assert_eq!(\n\n format!(\"{:?}\", cpu.get_reg_snapshot()).to_lowercase(),\n\n \"register { a: 255, b: 0, c: 138, d: 0, e: 0, f: 192, h: 101, l: 8, pc: 19224, sp: 57323 }\"\n\n );\n\n}\n", "file_path": "tests/opcodes.rs", "rank": 43, "score": 40106.949245661934 }, { "content": "#[test]\n\nfn test_opcode_0X87() {\n\n let mem = Rc::new(RefCell::new(FakeMemory::new()));\n\n let reg = Register::new_from_debug_string(\n\n \"register { a: 64, b: 0, c: 138, d: 0, e: 64, f: 192, h: 126, l: 121, pc: 32358, sp: 57337 }\",\n\n );\n\n mem.borrow_mut().fake_data(65295, 0);\n\n mem.borrow_mut().fake_data(65535, 13);\n\n mem.borrow_mut().fake_data(32358, 131);\n\n let mut cpu = CPU::new(mem, false);\n\n cpu.set_reg(reg);\n\n cpu.op_0x87();\n\n assert_eq!(\n\n format!(\"{:?}\", cpu.get_reg_snapshot()).to_lowercase(),\n\n \"register { a: 128, b: 0, c: 138, d: 0, e: 64, f: 0, h: 126, l: 121, pc: 32358, sp: 57337 }\"\n\n );\n\n}\n", "file_path": "tests/opcodes.rs", "rank": 44, "score": 40106.949245661934 }, { "content": "#[test]\n\nfn test_opcode_0XE5() {\n\n let mem = Rc::new(RefCell::new(FakeMemory::new()));\n\n let reg = Register::new_from_debug_string(\n\n \"register { a: 255, b: 0, c: 138, d: 0, e: 0, f: 96, h: 160, l: 0, pc: 9138, sp: 57341 }\",\n\n );\n\n mem.borrow_mut().fake_data(9138, 213);\n\n let mut cpu = CPU::new(mem, false);\n\n cpu.set_reg(reg);\n\n cpu.op_0xE5();\n\n assert_eq!(\n\n format!(\"{:?}\", cpu.get_reg_snapshot()).to_lowercase(),\n\n \"register { a: 255, b: 0, c: 138, d: 0, e: 0, f: 96, h: 160, l: 0, pc: 9138, sp: 57339 }\"\n\n );\n\n}\n", "file_path": "tests/opcodes.rs", "rank": 45, "score": 40106.949245661934 }, { "content": "#[test]\n\nfn test_opcode_0XCC() {\n\n let mem = Rc::new(RefCell::new(FakeMemory::new()));\n\n let reg = Register::new_from_debug_string(\n\n \"register { a: 1, b: 2, c: 192, d: 0, e: 4, f: 32, h: 77, l: 238, pc: 8352, sp: 57325 }\",\n\n );\n\n mem.borrow_mut().fake_data(8352, 351);\n\n mem.borrow_mut().fake_data(8354, 250);\n\n let mut cpu = CPU::new(mem, false);\n\n cpu.set_reg(reg);\n\n cpu.op_0xCC();\n\n assert_eq!(\n\n format!(\"{:?}\", cpu.get_reg_snapshot()).to_lowercase(),\n\n \"register { a: 1, b: 2, c: 192, d: 0, e: 4, f: 32, h: 77, l: 238, pc: 8354, sp: 57325 }\"\n\n );\n\n}\n", "file_path": "tests/opcodes.rs", "rank": 46, "score": 40106.949245661934 }, { "content": "#[test]\n\nfn test_opcode_0XD1() {\n\n let mem = Rc::new(RefCell::new(FakeMemory::new()));\n\n let reg = Register::new_from_debug_string(\n\n \"register { a: 0, b: 0, c: 0, d: 0, e: 216, f: 128, h: 160, l: 0, pc: 14058, sp: 57339 }\",\n\n );\n\n mem.borrow_mut().fake_data(57339, 216);\n\n mem.borrow_mut().fake_data(14058, 201);\n\n let mut cpu = CPU::new(mem, false);\n\n cpu.set_reg(reg);\n\n cpu.op_0xD1();\n\n assert_eq!(\n\n format!(\"{:?}\", cpu.get_reg_snapshot()).to_lowercase(),\n\n \"register { a: 0, b: 0, c: 0, d: 0, e: 216, f: 128, h: 160, l: 0, pc: 14058, sp: 57341 }\"\n\n );\n\n}\n", "file_path": "tests/opcodes.rs", "rank": 47, "score": 40106.949245661934 }, { "content": "#[test]\n\nfn test_opcode_0X24() {\n\n let mem = Rc::new(RefCell::new(FakeMemory::new()));\n\n let reg = Register::new_from_debug_string(\n\n \"register { a: 0, b: 5, c: 0, d: 0, e: 0, f: 176, h: 156, l: 0, pc: 7638, sp: 50240 }\",\n\n );\n\n mem.borrow_mut().fake_data(7638, 5);\n\n let mut cpu = CPU::new(mem, false);\n\n cpu.set_reg(reg);\n\n cpu.op_0x24();\n\n assert_eq!(\n\n format!(\"{:?}\", cpu.get_reg_snapshot()).to_lowercase(),\n\n \"register { a: 0, b: 5, c: 0, d: 0, e: 0, f: 16, h: 157, l: 0, pc: 7638, sp: 50240 }\"\n\n );\n\n}\n", "file_path": "tests/opcodes.rs", "rank": 48, "score": 40106.949245661934 }, { "content": "#[test]\n\nfn test_opcode_0X11() {\n\n let mem = Rc::new(RefCell::new(FakeMemory::new()));\n\n let reg = Register::new_from_debug_string(\n\n \"register { a: 127, b: 0, c: 138, d: 0, e: 216, f: 128, h: 152, l: 5, pc: 7414, sp: 57341 }\",\n\n );\n\n mem.borrow_mut().fake_data(7414, 1024);\n\n mem.borrow_mut().fake_data(7416, 107);\n\n let mut cpu = CPU::new(mem, false);\n\n cpu.set_reg(reg);\n\n cpu.op_0x11();\n\n assert_eq!(\n\n format!(\"{:?}\", cpu.get_reg_snapshot()).to_lowercase(),\n\n \"register { a: 127, b: 0, c: 138, d: 4, e: 0, f: 128, h: 152, l: 5, pc: 7416, sp: 57341 }\"\n\n );\n\n}\n", "file_path": "tests/opcodes.rs", "rank": 49, "score": 40106.949245661934 }, { "content": "#[test]\n\nfn test_opcode_0X30() {\n\n let mem = Rc::new(RefCell::new(FakeMemory::new()));\n\n let reg = Register::new_from_debug_string(\n\n \"register { a: 192, b: 0, c: 138, d: 0, e: 192, f: 0, h: 126, l: 121, pc: 32361, sp: 57337 }\",\n\n );\n\n mem.borrow_mut().fake_data(32361, 1);\n\n mem.borrow_mut().fake_data(65295, 0);\n\n mem.borrow_mut().fake_data(65535, 13);\n\n mem.borrow_mut().fake_data(32363, 25);\n\n let mut cpu = CPU::new(mem, false);\n\n cpu.set_reg(reg);\n\n cpu.op_0x30();\n\n assert_eq!(\n\n format!(\"{:?}\", cpu.get_reg_snapshot()).to_lowercase(),\n\n \"register { a: 192, b: 0, c: 138, d: 0, e: 192, f: 0, h: 126, l: 121, pc: 32363, sp: 57337 }\"\n\n );\n\n}\n", "file_path": "tests/opcodes.rs", "rank": 50, "score": 40106.949245661934 }, { "content": "#[test]\n\nfn test_opcode_0X23() {\n\n let mem = Rc::new(RefCell::new(FakeMemory::new()));\n\n let reg = Register::new_from_debug_string(\n\n \"register { a: 0, b: 32, c: 0, d: 0, e: 216, f: 160, h: 192, l: 0, pc: 8067, sp: 57343 }\",\n\n );\n\n mem.borrow_mut().fake_data(8067, 11);\n\n let mut cpu = CPU::new(mem, false);\n\n cpu.set_reg(reg);\n\n cpu.op_0x23();\n\n assert_eq!(\n\n format!(\"{:?}\", cpu.get_reg_snapshot()).to_lowercase(),\n\n \"register { a: 0, b: 32, c: 0, d: 0, e: 216, f: 160, h: 192, l: 1, pc: 8067, sp: 57343 }\"\n\n );\n\n}\n", "file_path": "tests/opcodes.rs", "rank": 51, "score": 40106.949245661934 }, { "content": "#[test]\n\nfn test_opcode_0X12() {\n\n let mem = Rc::new(RefCell::new(FakeMemory::new()));\n\n let reg = Register::new_from_debug_string(\n\n \"register { a: 0, b: 128, c: 16, d: 136, e: 0, f: 32, h: 111, l: 233, pc: 24974, sp: 57331 }\",\n\n );\n\n mem.borrow_mut().fake_data(24974, 19);\n\n let mut cpu = CPU::new(mem, false);\n\n cpu.set_reg(reg);\n\n cpu.op_0x12();\n\n assert_eq!(\n\n format!(\"{:?}\", cpu.get_reg_snapshot()).to_lowercase(),\n\n \"register { a: 0, b: 128, c: 16, d: 136, e: 0, f: 32, h: 111, l: 233, pc: 24974, sp: 57331 }\"\n\n );\n\n}\n", "file_path": "tests/opcodes.rs", "rank": 52, "score": 40106.949245661934 }, { "content": "#[test]\n\nfn test_opcode_0X29() {\n\n let mem = Rc::new(RefCell::new(FakeMemory::new()));\n\n let reg = Register::new_from_debug_string(\n\n \"register { a: 12, b: 12, c: 0, d: 62, e: 141, f: 80, h: 0, l: 12, pc: 24051, sp: 57329 }\",\n\n );\n\n mem.borrow_mut().fake_data(65295, 0);\n\n mem.borrow_mut().fake_data(65535, 13);\n\n mem.borrow_mut().fake_data(24051, 17);\n\n let mut cpu = CPU::new(mem, false);\n\n cpu.set_reg(reg);\n\n cpu.op_0x29();\n\n assert_eq!(\n\n format!(\"{:?}\", cpu.get_reg_snapshot()).to_lowercase(),\n\n \"register { a: 12, b: 12, c: 0, d: 62, e: 141, f: 0, h: 0, l: 24, pc: 24051, sp: 57329 }\"\n\n );\n\n}\n", "file_path": "tests/opcodes.rs", "rank": 53, "score": 40106.949245661934 }, { "content": "#[test]\n\nfn test_opcode_0X85() {\n\n let mem = Rc::new(RefCell::new(FakeMemory::new()));\n\n let reg = Register::new_from_debug_string(\n\n \"register { a: 13, b: 6, c: 0, d: 0, e: 0, f: 0, h: 156, l: 19, pc: 7634, sp: 50100 }\",\n\n );\n\n mem.borrow_mut().fake_data(7634, 111);\n\n let mut cpu = CPU::new(mem, false);\n\n cpu.set_reg(reg);\n\n cpu.op_0x85();\n\n assert_eq!(\n\n format!(\"{:?}\", cpu.get_reg_snapshot()).to_lowercase(),\n\n \"register { a: 32, b: 6, c: 0, d: 0, e: 0, f: 32, h: 156, l: 19, pc: 7634, sp: 50100 }\"\n\n );\n\n}\n", "file_path": "tests/opcodes.rs", "rank": 54, "score": 40106.949245661934 }, { "content": "#[test]\n\nfn test_opcode_0XC1() {\n\n let mem = Rc::new(RefCell::new(FakeMemory::new()));\n\n let reg = Register::new_from_debug_string(\n\n \"register { a: 1, b: 0, c: 138, d: 24, e: 0, f: 192, h: 192, l: 206, pc: 9254, sp: 57335 }\",\n\n );\n\n mem.borrow_mut().fake_data(57335, 138);\n\n mem.borrow_mut().fake_data(9254, 209);\n\n let mut cpu = CPU::new(mem, false);\n\n cpu.set_reg(reg);\n\n cpu.op_0xC1();\n\n assert_eq!(\n\n format!(\"{:?}\", cpu.get_reg_snapshot()).to_lowercase(),\n\n \"register { a: 1, b: 0, c: 138, d: 24, e: 0, f: 192, h: 192, l: 206, pc: 9254, sp: 57337 }\"\n\n );\n\n}\n", "file_path": "tests/opcodes.rs", "rank": 55, "score": 40106.949245661934 }, { "content": "#[test]\n\nfn test_opcode_0X09() {\n\n let mem = Rc::new(RefCell::new(FakeMemory::new()));\n\n let reg = Register::new_from_debug_string(\n\n \"register { a: 2, b: 0, c: 0, d: 0, e: 4, f: 192, h: 192, l: 38, pc: 20747, sp: 57323 }\",\n\n );\n\n mem.borrow_mut().fake_data(20747, 126);\n\n let mut cpu = CPU::new(mem, false);\n\n cpu.set_reg(reg);\n\n cpu.op_0x09();\n\n assert_eq!(\n\n format!(\"{:?}\", cpu.get_reg_snapshot()).to_lowercase(),\n\n \"register { a: 2, b: 0, c: 0, d: 0, e: 4, f: 128, h: 192, l: 38, pc: 20747, sp: 57323 }\"\n\n );\n\n}\n", "file_path": "tests/opcodes.rs", "rank": 56, "score": 40106.949245661934 }, { "content": "#[test]\n\nfn test_opcode_0X36() {\n\n let mem = Rc::new(RefCell::new(FakeMemory::new()));\n\n let reg = Register::new_from_debug_string(\n\n \"register { a: 0, b: 32, c: 0, d: 0, e: 216, f: 160, h: 192, l: 0, pc: 8065, sp: 57343 }\",\n\n );\n\n mem.borrow_mut().fake_data(8065, 0);\n\n mem.borrow_mut().fake_data(8066, 35);\n\n let mut cpu = CPU::new(mem, false);\n\n cpu.set_reg(reg);\n\n cpu.op_0x36();\n\n assert_eq!(\n\n format!(\"{:?}\", cpu.get_reg_snapshot()).to_lowercase(),\n\n \"register { a: 0, b: 32, c: 0, d: 0, e: 216, f: 160, h: 192, l: 0, pc: 8066, sp: 57343 }\"\n\n );\n\n}\n", "file_path": "tests/opcodes.rs", "rank": 57, "score": 40106.949245661934 }, { "content": "#[test]\n\nfn test_opcode_0X76() {\n\n let mem = Rc::new(RefCell::new(FakeMemory::new()));\n\n let reg = Register::new_from_debug_string(\n\n \"register { a: 1, b: 0, c: 3, d: 0, e: 0, f: 192, h: 197, l: 8, pc: 8372, sp: 57325 }\",\n\n );\n\n\n\n let mut cpu = CPU::new(mem, false);\n\n cpu.set_reg(reg);\n\n cpu.op_0x76();\n\n assert_eq!(\n\n format!(\"{:?}\", cpu.get_reg_snapshot()).to_lowercase(),\n\n \"register { a: 1, b: 0, c: 3, d: 0, e: 0, f: 192, h: 197, l: 8, pc: 8372, sp: 57325 }\"\n\n );\n\n assert_eq!(cpu.is_halt(), true);\n\n}\n", "file_path": "tests/opcodes.rs", "rank": 58, "score": 40106.949245661934 }, { "content": "#[test]\n\nfn test_opcode_0XC5() {\n\n let mem = Rc::new(RefCell::new(FakeMemory::new()));\n\n let reg = Register::new_from_debug_string(\n\n \"register { a: 255, b: 0, c: 138, d: 0, e: 0, f: 96, h: 160, l: 0, pc: 9140, sp: 57337 }\",\n\n );\n\n mem.borrow_mut().fake_data(9140, 71);\n\n let mut cpu = CPU::new(mem, false);\n\n cpu.set_reg(reg);\n\n cpu.op_0xC5();\n\n assert_eq!(\n\n format!(\"{:?}\", cpu.get_reg_snapshot()).to_lowercase(),\n\n \"register { a: 255, b: 0, c: 138, d: 0, e: 0, f: 96, h: 160, l: 0, pc: 9140, sp: 57335 }\"\n\n );\n\n}\n", "file_path": "tests/opcodes.rs", "rank": 59, "score": 40106.949245661934 }, { "content": "#[test]\n\nfn test_opcode_0XE1() {\n\n let mem = Rc::new(RefCell::new(FakeMemory::new()));\n\n let reg = Register::new_from_debug_string(\n\n \"register { a: 1, b: 0, c: 138, d: 0, e: 0, f: 192, h: 192, l: 206, pc: 9256, sp: 57339 }\",\n\n );\n\n mem.borrow_mut().fake_data(57339, 40960);\n\n mem.borrow_mut().fake_data(9256, 201);\n\n let mut cpu = CPU::new(mem, false);\n\n cpu.set_reg(reg);\n\n cpu.op_0xE1();\n\n assert_eq!(\n\n format!(\"{:?}\", cpu.get_reg_snapshot()).to_lowercase(),\n\n \"register { a: 1, b: 0, c: 138, d: 0, e: 0, f: 192, h: 160, l: 0, pc: 9256, sp: 57341 }\"\n\n );\n\n}\n", "file_path": "tests/opcodes.rs", "rank": 60, "score": 40106.949245661934 }, { "content": "#[test]\n\nfn test_opcode_0X47() {\n\n let mem = Rc::new(RefCell::new(FakeMemory::new()));\n\n let reg = Register::new_from_debug_string(\n\n \"register { a: 0, b: 0, c: 19, d: 0, e: 216, f: 128, h: 1, l: 77, pc: 103, sp: 65532 }\",\n\n );\n\n mem.borrow_mut().fake_data(103, 203);\n\n mem.borrow_mut().fake_data(104, 135);\n\n mem.borrow_mut().fake_data(105, 224);\n\n let mut cpu = CPU::new(mem, false);\n\n cpu.set_reg(reg);\n\n cpu.op_0x47();\n\n assert_eq!(\n\n format!(\"{:?}\", cpu.get_reg_snapshot()).to_lowercase(),\n\n \"register { a: 0, b: 0, c: 19, d: 0, e: 216, f: 128, h: 1, l: 77, pc: 103, sp: 65532 }\"\n\n );\n\n}\n", "file_path": "tests/opcodes.rs", "rank": 61, "score": 40106.949245661934 }, { "content": "#[test]\n\nfn test_opcode_0XE2() {\n\n let mem = Rc::new(RefCell::new(FakeMemory::new()));\n\n let reg = Register::new_from_debug_string(\n\n \"register { a: 62, b: 10, c: 128, d: 0, e: 216, f: 192, h: 75, l: 252, pc: 19446, sp: 57341 }\",\n\n );\n\n mem.borrow_mut().fake_data(19446, 12);\n\n let mut cpu = CPU::new(mem, false);\n\n cpu.set_reg(reg);\n\n cpu.op_0xE2();\n\n assert_eq!(\n\n format!(\"{:?}\", cpu.get_reg_snapshot()).to_lowercase(),\n\n \"register { a: 62, b: 10, c: 128, d: 0, e: 216, f: 192, h: 75, l: 252, pc: 19446, sp: 57341 }\"\n\n );\n\n}\n", "file_path": "tests/opcodes.rs", "rank": 62, "score": 40106.949245661934 }, { "content": "#[test]\n\nfn test_opcode_0XD6() {\n\n let mem = Rc::new(RefCell::new(FakeMemory::new()));\n\n let reg = Register::new_from_debug_string(\n\n \"register { a: 32, b: 4, c: 32, d: 98, e: 136, f: 160, h: 150, l: 0, pc: 6274, sp: 57325 }\",\n\n );\n\n mem.borrow_mut().fake_data(6274, 8);\n\n mem.borrow_mut().fake_data(65295, 0);\n\n mem.borrow_mut().fake_data(65535, 13);\n\n mem.borrow_mut().fake_data(6275, 79);\n\n let mut cpu = CPU::new(mem, false);\n\n cpu.set_reg(reg);\n\n cpu.op_0xD6();\n\n assert_eq!(\n\n format!(\"{:?}\", cpu.get_reg_snapshot()).to_lowercase(),\n\n \"register { a: 24, b: 4, c: 32, d: 98, e: 136, f: 96, h: 150, l: 0, pc: 6275, sp: 57325 }\"\n\n );\n\n}\n", "file_path": "tests/opcodes.rs", "rank": 63, "score": 40106.949245661934 }, { "content": "#[test]\n\nfn test_opcode_0X72() {\n\n let mem = Rc::new(RefCell::new(FakeMemory::new()));\n\n let reg = Register::new_from_debug_string(\n\n \"register { a: 1, b: 6, c: 0, d: 0, e: 0, f: 0, h: 156, l: 1, pc: 7586, sp: 50082 }\",\n\n );\n\n mem.borrow_mut().fake_data(7586, 44);\n\n let mut cpu = CPU::new(mem, false);\n\n cpu.set_reg(reg);\n\n cpu.op_0x72();\n\n assert_eq!(\n\n format!(\"{:?}\", cpu.get_reg_snapshot()).to_lowercase(),\n\n \"register { a: 1, b: 6, c: 0, d: 0, e: 0, f: 0, h: 156, l: 1, pc: 7586, sp: 50082 }\"\n\n );\n\n}\n", "file_path": "tests/opcodes.rs", "rank": 64, "score": 40106.949245661934 }, { "content": "#[test]\n\nfn test_opcode_0X42() {\n\n let mem = Rc::new(RefCell::new(FakeMemory::new()));\n\n let reg = Register::new_from_debug_string(\n\n \"register { a: 0, b: 255, c: 138, d: 160, e: 0, f: 128, h: 192, l: 6, pc: 23178, sp: 57331 }\",\n\n );\n\n mem.borrow_mut().fake_data(23178, 34);\n\n let mut cpu = CPU::new(mem, false);\n\n cpu.set_reg(reg);\n\n cpu.op_0x42();\n\n assert_eq!(\n\n format!(\"{:?}\", cpu.get_reg_snapshot()).to_lowercase(),\n\n \"register { a: 0, b: 160, c: 138, d: 160, e: 0, f: 128, h: 192, l: 6, pc: 23178, sp: 57331 }\"\n\n );\n\n}\n", "file_path": "tests/opcodes.rs", "rank": 65, "score": 40106.949245661934 }, { "content": "#[test]\n\nfn test_opcode_0X00() {\n\n let mem = Rc::new(RefCell::new(FakeMemory::new()));\n\n let reg = Register::new_from_debug_string(\n\n \"register { a: 1, b: 0, c: 19, d: 0, e: 216, f: 176, h: 1, l: 77, pc: 257, sp: 65534 }\",\n\n );\n\n mem.borrow_mut().fake_data(65295, 0);\n\n mem.borrow_mut().fake_data(65535, 0);\n\n mem.borrow_mut().fake_data(257, 195);\n\n let mut cpu = CPU::new(mem, false);\n\n cpu.set_reg(reg);\n\n cpu.op_0x00();\n\n assert_eq!(\n\n format!(\"{:?}\", cpu.get_reg_snapshot()).to_lowercase(),\n\n \"register { a: 1, b: 0, c: 19, d: 0, e: 216, f: 176, h: 1, l: 77, pc: 257, sp: 65534 }\"\n\n );\n\n}\n", "file_path": "tests/opcodes.rs", "rank": 66, "score": 40106.949245661934 }, { "content": "#[test]\n\nfn test_opcode_0X2A() {\n\n let mem = Rc::new(RefCell::new(FakeMemory::new()));\n\n let reg = Register::new_from_debug_string(\n\n \"register { a: 1, b: 10, c: 128, d: 0, e: 216, f: 192, h: 75, l: 251, pc: 19445, sp: 57341 }\",\n\n );\n\n mem.borrow_mut().fake_data(19451, 62);\n\n mem.borrow_mut().fake_data(19445, 226);\n\n let mut cpu = CPU::new(mem, false);\n\n cpu.set_reg(reg);\n\n cpu.op_0x2A();\n\n assert_eq!(\n\n format!(\"{:?}\", cpu.get_reg_snapshot()).to_lowercase(),\n\n \"register { a: 62, b: 10, c: 128, d: 0, e: 216, f: 192, h: 75, l: 252, pc: 19445, sp: 57341 }\"\n\n );\n\n}\n", "file_path": "tests/opcodes.rs", "rank": 67, "score": 40106.949245661934 }, { "content": "#[test]\n\nfn test_opcode_0X7A() {\n\n let mem = Rc::new(RefCell::new(FakeMemory::new()));\n\n let reg = Register::new_from_debug_string(\n\n \"register { a: 0, b: 32, c: 0, d: 0, e: 216, f: 128, h: 128, l: 0, pc: 14051, sp: 57339 }\",\n\n );\n\n mem.borrow_mut().fake_data(14051, 34);\n\n let mut cpu = CPU::new(mem, false);\n\n cpu.set_reg(reg);\n\n cpu.op_0x7A();\n\n assert_eq!(\n\n format!(\"{:?}\", cpu.get_reg_snapshot()).to_lowercase(),\n\n \"register { a: 0, b: 32, c: 0, d: 0, e: 216, f: 128, h: 128, l: 0, pc: 14051, sp: 57339 }\"\n\n );\n\n}\n", "file_path": "tests/opcodes.rs", "rank": 68, "score": 40106.949245661934 }, { "content": "#[test]\n\nfn test_opcode_0X44() {\n\n let mem = Rc::new(RefCell::new(FakeMemory::new()));\n\n let reg = Register::new_from_debug_string(\n\n \"register { a: 80, b: 0, c: 40, d: 69, e: 135, f: 192, h: 196, l: 143, pc: 6492, sp: 57327 }\",\n\n );\n\n mem.borrow_mut().fake_data(65295, 0);\n\n mem.borrow_mut().fake_data(65535, 13);\n\n mem.borrow_mut().fake_data(6492, 77);\n\n let mut cpu = CPU::new(mem, false);\n\n cpu.set_reg(reg);\n\n cpu.op_0x44();\n\n assert_eq!(\n\n format!(\"{:?}\", cpu.get_reg_snapshot()).to_lowercase(),\n\n \"register { a: 80, b: 196, c: 40, d: 69, e: 135, f: 192, h: 196, l: 143, pc: 6492, sp: 57327 }\"\n\n );\n\n}\n", "file_path": "tests/opcodes.rs", "rank": 69, "score": 40106.949245661934 }, { "content": "#[test]\n\nfn test_opcode_0X88() {\n\n let mem = Rc::new(RefCell::new(FakeMemory::new()));\n\n let reg = Register::new_from_debug_string(\n\n \"register { a: 0, b: 130, c: 228, d: 0, e: 4, f: 192, h: 122, l: 143, pc: 31381, sp: 57311 }\",\n\n );\n\n mem.borrow_mut().fake_data(31381, 224);\n\n let mut cpu = CPU::new(mem, false);\n\n cpu.set_reg(reg);\n\n cpu.op_0x88();\n\n assert_eq!(\n\n format!(\"{:?}\", cpu.get_reg_snapshot()).to_lowercase(),\n\n \"register { a: 130, b: 130, c: 228, d: 0, e: 4, f: 0, h: 122, l: 143, pc: 31381, sp: 57311 }\"\n\n );\n\n}\n", "file_path": "tests/opcodes.rs", "rank": 70, "score": 40106.949245661934 }, { "content": "#[test]\n\nfn test_opcode_0X28() {\n\n let mem = Rc::new(RefCell::new(FakeMemory::new()));\n\n let reg = Register::new_from_debug_string(\n\n \"register { a: 1, b: 0, c: 19, d: 0, e: 216, f: 80, h: 1, l: 77, pc: 339, sp: 65534 }\",\n\n );\n\n mem.borrow_mut().fake_data(339, 3);\n\n mem.borrow_mut().fake_data(65295, 0);\n\n mem.borrow_mut().fake_data(65535, 0);\n\n mem.borrow_mut().fake_data(340, 175);\n\n let mut cpu = CPU::new(mem, false);\n\n cpu.set_reg(reg);\n\n cpu.op_0x28();\n\n assert_eq!(\n\n format!(\"{:?}\", cpu.get_reg_snapshot()).to_lowercase(),\n\n \"register { a: 1, b: 0, c: 19, d: 0, e: 216, f: 80, h: 1, l: 77, pc: 340, sp: 65534 }\"\n\n );\n\n}\n", "file_path": "tests/opcodes.rs", "rank": 71, "score": 40106.949245661934 }, { "content": "#[test]\n\nfn test_opcode_0X71() {\n\n let mem = Rc::new(RefCell::new(FakeMemory::new()));\n\n let reg = Register::new_from_debug_string(\n\n \"register { a: 0, b: 0, c: 138, d: 0, e: 0, f: 192, h: 204, l: 84, pc: 32347, sp: 57337 }\",\n\n );\n\n mem.borrow_mut().fake_data(65295, 0);\n\n mem.borrow_mut().fake_data(65535, 13);\n\n mem.borrow_mut().fake_data(32347, 33);\n\n let mut cpu = CPU::new(mem, false);\n\n cpu.set_reg(reg);\n\n cpu.op_0x71();\n\n assert_eq!(\n\n format!(\"{:?}\", cpu.get_reg_snapshot()).to_lowercase(),\n\n \"register { a: 0, b: 0, c: 138, d: 0, e: 0, f: 192, h: 204, l: 84, pc: 32347, sp: 57337 }\"\n\n );\n\n}\n", "file_path": "tests/opcodes.rs", "rank": 72, "score": 40106.949245661934 }, { "content": "#[test]\n\nfn test_opcode_0X01() {\n\n let mem = Rc::new(RefCell::new(FakeMemory::new()));\n\n let reg = Register::new_from_debug_string(\n\n \"register { a: 0, b: 0, c: 19, d: 0, e: 216, f: 160, h: 192, l: 0, pc: 8062, sp: 57343 }\",\n\n );\n\n mem.borrow_mut().fake_data(8062, 8192);\n\n mem.borrow_mut().fake_data(8064, 54);\n\n let mut cpu = CPU::new(mem, false);\n\n cpu.set_reg(reg);\n\n cpu.op_0x01();\n\n assert_eq!(\n\n format!(\"{:?}\", cpu.get_reg_snapshot()).to_lowercase(),\n\n \"register { a: 0, b: 32, c: 0, d: 0, e: 216, f: 160, h: 192, l: 0, pc: 8064, sp: 57343 }\"\n\n );\n\n}\n", "file_path": "tests/opcodes.rs", "rank": 73, "score": 40106.949245661934 }, { "content": "#[test]\n\nfn test_opcode_0XCD() {\n\n let mem = Rc::new(RefCell::new(FakeMemory::new()));\n\n let reg = Register::new_from_debug_string(\n\n \"register { a: 128, b: 0, c: 19, d: 0, e: 216, f: 128, h: 1, l: 77, pc: 8053, sp: 65534 }\",\n\n );\n\n mem.borrow_mut().fake_data(8053, 97);\n\n mem.borrow_mut().fake_data(97, 175);\n\n let mut cpu = CPU::new(mem, false);\n\n cpu.set_reg(reg);\n\n cpu.op_0xCD();\n\n assert_eq!(\n\n format!(\"{:?}\", cpu.get_reg_snapshot()).to_lowercase(),\n\n \"register { a: 128, b: 0, c: 19, d: 0, e: 216, f: 128, h: 1, l: 77, pc: 97, sp: 65532 }\"\n\n );\n\n}\n", "file_path": "tests/opcodes.rs", "rank": 74, "score": 40106.949245661934 }, { "content": "#[test]\n\nfn test_opcode_0X20() {\n\n let mem = Rc::new(RefCell::new(FakeMemory::new()));\n\n let reg = Register::new_from_debug_string(\n\n \"register { a: 0, b: 0, c: 19, d: 0, e: 216, f: 112, h: 1, l: 77, pc: 112, sp: 65532 }\",\n\n );\n\n mem.borrow_mut().fake_data(112, 250);\n\n mem.borrow_mut().fake_data(107, 240);\n\n let mut cpu = CPU::new(mem, false);\n\n cpu.set_reg(reg);\n\n cpu.op_0x20();\n\n assert_eq!(\n\n format!(\"{:?}\", cpu.get_reg_snapshot()).to_lowercase(),\n\n \"register { a: 0, b: 0, c: 19, d: 0, e: 216, f: 112, h: 1, l: 77, pc: 107, sp: 65532 }\"\n\n );\n\n}\n", "file_path": "tests/opcodes.rs", "rank": 75, "score": 40106.949245661934 }, { "content": "#[test]\n\nfn test_opcode_0XB0() {\n\n let mem = Rc::new(RefCell::new(FakeMemory::new()));\n\n let reg = Register::new_from_debug_string(\n\n \"register { a: 0, b: 0, c: 0, d: 25, e: 108, f: 160, h: 77, l: 238, pc: 403, sp: 57315 }\",\n\n );\n\n mem.borrow_mut().fake_data(403, 224);\n\n let mut cpu = CPU::new(mem, false);\n\n cpu.set_reg(reg);\n\n cpu.op_0xB0();\n\n assert_eq!(\n\n format!(\"{:?}\", cpu.get_reg_snapshot()).to_lowercase(),\n\n \"register { a: 0, b: 0, c: 0, d: 25, e: 108, f: 128, h: 77, l: 238, pc: 403, sp: 57315 }\"\n\n );\n\n}\n", "file_path": "tests/opcodes.rs", "rank": 76, "score": 40106.949245661934 }, { "content": "#[test]\n\nfn test_opcode_0XB1() {\n\n let mem = Rc::new(RefCell::new(FakeMemory::new()));\n\n let reg = Register::new_from_debug_string(\n\n \"register { a: 31, b: 31, c: 255, d: 0, e: 216, f: 160, h: 192, l: 1, pc: 8070, sp: 57343 }\",\n\n );\n\n mem.borrow_mut().fake_data(8070, 32);\n\n let mut cpu = CPU::new(mem, false);\n\n cpu.set_reg(reg);\n\n cpu.op_0xB1();\n\n assert_eq!(\n\n format!(\"{:?}\", cpu.get_reg_snapshot()).to_lowercase(),\n\n \"register { a: 255, b: 31, c: 255, d: 0, e: 216, f: 0, h: 192, l: 1, pc: 8070, sp: 57343 }\"\n\n );\n\n}\n", "file_path": "tests/opcodes.rs", "rank": 77, "score": 40106.949245661934 }, { "content": "#[test]\n\nfn test_opcode_0X78() {\n\n let mem = Rc::new(RefCell::new(FakeMemory::new()));\n\n let reg = Register::new_from_debug_string(\n\n \"register { a: 0, b: 0, c: 19, d: 0, e: 216, f: 160, h: 1, l: 77, pc: 120, sp: 65532 }\",\n\n );\n\n mem.borrow_mut().fake_data(120, 224);\n\n let mut cpu = CPU::new(mem, false);\n\n cpu.set_reg(reg);\n\n cpu.op_0x78();\n\n assert_eq!(\n\n format!(\"{:?}\", cpu.get_reg_snapshot()).to_lowercase(),\n\n \"register { a: 0, b: 0, c: 19, d: 0, e: 216, f: 160, h: 1, l: 77, pc: 120, sp: 65532 }\"\n\n );\n\n}\n", "file_path": "tests/opcodes.rs", "rank": 78, "score": 40106.949245661934 }, { "content": "#[test]\n\nfn test_opcode_0X79() {\n\n let mem = Rc::new(RefCell::new(FakeMemory::new()));\n\n let reg = Register::new_from_debug_string(\n\n \"register { a: 0, b: 0, c: 0, d: 0, e: 4, f: 160, h: 192, l: 38, pc: 20785, sp: 57323 }\",\n\n );\n\n mem.borrow_mut().fake_data(20786, 12);\n\n let mut cpu = CPU::new(mem, false);\n\n cpu.set_reg(reg);\n\n cpu.op_0x79();\n\n assert_eq!(\n\n format!(\"{:?}\", cpu.get_reg_snapshot()).to_lowercase(),\n\n \"register { a: 0, b: 0, c: 0, d: 0, e: 4, f: 160, h: 192, l: 38, pc: 20785, sp: 57323 }\"\n\n );\n\n}\n", "file_path": "tests/opcodes.rs", "rank": 79, "score": 40106.949245661934 }, { "content": "#[test]\n\nfn test_opcode_0X13() {\n\n let mem = Rc::new(RefCell::new(FakeMemory::new()));\n\n let reg = Register::new_from_debug_string(\n\n \"register { a: 28, b: 0, c: 138, d: 127, e: 57, f: 0, h: 127, l: 57, pc: 32371, sp: 57337 }\",\n\n );\n\n mem.borrow_mut().fake_data(65295, 0);\n\n mem.borrow_mut().fake_data(65535, 13);\n\n mem.borrow_mut().fake_data(32371, 26);\n\n let mut cpu = CPU::new(mem, false);\n\n cpu.set_reg(reg);\n\n cpu.op_0x13();\n\n assert_eq!(\n\n format!(\"{:?}\", cpu.get_reg_snapshot()).to_lowercase(),\n\n \"register { a: 28, b: 0, c: 138, d: 127, e: 58, f: 0, h: 127, l: 57, pc: 32371, sp: 57337 }\"\n\n );\n\n}\n", "file_path": "tests/opcodes.rs", "rank": 80, "score": 40106.949245661934 }, { "content": "#[test]\n\nfn test_opcode_0X57() {\n\n let mem = Rc::new(RefCell::new(FakeMemory::new()));\n\n let reg = Register::new_from_debug_string(\n\n \"register { a: 0, b: 32, c: 0, d: 0, e: 216, f: 128, h: 128, l: 0, pc: 14050, sp: 57339 }\",\n\n );\n\n mem.borrow_mut().fake_data(14050, 122);\n\n let mut cpu = CPU::new(mem, false);\n\n cpu.set_reg(reg);\n\n cpu.op_0x57();\n\n assert_eq!(\n\n format!(\"{:?}\", cpu.get_reg_snapshot()).to_lowercase(),\n\n \"register { a: 0, b: 32, c: 0, d: 0, e: 216, f: 128, h: 128, l: 0, pc: 14050, sp: 57339 }\"\n\n );\n\n}\n", "file_path": "tests/opcodes.rs", "rank": 81, "score": 40106.949245661934 }, { "content": "#[test]\n\nfn test_opcode_0XD9() {\n\n let mem = Rc::new(RefCell::new(FakeMemory::new()));\n\n let reg = Register::new_from_debug_string(\n\n \"register { a: 1, b: 0, c: 138, d: 0, e: 0, f: 192, h: 101, l: 8, pc: 8368, sp: 57333 }\",\n\n );\n\n mem.borrow_mut().fake_data(57333, 24743);\n\n mem.borrow_mut().fake_data(65295, 0);\n\n mem.borrow_mut().fake_data(65535, 13);\n\n mem.borrow_mut().fake_data(24743, 205);\n\n let mut cpu = CPU::new(mem, false);\n\n cpu.set_reg(reg);\n\n cpu.op_0xD9();\n\n assert_eq!(\n\n format!(\"{:?}\", cpu.get_reg_snapshot()).to_lowercase(),\n\n \"register { a: 1, b: 0, c: 138, d: 0, e: 0, f: 192, h: 101, l: 8, pc: 24743, sp: 57335 }\"\n\n );\n\n}\n", "file_path": "tests/opcodes.rs", "rank": 82, "score": 40106.949245661934 }, { "content": "#[test]\n\nfn test_opcode_0X37() {\n\n let mem = Rc::new(RefCell::new(FakeMemory::new()));\n\n let reg = Register::new_from_debug_string(\n\n \"register { a: 0, b: 0, c: 138, d: 0, e: 0, f: 128, h: 100, l: 248, pc: 24833, sp: 57335 }\",\n\n );\n\n mem.borrow_mut().fake_data(65295, 0);\n\n mem.borrow_mut().fake_data(65535, 13);\n\n mem.borrow_mut().fake_data(24833, 201);\n\n let mut cpu = CPU::new(mem, false);\n\n cpu.set_reg(reg);\n\n cpu.op_0x37();\n\n assert_eq!(\n\n format!(\"{:?}\", cpu.get_reg_snapshot()).to_lowercase(),\n\n \"register { a: 0, b: 0, c: 138, d: 0, e: 0, f: 144, h: 100, l: 248, pc: 24833, sp: 57335 }\"\n\n );\n\n}\n", "file_path": "tests/opcodes.rs", "rank": 83, "score": 40106.949245661934 }, { "content": "#[test]\n\nfn test_opcode_0X05() {\n\n let mem = Rc::new(RefCell::new(FakeMemory::new()));\n\n let reg = Register::new_from_debug_string(\n\n \"register { a: 0, b: 160, c: 0, d: 0, e: 216, f: 128, h: 195, l: 1, pc: 138, sp: 57341 }\",\n\n );\n\n mem.borrow_mut().fake_data(138, 32);\n\n let mut cpu = CPU::new(mem, false);\n\n cpu.set_reg(reg);\n\n cpu.op_0x05();\n\n assert_eq!(\n\n format!(\"{:?}\", cpu.get_reg_snapshot()).to_lowercase(),\n\n \"register { a: 0, b: 159, c: 0, d: 0, e: 216, f: 96, h: 195, l: 1, pc: 138, sp: 57341 }\"\n\n );\n\n}\n", "file_path": "tests/opcodes.rs", "rank": 84, "score": 40106.949245661934 }, { "content": "#[test]\n\nfn test_opcode_0XC9() {\n\n let mem = Rc::new(RefCell::new(FakeMemory::new()));\n\n let reg = Register::new_from_debug_string(\n\n \"register { a: 0, b: 0, c: 19, d: 0, e: 216, f: 160, h: 1, l: 77, pc: 123, sp: 65532 }\",\n\n );\n\n mem.borrow_mut().fake_data(65532, 8055);\n\n mem.borrow_mut().fake_data(8055, 49);\n\n let mut cpu = CPU::new(mem, false);\n\n cpu.set_reg(reg);\n\n cpu.op_0xC9();\n\n assert_eq!(\n\n format!(\"{:?}\", cpu.get_reg_snapshot()).to_lowercase(),\n\n \"register { a: 0, b: 0, c: 19, d: 0, e: 216, f: 160, h: 1, l: 77, pc: 8055, sp: 65534 }\"\n\n );\n\n}\n", "file_path": "tests/opcodes.rs", "rank": 85, "score": 40106.949245661934 }, { "content": "#[test]\n\nfn test_opcode_0XB3() {\n\n let mem = Rc::new(RefCell::new(FakeMemory::new()));\n\n let reg = Register::new_from_debug_string(\n\n \"register { a: 27, b: 0, c: 138, d: 27, e: 87, f: 128, h: 101, l: 8, pc: 24915, sp: 57329 }\",\n\n );\n\n mem.borrow_mut().fake_data(24915, 32);\n\n let mut cpu = CPU::new(mem, false);\n\n cpu.set_reg(reg);\n\n cpu.op_0xB3();\n\n assert_eq!(\n\n format!(\"{:?}\", cpu.get_reg_snapshot()).to_lowercase(),\n\n \"register { a: 95, b: 0, c: 138, d: 27, e: 87, f: 0, h: 101, l: 8, pc: 24915, sp: 57329 }\"\n\n );\n\n}\n", "file_path": "tests/opcodes.rs", "rank": 86, "score": 40106.949245661934 }, { "content": "#[test]\n\nfn test_opcode_0X06() {\n\n let mem = Rc::new(RefCell::new(FakeMemory::new()));\n\n let reg = Register::new_from_debug_string(\n\n \"register { a: 0, b: 0, c: 0, d: 0, e: 216, f: 128, h: 195, l: 0, pc: 135, sp: 57341 }\",\n\n );\n\n mem.borrow_mut().fake_data(135, 160);\n\n mem.borrow_mut().fake_data(136, 34);\n\n let mut cpu = CPU::new(mem, false);\n\n cpu.set_reg(reg);\n\n cpu.op_0x06();\n\n assert_eq!(\n\n format!(\"{:?}\", cpu.get_reg_snapshot()).to_lowercase(),\n\n \"register { a: 0, b: 160, c: 0, d: 0, e: 216, f: 128, h: 195, l: 0, pc: 136, sp: 57341 }\"\n\n );\n\n}\n", "file_path": "tests/opcodes.rs", "rank": 87, "score": 40106.949245661934 }, { "content": "#[test]\n\nfn test_opcode_0X15() {\n\n let mem = Rc::new(RefCell::new(FakeMemory::new()));\n\n let reg = Register::new_from_debug_string(\n\n \"register { a: 127, b: 0, c: 138, d: 4, e: 0, f: 192, h: 153, l: 0, pc: 7422, sp: 57341 }\",\n\n );\n\n mem.borrow_mut().fake_data(7422, 32);\n\n let mut cpu = CPU::new(mem, false);\n\n cpu.set_reg(reg);\n\n cpu.op_0x15();\n\n assert_eq!(\n\n format!(\"{:?}\", cpu.get_reg_snapshot()).to_lowercase(),\n\n \"register { a: 127, b: 0, c: 138, d: 3, e: 0, f: 64, h: 153, l: 0, pc: 7422, sp: 57341 }\"\n\n );\n\n}\n", "file_path": "tests/opcodes.rs", "rank": 88, "score": 40106.949245661934 }, { "content": "#[test]\n\nfn test_opcode_0X31() {\n\n let mem = Rc::new(RefCell::new(FakeMemory::new()));\n\n let reg = Register::new_from_debug_string(\n\n \"register { a: 0, b: 0, c: 19, d: 0, e: 216, f: 160, h: 1, l: 77, pc: 8056, sp: 65534 }\",\n\n );\n\n mem.borrow_mut().fake_data(8056, 57343);\n\n mem.borrow_mut().fake_data(8058, 33);\n\n let mut cpu = CPU::new(mem, false);\n\n cpu.set_reg(reg);\n\n cpu.op_0x31();\n\n assert_eq!(\n\n format!(\"{:?}\", cpu.get_reg_snapshot()).to_lowercase(),\n\n \"register { a: 0, b: 0, c: 19, d: 0, e: 216, f: 160, h: 1, l: 77, pc: 8058, sp: 57343 }\"\n\n );\n\n}\n", "file_path": "tests/opcodes.rs", "rank": 89, "score": 40106.949245661934 }, { "content": "#[test]\n\nfn test_opcode_0XE6() {\n\n let mem = Rc::new(RefCell::new(FakeMemory::new()));\n\n let reg = Register::new_from_debug_string(\n\n \"register { a: 128, b: 0, c: 19, d: 0, e: 216, f: 192, h: 1, l: 77, pc: 116, sp: 65532 }\",\n\n );\n\n mem.borrow_mut().fake_data(116, 127);\n\n mem.borrow_mut().fake_data(117, 224);\n\n let mut cpu = CPU::new(mem, false);\n\n cpu.set_reg(reg);\n\n cpu.op_0xE6();\n\n assert_eq!(\n\n format!(\"{:?}\", cpu.get_reg_snapshot()).to_lowercase(),\n\n \"register { a: 0, b: 0, c: 19, d: 0, e: 216, f: 160, h: 1, l: 77, pc: 117, sp: 65532 }\"\n\n );\n\n}\n", "file_path": "tests/opcodes.rs", "rank": 90, "score": 40106.949245661934 }, { "content": "#[test]\n\nfn test_opcode_0X19() {\n\n let mem = Rc::new(RefCell::new(FakeMemory::new()));\n\n let reg = Register::new_from_debug_string(\n\n \"register { a: 192, b: 0, c: 138, d: 0, e: 192, f: 0, h: 126, l: 121, pc: 32364, sp: 57337 }\",\n\n );\n\n mem.borrow_mut().fake_data(65295, 0);\n\n mem.borrow_mut().fake_data(65535, 13);\n\n mem.borrow_mut().fake_data(32364, 84);\n\n let mut cpu = CPU::new(mem, false);\n\n cpu.set_reg(reg);\n\n cpu.op_0x19();\n\n assert_eq!(\n\n format!(\"{:?}\", cpu.get_reg_snapshot()).to_lowercase(),\n\n \"register { a: 192, b: 0, c: 138, d: 0, e: 192, f: 0, h: 127, l: 57, pc: 32364, sp: 57337 }\"\n\n );\n\n}\n", "file_path": "tests/opcodes.rs", "rank": 91, "score": 40106.949245661934 }, { "content": "#[test]\n\nfn test_opcode_0X26() {\n\n let mem = Rc::new(RefCell::new(FakeMemory::new()));\n\n let reg = Register::new_from_debug_string(\n\n \"register { a: 255, b: 0, c: 138, d: 0, e: 216, f: 128, h: 76, l: 5, pc: 8127, sp: 57343 }\",\n\n );\n\n mem.borrow_mut().fake_data(8127, 152);\n\n mem.borrow_mut().fake_data(8128, 205);\n\n let mut cpu = CPU::new(mem, false);\n\n cpu.set_reg(reg);\n\n cpu.op_0x26();\n\n assert_eq!(\n\n format!(\"{:?}\", cpu.get_reg_snapshot()).to_lowercase(),\n\n \"register { a: 255, b: 0, c: 138, d: 0, e: 216, f: 128, h: 152, l: 5, pc: 8128, sp: 57343 }\"\n\n );\n\n}\n", "file_path": "tests/opcodes.rs", "rank": 92, "score": 40106.949245661934 }, { "content": "#[test]\n\nfn test_opcode_0X83() {\n\n let mem = Rc::new(RefCell::new(FakeMemory::new()));\n\n let reg = Register::new_from_debug_string(\n\n \"register { a: 128, b: 0, c: 138, d: 0, e: 64, f: 0, h: 126, l: 121, pc: 32359, sp: 57337 }\",\n\n );\n\n mem.borrow_mut().fake_data(65295, 0);\n\n mem.borrow_mut().fake_data(65535, 13);\n\n mem.borrow_mut().fake_data(32359, 95);\n\n let mut cpu = CPU::new(mem, false);\n\n cpu.set_reg(reg);\n\n cpu.op_0x83();\n\n assert_eq!(\n\n format!(\"{:?}\", cpu.get_reg_snapshot()).to_lowercase(),\n\n \"register { a: 192, b: 0, c: 138, d: 0, e: 64, f: 0, h: 126, l: 121, pc: 32359, sp: 57337 }\"\n\n );\n\n}\n", "file_path": "tests/opcodes.rs", "rank": 93, "score": 40106.949245661934 }, { "content": "#[test]\n\nfn test_opcode_0X21() {\n\n let mem = Rc::new(RefCell::new(FakeMemory::new()));\n\n let reg = Register::new_from_debug_string(\n\n \"register { a: 0, b: 0, c: 19, d: 0, e: 216, f: 160, h: 1, l: 77, pc: 8059, sp: 57343 }\",\n\n );\n\n mem.borrow_mut().fake_data(8059, 49152);\n\n mem.borrow_mut().fake_data(8061, 1);\n\n let mut cpu = CPU::new(mem, false);\n\n cpu.set_reg(reg);\n\n cpu.op_0x21();\n\n assert_eq!(\n\n format!(\"{:?}\", cpu.get_reg_snapshot()).to_lowercase(),\n\n \"register { a: 0, b: 0, c: 19, d: 0, e: 216, f: 160, h: 192, l: 0, pc: 8061, sp: 57343 }\"\n\n );\n\n}\n", "file_path": "tests/opcodes.rs", "rank": 94, "score": 40106.949245661934 }, { "content": "#[test]\n\nfn test_opcode_0XCA() {\n\n let mem = Rc::new(RefCell::new(FakeMemory::new()));\n\n let reg = Register::new_from_debug_string(\n\n \"register { a: 255, b: 255, c: 138, d: 0, e: 0, f: 192, h: 160, l: 0, pc: 22652, sp: 57333 }\",\n\n );\n\n mem.borrow_mut().fake_data(22652, 23092);\n\n mem.borrow_mut().fake_data(23092, 62);\n\n let mut cpu = CPU::new(mem, false);\n\n cpu.set_reg(reg);\n\n cpu.op_0xCA();\n\n assert_eq!(\n\n format!(\"{:?}\", cpu.get_reg_snapshot()).to_lowercase(),\n\n \"register { a: 255, b: 255, c: 138, d: 0, e: 0, f: 192, h: 160, l: 0, pc: 23092, sp: 57333 }\"\n\n );\n\n}\n", "file_path": "tests/opcodes.rs", "rank": 95, "score": 40106.949245661934 }, { "content": "#[test]\n\nfn test_opcode_0X22() {\n\n let mem = Rc::new(RefCell::new(FakeMemory::new()));\n\n let reg = Register::new_from_debug_string(\n\n \"register { a: 0, b: 32, c: 0, d: 0, e: 216, f: 128, h: 128, l: 0, pc: 14052, sp: 57339 }\",\n\n );\n\n mem.borrow_mut().fake_data(14052, 11);\n\n let mut cpu = CPU::new(mem, false);\n\n cpu.set_reg(reg);\n\n cpu.op_0x22();\n\n assert_eq!(\n\n format!(\"{:?}\", cpu.get_reg_snapshot()).to_lowercase(),\n\n \"register { a: 0, b: 32, c: 0, d: 0, e: 216, f: 128, h: 128, l: 1, pc: 14052, sp: 57339 }\"\n\n );\n\n}\n", "file_path": "tests/opcodes.rs", "rank": 96, "score": 40106.949245661934 }, { "content": "#[test]\n\nfn test_opcode_0X73() {\n\n let mem = Rc::new(RefCell::new(FakeMemory::new()));\n\n let reg = Register::new_from_debug_string(\n\n \"register { a: 1, b: 6, c: 0, d: 0, e: 0, f: 160, h: 156, l: 0, pc: 7584, sp: 50082 }\",\n\n );\n\n mem.borrow_mut().fake_data(7584, 44);\n\n let mut cpu = CPU::new(mem, false);\n\n cpu.set_reg(reg);\n\n cpu.op_0x73();\n\n assert_eq!(\n\n format!(\"{:?}\", cpu.get_reg_snapshot()).to_lowercase(),\n\n \"register { a: 1, b: 6, c: 0, d: 0, e: 0, f: 160, h: 156, l: 0, pc: 7584, sp: 50082 }\"\n\n );\n\n}\n", "file_path": "tests/opcodes.rs", "rank": 97, "score": 40106.949245661934 }, { "content": "#[test]\n\nfn test_opcode_0XC8() {\n\n let mem = Rc::new(RefCell::new(FakeMemory::new()));\n\n let reg = Register::new_from_debug_string(\n\n \"register { a: 1, b: 0, c: 138, d: 62, e: 141, f: 32, h: 100, l: 248, pc: 24559, sp: 57333 }\",\n\n );\n\n mem.borrow_mut().fake_data(24559, 71);\n\n let mut cpu = CPU::new(mem, false);\n\n cpu.set_reg(reg);\n\n cpu.op_0xC8();\n\n assert_eq!(\n\n format!(\"{:?}\", cpu.get_reg_snapshot()).to_lowercase(),\n\n \"register { a: 1, b: 0, c: 138, d: 62, e: 141, f: 32, h: 100, l: 248, pc: 24559, sp: 57333 }\"\n\n );\n\n}\n", "file_path": "tests/opcodes.rs", "rank": 98, "score": 40106.949245661934 }, { "content": "#[test]\n\nfn test_opcode_0XE0() {\n\n let mem = Rc::new(RefCell::new(FakeMemory::new()));\n\n let reg = Register::new_from_debug_string(\n\n \"register { a: 0, b: 0, c: 19, d: 0, e: 216, f: 128, h: 1, l: 77, pc: 8023, sp: 65534 }\",\n\n );\n\n mem.borrow_mut().fake_data(8023, 15);\n\n mem.borrow_mut().fake_data(8024, 224);\n\n let mut cpu = CPU::new(mem, false);\n\n cpu.set_reg(reg);\n\n cpu.op_0xE0();\n\n assert_eq!(\n\n format!(\"{:?}\", cpu.get_reg_snapshot()).to_lowercase(),\n\n \"register { a: 0, b: 0, c: 19, d: 0, e: 216, f: 128, h: 1, l: 77, pc: 8024, sp: 65534 }\"\n\n );\n\n}\n", "file_path": "tests/opcodes.rs", "rank": 99, "score": 40106.949245661934 } ]
Rust
contracts/tland-token/src/msg.rs
highwayns/realestate
508db9bc5578ae57050e9bd9e0faacd4f5746cf6
use cosmwasm_std::{StdError, StdResult, Uint128, Binary}; use cw20::{Cw20Coin, Logo}; use schemars::JsonSchema; use serde::{Deserialize, Serialize}; use cw0::Expiration; #[derive(Serialize, Deserialize, JsonSchema, Debug, Clone, PartialEq)] pub struct InstantiateMarketingInfo { pub project: Option<String>, pub description: Option<String>, pub marketing: Option<String>, pub logo: Option<Logo>, } #[derive(Serialize, Deserialize, JsonSchema, Debug, Clone, PartialEq)] pub struct InstantiateMsg { pub owner: String, pub name: String, pub symbol: String, pub decimals: u8, pub initial_balances: Vec<Cw20Coin>, pub marketing: Option<InstantiateMarketingInfo>, } impl InstantiateMsg { pub fn validate(&self) -> StdResult<()> { if !is_valid_name(&self.name) { return Err(StdError::generic_err( "Name is not in the expected format (3-50 UTF-8 bytes)", )); } if !is_valid_symbol(&self.symbol) { return Err(StdError::generic_err( "Ticker symbol is not in expected format [a-zA-Z\\-]{3,12}", )); } if self.decimals > 18 { return Err(StdError::generic_err("Decimals must not exceed 18")); } Ok(()) } } fn is_valid_name(name: &str) -> bool { let bytes = name.as_bytes(); if bytes.len() < 3 || bytes.len() > 50 { return false; } true } fn is_valid_symbol(symbol: &str) -> bool { let bytes = symbol.as_bytes(); if bytes.len() < 3 || bytes.len() > 12 { return false; } for byte in bytes.iter() { if (*byte != 45) && (*byte < 65 || *byte > 90) && (*byte < 97 || *byte > 122) { return false; } } true } #[derive(Serialize, Deserialize, Clone, Debug, PartialEq, JsonSchema)] #[serde(rename_all = "snake_case")] pub enum QueryMsg { Config {}, Balance { address: String }, TokenInfo {}, Allowance { owner: String, spender: String }, AllAllowances { owner: String, start_after: Option<String>, limit: Option<u32>, }, AllAccounts { start_after: Option<String>, limit: Option<u32>, }, MarketingInfo {}, DownloadLogo {}, } #[derive(Serialize, Deserialize, Clone, Debug, PartialEq, JsonSchema)] pub struct MigrateMsg {} #[derive(Serialize, Deserialize, Clone, PartialEq, JsonSchema, Debug)] #[serde(rename_all = "snake_case")] pub enum ExecuteMsg { UpdateConfig { owner: Option<String>, }, Transfer { recipient: String, amount: Uint128 }, Burn { amount: Uint128 }, Send { contract: String, amount: Uint128, msg: Binary, }, IncreaseAllowance { spender: String, amount: Uint128, expires: Option<Expiration>, }, DecreaseAllowance { spender: String, amount: Uint128, expires: Option<Expiration>, }, TransferFrom { owner: String, recipient: String, amount: Uint128, }, SendFrom { owner: String, contract: String, amount: Uint128, msg: Binary, }, BurnFrom { owner: String, amount: Uint128 }, UpdateMarketing { project: Option<String>, description: Option<String>, marketing: Option<String>, }, UploadLogo(Logo), WithdrawLockedFunds { denom: String, amount: Uint128, recipient: String, } }
use cosmwasm_std::{StdError, StdResult, Uint128, Binary}; use cw20::{Cw20Coin, Logo}; use schemars::JsonSchema; use serde::{Deserialize, Serialize}; use cw0::Expiration; #[derive(Serialize, Deserialize, JsonSchema, Debug, Clone, PartialEq)] pub struct InstantiateMarketingInfo { pub project: Option<String>, pub description: Option<String>, pub marketing: Option<String>, pub logo: Option<Logo>, } #[derive(Serialize, Deserialize, JsonSchema, Debug, Clone, PartialEq)] pub struct InstantiateMsg { pub owner: String, pub name: String, pub symbol: String, pub decimals: u8, pub initial_balances: Vec<Cw20Coin>, pub marketing: Option<InstantiateMarketingInfo>, } impl InstantiateMsg { pub fn validate(&self) -> StdResult<()> { if !is_valid_name(&self.name) { return Err(StdError::generic_err( "Name is not in the expected format (3-50 UTF-8 bytes)", )); } if !i
} fn is_valid_name(name: &str) -> bool { let bytes = name.as_bytes(); if bytes.len() < 3 || bytes.len() > 50 { return false; } true } fn is_valid_symbol(symbol: &str) -> bool { let bytes = symbol.as_bytes(); if bytes.len() < 3 || bytes.len() > 12 { return false; } for byte in bytes.iter() { if (*byte != 45) && (*byte < 65 || *byte > 90) && (*byte < 97 || *byte > 122) { return false; } } true } #[derive(Serialize, Deserialize, Clone, Debug, PartialEq, JsonSchema)] #[serde(rename_all = "snake_case")] pub enum QueryMsg { Config {}, Balance { address: String }, TokenInfo {}, Allowance { owner: String, spender: String }, AllAllowances { owner: String, start_after: Option<String>, limit: Option<u32>, }, AllAccounts { start_after: Option<String>, limit: Option<u32>, }, MarketingInfo {}, DownloadLogo {}, } #[derive(Serialize, Deserialize, Clone, Debug, PartialEq, JsonSchema)] pub struct MigrateMsg {} #[derive(Serialize, Deserialize, Clone, PartialEq, JsonSchema, Debug)] #[serde(rename_all = "snake_case")] pub enum ExecuteMsg { UpdateConfig { owner: Option<String>, }, Transfer { recipient: String, amount: Uint128 }, Burn { amount: Uint128 }, Send { contract: String, amount: Uint128, msg: Binary, }, IncreaseAllowance { spender: String, amount: Uint128, expires: Option<Expiration>, }, DecreaseAllowance { spender: String, amount: Uint128, expires: Option<Expiration>, }, TransferFrom { owner: String, recipient: String, amount: Uint128, }, SendFrom { owner: String, contract: String, amount: Uint128, msg: Binary, }, BurnFrom { owner: String, amount: Uint128 }, UpdateMarketing { project: Option<String>, description: Option<String>, marketing: Option<String>, }, UploadLogo(Logo), WithdrawLockedFunds { denom: String, amount: Uint128, recipient: String, } }
s_valid_symbol(&self.symbol) { return Err(StdError::generic_err( "Ticker symbol is not in expected format [a-zA-Z\\-]{3,12}", )); } if self.decimals > 18 { return Err(StdError::generic_err("Decimals must not exceed 18")); } Ok(()) }
function_block-function_prefixed
[ { "content": "pub fn query_allowance(deps: Deps, owner: String, spender: String) -> StdResult<AllowanceResponse> {\n\n let owner_addr = deps.api.addr_validate(&owner)?;\n\n let spender_addr = deps.api.addr_validate(&spender)?;\n\n let allowance = ALLOWANCES\n\n .may_load(deps.storage, (&owner_addr, &spender_addr))?\n\n .unwrap_or_default();\n\n Ok(allowance)\n\n}\n\n\n\n#[cfg(test)]\n\nmod tests {\n\n use super::*;\n\n\n\n use cosmwasm_std::testing::{mock_dependencies, mock_env, mock_info};\n\n use cosmwasm_std::{coins, CosmosMsg, SubMsg, Timestamp, WasmMsg};\n\n use cw20::{Cw20Coin, TokenInfoResponse};\n\n\n\n use crate::contract::{execute, instantiate, query_balance, query_token_info};\n\n use crate::msg::{ExecuteMsg, InstantiateMsg};\n\n\n", "file_path": "contracts/tland-token/src/allowances.rs", "rank": 0, "score": 206046.8987795983 }, { "content": "/// Validates XML logo\n\nfn verify_xml_logo(logo: &[u8]) -> Result<(), ContractError> {\n\n verify_xml_preamble(logo)?;\n\n\n\n if logo.len() > LOGO_SIZE_CAP {\n\n Err(ContractError::LogoTooBig {})\n\n } else {\n\n Ok(())\n\n }\n\n}\n\n\n", "file_path": "contracts/tland-token/src/contract.rs", "rank": 1, "score": 162589.27469019959 }, { "content": "/// Validates png logo\n\nfn verify_png_logo(logo: &[u8]) -> Result<(), ContractError> {\n\n // PNG header format:\n\n // 0x89 - magic byte, out of ASCII table to fail on 7-bit systems\n\n // \"PNG\" ascii representation\n\n // [0x0d, 0x0a] - dos style line ending\n\n // 0x1a - dos control character, stop displaying rest of the file\n\n // 0x0a - unix style line ending\n\n const HEADER: [u8; 8] = [0x89, b'P', b'N', b'G', 0x0d, 0x0a, 0x1a, 0x0a];\n\n if logo.len() > LOGO_SIZE_CAP {\n\n Err(ContractError::LogoTooBig {})\n\n } else if !logo.starts_with(&HEADER) {\n\n Err(ContractError::InvalidPngHeader {})\n\n } else {\n\n Ok(())\n\n }\n\n}\n\n\n", "file_path": "contracts/tland-token/src/contract.rs", "rank": 2, "score": 162589.27469019959 }, { "content": "#[inline]\n\nfn coin_to_string(amount: Uint128, denom: &str) -> String {\n\n format!(\"{} {}\", amount, denom)\n\n}\n\n\n", "file_path": "contracts/staking/src/contract.rs", "rank": 3, "score": 162305.98595837218 }, { "content": "pub fn query_member(deps: Deps, addr: String) -> StdResult<MemberResponse> {\n\n let addr = deps.api.addr_validate(&addr)?;\n\n let cfg = CONFIG.load(deps.storage)?;\n\n let member = MEMBERS.may_load(deps.storage, &addr)?;\n\n\n\n let res: Option<MemberResponseItem> = match member {\n\n Some(m) => {\n\n let passed_missions = check_missions(&deps.querier, &cfg, &addr)?;\n\n let available_to_claim = calc_claim_amount(&passed_missions, &m)?;\n\n\n\n Some(MemberResponseItem {\n\n amount: m.amount,\n\n available_to_claim,\n\n claimed: m.claimed,\n\n passed_missions,\n\n })\n\n }\n\n None => None,\n\n };\n\n\n\n Ok(MemberResponse { member: res })\n\n}\n\n\n\n// settings for pagination\n\nconst MAX_LIMIT: u32 = 30;\n\nconst DEFAULT_LIMIT: u32 = 10;\n\n\n", "file_path": "contracts/airdrop/src/contract.rs", "rank": 4, "score": 154908.21702317288 }, { "content": "pub fn query_balance(deps: Deps, address: String) -> StdResult<BalanceResponse> {\n\n let address = deps.api.addr_validate(&address)?;\n\n let balance = BALANCES\n\n .may_load(deps.storage, &address)?\n\n .unwrap_or_default();\n\n Ok(BalanceResponse { balance })\n\n}\n\n\n", "file_path": "contracts/tland-token/src/contract.rs", "rank": 5, "score": 153129.35807332577 }, { "content": "pub fn query_marketing_info(deps: Deps) -> StdResult<MarketingInfoResponse> {\n\n Ok(MARKETING_INFO.may_load(deps.storage)?.unwrap_or_default())\n\n}\n\n\n", "file_path": "contracts/tland-token/src/contract.rs", "rank": 6, "score": 148833.49148589242 }, { "content": "pub fn query_download_logo(deps: Deps) -> StdResult<DownloadLogoResponse> {\n\n let logo = LOGO.load(deps.storage)?;\n\n match logo {\n\n Logo::Embedded(EmbeddedLogo::Svg(logo)) => Ok(DownloadLogoResponse {\n\n mime_type: \"image/svg+xml\".to_owned(),\n\n data: logo,\n\n }),\n\n Logo::Embedded(EmbeddedLogo::Png(logo)) => Ok(DownloadLogoResponse {\n\n mime_type: \"image/png\".to_owned(),\n\n data: logo,\n\n }),\n\n Logo::Url(_) => Err(StdError::not_found(\"logo\")),\n\n }\n\n}\n\n\n", "file_path": "contracts/tland-token/src/contract.rs", "rank": 7, "score": 148776.50243323238 }, { "content": "pub fn create_accounts(deps: &mut DepsMut, accounts: &[Cw20Coin]) -> StdResult<Uint128> {\n\n let mut total_supply = Uint128::zero();\n\n for row in accounts {\n\n let address = deps.api.addr_validate(&row.address)?;\n\n BALANCES.save(deps.storage, &address, &row.amount)?;\n\n total_supply += row.amount;\n\n }\n\n Ok(total_supply)\n\n}\n\n\n", "file_path": "contracts/tland-token/src/contract.rs", "rank": 8, "score": 146341.42713396816 }, { "content": "pub fn query_member(deps: Deps, addr: String, time: u64) -> StdResult<MemberResponse> {\n\n let addr = deps.api.addr_validate(&addr)?;\n\n let cfg = CONFIG.load(deps.storage)?;\n\n let member = MEMBERS.may_load(deps.storage, &addr)?;\n\n\n\n let res: Option<MemberResponseItem> = match member {\n\n Some(m) => Some(MemberResponseItem {\n\n amount: m.amount,\n\n available_to_claim: compute_available_amount(&m, &cfg, time),\n\n claimed: m.claimed,\n\n }),\n\n None => None,\n\n };\n\n\n\n Ok(MemberResponse { member: res })\n\n}\n\n\n\n// settings for pagination\n\nconst MAX_LIMIT: u32 = 30;\n\nconst DEFAULT_LIMIT: u32 = 10;\n\n\n", "file_path": "contracts/vesting/src/contract.rs", "rank": 9, "score": 144587.0345551035 }, { "content": "pub fn execute_update_marketing(\n\n deps: DepsMut,\n\n _env: Env,\n\n info: MessageInfo,\n\n project: Option<String>,\n\n description: Option<String>,\n\n marketing: Option<String>,\n\n) -> Result<Response, ContractError> {\n\n let mut marketing_info = MARKETING_INFO\n\n .may_load(deps.storage)?\n\n .ok_or(ContractError::Unauthorized {})?;\n\n\n\n if marketing_info\n\n .marketing\n\n .as_ref()\n\n .ok_or(ContractError::Unauthorized {})?\n\n != &info.sender\n\n {\n\n return Err(ContractError::Unauthorized {});\n\n }\n", "file_path": "contracts/tland-token/src/contract.rs", "rank": 10, "score": 142215.4033153553 }, { "content": "pub fn execute_upload_logo(\n\n deps: DepsMut,\n\n _env: Env,\n\n info: MessageInfo,\n\n logo: Logo,\n\n) -> Result<Response, ContractError> {\n\n let mut marketing_info = MARKETING_INFO\n\n .may_load(deps.storage)?\n\n .ok_or(ContractError::Unauthorized {})?;\n\n\n\n verify_logo(&logo)?;\n\n\n\n if marketing_info\n\n .marketing\n\n .as_ref()\n\n .ok_or(ContractError::Unauthorized {})?\n\n != &info.sender\n\n {\n\n return Err(ContractError::Unauthorized {});\n\n }\n", "file_path": "contracts/tland-token/src/contract.rs", "rank": 11, "score": 142166.07695167133 }, { "content": "#[cfg_attr(not(feature = \"library\"), entry_point)]\n\npub fn query(deps: Deps, _env: Env, msg: QueryMsg) -> StdResult<Binary> {\n\n match msg {\n\n QueryMsg::Config {} => to_binary(&query_config(deps)?),\n\n QueryMsg::State {} => to_binary(&query_state(deps)?),\n\n QueryMsg::Member { address } => to_binary(&query_member(deps, address)?),\n\n QueryMsg::ListMembers { start_after, limit } =>\n\n to_binary(&query_member_list(deps, start_after, limit)?),\n\n }\n\n}\n\n\n", "file_path": "contracts/airdrop/src/contract.rs", "rank": 12, "score": 127826.93090921504 }, { "content": "#[cfg_attr(not(feature = \"library\"), entry_point)]\n\npub fn query(deps: Deps, env: Env, msg: QueryMsg) -> StdResult<Binary> {\n\n match msg {\n\n QueryMsg::Config {} => to_binary(&query_config(deps)?),\n\n QueryMsg::State {} => to_binary(&query_state(deps)?),\n\n QueryMsg::Member { address } =>\n\n to_binary(&query_member(deps, address, env.block.time.seconds())?),\n\n QueryMsg::ListMembers { start_after, limit } =>\n\n to_binary(&query_member_list(deps, start_after, limit, env.block.time.seconds())?),\n\n }\n\n}\n\n\n", "file_path": "contracts/vesting/src/contract.rs", "rank": 13, "score": 127826.93090921504 }, { "content": "#[cfg_attr(not(feature = \"library\"), entry_point)]\n\npub fn query(deps: Deps, env: Env, msg: QueryMsg) -> StdResult<Binary> {\n\n match msg {\n\n QueryMsg::Config {} => to_binary(&query_config(deps)?),\n\n QueryMsg::State {} => to_binary(&query_state(deps)?),\n\n QueryMsg::Member { address } => to_binary(&query_member(deps, env, address)?),\n\n QueryMsg::ListMembers { start_after, limit } =>\n\n to_binary(&query_member_list(deps, env, start_after, limit)?),\n\n }\n\n}\n\n\n", "file_path": "contracts/staking/src/contract.rs", "rank": 14, "score": 127826.93090921504 }, { "content": "#[cfg_attr(not(feature = \"library\"), entry_point)]\n\npub fn query(deps: Deps, _env: Env, msg: QueryMsg) -> StdResult<Binary> {\n\n match msg {\n\n QueryMsg::Config {} => to_binary(&query_config(deps)?),\n\n QueryMsg::Balance { address } => to_binary(&query_balance(deps, address)?),\n\n QueryMsg::TokenInfo {} => to_binary(&query_token_info(deps)?),\n\n QueryMsg::Allowance { owner, spender } => {\n\n to_binary(&query_allowance(deps, owner, spender)?)\n\n }\n\n QueryMsg::AllAllowances {\n\n owner,\n\n start_after,\n\n limit,\n\n } => to_binary(&query_all_allowances(deps, owner, start_after, limit)?),\n\n QueryMsg::AllAccounts { start_after, limit } => {\n\n to_binary(&query_all_accounts(deps, start_after, limit)?)\n\n }\n\n QueryMsg::MarketingInfo {} => to_binary(&query_marketing_info(deps)?),\n\n QueryMsg::DownloadLogo {} => to_binary(&query_download_logo(deps)?),\n\n }\n\n}\n\n\n", "file_path": "contracts/tland-token/src/contract.rs", "rank": 15, "score": 126123.11858904775 }, { "content": "/// Checks if passed logo is correct, and if not, returns an error\n\nfn verify_logo(logo: &Logo) -> Result<(), ContractError> {\n\n match logo {\n\n Logo::Embedded(EmbeddedLogo::Svg(logo)) => verify_xml_logo(&logo),\n\n Logo::Embedded(EmbeddedLogo::Png(logo)) => verify_png_logo(&logo),\n\n Logo::Url(_) => Ok(()), // Any reasonable url validation would be regex based, probably not worth it\n\n }\n\n}\n\n\n", "file_path": "contracts/tland-token/src/contract.rs", "rank": 16, "score": 123560.43583850912 }, { "content": "fn compute_member_reward(member_info: &MemberInfo, global_reward_index: Decimal) -> Uint128 {\n\n let pending_reward = member_info.stake * global_reward_index\n\n - member_info.stake * member_info.reward_index;\n\n\n\n return member_info.pending_reward + pending_reward;\n\n}\n\n\n", "file_path": "contracts/staking/src/contract.rs", "rank": 17, "score": 120245.30493821099 }, { "content": "pub fn query_config(deps: Deps) -> StdResult<Config> {\n\n Ok(CONFIG.load(deps.storage)?)\n\n}\n\n\n", "file_path": "contracts/airdrop/src/contract.rs", "rank": 18, "score": 116787.61230345952 }, { "content": "pub fn query_state(deps: Deps) -> StdResult<State> {\n\n Ok(STATE.load(deps.storage)?)\n\n}\n\n\n", "file_path": "contracts/vesting/src/contract.rs", "rank": 19, "score": 116787.61230345952 }, { "content": "pub fn query_config(deps: Deps) -> StdResult<Config> {\n\n Ok(CONFIG.load(deps.storage)?)\n\n}\n\n\n", "file_path": "contracts/vesting/src/contract.rs", "rank": 20, "score": 116787.61230345952 }, { "content": "pub fn query_state(deps: Deps) -> StdResult<State> {\n\n Ok(STATE.load(deps.storage)?)\n\n}\n\n\n", "file_path": "contracts/airdrop/src/contract.rs", "rank": 21, "score": 116787.61230345952 }, { "content": "pub fn query_config(deps: Deps) -> StdResult<Config> {\n\n Ok(CONFIG.load(deps.storage)?)\n\n}\n\n\n", "file_path": "contracts/staking/src/contract.rs", "rank": 22, "score": 116787.61230345952 }, { "content": "pub fn query_config(deps: Deps) -> StdResult<Config> {\n\n Ok(CONFIG.load(deps.storage)?)\n\n}\n\n\n", "file_path": "contracts/tland-token/src/contract.rs", "rank": 25, "score": 115444.54022614454 }, { "content": "#[cfg_attr(not(feature = \"library\"), entry_point)]\n\npub fn instantiate(\n\n deps: DepsMut,\n\n _env: Env,\n\n _info: MessageInfo,\n\n msg: InstantiateMsg,\n\n) -> Result<Response, ContractError> {\n\n set_contract_version(deps.storage, CONTRACT_NAME, CONTRACT_VERSION)?;\n\n\n\n let config = Config {\n\n owner: deps.api.addr_validate(&msg.owner)?,\n\n terraland_token: deps.api.addr_validate(&msg.terraland_token)?,\n\n name: msg.name,\n\n fee_config: msg.fee_config,\n\n vesting: msg.vesting,\n\n };\n\n\n\n CONFIG.save(deps.storage, &config)?;\n\n STATE.save(deps.storage, &State { num_of_members: 0 })?;\n\n\n\n Ok(Response::default())\n\n}\n\n\n", "file_path": "contracts/vesting/src/contract.rs", "rank": 26, "score": 115342.30916631679 }, { "content": "#[cfg_attr(not(feature = \"library\"), entry_point)]\n\npub fn execute(\n\n deps: DepsMut,\n\n env: Env,\n\n info: MessageInfo,\n\n msg: ExecuteMsg,\n\n) -> Result<Response, ContractError> {\n\n match msg {\n\n ExecuteMsg::UpdateConfig { owner, fee_config, mission_smart_contracts } =>\n\n execute_update_config(deps, env, info, owner, fee_config, mission_smart_contracts),\n\n ExecuteMsg::RegisterMembers(members) =>\n\n execute_register_members(deps, env, info, members),\n\n ExecuteMsg::RemoveMembers(addresses) =>\n\n execute_remove_members(deps, env, info, addresses),\n\n ExecuteMsg::Claim {} => execute_claim(deps, env, info),\n\n ExecuteMsg::UstWithdraw { recipient, amount } =>\n\n execute_ust_withdraw(deps, env, info, recipient, amount),\n\n ExecuteMsg::TokenWithdraw { token, recipient } =>\n\n execute_token_withdraw(deps, env, info, token, recipient),\n\n }\n\n}\n\n\n", "file_path": "contracts/airdrop/src/contract.rs", "rank": 27, "score": 115342.30916631679 }, { "content": "#[cfg_attr(not(feature = \"library\"), entry_point)]\n\npub fn execute(\n\n deps: DepsMut,\n\n env: Env,\n\n info: MessageInfo,\n\n msg: ExecuteMsg,\n\n) -> Result<Response, ContractError> {\n\n match msg {\n\n ExecuteMsg::UpdateConfig { owner, name, fee_config, vesting } =>\n\n execute_update_config(deps, env, info, owner, name, fee_config, vesting),\n\n ExecuteMsg::RegisterMembers(members) =>\n\n execute_register_members(deps, env, info, members),\n\n ExecuteMsg::Claim {} => execute_claim(deps, env, info),\n\n ExecuteMsg::UstWithdraw { recipient, amount } =>\n\n execute_ust_withdraw(deps, env, info, recipient, amount),\n\n ExecuteMsg::TokenWithdraw { token, recipient } =>\n\n execute_token_withdraw(deps, env, info, token, recipient),\n\n }\n\n}\n\n\n", "file_path": "contracts/vesting/src/contract.rs", "rank": 28, "score": 115342.30916631679 }, { "content": "#[cfg_attr(not(feature = \"library\"), entry_point)]\n\npub fn execute(\n\n deps: DepsMut,\n\n env: Env,\n\n info: MessageInfo,\n\n msg: ExecuteMsg,\n\n) -> Result<Response, ContractError> {\n\n match msg {\n\n ExecuteMsg::UpdateConfig(new_config) => execute_update_config(deps, env, info, new_config),\n\n ExecuteMsg::Receive(msg) => execute_receive(deps, env, info, msg),\n\n ExecuteMsg::Unbond { tokens: amount } => execute_unbond(deps, env, info, amount),\n\n ExecuteMsg::Claim {} => execute_claim(deps, env, info),\n\n ExecuteMsg::InstantClaim {} => execute_instant_claim(deps, env, info),\n\n ExecuteMsg::Withdraw {} => execute_withdraw(deps, env, info),\n\n ExecuteMsg::UstWithdraw { recipient, amount } =>\n\n execute_ust_withdraw(deps, env, info, recipient, amount),\n\n ExecuteMsg::TokenWithdraw { token, recipient } =>\n\n execute_token_withdraw(deps, env, info, token, recipient),\n\n }\n\n}\n\n\n", "file_path": "contracts/staking/src/contract.rs", "rank": 29, "score": 115342.30916631679 }, { "content": "#[cfg_attr(not(feature = \"library\"), entry_point)]\n\npub fn instantiate(\n\n deps: DepsMut,\n\n _env: Env,\n\n _info: MessageInfo,\n\n msg: InstantiateMsg,\n\n) -> Result<Response, ContractError> {\n\n set_contract_version(deps.storage, CONTRACT_NAME, CONTRACT_VERSION)?;\n\n\n\n let config = Config {\n\n owner: deps.api.addr_validate(&msg.owner)?,\n\n staking_token: deps.api.addr_validate(&msg.staking_token)?,\n\n terraland_token: deps.api.addr_validate(&msg.terraland_token)?,\n\n unbonding_period: msg.unbonding_period,\n\n burn_address: deps.api.addr_validate(&msg.burn_address)?,\n\n instant_claim_percentage_loss: msg.instant_claim_percentage_loss,\n\n distribution_schedule: msg.distribution_schedule,\n\n fee_config: msg.fee_config,\n\n };\n\n\n\n let state = State {\n", "file_path": "contracts/staking/src/contract.rs", "rank": 30, "score": 115342.30916631679 }, { "content": "#[cfg_attr(not(feature = \"library\"), entry_point)]\n\npub fn instantiate(\n\n deps: DepsMut,\n\n _env: Env,\n\n _info: MessageInfo,\n\n msg: InstantiateMsg,\n\n) -> Result<Response, ContractError> {\n\n set_contract_version(deps.storage, CONTRACT_NAME, CONTRACT_VERSION)?;\n\n\n\n let config = Config {\n\n owner: deps.api.addr_validate(&msg.owner)?,\n\n terraland_token: deps.api.addr_validate(&msg.terraland_token)?,\n\n fee_config: msg.fee_config,\n\n mission_smart_contracts: mission_smart_contracts_from(&deps, msg.mission_smart_contracts)?,\n\n };\n\n\n\n CONFIG.save(deps.storage, &config)?;\n\n STATE.save(deps.storage, &State { num_of_members: 0 })?;\n\n\n\n Ok(Response::default())\n\n}\n\n\n", "file_path": "contracts/airdrop/src/contract.rs", "rank": 31, "score": 115342.30916631679 }, { "content": "fn calc_claim_amount(missions: &Missions, member: &Member) -> StdResult<Uint128> {\n\n let passed_missions_num = calc_missions_passed(&missions);\n\n\n\n // amount earned equals amount multiplied by percentage of passed missions\n\n let amount_earned = member.amount\n\n .checked_mul(Uint128::from(passed_missions_num))\n\n .map_err(StdError::overflow)?\n\n .div(Uint128::new(NUM_OF_MISSIONS as u128));\n\n\n\n // claim amount is amount_earned minus already claimed\n\n Ok(amount_earned\n\n .checked_sub(member.claimed)\n\n .unwrap_or_default())\n\n}\n\n\n", "file_path": "contracts/airdrop/src/contract.rs", "rank": 32, "score": 114339.29956541384 }, { "content": "pub fn execute_claim(\n\n deps: DepsMut,\n\n _env: Env,\n\n info: MessageInfo,\n\n) -> Result<Response, ContractError> {\n\n let cfg = CONFIG.load(deps.storage)?;\n\n\n\n // sender has to pay 1 UST to claim\n\n must_pay_fee(&info, &cfg, \"claim\".to_string())?;\n\n\n\n let member = MEMBERS.may_load(deps.storage, &info.sender)?;\n\n\n\n let amount = match member {\n\n Some(mut member) => {\n\n // check missions passed by the sender\n\n let missions = check_missions(&deps.querier, &cfg, &info.sender)?;\n\n // calculate amount to claim based on passed missions\n\n let available_to_claim = calc_claim_amount(&missions, &member)?;\n\n // update member claimed amount\n\n member.claimed += available_to_claim;\n", "file_path": "contracts/airdrop/src/contract.rs", "rank": 33, "score": 113511.39525024252 }, { "content": "pub fn execute_unbond(\n\n deps: DepsMut,\n\n env: Env,\n\n info: MessageInfo,\n\n amount: Uint128,\n\n) -> Result<Response, ContractError> {\n\n let cfg = CONFIG.load(deps.storage)?;\n\n\n\n // sender has to pay fee to unbond\n\n must_pay_fee(&info, &cfg, \"unbond\".to_string())?;\n\n\n\n // provide them a claim\n\n CLAIMS.create_claim(\n\n deps.storage,\n\n &info.sender,\n\n amount,\n\n Duration::Time(cfg.unbonding_period).after(&env.block),\n\n )?;\n\n\n\n let mut state = STATE.load(deps.storage)?;\n", "file_path": "contracts/staking/src/contract.rs", "rank": 34, "score": 113511.39525024252 }, { "content": "pub fn execute_receive(\n\n deps: DepsMut,\n\n env: Env,\n\n info: MessageInfo,\n\n wrapper: Cw20ReceiveMsg,\n\n) -> Result<Response, ContractError> {\n\n // info.sender is the address of the cw20 contract (that re-sent this message).\n\n // wrapper.sender is the address of the user that requested the cw20 contract to send this.\n\n // This cannot be fully trusted (the cw20 contract can fake it), so only use it for actions\n\n // in the address's favor (like paying/bonding tokens, not withdrawls)\n\n let msg: ReceiveMsg = from_slice(&wrapper.msg)?;\n\n let balance = Balance::Cw20(Cw20CoinVerified {\n\n address: info.sender,\n\n amount: wrapper.amount,\n\n });\n\n let api = deps.api;\n\n match msg {\n\n ReceiveMsg::Bond {} => {\n\n execute_bond(deps, env, balance, api.addr_validate(&wrapper.sender)?)\n\n }\n\n }\n\n}\n\n\n", "file_path": "contracts/staking/src/contract.rs", "rank": 35, "score": 113511.39525024252 }, { "content": "pub fn execute_claim(\n\n deps: DepsMut,\n\n env: Env,\n\n info: MessageInfo,\n\n) -> Result<Response, ContractError> {\n\n let cfg = CONFIG.load(deps.storage)?;\n\n\n\n // sender has to pay fee to claim\n\n must_pay_fee(&info, &cfg, \"claim\".to_string())?;\n\n\n\n // get amount of tokens to release\n\n let release = CLAIMS.claim_tokens(deps.storage, &info.sender, &env.block, None)?;\n\n if release.is_zero() {\n\n return Err(ContractError::NothingToClaim {});\n\n }\n\n\n\n // create message to transfer staking tokens\n\n let message = SubMsg::new(WasmMsg::Execute {\n\n contract_addr: cfg.staking_token.clone().into(),\n\n msg: to_binary(&Cw20ExecuteMsg::Transfer {\n", "file_path": "contracts/staking/src/contract.rs", "rank": 36, "score": 113511.39525024252 }, { "content": "pub fn execute_bond(\n\n deps: DepsMut,\n\n env: Env,\n\n amount: Balance,\n\n sender: Addr,\n\n) -> Result<Response, ContractError> {\n\n let cfg = CONFIG.load(deps.storage)?;\n\n\n\n // ensure the sent token was proper\n\n let amount = match &amount {\n\n Balance::Cw20(token) => {\n\n if token.address == cfg.staking_token {\n\n Ok(token.amount)\n\n } else {\n\n Err(ContractError::InvalidToken(token.address.to_string()))\n\n }\n\n }\n\n _ => Err(ContractError::MissedToken {})\n\n }?;\n\n\n", "file_path": "contracts/staking/src/contract.rs", "rank": 37, "score": 113511.39525024252 }, { "content": "#[cfg_attr(not(feature = \"library\"), entry_point)]\n\npub fn instantiate(\n\n mut deps: DepsMut,\n\n _env: Env,\n\n _info: MessageInfo,\n\n msg: InstantiateMsg,\n\n) -> Result<Response, ContractError> {\n\n set_contract_version(deps.storage, CONTRACT_NAME, CONTRACT_VERSION)?;\n\n // check valid token info\n\n msg.validate()?;\n\n // create initial accounts\n\n let total_supply = create_accounts(&mut deps, &msg.initial_balances)?;\n\n\n\n // store token info\n\n let data = TokenInfo {\n\n name: msg.name,\n\n symbol: msg.symbol,\n\n decimals: msg.decimals,\n\n total_supply,\n\n };\n\n TOKEN_INFO.save(deps.storage, &data)?;\n", "file_path": "contracts/tland-token/src/contract.rs", "rank": 38, "score": 113511.39525024252 }, { "content": "#[cfg_attr(not(feature = \"library\"), entry_point)]\n\npub fn execute(\n\n deps: DepsMut,\n\n env: Env,\n\n info: MessageInfo,\n\n msg: ExecuteMsg,\n\n) -> Result<Response, ContractError> {\n\n match msg {\n\n ExecuteMsg::UpdateConfig { owner } =>\n\n execute_update_config(deps, env, info, owner),\n\n ExecuteMsg::Transfer { recipient, amount } => {\n\n execute_transfer(deps, env, info, recipient, amount)\n\n }\n\n ExecuteMsg::Burn { amount } => execute_burn(deps, env, info, amount),\n\n ExecuteMsg::Send {\n\n contract,\n\n amount,\n\n msg,\n\n } => execute_send(deps, env, info, contract, amount, msg),\n\n ExecuteMsg::IncreaseAllowance {\n\n spender,\n", "file_path": "contracts/tland-token/src/contract.rs", "rank": 39, "score": 113511.39525024252 }, { "content": "pub fn execute_claim(\n\n deps: DepsMut,\n\n env: Env,\n\n info: MessageInfo,\n\n) -> Result<Response, ContractError> {\n\n let cfg = CONFIG.load(deps.storage)?;\n\n\n\n // sender has to pay fee to claim\n\n must_pay_fee(&info, &cfg, \"claim\".to_string())?;\n\n\n\n let member = MEMBERS.may_load(deps.storage, &info.sender)?;\n\n\n\n let amount = match member {\n\n Some(mut member) => {\n\n // compute amount available to claim\n\n let available_to_claim = compute_available_amount(&member, &cfg, env.block.time.seconds());\n\n // update member claimed amount\n\n member.claimed += available_to_claim;\n\n MEMBERS.save(deps.storage, &info.sender, &member)?;\n\n Ok(available_to_claim)\n", "file_path": "contracts/vesting/src/contract.rs", "rank": 40, "score": 113511.39525024252 }, { "content": "pub fn execute_withdraw(\n\n deps: DepsMut,\n\n env: Env,\n\n info: MessageInfo,\n\n) -> Result<Response, ContractError> {\n\n let cfg = CONFIG.load(deps.storage)?;\n\n\n\n // sender has to pay fee to withdraw\n\n must_pay_fee(&info, &cfg, \"withdraw\".to_string())?;\n\n\n\n let state = STATE.load(deps.storage)?;\n\n let mut member_info = MEMBERS.may_load(deps.storage, &info.sender)?\n\n .unwrap_or(Default::default());\n\n\n\n // calculate member reward until current block or end of distribution\n\n update_member_reward(&state, &cfg, env.block.time.seconds(), &mut member_info)?;\n\n\n\n // amount to withdraw is difference between the reward and the withdraw amount\n\n let amount = member_info.pending_reward.checked_sub(member_info.withdrawn)\n\n .map_err(StdError::overflow)?;\n", "file_path": "contracts/staking/src/contract.rs", "rank": 41, "score": 113511.39525024252 }, { "content": "// this can be used to update a lower allowance - call bucket.update with proper keys\n\npub fn deduct_allowance(\n\n storage: &mut dyn Storage,\n\n owner: &Addr,\n\n spender: &Addr,\n\n block: &BlockInfo,\n\n amount: Uint128,\n\n) -> Result<AllowanceResponse, ContractError> {\n\n ALLOWANCES.update(storage, (owner, spender), |current| {\n\n match current {\n\n Some(mut a) => {\n\n if a.expires.is_expired(block) {\n\n Err(ContractError::Expired {})\n\n } else {\n\n // deduct the allowance if enough\n\n a.allowance = a\n\n .allowance\n\n .checked_sub(amount)\n\n .map_err(StdError::overflow)?;\n\n Ok(a)\n\n }\n\n }\n\n None => Err(ContractError::NoAllowance {}),\n\n }\n\n })\n\n}\n\n\n", "file_path": "contracts/tland-token/src/allowances.rs", "rank": 42, "score": 111782.30892179797 }, { "content": "pub fn execute_transfer_from(\n\n deps: DepsMut,\n\n env: Env,\n\n info: MessageInfo,\n\n owner: String,\n\n recipient: String,\n\n amount: Uint128,\n\n) -> Result<Response, ContractError> {\n\n let rcpt_addr = deps.api.addr_validate(&recipient)?;\n\n let owner_addr = deps.api.addr_validate(&owner)?;\n\n\n\n // deduct allowance before doing anything else have enough allowance\n\n deduct_allowance(deps.storage, &owner_addr, &info.sender, &env.block, amount)?;\n\n\n\n BALANCES.update(\n\n deps.storage,\n\n &owner_addr,\n\n |balance: Option<Uint128>| -> StdResult<_> {\n\n Ok(balance.unwrap_or_default().checked_sub(amount)?)\n\n },\n", "file_path": "contracts/tland-token/src/allowances.rs", "rank": 43, "score": 111778.62308301548 }, { "content": "pub fn execute_burn(\n\n deps: DepsMut,\n\n _env: Env,\n\n info: MessageInfo,\n\n amount: Uint128,\n\n) -> Result<Response, ContractError> {\n\n // authorized owner\n\n let cfg = CONFIG.load(deps.storage)?;\n\n if info.sender != cfg.owner {\n\n return Err(ContractError::Unauthorized {});\n\n }\n\n\n\n if amount == Uint128::zero() {\n\n return Err(ContractError::InvalidZeroAmount {});\n\n }\n\n\n\n // lower balance\n\n BALANCES.update(\n\n deps.storage,\n\n &info.sender,\n", "file_path": "contracts/tland-token/src/contract.rs", "rank": 44, "score": 111778.62308301548 }, { "content": "pub fn query_all_accounts(\n\n deps: Deps,\n\n start_after: Option<String>,\n\n limit: Option<u32>,\n\n) -> StdResult<AllAccountsResponse> {\n\n let limit = limit.unwrap_or(DEFAULT_LIMIT).min(MAX_LIMIT) as usize;\n\n let start = start_after.map(Bound::exclusive);\n\n\n\n let accounts: Result<Vec<_>, _> = BALANCES\n\n .keys(deps.storage, start, None, Order::Ascending)\n\n .map(String::from_utf8)\n\n .take(limit)\n\n .collect();\n\n\n\n Ok(AllAccountsResponse {\n\n accounts: accounts?,\n\n })\n\n}\n\n\n\n#[cfg(test)]\n", "file_path": "contracts/tland-token/src/enumerable.rs", "rank": 45, "score": 111778.62308301548 }, { "content": "pub fn execute_update_config(\n\n deps: DepsMut,\n\n _env: Env,\n\n info: MessageInfo,\n\n new_owner: Option<String>,\n\n new_fee_config: Option<Vec<FeeConfig>>,\n\n new_mission_smart_contracts: Option<InstantiateMissionSmartContracts>,\n\n) -> Result<Response, ContractError> {\n\n // authorized owner\n\n let cfg = CONFIG.load(deps.storage)?;\n\n if info.sender != cfg.owner {\n\n return Err(ContractError::Unauthorized {});\n\n }\n\n\n\n let api = deps.api;\n\n let new_mission_sc = mission_smart_contracts_from(&deps, new_mission_smart_contracts)?;\n\n\n\n CONFIG.update(deps.storage, |mut existing_config| -> StdResult<_> {\n\n // update new owner if set\n\n if let Some(addr) = new_owner {\n", "file_path": "contracts/airdrop/src/contract.rs", "rank": 46, "score": 111778.62308301548 }, { "content": "pub fn query_all_allowances(\n\n deps: Deps,\n\n owner: String,\n\n start_after: Option<String>,\n\n limit: Option<u32>,\n\n) -> StdResult<AllAllowancesResponse> {\n\n let owner_addr = deps.api.addr_validate(&owner)?;\n\n let limit = limit.unwrap_or(DEFAULT_LIMIT).min(MAX_LIMIT) as usize;\n\n let start = start_after.map(Bound::exclusive);\n\n\n\n let allowances: StdResult<Vec<AllowanceInfo>> = ALLOWANCES\n\n .prefix(&owner_addr)\n\n .range(deps.storage, start, None, Order::Ascending)\n\n .take(limit)\n\n .map(|item| {\n\n let (k, v) = item?;\n\n Ok(AllowanceInfo {\n\n spender: String::from_utf8(k)?,\n\n allowance: v.allowance,\n\n expires: v.expires,\n\n })\n\n })\n\n .collect();\n\n Ok(AllAllowancesResponse {\n\n allowances: allowances?,\n\n })\n\n}\n\n\n", "file_path": "contracts/tland-token/src/enumerable.rs", "rank": 47, "score": 111778.62308301548 }, { "content": "pub fn execute_send(\n\n deps: DepsMut,\n\n _env: Env,\n\n info: MessageInfo,\n\n contract: String,\n\n amount: Uint128,\n\n msg: Binary,\n\n) -> Result<Response, ContractError> {\n\n if amount == Uint128::zero() {\n\n return Err(ContractError::InvalidZeroAmount {});\n\n }\n\n\n\n let rcpt_addr = deps.api.addr_validate(&contract)?;\n\n\n\n // move the tokens to the contract\n\n BALANCES.update(\n\n deps.storage,\n\n &info.sender,\n\n |balance: Option<Uint128>| -> StdResult<_> {\n\n Ok(balance.unwrap_or_default().checked_sub(amount)?)\n", "file_path": "contracts/tland-token/src/contract.rs", "rank": 48, "score": 111778.62308301548 }, { "content": "pub fn execute_send_from(\n\n deps: DepsMut,\n\n env: Env,\n\n info: MessageInfo,\n\n owner: String,\n\n contract: String,\n\n amount: Uint128,\n\n msg: Binary,\n\n) -> Result<Response, ContractError> {\n\n let rcpt_addr = deps.api.addr_validate(&contract)?;\n\n let owner_addr = deps.api.addr_validate(&owner)?;\n\n\n\n // deduct allowance before doing anything else have enough allowance\n\n deduct_allowance(deps.storage, &owner_addr, &info.sender, &env.block, amount)?;\n\n\n\n // move the tokens to the contract\n\n BALANCES.update(\n\n deps.storage,\n\n &owner_addr,\n\n |balance: Option<Uint128>| -> StdResult<_> {\n", "file_path": "contracts/tland-token/src/allowances.rs", "rank": 49, "score": 111778.62308301548 }, { "content": "pub fn execute_instant_claim(\n\n deps: DepsMut,\n\n env: Env,\n\n info: MessageInfo,\n\n) -> Result<Response, ContractError> {\n\n let cfg = CONFIG.load(deps.storage)?;\n\n\n\n // sender has to pay fee to instant claim\n\n must_pay_fee(&info, &cfg, \"instant_claim\".to_string())?;\n\n\n\n let config = CONFIG.load(deps.storage)?;\n\n\n\n // Create block after unbonding_period to be able to release all claims\n\n let mut block = env.block.clone();\n\n block.time = block.time.plus_seconds(YEAR_IN_SEC);\n\n\n\n // get amount of tokens to release\n\n let mut release = CLAIMS.claim_tokens(deps.storage, &info.sender, &block, None)?;\n\n if release.is_zero() {\n\n return Err(ContractError::NothingToClaim {});\n", "file_path": "contracts/staking/src/contract.rs", "rank": 50, "score": 111778.62308301548 }, { "content": "pub fn execute_token_withdraw(\n\n deps: DepsMut,\n\n env: Env,\n\n info: MessageInfo,\n\n token: String,\n\n recipient: String,\n\n) -> Result<Response, ContractError> {\n\n // authorized owner\n\n let cfg = CONFIG.load(deps.storage)?;\n\n if info.sender != cfg.owner {\n\n return Err(ContractError::Unauthorized {});\n\n }\n\n\n\n // get token balance for this contract\n\n let token_addr = deps.api.addr_validate(&token)?;\n\n let query = WasmQuery::Smart {\n\n contract_addr: token_addr.to_string(),\n\n msg: to_binary(&Cw20QueryMsg::Balance {\n\n address: env.contract.address.to_string(),\n\n })?,\n", "file_path": "contracts/staking/src/contract.rs", "rank": 51, "score": 111778.62308301548 }, { "content": "pub fn execute_token_withdraw(\n\n deps: DepsMut,\n\n env: Env,\n\n info: MessageInfo,\n\n token: String,\n\n recipient: String,\n\n) -> Result<Response, ContractError> {\n\n // authorized owner\n\n let cfg = CONFIG.load(deps.storage)?;\n\n if info.sender != cfg.owner {\n\n return Err(ContractError::Unauthorized {});\n\n }\n\n\n\n // get token balance for this contract\n\n let token_addr = deps.api.addr_validate(&token)?;\n\n let query = WasmQuery::Smart {\n\n contract_addr: token_addr.to_string(),\n\n msg: to_binary(&Cw20QueryMsg::Balance {\n\n address: env.contract.address.to_string(),\n\n })?,\n", "file_path": "contracts/vesting/src/contract.rs", "rank": 52, "score": 111778.62308301548 }, { "content": "pub fn execute_register_members(\n\n deps: DepsMut,\n\n _env: Env,\n\n info: MessageInfo,\n\n members: Vec<RegisterMemberItem>,\n\n) -> Result<Response, ContractError> {\n\n // authorized owner\n\n let cfg = CONFIG.load(deps.storage)?;\n\n if info.sender != cfg.owner {\n\n return Err(ContractError::Unauthorized {});\n\n }\n\n\n\n // save all members with valid address in storage\n\n let mut new_members: u64 = 0;\n\n for m in members.iter() {\n\n let address = deps.api.addr_validate(&m.address)?;\n\n let val = Member {\n\n amount: m.amount,\n\n claimed: m.claimed.unwrap_or_default(),\n\n };\n", "file_path": "contracts/vesting/src/contract.rs", "rank": 53, "score": 111778.62308301548 }, { "content": "pub fn execute_update_config(\n\n deps: DepsMut,\n\n _env: Env,\n\n info: MessageInfo,\n\n new_config: NewConfig,\n\n) -> Result<Response, ContractError> {\n\n // authorized owner\n\n let cfg = CONFIG.load(deps.storage)?;\n\n if info.sender != cfg.owner {\n\n return Err(ContractError::Unauthorized {});\n\n }\n\n\n\n let api = deps.api;\n\n\n\n CONFIG.update(deps.storage, |mut exists| -> StdResult<_> {\n\n if let Some(addr) = new_config.owner {\n\n exists.owner = api.addr_validate(&addr)?;\n\n }\n\n if let Some(addr) = new_config.staking_token {\n\n exists.staking_token = api.addr_validate(&addr)?;\n", "file_path": "contracts/staking/src/contract.rs", "rank": 54, "score": 111778.62308301548 }, { "content": "pub fn execute_burn_from(\n\n deps: DepsMut,\n\n\n\n env: Env,\n\n info: MessageInfo,\n\n owner: String,\n\n amount: Uint128,\n\n) -> Result<Response, ContractError> {\n\n // authorized owner\n\n let cfg = CONFIG.load(deps.storage)?;\n\n if info.sender != cfg.owner {\n\n return Err(ContractError::Unauthorized {});\n\n }\n\n\n\n let owner_addr = deps.api.addr_validate(&owner)?;\n\n\n\n // deduct allowance before doing anything else have enough allowance\n\n deduct_allowance(deps.storage, &owner_addr, &info.sender, &env.block, amount)?;\n\n\n\n // lower balance\n", "file_path": "contracts/tland-token/src/allowances.rs", "rank": 55, "score": 111778.62308301548 }, { "content": "pub fn execute_ust_withdraw(\n\n deps: DepsMut,\n\n _env: Env,\n\n info: MessageInfo,\n\n recipient: String,\n\n amount: Uint128,\n\n) -> Result<Response, ContractError> {\n\n // authorized owner\n\n let cfg = CONFIG.load(deps.storage)?;\n\n if info.sender != cfg.owner {\n\n return Err(ContractError::Unauthorized {});\n\n }\n\n\n\n // create message to transfer ust\n\n let message = SubMsg::new(BankMsg::Send {\n\n to_address: String::from(deps.api.addr_validate(&recipient)?),\n\n amount: vec![Coin{ denom: \"uusd\".to_string(), amount }],\n\n });\n\n\n\n Ok(Response::new()\n\n .add_submessage(message)\n\n .add_attribute(\"action\", \"ust_withdraw\")\n\n .add_attribute(\"sender\", info.sender))\n\n}\n\n\n", "file_path": "contracts/staking/src/contract.rs", "rank": 56, "score": 111778.62308301548 }, { "content": "pub fn execute_ust_withdraw(\n\n deps: DepsMut,\n\n _env: Env,\n\n info: MessageInfo,\n\n recipient: String,\n\n amount: Uint128,\n\n) -> Result<Response, ContractError> {\n\n // authorized owner\n\n let cfg = CONFIG.load(deps.storage)?;\n\n if info.sender != cfg.owner {\n\n return Err(ContractError::Unauthorized {});\n\n }\n\n\n\n // create message to transfer ust\n\n let message = SubMsg::new(BankMsg::Send {\n\n to_address: String::from(deps.api.addr_validate(&recipient)?),\n\n amount: vec![Coin { denom: \"uusd\".to_string(), amount }],\n\n });\n\n\n\n Ok(Response::new()\n\n .add_submessage(message)\n\n .add_attribute(\"action\", \"ust_withdraw\")\n\n .add_attribute(\"sender\", info.sender))\n\n}\n\n\n", "file_path": "contracts/airdrop/src/contract.rs", "rank": 57, "score": 111778.62308301548 }, { "content": "pub fn execute_transfer(\n\n deps: DepsMut,\n\n _env: Env,\n\n info: MessageInfo,\n\n recipient: String,\n\n amount: Uint128,\n\n) -> Result<Response, ContractError> {\n\n if amount == Uint128::zero() {\n\n return Err(ContractError::InvalidZeroAmount {});\n\n }\n\n\n\n let rcpt_addr = deps.api.addr_validate(&recipient)?;\n\n\n\n BALANCES.update(\n\n deps.storage,\n\n &info.sender,\n\n |balance: Option<Uint128>| -> StdResult<_> {\n\n Ok(balance.unwrap_or_default().checked_sub(amount)?)\n\n },\n\n )?;\n", "file_path": "contracts/tland-token/src/contract.rs", "rank": 58, "score": 111778.62308301548 }, { "content": "pub fn execute_token_withdraw(\n\n deps: DepsMut,\n\n env: Env,\n\n info: MessageInfo,\n\n token: String,\n\n recipient: String,\n\n) -> Result<Response, ContractError> {\n\n // authorized owner\n\n let cfg = CONFIG.load(deps.storage)?;\n\n if info.sender != cfg.owner {\n\n return Err(ContractError::Unauthorized {});\n\n }\n\n\n\n // get token balance for this contract\n\n let token_addr = deps.api.addr_validate(&token)?;\n\n let query = WasmQuery::Smart {\n\n contract_addr: token_addr.to_string(),\n\n msg: to_binary(&Cw20QueryMsg::Balance {\n\n address: env.contract.address.to_string(),\n\n })?,\n", "file_path": "contracts/airdrop/src/contract.rs", "rank": 59, "score": 111778.62308301548 }, { "content": "pub fn execute_update_config(\n\n deps: DepsMut,\n\n _env: Env,\n\n info: MessageInfo,\n\n new_owner: Option<String>,\n\n new_name: Option<String>,\n\n new_fee_config: Option<Vec<FeeConfig>>,\n\n new_vesting: Option<Vesting>,\n\n) -> Result<Response, ContractError> {\n\n // authorized owner\n\n let cfg = CONFIG.load(deps.storage)?;\n\n if info.sender != cfg.owner {\n\n return Err(ContractError::Unauthorized {});\n\n }\n\n\n\n let api = deps.api;\n\n\n\n CONFIG.update(deps.storage, |mut existing_config| -> StdResult<_> {\n\n // update new owner if set\n\n if let Some(addr) = new_owner {\n", "file_path": "contracts/vesting/src/contract.rs", "rank": 60, "score": 111778.62308301548 }, { "content": "pub fn execute_remove_members(\n\n deps: DepsMut,\n\n _env: Env,\n\n info: MessageInfo,\n\n addresses: Vec<String>,\n\n) -> Result<Response, ContractError> {\n\n // authorized owner\n\n let cfg = CONFIG.load(deps.storage)?;\n\n if info.sender != cfg.owner {\n\n return Err(ContractError::Unauthorized {});\n\n }\n\n\n\n let mut removed: u64 = 0;\n\n for address in addresses.iter() {\n\n let addr = deps.api.addr_validate(address)?;\n\n if MEMBERS.has(deps.storage, &addr) {\n\n removed += 1;\n\n };\n\n MEMBERS.remove(deps.storage, &addr);\n\n }\n", "file_path": "contracts/airdrop/src/contract.rs", "rank": 61, "score": 111778.62308301548 }, { "content": "pub fn execute_ust_withdraw(\n\n deps: DepsMut,\n\n _env: Env,\n\n info: MessageInfo,\n\n recipient: String,\n\n amount: Uint128,\n\n) -> Result<Response, ContractError> {\n\n // authorized owner\n\n let cfg = CONFIG.load(deps.storage)?;\n\n if info.sender != cfg.owner {\n\n return Err(ContractError::Unauthorized {});\n\n }\n\n\n\n // create message to transfer ust\n\n let message = SubMsg::new(BankMsg::Send {\n\n to_address: String::from(deps.api.addr_validate(&recipient)?),\n\n amount: vec![Coin { denom: \"uusd\".to_string(), amount }],\n\n });\n\n\n\n Ok(Response::new()\n\n .add_submessage(message)\n\n .add_attribute(\"action\", \"ust_withdraw\")\n\n .add_attribute(\"sender\", info.sender))\n\n}\n\n\n", "file_path": "contracts/vesting/src/contract.rs", "rank": 62, "score": 111778.62308301548 }, { "content": "pub fn execute_register_members(\n\n deps: DepsMut,\n\n _env: Env,\n\n info: MessageInfo,\n\n members: Vec<RegisterMemberItem>,\n\n) -> Result<Response, ContractError> {\n\n // authorized owner\n\n let cfg = CONFIG.load(deps.storage)?;\n\n if info.sender != cfg.owner {\n\n return Err(ContractError::Unauthorized {});\n\n }\n\n\n\n // save all members with valid address in storage\n\n let mut new_members: u64 = 0;\n\n for m in members.iter() {\n\n let address = deps.api.addr_validate(&m.address)?;\n\n if !MEMBERS.has(deps.storage, &address) {\n\n new_members += 1;\n\n };\n\n MEMBERS.update(deps.storage, &address, |old| -> StdResult<_> {\n", "file_path": "contracts/airdrop/src/contract.rs", "rank": 63, "score": 111778.62308301548 }, { "content": "pub fn query_token_info(deps: Deps) -> StdResult<TokenInfoResponse> {\n\n let info = TOKEN_INFO.load(deps.storage)?;\n\n let res = TokenInfoResponse {\n\n name: info.name,\n\n symbol: info.symbol,\n\n decimals: info.decimals,\n\n total_supply: info.total_supply,\n\n };\n\n Ok(res)\n\n}\n\n\n", "file_path": "contracts/tland-token/src/contract.rs", "rank": 64, "score": 111771.01342283213 }, { "content": "pub fn execute_decrease_allowance(\n\n deps: DepsMut,\n\n _env: Env,\n\n info: MessageInfo,\n\n spender: String,\n\n amount: Uint128,\n\n expires: Option<Expiration>,\n\n) -> Result<Response, ContractError> {\n\n let spender_addr = deps.api.addr_validate(&spender)?;\n\n if spender_addr == info.sender {\n\n return Err(ContractError::CannotSetOwnAccount {});\n\n }\n\n\n\n let key = (&info.sender, &spender_addr);\n\n // load value and delete if it hits 0, or update otherwise\n\n let mut allowance = ALLOWANCES.load(deps.storage, key)?;\n\n if amount < allowance.allowance {\n\n // update the new amount\n\n allowance.allowance = allowance\n\n .allowance\n", "file_path": "contracts/tland-token/src/allowances.rs", "rank": 65, "score": 110136.30765336688 }, { "content": "pub fn execute_increase_allowance(\n\n deps: DepsMut,\n\n _env: Env,\n\n info: MessageInfo,\n\n spender: String,\n\n amount: Uint128,\n\n expires: Option<Expiration>,\n\n) -> Result<Response, ContractError> {\n\n let spender_addr = deps.api.addr_validate(&spender)?;\n\n if spender_addr == info.sender {\n\n return Err(ContractError::CannotSetOwnAccount {});\n\n }\n\n\n\n ALLOWANCES.update(\n\n deps.storage,\n\n (&info.sender, &spender_addr),\n\n |allow| -> StdResult<_> {\n\n let mut val = allow.unwrap_or_default();\n\n if let Some(exp) = expires {\n\n val.expires = exp;\n", "file_path": "contracts/tland-token/src/allowances.rs", "rank": 66, "score": 110136.30765336688 }, { "content": "pub fn execute_update_config(\n\n deps: DepsMut,\n\n _env: Env,\n\n info: MessageInfo,\n\n new_owner: Option<String>,\n\n) -> Result<Response, ContractError> {\n\n // authorized owner\n\n let cfg = CONFIG.load(deps.storage)?;\n\n if info.sender != cfg.owner {\n\n return Err(ContractError::Unauthorized {});\n\n }\n\n\n\n let api = deps.api;\n\n\n\n CONFIG.update(deps.storage, |mut existing_config| -> StdResult<_> {\n\n // update new owner if set\n\n if let Some(addr) = new_owner {\n\n existing_config.owner = api.addr_validate(&addr)?;\n\n }\n\n Ok(existing_config)\n\n })?;\n\n\n\n Ok(Response::new()\n\n .add_attribute(\"action\", \"update_config\")\n\n .add_attribute(\"sender\", info.sender))\n\n}\n\n\n", "file_path": "contracts/tland-token/src/contract.rs", "rank": 67, "score": 110136.30765336688 }, { "content": "pub fn execute_withdraw_locked_funds(\n\n deps: DepsMut,\n\n info: MessageInfo,\n\n denom: String,\n\n amount: Uint128,\n\n recipient: String,\n\n) -> Result<Response, ContractError> {\n\n // authorized owner\n\n let cfg = CONFIG.load(deps.storage)?;\n\n if info.sender != cfg.owner {\n\n return Err(ContractError::Unauthorized {});\n\n }\n\n\n\n Ok(Response::new()\n\n .add_attribute(\"method\", \"withdraw_locked_funds\")\n\n .add_attribute(\"sender\", info.sender.clone())\n\n .add_attribute(\"denom\", denom.clone())\n\n .add_attribute(\"amount\", amount.to_string())\n\n .add_attribute(\"recipient\", recipient.clone())\n\n .add_submessage(SubMsg::new(BankMsg::Send {\n\n to_address: recipient,\n\n amount: vec![deduct_tax(deps, coin(amount.u128(), denom))?],\n\n })))\n\n}\n\n\n", "file_path": "contracts/tland-token/src/contract.rs", "rank": 68, "score": 108577.5459082259 }, { "content": "fn query_member(deps: Deps, env: Env, addr: String) -> StdResult<MemberResponse> {\n\n let addr = deps.api.addr_validate(&addr)?;\n\n let member_info = MEMBERS.may_load(deps.storage, &addr)?;\n\n\n\n if let Some(mut info) = member_info {\n\n let cfg = CONFIG.load(deps.storage)?;\n\n let state = STATE.load(deps.storage)?;\n\n update_member_reward(&state, &cfg, env.block.time.seconds(), &mut info)?;\n\n\n\n return Ok(MemberResponse {\n\n member: Some(MemberResponseItem {\n\n stake: info.stake,\n\n reward: info.pending_reward,\n\n reward_index: info.reward_index,\n\n withdrawn: info.withdrawn,\n\n claims: CLAIMS.query_claims(deps, &addr)?.claims,\n\n }),\n\n });\n\n }\n\n\n\n Ok(MemberResponse { member: None })\n\n}\n\n\n\n// settings for pagination\n\nconst MAX_LIMIT: u32 = 30;\n\nconst DEFAULT_LIMIT: u32 = 10;\n\n\n", "file_path": "contracts/staking/src/contract.rs", "rank": 69, "score": 106059.96824432505 }, { "content": "fn option_addr_validate(deps: &DepsMut, value: &Option<String>) -> StdResult<Option<Addr>> {\n\n let v = match value {\n\n Some(str) => Some(deps.api.addr_validate(&str)?),\n\n None => None,\n\n };\n\n Ok(v)\n\n}\n\n\n", "file_path": "contracts/airdrop/src/contract.rs", "rank": 70, "score": 104923.48733468121 }, { "content": "/// Checks if data starts with XML preamble\n\nfn verify_xml_preamble(data: &[u8]) -> Result<(), ContractError> {\n\n // The easiest way to perform this check would be just match on regex, however regex\n\n // compilation is heavy and probably not worth it.\n\n\n\n let preamble = data\n\n .split_inclusive(|c| *c == b'>')\n\n .next()\n\n .ok_or(ContractError::InvalidXmlPreamble {})?;\n\n\n\n const PREFIX: &[u8] = b\"<?xml \";\n\n const POSTFIX: &[u8] = b\"?>\";\n\n\n\n if !(preamble.starts_with(PREFIX) && preamble.ends_with(POSTFIX)) {\n\n Err(ContractError::InvalidXmlPreamble {})\n\n } else {\n\n Ok(())\n\n }\n\n\n\n // Additionally attributes format could be validated as they are well defined, as well as\n\n // comments presence inside of preable, but it is probably not worth it.\n\n}\n\n\n", "file_path": "contracts/tland-token/src/contract.rs", "rank": 71, "score": 99480.47253619603 }, { "content": "fn compute_released_amount(member: &Member, cfg: &Config, time: u64) -> Uint128 {\n\n // before vesting start released amount is 0\n\n if time < cfg.vesting.start_time {\n\n return Uint128::zero();\n\n }\n\n\n\n // after vesting end released full amount\n\n if time > cfg.vesting.end_time {\n\n return member.amount;\n\n }\n\n\n\n // initial amount is released at the beginning of vesting\n\n let initial_amount = member.amount * Uint128::from(cfg.vesting.initial_percentage) / Uint128::new(100);\n\n\n\n // during the cliff the initial_amount is released\n\n if time < cfg.vesting.cliff_end_time {\n\n return initial_amount;\n\n }\n\n\n\n const DAY: u64 = 24 * 3600;\n\n let total_days = (cfg.vesting.end_time - cfg.vesting.cliff_end_time) / DAY;\n\n let days_passed = (time - cfg.vesting.cliff_end_time) / DAY;\n\n\n\n // after cliff ends smart contract release initial_amount + rest daily\n\n return (member.amount - initial_amount) * Uint128::from(days_passed) / Uint128::from(total_days) + initial_amount;\n\n}\n\n\n", "file_path": "contracts/vesting/src/contract.rs", "rank": 72, "score": 91453.17816829516 }, { "content": "fn compute_available_amount(member: &Member, cfg: &Config, time: u64) -> Uint128 {\n\n // calculate released amount for the member\n\n let released_amount = compute_released_amount(&member, &cfg, time);\n\n // available amount to claim is decreased by already claimed tokens\n\n return released_amount - member.claimed;\n\n}\n\n\n", "file_path": "contracts/vesting/src/contract.rs", "rank": 73, "score": 91453.17816829516 }, { "content": "fn compute_tax(deps: DepsMut, coin: &Coin) -> Result<Uint128, ContractError> {\n\n let amount = coin.amount;\n\n let denom = coin.denom.clone();\n\n\n\n if denom == \"uluna\" {\n\n Ok(Uint128::zero())\n\n } else {\n\n let terra_querier = TerraQuerier::new(&deps.querier);\n\n let tax_rate: Decimal = (terra_querier.query_tax_rate()?).rate;\n\n let tax_cap: Uint128 = (terra_querier.query_tax_cap(denom.to_string())?).cap;\n\n Ok(std::cmp::min(\n\n amount.checked_sub(amount.multiply_ratio(\n\n DECIMAL_FRACTION,\n\n DECIMAL_FRACTION * tax_rate + DECIMAL_FRACTION,\n\n ))?,\n\n tax_cap,\n\n ))\n\n }\n\n}\n\n\n", "file_path": "contracts/tland-token/src/contract.rs", "rank": 74, "score": 89020.8805433178 }, { "content": "fn compute_reward_index(cfg: &Config, state: &State, time: u64) -> StdResult<Decimal> {\n\n // if there is first stake, the reward index is 0\n\n if state.last_updated == 0 {\n\n return Ok(Decimal::zero());\n\n }\n\n\n\n // if we are outside distribution schedule then Error\n\n let (i, j) = find_distribution_schedule_range(\n\n &cfg, state.last_updated, time);\n\n\n\n let mut distributed_amount = Uint128::zero();\n\n\n\n for id in i..=j {\n\n if id < 0 || id >= cfg.distribution_schedule.len() as i32 {\n\n continue;\n\n }\n\n\n\n let schedule = &cfg.distribution_schedule[id as usize];\n\n\n\n // compute distributed amount per second for current schedule\n", "file_path": "contracts/staking/src/contract.rs", "rank": 75, "score": 86731.05898396697 }, { "content": "fn must_pay_fee(info: &MessageInfo, cfg: &Config, operation: String) -> Result<(), ContractError> {\n\n let mut denom = \"\".to_string();\n\n let mut fee_amount = Uint128::zero();\n\n\n\n for fee_config in cfg.fee_config.iter() {\n\n if fee_config.operation == operation {\n\n fee_amount = fee_config.fee;\n\n denom = fee_config.denom.clone();\n\n }\n\n }\n\n\n\n if fee_amount == Uint128::zero() {\n\n return Ok(());\n\n }\n\n\n\n // check if exact fee amount was send\n\n let amount = must_pay(info, denom.as_str())?;\n\n if amount != fee_amount {\n\n return Err(ContractError::InvalidFeeAmount {});\n\n }\n\n\n\n Ok(())\n\n}\n\n\n", "file_path": "contracts/airdrop/src/contract.rs", "rank": 76, "score": 85999.57107475112 }, { "content": "fn must_pay_fee(info: &MessageInfo, cfg: &Config, operation: String) -> Result<(), ContractError> {\n\n let mut denom = \"\".to_string();\n\n let mut fee_amount = Uint128::zero();\n\n\n\n for fee_config in cfg.fee_config.iter() {\n\n if fee_config.operation == operation {\n\n fee_amount = fee_config.fee;\n\n denom = fee_config.denom.clone();\n\n }\n\n }\n\n\n\n if fee_amount == Uint128::zero() {\n\n return Ok(());\n\n }\n\n\n\n // check if exact fee amount was send\n\n let amount = must_pay(info, denom.as_str())?;\n\n if amount != fee_amount {\n\n return Err(ContractError::InvalidFeeAmount {});\n\n }\n\n\n\n Ok(())\n\n}\n\n\n", "file_path": "contracts/staking/src/contract.rs", "rank": 77, "score": 85999.57107475112 }, { "content": "fn must_pay_fee(info: &MessageInfo, cfg: &Config, operation: String) -> Result<(), ContractError> {\n\n let mut denom = \"\".to_string();\n\n let mut fee_amount = Uint128::zero();\n\n\n\n for fee_config in cfg.fee_config.iter() {\n\n if fee_config.operation == operation {\n\n fee_amount = fee_config.fee;\n\n denom = fee_config.denom.clone();\n\n }\n\n }\n\n\n\n if fee_amount == Uint128::zero() {\n\n return Ok(());\n\n }\n\n\n\n // check if exact fee amount was send\n\n let amount = must_pay(info, denom.as_str())?;\n\n if amount != fee_amount {\n\n return Err(ContractError::InvalidFeeAmount {});\n\n }\n\n\n\n Ok(())\n\n}\n\n\n", "file_path": "contracts/vesting/src/contract.rs", "rank": 78, "score": 85999.57107475112 }, { "content": "#[cfg_attr(not(feature = \"library\"), entry_point)]\n\npub fn migrate(deps: DepsMut, _env: Env, _msg: MigrateMsg) -> Result<Response, ContractError> {\n\n let version = get_contract_version(deps.storage)?;\n\n if version.contract != CONTRACT_NAME {\n\n return Err(ContractError::CannotMigrate {\n\n previous_contract: version.contract,\n\n });\n\n }\n\n Ok(Response::default())\n\n}\n\n\n", "file_path": "contracts/airdrop/src/contract.rs", "rank": 79, "score": 79130.22677351168 }, { "content": "#[cfg_attr(not(feature = \"library\"), entry_point)]\n\npub fn migrate(deps: DepsMut, _env: Env, _msg: MigrateMsg) -> Result<Response, ContractError> {\n\n let version = get_contract_version(deps.storage)?;\n\n if version.contract != CONTRACT_NAME {\n\n return Err(ContractError::CannotMigrate {\n\n previous_contract: version.contract,\n\n });\n\n }\n\n Ok(Response::default())\n\n}\n\n\n", "file_path": "contracts/vesting/src/contract.rs", "rank": 80, "score": 79130.22677351168 }, { "content": "#[cfg_attr(not(feature = \"library\"), entry_point)]\n\npub fn migrate(deps: DepsMut, _env: Env, _msg: MigrateMsg) -> Result<Response, ContractError> {\n\n let version = get_contract_version(deps.storage)?;\n\n if version.contract != CONTRACT_NAME {\n\n return Err(ContractError::CannotMigrate {\n\n previous_contract: version.contract,\n\n });\n\n }\n\n Ok(Response::default())\n\n}\n\n\n", "file_path": "contracts/staking/src/contract.rs", "rank": 81, "score": 79130.22677351168 }, { "content": "#[cfg_attr(not(feature = \"library\"), entry_point)]\n\npub fn migrate(deps: DepsMut, _env: Env, _msg: MigrateMsg) -> Result<Response, ContractError> {\n\n let version = get_contract_version(deps.storage)?;\n\n if version.contract != CONTRACT_NAME {\n\n return Err(ContractError::CannotMigrate {\n\n previous_contract: version.contract,\n\n });\n\n }\n\n Ok(Response::default())\n\n}\n\n\n", "file_path": "contracts/tland-token/src/contract.rs", "rank": 82, "score": 78103.12900639228 }, { "content": "fn query_state(deps: Deps) -> StdResult<State> {\n\n Ok(STATE.load(deps.storage)?)\n\n}\n\n\n", "file_path": "contracts/staking/src/contract.rs", "rank": 83, "score": 70913.80370909686 }, { "content": "fn check_missions(querier: &QuerierWrapper, cfg: &Config, addr: &Addr) -> StdResult<Missions> {\n\n let mut missions = Missions {\n\n is_in_lp_staking: false,\n\n is_registered_on_platform: false,\n\n is_property_shareholder: false,\n\n };\n\n\n\n if let Some(contract_addr) = cfg.mission_smart_contracts.lp_staking.clone() {\n\n let query = WasmQuery::Smart {\n\n contract_addr: contract_addr.to_string(),\n\n msg: to_binary(&StakingQueryMsg::Member {\n\n address: addr.to_string(),\n\n })?,\n\n }.into();\n\n let res: StakingMemberResponse = querier.query(&query)?;\n\n if res.member.is_some() {\n\n missions.is_in_lp_staking = true;\n\n }\n\n }\n\n\n", "file_path": "contracts/airdrop/src/contract.rs", "rank": 84, "score": 59607.72654313354 }, { "content": "fn mission_smart_contracts_from(deps: &DepsMut, m: Option<InstantiateMissionSmartContracts>) -> StdResult<MissionSmartContracts> {\n\n let res = match m {\n\n Some(m) => MissionSmartContracts {\n\n lp_staking: option_addr_validate(&deps, &m.lp_staking)?,\n\n tland_staking: option_addr_validate(&deps, &m.tland_staking)?,\n\n platform_registry: option_addr_validate(&deps, &m.platform_registry)?,\n\n },\n\n None => MissionSmartContracts {\n\n lp_staking: None,\n\n tland_staking: None,\n\n platform_registry: None,\n\n },\n\n };\n\n Ok(res)\n\n}\n\n\n", "file_path": "contracts/airdrop/src/contract.rs", "rank": 85, "score": 59252.64374602174 }, { "content": "fn main() {\n\n let mut out_dir = current_dir().unwrap();\n\n out_dir.push(\"schema\");\n\n create_dir_all(&out_dir).unwrap();\n\n remove_schemas(&out_dir).unwrap();\n\n\n\n export_schema(&schema_for!(InstantiateMsg), &out_dir);\n\n export_schema(&schema_for!(ExecuteMsg), &out_dir);\n\n export_schema(&schema_for!(QueryMsg), &out_dir);\n\n export_schema(&schema_for!(MigrateMsg), &out_dir);\n\n\n\n export_schema(&schema_for!(ConfigResponse), &out_dir);\n\n export_schema(&schema_for!(StateResponse), &out_dir);\n\n export_schema(&schema_for!(MemberResponse), &out_dir);\n\n export_schema(&schema_for!(MemberListResponse), &out_dir);\n\n}\n", "file_path": "contracts/vesting/examples/schema.rs", "rank": 86, "score": 58367.42866951428 }, { "content": "fn main() {\n\n let mut out_dir = current_dir().unwrap();\n\n out_dir.push(\"schema\");\n\n create_dir_all(&out_dir).unwrap();\n\n remove_schemas(&out_dir).unwrap();\n\n\n\n export_schema(&schema_for!(InstantiateMsg), &out_dir);\n\n export_schema(&schema_for!(ExecuteMsg), &out_dir);\n\n export_schema(&schema_for!(QueryMsg), &out_dir);\n\n export_schema(&schema_for!(MigrateMsg), &out_dir);\n\n\n\n export_schema(&schema_for!(ConfigResponse), &out_dir);\n\n export_schema(&schema_for!(StateResponse), &out_dir);\n\n export_schema(&schema_for!(MemberResponse), &out_dir);\n\n export_schema(&schema_for!(MemberListResponse), &out_dir);\n\n}\n", "file_path": "contracts/airdrop/examples/schema.rs", "rank": 87, "score": 58367.42866951428 }, { "content": "fn main() {\n\n let mut out_dir = current_dir().unwrap();\n\n out_dir.push(\"schema\");\n\n create_dir_all(&out_dir).unwrap();\n\n remove_schemas(&out_dir).unwrap();\n\n\n\n export_schema(&schema_for!(InstantiateMsg), &out_dir);\n\n export_schema(&schema_for!(ExecuteMsg), &out_dir);\n\n export_schema(&schema_for!(QueryMsg), &out_dir);\n\n export_schema(&schema_for!(ReceiveMsg), &out_dir);\n\n export_schema(&schema_for!(MigrateMsg), &out_dir);\n\n\n\n export_schema(&schema_for!(ConfigResponse), &out_dir);\n\n export_schema(&schema_for!(StateResponse), &out_dir);\n\n export_schema(&schema_for!(MemberListResponse), &out_dir);\n\n export_schema(&schema_for!(MemberResponse), &out_dir);\n\n}\n", "file_path": "contracts/staking/examples/schema.rs", "rank": 88, "score": 58367.42866951428 }, { "content": "fn main() {\n\n let mut out_dir = current_dir().unwrap();\n\n out_dir.push(\"schema\");\n\n create_dir_all(&out_dir).unwrap();\n\n remove_schemas(&out_dir).unwrap();\n\n\n\n export_schema(&schema_for!(InstantiateMsg), &out_dir);\n\n export_schema(&schema_for!(ExecuteMsg), &out_dir);\n\n export_schema(&schema_for!(QueryMsg), &out_dir);\n\n export_schema(&schema_for!(MigrateMsg), &out_dir);\n\n\n\n export_schema(&schema_for!(AllowanceResponse), &out_dir);\n\n export_schema(&schema_for!(BalanceResponse), &out_dir);\n\n export_schema(&schema_for!(TokenInfoResponse), &out_dir);\n\n export_schema(&schema_for!(AllAllowancesResponse), &out_dir);\n\n export_schema(&schema_for!(AllAccountsResponse), &out_dir);\n\n export_schema(&schema_for!(ConfigResponse), &out_dir);\n\n}\n", "file_path": "contracts/tland-token/examples/schema.rs", "rank": 89, "score": 57409.32015582263 }, { "content": "fn main() {\n\n let mut out_dir = current_dir().unwrap();\n\n out_dir.push(\"schema\");\n\n create_dir_all(&out_dir).unwrap();\n\n remove_schemas(&out_dir).unwrap();\n\n\n\n export_schema(&schema_for!(PlatformRegistryQueryMsg), &out_dir);\n\n export_schema(&schema_for!(AddressBaseInfoResponse), &out_dir);\n\n}\n", "file_path": "contracts/platform-registry/examples/schema.rs", "rank": 90, "score": 57409.32015582263 }, { "content": "fn query_member_list(\n\n deps: Deps,\n\n start_after: Option<String>,\n\n limit: Option<u32>,\n\n) -> StdResult<MemberListResponse> {\n\n let limit = limit.unwrap_or(DEFAULT_LIMIT).min(MAX_LIMIT) as usize;\n\n let addr = maybe_addr(deps.api, start_after)?;\n\n let start = addr.map(|addr| Bound::exclusive(addr.as_ref()));\n\n\n\n let members: StdResult<Vec<_>> = MEMBERS\n\n .range(deps.storage, start, None, Order::Ascending)\n\n .take(limit)\n\n .map(|item| {\n\n let (key, m) = item?;\n\n\n\n let addr = deps.api.addr_validate(&String::from_utf8(key)?)?;\n\n\n\n Ok(MemberListResponseItem {\n\n address: addr.to_string(),\n\n amount: m.amount,\n\n claimed: m.claimed\n\n })\n\n })\n\n .collect();\n\n\n\n Ok(MemberListResponse { members: members? })\n\n}\n\n\n\n\n", "file_path": "contracts/airdrop/src/contract.rs", "rank": 91, "score": 56503.98309445375 }, { "content": "fn query_member_list(\n\n deps: Deps,\n\n start_after: Option<String>,\n\n limit: Option<u32>,\n\n time: u64,\n\n) -> StdResult<MemberListResponse> {\n\n let limit = limit.unwrap_or(DEFAULT_LIMIT).min(MAX_LIMIT) as usize;\n\n let addr = maybe_addr(deps.api, start_after)?;\n\n let start = addr.map(|addr| Bound::exclusive(addr.as_ref()));\n\n let cfg = CONFIG.load(deps.storage)?;\n\n\n\n let members: StdResult<Vec<_>> = MEMBERS\n\n .range(deps.storage, start, None, Order::Ascending)\n\n .take(limit)\n\n .map(|item| {\n\n let (key, m) = item?;\n\n\n\n let addr = deps.api.addr_validate(&String::from_utf8(key)?)?;\n\n\n\n Ok(MemberListResponseItem {\n", "file_path": "contracts/vesting/src/contract.rs", "rank": 92, "score": 56503.98309445375 }, { "content": "fn query_member_list(\n\n deps: Deps,\n\n env: Env,\n\n start_after: Option<String>,\n\n limit: Option<u32>,\n\n) -> StdResult<MemberListResponse> {\n\n let limit = limit.unwrap_or(DEFAULT_LIMIT).min(MAX_LIMIT) as usize;\n\n let addr = maybe_addr(deps.api, start_after)?;\n\n let start = addr.map(|addr| Bound::exclusive(addr.as_ref()));\n\n\n\n let members: StdResult<Vec<_>> = MEMBERS\n\n .range(deps.storage, start, None, Order::Ascending)\n\n .take(limit)\n\n .map(|item| {\n\n let (key, mut info) = item?;\n\n let address = deps.api.addr_validate(&String::from_utf8(key)?)?;\n\n let cfg = CONFIG.load(deps.storage)?;\n\n let state = STATE.load(deps.storage)?;\n\n\n\n update_member_reward(&state, &cfg, env.block.time.seconds(), &mut info)?;\n", "file_path": "contracts/staking/src/contract.rs", "rank": 93, "score": 56503.98309445375 }, { "content": "fn update_member_reward(state: &State, cfg: &Config, time: u64, member_info: &mut MemberInfo) -> StdResult<()> {\n\n let global_reward_index = compute_reward_index(&cfg, &state, time)?;\n\n\n\n let reward = compute_member_reward(&member_info, global_reward_index);\n\n\n\n member_info.reward_index = global_reward_index;\n\n member_info.pending_reward = reward;\n\n\n\n Ok(())\n\n}\n\n\n", "file_path": "contracts/staking/src/contract.rs", "rank": 94, "score": 54538.39056065265 }, { "content": "fn calc_missions_passed(missions: &Missions) -> u32 {\n\n // one mission is always passed\n\n let mut passed = 1;\n\n\n\n if missions.is_in_lp_staking {\n\n passed += 1;\n\n }\n\n if missions.is_registered_on_platform {\n\n passed += 1;\n\n }\n\n if missions.is_property_shareholder {\n\n passed += 1;\n\n }\n\n\n\n return passed;\n\n}\n", "file_path": "contracts/airdrop/src/contract.rs", "rank": 95, "score": 49383.78253208147 }, { "content": "fn deduct_tax(deps: DepsMut, coin: Coin) -> Result<Coin, ContractError> {\n\n Ok(Coin {\n\n denom: coin.denom.clone(),\n\n amount: coin.amount.checked_sub(compute_tax(deps, &coin)?)?,\n\n })\n\n}\n\n\n\n#[cfg(test)]\n\nmod tests {\n\n use cosmwasm_std::{Addr, coins, CosmosMsg, from_binary, StdError, SubMsg, WasmMsg};\n\n use cosmwasm_std::testing::{mock_dependencies, mock_env, mock_info};\n\n\n\n use crate::msg::InstantiateMarketingInfo;\n\n\n\n use super::*;\n\n\n\n fn get_balance<T: Into<String>>(deps: Deps, address: T) -> Uint128 {\n\n query_balance(deps, address.into()).unwrap().balance\n\n }\n\n\n", "file_path": "contracts/tland-token/src/contract.rs", "rank": 96, "score": 41447.51702287259 }, { "content": "fn find_distribution_schedule_range(cfg: &Config, start_time: u64, end_time: u64) -> (i32, i32) {\n\n let mut start = -1;\n\n let mut end = -1;\n\n\n\n for (i, schedule) in cfg.distribution_schedule.iter().enumerate() {\n\n if start_time >= schedule.start_time && start_time < schedule.end_time {\n\n start = i as i32\n\n } else if start_time >= schedule.end_time {\n\n start = (i + 1) as i32\n\n }\n\n\n\n if end_time >= schedule.start_time && end_time < schedule.end_time {\n\n end = i as i32\n\n } else if start_time >= schedule.end_time {\n\n end = (i + 1) as i32\n\n }\n\n }\n\n\n\n (start, end)\n\n}\n\n\n", "file_path": "contracts/staking/src/contract.rs", "rank": 97, "score": 39600.81599952014 }, { "content": "use schemars::JsonSchema;\n\nuse serde::{Deserialize, Serialize};\n\n\n\nuse cosmwasm_std::{Addr, Uint128};\n\nuse cw_storage_plus::{Item, Map};\n\n\n\nuse cw20::{AllowanceResponse, Logo, MarketingInfoResponse};\n\n\n\n#[derive(Serialize, Deserialize, Clone, PartialEq, JsonSchema, Debug)]\n\n#[serde(rename_all = \"snake_case\")]\n\npub struct TokenInfo {\n\n pub name: String,\n\n pub symbol: String,\n\n pub decimals: u8,\n\n pub total_supply: Uint128,\n\n}\n\n\n\n#[derive(Serialize, Deserialize, Clone, Debug, PartialEq, JsonSchema)]\n\npub struct Config {\n\n pub owner: Addr,\n\n}\n\n\n\npub const TOKEN_INFO: Item<TokenInfo> = Item::new(\"token_info\");\n\npub const MARKETING_INFO: Item<MarketingInfoResponse> = Item::new(\"marketing_info\");\n\npub const LOGO: Item<Logo> = Item::new(\"logo\");\n\npub const BALANCES: Map<&Addr, Uint128> = Map::new(\"balance\");\n\npub const ALLOWANCES: Map<(&Addr, &Addr), AllowanceResponse> = Map::new(\"allowance\");\n\npub const CONFIG: Item<Config> = Item::new(\"config\");\n", "file_path": "contracts/tland-token/src/state.rs", "rank": 99, "score": 40.50456157486774 } ]
Rust
07-rust/stm32l0x1/stm32l0x1_pac/src/syscfg_comp/comp1_ctrl.rs
aaronhktan/stm32-exploration
dcd7674424cd17b02b85c6b3ce533456d5037d65
#[doc = "Reader of register COMP1_CTRL"] pub type R = crate::R<u32, super::COMP1_CTRL>; #[doc = "Writer for register COMP1_CTRL"] pub type W = crate::W<u32, super::COMP1_CTRL>; #[doc = "Register COMP1_CTRL `reset()`'s with value 0"] impl crate::ResetValue for super::COMP1_CTRL { type Type = u32; #[inline(always)] fn reset_value() -> Self::Type { 0 } } #[doc = "Reader of field `COMP1EN`"] pub type COMP1EN_R = crate::R<bool, bool>; #[doc = "Write proxy for field `COMP1EN`"] pub struct COMP1EN_W<'a> { w: &'a mut W, } impl<'a> COMP1EN_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 } } #[doc = "Reader of field `COMP1INNSEL`"] pub type COMP1INNSEL_R = crate::R<u8, u8>; #[doc = "Write proxy for field `COMP1INNSEL`"] pub struct COMP1INNSEL_W<'a> { w: &'a mut W, } impl<'a> COMP1INNSEL_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 & !(0x03 << 4)) | (((value as u32) & 0x03) << 4); self.w } } #[doc = "Reader of field `COMP1WM`"] pub type COMP1WM_R = crate::R<bool, bool>; #[doc = "Write proxy for field `COMP1WM`"] pub struct COMP1WM_W<'a> { w: &'a mut W, } impl<'a> COMP1WM_W<'a> { #[doc = r"Sets the field bit"] #[inline(always)] pub fn set_bit(self) -> &'a mut W { self.bit(true) } #[doc = r"Clears the field bit"] #[inline(always)] pub fn clear_bit(self) -> &'a mut W { self.bit(false) } #[doc = r"Writes raw bits to the field"] #[inline(always)] pub fn bit(self, value: bool) -> &'a mut W { self.w.bits = (self.w.bits & !(0x01 << 8)) | (((value as u32) & 0x01) << 8); self.w } } #[doc = "Reader of field `COMP1LPTIMIN1`"] pub type COMP1LPTIMIN1_R = crate::R<bool, bool>; #[doc = "Write proxy for field `COMP1LPTIMIN1`"] pub struct COMP1LPTIMIN1_W<'a> { w: &'a mut W, } impl<'a> COMP1LPTIMIN1_W<'a> { #[doc = r"Sets the field bit"] #[inline(always)] pub fn set_bit(self) -> &'a mut W { self.bit(true) } #[doc = r"Clears the field bit"] #[inline(always)] pub fn clear_bit(self) -> &'a mut W { self.bit(false) } #[doc = r"Writes raw bits to the field"] #[inline(always)] pub fn bit(self, value: bool) -> &'a mut W { self.w.bits = (self.w.bits & !(0x01 << 12)) | (((value as u32) & 0x01) << 12); self.w } } #[doc = "Reader of field `COMP1POLARITY`"] pub type COMP1POLARITY_R = crate::R<bool, bool>; #[doc = "Write proxy for field `COMP1POLARITY`"] pub struct COMP1POLARITY_W<'a> { w: &'a mut W, } impl<'a> COMP1POLARITY_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 << 15)) | (((value as u32) & 0x01) << 15); self.w } } #[doc = "Reader of field `COMP1VALUE`"] pub type COMP1VALUE_R = crate::R<bool, bool>; #[doc = "Write proxy for field `COMP1VALUE`"] pub struct COMP1VALUE_W<'a> { w: &'a mut W, } impl<'a> COMP1VALUE_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 `COMP1LOCK`"] pub type COMP1LOCK_R = crate::R<bool, bool>; #[doc = "Write proxy for field `COMP1LOCK`"] pub struct COMP1LOCK_W<'a> { w: &'a mut W, } impl<'a> COMP1LOCK_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 = "Bit 0 - Comparator 1 enable bit"] #[inline(always)] pub fn comp1en(&self) -> COMP1EN_R { COMP1EN_R::new((self.bits & 0x01) != 0) } #[doc = "Bits 4:5 - Comparator 1 Input Minus connection configuration bit"] #[inline(always)] pub fn comp1innsel(&self) -> COMP1INNSEL_R { COMP1INNSEL_R::new(((self.bits >> 4) & 0x03) as u8) } #[doc = "Bit 8 - Comparator 1 window mode selection bit"] #[inline(always)] pub fn comp1wm(&self) -> COMP1WM_R { COMP1WM_R::new(((self.bits >> 8) & 0x01) != 0) } #[doc = "Bit 12 - Comparator 1 LPTIM input propagation bit"] #[inline(always)] pub fn comp1lptimin1(&self) -> COMP1LPTIMIN1_R { COMP1LPTIMIN1_R::new(((self.bits >> 12) & 0x01) != 0) } #[doc = "Bit 15 - Comparator 1 polarity selection bit"] #[inline(always)] pub fn comp1polarity(&self) -> COMP1POLARITY_R { COMP1POLARITY_R::new(((self.bits >> 15) & 0x01) != 0) } #[doc = "Bit 30 - Comparator 1 output status bit"] #[inline(always)] pub fn comp1value(&self) -> COMP1VALUE_R { COMP1VALUE_R::new(((self.bits >> 30) & 0x01) != 0) } #[doc = "Bit 31 - COMP1_CSR register lock bit"] #[inline(always)] pub fn comp1lock(&self) -> COMP1LOCK_R { COMP1LOCK_R::new(((self.bits >> 31) & 0x01) != 0) } } impl W { #[doc = "Bit 0 - Comparator 1 enable bit"] #[inline(always)] pub fn comp1en(&mut self) -> COMP1EN_W { COMP1EN_W { w: self } } #[doc = "Bits 4:5 - Comparator 1 Input Minus connection configuration bit"] #[inline(always)] pub fn comp1innsel(&mut self) -> COMP1INNSEL_W { COMP1INNSEL_W { w: self } } #[doc = "Bit 8 - Comparator 1 window mode selection bit"] #[inline(always)] pub fn comp1wm(&mut self) -> COMP1WM_W { COMP1WM_W { w: self } } #[doc = "Bit 12 - Comparator 1 LPTIM input propagation bit"] #[inline(always)] pub fn comp1lptimin1(&mut self) -> COMP1LPTIMIN1_W { COMP1LPTIMIN1_W { w: self } } #[doc = "Bit 15 - Comparator 1 polarity selection bit"] #[inline(always)] pub fn comp1polarity(&mut self) -> COMP1POLARITY_W { COMP1POLARITY_W { w: self } } #[doc = "Bit 30 - Comparator 1 output status bit"] #[inline(always)] pub fn comp1value(&mut self) -> COMP1VALUE_W { COMP1VALUE_W { w: self } } #[doc = "Bit 31 - COMP1_CSR register lock bit"] #[inline(always)] pub fn comp1lock(&mut self) -> COMP1LOCK_W { COMP1LOCK_W { w: self } } }
#[doc = "Reader of register COMP1_CTRL"] pub type R = crate::R<u32, super::COMP1_CTRL>; #[doc = "Writer for register COMP1_CTRL"] pub type W = crate::W<u32, super::COMP1_CTRL>; #[doc = "Register COMP1_CTRL `reset()`'s with value 0"] impl crate::ResetValue for super::COMP1_CTRL { type Type = u32; #[inline(always)] fn reset_value() -> Self::Type { 0 } } #[doc = "Reader of field `COMP1EN`"] pub type COMP1EN_R = crate::R<bool, bool>; #[doc = "Write proxy for field `COMP1EN`"] pub struct COMP1EN_W<'a> { w: &'a mut W, } impl<'a> COMP1EN_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 } } #[doc = "Reader of field `COMP1INNSEL`"] pub type COMP1INNSEL_R = crate::R<u8, u8>; #[doc = "Write proxy for field `COMP1INNSEL`"] pub struct COMP1INNSEL_W<'a> { w: &'a mut W, } impl<'a> COMP1INNSEL_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 & !(0x03 << 4)) | (((value as u32) & 0x03) << 4); self.w } } #[doc = "Reader of field `COMP1WM`"] pub type COMP1WM_R = crate::R<bool, bool>; #[doc = "Write proxy for field `COMP1WM`"] pub struct COMP1WM_W<'a> { w: &'a mut W, } impl<'a> COMP1WM_W<'a> { #[doc = r"Sets the field bit"] #[inline(always)] pub fn set_bit(self) -> &'a mut W { self.bit(true) } #[doc = r"Clears the field bit"] #[inline(always)] pub fn clear_bit(self) -> &'a mut W { self.bit(false) } #[doc = r"Writes raw bits to the field"] #[inline(always)] pub fn bit(self, value: bool) -> &'a mut W { self.w.bits = (self.w.bits & !(0x01 << 8)) | (((value as u32) & 0x01) << 8); self.w } } #[doc = "Reader of field `COMP1LPTIMIN1`"] pub type COMP1LPTIMIN1_R = crate::R<bool, bool>; #[doc = "Write proxy for field `COMP1LPTIMIN1`"] pub struct COMP1LPTIMIN1_W<'a> { w: &'a mut W, } impl<'a> COMP1LPTIMIN1_W<'a> { #[doc = r"Sets the field bit"] #[inline(always)] pub fn set_bit(self) -> &'a mut W { self.bit(true) } #[doc = r"Clears the field bit"] #[inline(always)] pub fn clear_bit(self) -> &'a mut W { self.bit(false) } #[doc = r"Writes raw bits to the field"] #[inline(always)] pub fn bit(self, value: bool) -> &'a mut W { self.w.bits = (self.w.bits & !(0x01 << 12)) | (((value as u32) & 0x01) << 12); self.w } } #[doc = "Reader of field `COMP1POLARITY`"] pub type COMP1POLARITY_R = crate::R<bool, bool>; #[doc = "Write proxy for field `COMP1POLARITY`"] pub struct COMP1POLARITY_W<'a> { w: &'a mut W, } impl<'a> COMP1POLARITY_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 << 15)) | (((value as u32) & 0x01) << 15); self.w } } #[doc = "Reader of field `COMP1VALUE`"] pub type COMP1VALUE_R = crate::R<bool, bool>; #[doc
TY_R { COMP1POLARITY_R::new(((self.bits >> 15) & 0x01) != 0) } #[doc = "Bit 30 - Comparator 1 output status bit"] #[inline(always)] pub fn comp1value(&self) -> COMP1VALUE_R { COMP1VALUE_R::new(((self.bits >> 30) & 0x01) != 0) } #[doc = "Bit 31 - COMP1_CSR register lock bit"] #[inline(always)] pub fn comp1lock(&self) -> COMP1LOCK_R { COMP1LOCK_R::new(((self.bits >> 31) & 0x01) != 0) } } impl W { #[doc = "Bit 0 - Comparator 1 enable bit"] #[inline(always)] pub fn comp1en(&mut self) -> COMP1EN_W { COMP1EN_W { w: self } } #[doc = "Bits 4:5 - Comparator 1 Input Minus connection configuration bit"] #[inline(always)] pub fn comp1innsel(&mut self) -> COMP1INNSEL_W { COMP1INNSEL_W { w: self } } #[doc = "Bit 8 - Comparator 1 window mode selection bit"] #[inline(always)] pub fn comp1wm(&mut self) -> COMP1WM_W { COMP1WM_W { w: self } } #[doc = "Bit 12 - Comparator 1 LPTIM input propagation bit"] #[inline(always)] pub fn comp1lptimin1(&mut self) -> COMP1LPTIMIN1_W { COMP1LPTIMIN1_W { w: self } } #[doc = "Bit 15 - Comparator 1 polarity selection bit"] #[inline(always)] pub fn comp1polarity(&mut self) -> COMP1POLARITY_W { COMP1POLARITY_W { w: self } } #[doc = "Bit 30 - Comparator 1 output status bit"] #[inline(always)] pub fn comp1value(&mut self) -> COMP1VALUE_W { COMP1VALUE_W { w: self } } #[doc = "Bit 31 - COMP1_CSR register lock bit"] #[inline(always)] pub fn comp1lock(&mut self) -> COMP1LOCK_W { COMP1LOCK_W { w: self } } }
= "Write proxy for field `COMP1VALUE`"] pub struct COMP1VALUE_W<'a> { w: &'a mut W, } impl<'a> COMP1VALUE_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 `COMP1LOCK`"] pub type COMP1LOCK_R = crate::R<bool, bool>; #[doc = "Write proxy for field `COMP1LOCK`"] pub struct COMP1LOCK_W<'a> { w: &'a mut W, } impl<'a> COMP1LOCK_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 = "Bit 0 - Comparator 1 enable bit"] #[inline(always)] pub fn comp1en(&self) -> COMP1EN_R { COMP1EN_R::new((self.bits & 0x01) != 0) } #[doc = "Bits 4:5 - Comparator 1 Input Minus connection configuration bit"] #[inline(always)] pub fn comp1innsel(&self) -> COMP1INNSEL_R { COMP1INNSEL_R::new(((self.bits >> 4) & 0x03) as u8) } #[doc = "Bit 8 - Comparator 1 window mode selection bit"] #[inline(always)] pub fn comp1wm(&self) -> COMP1WM_R { COMP1WM_R::new(((self.bits >> 8) & 0x01) != 0) } #[doc = "Bit 12 - Comparator 1 LPTIM input propagation bit"] #[inline(always)] pub fn comp1lptimin1(&self) -> COMP1LPTIMIN1_R { COMP1LPTIMIN1_R::new(((self.bits >> 12) & 0x01) != 0) } #[doc = "Bit 15 - Comparator 1 polarity selection bit"] #[inline(always)] pub fn comp1polarity(&self) -> COMP1POLARI
random
[ { "content": "#[doc = \"Reset value of the register\"]\n\n#[doc = \"\"]\n\n#[doc = \"This value is initial value for `write` method.\"]\n\n#[doc = \"It can be also directly writed to register by `reset` method.\"]\n\npub trait ResetValue {\n\n #[doc = \"Register size\"]\n\n type Type;\n\n #[doc = \"Reset value of the register\"]\n\n fn reset_value() -> Self::Type;\n\n}\n\n#[doc = \"This structure provides volatile access to register\"]\n\npub struct Reg<U, REG> {\n\n register: vcell::VolatileCell<U>,\n\n _marker: marker::PhantomData<REG>,\n\n}\n\nunsafe impl<U: Send, REG> Send for Reg<U, REG> {}\n\nimpl<U, REG> Reg<U, REG>\n\nwhere\n\n Self: Readable,\n\n U: Copy,\n\n{\n\n #[doc = \"Reads the contents of `Readable` register\"]\n\n #[doc = \"\"]\n\n #[doc = \"You can read the contents of a register in such way:\"]\n", "file_path": "07-rust/stm32f446/stm32f446_pac/src/generic.rs", "rank": 0, "score": 192988.70578231278 }, { "content": "#[doc = \"Reset value of the register\"]\n\n#[doc = \"\"]\n\n#[doc = \"This value is initial value for `write` method.\"]\n\n#[doc = \"It can be also directly writed to register by `reset` method.\"]\n\npub trait ResetValue {\n\n #[doc = \"Register size\"]\n\n type Type;\n\n #[doc = \"Reset value of the register\"]\n\n fn reset_value() -> Self::Type;\n\n}\n\n#[doc = \"This structure provides volatile access to register\"]\n\npub struct Reg<U, REG> {\n\n register: vcell::VolatileCell<U>,\n\n _marker: marker::PhantomData<REG>,\n\n}\n\nunsafe impl<U: Send, REG> Send for Reg<U, REG> {}\n\nimpl<U, REG> Reg<U, REG>\n\nwhere\n\n Self: Readable,\n\n U: Copy,\n\n{\n\n #[doc = \"Reads the contents of `Readable` register\"]\n\n #[doc = \"\"]\n\n #[doc = \"You can read the contents of a register in such way:\"]\n", "file_path": "07-rust/stm32l0x1/stm32l0x1_pac/src/generic.rs", "rank": 1, "score": 192988.70578231278 }, { "content": "#[doc = \"Reset value of the register\"]\n\n#[doc = \"\"]\n\n#[doc = \"This value is initial value for `write` method.\"]\n\n#[doc = \"It can be also directly writed to register by `reset` method.\"]\n\npub trait ResetValue {\n\n #[doc = \"Register size\"]\n\n type Type;\n\n #[doc = \"Reset value of the register\"]\n\n fn reset_value() -> Self::Type;\n\n}\n\n#[doc = \"This structure provides volatile access to register\"]\n\npub struct Reg<U, REG> {\n\n register: vcell::VolatileCell<U>,\n\n _marker: marker::PhantomData<REG>,\n\n}\n\nunsafe impl<U: Send, REG> Send for Reg<U, REG> {}\n\nimpl<U, REG> Reg<U, REG>\n\nwhere\n\n Self: Readable,\n\n U: Copy,\n\n{\n\n #[doc = \"Reads the contents of `Readable` register\"]\n\n #[doc = \"\"]\n\n #[doc = \"You can read the contents of a register in such way:\"]\n", "file_path": "07-rust/stm32f0x1/stm32f0x1_pac/src/generic.rs", "rank": 2, "score": 192988.70578231275 }, { "content": "#[entry]\n\nfn main() -> ! { // ! means no return type\n\n // Check out the 'Cortex-M Peripherals' singleton\n\n let cm_p = cortex_m::Peripherals::take().unwrap();\n\n // Set up the SysTick peripheral\n\n // Rust variables are immutable by default; use mut to make mutable\n\n let mut syst = cm_p.SYST;\n\n syst.set_clock_source(SystClkSource::Core);\n\n // ~2s period; STM32F0 by default uses the 8MHz HSI on boot\n\n // (See section 6.2 of the reference manual)\n\n syst.set_reload(16_000_000);\n\n syst.enable_counter();\n\n\n\n // Set up GPIO pin B3 as push-pull output\n\n let p = stm32f0x1::Peripherals::take().unwrap();\n\n let rcc = p.RCC;\n\n // rcc.iopenr is the GPIO clock enable register\n\n // |x| is closure notation in Rust\n\n rcc.ahbenr.write(|w| w.iopben().set_bit());\n\n\n\n // Set moder on third pin of GPIOB to 0b01, output\n", "file_path": "07-rust/stm32f0x1/rust-blink-f031k6/src/main.rs", "rank": 3, "score": 134178.0685062561 }, { "content": "#[entry]\n\nfn main() -> ! { // ! means no return type\n\n // Check out the 'Cortex-M Peripherals' singleton\n\n let cm_p = cortex_m::Peripherals::take().unwrap();\n\n // Set up the SysTick peripheral\n\n // Rust variables are immutable by default; use mut to make mutable\n\n let mut syst = cm_p.SYST;\n\n syst.set_clock_source(SystClkSource::Core);\n\n // ~1s period; STM32F4 by default uses the 16MHz HSI on boot\n\n // (See section 6.2.2 in the reference manual)\n\n syst.set_reload(16_000_000);\n\n syst.enable_counter();\n\n\n\n // Set up GPIO pin A5 as push-pull output\n\n let p = stm32f446::Peripherals::take().unwrap();\n\n let rcc = p.RCC;\n\n // rcc.iopenr is the GPIO clock enable register\n\n // |x| is closure notation in Rust\n\n rcc.ahb1enr.write(|w| w.gpioaen().set_bit());\n\n\n\n // Set moder on fifth pin of GPIOB to 0b01, output\n", "file_path": "07-rust/stm32f446/rust-blink-f446re/src/main.rs", "rank": 4, "score": 134178.0685062561 }, { "content": "#[entry]\n\nfn main() -> ! { // ! means no return type\n\n // Check out the 'Cortex-M Peripherals' singleton\n\n let cm_p = cortex_m::Peripherals::take().unwrap();\n\n // Set up the SysTick peripheral\n\n // Rust variables are immutable by default; use mut to make mutable\n\n let mut syst = cm_p.SYST;\n\n syst.set_clock_source(SystClkSource::Core);\n\n // ~2s period; STM32L0 boots to a ~2.1MHz internal oscillator\n\n // (See Section 7.2 of the STM32L0x1 reference manual)\n\n syst.set_reload(4_200_000);\n\n syst.enable_counter();\n\n\n\n // Set up GPIO pin B3 as push-pull output\n\n let p = stm32l0x1::Peripherals::take().unwrap();\n\n let rcc = p.RCC;\n\n // rcc.iopenr is the GPIO clock enable register\n\n // |x| is closure notation in Rust\n\n rcc.iopenr.write(|w| w.iopben().set_bit());\n\n\n\n // Set moder on third pin of GPIOB to 0b01, output\n", "file_path": "07-rust/stm32l0x1/rust-blink-l031k6/src/main.rs", "rank": 5, "score": 134178.0685062561 }, { "content": "TickType_t uxTaskResetEventItemValue( void )\n\n{\n\nTickType_t uxReturn;\n\n\n\n\tuxReturn = listGET_LIST_ITEM_VALUE( &( pxCurrentTCB->xEventListItem ) );\n\n\n\n\t/* Reset the event list item to its normal value - so it can be used with\n\n\tqueues and semaphores. */\n\n\tlistSET_LIST_ITEM_VALUE( &( pxCurrentTCB->xEventListItem ), ( ( TickType_t ) configMAX_PRIORITIES - ( TickType_t ) pxCurrentTCB->uxPriority ) ); /*lint !e961 MISRA exception as the casts are only redundant for some ports. */\n\n\n\n\treturn uxReturn;\n", "file_path": "06-freertos/freertos/Source/tasks.c", "rank": 6, "score": 104903.10307163426 }, { "content": "#define portMAX_8_BIT_VALUE\t\t\t\t\t( ( uint8_t ) 0xff )\n", "file_path": "06-freertos/freertos/Source/portable/GCC/ARM_CM4F/port.c", "rank": 7, "score": 100509.13876308527 }, { "content": "fn main() {\n\n if env::var_os(\"CARGO_FEATURE_RT\").is_some() {\n\n let out = &PathBuf::from(env::var_os(\"OUT_DIR\").unwrap());\n\n File::create(out.join(\"device.x\"))\n\n .unwrap()\n\n .write_all(include_bytes!(\"device.x\"))\n\n .unwrap();\n\n println!(\"cargo:rustc-link-search={}\", out.display());\n\n println!(\"cargo:rerun-if-changed=device.x\");\n\n }\n\n println!(\"cargo:rerun-if-changed=build.rs\");\n\n}\n", "file_path": "07-rust/stm32f446/stm32f446_pac/build.rs", "rank": 8, "score": 88441.66588380146 }, { "content": "fn main() {\n\n if env::var_os(\"CARGO_FEATURE_RT\").is_some() {\n\n let out = &PathBuf::from(env::var_os(\"OUT_DIR\").unwrap());\n\n File::create(out.join(\"device.x\"))\n\n .unwrap()\n\n .write_all(include_bytes!(\"device.x\"))\n\n .unwrap();\n\n println!(\"cargo:rustc-link-search={}\", out.display());\n\n println!(\"cargo:rerun-if-changed=device.x\");\n\n }\n\n println!(\"cargo:rerun-if-changed=build.rs\");\n\n}\n", "file_path": "07-rust/stm32f0x1/stm32f0x1_pac/build.rs", "rank": 9, "score": 88441.66588380146 }, { "content": "fn main() {\n\n if env::var_os(\"CARGO_FEATURE_RT\").is_some() {\n\n let out = &PathBuf::from(env::var_os(\"OUT_DIR\").unwrap());\n\n File::create(out.join(\"device.x\"))\n\n .unwrap()\n\n .write_all(include_bytes!(\"device.x\"))\n\n .unwrap();\n\n println!(\"cargo:rustc-link-search={}\", out.display());\n\n println!(\"cargo:rerun-if-changed=device.x\");\n\n }\n\n println!(\"cargo:rerun-if-changed=build.rs\");\n\n}\n", "file_path": "07-rust/stm32l0x1/stm32l0x1_pac/build.rs", "rank": 10, "score": 88441.66588380146 }, { "content": "fn main() {\n\n // Put `memory.x` in our output directory and ensure it's\n\n // on the linker search path.\n\n let out = &PathBuf::from(env::var_os(\"OUT_DIR\").unwrap());\n\n File::create(out.join(\"memory.x\"))\n\n .unwrap()\n\n .write_all(include_bytes!(\"memory.x\"))\n\n .unwrap();\n\n println!(\"cargo:rustc-link-search={}\", out.display());\n\n\n\n // By default, Cargo will re-run a build script whenever\n\n // any file in the project changes. By specifying `memory.x`\n\n // here, we ensure the build script is only re-run when\n\n // `memory.x` is changed.\n\n println!(\"cargo:rerun-if-changed=memory.x\");\n\n}\n", "file_path": "07-rust/stm32f0x1/rust-blink-f031k6/build.rs", "rank": 11, "score": 86885.72247686045 }, { "content": "fn main() {\n\n // Put `memory.x` in our output directory and ensure it's\n\n // on the linker search path.\n\n let out = &PathBuf::from(env::var_os(\"OUT_DIR\").unwrap());\n\n File::create(out.join(\"memory.x\"))\n\n .unwrap()\n\n .write_all(include_bytes!(\"memory.x\"))\n\n .unwrap();\n\n println!(\"cargo:rustc-link-search={}\", out.display());\n\n\n\n // By default, Cargo will re-run a build script whenever\n\n // any file in the project changes. By specifying `memory.x`\n\n // here, we ensure the build script is only re-run when\n\n // `memory.x` is changed.\n\n println!(\"cargo:rerun-if-changed=memory.x\");\n\n}\n", "file_path": "07-rust/stm32l0x1/rust-blink-l031k6/build.rs", "rank": 12, "score": 86885.72247686045 }, { "content": "fn main() {\n\n // Put `memory.x` in our output directory and ensure it's\n\n // on the linker search path.\n\n let out = &PathBuf::from(env::var_os(\"OUT_DIR\").unwrap());\n\n File::create(out.join(\"memory.x\"))\n\n .unwrap()\n\n .write_all(include_bytes!(\"memory.x\"))\n\n .unwrap();\n\n println!(\"cargo:rustc-link-search={}\", out.display());\n\n\n\n // By default, Cargo will re-run a build script whenever\n\n // any file in the project changes. By specifying `memory.x`\n\n // here, we ensure the build script is only re-run when\n\n // `memory.x` is changed.\n\n println!(\"cargo:rerun-if-changed=memory.x\");\n\n}\n", "file_path": "07-rust/stm32f446/rust-blink-f446re/build.rs", "rank": 13, "score": 86885.72247686045 }, { "content": "#[doc = \"This trait shows that register has `write`, `write_with_zero` and `reset` method\"]\n\n#[doc = \"\"]\n\n#[doc = \"Registers marked with `Readable` can be also `modify`'ed\"]\n\npub trait Writable {}\n", "file_path": "07-rust/stm32f0x1/stm32f0x1_pac/src/generic.rs", "rank": 14, "score": 79445.02919668888 }, { "content": "#[doc = \"This trait shows that register has `write`, `write_with_zero` and `reset` method\"]\n\n#[doc = \"\"]\n\n#[doc = \"Registers marked with `Readable` can be also `modify`'ed\"]\n\npub trait Writable {}\n", "file_path": "07-rust/stm32l0x1/stm32l0x1_pac/src/generic.rs", "rank": 15, "score": 79445.02919668888 }, { "content": "#[doc = \"This trait shows that register has `write`, `write_with_zero` and `reset` method\"]\n\n#[doc = \"\"]\n\n#[doc = \"Registers marked with `Readable` can be also `modify`'ed\"]\n\npub trait Writable {}\n", "file_path": "07-rust/stm32f446/stm32f446_pac/src/generic.rs", "rank": 16, "score": 79445.02919668888 }, { "content": "#[doc = \"This trait shows that register has `read` method\"]\n\n#[doc = \"\"]\n\n#[doc = \"Registers marked with `Writable` can be also `modify`'ed\"]\n\npub trait Readable {}\n", "file_path": "07-rust/stm32f0x1/stm32f0x1_pac/src/generic.rs", "rank": 17, "score": 79431.945204443 }, { "content": "#[doc = \"This trait shows that register has `read` method\"]\n\n#[doc = \"\"]\n\n#[doc = \"Registers marked with `Writable` can be also `modify`'ed\"]\n\npub trait Readable {}\n", "file_path": "07-rust/stm32l0x1/stm32l0x1_pac/src/generic.rs", "rank": 18, "score": 79431.945204443 }, { "content": "#[doc = \"This trait shows that register has `read` method\"]\n\n#[doc = \"\"]\n\n#[doc = \"Registers marked with `Writable` can be also `modify`'ed\"]\n\npub trait Readable {}\n", "file_path": "07-rust/stm32f446/stm32f446_pac/src/generic.rs", "rank": 19, "score": 79431.945204443 }, { "content": " CAN_FilterRegister_TypeDef sFilterRegister[28]; /*!< CAN Filter Register, Address offset: 0x240-0x31C */\n", "file_path": "03-gpio/include_f446re/stm32f446xx.h", "rank": 20, "score": 57472.86116302295 }, { "content": "\tint8_t *pcWriteTo;\t\t\t\t/*< Points to the free next place in the storage area. */\n", "file_path": "06-freertos/freertos/Source/queue.c", "rank": 21, "score": 57472.86116302295 }, { "content": " CAN_FilterRegister_TypeDef sFilterRegister[28]; /*!< CAN Filter Register, Address offset: 0x240-0x31C */\n", "file_path": "04-interrupt/include_f446re/stm32f446xx.h", "rank": 22, "score": 57472.86116302295 }, { "content": " CAN_FilterRegister_TypeDef sFilterRegister[28]; /*!< CAN Filter Register, Address offset: 0x240-0x31C */\n", "file_path": "06-freertos/include_f446re/stm32f446xx.h", "rank": 23, "score": 57472.86116302295 }, { "content": " CAN_FilterRegister_TypeDef sFilterRegister[28]; /*!< CAN Filter Register, Address offset: 0x240-0x31C */\n", "file_path": "05-timer/include_f446re/stm32f446xx.h", "rank": 24, "score": 57472.86116302295 }, { "content": "\tTickType_t\t\t\txMessageValue;\t\t/*<< An optional value used by a subset of commands, for example, when changing the period of a timer. */\n", "file_path": "06-freertos/freertos/Source/timers.c", "rank": 25, "score": 57471.50877440298 }, { "content": "PRIVILEGED_DATA static volatile TickType_t xNextTaskUnblockTime\t\t= ( TickType_t ) 0U; /* Initialised to portMAX_DELAY before the scheduler starts. */\n", "file_path": "06-freertos/freertos/Source/tasks.c", "rank": 26, "score": 57470.61156608577 }, { "content": "PRIVILEGED_DATA static volatile BaseType_t xNumOfOverflows \t\t\t= ( BaseType_t ) 0;\n", "file_path": "06-freertos/freertos/Source/tasks.c", "rank": 27, "score": 57470.61156608577 }, { "content": "#define uxQueueType\t\t\t\t\t\tpcHead\n", "file_path": "06-freertos/freertos/Source/queue.c", "rank": 28, "score": 56131.91337094036 }, { "content": "BaseType_t xQueueGenericReset( QueueHandle_t xQueue, BaseType_t xNewQueue )\n\n{\n\nQueue_t * const pxQueue = xQueue;\n\n\n\n\tconfigASSERT( pxQueue );\n\n\n\n\ttaskENTER_CRITICAL();\n\n\t{\n\n\t\tpxQueue->u.xQueue.pcTail = pxQueue->pcHead + ( pxQueue->uxLength * pxQueue->uxItemSize ); /*lint !e9016 Pointer arithmetic allowed on char types, especially when it assists conveying intent. */\n\n\t\tpxQueue->uxMessagesWaiting = ( UBaseType_t ) 0U;\n\n\t\tpxQueue->pcWriteTo = pxQueue->pcHead;\n\n\t\tpxQueue->u.xQueue.pcReadFrom = pxQueue->pcHead + ( ( pxQueue->uxLength - 1U ) * pxQueue->uxItemSize ); /*lint !e9016 Pointer arithmetic allowed on char types, especially when it assists conveying intent. */\n\n\t\tpxQueue->cRxLock = queueUNLOCKED;\n\n\t\tpxQueue->cTxLock = queueUNLOCKED;\n\n\n\n\t\tif( xNewQueue == pdFALSE )\n\n\t\t{\n\n\t\t\t/* If there are tasks blocked waiting to read from the queue, then\n\n\t\t\tthe tasks will remain blocked as after this function exits the queue\n\n\t\t\twill still be empty. If there are tasks blocked waiting to write to\n\n\t\t\tthe queue, then one should be unblocked as after this function exits\n\n\t\t\tit will be possible to write to it. */\n\n\t\t\tif( listLIST_IS_EMPTY( &( pxQueue->xTasksWaitingToSend ) ) == pdFALSE )\n\n\t\t\t{\n\n\t\t\t\tif( xTaskRemoveFromEventList( &( pxQueue->xTasksWaitingToSend ) ) != pdFALSE )\n\n\t\t\t\t{\n\n\t\t\t\t\tqueueYIELD_IF_USING_PREEMPTION();\n\n\t\t\t\t}\n\n\t\t\t\telse\n\n\t\t\t\t{\n\n\t\t\t\t\tmtCOVERAGE_TEST_MARKER();\n\n\t\t\t\t}\n\n\t\t\t}\n\n\t\t\telse\n\n\t\t\t{\n\n\t\t\t\tmtCOVERAGE_TEST_MARKER();\n\n\t\t\t}\n\n\t\t}\n\n\t\telse\n\n\t\t{\n\n\t\t\t/* Ensure the event queues start in the correct state. */\n\n\t\t\tvListInitialise( &( pxQueue->xTasksWaitingToSend ) );\n\n\t\t\tvListInitialise( &( pxQueue->xTasksWaitingToReceive ) );\n\n\t\t}\n\n\t}\n\n\ttaskEXIT_CRITICAL();\n\n\n\n\t/* A value is returned for calling semantic consistency with previous\n\n\tversions. */\n\n\treturn pdPASS;\n", "file_path": "06-freertos/freertos/Source/queue.c", "rank": 29, "score": 56128.73144872263 }, { "content": "\tconfigLIST_VOLATILE TickType_t xItemValue;\n", "file_path": "06-freertos/freertos/Source/include/list.h", "rank": 30, "score": 56128.51211806137 }, { "content": "PRIVILEGED_DATA static volatile UBaseType_t uxSchedulerSuspended\t= ( UBaseType_t ) pdFALSE;\n", "file_path": "06-freertos/freertos/Source/tasks.c", "rank": 31, "score": 56127.635875746186 }, { "content": "BaseType_t xStreamBufferReset( StreamBufferHandle_t xStreamBuffer )\n\n{\n\nStreamBuffer_t * const pxStreamBuffer = xStreamBuffer;\n\nBaseType_t xReturn = pdFAIL;\n\n\n\n#if( configUSE_TRACE_FACILITY == 1 )\n\n\tUBaseType_t uxStreamBufferNumber;\n\n#endif\n\n\n\n\tconfigASSERT( pxStreamBuffer );\n\n\n\n\t#if( configUSE_TRACE_FACILITY == 1 )\n\n\t{\n\n\t\t/* Store the stream buffer number so it can be restored after the\n\n\t\treset. */\n\n\t\tuxStreamBufferNumber = pxStreamBuffer->uxStreamBufferNumber;\n\n\t}\n\n\t#endif\n\n\n\n\t/* Can only reset a message buffer if there are no tasks blocked on it. */\n\n\ttaskENTER_CRITICAL();\n\n\t{\n\n\t\tif( pxStreamBuffer->xTaskWaitingToReceive == NULL )\n\n\t\t{\n\n\t\t\tif( pxStreamBuffer->xTaskWaitingToSend == NULL )\n\n\t\t\t{\n\n\t\t\t\tprvInitialiseNewStreamBuffer( pxStreamBuffer,\n\n\t\t\t\t\t\t\t\t\t\t\t pxStreamBuffer->pucBuffer,\n\n\t\t\t\t\t\t\t\t\t\t\t pxStreamBuffer->xLength,\n\n\t\t\t\t\t\t\t\t\t\t\t pxStreamBuffer->xTriggerLevelBytes,\n\n\t\t\t\t\t\t\t\t\t\t\t pxStreamBuffer->ucFlags );\n\n\t\t\t\txReturn = pdPASS;\n\n\n\n\t\t\t\t#if( configUSE_TRACE_FACILITY == 1 )\n\n\t\t\t\t{\n\n\t\t\t\t\tpxStreamBuffer->uxStreamBufferNumber = uxStreamBufferNumber;\n\n\t\t\t\t}\n\n\t\t\t\t#endif\n\n\n\n\t\t\t\ttraceSTREAM_BUFFER_RESET( xStreamBuffer );\n\n\t\t\t}\n\n\t\t}\n\n\t}\n\n\ttaskEXIT_CRITICAL();\n\n\n\n\treturn xReturn;\n", "file_path": "06-freertos/freertos/Source/stream_buffer.c", "rank": 32, "score": 54847.06295371009 }, { "content": "\tList_t xTasksWaitingForBits;\t\t/*< List of tasks waiting for a bit to be set. */\n", "file_path": "06-freertos/freertos/Source/event_groups.c", "rank": 33, "score": 54842.57219325134 }, { "content": "\tEventBits_t uxEventBits;\n", "file_path": "06-freertos/freertos/Source/event_groups.c", "rank": 34, "score": 54842.57219325134 }, { "content": "static size_t prvWriteMessageToBuffer( StreamBuffer_t * const pxStreamBuffer,\n\n\t\t\t\t\t\t\t\t\t\tconst void * pvTxData,\n\n\t\t\t\t\t\t\t\t\t\tsize_t xDataLengthBytes,\n\n\t\t\t\t\t\t\t\t\t\tsize_t xSpace,\n", "file_path": "06-freertos/freertos/Source/stream_buffer.c", "rank": 35, "score": 53630.907899285085 }, { "content": "static size_t prvWriteBytesToBuffer( StreamBuffer_t * const pxStreamBuffer, const uint8_t *pucData, size_t xCount ) PRIVILEGED_FUNCTION;\n", "file_path": "06-freertos/freertos/Source/stream_buffer.c", "rank": 36, "score": 53623.67239880589 }, { "content": "EventBits_t xEventGroupWaitBits( EventGroupHandle_t xEventGroup, const EventBits_t uxBitsToWaitFor, const BaseType_t xClearOnExit, const BaseType_t xWaitForAllBits, TickType_t xTicksToWait )\n\n{\n\nEventGroup_t *pxEventBits = xEventGroup;\n\nEventBits_t uxReturn, uxControlBits = 0;\n\nBaseType_t xWaitConditionMet, xAlreadyYielded;\n\nBaseType_t xTimeoutOccurred = pdFALSE;\n\n\n\n\t/* Check the user is not attempting to wait on the bits used by the kernel\n\n\titself, and that at least one bit is being requested. */\n\n\tconfigASSERT( xEventGroup );\n\n\tconfigASSERT( ( uxBitsToWaitFor & eventEVENT_BITS_CONTROL_BYTES ) == 0 );\n\n\tconfigASSERT( uxBitsToWaitFor != 0 );\n\n\t#if ( ( INCLUDE_xTaskGetSchedulerState == 1 ) || ( configUSE_TIMERS == 1 ) )\n\n\t{\n\n\t\tconfigASSERT( !( ( xTaskGetSchedulerState() == taskSCHEDULER_SUSPENDED ) && ( xTicksToWait != 0 ) ) );\n\n\t}\n\n\t#endif\n\n\n\n\tvTaskSuspendAll();\n\n\t{\n\n\t\tconst EventBits_t uxCurrentEventBits = pxEventBits->uxEventBits;\n\n\n\n\t\t/* Check to see if the wait condition is already met or not. */\n\n\t\txWaitConditionMet = prvTestWaitCondition( uxCurrentEventBits, uxBitsToWaitFor, xWaitForAllBits );\n\n\n\n\t\tif( xWaitConditionMet != pdFALSE )\n\n\t\t{\n\n\t\t\t/* The wait condition has already been met so there is no need to\n\n\t\t\tblock. */\n\n\t\t\tuxReturn = uxCurrentEventBits;\n\n\t\t\txTicksToWait = ( TickType_t ) 0;\n\n\n\n\t\t\t/* Clear the wait bits if requested to do so. */\n\n\t\t\tif( xClearOnExit != pdFALSE )\n\n\t\t\t{\n\n\t\t\t\tpxEventBits->uxEventBits &= ~uxBitsToWaitFor;\n\n\t\t\t}\n\n\t\t\telse\n\n\t\t\t{\n\n\t\t\t\tmtCOVERAGE_TEST_MARKER();\n\n\t\t\t}\n\n\t\t}\n\n\t\telse if( xTicksToWait == ( TickType_t ) 0 )\n\n\t\t{\n\n\t\t\t/* The wait condition has not been met, but no block time was\n\n\t\t\tspecified, so just return the current value. */\n\n\t\t\tuxReturn = uxCurrentEventBits;\n\n\t\t\txTimeoutOccurred = pdTRUE;\n\n\t\t}\n\n\t\telse\n\n\t\t{\n\n\t\t\t/* The task is going to block to wait for its required bits to be\n\n\t\t\tset. uxControlBits are used to remember the specified behaviour of\n\n\t\t\tthis call to xEventGroupWaitBits() - for use when the event bits\n\n\t\t\tunblock the task. */\n\n\t\t\tif( xClearOnExit != pdFALSE )\n\n\t\t\t{\n\n\t\t\t\tuxControlBits |= eventCLEAR_EVENTS_ON_EXIT_BIT;\n\n\t\t\t}\n\n\t\t\telse\n\n\t\t\t{\n\n\t\t\t\tmtCOVERAGE_TEST_MARKER();\n\n\t\t\t}\n\n\n\n\t\t\tif( xWaitForAllBits != pdFALSE )\n\n\t\t\t{\n\n\t\t\t\tuxControlBits |= eventWAIT_FOR_ALL_BITS;\n\n\t\t\t}\n\n\t\t\telse\n\n\t\t\t{\n\n\t\t\t\tmtCOVERAGE_TEST_MARKER();\n\n\t\t\t}\n\n\n\n\t\t\t/* Store the bits that the calling task is waiting for in the\n\n\t\t\ttask's event list item so the kernel knows when a match is\n\n\t\t\tfound. Then enter the blocked state. */\n\n\t\t\tvTaskPlaceOnUnorderedEventList( &( pxEventBits->xTasksWaitingForBits ), ( uxBitsToWaitFor | uxControlBits ), xTicksToWait );\n\n\n\n\t\t\t/* This is obsolete as it will get set after the task unblocks, but\n\n\t\t\tsome compilers mistakenly generate a warning about the variable\n\n\t\t\tbeing returned without being set if it is not done. */\n\n\t\t\tuxReturn = 0;\n\n\n\n\t\t\ttraceEVENT_GROUP_WAIT_BITS_BLOCK( xEventGroup, uxBitsToWaitFor );\n\n\t\t}\n\n\t}\n\n\txAlreadyYielded = xTaskResumeAll();\n\n\n\n\tif( xTicksToWait != ( TickType_t ) 0 )\n\n\t{\n\n\t\tif( xAlreadyYielded == pdFALSE )\n\n\t\t{\n\n\t\t\tportYIELD_WITHIN_API();\n\n\t\t}\n\n\t\telse\n\n\t\t{\n\n\t\t\tmtCOVERAGE_TEST_MARKER();\n\n\t\t}\n\n\n\n\t\t/* The task blocked to wait for its required bits to be set - at this\n\n\t\tpoint either the required bits were set or the block time expired. If\n\n\t\tthe required bits were set they will have been stored in the task's\n\n\t\tevent list item, and they should now be retrieved then cleared. */\n\n\t\tuxReturn = uxTaskResetEventItemValue();\n\n\n\n\t\tif( ( uxReturn & eventUNBLOCKED_DUE_TO_BIT_SET ) == ( EventBits_t ) 0 )\n\n\t\t{\n\n\t\t\ttaskENTER_CRITICAL();\n\n\t\t\t{\n\n\t\t\t\t/* The task timed out, just return the current event bit value. */\n\n\t\t\t\tuxReturn = pxEventBits->uxEventBits;\n\n\n\n\t\t\t\t/* It is possible that the event bits were updated between this\n\n\t\t\t\ttask leaving the Blocked state and running again. */\n\n\t\t\t\tif( prvTestWaitCondition( uxReturn, uxBitsToWaitFor, xWaitForAllBits ) != pdFALSE )\n\n\t\t\t\t{\n\n\t\t\t\t\tif( xClearOnExit != pdFALSE )\n\n\t\t\t\t\t{\n\n\t\t\t\t\t\tpxEventBits->uxEventBits &= ~uxBitsToWaitFor;\n\n\t\t\t\t\t}\n\n\t\t\t\t\telse\n\n\t\t\t\t\t{\n\n\t\t\t\t\t\tmtCOVERAGE_TEST_MARKER();\n\n\t\t\t\t\t}\n\n\t\t\t\t}\n\n\t\t\t\telse\n\n\t\t\t\t{\n\n\t\t\t\t\tmtCOVERAGE_TEST_MARKER();\n\n\t\t\t\t}\n\n\t\t\t\txTimeoutOccurred = pdTRUE;\n\n\t\t\t}\n\n\t\t\ttaskEXIT_CRITICAL();\n\n\t\t}\n\n\t\telse\n\n\t\t{\n\n\t\t\t/* The task unblocked because the bits were set. */\n\n\t\t}\n\n\n\n\t\t/* The task blocked so control bits may have been set. */\n\n\t\tuxReturn &= ~eventEVENT_BITS_CONTROL_BYTES;\n\n\t}\n\n\ttraceEVENT_GROUP_WAIT_BITS_END( xEventGroup, uxBitsToWaitFor, xTimeoutOccurred );\n\n\n\n\t/* Prevent compiler warnings when trace macros are not used. */\n\n\t( void ) xTimeoutOccurred;\n\n\n\n\treturn uxReturn;\n", "file_path": "06-freertos/freertos/Source/event_groups.c", "rank": 37, "score": 53618.229617090416 }, { "content": "EventBits_t xEventGroupClearBits( EventGroupHandle_t xEventGroup, const EventBits_t uxBitsToClear )\n\n{\n\nEventGroup_t *pxEventBits = xEventGroup;\n\nEventBits_t uxReturn;\n\n\n\n\t/* Check the user is not attempting to clear the bits used by the kernel\n\n\titself. */\n\n\tconfigASSERT( xEventGroup );\n\n\tconfigASSERT( ( uxBitsToClear & eventEVENT_BITS_CONTROL_BYTES ) == 0 );\n\n\n\n\ttaskENTER_CRITICAL();\n\n\t{\n\n\t\ttraceEVENT_GROUP_CLEAR_BITS( xEventGroup, uxBitsToClear );\n\n\n\n\t\t/* The value returned is the event group value prior to the bits being\n\n\t\tcleared. */\n\n\t\tuxReturn = pxEventBits->uxEventBits;\n\n\n\n\t\t/* Clear the bits. */\n\n\t\tpxEventBits->uxEventBits &= ~uxBitsToClear;\n\n\t}\n\n\ttaskEXIT_CRITICAL();\n\n\n\n\treturn uxReturn;\n", "file_path": "06-freertos/freertos/Source/event_groups.c", "rank": 38, "score": 53618.229617090416 }, { "content": "EventBits_t xEventGroupSetBits( EventGroupHandle_t xEventGroup, const EventBits_t uxBitsToSet )\n\n{\n\nListItem_t *pxListItem, *pxNext;\n\nListItem_t const *pxListEnd;\n\nList_t const * pxList;\n\nEventBits_t uxBitsToClear = 0, uxBitsWaitedFor, uxControlBits;\n\nEventGroup_t *pxEventBits = xEventGroup;\n\nBaseType_t xMatchFound = pdFALSE;\n\n\n\n\t/* Check the user is not attempting to set the bits used by the kernel\n\n\titself. */\n\n\tconfigASSERT( xEventGroup );\n\n\tconfigASSERT( ( uxBitsToSet & eventEVENT_BITS_CONTROL_BYTES ) == 0 );\n\n\n\n\tpxList = &( pxEventBits->xTasksWaitingForBits );\n\n\tpxListEnd = listGET_END_MARKER( pxList ); /*lint !e826 !e740 !e9087 The mini list structure is used as the list end to save RAM. This is checked and valid. */\n\n\tvTaskSuspendAll();\n\n\t{\n\n\t\ttraceEVENT_GROUP_SET_BITS( xEventGroup, uxBitsToSet );\n\n\n\n\t\tpxListItem = listGET_HEAD_ENTRY( pxList );\n\n\n\n\t\t/* Set the bits. */\n\n\t\tpxEventBits->uxEventBits |= uxBitsToSet;\n\n\n\n\t\t/* See if the new bit value should unblock any tasks. */\n\n\t\twhile( pxListItem != pxListEnd )\n\n\t\t{\n\n\t\t\tpxNext = listGET_NEXT( pxListItem );\n\n\t\t\tuxBitsWaitedFor = listGET_LIST_ITEM_VALUE( pxListItem );\n\n\t\t\txMatchFound = pdFALSE;\n\n\n\n\t\t\t/* Split the bits waited for from the control bits. */\n\n\t\t\tuxControlBits = uxBitsWaitedFor & eventEVENT_BITS_CONTROL_BYTES;\n\n\t\t\tuxBitsWaitedFor &= ~eventEVENT_BITS_CONTROL_BYTES;\n\n\n\n\t\t\tif( ( uxControlBits & eventWAIT_FOR_ALL_BITS ) == ( EventBits_t ) 0 )\n\n\t\t\t{\n\n\t\t\t\t/* Just looking for single bit being set. */\n\n\t\t\t\tif( ( uxBitsWaitedFor & pxEventBits->uxEventBits ) != ( EventBits_t ) 0 )\n\n\t\t\t\t{\n\n\t\t\t\t\txMatchFound = pdTRUE;\n\n\t\t\t\t}\n\n\t\t\t\telse\n\n\t\t\t\t{\n\n\t\t\t\t\tmtCOVERAGE_TEST_MARKER();\n\n\t\t\t\t}\n\n\t\t\t}\n\n\t\t\telse if( ( uxBitsWaitedFor & pxEventBits->uxEventBits ) == uxBitsWaitedFor )\n\n\t\t\t{\n\n\t\t\t\t/* All bits are set. */\n\n\t\t\t\txMatchFound = pdTRUE;\n\n\t\t\t}\n\n\t\t\telse\n\n\t\t\t{\n\n\t\t\t\t/* Need all bits to be set, but not all the bits were set. */\n\n\t\t\t}\n\n\n\n\t\t\tif( xMatchFound != pdFALSE )\n\n\t\t\t{\n\n\t\t\t\t/* The bits match. Should the bits be cleared on exit? */\n\n\t\t\t\tif( ( uxControlBits & eventCLEAR_EVENTS_ON_EXIT_BIT ) != ( EventBits_t ) 0 )\n\n\t\t\t\t{\n\n\t\t\t\t\tuxBitsToClear |= uxBitsWaitedFor;\n\n\t\t\t\t}\n\n\t\t\t\telse\n\n\t\t\t\t{\n\n\t\t\t\t\tmtCOVERAGE_TEST_MARKER();\n\n\t\t\t\t}\n\n\n\n\t\t\t\t/* Store the actual event flag value in the task's event list\n\n\t\t\t\titem before removing the task from the event list. The\n\n\t\t\t\teventUNBLOCKED_DUE_TO_BIT_SET bit is set so the task knows\n\n\t\t\t\tthat is was unblocked due to its required bits matching, rather\n\n\t\t\t\tthan because it timed out. */\n\n\t\t\t\tvTaskRemoveFromUnorderedEventList( pxListItem, pxEventBits->uxEventBits | eventUNBLOCKED_DUE_TO_BIT_SET );\n\n\t\t\t}\n\n\n\n\t\t\t/* Move onto the next list item. Note pxListItem->pxNext is not\n\n\t\t\tused here as the list item may have been removed from the event list\n\n\t\t\tand inserted into the ready/pending reading list. */\n\n\t\t\tpxListItem = pxNext;\n\n\t\t}\n\n\n\n\t\t/* Clear any bits that matched when the eventCLEAR_EVENTS_ON_EXIT_BIT\n\n\t\tbit was set in the control word. */\n\n\t\tpxEventBits->uxEventBits &= ~uxBitsToClear;\n\n\t}\n\n\t( void ) xTaskResumeAll();\n\n\n\n\treturn pxEventBits->uxEventBits;\n", "file_path": "06-freertos/freertos/Source/event_groups.c", "rank": 39, "score": 53618.229617090416 }, { "content": "static size_t xBlockAllocatedBit = 0;\n", "file_path": "06-freertos/freertos/Source/portable/MemMang/heap_5.c", "rank": 40, "score": 52459.95583543297 }, { "content": "static size_t xBlockAllocatedBit = 0;\n", "file_path": "06-freertos/freertos/Source/portable/MemMang/heap_4.c", "rank": 41, "score": 52459.95583543297 }, { "content": "void vEventGroupClearBitsCallback( void *pvEventGroup, const uint32_t ulBitsToClear )\n\n{\n\n\t( void ) xEventGroupClearBits( pvEventGroup, ( EventBits_t ) ulBitsToClear ); /*lint !e9079 Can't avoid cast to void* as a generic timer callback prototype. Callback casts back to original type so safe. */\n", "file_path": "06-freertos/freertos/Source/event_groups.c", "rank": 42, "score": 52453.166317740535 }, { "content": "void vEventGroupSetBitsCallback( void *pvEventGroup, const uint32_t ulBitsToSet )\n\n{\n\n\t( void ) xEventGroupSetBits( pvEventGroup, ( EventBits_t ) ulBitsToSet ); /*lint !e9079 Can't avoid cast to void* as a generic timer callback prototype. Callback casts back to original type so safe. */\n", "file_path": "06-freertos/freertos/Source/event_groups.c", "rank": 43, "score": 52453.166317740535 }, { "content": "static const uint16_t heapSTRUCT_SIZE\t= ( ( sizeof ( BlockLink_t ) + ( portBYTE_ALIGNMENT - 1 ) ) & ~portBYTE_ALIGNMENT_MASK );\n", "file_path": "06-freertos/freertos/Source/portable/MemMang/heap_2.c", "rank": 44, "score": 52453.10204254395 }, { "content": "static const size_t xHeapStructSize\t= ( sizeof( BlockLink_t ) + ( ( size_t ) ( portBYTE_ALIGNMENT - 1 ) ) ) & ~( ( size_t ) portBYTE_ALIGNMENT_MASK );\n", "file_path": "06-freertos/freertos/Source/portable/MemMang/heap_5.c", "rank": 45, "score": 52453.10204254395 }, { "content": "static const size_t xHeapStructSize\t= ( sizeof( BlockLink_t ) + ( ( size_t ) ( portBYTE_ALIGNMENT - 1 ) ) ) & ~( ( size_t ) portBYTE_ALIGNMENT_MASK );\n", "file_path": "06-freertos/freertos/Source/portable/MemMang/heap_4.c", "rank": 46, "score": 52453.10204254395 }, { "content": "BaseType_t MPU_xStreamBufferReset( StreamBufferHandle_t xStreamBuffer ) FREERTOS_SYSTEM_CALL;\n", "file_path": "06-freertos/freertos/Source/include/mpu_prototypes.h", "rank": 47, "score": 52451.65401680738 }, { "content": "static void prvResetNextTaskUnblockTime( void );\n", "file_path": "06-freertos/freertos/Source/tasks.c", "rank": 48, "score": 52451.65401680738 }, { "content": "BaseType_t MPU_xQueueGenericReset( QueueHandle_t xQueue, BaseType_t xNewQueue ) FREERTOS_SYSTEM_CALL;\n", "file_path": "06-freertos/freertos/Source/include/mpu_prototypes.h", "rank": 49, "score": 52451.65401680738 }, { "content": "EventBits_t xEventGroupGetBitsFromISR( EventGroupHandle_t xEventGroup )\n\n{\n\nUBaseType_t uxSavedInterruptStatus;\n\nEventGroup_t const * const pxEventBits = xEventGroup;\n\nEventBits_t uxReturn;\n\n\n\n\tuxSavedInterruptStatus = portSET_INTERRUPT_MASK_FROM_ISR();\n\n\t{\n\n\t\tuxReturn = pxEventBits->uxEventBits;\n\n\t}\n\n\tportCLEAR_INTERRUPT_MASK_FROM_ISR( uxSavedInterruptStatus );\n\n\n\n\treturn uxReturn;\n", "file_path": "06-freertos/freertos/Source/event_groups.c", "rank": 50, "score": 52447.35938732006 }, { "content": "#define heapBITS_PER_BYTE\t\t( ( size_t ) 8 )\n", "file_path": "06-freertos/freertos/Source/portable/MemMang/heap_5.c", "rank": 51, "score": 51332.692742444764 }, { "content": "#define heapBITS_PER_BYTE\t\t( ( size_t ) 8 )\n", "file_path": "06-freertos/freertos/Source/portable/MemMang/heap_4.c", "rank": 52, "score": 51332.692742444764 }, { "content": "EventBits_t MPU_xEventGroupSetBits( EventGroupHandle_t xEventGroup, const EventBits_t uxBitsToSet ) FREERTOS_SYSTEM_CALL;\n", "file_path": "06-freertos/freertos/Source/include/mpu_prototypes.h", "rank": 53, "score": 51326.53331227369 }, { "content": "EventBits_t MPU_xEventGroupClearBits( EventGroupHandle_t xEventGroup, const EventBits_t uxBitsToClear ) FREERTOS_SYSTEM_CALL;\n", "file_path": "06-freertos/freertos/Source/include/mpu_prototypes.h", "rank": 54, "score": 51326.53331227369 }, { "content": "EventBits_t MPU_xEventGroupWaitBits( EventGroupHandle_t xEventGroup, const EventBits_t uxBitsToWaitFor, const BaseType_t xClearOnExit, const BaseType_t xWaitForAllBits, TickType_t xTicksToWait ) FREERTOS_SYSTEM_CALL;\n", "file_path": "06-freertos/freertos/Source/include/mpu_prototypes.h", "rank": 55, "score": 51326.53331227369 }, { "content": "#define portMAX_24_BIT_NUMBER\t\t\t\t( 0xffffffUL )\n", "file_path": "06-freertos/freertos/Source/portable/GCC/ARM_CM4F/port.c", "rank": 56, "score": 50258.769547518794 }, { "content": "#define portMAX_24_BIT_NUMBER\t\t\t\t( 0xffffffUL )\n", "file_path": "06-freertos/freertos/Source/portable/GCC/ARM_CM0/port.c", "rank": 57, "score": 50258.769547518794 }, { "content": "uint32_t MPU_ulTaskNotifyValueClear( TaskHandle_t xTask, uint32_t ulBitsToClear ) FREERTOS_SYSTEM_CALL;\n", "file_path": "06-freertos/freertos/Source/include/mpu_prototypes.h", "rank": 58, "score": 50256.52864573755 }, { "content": "uint8_t MPU_ucQueueGetQueueType( QueueHandle_t xQueue ) FREERTOS_SYSTEM_CALL;\n", "file_path": "06-freertos/freertos/Source/include/mpu_prototypes.h", "rank": 59, "score": 50255.74407306045 }, { "content": "#define portASPEN_AND_LSPEN_BITS\t\t\t( 0x3UL << 30UL )\n", "file_path": "06-freertos/freertos/Source/portable/GCC/ARM_CM4F/port.c", "rank": 60, "score": 50252.61011734772 }, { "content": "#define portNVIC_PENDSVSET_BIT\t\t\t\t( 1UL << 28UL )\n", "file_path": "06-freertos/freertos/Source/portable/GCC/ARM_CM0/port.c", "rank": 61, "score": 50252.61011734772 }, { "content": "#define portTOP_BIT_OF_BYTE\t\t\t\t\t( ( uint8_t ) 0x80 )\n", "file_path": "06-freertos/freertos/Source/portable/GCC/ARM_CM4F/port.c", "rank": 62, "score": 50252.61011734772 }, { "content": "#define portMAX_PRIGROUP_BITS\t\t\t\t( ( uint8_t ) 7 )\n", "file_path": "06-freertos/freertos/Source/portable/GCC/ARM_CM4F/port.c", "rank": 63, "score": 50252.61011734772 }, { "content": "#define portNVIC_PENDSVCLEAR_BIT \t\t\t( 1UL << 27UL )\n", "file_path": "06-freertos/freertos/Source/portable/GCC/ARM_CM4F/port.c", "rank": 64, "score": 50252.61011734772 }, { "content": "#define portNVIC_SYSTICK_INT_BIT\t\t\t( 1UL << 1UL )\n", "file_path": "06-freertos/freertos/Source/portable/GCC/ARM_CM4F/port.c", "rank": 65, "score": 49236.35037227041 }, { "content": "#define portNVIC_IP_REGISTERS_OFFSET_16 \t( 0xE000E3F0 )\n", "file_path": "06-freertos/freertos/Source/portable/GCC/ARM_CM4F/port.c", "rank": 66, "score": 49227.70263634573 }, { "content": "#define portNVIC_SYSTICK_ENABLE_BIT\t\t\t( 1UL << 0UL )\n", "file_path": "06-freertos/freertos/Source/portable/GCC/ARM_CM0/port.c", "rank": 67, "score": 49222.7060438369 }, { "content": "#define portNVIC_SYSTICK_CLK_BIT\t\t\t( 1UL << 2UL )\n", "file_path": "06-freertos/freertos/Source/portable/GCC/ARM_CM0/port.c", "rank": 68, "score": 49222.7060438369 }, { "content": "#define portNVIC_SYSTICK_ENABLE_BIT\t\t\t( 1UL << 0UL )\n", "file_path": "06-freertos/freertos/Source/portable/GCC/ARM_CM4F/port.c", "rank": 69, "score": 49222.7060438369 }, { "content": "#define portNVIC_SYSTICK_INT_BIT\t\t\t( 1UL << 1UL )\n", "file_path": "06-freertos/freertos/Source/portable/GCC/ARM_CM0/port.c", "rank": 70, "score": 49222.7060438369 }, { "content": "#define portNVIC_SYSTICK_CURRENT_VALUE_REG\t( * ( ( volatile uint32_t * ) 0xe000e018 ) )\n", "file_path": "06-freertos/freertos/Source/portable/GCC/ARM_CM0/port.c", "rank": 71, "score": 48237.930127727086 }, { "content": "#define portNVIC_SYSTICK_CURRENT_VALUE_REG\t( * ( ( volatile uint32_t * ) 0xe000e018 ) )\n", "file_path": "06-freertos/freertos/Source/portable/GCC/ARM_CM4F/port.c", "rank": 72, "score": 48237.930127727086 }, { "content": "#define portNVIC_PEND_SYSTICK_CLEAR_BIT\t\t( 1UL << 25UL )\n", "file_path": "06-freertos/freertos/Source/portable/GCC/ARM_CM4F/port.c", "rank": 73, "score": 48234.16899054223 }, { "content": "#define portNVIC_SYSTICK_COUNT_FLAG_BIT\t\t( 1UL << 16UL )\n", "file_path": "06-freertos/freertos/Source/portable/GCC/ARM_CM0/port.c", "rank": 74, "score": 48234.16899054223 }, { "content": "#define portNVIC_SYSTICK_COUNT_FLAG_BIT\t\t( 1UL << 16UL )\n", "file_path": "06-freertos/freertos/Source/portable/GCC/ARM_CM4F/port.c", "rank": 75, "score": 48234.16899054223 }, { "content": "#[doc = \"Reader of register SDCMR\"]\n\npub type R = crate::R<u32, super::SDCMR>;\n\n#[doc = \"Writer for register SDCMR\"]\n\npub type W = crate::W<u32, super::SDCMR>;\n\n#[doc = \"Register SDCMR `reset()`'s with value 0\"]\n\nimpl crate::ResetValue for super::SDCMR {\n\n type Type = u32;\n\n #[inline(always)]\n\n fn reset_value() -> Self::Type {\n\n 0\n\n }\n\n}\n\n#[doc = \"Write proxy for field `MODE`\"]\n\npub struct MODE_W<'a> {\n\n w: &'a mut W,\n\n}\n\nimpl<'a> MODE_W<'a> {\n\n #[doc = r\"Writes raw bits to the field\"]\n\n #[inline(always)]\n\n pub unsafe fn bits(self, value: u8) -> &'a mut W {\n", "file_path": "07-rust/stm32f446/stm32f446_pac/src/fmc/sdcmr.rs", "rank": 76, "score": 98.06184003549438 }, { "content": "#[doc = \"Reader of register OR\"]\n\npub type R = crate::R<u32, super::OR>;\n\n#[doc = \"Writer for register OR\"]\n\npub type W = crate::W<u32, super::OR>;\n\n#[doc = \"Register OR `reset()`'s with value 0\"]\n\nimpl crate::ResetValue for super::OR {\n\n type Type = u32;\n\n #[inline(always)]\n\n fn reset_value() -> Self::Type {\n\n 0\n\n }\n\n}\n\n#[doc = \"Reader of field `RMP`\"]\n\npub type RMP_R = crate::R<u8, u8>;\n\n#[doc = \"Write proxy for field `RMP`\"]\n\npub struct RMP_W<'a> {\n\n w: &'a mut W,\n\n}\n\nimpl<'a> RMP_W<'a> {\n\n #[doc = r\"Writes raw bits to the field\"]\n", "file_path": "07-rust/stm32f446/stm32f446_pac/src/tim11/or.rs", "rank": 77, "score": 96.96972511099106 }, { "content": "#[doc = \"Reader of register OR\"]\n\npub type R = crate::R<u32, super::OR>;\n\n#[doc = \"Writer for register OR\"]\n\npub type W = crate::W<u32, super::OR>;\n\n#[doc = \"Register OR `reset()`'s with value 0\"]\n\nimpl crate::ResetValue for super::OR {\n\n type Type = u32;\n\n #[inline(always)]\n\n fn reset_value() -> Self::Type {\n\n 0\n\n }\n\n}\n\n#[doc = \"Reader of field `RMP`\"]\n\npub type RMP_R = crate::R<u8, u8>;\n\n#[doc = \"Write proxy for field `RMP`\"]\n\npub struct RMP_W<'a> {\n\n w: &'a mut W,\n\n}\n\nimpl<'a> RMP_W<'a> {\n\n #[doc = r\"Writes raw bits to the field\"]\n", "file_path": "07-rust/stm32f0x1/stm32f0x1_pac/src/tim14/or.rs", "rank": 78, "score": 96.96972511099109 }, { "content": "#[doc = \"Reader of register OR\"]\n\npub type R = crate::R<u32, super::OR>;\n\n#[doc = \"Writer for register OR\"]\n\npub type W = crate::W<u32, super::OR>;\n\n#[doc = \"Register OR `reset()`'s with value 0\"]\n\nimpl crate::ResetValue for super::OR {\n\n type Type = u32;\n\n #[inline(always)]\n\n fn reset_value() -> Self::Type {\n\n 0\n\n }\n\n}\n\n#[doc = \"Reader of field `ETR_RMP`\"]\n\npub type ETR_RMP_R = crate::R<u8, u8>;\n\n#[doc = \"Write proxy for field `ETR_RMP`\"]\n\npub struct ETR_RMP_W<'a> {\n\n w: &'a mut W,\n\n}\n\nimpl<'a> ETR_RMP_W<'a> {\n\n #[doc = r\"Writes raw bits to the field\"]\n", "file_path": "07-rust/stm32l0x1/stm32l0x1_pac/src/tim21/or.rs", "rank": 79, "score": 94.72445113417835 }, { "content": "#[doc = \"Reader of register OR\"]\n\npub type R = crate::R<u32, super::OR>;\n\n#[doc = \"Writer for register OR\"]\n\npub type W = crate::W<u32, super::OR>;\n\n#[doc = \"Register OR `reset()`'s with value 0\"]\n\nimpl crate::ResetValue for super::OR {\n\n type Type = u32;\n\n #[inline(always)]\n\n fn reset_value() -> Self::Type {\n\n 0\n\n }\n\n}\n\n#[doc = \"Reader of field `ITR1_RMP`\"]\n\npub type ITR1_RMP_R = crate::R<u8, u8>;\n\n#[doc = \"Write proxy for field `ITR1_RMP`\"]\n\npub struct ITR1_RMP_W<'a> {\n\n w: &'a mut W,\n\n}\n\nimpl<'a> ITR1_RMP_W<'a> {\n\n #[doc = r\"Writes raw bits to the field\"]\n", "file_path": "07-rust/stm32f446/stm32f446_pac/src/tim2/or.rs", "rank": 80, "score": 94.72445113417837 }, { "content": "#[doc = \"Reader of register OR\"]\n\npub type R = crate::R<u32, super::OR>;\n\n#[doc = \"Writer for register OR\"]\n\npub type W = crate::W<u32, super::OR>;\n\n#[doc = \"Register OR `reset()`'s with value 0\"]\n\nimpl crate::ResetValue for super::OR {\n\n type Type = u32;\n\n #[inline(always)]\n\n fn reset_value() -> Self::Type {\n\n 0\n\n }\n\n}\n\n#[doc = \"Reader of field `ETR_RMP`\"]\n\npub type ETR_RMP_R = crate::R<u8, u8>;\n\n#[doc = \"Write proxy for field `ETR_RMP`\"]\n\npub struct ETR_RMP_W<'a> {\n\n w: &'a mut W,\n\n}\n\nimpl<'a> ETR_RMP_W<'a> {\n\n #[doc = r\"Writes raw bits to the field\"]\n", "file_path": "07-rust/stm32l0x1/stm32l0x1_pac/src/tim22/or.rs", "rank": 81, "score": 94.72445113417835 }, { "content": "#[doc = \"Reader of register OR\"]\n\npub type R = crate::R<u32, super::OR>;\n\n#[doc = \"Writer for register OR\"]\n\npub type W = crate::W<u32, super::OR>;\n\n#[doc = \"Register OR `reset()`'s with value 0\"]\n\nimpl crate::ResetValue for super::OR {\n\n type Type = u32;\n\n #[inline(always)]\n\n fn reset_value() -> Self::Type {\n\n 0\n\n }\n\n}\n\n#[doc = \"Reader of field `ETR_RMP`\"]\n\npub type ETR_RMP_R = crate::R<u8, u8>;\n\n#[doc = \"Write proxy for field `ETR_RMP`\"]\n\npub struct ETR_RMP_W<'a> {\n\n w: &'a mut W,\n\n}\n\nimpl<'a> ETR_RMP_W<'a> {\n\n #[doc = r\"Writes raw bits to the field\"]\n", "file_path": "07-rust/stm32l0x1/stm32l0x1_pac/src/tim2/or.rs", "rank": 82, "score": 94.72445113417837 }, { "content": "#[doc = \"Reader of register OR\"]\n\npub type R = crate::R<u32, super::OR>;\n\n#[doc = \"Writer for register OR\"]\n\npub type W = crate::W<u32, super::OR>;\n\n#[doc = \"Register OR `reset()`'s with value 0\"]\n\nimpl crate::ResetValue for super::OR {\n\n type Type = u32;\n\n #[inline(always)]\n\n fn reset_value() -> Self::Type {\n\n 0\n\n }\n\n}\n\n#[doc = \"Reader of field `IT4_RMP`\"]\n\npub type IT4_RMP_R = crate::R<u8, u8>;\n\n#[doc = \"Write proxy for field `IT4_RMP`\"]\n\npub struct IT4_RMP_W<'a> {\n\n w: &'a mut W,\n\n}\n\nimpl<'a> IT4_RMP_W<'a> {\n\n #[doc = r\"Writes raw bits to the field\"]\n", "file_path": "07-rust/stm32f446/stm32f446_pac/src/tim5/or.rs", "rank": 83, "score": 94.72445113417837 }, { "content": "#[doc = \"Reader of register CR1\"]\n\npub type R = crate::R<u32, super::CR1>;\n\n#[doc = \"Writer for register CR1\"]\n\npub type W = crate::W<u32, super::CR1>;\n\n#[doc = \"Register CR1 `reset()`'s with value 0\"]\n\nimpl crate::ResetValue for super::CR1 {\n\n type Type = u32;\n\n #[inline(always)]\n\n fn reset_value() -> Self::Type {\n\n 0\n\n }\n\n}\n\n#[doc = \"Reader of field `CKD`\"]\n\npub type CKD_R = crate::R<u8, u8>;\n\n#[doc = \"Write proxy for field `CKD`\"]\n\npub struct CKD_W<'a> {\n\n w: &'a mut W,\n\n}\n\nimpl<'a> CKD_W<'a> {\n\n #[doc = r\"Writes raw bits to the field\"]\n", "file_path": "07-rust/stm32f446/stm32f446_pac/src/tim5/cr1.rs", "rank": 85, "score": 94.28899823669879 }, { "content": "#[doc = \"Reader of register EP7R\"]\n\npub type R = crate::R<u32, super::EP7R>;\n\n#[doc = \"Writer for register EP7R\"]\n\npub type W = crate::W<u32, super::EP7R>;\n\n#[doc = \"Register EP7R `reset()`'s with value 0\"]\n\nimpl crate::ResetValue for super::EP7R {\n\n type Type = u32;\n\n #[inline(always)]\n\n fn reset_value() -> Self::Type {\n\n 0\n\n }\n\n}\n\n#[doc = \"Reader of field `EA`\"]\n\npub type EA_R = crate::R<u8, u8>;\n\n#[doc = \"Write proxy for field `EA`\"]\n\npub struct EA_W<'a> {\n\n w: &'a mut W,\n\n}\n\nimpl<'a> EA_W<'a> {\n\n #[doc = r\"Writes raw bits to the field\"]\n", "file_path": "07-rust/stm32f0x1/stm32f0x1_pac/src/usb/ep7r.rs", "rank": 86, "score": 94.28899823669879 }, { "content": "#[doc = \"Reader of register CR1\"]\n\npub type R = crate::R<u32, super::CR1>;\n\n#[doc = \"Writer for register CR1\"]\n\npub type W = crate::W<u32, super::CR1>;\n\n#[doc = \"Register CR1 `reset()`'s with value 0\"]\n\nimpl crate::ResetValue for super::CR1 {\n\n type Type = u32;\n\n #[inline(always)]\n\n fn reset_value() -> Self::Type {\n\n 0\n\n }\n\n}\n\n#[doc = \"Reader of field `CKD`\"]\n\npub type CKD_R = crate::R<u8, u8>;\n\n#[doc = \"Write proxy for field `CKD`\"]\n\npub struct CKD_W<'a> {\n\n w: &'a mut W,\n\n}\n\nimpl<'a> CKD_W<'a> {\n\n #[doc = r\"Writes raw bits to the field\"]\n", "file_path": "07-rust/stm32f446/stm32f446_pac/src/tim3/cr1.rs", "rank": 87, "score": 94.2889982366988 }, { "content": "#[doc = \"Reader of register DCR\"]\n\npub type R = crate::R<u32, super::DCR>;\n\n#[doc = \"Writer for register DCR\"]\n\npub type W = crate::W<u32, super::DCR>;\n\n#[doc = \"Register DCR `reset()`'s with value 0\"]\n\nimpl crate::ResetValue for super::DCR {\n\n type Type = u32;\n\n #[inline(always)]\n\n fn reset_value() -> Self::Type {\n\n 0\n\n }\n\n}\n\n#[doc = \"Reader of field `DBL`\"]\n\npub type DBL_R = crate::R<u8, u8>;\n\n#[doc = \"Write proxy for field `DBL`\"]\n\npub struct DBL_W<'a> {\n\n w: &'a mut W,\n\n}\n\nimpl<'a> DBL_W<'a> {\n\n #[doc = r\"Writes raw bits to the field\"]\n", "file_path": "07-rust/stm32f446/stm32f446_pac/src/tim1/dcr.rs", "rank": 88, "score": 94.28899823669879 }, { "content": "#[doc = \"Reader of register OSPEEDR\"]\n\npub type R = crate::R<u32, super::OSPEEDR>;\n\n#[doc = \"Writer for register OSPEEDR\"]\n\npub type W = crate::W<u32, super::OSPEEDR>;\n\n#[doc = \"Register OSPEEDR `reset()`'s with value 0\"]\n\nimpl crate::ResetValue for super::OSPEEDR {\n\n type Type = u32;\n\n #[inline(always)]\n\n fn reset_value() -> Self::Type {\n\n 0\n\n }\n\n}\n\n#[doc = \"Reader of field `OSPEED15`\"]\n\npub type OSPEED15_R = crate::R<u8, u8>;\n\n#[doc = \"Write proxy for field `OSPEED15`\"]\n\npub struct OSPEED15_W<'a> {\n\n w: &'a mut W,\n\n}\n\nimpl<'a> OSPEED15_W<'a> {\n\n #[doc = r\"Writes raw bits to the field\"]\n", "file_path": "07-rust/stm32l0x1/stm32l0x1_pac/src/gpioa/ospeedr.rs", "rank": 89, "score": 94.28899823669879 }, { "content": "#[doc = \"Reader of register PUPDR\"]\n\npub type R = crate::R<u32, super::PUPDR>;\n\n#[doc = \"Writer for register PUPDR\"]\n\npub type W = crate::W<u32, super::PUPDR>;\n\n#[doc = \"Register PUPDR `reset()`'s with value 0\"]\n\nimpl crate::ResetValue for super::PUPDR {\n\n type Type = u32;\n\n #[inline(always)]\n\n fn reset_value() -> Self::Type {\n\n 0\n\n }\n\n}\n\n#[doc = \"Reader of field `PUPDR15`\"]\n\npub type PUPDR15_R = crate::R<u8, u8>;\n\n#[doc = \"Write proxy for field `PUPDR15`\"]\n\npub struct PUPDR15_W<'a> {\n\n w: &'a mut W,\n\n}\n\nimpl<'a> PUPDR15_W<'a> {\n\n #[doc = r\"Writes raw bits to the field\"]\n", "file_path": "07-rust/stm32f446/stm32f446_pac/src/gpioh/pupdr.rs", "rank": 90, "score": 94.28899823669877 }, { "content": "#[doc = \"Reader of register RTOR\"]\n\npub type R = crate::R<u32, super::RTOR>;\n\n#[doc = \"Writer for register RTOR\"]\n\npub type W = crate::W<u32, super::RTOR>;\n\n#[doc = \"Register RTOR `reset()`'s with value 0\"]\n\nimpl crate::ResetValue for super::RTOR {\n\n type Type = u32;\n\n #[inline(always)]\n\n fn reset_value() -> Self::Type {\n\n 0\n\n }\n\n}\n\n#[doc = \"Reader of field `BLEN`\"]\n\npub type BLEN_R = crate::R<u8, u8>;\n\n#[doc = \"Write proxy for field `BLEN`\"]\n\npub struct BLEN_W<'a> {\n\n w: &'a mut W,\n\n}\n\nimpl<'a> BLEN_W<'a> {\n\n #[doc = r\"Writes raw bits to the field\"]\n", "file_path": "07-rust/stm32f0x1/stm32f0x1_pac/src/usart1/rtor.rs", "rank": 91, "score": 94.28899823669877 }, { "content": "#[doc = \"Reader of register CR1\"]\n\npub type R = crate::R<u32, super::CR1>;\n\n#[doc = \"Writer for register CR1\"]\n\npub type W = crate::W<u32, super::CR1>;\n\n#[doc = \"Register CR1 `reset()`'s with value 0\"]\n\nimpl crate::ResetValue for super::CR1 {\n\n type Type = u32;\n\n #[inline(always)]\n\n fn reset_value() -> Self::Type {\n\n 0\n\n }\n\n}\n\n#[doc = \"Reader of field `CKD`\"]\n\npub type CKD_R = crate::R<u8, u8>;\n\n#[doc = \"Write proxy for field `CKD`\"]\n\npub struct CKD_W<'a> {\n\n w: &'a mut W,\n\n}\n\nimpl<'a> CKD_W<'a> {\n\n #[doc = r\"Writes raw bits to the field\"]\n", "file_path": "07-rust/stm32f0x1/stm32f0x1_pac/src/tim2/cr1.rs", "rank": 92, "score": 94.28899823669879 }, { "content": "#[doc = \"Reader of register ACR2\"]\n\npub type R = crate::R<u32, super::ACR2>;\n\n#[doc = \"Writer for register ACR2\"]\n\npub type W = crate::W<u32, super::ACR2>;\n\n#[doc = \"Register ACR2 `reset()`'s with value 0\"]\n\nimpl crate::ResetValue for super::ACR2 {\n\n type Type = u32;\n\n #[inline(always)]\n\n fn reset_value() -> Self::Type {\n\n 0\n\n }\n\n}\n\n#[doc = \"Reader of field `COMP`\"]\n\npub type COMP_R = crate::R<u8, u8>;\n\n#[doc = \"Write proxy for field `COMP`\"]\n\npub struct COMP_W<'a> {\n\n w: &'a mut W,\n\n}\n\nimpl<'a> COMP_W<'a> {\n\n #[doc = r\"Writes raw bits to the field\"]\n", "file_path": "07-rust/stm32f446/stm32f446_pac/src/sai1/acr2.rs", "rank": 93, "score": 94.28899823669879 }, { "content": "#[doc = \"Reader of register DCR\"]\n\npub type R = crate::R<u32, super::DCR>;\n\n#[doc = \"Writer for register DCR\"]\n\npub type W = crate::W<u32, super::DCR>;\n\n#[doc = \"Register DCR `reset()`'s with value 0\"]\n\nimpl crate::ResetValue for super::DCR {\n\n type Type = u32;\n\n #[inline(always)]\n\n fn reset_value() -> Self::Type {\n\n 0\n\n }\n\n}\n\n#[doc = \"Reader of field `DBL`\"]\n\npub type DBL_R = crate::R<u8, u8>;\n\n#[doc = \"Write proxy for field `DBL`\"]\n\npub struct DBL_W<'a> {\n\n w: &'a mut W,\n\n}\n\nimpl<'a> DBL_W<'a> {\n\n #[doc = r\"Writes raw bits to the field\"]\n", "file_path": "07-rust/stm32f446/stm32f446_pac/src/tim2/dcr.rs", "rank": 94, "score": 94.28899823669879 }, { "content": "#[doc = \"Reader of register EP6R\"]\n\npub type R = crate::R<u32, super::EP6R>;\n\n#[doc = \"Writer for register EP6R\"]\n\npub type W = crate::W<u32, super::EP6R>;\n\n#[doc = \"Register EP6R `reset()`'s with value 0\"]\n\nimpl crate::ResetValue for super::EP6R {\n\n type Type = u32;\n\n #[inline(always)]\n\n fn reset_value() -> Self::Type {\n\n 0\n\n }\n\n}\n\n#[doc = \"Reader of field `EA`\"]\n\npub type EA_R = crate::R<u8, u8>;\n\n#[doc = \"Write proxy for field `EA`\"]\n\npub struct EA_W<'a> {\n\n w: &'a mut W,\n\n}\n\nimpl<'a> EA_W<'a> {\n\n #[doc = r\"Writes raw bits to the field\"]\n", "file_path": "07-rust/stm32f0x1/stm32f0x1_pac/src/usb/ep6r.rs", "rank": 95, "score": 94.28899823669879 }, { "content": "#[doc = \"Reader of register OAR2\"]\n\npub type R = crate::R<u32, super::OAR2>;\n\n#[doc = \"Writer for register OAR2\"]\n\npub type W = crate::W<u32, super::OAR2>;\n\n#[doc = \"Register OAR2 `reset()`'s with value 0\"]\n\nimpl crate::ResetValue for super::OAR2 {\n\n type Type = u32;\n\n #[inline(always)]\n\n fn reset_value() -> Self::Type {\n\n 0\n\n }\n\n}\n\n#[doc = \"Reader of field `ADD2`\"]\n\npub type ADD2_R = crate::R<u8, u8>;\n\n#[doc = \"Write proxy for field `ADD2`\"]\n\npub struct ADD2_W<'a> {\n\n w: &'a mut W,\n\n}\n\nimpl<'a> ADD2_W<'a> {\n\n #[doc = r\"Writes raw bits to the field\"]\n", "file_path": "07-rust/stm32f446/stm32f446_pac/src/i2c3/oar2.rs", "rank": 96, "score": 94.28899823669879 }, { "content": "#[doc = \"Reader of register CFGR1\"]\n\npub type R = crate::R<u32, super::CFGR1>;\n\n#[doc = \"Writer for register CFGR1\"]\n\npub type W = crate::W<u32, super::CFGR1>;\n\n#[doc = \"Register CFGR1 `reset()`'s with value 0\"]\n\nimpl crate::ResetValue for super::CFGR1 {\n\n type Type = u32;\n\n #[inline(always)]\n\n fn reset_value() -> Self::Type {\n\n 0\n\n }\n\n}\n\n#[doc = \"Reader of field `AWDCH`\"]\n\npub type AWDCH_R = crate::R<u8, u8>;\n\n#[doc = \"Write proxy for field `AWDCH`\"]\n\npub struct AWDCH_W<'a> {\n\n w: &'a mut W,\n\n}\n\nimpl<'a> AWDCH_W<'a> {\n\n #[doc = r\"Writes raw bits to the field\"]\n", "file_path": "07-rust/stm32f0x1/stm32f0x1_pac/src/adc/cfgr1.rs", "rank": 97, "score": 94.2889982366988 }, { "content": "#[doc = \"Reader of register CFGR1\"]\n\npub type R = crate::R<u32, super::CFGR1>;\n\n#[doc = \"Writer for register CFGR1\"]\n\npub type W = crate::W<u32, super::CFGR1>;\n\n#[doc = \"Register CFGR1 `reset()`'s with value 0\"]\n\nimpl crate::ResetValue for super::CFGR1 {\n\n type Type = u32;\n\n #[inline(always)]\n\n fn reset_value() -> Self::Type {\n\n 0\n\n }\n\n}\n\n#[doc = \"Reader of field `AWDCH`\"]\n\npub type AWDCH_R = crate::R<u8, u8>;\n\n#[doc = \"Write proxy for field `AWDCH`\"]\n\npub struct AWDCH_W<'a> {\n\n w: &'a mut W,\n\n}\n\nimpl<'a> AWDCH_W<'a> {\n\n #[doc = r\"Writes raw bits to the field\"]\n", "file_path": "07-rust/stm32l0x1/stm32l0x1_pac/src/adc/cfgr1.rs", "rank": 98, "score": 94.28899823669879 }, { "content": "#[doc = \"Reader of register ESCR\"]\n\npub type R = crate::R<u32, super::ESCR>;\n\n#[doc = \"Writer for register ESCR\"]\n\npub type W = crate::W<u32, super::ESCR>;\n\n#[doc = \"Register ESCR `reset()`'s with value 0\"]\n\nimpl crate::ResetValue for super::ESCR {\n\n type Type = u32;\n\n #[inline(always)]\n\n fn reset_value() -> Self::Type {\n\n 0\n\n }\n\n}\n\n#[doc = \"Reader of field `FEC`\"]\n\npub type FEC_R = crate::R<u8, u8>;\n\n#[doc = \"Write proxy for field `FEC`\"]\n\npub struct FEC_W<'a> {\n\n w: &'a mut W,\n\n}\n\nimpl<'a> FEC_W<'a> {\n\n #[doc = r\"Writes raw bits to the field\"]\n", "file_path": "07-rust/stm32f446/stm32f446_pac/src/dcmi/escr.rs", "rank": 99, "score": 94.28899823669877 } ]
Rust
riscv/src/mmu.rs
plorefice/rv6
adb7e28994b08b86596d2bdfbfee0ca5832e3d21
use core::{ fmt, slice::{Iter, IterMut}, }; use bitflags::bitflags; use kmm::{allocator::FrameAllocator, Align}; use crate::{ addr::{PAGE_SHIFT, PAGE_SIZE}, PhysAddr, VirtAddr, }; #[cfg(feature = "sv39")] const PTE_PPN_MASK: u64 = 0x3ff_ffff; #[cfg(feature = "sv48")] const PTE_PPN_MASK: u64 = 0xfff_ffff_ffff; const PTE_PPN_OFFSET: u64 = 10; #[cfg(feature = "sv39")] const PAGE_LEVELS: usize = 3; #[cfg(feature = "sv48")] const PAGE_LEVELS: usize = 4; bitflags! { pub struct EntryFlags: u64 { const VALID = 1 << 0; const READ = 1 << 1; const WRITE = 1 << 2; const EXEC = 1 << 3; const USER = 1 << 4; const GLOBAL = 1 << 5; const ACCESS = 1 << 6; const DIRTY = 1 << 7; const RW = Self::READ.bits | Self::WRITE.bits; const RX = Self::READ.bits | Self::EXEC.bits; const RWX = Self::READ.bits | Self::WRITE.bits | Self::EXEC.bits; const RWXUG = Self::RWX.bits | Self::USER.bits | Self::GLOBAL.bits; const ALL = 0xf; } } #[derive(Debug)] pub struct PageTable { entries: [Entry; 512], } impl PageTable { pub fn clear(&mut self) { for entry in &mut self.entries { entry.clear(); } } pub fn get_entry(&self, i: usize) -> Option<&Entry> { self.entries.get(i) } pub fn get_entry_mut(&mut self, i: usize) -> Option<&mut Entry> { self.entries.get_mut(i) } pub fn iter(&self) -> Iter<'_, Entry> { self.entries.iter() } pub fn iter_mut(&mut self) -> IterMut<'_, Entry> { self.entries.iter_mut() } } impl fmt::Display for PageTable { fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { for (i, e) in self.entries.iter().enumerate() { if e.is_valid() { writeln!(f, "{:>3}: {}", i, e)?; } } Ok(()) } } #[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)] pub struct Entry { inner: EntryFlags, } impl Entry { pub fn is_valid(&self) -> bool { self.inner.contains(EntryFlags::VALID) } pub fn is_read(&self) -> bool { self.inner.contains(EntryFlags::READ) } pub fn is_write(&self) -> bool { self.inner.contains(EntryFlags::WRITE) } pub fn is_exec(&self) -> bool { self.inner.contains(EntryFlags::EXEC) } pub fn is_user(&self) -> bool { self.inner.contains(EntryFlags::USER) } pub fn is_global(&self) -> bool { self.inner.contains(EntryFlags::GLOBAL) } pub fn is_accessed(&self) -> bool { self.inner.contains(EntryFlags::ACCESS) } pub fn is_dirty(&self) -> bool { self.inner.contains(EntryFlags::DIRTY) } pub fn is_leaf(&self) -> bool { self.inner .intersects(EntryFlags::READ | EntryFlags::WRITE | EntryFlags::EXEC) } pub fn flags(&self) -> EntryFlags { self.inner & EntryFlags::ALL } pub fn clear(&mut self) { self.inner.bits = 0; } pub fn set_flags(&mut self, flags: EntryFlags) { self.inner &= !EntryFlags::ALL; self.inner |= flags; } pub fn get_ppn(&self) -> u64 { (self.inner.bits() >> PTE_PPN_OFFSET) & PTE_PPN_MASK } pub fn set_ppn(&mut self, ppn: u64) { self.inner.bits &= !(PTE_PPN_MASK << PTE_PPN_OFFSET); self.inner.bits |= (ppn & PTE_PPN_MASK) << PTE_PPN_OFFSET; } } impl fmt::Display for Entry { fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { write!(f, "phy: 0x{:016x} ", self.get_ppn() << PTE_PPN_OFFSET)?; write!( f, "{} {} {} {} {} {} {}", if self.is_read() { 'R' } else { ' ' }, if self.is_write() { 'W' } else { ' ' }, if self.is_exec() { 'X' } else { ' ' }, if self.is_user() { 'U' } else { ' ' }, if self.is_global() { 'G' } else { ' ' }, if self.is_accessed() { 'A' } else { ' ' }, if self.is_dirty() { 'D' } else { ' ' }, ) } } #[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash)] pub enum PageSize { Kb, Mb, Gb, #[cfg(feature = "sv48")] Tb, } impl PageSize { fn to_table_level(self) -> usize { match self { PageSize::Kb => 0, PageSize::Mb => 1, PageSize::Gb => 2, #[cfg(feature = "sv48")] PageSize::Tb => 3, } } } #[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)] pub enum MapError { AlreadyMapped, AllocationFailed, } #[derive(Debug)] pub struct OffsetPageMapper<'a> { rpt: &'a mut PageTable, phys_offset: VirtAddr, } impl<'a> OffsetPageMapper<'a> { pub unsafe fn new(rpt: &'a mut PageTable, phys_offset: VirtAddr) -> Self { Self { rpt, phys_offset } } pub unsafe fn map<A>( &mut self, vaddr: VirtAddr, paddr: PhysAddr, page_size: PageSize, mut flags: EntryFlags, frame_allocator: &mut A, ) -> Result<(), MapError> where A: FrameAllocator<PhysAddr, PAGE_SIZE>, { #[cfg(feature = "sv39")] let vpn = [vaddr.vpn0(), vaddr.vpn1(), vaddr.vpn2()]; #[cfg(feature = "sv48")] let vpn = [vaddr.vpn0(), vaddr.vpn1(), vaddr.vpn2(), vaddr.vpn3()]; let mut pte = self.rpt.get_entry_mut(vpn[PAGE_LEVELS - 1]).unwrap(); for i in (page_size.to_table_level()..PAGE_LEVELS - 1).rev() { let table_paddr = if !pte.is_valid() { let new_table_addr = unsafe { frame_allocator.alloc(1) }.ok_or(MapError::AllocationFailed)?; pte.clear(); pte.set_flags(EntryFlags::VALID); pte.set_ppn(new_table_addr.page_index()); new_table_addr } else { PhysAddr::new(pte.get_ppn() << PAGE_SHIFT) }; let table = unsafe { self.phys_to_virt(table_paddr) .as_mut_ptr::<PageTable>() .as_mut() .unwrap() }; pte = table.get_entry_mut(vpn[i]).unwrap(); } flags &= EntryFlags::RWXUG; if pte.is_valid() && pte.flags() & EntryFlags::RWXUG != flags { return Err(MapError::AlreadyMapped); } pte.set_flags(flags | EntryFlags::VALID); pte.set_ppn(paddr.page_index()); Ok(()) } pub unsafe fn identity_map_range<A>( &mut self, start: PhysAddr, end: PhysAddr, flags: EntryFlags, frame_allocator: &mut A, ) -> Result<(), MapError> where A: FrameAllocator<PhysAddr, PAGE_SIZE>, { let start = start.align_down(PAGE_SIZE); let end = end.align_up(PAGE_SIZE); let num_pages = u64::from(end - start) >> PAGE_SHIFT; for i in 0..num_pages { let addr = start + (i << PAGE_SHIFT); unsafe { self.map( VirtAddr::new(u64::from(addr) as usize), addr, PageSize::Kb, flags, frame_allocator, )?; } } Ok(()) } pub fn phys_to_virt(&self, paddr: PhysAddr) -> VirtAddr { VirtAddr::new(paddr.data() as usize) + self.phys_offset } pub fn virt_to_phys(&self, vaddr: VirtAddr) -> Option<PhysAddr> { #[cfg(feature = "sv39")] let vpn = [ (vaddr.data() >> 12) & 0x1ff, (vaddr.data() >> 21) & 0x1ff, (vaddr.data() >> 30) & 0x1ff, ]; #[cfg(feature = "sv48")] let vpn = [ (vaddr.data() >> 12) & 0x1ff, (vaddr.data() >> 21) & 0x1ff, (vaddr.data() >> 30) & 0x1ff, (vaddr.data() >> 39) & 0x1ff, ]; let mut table = &*self.rpt; for i in (0..PAGE_LEVELS).rev() { let pte = table.get_entry(vpn[i]).unwrap(); if !pte.is_valid() { break; } if pte.is_leaf() { let mut ppn = pte.get_ppn(); for (lvl, vpn) in vpn.iter().enumerate().take(i) { ppn |= (vpn << (lvl * 9)) as u64; } return Some(PhysAddr::new(ppn << PAGE_SHIFT) + vaddr.page_offset() as u64); } table = unsafe { self.phys_to_virt(PhysAddr::from_ppn(pte.get_ppn())) .as_ptr::<PageTable>() .as_ref() .unwrap() }; } None } }
use core::{ fmt, slice::{Iter, IterMut}, }; use bitflags::bitflags; use kmm::{allocator::FrameAllocator, Align}; use crate::{ addr::{PAGE_SHIFT, PAGE_SIZE}, PhysAddr, VirtAddr, }; #[cfg(feature = "sv39")] const PTE_PPN_MASK: u64 = 0x3ff_ffff; #[cfg(feature = "sv48")] const PTE_PPN_MASK: u64 = 0xfff_ffff_ffff; const PTE_PPN_OFFSET: u64 = 10; #[cfg(feature = "sv39")] const PAGE_LEVELS: usize = 3; #[cfg(feature = "sv48")] const PAGE_LEVELS: usize = 4; bitflags! { pub struct EntryFlags: u64 { const VALID = 1 << 0; const READ = 1 << 1; const WRITE = 1 << 2; const EXEC = 1 << 3; const USER = 1 << 4; const GLOBAL = 1 << 5; const ACCESS = 1 << 6; const DIRTY = 1 << 7; const RW = Self::READ.bits | Self::WRITE.bits; const RX = Self::READ.bits | Self::EXEC.bits; const RWX = Self::READ.bits | Self::WRITE.bits | Self::EXEC.bits; const RWXUG = Self::RWX.bits | Self::USER.bits | Self::GLOBAL.bits; const ALL = 0xf; } } #[derive(Debug)] pub struct PageTable { entries: [Entry; 512], } impl PageTable { pub fn clear(&mut self) { for entry in &mut self.entries { entry.clear(); } } pub fn get_entry(&self, i: usize) -> Option<&Entry> { self.entries.get(i) } pub fn get_entry_mut(&mut self, i: usize) -> Option<&mut Entry> { self.entries.get_mut(i) } pub fn iter(&self) -> Iter<'_, Entry> { self.entries.iter() } pub fn iter_mut(&mut self) -> IterMut<'_, Entry> { self.entries.iter_mut() } } impl fmt::Display for PageTable { fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { for (i, e) in self.entries.iter().enumerate() { if e.is_valid() { writeln!(f, "{:>3}: {}", i, e)?; } } Ok(()) } } #[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)] pub struct Entry { inner: EntryFlags, } impl Entry { pub fn is_valid(&self) -> bool { self.inner.contains(EntryFlags::VALID) } pub fn is_read(&self) -> bool { self.inner.contains(EntryFlags::READ) } pub fn is_write(&self) -> bool { self.inner.contains(EntryFlags::WRITE) } pub fn is_exec(&self) -> bool { self.inner.contains(EntryFlags::EXEC) } pub fn is_user(&self) -> bool { self.inner.contains(EntryFlags::USER) } pub fn is_global(&self) -> bool { self.inner.contains(EntryFlags::GLOBAL) } pub fn is_accessed(&self) -> bool { self.inner.contains(EntryFlags::ACCESS) } pub fn is_dirty(&self) -> bool { self.inner.contains(EntryFlags::DIRTY) } pub fn is_leaf(&self) -> bool { self.inner .intersects(EntryFlags::READ | EntryFlags::WRITE | EntryFlags::EXEC) } pub fn flags(&self) -> EntryFlags { self.inner & EntryFlags::ALL } pub fn clear(&mut self) { self.inner.bits = 0; } pub fn set_flags(&mut self, flags: EntryFlags) { self.inner &= !EntryFlags::ALL; self.inner |= flags; } pub fn get_ppn(&self) -> u64 { (self.inner.bits() >> PTE_PPN_OFFSET) & PTE_PPN_MASK } pub fn set_ppn(&mut self, ppn: u64) { self.inner.bits &= !(PTE_PPN_MASK << PTE_PPN_OFFSET); self.inner.bits |= (ppn & PTE_PPN_MASK) << PTE_PPN_OFFSET; } } impl fmt::Display for Entry { fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { write!(f, "phy: 0x{:016x} ", self.get_ppn() << PTE_PPN_OFFSET)?; write!( f, "{} {} {} {} {} {} {}", if self.is_read() { 'R' } else { ' ' }, if self.is_write() { 'W' } else { ' ' }, if self.is_exec() { 'X' } else { ' ' }, if self.is_user() { 'U' } else { ' ' }, if self.is_global() { 'G' } else { ' ' }, if self.is_accessed() { 'A' } else { ' ' }, if self.is_dirty() { 'D' } else { ' ' }, ) } } #[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash)] pub enum PageSize { Kb, Mb, Gb, #[cfg(feature = "sv48")] Tb, } impl PageSize { fn to_table_level(self) -> usize { match self { PageSize::Kb => 0, PageSize::Mb => 1, PageSize::Gb => 2, #[cfg(feature = "sv48")] PageSize::Tb => 3, } } } #[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)] pub enum MapError { AlreadyMapped, AllocationFailed, } #[derive(Debug)] pub struct OffsetPageMapper<'a> { rpt: &'a mut PageTable, phys_offset: VirtAddr, } impl<'a> OffsetPageMapper<'a> { pub unsafe fn new(rpt: &'a mut PageTable, phys_offset: VirtAddr) -> Self { Self { rpt, phys_offset } } pub unsafe fn map<A>( &mut self, vaddr: VirtAddr, paddr: PhysAddr, page_size: PageSize, mut flags: EntryFlags, frame_allocator: &mut A, ) -> Result<(), MapError> where A: FrameAllocator<PhysAddr, PAGE_SIZE>, { #[cfg(feature = "sv39")] let vpn = [vaddr.vpn0(), vaddr.vpn1(), vaddr.vpn2()]; #[cfg(feature = "sv48")] let vpn = [vaddr.vpn0(), vaddr.vpn1(), vaddr.vpn2(), vaddr.vpn3()]; let mut pte = self.rpt.get_entry_mut(vpn[PAGE_LEVELS - 1]).unwrap(); for i in (page_size.to_table_level()..PAGE_LEVELS - 1).rev() { let table_paddr = if !pte.is_valid() { let new_table_addr = unsafe { frame_allocator.alloc(1) }.ok_or(MapError::AllocationFailed)?; pte.clear(); pte.set_flags(EntryFlags::VALID); pte.set_ppn(new_table_addr.page_index()); new_table_addr } else { PhysAddr::new(pte.get_ppn() << PAGE_SHIFT) }; let table = unsafe { self.phys_to_virt(table_paddr) .as_mut_ptr::<PageTable>() .as_mut() .unwrap() }; pte = table.get_entry_mut(vpn[i]).unwrap(); } flags &= EntryFlags::RWXUG; if pte.is_valid() && pte.flags() & EntryFlags::RWXUG != flags { return Err(MapError::AlreadyMappe
pub unsafe fn identity_map_range<A>( &mut self, start: PhysAddr, end: PhysAddr, flags: EntryFlags, frame_allocator: &mut A, ) -> Result<(), MapError> where A: FrameAllocator<PhysAddr, PAGE_SIZE>, { let start = start.align_down(PAGE_SIZE); let end = end.align_up(PAGE_SIZE); let num_pages = u64::from(end - start) >> PAGE_SHIFT; for i in 0..num_pages { let addr = start + (i << PAGE_SHIFT); unsafe { self.map( VirtAddr::new(u64::from(addr) as usize), addr, PageSize::Kb, flags, frame_allocator, )?; } } Ok(()) } pub fn phys_to_virt(&self, paddr: PhysAddr) -> VirtAddr { VirtAddr::new(paddr.data() as usize) + self.phys_offset } pub fn virt_to_phys(&self, vaddr: VirtAddr) -> Option<PhysAddr> { #[cfg(feature = "sv39")] let vpn = [ (vaddr.data() >> 12) & 0x1ff, (vaddr.data() >> 21) & 0x1ff, (vaddr.data() >> 30) & 0x1ff, ]; #[cfg(feature = "sv48")] let vpn = [ (vaddr.data() >> 12) & 0x1ff, (vaddr.data() >> 21) & 0x1ff, (vaddr.data() >> 30) & 0x1ff, (vaddr.data() >> 39) & 0x1ff, ]; let mut table = &*self.rpt; for i in (0..PAGE_LEVELS).rev() { let pte = table.get_entry(vpn[i]).unwrap(); if !pte.is_valid() { break; } if pte.is_leaf() { let mut ppn = pte.get_ppn(); for (lvl, vpn) in vpn.iter().enumerate().take(i) { ppn |= (vpn << (lvl * 9)) as u64; } return Some(PhysAddr::new(ppn << PAGE_SHIFT) + vaddr.page_offset() as u64); } table = unsafe { self.phys_to_virt(PhysAddr::from_ppn(pte.get_ppn())) .as_ptr::<PageTable>() .as_ref() .unwrap() }; } None } }
d); } pte.set_flags(flags | EntryFlags::VALID); pte.set_ppn(paddr.page_index()); Ok(()) }
function_block-function_prefixed
[ { "content": "/// A physical memory address representable as an integer of type `U`.\n\npub trait PhysicalAddress<U>: Copy + Clone + Into<U> + AddressOps<U> {}\n\n\n", "file_path": "kmm/src/lib.rs", "rank": 0, "score": 142634.8631566231 }, { "content": "/// A trait for numeric types that can be aligned to a boundary.\n\npub trait Align<U> {\n\n /// Aligns address upwards to the specified bound.\n\n ///\n\n /// Returns the first address greater or equal than `addr` with alignment `align`.\n\n fn align_up(&self, align: U) -> Self;\n\n\n\n /// Aligns address downwards to the specified bound.\n\n ///\n\n /// Returns the first address lower or equal than `addr` with alignment `align`.\n\n fn align_down(&self, align: U) -> Self;\n\n\n\n /// Checks whether the address has the specified alignment.\n\n fn is_aligned(&self, align: U) -> bool;\n\n}\n", "file_path": "kmm/src/lib.rs", "rank": 1, "score": 134653.73908474375 }, { "content": "/// Returns the number of cycles elapsed since boot, in timebase units.\n\npub fn get_cycles() -> u64 {\n\n mmio::read_volatile(CLINT_BASE, CLINT_TIME_OFFSET)\n\n}\n\n\n", "file_path": "kernel/src/arch/riscv/time.rs", "rank": 2, "score": 119573.50406679367 }, { "content": "/// Reads a value of type `T` from location `base + offset` in memory.\n\npub fn read_volatile<T>(base: usize, offset: usize) -> T {\n\n let ptr = (base + offset) as *mut T;\n\n unsafe { ptr.read_volatile() }\n\n}\n", "file_path": "kernel/src/mm/mmio.rs", "rank": 3, "score": 112228.76212793995 }, { "content": "/// A trait for page-grained memory allocators.\n\npub trait FrameAllocator<A, const N: u64>\n\nwhere\n\n A: PhysicalAddress<u64>,\n\n{\n\n /// Allocates a memory section of `count` contiguous pages. If no countiguous section\n\n /// of the specified size can be allocated, `None` is returned.\n\n ///\n\n /// # Safety\n\n ///\n\n /// Low-level memory twiddling doesn't provide safety guarantees.\n\n unsafe fn alloc(&mut self, count: usize) -> Option<A>;\n\n\n\n /// Releases the allocated memory starting at the specified address back to the kernel.\n\n ///\n\n /// # Safety\n\n ///\n\n /// Low-level memory twiddling doesn't provide safety guarantees.\n\n unsafe fn free(&mut self, address: A);\n\n}\n\n\n", "file_path": "kmm/src/allocator/mod.rs", "rank": 4, "score": 112149.28288969176 }, { "content": "/// Schedules a timer interrupt to happend `interval` ticks in the future.\n\npub fn schedule_next_tick(interval: u64) {\n\n sbi::timer::set_timer(get_cycles() + interval).unwrap();\n\n}\n", "file_path": "kernel/src/arch/riscv/time.rs", "rank": 5, "score": 110869.19584477787 }, { "content": "/// Returns whether an address lies withing the kernel's `.text` section.\n\nfn is_kernel_text_address(pc: usize) -> bool {\n\n extern \"C\" {\n\n static __text_start: usize;\n\n static __text_end: usize;\n\n }\n\n\n\n unsafe {\n\n pc >= (&__text_start as *const _ as usize) && pc <= (&__text_end as *const _ as usize)\n\n }\n\n}\n\n\n", "file_path": "kernel/src/arch/riscv/stackframe.rs", "rank": 6, "score": 95708.68199398347 }, { "content": "/// Looks up a kernel symbol by address and returns its name and offset, or `None` if no symbol\n\n/// is found.\n\npub fn resolve_symbol(pc: usize) -> Option<(&'static str, usize)> {\n\n let markers = unsafe {\n\n assert!(!ksyms_markers.is_null());\n\n &*ptr::slice_from_raw_parts(ksyms_markers, get_symtab_len())\n\n };\n\n\n\n if let Some((i, base)) = lookup_symbol(pc) {\n\n let symbol_name_ptr = unsafe {\n\n assert!(!ksyms_names.is_null());\n\n &*ptr::slice_from_raw_parts(ksyms_names.add(markers[i]), markers[i + 1] - markers[i])\n\n };\n\n\n\n return Some((\n\n unsafe { str::from_utf8_unchecked(&*symbol_name_ptr) },\n\n pc - base,\n\n ));\n\n }\n\n\n\n None\n\n}\n\n\n", "file_path": "kernel/src/ksyms.rs", "rank": 7, "score": 93711.07195806276 }, { "content": "#[inline]\n\npub fn nop() {\n\n unsafe {\n\n asm!(\"nop\", options(nostack, nomem, preserves_flags));\n\n }\n\n}\n", "file_path": "riscv/src/instructions.rs", "rank": 8, "score": 88250.39853635755 }, { "content": "#[inline]\n\npub fn wfi() {\n\n unsafe {\n\n asm!(\"wfi\", options(nostack, nomem));\n\n }\n\n}\n\n\n\n/// Executes the `nop` instructions, which performs no operation (ie. does nothing).\n", "file_path": "riscv/src/instructions.rs", "rank": 9, "score": 88250.39853635755 }, { "content": "/// Operations common to physical address implementations.\n\npub trait AddressOps<U>:\n\n Align<U>\n\n + Add<Output = Self>\n\n + Sub<Output = Self>\n\n + Add<U, Output = Self>\n\n + Sub<U, Output = Self>\n\n + Sized\n\n{\n\n}\n\n\n", "file_path": "kmm/src/lib.rs", "rank": 10, "score": 86629.34737777169 }, { "content": "/// Configures the trap vector used to handle traps in S-mode.\n\npub fn init() {\n\n extern \"C\" {\n\n // Defined in trap.S\n\n fn trap_entry();\n\n }\n\n\n\n // Configure trap vector to point to `trap_entry`\n\n Stvec::write(trap_entry as *const () as u64);\n\n\n\n // Enable interrupts\n\n Sie::set(SiFlags::SSIE | SiFlags::STIE | SiFlags::SEIE);\n\n unsafe { Sstatus::set(SstatusFlags::SIE) };\n\n}\n", "file_path": "kernel/src/arch/riscv/trap.rs", "rank": 11, "score": 83720.05736551604 }, { "content": "/// Halts execution on the current hart forever.\n\npub fn halt() -> ! {\n\n // Disable all interrupts.\n\n unsafe { Sstatus::clear(SstatusFlags::SIE) };\n\n Sie::clear(SiFlags::SSIE | SiFlags::STIE | SiFlags::SEIE);\n\n Sip::write_raw(0);\n\n\n\n // Loop forever\n\n loop {\n\n wfi();\n\n }\n\n}\n", "file_path": "kernel/src/arch/riscv/mod.rs", "rank": 12, "score": 83716.75421578964 }, { "content": "pub fn init() {\n\n let version = base::get_spec_version();\n\n\n\n kprintln!(\n\n \"SBI specification v{}.{} detected\",\n\n version.major,\n\n version.minor,\n\n );\n\n\n\n if version.minor != 0x1 {\n\n kprintln!(\n\n \"SBI implementation ID=0x{:x} Version=0x{:x}\",\n\n base::get_impl_id().unwrap(),\n\n base::get_impl_version().unwrap(),\n\n );\n\n kprint!(\"SBI v0.2 detected extensions:\");\n\n if base::probe_extension(Extension::Timer).is_ok() {\n\n kprint!(\" TIMER\");\n\n }\n\n if base::probe_extension(Extension::Ipi).is_ok() {\n", "file_path": "kernel/src/arch/riscv/sbi.rs", "rank": 13, "score": 83716.75421578964 }, { "content": "/// Unwinds and prints the current stack frame.\n\n///\n\n/// # Panics\n\n///\n\n/// This function may panic if the stack frame is corrupted, eg. due to a misaligned frame pointer.\n\npub fn unwind_stack_frame() {\n\n kprintln!(\"Call trace:\");\n\n walk_stack_frame();\n\n}\n\n\n", "file_path": "kernel/src/arch/riscv/stackframe.rs", "rank": 14, "score": 79873.6161828861 }, { "content": "#[derive(Debug)]\n\nstruct BumpImpl {\n\n start: usize,\n\n end: usize,\n\n ptr: usize,\n\n allocated: usize,\n\n}\n\n\n\nimpl BumpAllocator {\n\n /// Creates a new bump allocator.\n\n ///\n\n /// # Panics\n\n ///\n\n /// Panics if `start > end`.\n\n pub const fn new(start: usize, end: usize) -> Self {\n\n assert!(start <= end);\n\n Self {\n\n inner: Mutex::new(BumpImpl {\n\n start,\n\n end,\n\n ptr: end,\n", "file_path": "rvalloc/src/lib.rs", "rank": 15, "score": 77751.64546012829 }, { "content": "#[derive(Debug, Clone, PartialEq, Eq)]\n\nstruct PageDescriptor {\n\n flags: PageFlags,\n\n}\n\n\n\n/// A frame allocator storing page state as a bitmap of page descriptors.\n\n#[derive(Debug)]\n\npub struct BitmapAllocator<A, const N: u64> {\n\n descriptors: &'static mut [PageDescriptor],\n\n base_addr: A,\n\n num_pages: u64,\n\n}\n\n\n\nimpl<A, const N: u64> BitmapAllocator<A, N>\n\nwhere\n\n A: PhysicalAddress<u64>,\n\n{\n\n /// Creates a new bitmap allocator taking ownership of the memory delimited by addresses\n\n /// `start` and `end`, and allocating pages of size `page_size`.\n\n ///\n\n /// Returns an `AllocationError` if any of the following conditions are not met:\n", "file_path": "kmm/src/allocator/bitmap.rs", "rank": 16, "score": 75355.59210245805 }, { "content": "/// Looks up an address and returns the symbol's index in the symbol table and its base address,\n\n/// or `None` if no symbol is found.\n\nfn lookup_symbol(pc: usize) -> Option<(usize, usize)> {\n\n let offsets = unsafe {\n\n assert!(!ksyms_offsets.is_null());\n\n &*ptr::slice_from_raw_parts(ksyms_offsets, get_symtab_len())\n\n };\n\n\n\n for (i, (&a, &b)) in offsets.iter().zip(offsets.iter().skip(1)).enumerate() {\n\n if (a..b).contains(&pc) {\n\n return Some((i, a));\n\n }\n\n }\n\n\n\n None\n\n}\n\n\n", "file_path": "kernel/src/ksyms.rs", "rank": 17, "score": 69894.88071168997 }, { "content": "fn print_dec(n: usize) {\n\n println!(\" .quad {}\", n);\n\n}\n\n\n", "file_path": "ksymsgen/src/main.rs", "rank": 18, "score": 66430.19054421141 }, { "content": "fn print_hex(n: usize) {\n\n println!(\" .quad 0x{:x}\", n);\n\n}\n\n\n", "file_path": "ksymsgen/src/main.rs", "rank": 19, "score": 66430.19054421141 }, { "content": "/// Returns the number of symbols in the table.\n\nfn get_symtab_len() -> usize {\n\n unsafe {\n\n assert!(!ksyms_num_syms.is_null());\n\n ksyms_num_syms.read() as usize\n\n }\n\n}\n", "file_path": "kernel/src/ksyms.rs", "rank": 20, "score": 65480.261858311394 }, { "content": "/// Traces the function to which PC belongs and displays both its name and the offset within.\n\nfn print_trace_address(pc: usize) {\n\n kprint!(\" [<{:016x}>] \", pc);\n\n if let Some((sym, off)) = ksyms::resolve_symbol(pc) {\n\n kprintln!(\"<{}>+0x{:x}\", sym, off);\n\n } else {\n\n kprintln!(\"?\");\n\n }\n\n}\n", "file_path": "kernel/src/arch/riscv/stackframe.rs", "rank": 21, "score": 58688.25583079895 }, { "content": "fn parse_nm_line(s: &str) -> Option<(usize, String)> {\n\n let mut fields = s.split_whitespace();\n\n\n\n let addr = usize::from_str_radix(fields.next().unwrap(), 16).unwrap();\n\n let kind = fields.next().unwrap();\n\n\n\n if kind == \"t\" || kind == \"T\" {\n\n Some((\n\n addr,\n\n format!(\"{:#}\", rustc_demangle::demangle(fields.next().unwrap())),\n\n ))\n\n } else {\n\n None\n\n }\n\n}\n\n\n", "file_path": "ksymsgen/src/main.rs", "rank": 22, "score": 55995.42368641176 }, { "content": "#[repr(C, packed)]\n\nstruct RegisterBlock {\n\n pub rthr: RW<u8>,\n\n pub ier: RW<u8>,\n\n pub isfcr: RO<u8>,\n\n pub lcr: RW<u8>,\n\n pub mcr: RW<u8>,\n\n pub lsr: RO<u8>,\n\n pub msr: RO<u8>,\n\n pub spr: RW<u8>,\n\n}\n\n\n\nimpl Ns16550 {\n\n /// Creates a new 16550 UART mapping to the given address.\n\n pub const fn new(addr: usize) -> Self {\n\n Self {\n\n p: unsafe { &mut *(addr as *mut RegisterBlock) },\n\n }\n\n }\n\n\n\n /// Writes a single byte to the serial interface.\n", "file_path": "kernel/src/drivers/ns16550.rs", "rank": 23, "score": 48524.12836102544 }, { "content": "#[repr(C, packed)]\n\nstruct RegisterBlock {\n\n pub reg: RW<u32>,\n\n}\n\n\n\nimpl Syscon {\n\n /// Creates a new system controller mapped at the given address.\n\n pub const fn new(addr: usize) -> Self {\n\n Self {\n\n p: unsafe { &mut *(addr as *mut RegisterBlock) },\n\n }\n\n }\n\n\n\n /// Sends a shutdown signal to the system controller with the given exit code.\n\n pub fn poweroff(&mut self, code: u32) {\n\n unsafe { self.p.reg.write((code << 16) | 0x3333) };\n\n }\n\n\n\n /// Sends a reboot signal to the system controller.\n\n pub fn reboot(&mut self) {\n\n unsafe { self.p.reg.write(0x7777) };\n\n }\n\n}\n", "file_path": "kernel/src/drivers/syscon.rs", "rank": 24, "score": 48524.12836102544 }, { "content": "#[repr(usize)]\n\n#[derive(Debug, Copy, Clone, PartialEq, Eq, Hash)]\n\nenum IrqCause {\n\n STimer = 5,\n\n}\n\n\n\n/// Possible exception causes on a RISC-V CPU.\n", "file_path": "kernel/src/arch/riscv/trap.rs", "rank": 25, "score": 48247.56830998229 }, { "content": "#[repr(usize)]\n\n#[derive(Debug, Copy, Clone, PartialEq, Eq, Hash)]\n\nenum ExceptionCause {\n\n InstrAddrMisaligned,\n\n InstrAccessFault,\n\n IllegalInstr,\n\n Breakpoint,\n\n LoadAddrMisaligned,\n\n LoadAccessFault,\n\n StoreAddrMisaligned,\n\n StoreAccessFault,\n\n EnvCallFromU,\n\n EnvCallFromS,\n\n InstrPageFault,\n\n LoadPageFault,\n\n StorePageFault,\n\n}\n\n\n\nimpl From<usize> for ExceptionCause {\n\n fn from(n: usize) -> Self {\n\n use ExceptionCause::*;\n\n\n", "file_path": "kernel/src/arch/riscv/trap.rs", "rank": 26, "score": 48247.56830998229 }, { "content": "/// Structure of a stack frame on RISC-V.\n\nstruct StackFrame {\n\n fp: usize,\n\n ra: usize,\n\n}\n\n\n", "file_path": "kernel/src/arch/riscv/stackframe.rs", "rank": 27, "score": 47424.024135799365 }, { "content": "#[repr(C)]\n\nstruct TrapFrame {\n\n ra: usize,\n\n sp: usize,\n\n gp: usize,\n\n tp: usize,\n\n t0: usize,\n\n t1: usize,\n\n t2: usize,\n\n s0: usize,\n\n s1: usize,\n\n a0: usize,\n\n a1: usize,\n\n a2: usize,\n\n a3: usize,\n\n a4: usize,\n\n a5: usize,\n\n a6: usize,\n\n a7: usize,\n\n s2: usize,\n\n s3: usize,\n", "file_path": "kernel/src/arch/riscv/trap.rs", "rank": 28, "score": 47424.024135799365 }, { "content": "fn main() {\n\n let target = env::var(\"CARGO_CFG_TARGET_ARCH\").unwrap();\n\n\n\n if target == \"riscv64\" {\n\n // Build startup code and archive it\n\n cc::Build::new()\n\n .file(\"src/arch/riscv/startup.S\")\n\n .file(\"src/arch/riscv/trap.S\")\n\n .compile(\"libcpu.a\");\n\n\n\n println!(\"cargo:rerun-if-changed=src/arch/riscv/startup.S\");\n\n println!(\"cargo:rerun-if-changed=src/arch/riscv/trap.S\");\n\n println!(\"cargo:rerun-if-changed=linkers/riscv.ld\");\n\n }\n\n\n\n println!(\"cargo:rerun-if-changed=build.rs\");\n\n}\n", "file_path": "kernel/build.rs", "rank": 29, "score": 46361.67330652154 }, { "content": "#[allow(clippy::too_many_arguments)]\n\nfn ecall(\n\n ext: Extension,\n\n fid: usize,\n\n mut a0: usize,\n\n mut a1: usize,\n\n a2: usize,\n\n a3: usize,\n\n a4: usize,\n\n a5: usize,\n\n) -> Result<usize> {\n\n unsafe {\n\n asm!(\"ecall\",\n\n inout(\"a0\") a0,\n\n inout(\"a1\") a1,\n\n in(\"a2\") a2,\n\n in(\"a3\") a3,\n\n in(\"a4\") a4,\n\n in(\"a5\") a5,\n\n in(\"a6\") fid,\n\n in(\"a7\") ext as usize);\n\n }\n\n\n\n if a0 == 0 {\n\n Ok(a1)\n\n } else {\n\n Err(SbiError::from(a0 as isize))\n\n }\n\n}\n", "file_path": "sbi/src/lib.rs", "rank": 30, "score": 44949.59072691349 }, { "content": "fn main() {\n\n let mut symbols: Vec<_> = io::stdin()\n\n .lock()\n\n .lines()\n\n .filter_map(|l| parse_nm_line(&l.unwrap()))\n\n .collect();\n\n\n\n symbols.sort_unstable_by_key(|sym| sym.0);\n\n\n\n print_prologue(\"ksyms_offsets\");\n\n for &(addr, _) in &symbols {\n\n print_hex(addr);\n\n }\n\n\n\n print_prologue(\"ksyms_num_syms\");\n\n print_dec(symbols.len());\n\n\n\n print_prologue(\"ksyms_markers\");\n\n print_dec(0);\n\n let mut acc = 0;\n", "file_path": "ksymsgen/src/main.rs", "rank": 31, "score": 44949.59072691349 }, { "content": "/// Traverses the stack frame and prints the call stack.\n\nfn walk_stack_frame() {\n\n let mut fp: usize;\n\n unsafe { asm!(\"add {}, fp, zero\", out(reg) fp) };\n\n\n\n let mut pc = walk_stack_frame as *const fn() as usize;\n\n\n\n loop {\n\n if !is_kernel_text_address(pc) {\n\n break;\n\n }\n\n\n\n print_trace_address(pc);\n\n\n\n // Unwind stack frame\n\n let frame = unsafe { (fp as *const StackFrame).sub(1).as_ref() }.unwrap();\n\n fp = frame.fp;\n\n pc = frame.ra;\n\n }\n\n}\n\n\n", "file_path": "kernel/src/arch/riscv/stackframe.rs", "rank": 32, "score": 40419.17823881122 }, { "content": "#[alloc_error_handler]\n\nfn oom(layout: Layout) -> ! {\n\n kprintln!(\"memory allocation of {} bytes failed\", layout.size());\n\n\n\n crate::arch::halt();\n\n}\n", "file_path": "kernel/src/panic.rs", "rank": 33, "score": 39816.31575921537 }, { "content": "fn print_ascii(s: &str) {\n\n println!(\" .asciz \\\"{}\\\"\", s);\n\n}\n", "file_path": "ksymsgen/src/main.rs", "rank": 34, "score": 39816.31575921537 }, { "content": "#[cfg(test)]\n\n#[panic_handler]\n\nfn panic(info: &PanicInfo) -> ! {\n\n use crate::drivers::syscon::SYSCON;\n\n\n\n kprintln!(\"FAILED\");\n\n kprintln!();\n\n kprintln!(\"Error: {}\", info);\n\n\n\n // Exit from QEMU with error\n\n SYSCON.lock().poweroff(1);\n\n\n\n unreachable!();\n\n}\n\n\n", "file_path": "kernel/src/panic.rs", "rank": 35, "score": 38738.42013336033 }, { "content": "fn print_prologue(label: &str) {\n\n println!(\".section .rodata, \\\"a\\\"\");\n\n println!(\".global {0}\\n.balign 8\\n{0}:\", label);\n\n}\n\n\n", "file_path": "ksymsgen/src/main.rs", "rank": 36, "score": 38738.42013336033 }, { "content": "use super::{memory, sbi, time, trap};\n\n\n\n/// Architecture-specific entry point.\n\n///\n\n/// This function performs any RISC-V-specific setup before handing control to the kernel.\n\n///\n\n/// # Safety\n\n///\n\n/// Physical and virtual memory setup is performed here among other things, so a lot of stuff\n\n/// can go wrong.\n\n#[no_mangle]\n\npub unsafe extern \"C\" fn arch_init() {\n\n kprintln!();\n\n\n\n // Initialize core subsystems\n\n sbi::init();\n\n trap::init();\n\n memory::init();\n\n\n\n // Start ticking\n\n time::schedule_next_tick(time::CLINT_TIMEBASE);\n\n}\n", "file_path": "kernel/src/arch/riscv/entry.rs", "rank": 37, "score": 28037.50875165401 }, { "content": " pub fn put(&mut self, val: u8) {\n\n while self.p.lsr.read() & 0b0010_0000 == 0 {}\n\n unsafe { self.p.rthr.write(val) };\n\n }\n\n\n\n /// Returns the next received byte, or `None` if the Rx queue is empty.\n\n pub fn get(&mut self) -> Option<u8> {\n\n if self.data_ready() {\n\n Some(self.p.rthr.read())\n\n } else {\n\n None\n\n }\n\n }\n\n\n\n /// Returns true if there is data available in the Rx FIFO.\n\n pub fn data_ready(&self) -> bool {\n\n self.p.lsr.read() & 0x1 != 0\n\n }\n\n}\n\n\n\nimpl Write for Ns16550 {\n\n fn write_str(&mut self, s: &str) -> core::fmt::Result {\n\n for b in s.bytes() {\n\n self.put(b);\n\n }\n\n Ok(())\n\n }\n\n}\n", "file_path": "kernel/src/drivers/ns16550.rs", "rank": 50, "score": 31.216955751435012 }, { "content": " Satp::write_ppn(PhysAddr::new_unchecked(rpt as *const _ as u64).page_index());\n\n Satp::write_mode(SatpMode::Sv48);\n\n\n\n // From now on, the root page table must be accessed using its virtual address\n\n let rpt = (PHYS_MEM_OFFSET + rpt as *const _ as usize)\n\n .as_mut_ptr::<PageTable>()\n\n .as_mut::<'static>()\n\n .unwrap();\n\n\n\n // Return the actual offset mapper\n\n Ok(OffsetPageMapper::new(rpt, PHYS_MEM_OFFSET))\n\n}\n\n\n\n/// Maps the heap allocator's virtual pages to physical memory.\n\n///\n\n/// # Safety\n\n///\n\n/// The caller must guarantee that the physical memory being mapped isn't already in use by the\n\n/// system.\n\nunsafe fn setup_heap(\n", "file_path": "kernel/src/arch/riscv/memory.rs", "rank": 52, "score": 30.91913415228956 }, { "content": " Self::write_raw(flags.bits())\n\n }\n\n\n\n /// Writes raw bits to `sip`.\n\n #[inline]\n\n pub fn write_raw(flags: u64) {\n\n unsafe { asm!(\"csrw sip, {}\", in(reg) flags, options(nostack)) };\n\n }\n\n\n\n /// Updates the content of `sip`.\n\n #[inline]\n\n pub fn update<F>(f: F)\n\n where\n\n F: FnOnce(&mut SiFlags),\n\n {\n\n let mut v = Self::read();\n\n f(&mut v);\n\n Self::write(v);\n\n }\n\n\n", "file_path": "riscv/src/registers.rs", "rank": 54, "score": 29.303497680859927 }, { "content": " /// Writes flags to `sie`.\n\n #[inline]\n\n pub fn write(flags: SiFlags) {\n\n Self::write_raw(flags.bits())\n\n }\n\n\n\n /// Writes raw bits to `sie`.\n\n #[inline]\n\n pub fn write_raw(flags: u64) {\n\n unsafe { asm!(\"csrw sie, {}\", in(reg) flags, options(nostack)) };\n\n }\n\n\n\n /// Updates the content of `sie`.\n\n #[inline]\n\n pub fn update<F>(f: F)\n\n where\n\n F: FnOnce(&mut SiFlags),\n\n {\n\n let mut v = Self::read();\n\n f(&mut v);\n", "file_path": "riscv/src/registers.rs", "rank": 55, "score": 28.583654318211508 }, { "content": " mapper: &mut OffsetPageMapper,\n\n start: VirtAddr,\n\n end: VirtAddr,\n\n phys_base: PhysAddr,\n\n) -> Result<(), MapError> {\n\n let page_size = PAGE_SIZE as usize;\n\n let num_heap_pages = (end - start).data() / page_size;\n\n\n\n // Map heap pages\n\n for i in 0..num_heap_pages {\n\n let vaddr = start + i * page_size;\n\n let paddr = phys_base + (i * page_size) as u64;\n\n\n\n mapper.map(vaddr, paddr, PageSize::Kb, EntryFlags::RWX, &mut GFA)?;\n\n }\n\n\n\n Ok(())\n\n}\n", "file_path": "kernel/src/arch/riscv/memory.rs", "rank": 56, "score": 26.937038891920313 }, { "content": "//! Collection of memory allocators.\n\n\n\nuse spin::Mutex;\n\n\n\nuse crate::PhysicalAddress;\n\n\n\npub mod bitmap;\n\n\n\n/// The error type returned by fallible allocator operations.\n\n#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, PartialOrd, Ord)]\n\npub enum AllocatorError {\n\n /// The provided address is not properly aligned.\n\n UnalignedAddress,\n\n /// The provided page size is not valid.\n\n InvalidPageSize,\n\n}\n\n\n\n/// A trait for page-grained memory allocators.\n", "file_path": "kmm/src/allocator/mod.rs", "rank": 58, "score": 26.40209537639723 }, { "content": " pub const fn vpn1(self) -> usize {\n\n (self.data() >> 21) & 0x1ff\n\n }\n\n\n\n /// Returns the 9-bit level 2 page table index.\n\n pub const fn vpn2(self) -> usize {\n\n (self.data() >> 30) & 0x1ff\n\n }\n\n\n\n /// Returns the 9-bit level 3 page table index.\n\n #[cfg(feature = \"sv48\")]\n\n pub const fn vpn3(self) -> usize {\n\n (self.data() >> 39) & 0x1ff\n\n }\n\n}\n\n\n\nimpl Align<usize> for VirtAddr {\n\n fn align_up(&self, align: usize) -> Self {\n\n assert!(align.is_power_of_two(), \"Alignment must be a power of two\");\n\n Self::new((self.data() + align - 1) & !(align - 1))\n", "file_path": "riscv/src/addr.rs", "rank": 60, "score": 25.916186615757272 }, { "content": "//! Physical and virtual addresses manipulation.\n\n\n\nuse core::{\n\n convert::TryFrom,\n\n fmt,\n\n ops::{Add, Sub},\n\n};\n\n\n\nuse kmm::{AddressOps, Align, PhysicalAddress};\n\n\n\n/// Number of bits that an address needs to be shifted to the left to obtain its page number.\n\npub const PAGE_SHIFT: u64 = 12;\n\n\n\n/// Size of a page in bytes.\n\npub const PAGE_SIZE: u64 = 1 << 12;\n\n\n\n/// Error type returned by failed address conversions or operations on invalid addresses.\n\n#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord)]\n\npub struct InvalidAddrError;\n\n\n", "file_path": "riscv/src/addr.rs", "rank": 62, "score": 25.75881507101512 }, { "content": " /// `Bare` translation mode (`virt` == `phys`).\n\n Bare = 0,\n\n /// `Sv32` translation scheme (2-level page table).\n\n Sv32 = 1,\n\n /// `Sv39` translation scheme (3-level page table).\n\n Sv39 = 8,\n\n /// `Sv48` translation scheme (4-level page table).\n\n Sv48 = 9,\n\n}\n\n\n\nimpl From<u64> for SatpMode {\n\n fn from(v: u64) -> Self {\n\n use SatpMode::*;\n\n\n\n match v {\n\n 0 => Bare,\n\n 1 => Sv32,\n\n 8 => Sv39,\n\n 9 => Sv48,\n\n _ => unreachable!(\"invalid stval mode field\"),\n", "file_path": "riscv/src/registers.rs", "rank": 64, "score": 24.687337452493185 }, { "content": "\n\n/// Read-write register.\n\npub struct RW<T>\n\nwhere\n\n T: Copy,\n\n{\n\n register: VolatileCell<T>,\n\n}\n\n\n\nimpl<T> RW<T>\n\nwhere\n\n T: Copy,\n\n{\n\n /// Performs a read-modify-write operation on the register.\n\n ///\n\n /// # Safety\n\n ///\n\n /// Unsafe because writes to registers are side-effectful.\n\n #[inline(always)]\n\n pub fn modify<F>(&self, f: F)\n", "file_path": "kernel/src/mm/mmio.rs", "rank": 65, "score": 23.89397644834178 }, { "content": "impl Sip {\n\n /// Reads the content of `sip`.\n\n #[inline]\n\n pub fn read() -> SiFlags {\n\n SiFlags::from_bits_truncate(Self::read_raw())\n\n }\n\n\n\n /// Reads the raw content of `sip`.\n\n #[inline]\n\n pub fn read_raw() -> u64 {\n\n let value: u64;\n\n unsafe {\n\n asm!(\"csrr {}, sip\", out(reg) value, options(nomem));\n\n }\n\n value\n\n }\n\n\n\n /// Writes flags to `sip`.\n\n #[inline]\n\n pub fn write(flags: SiFlags) {\n", "file_path": "riscv/src/registers.rs", "rank": 67, "score": 22.82054143775028 }, { "content": " ///\n\n /// This function is unsafe because it's possible to violate memory safety through it.\n\n #[inline]\n\n pub unsafe fn write_ppn(ppn: u64) {\n\n unsafe { Self::write_raw((Self::read_raw() & !0xfff_ffff_ffff_u64) | ppn) }\n\n }\n\n\n\n /// Writes the address-space identifier to the `satp` register.\n\n ///\n\n /// ## Safety\n\n ///\n\n /// This function is unsafe because it's possible to violate memory safety through it.\n\n #[inline]\n\n pub unsafe fn write_asid(asid: u64) {\n\n let mask = 0xffff << 44;\n\n unsafe { Self::write_raw((Self::read_raw() & !mask) | (asid << 44)) }\n\n }\n\n\n\n /// Writes the virtual translation mode to the `satp` register.\n\n ///\n", "file_path": "riscv/src/registers.rs", "rank": 68, "score": 22.373053739126135 }, { "content": "\n\n /// Writes raw bits to `sstatus`.\n\n ///\n\n /// ## Safety\n\n ///\n\n /// This function is unsafe because it's possible to violate memory safety through it.\n\n #[inline]\n\n pub unsafe fn write_raw(flags: u64) {\n\n unsafe { asm!(\"csrw sstatus, {}\", in(reg) flags, options(nostack)) };\n\n }\n\n\n\n /// Updates the content of `sstatus`.\n\n ///\n\n /// ## Safety\n\n ///\n\n /// This function is unsafe because it's possible to violate memory safety through it.\n\n #[inline]\n\n pub unsafe fn update<F>(f: F)\n\n where\n\n F: FnOnce(&mut SstatusFlags),\n", "file_path": "riscv/src/registers.rs", "rank": 69, "score": 22.280108685825734 }, { "content": "//! Implementation of the Supervisor Binary Interface (SBI) specification for RISC-V.\n\n//!\n\n//! This crate can be used to interact with an M-mode Runtime Firmware running on a RISC-V machine\n\n//! to execute certain privileged operations in supervisor mode.\n\n\n\n#![no_std]\n\n#![warn(missing_docs)]\n\n#![deny(missing_debug_implementations)]\n\n#![feature(asm)]\n\n// Require explicit unsafe blocks even in unsafe fn\n\n#![feature(unsafe_block_in_unsafe_fn)]\n\n#![deny(unsafe_op_in_unsafe_fn)]\n\n\n\nuse core::fmt;\n\n\n\n/// A standard SBI error code.\n\n#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]\n\npub enum SbiError {\n\n /// Operation failed.\n\n Failed,\n", "file_path": "sbi/src/lib.rs", "rank": 70, "score": 22.221505709230463 }, { "content": " /// Reads the content of `stval`.\n\n #[inline]\n\n pub fn read() -> u64 {\n\n let value: u64;\n\n unsafe {\n\n asm!(\"csrr {}, stval\", out(reg) value, options(nomem));\n\n }\n\n value\n\n }\n\n\n\n /// Writes to `stval`.\n\n #[inline]\n\n pub fn write(v: u64) {\n\n unsafe { asm!(\"csrw stval, {}\", in(reg) v, options(nostack)) };\n\n }\n\n}\n\n\n\n/// Virtual addressing modes supported by the RISC-V architectures.\n\n#[derive(Debug, Clone, Copy, PartialEq, Eq)]\n\npub enum SatpMode {\n", "file_path": "riscv/src/registers.rs", "rank": 71, "score": 21.978865762852546 }, { "content": "\n\n /// Reads the raw content of `sstatus`.\n\n #[inline]\n\n pub fn read_raw() -> u64 {\n\n let value: u64;\n\n unsafe {\n\n asm!(\"csrr {}, sstatus\", out(reg) value, options(nomem));\n\n }\n\n value\n\n }\n\n\n\n /// Writes flags to `sstatus`.\n\n ///\n\n /// ## Safety\n\n ///\n\n /// This function is unsafe because it's possible to violate memory safety through it.\n\n #[inline]\n\n pub unsafe fn write(flags: SstatusFlags) {\n\n unsafe { Self::write_raw(flags.bits()) }\n\n }\n", "file_path": "riscv/src/registers.rs", "rank": 72, "score": 21.6658906201253 }, { "content": " }\n\n }\n\n}\n\n\n\n/// The `stval` register controls S-Mode address translation and protection.\n\n#[derive(Debug)]\n\npub struct Satp;\n\n\n\nimpl Satp {\n\n /// Reads the physical page number of root page table from the `satp` register.\n\n #[inline]\n\n pub fn read_ppn() -> u64 {\n\n Self::read_raw() & 0xfff_ffff_ffff\n\n }\n\n\n\n /// Reads the address-space identifier from the `satp` register.\n\n #[inline]\n\n pub fn read_asid() -> u64 {\n\n (Self::read_raw() >> 44) & 0xffff\n\n }\n", "file_path": "riscv/src/registers.rs", "rank": 73, "score": 21.537507671379455 }, { "content": " let reserved_mem = total_num_pages * size_of::<PageDescriptor>() as u64;\n\n let avail_mem_start = (start + reserved_mem).align_up(N);\n\n let avail_mem_size = end - avail_mem_start;\n\n let avail_pages: u64 = avail_mem_size.into() / N;\n\n\n\n let descriptors = unsafe {\n\n slice::from_raw_parts_mut(\n\n <A as Into<u64>>::into(start) as *mut PageDescriptor,\n\n avail_pages as usize,\n\n )\n\n };\n\n\n\n // Initially mark all pages as free\n\n for descr in descriptors.iter_mut() {\n\n *descr = PageDescriptor {\n\n flags: PageFlags::empty(),\n\n };\n\n }\n\n\n\n Ok(Self {\n", "file_path": "kmm/src/allocator/bitmap.rs", "rank": 74, "score": 21.53010010090125 }, { "content": " fn from(addr: usize) -> Self {\n\n Self::new(addr)\n\n }\n\n}\n\n\n\nimpl fmt::Debug for VirtAddr {\n\n fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {\n\n write!(f, \"VirtAddr({:#x})\", self.0)\n\n }\n\n}\n\n\n\nimpl fmt::Display for VirtAddr {\n\n fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {\n\n fmt::LowerHex::fmt(&self.0, f)\n\n }\n\n}\n\n\n\nimpl fmt::LowerHex for VirtAddr {\n\n #[inline]\n\n fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {\n", "file_path": "riscv/src/addr.rs", "rank": 75, "score": 21.46768918247491 }, { "content": " pub fn new(addr: u64) -> Self {\n\n Self::try_new(addr)\n\n .expect(\"address passed to PhysAddr::new must not contain any data in bits 56 to 63\")\n\n }\n\n\n\n /// Creates a new physical address from a physical page index.\n\n ///\n\n /// # Panics\n\n ///\n\n /// Panics if `ppn` is not a valid physical page index for the target ISA.\n\n /// See [`PhysAddr`] documentation for details.\n\n pub fn from_ppn(ppn: u64) -> Self {\n\n Self::try_new(ppn << PAGE_SHIFT)\n\n .expect(\"index passed to PhysAddr::from_ppn is not a valid page number\")\n\n }\n\n\n\n /// Tries for create a new physical address.\n\n ///\n\n /// Returns an error if `addr` is not a valid physical address for the target ISA.\n\n pub fn try_new(addr: u64) -> Result<Self, InvalidAddrError> {\n", "file_path": "riscv/src/addr.rs", "rank": 76, "score": 21.421655308472186 }, { "content": "\n\n /// Returns the 9-bit level 1 page table index.\n\n pub const fn ppn1(self) -> u64 {\n\n (self.data() >> 21) & 0x1ff\n\n }\n\n\n\n /// Returns the level 2 page table index.\n\n ///\n\n /// The size of this field varies depending on the MMU specification.\n\n pub const fn ppn2(self) -> u64 {\n\n if cfg!(target = \"sv39\") {\n\n (self.data() >> 30) & 0x3ff_ffff\n\n } else {\n\n /* feature = \"sv48\" */\n\n (self.data() >> 30) & 0x1ff\n\n }\n\n }\n\n\n\n /// Returns the 17-bit level 3 page table index.\n\n #[cfg(feature = \"sv48\")]\n", "file_path": "riscv/src/addr.rs", "rank": 77, "score": 21.076543148968078 }, { "content": " pub const fn page_offset(self) -> usize {\n\n self.0 & 0xfff\n\n }\n\n\n\n /// Returns the full page number of this address.\n\n pub const fn page_index(self) -> usize {\n\n if cfg!(feature = \"sv39\") {\n\n (self.data() >> PAGE_SHIFT) & 0x7ff_ffff\n\n } else {\n\n /* feature = \"sv48\" */\n\n (self.data() >> PAGE_SHIFT) & 0xf_ffff_ffff\n\n }\n\n }\n\n\n\n /// Returns the 9-bit level 0 page table index.\n\n pub const fn vpn0(self) -> usize {\n\n (self.data() >> 12) & 0x1ff\n\n }\n\n\n\n /// Returns the 9-bit level 1 page table index.\n", "file_path": "riscv/src/addr.rs", "rank": 78, "score": 20.909178878415027 }, { "content": "//! This crate provides RISC-V specific functions and data structures,\n\n//! and access to various system registers.\n\n//!\n\n//! # Features\n\n//!\n\n//! - `sv39`: use Sv39 MMU specification\n\n//! - `sv48`: use Sv48 MMU specification\n\n\n\n#![no_std]\n\n#![warn(missing_docs)]\n\n#![deny(missing_debug_implementations)]\n\n#![feature(asm)]\n\n// Require explicit unsafe blocks even in unsafe fn\n\n#![feature(unsafe_block_in_unsafe_fn)]\n\n#![deny(unsafe_op_in_unsafe_fn)]\n\n\n\npub mod addr;\n\npub mod instructions;\n\npub mod mmu;\n\npub mod registers;\n\n\n\npub use addr::{InvalidAddrError, PhysAddr, VirtAddr};\n", "file_path": "riscv/src/lib.rs", "rank": 79, "score": 20.747731610829277 }, { "content": "\n\n /// Reads the virtual translation mode from the `satp` register.\n\n #[inline]\n\n pub fn read_mode() -> SatpMode {\n\n SatpMode::from(Self::read_raw() >> 60)\n\n }\n\n\n\n /// Reads the raw content of `satp`.\n\n #[inline]\n\n pub fn read_raw() -> u64 {\n\n let value: u64;\n\n unsafe {\n\n asm!(\"csrr {}, satp\", out(reg) value, options(nomem));\n\n }\n\n value\n\n }\n\n\n\n /// Writes the physical page number of the root page table to the `satp` register.\n\n ///\n\n /// ## Safety\n", "file_path": "riscv/src/registers.rs", "rank": 80, "score": 20.310356588915297 }, { "content": " {\n\n let mut v = Self::read();\n\n f(&mut v);\n\n unsafe { Self::write(v) };\n\n }\n\n\n\n /// Sets the specified flags to `sstatus`.\n\n ///\n\n /// ## Safety\n\n ///\n\n /// This function is unsafe because it's possible to violate memory safety through it.\n\n #[inline]\n\n pub unsafe fn set(flags: SstatusFlags) {\n\n unsafe { asm!(\"csrs sstatus, {}\", in(reg) flags.bits(), options(nostack)) };\n\n }\n\n\n\n /// Clears the specified flags from `sstatus`.\n\n ///\n\n /// ## Safety\n\n ///\n", "file_path": "riscv/src/registers.rs", "rank": 81, "score": 20.28019152720579 }, { "content": "\n\n/// Reason for the system reset.\n\n#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]\n\npub enum ResetReason {\n\n /// No reason for reset.\n\n None,\n\n /// Unexpected system failure.\n\n SystemFailure,\n\n /// Implementation-defined reason.\n\n Custom(usize),\n\n}\n\n\n\nimpl From<ResetReason> for usize {\n\n fn from(v: ResetReason) -> Self {\n\n match v {\n\n ResetReason::None => 0,\n\n ResetReason::SystemFailure => 1,\n\n ResetReason::Custom(v) => v,\n\n }\n\n }\n", "file_path": "sbi/src/lib.rs", "rank": 82, "score": 20.24839979772979 }, { "content": " descriptors,\n\n base_addr: avail_mem_start,\n\n num_pages: avail_pages,\n\n })\n\n }\n\n}\n\n\n\nimpl<A, const N: u64> FrameAllocator<A, N> for BitmapAllocator<A, N>\n\nwhere\n\n A: PhysicalAddress<u64>,\n\n{\n\n unsafe fn alloc(&mut self, count: usize) -> Option<A> {\n\n let mut i: usize = 0;\n\n\n\n 'outer: while i < self.num_pages as usize {\n\n let descr = &mut self.descriptors[i];\n\n\n\n // Page already taken => keep going.\n\n if descr.flags.intersects(PageFlags::TAKEN | PageFlags::LAST) {\n\n i += 1;\n", "file_path": "kmm/src/allocator/bitmap.rs", "rank": 83, "score": 20.148866522246504 }, { "content": "use riscv::registers::Stvec;\n\nuse stackframe::unwind_stack_frame;\n\n\n\nuse super::*;\n\n\n\n// {m,s}cause register flags\n\nconst CAUSE_IRQ_FLAG_MASK: usize = 1 << 63;\n\n\n\n/// Possible interrupt causes on a RISC-V CPU.\n\n#[repr(usize)]\n\n#[derive(Debug, Copy, Clone, PartialEq, Eq, Hash)]\n", "file_path": "kernel/src/arch/riscv/trap.rs", "rank": 84, "score": 20.04588633424539 }, { "content": "///\n\n/// The address width depends on the chosen MMU specification.\n\n/// - In Sv32 mode, virtual addresses are 32-bit wide and all bits are used in the translation.\n\n/// - In Sv39 mode, virtual addresses are 64-bit wide but only the lower 39 bits are used by the\n\n/// MMU. Bits 63–39 must all be equal to bit 38, or else a page-fault exception will occur.\n\n/// - In Sv48 mode, virtual addresses are 64-bit wide but only the lower 48 bits are used by the\n\n/// MMU. Bits 63–48 must all be equal to bit 47, or else a page-fault exception will occur.\n\n///\n\n/// The safe methods of this type ensure that the above constraints are met.\n\n#[derive(Clone, Copy, PartialEq, Eq, PartialOrd, Ord)]\n\n#[repr(transparent)]\n\npub struct VirtAddr(usize);\n\n\n\nimpl VirtAddr {\n\n /// Creates a new virtual address.\n\n ///\n\n /// # Panics\n\n ///\n\n /// Panics if `addr` is not a valid virtual address for the target ISA and MMU specification.\n\n /// See [`VirtAddr`] documentation for details.\n", "file_path": "riscv/src/addr.rs", "rank": 86, "score": 19.84872072639172 }, { "content": " let rodata_start = PhysAddr::new(&__rodata_start as *const usize as u64);\n\n let rodata_end = PhysAddr::new(&__rodata_end as *const usize as u64);\n\n let data_start = PhysAddr::new(&__data_start as *const usize as u64);\n\n let data_end = PhysAddr::new(&__data_end as *const usize as u64);\n\n\n\n kprintln!(\"Kernel memory map:\");\n\n kprintln!(\" [{} - {}] .text\", text_start, text_end);\n\n kprintln!(\" [{} - {}] .rodata\", rodata_start, rodata_end);\n\n kprintln!(\" [{} - {}] .data\", data_start, data_end);\n\n\n\n // Allocate a frame for the root page table to be used for virtual address translation.\n\n // Since translation is not enabled here yet, we can use the frame's physical address directly.\n\n let rpt = (GFA.alloc(1).unwrap().data() as *mut PageTable)\n\n .as_mut::<'static>()\n\n .unwrap();\n\n\n\n rpt.clear();\n\n\n\n // Again, since translation is off, we use an offset mapper with zero offset.\n\n let mut mapper = OffsetPageMapper::new(rpt, VirtAddr::new(0));\n", "file_path": "kernel/src/arch/riscv/memory.rs", "rank": 87, "score": 19.637814484602885 }, { "content": "#[derive(Debug)]\n\npub struct Sie;\n\n\n\nimpl Sie {\n\n /// Reads the content of `sie`.\n\n #[inline]\n\n pub fn read() -> SiFlags {\n\n SiFlags::from_bits_truncate(Self::read_raw())\n\n }\n\n\n\n /// Reads the raw content of `sie`.\n\n #[inline]\n\n pub fn read_raw() -> u64 {\n\n let value: u64;\n\n unsafe {\n\n asm!(\"csrr {}, sie\", out(reg) value, options(nomem));\n\n }\n\n value\n\n }\n\n\n", "file_path": "riscv/src/registers.rs", "rank": 88, "score": 19.613240385952157 }, { "content": "use core::cell::UnsafeCell;\n\n\n\n/// Read-only register.\n\npub struct RO<T>\n\nwhere\n\n T: Copy,\n\n{\n\n register: VolatileCell<T>,\n\n}\n\n\n\nimpl<T> RO<T>\n\nwhere\n\n T: Copy,\n\n{\n\n /// Reads a value from the register.\n\n #[inline(always)]\n\n pub fn read(&self) -> T {\n\n self.register.get()\n\n }\n\n}\n", "file_path": "kernel/src/mm/mmio.rs", "rank": 89, "score": 19.509959413430483 }, { "content": "//! Access to various system registers.\n\n\n\nuse bitflags::bitflags;\n\n\n\nbitflags! {\n\n /// Flags for the `sstatus` register.\n\n pub struct SstatusFlags: u64 {\n\n /// S-Mode interrupt enable.\n\n const SIE = 1 << 1;\n\n /// S-Mode previous interrupt enable.\n\n const SPIE = 1 << 5;\n\n /// U-Mode big endian memory access.\n\n const UBE = 1 << 6;\n\n /// S-Mode previous privilege level.\n\n const SPP = 1 << 8;\n\n /// Floating point unit state.\n\n const FS = 3 << 13;\n\n /// U-Mode extension state.\n\n const XS = 3 << 15;\n\n /// Permit S-Mode user memory access.\n", "file_path": "riscv/src/registers.rs", "rank": 90, "score": 19.49107829184146 }, { "content": "/// A 64-bit physical memory address.\n\n///\n\n/// This is a wrapper type around an `u64`, so it is always 8 bytes, even when compiled on\n\n/// non 64-bit systems. The [`TryFrom`](core::convert::TryFrom) trait can be used\n\n/// for performing conversions between `u64` and `usize`.\n\n///\n\n/// The actual address width depends on the target ISA. For R32 it will be 34-bit long,\n\n/// for R64 it is 56-bit long. Both are encoded as a 64-bit word.\n\n/// The remaining upper bits must be set to zero.\n\n#[derive(Clone, Copy, PartialEq, Eq, PartialOrd, Ord)]\n\n#[repr(transparent)]\n\npub struct PhysAddr(u64);\n\n\n\nimpl PhysAddr {\n\n /// Creates a new physical address.\n\n ///\n\n /// # Panics\n\n ///\n\n /// Panics if `addr` is not a valid physical address for the target ISA.\n\n /// See [`PhysAddr`] documentation for details.\n", "file_path": "riscv/src/addr.rs", "rank": 91, "score": 19.27294135410636 }, { "content": "\n\n fn assert_allocated<const N: u64>(\n\n allocator: &mut BitmapAllocator<u64, N>,\n\n start: u64,\n\n count: u64,\n\n ) {\n\n for i in start..start + count - 1 {\n\n assert_eq!(\n\n allocator.descriptors[i as usize],\n\n PageDescriptor {\n\n flags: PageFlags::TAKEN\n\n }\n\n );\n\n }\n\n\n\n assert_eq!(\n\n allocator.descriptors[(start + count - 1) as usize],\n\n PageDescriptor {\n\n flags: PageFlags::LAST\n\n }\n", "file_path": "kmm/src/allocator/bitmap.rs", "rank": 92, "score": 19.26435422936994 }, { "content": " fn is_aligned(&self, align: u64) -> bool {\n\n assert!(align.is_power_of_two(), \"Alignment must be a power of two\");\n\n (self.data() & (align - 1)) == 0\n\n }\n\n}\n\n\n\nimpl From<PhysAddr> for u64 {\n\n fn from(pa: PhysAddr) -> Self {\n\n pa.0\n\n }\n\n}\n\n\n\nimpl TryFrom<u64> for PhysAddr {\n\n type Error = InvalidAddrError;\n\n\n\n fn try_from(addr: u64) -> Result<Self, Self::Error> {\n\n Self::try_new(addr)\n\n }\n\n}\n\n\n", "file_path": "riscv/src/addr.rs", "rank": 93, "score": 18.95316156617852 }, { "content": "impl fmt::Pointer for PhysAddr {\n\n #[inline]\n\n fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {\n\n fmt::Pointer::fmt(&(self.0 as *const ()), f)\n\n }\n\n}\n\n\n\nimpl Add for PhysAddr {\n\n type Output = Self;\n\n\n\n fn add(self, rhs: Self) -> Self::Output {\n\n Self::new(self.0 + rhs.0)\n\n }\n\n}\n\n\n\nimpl Add<u64> for PhysAddr {\n\n type Output = Self;\n\n\n\n fn add(self, rhs: u64) -> Self::Output {\n\n Self::new(self.0 + rhs)\n", "file_path": "riscv/src/addr.rs", "rank": 94, "score": 18.828343492078425 }, { "content": " StartPending,\n\n /// The hart has requested to stop (or power-down) itself from the `Started` state.\n\n StopPending,\n\n}\n\n\n\nimpl From<usize> for HartState {\n\n fn from(code: usize) -> Self {\n\n match code {\n\n 0 => HartState::Started,\n\n 1 => HartState::Stopped,\n\n 2 => HartState::StartPending,\n\n 3 => HartState::StopPending,\n\n _ => unreachable!(\"unexpected hart state code\"),\n\n }\n\n }\n\n}\n\n\n\n/// System reset type being requested.\n\n#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]\n\npub enum ResetType {\n", "file_path": "sbi/src/lib.rs", "rank": 95, "score": 18.803269263634128 }, { "content": " T: Copy,\n\n {\n\n unsafe { self.inner.get().read_volatile() }\n\n }\n\n\n\n /// Writes the given value into the cell.\n\n #[inline(always)]\n\n pub fn set(&self, val: T)\n\n where\n\n T: Copy,\n\n {\n\n unsafe { self.inner.get().write_volatile(val) }\n\n }\n\n}\n\n\n\n/// Reads a value of type `T` from location `base + offset` in memory.\n", "file_path": "kernel/src/mm/mmio.rs", "rank": 96, "score": 18.581739905144897 }, { "content": " }\n\n\n\n // --- Test types and utilities ---\n\n\n\n impl PhysicalAddress<u64> for u64 {}\n\n\n\n impl AddressOps<u64> for u64 {}\n\n\n\n impl Align<u64> for u64 {\n\n fn align_up(&self, align: u64) -> Self {\n\n (self + align - 1) & !(align - 1)\n\n }\n\n\n\n fn align_down(&self, align: u64) -> Self {\n\n self & !(align - 1)\n\n }\n\n\n\n fn is_aligned(&self, align: u64) -> bool {\n\n self & (align - 1) == 0\n\n }\n", "file_path": "kmm/src/allocator/bitmap.rs", "rank": 97, "score": 18.494936863976214 }, { "content": "use core::fmt::Write;\n\n\n\nuse lazy_static::lazy_static;\n\nuse spin::Mutex;\n\n\n\nuse crate::mm::mmio::{RO, RW};\n\n\n\nlazy_static! {\n\n /// Instance of the UART0 serial port on this machine.\n\n pub static ref UART0: Mutex<Ns16550> = Mutex::new(Ns16550::new(0x1000_0000));\n\n}\n\n\n\n/// Device driver of the 16550 UART IC.\n\npub struct Ns16550 {\n\n p: &'static mut RegisterBlock,\n\n}\n\n\n\n#[repr(C, packed)]\n", "file_path": "kernel/src/drivers/ns16550.rs", "rank": 98, "score": 18.26532453688253 }, { "content": " pub const unsafe fn new_unchecked(addr: usize) -> Self {\n\n Self(addr)\n\n }\n\n\n\n /// Returns the integer representation of this address.\n\n pub const fn data(self) -> usize {\n\n self.0\n\n }\n\n\n\n /// Interprets this address as a raw pointer to `T`.\n\n pub const fn as_ptr<T>(self) -> *const T {\n\n self.data() as *const T\n\n }\n\n\n\n /// Interprets this address as an unsafe mutable pointer to `T`.\n\n pub const fn as_mut_ptr<T>(self) -> *mut T {\n\n self.data() as *mut T\n\n }\n\n\n\n /// Returns the lowest 12 bits of this address.\n", "file_path": "riscv/src/addr.rs", "rank": 99, "score": 18.258108694581907 } ]
Rust
src/bin/test_merge.rs
GuilloteauQ/rayon-adaptive
ad3c82ca5d942df9c052b079e20d0331f840e303
use itertools::{iproduct, Itertools}; use rand::Rng; use rayon_adaptive::adaptive_sort_raw_with_policies_swap_blocks; use rayon_adaptive::Policy; use std::fs::File; use std::io::prelude::*; use std::iter::{once, repeat_with}; use thread_binder::ThreadPoolBuilder; use time::precise_time_ns; fn random_vec_with_range(size: usize, min_value: u32, max_value: u32) -> Vec<u32> { (0..size) .map(|_| rand::thread_rng().gen_range(min_value, max_value)) .collect() } fn sorted_vec(size: usize) -> Vec<u32> { (0..size).map(|x| x as u32).collect() } fn reversed_vec(size: usize) -> Vec<u32> { (0..size).rev().map(|x| x as u32).collect() } fn half_sorted(size: usize) -> Vec<u32> { let mid = size / 2; (0..mid).rev().chain(mid..size).map(|x| x as u32).collect() } fn random_vec_with_duplicates(size: usize) -> Vec<u32> { random_vec_with_range(size, 0, size as u32 / 8) } fn random_vec(size: usize) -> Vec<u32> { random_vec_with_range(size, 0, size as u32) } fn bench<INPUT, I, F>(init_fn: I, timed_fn: F) -> (u64, bool) where INPUT: Sized, I: Fn() -> INPUT, F: Fn(INPUT) -> bool, { let input = init_fn(); let begin_time: u64 = precise_time_ns(); let state = timed_fn(input); let end_time: u64 = precise_time_ns(); (end_time - begin_time, state) } fn tuple_to_vec<A: Clone, B: Clone>(v: &Vec<(A, B)>) -> (Vec<A>, Vec<B>) { let mut va = Vec::new(); let mut vb = Vec::new(); for (a, b) in v.iter() { va.push(a.clone()); vb.push(b.clone()); } (va, vb) } fn average_times<INPUT: Sized, I: Fn() -> INPUT, F: Fn(INPUT) -> bool>( init_fn: I, timed_fn: F, iterations: usize, ) -> (f64, usize) { let mut ve = Vec::new(); for _ in 0..iterations { ve.push(bench(&init_fn, &timed_fn)); } let v = tuple_to_vec(&ve); let time: f64 = v.0.iter().sum::<u64>() as f64 / iterations as f64; let states: usize = v.1.iter().map(|&b| if b { 1 } else { 0 }).sum(); (time, states) } fn times_by_processors< INPUT: Sized, I: Fn() -> INPUT + Send + Copy + Sync, F: Fn(INPUT) -> bool + Send + Copy + Sync, THREADS: IntoIterator<Item = usize>, >( init_fn: I, timed_fn: F, iterations: usize, threads_numbers: THREADS, ) -> Vec<(f64, usize)> { threads_numbers .into_iter() .map(move |threads| { let pool = ThreadPoolBuilder::new() .num_threads(threads) .build() .expect("building pool failed"); pool.install(|| average_times(init_fn, timed_fn, iterations)) }) .collect() } fn main() { let iterations = 100; let sizes = vec![1_000_000]; let threads: Vec<usize> = vec![4]; let policies = vec![Policy::Join(1000), Policy::JoinContext(1000)]; let input_generators = vec![ /* ( Box::new(random_vec) as Box<Fn(usize) -> Vec<u32> + Sync>, "random", ), */ ( Box::new(sorted_vec) as Box<Fn(usize) -> Vec<u32> + Sync>, "sorted", ), /* ( Box::new(reversed_vec) as Box<Fn(usize) -> Vec<u32> + Sync>, "reversed", ), ( Box::new(random_vec_with_duplicates) as Box<Fn(usize) -> Vec<u32> + Sync>, "random_with_duplicates", ), ( Box::new(half_sorted) as Box<Fn(usize) -> Vec<u32> + Sync>, "half sorted, half reversed", ), */ ]; let algorithms: Vec<_> = iproduct!(policies.clone(), policies.clone()) .map(|(sort_policy, fuse_policy)| { ( Box::new(move |mut v: Vec<u32>| { adaptive_sort_raw_with_policies_swap_blocks(&mut v, sort_policy, fuse_policy) }) as Box<Fn(Vec<u32>) -> bool + Sync + Send>, format!("Swap {:?}/{:?}", sort_policy, fuse_policy), ) }) .collect(); for (generator_f, generator_name) in input_generators.iter() { println!(">>> {}", generator_name); for size in sizes.iter() { println!("Size: {}", size); let algo_results: Vec<_> = algorithms .iter() .map(|(algo_f, name)| { print!("{}: ", name); let res = times_by_processors( || generator_f(*size), |v| algo_f(v), iterations, threads.clone(), ); print!( "{}/{} copies\n", res.iter().map(|(_, b)| b).sum::<usize>(), iterations ); res }) .collect(); } } }
use itertools::{iproduct, Itertools}; use rand::Rng; use rayon_adaptive::adaptive_sort_raw_with_policies_swap_blocks; use rayon_adaptive::Policy; use std::fs::File; use std::io::prelude::*; use std::iter::{once, repeat_with}; use thread_binder::ThreadPoolBuilder; use time::precise_time_ns; fn random_vec_with_range(size: usize, min_value: u32, max_value: u32) -> Vec<u32> { (0..size) .map(|_| rand::thread_rng().gen_range(min_value, max_value)) .collect() } fn sorted_vec(size: usize) -> Vec<u32> { (0..size).map(|x| x as u32).collect() } fn reversed_vec(size: usize) -> Vec<u32> { (0..size).rev().map(|x| x as u32).collect() } fn half_sorted(size: usize) -> Vec<u32> { let mid = size / 2; (0..mid).rev().chain(mid..size).map(|x| x as u32).collect() } fn random_vec_with_duplicates(size: usize) -> Vec<u32> { random_vec_with_range(size, 0, size as u32 / 8) } fn random_vec(size: usize) -> Vec<u32> { random_vec_with_range(size, 0, size as u32) } fn bench<INPUT, I, F>(init_fn: I, timed_fn: F) -> (u64, bool) where INPUT: Sized, I: Fn() -> INPUT, F: Fn(INPUT) -> bool, { let input = init_fn(); let begin_time: u64 = precise_time_ns(); let state = timed_fn(input); let end_time: u64 = precise_time_ns(); (end_time - begin_time, state) } fn tuple_to_vec<A: Clone, B: Clone>(v: &Vec<(A, B)>) -> (Vec<A>, Vec<B>) { let mut va = Vec::new(); let mut vb = Vec::new(); for (a, b) in v.iter() { va.push(a.clone()); vb.push(b.c
let sizes = vec![1_000_000]; let threads: Vec<usize> = vec![4]; let policies = vec![Policy::Join(1000), Policy::JoinContext(1000)]; let input_generators = vec![ /* ( Box::new(random_vec) as Box<Fn(usize) -> Vec<u32> + Sync>, "random", ), */ ( Box::new(sorted_vec) as Box<Fn(usize) -> Vec<u32> + Sync>, "sorted", ), /* ( Box::new(reversed_vec) as Box<Fn(usize) -> Vec<u32> + Sync>, "reversed", ), ( Box::new(random_vec_with_duplicates) as Box<Fn(usize) -> Vec<u32> + Sync>, "random_with_duplicates", ), ( Box::new(half_sorted) as Box<Fn(usize) -> Vec<u32> + Sync>, "half sorted, half reversed", ), */ ]; let algorithms: Vec<_> = iproduct!(policies.clone(), policies.clone()) .map(|(sort_policy, fuse_policy)| { ( Box::new(move |mut v: Vec<u32>| { adaptive_sort_raw_with_policies_swap_blocks(&mut v, sort_policy, fuse_policy) }) as Box<Fn(Vec<u32>) -> bool + Sync + Send>, format!("Swap {:?}/{:?}", sort_policy, fuse_policy), ) }) .collect(); for (generator_f, generator_name) in input_generators.iter() { println!(">>> {}", generator_name); for size in sizes.iter() { println!("Size: {}", size); let algo_results: Vec<_> = algorithms .iter() .map(|(algo_f, name)| { print!("{}: ", name); let res = times_by_processors( || generator_f(*size), |v| algo_f(v), iterations, threads.clone(), ); print!( "{}/{} copies\n", res.iter().map(|(_, b)| b).sum::<usize>(), iterations ); res }) .collect(); } } }
lone()); } (va, vb) } fn average_times<INPUT: Sized, I: Fn() -> INPUT, F: Fn(INPUT) -> bool>( init_fn: I, timed_fn: F, iterations: usize, ) -> (f64, usize) { let mut ve = Vec::new(); for _ in 0..iterations { ve.push(bench(&init_fn, &timed_fn)); } let v = tuple_to_vec(&ve); let time: f64 = v.0.iter().sum::<u64>() as f64 / iterations as f64; let states: usize = v.1.iter().map(|&b| if b { 1 } else { 0 }).sum(); (time, states) } fn times_by_processors< INPUT: Sized, I: Fn() -> INPUT + Send + Copy + Sync, F: Fn(INPUT) -> bool + Send + Copy + Sync, THREADS: IntoIterator<Item = usize>, >( init_fn: I, timed_fn: F, iterations: usize, threads_numbers: THREADS, ) -> Vec<(f64, usize)> { threads_numbers .into_iter() .map(move |threads| { let pool = ThreadPoolBuilder::new() .num_threads(threads) .build() .expect("building pool failed"); pool.install(|| average_times(init_fn, timed_fn, iterations)) }) .collect() } fn main() { let iterations = 100;
random
[ { "content": "/// compute a block size with the given function.\n\n/// this allows us to ensure we enforce important bounds on sizes.\n\nfn compute_size<F: Fn(usize) -> usize>(n: usize, sizing_function: F) -> usize {\n\n let p = current_num_threads();\n\n std::cmp::max(min(n / (2 * p), sizing_function(n)), 1)\n\n}\n\n\n\npub(crate) fn schedule<F, RF>(\n\n input: F::Input,\n\n folder: &F,\n\n reduce_function: &RF,\n\n policy: Policy,\n\n) -> F::Output\n\nwhere\n\n F: Folder,\n\n RF: Fn(F::Output, F::Output) -> F::Output + Sync,\n\n{\n\n SEQUENCE.with(|s| {\n\n if *s.borrow() || input.base_length() == 1 {\n\n schedule_sequential(input, folder)\n\n } else {\n\n let block_size = match policy {\n", "file_path": "src/scheduling.rs", "rank": 0, "score": 217437.99240528225 }, { "content": "fn schedule_sequential<F: Folder>(input: F::Input, folder: &F) -> F::Output {\n\n let len = input.base_length();\n\n let (io, i) = folder.fold(folder.identity(), input, len);\n\n folder.to_output(io, i)\n\n}\n\n\n", "file_path": "src/scheduling.rs", "rank": 1, "score": 200868.57518108323 }, { "content": "pub fn vec_gen(size: u64) -> Vec<Token> {\n\n (1..size)\n\n .enumerate()\n\n .map(|(pos, num)| {\n\n if pos % 2 == 0 {\n\n Token::Num(num % 5)\n\n } else {\n\n let temp: u32 = rand::random();\n\n if temp % 100_000 == 0 {\n\n Token::Add\n\n } else {\n\n Token::Mult\n\n }\n\n }\n\n })\n\n .collect()\n\n}\n\n\n", "file_path": "src/algorithms/infix_solvers.rs", "rank": 2, "score": 164533.73750045226 }, { "content": "fn blocks_sizes(c: &mut Criterion) {\n\n let sizes = vec![\n\n 60, 80, 100, 120, 140, 160, 200, 500, 800, 2000, 4000, 6000, 10000,\n\n ];\n\n let sizes = sizes\n\n .into_iter()\n\n .map(|block_size| INPUT_SIZE / block_size)\n\n .collect::<Vec<_>>();\n\n let pool = rayon::ThreadPoolBuilder::new()\n\n .num_threads(1)\n\n .build()\n\n .expect(\"pool build failed\");\n\n c.bench(\n\n \"initial size\",\n\n ParameterizedBenchmark::new(\n\n \"adaptive\",\n\n move |b, block_size| {\n\n b.iter(|| {\n\n pool.install(|| {\n\n assert_eq!(\n", "file_path": "benches/initial_size.rs", "rank": 3, "score": 160333.61744899134 }, { "content": "fn filter_collect_adaptive(c: &mut Criterion) {\n\n c.bench_function(\"adaptive filter_collect(size=10_000_000)\", move |b| {\n\n b.iter(|| {\n\n (0..10_000_000)\n\n .into_adapt_iter()\n\n .filter(|&x| x * 2 == 0)\n\n .collect::<Vec<usize>>()\n\n })\n\n });\n\n c.bench_function(\"sequential filter_collect(size=10_000_000)\", move |b| {\n\n b.iter(|| {\n\n (0..10_000_000)\n\n .filter(|&x| x * 2 == 0)\n\n .collect::<Vec<usize>>()\n\n })\n\n });\n\n}\n\n\n\ncriterion_group!(benches, filter_collect_adaptive);\n\ncriterion_main!(benches);\n", "file_path": "benches/filter_collect.rs", "rank": 4, "score": 157736.00332082322 }, { "content": "fn schedule_join_context_max_size<F, RF>(\n\n input: F::Input,\n\n folder: &F,\n\n reduce_function: &RF,\n\n min_size: usize,\n\n max_size: usize,\n\n) -> F::Output\n\nwhere\n\n F: Folder,\n\n RF: Fn(F::Output, F::Output) -> F::Output + Sync,\n\n{\n\n let len = input.base_length();\n\n if len <= min_size {\n\n schedule_sequential(input, folder)\n\n } else {\n\n let (i1, i2) = input.divide();\n\n let (r1, r2) = rayon::join_context(\n\n |_| schedule_join_context_max_size(i1, folder, reduce_function, min_size, max_size),\n\n |c| {\n\n if len > max_size || c.migrated() {\n", "file_path": "src/scheduling.rs", "rank": 5, "score": 148955.1921553869 }, { "content": "/// Fuse contiguous slices together back into one.\n\n/// This panics if slices are not contiguous.\n\npub fn fuse_slices<'a, 'b, 'c: 'a + 'b, T: 'c>(s1: &'a mut [T], s2: &'b mut [T]) -> &'c mut [T] {\n\n let ptr1 = s1.as_mut_ptr();\n\n unsafe {\n\n assert_eq!(ptr1.add(s1.len()) as *const T, s2.as_ptr());\n\n std::slice::from_raw_parts_mut(ptr1, s1.len() + s2.len())\n\n }\n\n}\n\n\n", "file_path": "src/utils.rs", "rank": 6, "score": 142520.14274409798 }, { "content": "/// by default, max block size is sqrt(n)\n\nfn default_max_block_size(n: usize) -> usize {\n\n ((n as f64).sqrt() * 10.0f64).ceil() as usize\n\n}\n\n\n", "file_path": "src/scheduling.rs", "rank": 7, "score": 129518.70202177296 }, { "content": "/// by default, min block size is log(n)\n\nfn default_min_block_size(n: usize) -> usize {\n\n let power = ((n as f64 / (n as f64).log(2.0) + 1.0).log(2.0) - 1.0).floor();\n\n ((n as f64) / (2.0f64.powi(power as i32 + 1) - 1.0)).ceil() as usize\n\n}\n\n\n", "file_path": "src/scheduling.rs", "rank": 8, "score": 129518.70202177296 }, { "content": "fn schedule_join<F, RF>(\n\n input: F::Input,\n\n folder: &F,\n\n reduce_function: &RF,\n\n block_size: usize,\n\n) -> F::Output\n\nwhere\n\n F: Folder,\n\n RF: Fn(F::Output, F::Output) -> F::Output + Sync,\n\n{\n\n let len = input.base_length();\n\n if len <= block_size {\n\n schedule_sequential(input, folder)\n\n } else {\n\n let (i1, i2) = input.divide();\n\n let (r1, r2) = rayon::join(\n\n || schedule_join(i1, folder, reduce_function, block_size),\n\n || schedule_join(i2, folder, reduce_function, block_size),\n\n );\n\n reduce_function(r1, r2)\n\n }\n\n}\n\n\n", "file_path": "src/scheduling.rs", "rank": 9, "score": 122285.49094246927 }, { "content": "//TODO: we could maybe avoid code duplication between master and slave with a dummy head of the\n\n//list for the master\n\nfn slave_work<'scope, F>(\n\n scope: &Scope<'scope>,\n\n node: AtomicLink<(Option<F::Output>, Option<F::Input>)>,\n\n slave_folder: &'scope F,\n\n min_size: usize,\n\n max_size: usize,\n\n) where\n\n F: Folder + 'scope + Send,\n\n F::Input: DivisibleIntoBlocks + 'scope,\n\n{\n\n let mut input = node.take().unwrap().1.unwrap();\n\n let mut o2 = slave_folder.identity();\n\n loop {\n\n let sender = spawn_stealing_task(scope, slave_folder, min_size, max_size);\n\n // let's work sequentially until stolen\n\n match powers(min_size)\n\n .take_while(|&p| p < max_size)\n\n .chain(repeat(max_size))\n\n .take_while(|_| !sender.receiver_is_waiting() && !node.requested())\n\n .try_fold((o2, input), |(output2, input), size| {\n", "file_path": "src/scheduling.rs", "rank": 10, "score": 122285.49094246927 }, { "content": "fn schedule_depjoin<F, RF>(\n\n input: F::Input,\n\n folder: &F,\n\n reduce_function: &RF,\n\n block_size: usize,\n\n) -> F::Output\n\nwhere\n\n F: Folder,\n\n RF: Fn(F::Output, F::Output) -> F::Output + Sync,\n\n{\n\n let len = input.base_length();\n\n if len <= block_size {\n\n schedule_sequential(input, folder)\n\n } else {\n\n let (i1, i2) = input.divide();\n\n depjoin(\n\n || schedule_depjoin(i1, folder, reduce_function, block_size),\n\n || schedule_depjoin(i2, folder, reduce_function, block_size),\n\n reduce_function,\n\n )\n\n }\n\n}\n\n\n", "file_path": "src/scheduling.rs", "rank": 11, "score": 122285.49094246927 }, { "content": "fn schedule_join_context<F, RF>(\n\n input: F::Input,\n\n folder: &F,\n\n reduce_function: &RF,\n\n block_size: usize,\n\n) -> F::Output\n\nwhere\n\n F: Folder,\n\n RF: Fn(F::Output, F::Output) -> F::Output + Sync,\n\n{\n\n let len = input.base_length();\n\n if len <= block_size {\n\n schedule_sequential(input, folder)\n\n } else {\n\n let (i1, i2) = input.divide();\n\n let (r1, r2) = rayon::join_context(\n\n |_| schedule_join_context(i1, folder, reduce_function, block_size),\n\n |c| {\n\n if c.migrated() {\n\n schedule_join_context(i2, folder, reduce_function, block_size)\n\n } else {\n\n schedule_sequential(i2, folder)\n\n }\n\n },\n\n );\n\n reduce_function(r1, r2)\n\n }\n\n}\n\n\n", "file_path": "src/scheduling.rs", "rank": 12, "score": 120327.80361726608 }, { "content": "fn spawn_stealing_task<'scope, F>(\n\n scope: &Scope<'scope>,\n\n slave_folder: &'scope F,\n\n min_size: usize,\n\n max_size: usize,\n\n) -> SmallSender<AtomicLink<(Option<F::Output>, Option<F::Input>)>>\n\nwhere\n\n F: Folder + 'scope + Send,\n\n F::Input: DivisibleIntoBlocks + 'scope,\n\n{\n\n let (sender, receiver) = small_channel();\n\n scope.spawn(move |s| {\n\n let stolen_input: Option<AtomicLink<(Option<F::Output>, Option<F::Input>)>>;\n\n #[cfg(feature = \"logs\")]\n\n {\n\n stolen_input = rayon_logs::subgraph(\"slave wait\", 1, || receiver.recv());\n\n }\n\n #[cfg(not(feature = \"logs\"))]\n\n {\n\n stolen_input = receiver.recv();\n\n }\n\n if stolen_input.is_none() {\n\n return;\n\n }\n\n slave_work(s, stolen_input.unwrap(), slave_folder, min_size, max_size)\n\n });\n\n sender\n\n}\n\n\n", "file_path": "src/scheduling.rs", "rank": 13, "score": 120327.80361726608 }, { "content": "fn prefix_adaptive(c: &mut Criterion) {\n\n let sizes = vec![10_000, 20_000, 50_000, 75_000, 100_000];\n\n c.bench(\n\n \"prefix (multiplying floats)\",\n\n ParameterizedBenchmark::new(\n\n \"adaptive\",\n\n |b, input_size| {\n\n b.iter_with_setup(\n\n || (0..*input_size).map(|_| 1.0).collect::<Vec<f64>>(),\n\n |mut v| {\n\n adaptive_prefix(&mut v, |a, b| *a * *b);\n\n },\n\n )\n\n },\n\n sizes,\n\n ).with_function(\"sequential\", |b, input_size| {\n\n b.iter_with_setup(\n\n || (0..*input_size).map(|_| 1.0).collect::<Vec<f64>>(),\n\n |mut v| {\n\n v.iter_mut().fold(1.0, |acc, x| {\n", "file_path": "benches/prefix.rs", "rank": 14, "score": 118937.4123886262 }, { "content": "fn schedule_rayon_join_context<F, RF>(\n\n input: F::Input,\n\n folder: &F,\n\n reduce_function: &RF,\n\n split_limit: usize,\n\n) -> F::Output\n\nwhere\n\n F: Folder,\n\n RF: Fn(F::Output, F::Output) -> F::Output + Sync,\n\n{\n\n if split_limit == 0 || input.base_length() == 1 {\n\n schedule_sequential(input, folder)\n\n } else {\n\n let (i1, i2) = input.divide();\n\n let (r1, r2) = rayon::join_context(\n\n |_| schedule_rayon_join_context(i1, folder, reduce_function, split_limit / 2),\n\n |c| {\n\n if c.migrated() {\n\n schedule_rayon_join_context(\n\n i2,\n", "file_path": "src/scheduling.rs", "rank": 15, "score": 118478.73398988118 }, { "content": "fn infix_solver_bench(c: &mut Criterion) {\n\n rayon::ThreadPoolBuilder::new()\n\n .num_threads(NUM_THREADS)\n\n .build_global()\n\n .expect(\"Rayon global pool initialisation failed\");\n\n c.bench_function(\"adaptive infix (size=100_000_000)\", |b| {\n\n b.iter_with_setup(\n\n || vec_gen(SIZE),\n\n |testin| {\n\n solver_adaptive(&testin, Default::default());\n\n testin\n\n },\n\n )\n\n });\n\n c.bench_function(\"parallel split infix (size=100_000_000)\", |b| {\n\n b.iter_with_setup(\n\n || vec_gen(SIZE),\n\n |testin| {\n\n solver_par_split(&testin);\n\n testin\n", "file_path": "benches/infix.rs", "rank": 16, "score": 116985.92203720522 }, { "content": "fn find_first_adaptive(c: &mut Criterion) {\n\n let sizes = vec![100_000, 200_000, 400_000, 600_000];\n\n c.bench(\n\n \"find first random element\",\n\n ParameterizedBenchmark::new(\n\n \"sequential\",\n\n |b, input_size| {\n\n b.iter_with_setup(\n\n || (0..*input_size).collect::<Vec<u32>>(),\n\n |v| {\n\n let target = rand::random::<u32>() % input_size;\n\n assert_eq!(v.iter().find(|&e| *e == target).cloned().unwrap(), target)\n\n },\n\n )\n\n },\n\n sizes,\n\n ).with_function(\"adaptive\", |b, input_size| {\n\n b.iter_with_setup(\n\n || (0..*input_size).collect::<Vec<u32>>(),\n\n |v| {\n", "file_path": "benches/find_first.rs", "rank": 17, "score": 115142.70555902085 }, { "content": "fn merge_sort_adaptive(c: &mut Criterion) {\n\n let sizes = vec![50_000, 100_000, 150_000, 262_144];\n\n c.bench(\n\n \"merge sort (random input)\",\n\n ParameterizedBenchmark::new(\n\n \"sequential\",\n\n |b, input_size| {\n\n b.iter_with_setup(\n\n || {\n\n (0..*input_size)\n\n .map(|_| rand::random())\n\n .collect::<Vec<u32>>()\n\n },\n\n |mut v| {\n\n v.sort();\n\n },\n\n )\n\n },\n\n sizes.clone(),\n\n )\n", "file_path": "benches/merge_sort.rs", "rank": 18, "score": 115142.70555902085 }, { "content": "fn schedule_adaptive<F, RF, MINSIZE, MAXSIZE>(\n\n input: F::Input,\n\n partial_output: F::IntermediateOutput,\n\n folder: &F,\n\n reduce_function: &RF,\n\n block_sizes: (MINSIZE, MAXSIZE),\n\n) -> F::Output\n\nwhere\n\n F: Folder,\n\n RF: Fn(F::Output, F::Output) -> F::Output + Sync,\n\n MINSIZE: Fn(usize) -> usize + Send + Copy,\n\n MAXSIZE: Fn(usize) -> usize + Send + Copy,\n\n{\n\n let size = input.base_length();\n\n if size <= compute_size(size, block_sizes.0) {\n\n let (io, i) = folder.fold(partial_output, input, size);\n\n folder.to_output(io, i)\n\n } else {\n\n let stolen = &AtomicBool::new(false);\n\n let (sender, receiver) = small_channel();\n", "file_path": "src/scheduling.rs", "rank": 19, "score": 113774.8596917623 }, { "content": "fn master_work<'scope, F, O1, FOLD1>(\n\n scope: &Scope<'scope>,\n\n init: O1,\n\n input: F::Input,\n\n fold: &FOLD1,\n\n slave_folder: &'scope F,\n\n stolen_stuffs: &AtomicList<(Option<F::Output>, Option<F::Input>)>,\n\n min_size: usize,\n\n max_size: usize,\n\n) -> O1\n\nwhere\n\n F: Folder + 'scope + Send,\n\n F::Input: DivisibleIntoBlocks + 'scope,\n\n O1: Send,\n\n FOLD1: Fn(O1, F::Input, usize) -> (O1, F::Input),\n\n{\n\n let mut input = input;\n\n let mut current_output = init;\n\n loop {\n\n let sender = spawn_stealing_task(scope, slave_folder, min_size, max_size);\n", "file_path": "src/scheduling.rs", "rank": 20, "score": 113774.8596917623 }, { "content": "pub fn solver_seq(inp: &[Token]) -> u64 {\n\n let t = inp.iter().fold((0, 1), |tup, elem| match elem {\n\n Token::Num(i) => (tup.0, tup.1 * *i),\n\n Token::Mult => tup,\n\n Token::Add => (tup.0 + tup.1, 1),\n\n });\n\n t.0 + t.1\n\n}\n\n\n", "file_path": "src/algorithms/infix_solvers.rs", "rank": 21, "score": 110705.75969594622 }, { "content": "//Not logged by rayon_logs.\n\npub fn solver_par_split(inp: &[Token]) -> u64 {\n\n #[cfg(feature = \"logs\")]\n\n use crate::real_rayon::prelude::ParallelSlice;\n\n inp.as_parallel_slice()\n\n .par_split(|tok| *tok == Token::Add)\n\n .map(|slice| {\n\n // It's tricky because rayon-logs does not support par_split right now\n\n #[cfg(not(feature = \"logs\"))]\n\n let iterator = slice.into_par_iter();\n\n #[cfg(feature = \"logs\")]\n\n let iterator = crate::real_rayon::prelude::IntoParallelIterator::into_par_iter(slice);\n\n iterator\n\n .filter_map(|tok| match tok {\n\n Token::Mult | Token::Add => None,\n\n Token::Num(i) => Some(i),\n\n })\n\n .product::<u64>()\n\n })\n\n .sum::<u64>()\n\n}\n", "file_path": "src/algorithms/infix_solvers.rs", "rank": 22, "score": 109131.25902546887 }, { "content": "//Logged\n\npub fn solver_par_fold(inp: &[Token]) -> u64 {\n\n inp.into_par_iter()\n\n .fold(PartialProducts::new, |mut products, tok| match *tok {\n\n Token::Num(i) => {\n\n products.update_product(i);\n\n products\n\n }\n\n Token::Add => {\n\n products.append_product();\n\n products\n\n }\n\n Token::Mult => products,\n\n })\n\n .reduce(PartialProducts::new, |left, right| left.fuse(&right))\n\n .evaluate()\n\n}\n\n\n", "file_path": "src/algorithms/infix_solvers.rs", "rank": 23, "score": 109131.25902546887 }, { "content": "/// Execute potentially `oper_a` and `oper_b` in parallel like in a standard join.\n\n/// Then the last closure to finish calls `oper_c` on both results.\n\npub fn depjoin<A, B, C, RA, RB, RC>(oper_a: A, oper_b: B, oper_c: C) -> RC\n\nwhere\n\n A: FnOnce() -> RA + Send,\n\n B: FnOnce() -> RB + Send,\n\n C: FnOnce(RA, RB) -> RC + Send,\n\n RA: Send,\n\n RB: Send,\n\n RC: Send,\n\n{\n\n let done = &AtomicBool::new(false);\n\n let (sender_a, receiver_a) = small_channel();\n\n let (sender_b, receiver_b) = small_channel();\n\n let results = rayon::join(\n\n move || {\n\n let ra = oper_a();\n\n let we_are_last = done.swap(true, Ordering::SeqCst);\n\n if we_are_last {\n\n let rb = receiver_a.recv().expect(\"receiving result failed\");\n\n Some(oper_c(ra, rb))\n\n } else {\n", "file_path": "src/lib.rs", "rank": 24, "score": 107332.81552185446 }, { "content": "pub fn solver_adaptive(inp: &[Token], policy: Policy) -> u64 {\n\n inp.into_adapt_iter()\n\n .with_policy(policy)\n\n .fold(PartialProducts::new, |mut p, token| {\n\n match token {\n\n Token::Num(i) => p.update_product(*i),\n\n Token::Add => p.append_product(),\n\n Token::Mult => {}\n\n }\n\n p\n\n })\n\n .reduce(|left, right| left.fuse(&right))\n\n .evaluate()\n\n}\n", "file_path": "src/algorithms/infix_solvers.rs", "rank": 25, "score": 103668.94868840175 }, { "content": "fn main() {\n\n let v: Vec<usize> = (0..10_000_000)\n\n .into_adapt_iter()\n\n .filter(|&x| x % 2 == 0)\n\n .collect();\n\n let v_seq: Vec<usize> = (0..10_000_000).filter(|&x| x % 2 == 0).collect();\n\n assert_eq!(v, v_seq);\n\n}\n", "file_path": "examples/collect.rs", "rank": 26, "score": 101116.7570151387 }, { "content": "/// Run adaptive prefix algortihm on given slice.\n\n/// Each element is replaced by folding with op since beginning of the slice.\n\n/// It requires an associative operation.\n\n///\n\n/// # Example\n\n///\n\n/// ```\n\n/// use rayon_adaptive::adaptive_prefix;\n\n/// let mut v = vec![1u32; 100_000];\n\n/// adaptive_prefix(&mut v, |e1, e2| e1 + e2);\n\n/// let count: Vec<u32> = (1..=100_000).collect();\n\n/// assert_eq!(v, count);\n\n/// ```\n\npub fn adaptive_prefix<T, O>(v: &mut [T], op: O)\n\nwhere\n\n T: Send + Sync + Clone,\n\n O: Fn(&T, &T) -> T + Sync,\n\n{\n\n let input = EdibleSliceMut::new(v);\n\n input\n\n .work(|mut slice, limit| {\n\n let c = {\n\n let mut elements = slice.iter_mut().take(limit);\n\n let mut c = elements.next().unwrap().clone();\n\n for e in elements {\n\n *e = op(e, &c);\n\n c = e.clone();\n\n }\n\n c\n\n };\n\n // pre-update next one\n\n if let Some(e) = slice.peek() {\n\n *e = op(e, &c);\n", "file_path": "src/algorithms/prefix.rs", "rank": 27, "score": 99284.00936763245 }, { "content": "fn update<T, O>(slice: &mut [T], increment: T, op: &O)\n\nwhere\n\n T: Send + Sync + Clone,\n\n O: Fn(&T, &T) -> T + Sync,\n\n{\n\n slice.into_adapt_iter().for_each(|e| *e = op(e, &increment))\n\n}\n", "file_path": "src/algorithms/prefix.rs", "rank": 28, "score": 96373.4951752373 }, { "content": "#[inline]\n\nfn raw_capacity(len: usize) -> usize {\n\n try_raw_capacity(len).expect(\"raw_capacity overflow\")\n\n}\n\n\n\npub(crate) unsafe fn extract_hashmap_slices<'a, K: Eq + Hash, V, S: BuildHasher>(\n\n table: &'a HashMap<K, V, S>,\n\n) -> (&'a [HashUint], &'a [(K, V)]) {\n\n let capacity = raw_capacity(table.capacity());\n\n let i: std::collections::hash_map::Iter<'a, K, V> = table.iter();\n\n // I feel like satan himself\n\n let i = transmute::<std::collections::hash_map::Iter<'a, K, V>, Iter<'a, K, V>>(i);\n\n let hashes = std::slice::from_raw_parts(i.iter.raw.hash_start, capacity);\n\n let pairs = std::slice::from_raw_parts(i.iter.raw.pair_start, capacity);\n\n (hashes, pairs)\n\n}\n\n\n\npub(crate) unsafe fn extract_hashset_slices<'a, K: Eq + Hash, S: BuildHasher>(\n\n table: &'a HashSet<K, S>,\n\n) -> (&'a [HashUint], &'a [(K, ())]) {\n\n let capacity = raw_capacity(table.capacity());\n\n let i: std::collections::hash_set::Iter<'a, K> = table.iter();\n\n // I feel like satan himself\n\n let i = transmute::<std::collections::hash_set::Iter<'a, K>, HashSetIter<'a, K>>(i);\n\n let hashes = std::slice::from_raw_parts(i.iter.inner.iter.raw.hash_start, capacity);\n\n let pairs = std::slice::from_raw_parts(i.iter.inner.iter.raw.pair_start, capacity);\n\n (hashes, pairs)\n\n}\n", "file_path": "src/iter/hash/toxic.rs", "rank": 29, "score": 94796.94996194058 }, { "content": "/// Sort given slice using an adaptive version of merge sort.\n\n/// For now we require Copy on T.\n\n/// Sort is stable.\n\n///\n\n/// # Examples\n\n///\n\n/// ```\n\n/// use rayon_adaptive::adaptive_sort;\n\n/// use rand::{thread_rng, Rng};\n\n///\n\n/// let v: Vec<u32> = (0..100_000).collect();\n\n/// let mut inverted_v: Vec<u32> = (0..100_000).rev().collect();\n\n/// let mut rng = thread_rng();\n\n/// let mut random_v: Vec<u32> = (0..100_000).collect();\n\n/// rng.shuffle(&mut random_v);\n\n/// adaptive_sort(&mut random_v);\n\n/// adaptive_sort(&mut inverted_v);\n\n/// assert_eq!(v, inverted_v);\n\n/// assert_eq!(v, random_v);\n\n/// ```\n\npub fn adaptive_sort<T: Ord + Copy + Send + Sync>(slice: &mut [T]) {\n\n let mut tmp_slice1 = Vec::with_capacity(slice.base_length());\n\n let mut tmp_slice2 = Vec::with_capacity(slice.base_length());\n\n unsafe {\n\n tmp_slice1.set_len(slice.base_length());\n\n tmp_slice2.set_len(slice.base_length());\n\n }\n\n let slice_len = slice.len();\n\n let num_threads = rayon::current_num_threads();\n\n\n\n let slices = SortingSlices {\n\n s: vec![slice, tmp_slice1.as_mut_slice(), tmp_slice2.as_mut_slice()],\n\n i: 0,\n\n };\n\n\n\n let mut result_slices = slices\n\n .with_policy(Policy::DepJoin(slice_len / (2 * num_threads)))\n\n .map_reduce(\n\n |mut slices| {\n\n slices.s[slices.i].sort();\n", "file_path": "src/algorithms/merge_sort.rs", "rank": 30, "score": 93756.95188646807 }, { "content": "/// Sort given slice using an adaptive version of merge sort.\n\n/// For now we require Copy on T.\n\n/// Sort is stable.\n\n///\n\n/// # Examples\n\n///\n\n/// ```\n\n/// use rayon_adaptive::adaptive_sort_raw;\n\n/// use rand::{thread_rng, Rng};\n\n///\n\n/// let v: Vec<u32> = (0..100_000).collect();\n\n/// let mut inverted_v: Vec<u32> = (0..100_000).rev().collect();\n\n/// let mut rng = thread_rng();\n\n/// let mut random_v: Vec<u32> = (0..100_000).collect();\n\n/// rng.shuffle(&mut random_v);\n\n/// adaptive_sort_raw(&mut random_v);\n\n/// adaptive_sort_raw(&mut inverted_v);\n\n/// assert_eq!(v, inverted_v);\n\n/// assert_eq!(v, random_v);\n\n/// ```\n\npub fn adaptive_sort_raw<T: Ord + Copy + Send + Sync>(slice: &mut [T]) {\n\n let mut tmp_slice1 = Vec::with_capacity(slice.base_length());\n\n let mut tmp_slice2 = Vec::with_capacity(slice.base_length());\n\n unsafe {\n\n tmp_slice1.set_len(slice.base_length());\n\n tmp_slice2.set_len(slice.base_length());\n\n }\n\n\n\n let slice_len = slice.len();\n\n let num_threads = rayon::current_num_threads();\n\n\n\n let slices = SortingSlices {\n\n s: vec![slice, tmp_slice1.as_mut_slice(), tmp_slice2.as_mut_slice()],\n\n i: 0,\n\n };\n\n\n\n let mut result_slices = slices\n\n .with_policy(Policy::DepJoin(slice_len / (num_threads * 2)))\n\n .map_reduce(\n\n |mut slices| {\n", "file_path": "src/algorithms/merge_sort_raw.rs", "rank": 31, "score": 91355.02498269346 }, { "content": "/// Sort given slice using an adaptive version of merge sort.\n\n/// For now we require Copy on T.\n\n/// Sort is stable.\n\n///\n\n/// # Examples\n\n///\n\n/// ```\n\n/// use rayon_adaptive::adaptive_sort_raw;\n\n/// use rand::{thread_rng, Rng};\n\n///\n\n/// let v: Vec<u32> = (0..100_000).collect();\n\n/// let mut inverted_v: Vec<u32> = (0..100_000).rev().collect();\n\n/// let mut rng = thread_rng();\n\n/// let mut random_v: Vec<u32> = (0..100_000).collect();\n\n/// rng.shuffle(&mut random_v);\n\n/// adaptive_sort_raw(&mut random_v);\n\n/// adaptive_sort_raw(&mut inverted_v);\n\n/// assert_eq!(v, inverted_v);\n\n/// assert_eq!(v, random_v);\n\n/// ```\n\npub fn adaptive_sort_no_copy<T: Ord + Copy + Send + Sync>(slice: &mut [T]) {\n\n let mut tmp_slice1 = Vec::with_capacity(slice.base_length());\n\n let mut tmp_slice2 = Vec::with_capacity(slice.base_length());\n\n unsafe {\n\n tmp_slice1.set_len(slice.base_length());\n\n tmp_slice2.set_len(slice.base_length());\n\n }\n\n\n\n let slice_len = slice.len();\n\n let num_threads = rayon::current_num_threads();\n\n\n\n let slices = SortingSlices {\n\n s: vec![slice, tmp_slice1.as_mut_slice(), tmp_slice2.as_mut_slice()],\n\n i: 0,\n\n depth: 0,\n\n };\n\n\n\n let mut result_slices = slices\n\n .with_policy(Policy::DepJoin(slice_len / (num_threads * 2)))\n\n .map_reduce(\n", "file_path": "src/algorithms/merge_sort_no_copy.rs", "rank": 32, "score": 91355.02498269346 }, { "content": "#[inline]\n\nfn try_raw_capacity(len: usize) -> Option<usize> {\n\n if len == 0 {\n\n Some(0)\n\n } else {\n\n // 1. Account for loading: `raw_capacity >= len * 1.1`.\n\n // 2. Ensure it is a power of two.\n\n // 3. Ensure it is at least the minimum size.\n\n len.checked_mul(11)\n\n .map(|l| l / 10)\n\n .and_then(|l| l.checked_next_power_of_two())\n\n .map(|l| max(MIN_NONZERO_RAW_CAPACITY, l))\n\n }\n\n}\n\n\n", "file_path": "src/iter/hash/toxic.rs", "rank": 33, "score": 90830.20130183159 }, { "content": "/// Sort given slice using an adaptive version of merge sort.\n\n/// For now we require Copy on T.\n\n/// Sort is stable.\n\n///\n\n/// # Examples\n\n///\n\n/// ```\n\n/// use rayon_adaptive::adaptive_sort_raw;\n\n/// use rand::{thread_rng, Rng};\n\n///\n\n/// let v: Vec<u32> = (0..100_000).collect();\n\n/// let mut inverted_v: Vec<u32> = (0..100_000).rev().collect();\n\n/// let mut rng = thread_rng();\n\n/// let mut random_v: Vec<u32> = (0..100_000).collect();\n\n/// rng.shuffle(&mut random_v);\n\n/// adaptive_sort_raw(&mut random_v);\n\n/// adaptive_sort_raw(&mut inverted_v);\n\n/// assert_eq!(v, inverted_v);\n\n/// assert_eq!(v, random_v);\n\n/// ```\n\npub fn adaptive_sort_raw_cut<T: Ord + Copy + Send + Sync>(slice: &mut [T]) {\n\n let mut tmp_slice1 = Vec::with_capacity(slice.base_length());\n\n let mut tmp_slice2 = Vec::with_capacity(slice.base_length());\n\n unsafe {\n\n tmp_slice1.set_len(slice.base_length());\n\n tmp_slice2.set_len(slice.base_length());\n\n }\n\n\n\n let slice_len = slice.len();\n\n let num_threads = rayon::current_num_threads();\n\n\n\n let slices = SortingSlices {\n\n s: vec![slice, tmp_slice1.as_mut_slice(), tmp_slice2.as_mut_slice()],\n\n i: 0,\n\n block_size: 1000,\n\n };\n\n\n\n let mut result_slices = slices\n\n .with_policy(Policy::DepJoin(slice_len / (num_threads * 2)))\n\n .map_reduce(\n", "file_path": "src/algorithms/merge_sort_raw_cut.rs", "rank": 34, "score": 89157.51846441616 }, { "content": "/// Sort given slice using an adaptive version of merge sort.\n\n/// For now we require Copy on T.\n\n/// Sort is stable.\n\n///\n\n/// # Examples\n\n///\n\n/// ```\n\n/// use rayon_adaptive::adaptive_sort_raw;\n\n/// use rand::{thread_rng, Rng};\n\n///\n\n/// let v: Vec<u32> = (0..100_000).collect();\n\n/// let mut inverted_v: Vec<u32> = (0..100_000).rev().collect();\n\n/// let mut rng = thread_rng();\n\n/// let mut random_v: Vec<u32> = (0..100_000).collect();\n\n/// rng.shuffle(&mut random_v);\n\n/// adaptive_sort_raw(&mut random_v);\n\n/// adaptive_sort_raw(&mut inverted_v);\n\n/// assert_eq!(v, inverted_v);\n\n/// assert_eq!(v, random_v);\n\n/// ```\n\npub fn adaptive_sort_raw_logs<T: Ord + Copy + Send + Sync>(slice: &mut [T]) {\n\n let mut tmp_slice1 = Vec::with_capacity(slice.base_length());\n\n let mut tmp_slice2 = Vec::with_capacity(slice.base_length());\n\n unsafe {\n\n tmp_slice1.set_len(slice.base_length());\n\n tmp_slice2.set_len(slice.base_length());\n\n }\n\n\n\n let slice_len = slice.len();\n\n let num_threads = rayon::current_num_threads();\n\n\n\n let slices = SortingSlices {\n\n s: vec![slice, tmp_slice1.as_mut_slice(), tmp_slice2.as_mut_slice()],\n\n i: 0,\n\n };\n\n\n\n let mut result_slices = slices\n\n .with_policy(Policy::DepJoin(slice_len / (num_threads * 2)))\n\n .map_reduce(\n\n |mut slices| {\n", "file_path": "src/algorithms/merge_sort_raw_logs.rs", "rank": 35, "score": 89157.51846441616 }, { "content": "/// iterate on starting_value * 2**i\n\npub fn powers(starting_value: usize) -> impl Iterator<Item = usize> {\n\n (0..).scan(starting_value, |state, _| {\n\n *state *= 2;\n\n Some(*state)\n\n })\n\n}\n\n\n\npub struct AbortingDivisible<'a, I> {\n\n pub real_content: I,\n\n pub abort: &'a AtomicBool,\n\n}\n\n\n\nimpl<'a, I: Divisible> Divisible for AbortingDivisible<'a, I> {\n\n type Power = I::Power;\n\n fn base_length(&self) -> usize {\n\n if self.abort.load(Ordering::Relaxed) {\n\n 0\n\n } else {\n\n self.real_content.base_length()\n\n }\n", "file_path": "src/utils.rs", "rank": 36, "score": 88352.4328180535 }, { "content": "/// Sort given slice using an adaptive version of merge sort.\n\n/// For now we require Copy on T.\n\n/// Sort is stable.\n\n///\n\n/// # Examples\n\n///\n\n/// ```\n\n/// use rayon_adaptive::adaptive_sort_raw;\n\n/// use rand::{thread_rng, Rng};\n\n///\n\n/// let v: Vec<u32> = (0..100_000).collect();\n\n/// let mut inverted_v: Vec<u32> = (0..100_000).rev().collect();\n\n/// let mut rng = thread_rng();\n\n/// let mut random_v: Vec<u32> = (0..100_000).collect();\n\n/// rng.shuffle(&mut random_v);\n\n/// adaptive_sort_raw(&mut random_v);\n\n/// adaptive_sort_raw(&mut inverted_v);\n\n/// assert_eq!(v, inverted_v);\n\n/// assert_eq!(v, random_v);\n\n/// ```\n\npub fn adaptive_sort_raw_swap_blocks<T: Ord + Copy + Send + Sync>(slice: &mut [T]) {\n\n let mut tmp_slice1 = Vec::with_capacity(slice.base_length());\n\n let mut tmp_slice2 = Vec::with_capacity(slice.base_length());\n\n unsafe {\n\n tmp_slice1.set_len(slice.base_length());\n\n tmp_slice2.set_len(slice.base_length());\n\n }\n\n\n\n let slice_len = slice.len();\n\n let num_threads = rayon::current_num_threads();\n\n\n\n let slices = SortingSlices {\n\n s: vec![slice, tmp_slice1.as_mut_slice(), tmp_slice2.as_mut_slice()],\n\n i: 0,\n\n };\n\n\n\n let mut result_slices = slices\n\n .with_policy(Policy::DepJoin(slice_len / (num_threads * 2)))\n\n .map_reduce(\n\n |mut slices| {\n", "file_path": "src/algorithms/merge_sort_swap_blocks.rs", "rank": 37, "score": 88127.3696811398 }, { "content": "/// Sort given slice using an adaptive version of merge sort.\n\n/// For now we require Copy on T.\n\n/// Sort is stable.\n\n///\n\n/// # Examples\n\n///\n\n/// ```\n\n/// use rayon_adaptive::adaptive_sort_raw;\n\n/// use rand::{thread_rng, Rng};\n\n///\n\n/// let v: Vec<u32> = (0..100_000).collect();\n\n/// let mut inverted_v: Vec<u32> = (0..100_000).rev().collect();\n\n/// let mut rng = thread_rng();\n\n/// let mut random_v: Vec<u32> = (0..100_000).collect();\n\n/// rng.shuffle(&mut random_v);\n\n/// adaptive_sort_raw(&mut random_v);\n\n/// adaptive_sort_raw(&mut inverted_v);\n\n/// assert_eq!(v, inverted_v);\n\n/// assert_eq!(v, random_v);\n\n/// ```\n\npub fn adaptive_sort_raw_cut_ceil<T: Ord + Copy + Send + Sync>(slice: &mut [T]) {\n\n let mut tmp_slice1 = Vec::with_capacity(slice.base_length());\n\n let mut tmp_slice2 = Vec::with_capacity(slice.base_length());\n\n unsafe {\n\n tmp_slice1.set_len(slice.base_length());\n\n tmp_slice2.set_len(slice.base_length());\n\n }\n\n\n\n let slice_len = slice.len();\n\n let num_threads = rayon::current_num_threads();\n\n\n\n let slices = SortingSlices {\n\n s: vec![slice, tmp_slice1.as_mut_slice(), tmp_slice2.as_mut_slice()],\n\n i: 0,\n\n };\n\n\n\n let mut result_slices = slices\n\n .with_policy(Policy::DepJoin(slice_len / (num_threads * 2)))\n\n .map_reduce(\n\n |mut slices| {\n", "file_path": "src/algorithms/merge_sort_raw_cut_ceil.rs", "rank": 38, "score": 87139.22723869457 }, { "content": "/// Sort given slice using an adaptive version of merge sort.\n\n/// For now we require Copy on T.\n\n/// Sort is stable.\n\n///\n\n/// # Examples\n\n///\n\n/// ```\n\n/// use rayon_adaptive::adaptive_sort_raw;\n\n/// use rand::{thread_rng, Rng};\n\n///\n\n/// let v: Vec<u32> = (0..100_000).collect();\n\n/// let mut inverted_v: Vec<u32> = (0..100_000).rev().collect();\n\n/// let mut rng = thread_rng();\n\n/// let mut random_v: Vec<u32> = (0..100_000).collect();\n\n/// rng.shuffle(&mut random_v);\n\n/// adaptive_sort_raw(&mut random_v);\n\n/// adaptive_sort_raw(&mut inverted_v);\n\n/// assert_eq!(v, inverted_v);\n\n/// assert_eq!(v, random_v);\n\n/// ```\n\npub fn adaptive_sort_raw_cut_floor<T: Ord + Copy + Send + Sync>(slice: &mut [T]) {\n\n let mut tmp_slice1 = Vec::with_capacity(slice.base_length());\n\n let mut tmp_slice2 = Vec::with_capacity(slice.base_length());\n\n unsafe {\n\n tmp_slice1.set_len(slice.base_length());\n\n tmp_slice2.set_len(slice.base_length());\n\n }\n\n\n\n let slice_len = slice.len();\n\n let num_threads = rayon::current_num_threads();\n\n\n\n let slices = SortingSlices {\n\n s: vec![slice, tmp_slice1.as_mut_slice(), tmp_slice2.as_mut_slice()],\n\n i: 0,\n\n };\n\n\n\n let mut result_slices = slices\n\n .with_policy(Policy::DepJoin(slice_len / (num_threads * 2)))\n\n .map_reduce(\n\n |mut slices| {\n", "file_path": "src/algorithms/merge_sort_raw_cut_floor.rs", "rank": 39, "score": 87139.22723869457 }, { "content": "fn fuse<T: Ord + Send + Sync + Copy>(left: &[T], right: &[T], output: &mut [T], policy: Policy) {\n\n let slices = FusionSlice {\n\n left: EdibleSlice::new(left),\n\n right: EdibleSlice::new(right),\n\n output: EdibleSliceMut::new(output),\n\n };\n\n\n\n slices\n\n .with_policy(policy)\n\n .partial_for_each(|mut slices, limit| {\n\n {\n\n if slices.left.base_length() > limit && slices.right.base_length() > limit {\n\n let mut left_i = slices.left.iter();\n\n let mut right_i = slices.right.iter();\n\n for o in slices.output.iter_mut().take(limit) {\n\n let go_left = left_i.peek() <= right_i.peek();\n\n *o = if go_left {\n\n *left_i.next().unwrap()\n\n } else {\n\n *right_i.next().unwrap()\n", "file_path": "src/algorithms/merge_sort.rs", "rank": 40, "score": 83099.34153204135 }, { "content": "fn fuse<T: Ord + Send + Sync + Copy>(left: &[T], right: &[T], output: &mut [T], policy: Policy) {\n\n let slices = FusionSlice {\n\n left: left,\n\n left_index: 0,\n\n right: right,\n\n right_index: 0,\n\n output: output,\n\n output_index: 0,\n\n };\n\n\n\n slices\n\n .with_policy(policy)\n\n .partial_for_each(|mut slices, limit| {\n\n {\n\n if (slices.left.len() - slices.left_index) > limit\n\n && (slices.right.len() - slices.right_index) > limit\n\n {\n\n for _ in 0..limit {\n\n let output_ref =\n\n unsafe { slices.output.get_unchecked_mut(slices.output_index) };\n", "file_path": "src/algorithms/merge_sort_no_copy.rs", "rank": 41, "score": 82069.192748765 }, { "content": "fn fuse<T: Ord + Send + Sync + Copy>(left: &[T], right: &[T], output: &mut [T], policy: Policy) {\n\n let slices = FusionSlice {\n\n left: left,\n\n left_index: 0,\n\n right: right,\n\n right_index: 0,\n\n output: output,\n\n output_index: 0,\n\n };\n\n\n\n slices\n\n .with_policy(policy)\n\n .partial_for_each(|mut slices, limit| {\n\n {\n\n if (slices.left.len() - slices.left_index) > limit\n\n && (slices.right.len() - slices.right_index) > limit\n\n {\n\n for _ in 0..limit {\n\n let output_ref =\n\n unsafe { slices.output.get_unchecked_mut(slices.output_index) };\n", "file_path": "src/algorithms/merge_sort_raw.rs", "rank": 42, "score": 82069.192748765 }, { "content": "fn fuse<T: Ord + Send + Sync + Copy>(left: &[T], right: &[T], output: &mut [T], policy: Policy) {\n\n let slices = FusionSlice {\n\n left: left,\n\n left_index: 0,\n\n right: right,\n\n right_index: 0,\n\n output: output,\n\n output_index: 0,\n\n };\n\n\n\n slices\n\n .with_policy(policy)\n\n .partial_for_each(|mut slices, limit| {\n\n {\n\n if (slices.left.len() - slices.left_index) > limit\n\n && (slices.right.len() - slices.right_index) > limit\n\n {\n\n for _ in 0..limit {\n\n let output_ref =\n\n unsafe { slices.output.get_unchecked_mut(slices.output_index) };\n", "file_path": "src/algorithms/merge_sort_swap_blocks.rs", "rank": 43, "score": 81081.05030631975 }, { "content": "fn fuse<T: Ord + Send + Sync + Copy>(left: &[T], right: &[T], output: &mut [T], policy: Policy) {\n\n let slices = FusionSlice {\n\n left: left,\n\n left_index: 0,\n\n right: right,\n\n right_index: 0,\n\n output: output,\n\n output_index: 0,\n\n };\n\n\n\n slices\n\n .with_policy(policy)\n\n .partial_for_each(|mut slices, limit| {\n\n {\n\n if (slices.left.len() - slices.left_index) > limit\n\n && (slices.right.len() - slices.right_index) > limit\n\n {\n\n for _ in 0..limit {\n\n let output_ref =\n\n unsafe { slices.output.get_unchecked_mut(slices.output_index) };\n", "file_path": "src/algorithms/merge_sort_raw_logs.rs", "rank": 44, "score": 81081.05030631975 }, { "content": "fn fuse<T: Ord + Send + Sync + Copy>(left: &[T], right: &[T], output: &mut [T], policy: Policy) {\n\n let slices = FusionSlice {\n\n left: left,\n\n left_index: 0,\n\n right: right,\n\n right_index: 0,\n\n output: output,\n\n output_index: 0,\n\n };\n\n\n\n slices\n\n .with_policy(policy)\n\n .partial_for_each(|mut slices, limit| {\n\n {\n\n if (slices.left.len() - slices.left_index) > limit\n\n && (slices.right.len() - slices.right_index) > limit\n\n {\n\n for _ in 0..limit {\n\n let output_ref =\n\n unsafe { slices.output.get_unchecked_mut(slices.output_index) };\n", "file_path": "src/algorithms/merge_sort_raw_cut.rs", "rank": 45, "score": 81081.05030631975 }, { "content": "fn fuse<T: Ord + Send + Sync + Copy>(left: &[T], right: &[T], output: &mut [T], policy: Policy) {\n\n let slices = FusionSlice {\n\n left: left,\n\n left_index: 0,\n\n right: right,\n\n right_index: 0,\n\n output: output,\n\n output_index: 0,\n\n };\n\n\n\n slices\n\n .with_policy(policy)\n\n .partial_for_each(|mut slices, limit| {\n\n {\n\n if (slices.left.len() - slices.left_index) > limit\n\n && (slices.right.len() - slices.right_index) > limit\n\n {\n\n for _ in 0..limit {\n\n let output_ref =\n\n unsafe { slices.output.get_unchecked_mut(slices.output_index) };\n", "file_path": "src/algorithms/merge_sort_raw_cut_ceil.rs", "rank": 46, "score": 80132.39620624148 }, { "content": "fn fuse<T: Ord + Send + Sync + Copy>(left: &[T], right: &[T], output: &mut [T], policy: Policy) {\n\n let slices = FusionSlice {\n\n left: left,\n\n left_index: 0,\n\n right: right,\n\n right_index: 0,\n\n output: output,\n\n output_index: 0,\n\n };\n\n\n\n slices\n\n .with_policy(policy)\n\n .partial_for_each(|mut slices, limit| {\n\n {\n\n if (slices.left.len() - slices.left_index) > limit\n\n && (slices.right.len() - slices.right_index) > limit\n\n {\n\n for _ in 0..limit {\n\n let output_ref =\n\n unsafe { slices.output.get_unchecked_mut(slices.output_index) };\n", "file_path": "src/algorithms/merge_sort_raw_cut_floor.rs", "rank": 47, "score": 80132.39620624148 }, { "content": "/// Cut sorted slice `slice` around start point, splitting around\n\n/// all values equal to value at start point.\n\n/// cost is O(log(|removed part size|))\n\nfn split_around<T: Eq>(slice: &[T], start: usize) -> (&[T], &[T], &[T]) {\n\n let low_slice = subslice_without_last_value(&slice[0..=start]);\n\n let high_slice = subslice_without_first_value(&slice[start..]);\n\n let equal_slice = &slice[low_slice.len()..slice.len() - high_slice.len()];\n\n (low_slice, equal_slice, high_slice)\n\n}\n\n\n", "file_path": "src/algorithms/merge_sort.rs", "rank": 48, "score": 71653.81216325013 }, { "content": "/// Cut sorted slice `slice` around start point, splitting around\n\n/// all values equal to value at start point.\n\n/// cost is O(log(|removed part size|))\n\nfn split_around<T: Eq>(slice: &[T], start: usize) -> (&[T], &[T], &[T]) {\n\n let low_slice = subslice_without_last_value(&slice[0..=start]);\n\n let high_slice = subslice_without_first_value(&slice[start..]);\n\n let equal_slice = &slice[low_slice.len()..slice.len() - high_slice.len()];\n\n (low_slice, equal_slice, high_slice)\n\n}\n\n\n", "file_path": "src/algorithms/merge_sort_raw.rs", "rank": 49, "score": 70424.29050314789 }, { "content": "/// Cut sorted slice `slice` around start point, splitting around\n\n/// all values equal to value at start point.\n\n/// cost is O(log(|removed part size|))\n\nfn split_around<T: Eq>(slice: &[T], start: usize) -> (&[T], &[T], &[T]) {\n\n let low_slice = subslice_without_last_value(&slice[0..=start]);\n\n let high_slice = subslice_without_first_value(&slice[start..]);\n\n let equal_slice = &slice[low_slice.len()..slice.len() - high_slice.len()];\n\n (low_slice, equal_slice, high_slice)\n\n}\n\n\n", "file_path": "src/algorithms/merge_sort_no_copy.rs", "rank": 50, "score": 70424.29050314789 }, { "content": "/// Cut sorted slice `slice` around start point, splitting around\n\n/// all values equal to value at start point.\n\n/// cost is O(log(|removed part size|))\n\nfn split_around<T: Eq>(slice: &[T], start: usize) -> (&[T], &[T], &[T]) {\n\n let low_slice = subslice_without_last_value(&slice[0..=start]);\n\n let high_slice = subslice_without_first_value(&slice[start..]);\n\n let equal_slice = &slice[low_slice.len()..slice.len() - high_slice.len()];\n\n (low_slice, equal_slice, high_slice)\n\n}\n\n\n", "file_path": "src/algorithms/merge_sort_raw_logs.rs", "rank": 51, "score": 69249.356873061 }, { "content": "/// Cut sorted slice `slice` around start point, splitting around\n\n/// all values equal to value at start point.\n\n/// cost is O(log(|removed part size|))\n\nfn split_around<T: Eq>(slice: &[T], start: usize) -> (&[T], &[T], &[T]) {\n\n let low_slice = subslice_without_last_value(&slice[0..=start]);\n\n let high_slice = subslice_without_first_value(&slice[start..]);\n\n let equal_slice = &slice[low_slice.len()..slice.len() - high_slice.len()];\n\n (low_slice, equal_slice, high_slice)\n\n}\n\n\n", "file_path": "src/algorithms/merge_sort_raw_cut.rs", "rank": 52, "score": 69249.356873061 }, { "content": "/// Cut sorted slice `slice` around start point, splitting around\n\n/// all values equal to value at start point.\n\n/// cost is O(log(|removed part size|))\n\nfn split_around<T: Eq>(slice: &[T], start: usize) -> (&[T], &[T], &[T]) {\n\n let low_slice = subslice_without_last_value(&slice[0..=start]);\n\n let high_slice = subslice_without_first_value(&slice[start..]);\n\n let equal_slice = &slice[low_slice.len()..slice.len() - high_slice.len()];\n\n (low_slice, equal_slice, high_slice)\n\n}\n\n\n", "file_path": "src/algorithms/merge_sort_swap_blocks.rs", "rank": 53, "score": 69249.356873061 }, { "content": "/// Cut sorted slice `slice` around start point, splitting around\n\n/// all values equal to value at start point.\n\n/// cost is O(log(|removed part size|))\n\nfn split_around<T: Eq>(slice: &[T], start: usize) -> (&[T], &[T], &[T]) {\n\n let low_slice = subslice_without_last_value(&slice[0..=start]);\n\n let high_slice = subslice_without_first_value(&slice[start..]);\n\n let equal_slice = &slice[low_slice.len()..slice.len() - high_slice.len()];\n\n (low_slice, equal_slice, high_slice)\n\n}\n\n\n", "file_path": "src/algorithms/merge_sort_raw_cut_floor.rs", "rank": 54, "score": 68125.45484095256 }, { "content": "/// Cut sorted slice `slice` around start point, splitting around\n\n/// all values equal to value at start point.\n\n/// cost is O(log(|removed part size|))\n\nfn split_around<T: Eq>(slice: &[T], start: usize) -> (&[T], &[T], &[T]) {\n\n let low_slice = subslice_without_last_value(&slice[0..=start]);\n\n let high_slice = subslice_without_first_value(&slice[start..]);\n\n let equal_slice = &slice[low_slice.len()..slice.len() - high_slice.len()];\n\n (low_slice, equal_slice, high_slice)\n\n}\n\n\n", "file_path": "src/algorithms/merge_sort_raw_cut_ceil.rs", "rank": 55, "score": 68125.45484095256 }, { "content": "// this file is expected to be run with the logs feature enabled:\n\n// cargo run --features logs --example max --release\n\nfn main() {\n\n let mut v: Vec<u32> = (0..SIZE).collect();\n\n let mut rng = rand::thread_rng();\n\n v.shuffle(&mut rng);\n\n let pool = ThreadPoolBuilder::new()\n\n .num_threads(2)\n\n .build()\n\n .expect(\"failed building pool\");\n\n #[cfg(features = \"logs\")]\n\n {\n\n pool.compare()\n\n .runs_number(500)\n\n // .attach_algorithm(\"truly sequential\", || {\n\n // assert_eq!(v.iter().max().cloned(), Some(SIZE - 1))\n\n // })\n\n // .attach_algorithm(\"sequential\", || {\n\n // assert_eq!(\n\n // v.into_adapt_iter()\n\n // .with_policy(Policy::Sequential)\n\n // .max()\n", "file_path": "examples/max.rs", "rank": 56, "score": 62646.59890659341 }, { "content": "fn main() {\n\n let v: Vec<u32> = (0..SIZE).collect();\n\n let mut rng = thread_rng();\n\n let mut random_v_0: Vec<u32> = (0..SIZE).collect();\n\n let mut random_v_1: Vec<u32> = (0..SIZE).collect();\n\n let mut random_v_2: Vec<u32> = (0..SIZE).collect();\n\n rng.shuffle(&mut random_v_0);\n\n rng.shuffle(&mut random_v_1);\n\n rng.shuffle(&mut random_v_2);\n\n //let mut inverted_v: Vec<u32> = (0..SIZE).rev().collect();\n\n #[cfg(not(feature = \"logs\"))]\n\n {\n\n adaptive_sort(&mut random_v_0);\n\n adaptive_sort_raw(&mut random_v_1);\n\n random_v_2.par_sort();\n\n assert_eq!(v, random_v_0);\n\n assert_eq!(v, random_v_1);\n\n assert_eq!(v, random_v_2);\n\n }\n\n #[cfg(feature = \"logs\")]\n", "file_path": "examples/bug.rs", "rank": 57, "score": 62646.59890659341 }, { "content": "fn main() {\n\n let v: Vec<u32> = (0..2_000_000).collect();\n\n\n\n let pool = ThreadPoolBuilder::new()\n\n .num_threads(2)\n\n .build()\n\n .expect(\"building pool failed\");\n\n\n\n let even_elements = pool.install(|| {\n\n let mut vecs = v\n\n .into_adapt_iter()\n\n .filter(|&e| *e % 2 == 0)\n\n .with_policy(Policy::Adaptive(20, 200_000))\n\n .fold(Vec::new, |mut v, e| {\n\n v.push(*e);\n\n v\n\n })\n\n .into_iter();\n\n let final_vec = vecs.next().unwrap();\n\n vecs.fold(final_vec, |mut f, v| {\n\n f.extend(v);\n\n f\n\n })\n\n });\n\n\n\n assert_eq!(even_elements.len(), 1_000_000);\n\n}\n", "file_path": "examples/fmr.rs", "rank": 58, "score": 62646.59890659341 }, { "content": "fn main() {\n\n let pool = ThreadPoolBuilder::new()\n\n .num_threads(2)\n\n .build()\n\n .expect(\"building pool failed\");\n\n let r = pool.install(|| {\n\n (0..100_000)\n\n .into_adapt_iter()\n\n .with_policy(Policy::Join(50_000))\n\n .find_any(|&x| x % 20_000 == 19_999)\n\n });\n\n println!(\"r: {:?}\", r);\n\n assert_eq!(r.unwrap() % 20_000, 19_999);\n\n}\n", "file_path": "examples/find_any.rs", "rank": 59, "score": 62646.59890659341 }, { "content": "fn main() {\n\n let s = \"hello world\";\n\n assert!(s.adapt_chars().all(|c| c != 'a'));\n\n}\n", "file_path": "examples/chars.rs", "rank": 60, "score": 62646.59890659341 }, { "content": "fn main() {\n\n let h: HashMap<u32, u32> = (0..1000).map(|i| (i, i + 1)).collect();\n\n let s: u32 = par_keys(&h).sum();\n\n assert_eq!(s, 500 * 999);\n\n let mut hash_set = HashSet::new();\n\n hash_set.insert(0);\n\n hash_set.insert(0);\n\n hash_set.insert(1);\n\n hash_set.insert(1);\n\n hash_set.insert(2);\n\n hash_set.insert(3);\n\n let my_vec: Vec<_> = par_elements(&hash_set)\n\n .filter(|index| **index > 0)\n\n .collect();\n\n println!(\"{:?}\", my_vec);\n\n}\n", "file_path": "examples/hashmap.rs", "rank": 61, "score": 62646.59890659341 }, { "content": "fn main() {\n\n let v: Vec<u32> = (0..10_000).collect();\n\n let s = v\n\n .into_adapt_iter()\n\n .fold(|| 0, |acc, x| acc + *x)\n\n .reduce(|a, b| a + b);\n\n assert_eq!(s, v.len() as u32 * (v.len() as u32 - 1) / 2);\n\n let s: usize = (0..10_000).into_adapt_iter().map(|x| x * 2).sum();\n\n assert_eq!(s, 10_000 * 9_999);\n\n let all_eq = (0..1000)\n\n .into_adapt_iter()\n\n .zip((0..1000).into_adapt_iter())\n\n .map(|(a, b)| a == b)\n\n .fold(|| true, |acc, t| if t { acc } else { false })\n\n .reduce(|a, b| a && b);\n\n assert!(all_eq);\n\n\n\n assert!((0..10_000).into_adapt_iter().any(|x| x == 2345));\n\n}\n", "file_path": "examples/iterators.rs", "rank": 62, "score": 62646.59890659341 }, { "content": "/// Abstract between Input and ParametrizedInput in order to avoid duplicated code.\n\npub trait AdaptiveRunner<I: Divisible, S: Iterator<Item = usize>>: Sized {\n\n /// Return input's base length.\n\n /// Useful for computing blocks sizes.\n\n fn input_length(&self) -> usize;\n\n /// Return input, policy and sizes iterator.\n\n fn input_policy_sizes(self) -> (I, Policy, S);\n\n}\n\n\n", "file_path": "src/policy.rs", "rank": 63, "score": 61033.7022101502 }, { "content": "/// split large array at midpoint and small array where needed for merge.\n\nfn merge_split<'a, T: Ord>(\n\n large: &'a [T],\n\n small: &'a [T],\n\n) -> ((&'a [T], &'a [T], &'a [T]), (&'a [T], &'a [T], &'a [T])) {\n\n let middle = large.len() / 2;\n\n let split_large = split_around(large, middle);\n\n let split_small = match small.binary_search(&large[middle]) {\n\n Ok(i) => split_around(small, i),\n\n Err(i) => {\n\n let (small1, small3) = small.split_at(i);\n\n (small1, &small[0..0], small3)\n\n }\n\n };\n\n (split_large, split_small)\n\n}\n\n\n", "file_path": "src/algorithms/merge_sort.rs", "rank": 64, "score": 53988.780092689325 }, { "content": "/// split large array at midpoint and small array where needed for merge.\n\nfn merge_split<'a, T: Ord>(\n\n large: &'a [T],\n\n small: &'a [T],\n\n) -> ((&'a [T], &'a [T], &'a [T]), (&'a [T], &'a [T], &'a [T])) {\n\n let middle = large.len() / 2;\n\n let split_large = split_around(large, middle);\n\n let split_small = match small.binary_search(&large[middle]) {\n\n Ok(i) => split_around(small, i),\n\n Err(i) => {\n\n let (small1, small3) = small.split_at(i);\n\n (small1, &small[0..0], small3)\n\n }\n\n };\n\n (split_large, split_small)\n\n}\n\n\n", "file_path": "src/algorithms/merge_sort_raw.rs", "rank": 65, "score": 53133.51648271911 }, { "content": "/// split large array at midpoint and small array where needed for merge.\n\nfn merge_split<'a, T: Ord>(\n\n large: &'a [T],\n\n small: &'a [T],\n\n) -> ((&'a [T], &'a [T], &'a [T]), (&'a [T], &'a [T], &'a [T])) {\n\n let middle = large.len() / 2;\n\n let split_large = split_around(large, middle);\n\n let split_small = match small.binary_search(&large[middle]) {\n\n Ok(i) => split_around(small, i),\n\n Err(i) => {\n\n let (small1, small3) = small.split_at(i);\n\n (small1, &small[0..0], small3)\n\n }\n\n };\n\n (split_large, split_small)\n\n}\n\n\n", "file_path": "src/algorithms/merge_sort_no_copy.rs", "rank": 66, "score": 53133.51648271911 }, { "content": "/// split large array at midpoint and small array where needed for merge.\n\nfn merge_split<'a, T: Ord>(\n\n large: &'a [T],\n\n small: &'a [T],\n\n) -> ((&'a [T], &'a [T], &'a [T]), (&'a [T], &'a [T], &'a [T])) {\n\n let middle = large.len() / 2;\n\n let split_large = split_around(large, middle);\n\n let split_small = match small.binary_search(&large[middle]) {\n\n Ok(i) => split_around(small, i),\n\n Err(i) => {\n\n let (small1, small3) = small.split_at(i);\n\n (small1, &small[0..0], small3)\n\n }\n\n };\n\n (split_large, split_small)\n\n}\n\n\n", "file_path": "src/algorithms/merge_sort_raw_logs.rs", "rank": 67, "score": 52323.21078714571 }, { "content": "/// split large array at midpoint and small array where needed for merge.\n\nfn merge_split<'a, T: Ord>(\n\n large: &'a [T],\n\n small: &'a [T],\n\n) -> ((&'a [T], &'a [T], &'a [T]), (&'a [T], &'a [T], &'a [T])) {\n\n let middle = large.len() / 2;\n\n let split_large = split_around(large, middle);\n\n let split_small = match small.binary_search(&large[middle]) {\n\n Ok(i) => split_around(small, i),\n\n Err(i) => {\n\n let (small1, small3) = small.split_at(i);\n\n (small1, &small[0..0], small3)\n\n }\n\n };\n\n (split_large, split_small)\n\n}\n\n\n", "file_path": "src/algorithms/merge_sort_swap_blocks.rs", "rank": 68, "score": 52323.21078714571 }, { "content": "/// split large array at midpoint and small array where needed for merge.\n\nfn merge_split<'a, T: Ord>(\n\n large: &'a [T],\n\n small: &'a [T],\n\n) -> ((&'a [T], &'a [T], &'a [T]), (&'a [T], &'a [T], &'a [T])) {\n\n let middle = large.len() / 2;\n\n let split_large = split_around(large, middle);\n\n let split_small = match small.binary_search(&large[middle]) {\n\n Ok(i) => split_around(small, i),\n\n Err(i) => {\n\n let (small1, small3) = small.split_at(i);\n\n (small1, &small[0..0], small3)\n\n }\n\n };\n\n (split_large, split_small)\n\n}\n\n\n", "file_path": "src/algorithms/merge_sort_raw_cut.rs", "rank": 69, "score": 52323.21078714571 }, { "content": "/// split large array at midpoint and small array where needed for merge.\n\nfn merge_split<'a, T: Ord>(\n\n large: &'a [T],\n\n small: &'a [T],\n\n) -> ((&'a [T], &'a [T], &'a [T]), (&'a [T], &'a [T], &'a [T])) {\n\n let middle = large.len() / 2;\n\n let split_large = split_around(large, middle);\n\n let split_small = match small.binary_search(&large[middle]) {\n\n Ok(i) => split_around(small, i),\n\n Err(i) => {\n\n let (small1, small3) = small.split_at(i);\n\n (small1, &small[0..0], small3)\n\n }\n\n };\n\n (split_large, split_small)\n\n}\n\n\n", "file_path": "src/algorithms/merge_sort_raw_cut_ceil.rs", "rank": 70, "score": 51554.40889400763 }, { "content": "/// split large array at midpoint and small array where needed for merge.\n\nfn merge_split<'a, T: Ord>(\n\n large: &'a [T],\n\n small: &'a [T],\n\n) -> ((&'a [T], &'a [T], &'a [T]), (&'a [T], &'a [T], &'a [T])) {\n\n let middle = large.len() / 2;\n\n let split_large = split_around(large, middle);\n\n let split_small = match small.binary_search(&large[middle]) {\n\n Ok(i) => split_around(small, i),\n\n Err(i) => {\n\n let (small1, small3) = small.split_at(i);\n\n (small1, &small[0..0], small3)\n\n }\n\n };\n\n (split_large, split_small)\n\n}\n\n\n", "file_path": "src/algorithms/merge_sort_raw_cut_floor.rs", "rank": 71, "score": 51554.40889400763 }, { "content": "/// find subslice without first value in given sorted slice.\n\nfn subslice_without_first_value<T: Eq>(slice: &[T]) -> &[T] {\n\n match slice.first() {\n\n Some(target) => {\n\n let searching_range_end = repeat(())\n\n .scan(1, |acc, _| {\n\n *acc *= 2;\n\n Some(*acc)\n\n }) // iterate on all powers of 2\n\n .take_while(|&i| i < slice.len())\n\n .find(|&i| unsafe { slice.get_unchecked(i) != target })\n\n .unwrap_or_else(|| slice.len());\n\n\n\n let index = slice[..searching_range_end]\n\n .binary_search_by(|x| {\n\n if x.eq(target) {\n\n std::cmp::Ordering::Less\n\n } else {\n\n std::cmp::Ordering::Greater\n\n }\n\n })\n\n .unwrap_err();\n\n &slice[index..]\n\n }\n\n None => slice,\n\n }\n\n}\n\n\n", "file_path": "src/algorithms/merge_sort.rs", "rank": 72, "score": 48256.59485138829 }, { "content": "/// find subslice without last value in given sorted slice.\n\nfn subslice_without_last_value<T: Eq>(slice: &[T]) -> &[T] {\n\n match slice.split_last() {\n\n Some((target, slice)) => {\n\n let searching_range_start = repeat(())\n\n .scan(1, |acc, _| {\n\n *acc *= 2;\n\n Some(*acc)\n\n }) // iterate on all powers of 2\n\n .take_while(|&i| i < slice.len())\n\n .map(|i| slice.len() - i) // go farther and farther from end of slice\n\n .find(|&i| unsafe { slice.get_unchecked(i) != target })\n\n .unwrap_or(0);\n\n\n\n let index = slice[searching_range_start..]\n\n .binary_search_by(|x| {\n\n if x.eq(target) {\n\n std::cmp::Ordering::Greater\n\n } else {\n\n std::cmp::Ordering::Less\n\n }\n\n })\n\n .unwrap_err();\n\n &slice[0..(searching_range_start + index)]\n\n }\n\n None => slice,\n\n }\n\n}\n\n\n", "file_path": "src/algorithms/merge_sort.rs", "rank": 73, "score": 48256.59485138829 }, { "content": "/// find subslice without last value in given sorted slice.\n\nfn subslice_without_last_value<T: Eq>(slice: &[T]) -> &[T] {\n\n match slice.split_last() {\n\n Some((target, slice)) => {\n\n let searching_range_start = repeat(())\n\n .scan(1, |acc, _| {\n\n *acc *= 2;\n\n Some(*acc)\n\n }) // iterate on all powers of 2\n\n .take_while(|&i| i < slice.len())\n\n .map(|i| slice.len() - i) // go farther and farther from end of slice\n\n .find(|&i| unsafe { slice.get_unchecked(i) != target })\n\n .unwrap_or(0);\n\n\n\n let index = slice[searching_range_start..]\n\n .binary_search_by(|x| {\n\n if x.eq(target) {\n\n std::cmp::Ordering::Greater\n\n } else {\n\n std::cmp::Ordering::Less\n\n }\n\n })\n\n .unwrap_err();\n\n &slice[0..(searching_range_start + index)]\n\n }\n\n None => slice,\n\n }\n\n}\n\n\n", "file_path": "src/algorithms/merge_sort_raw.rs", "rank": 74, "score": 47594.8255975669 }, { "content": "/// find subslice without last value in given sorted slice.\n\nfn subslice_without_last_value<T: Eq>(slice: &[T]) -> &[T] {\n\n match slice.split_last() {\n\n Some((target, slice)) => {\n\n let searching_range_start = repeat(())\n\n .scan(1, |acc, _| {\n\n *acc *= 2;\n\n Some(*acc)\n\n }) // iterate on all powers of 2\n\n .take_while(|&i| i < slice.len())\n\n .map(|i| slice.len() - i) // go farther and farther from end of slice\n\n .find(|&i| unsafe { slice.get_unchecked(i) != target })\n\n .unwrap_or(0);\n\n\n\n let index = slice[searching_range_start..]\n\n .binary_search_by(|x| {\n\n if x.eq(target) {\n\n std::cmp::Ordering::Greater\n\n } else {\n\n std::cmp::Ordering::Less\n\n }\n\n })\n\n .unwrap_err();\n\n &slice[0..(searching_range_start + index)]\n\n }\n\n None => slice,\n\n }\n\n}\n\n\n", "file_path": "src/algorithms/merge_sort_no_copy.rs", "rank": 75, "score": 47594.8255975669 }, { "content": "/// find subslice without first value in given sorted slice.\n\nfn subslice_without_first_value<T: Eq>(slice: &[T]) -> &[T] {\n\n match slice.first() {\n\n Some(target) => {\n\n let searching_range_end = repeat(())\n\n .scan(1, |acc, _| {\n\n *acc *= 2;\n\n Some(*acc)\n\n }) // iterate on all powers of 2\n\n .take_while(|&i| i < slice.len())\n\n .find(|&i| unsafe { slice.get_unchecked(i) != target })\n\n .unwrap_or_else(|| slice.len());\n\n\n\n let index = slice[..searching_range_end]\n\n .binary_search_by(|x| {\n\n if x.eq(target) {\n\n std::cmp::Ordering::Less\n\n } else {\n\n std::cmp::Ordering::Greater\n\n }\n\n })\n\n .unwrap_err();\n\n &slice[index..]\n\n }\n\n None => slice,\n\n }\n\n}\n\n\n", "file_path": "src/algorithms/merge_sort_raw.rs", "rank": 76, "score": 47594.8255975669 }, { "content": "/// find subslice without first value in given sorted slice.\n\nfn subslice_without_first_value<T: Eq>(slice: &[T]) -> &[T] {\n\n match slice.first() {\n\n Some(target) => {\n\n let searching_range_end = repeat(())\n\n .scan(1, |acc, _| {\n\n *acc *= 2;\n\n Some(*acc)\n\n }) // iterate on all powers of 2\n\n .take_while(|&i| i < slice.len())\n\n .find(|&i| unsafe { slice.get_unchecked(i) != target })\n\n .unwrap_or_else(|| slice.len());\n\n\n\n let index = slice[..searching_range_end]\n\n .binary_search_by(|x| {\n\n if x.eq(target) {\n\n std::cmp::Ordering::Less\n\n } else {\n\n std::cmp::Ordering::Greater\n\n }\n\n })\n\n .unwrap_err();\n\n &slice[index..]\n\n }\n\n None => slice,\n\n }\n\n}\n\n\n", "file_path": "src/algorithms/merge_sort_no_copy.rs", "rank": 77, "score": 47594.8255975669 }, { "content": "/// find subslice without first value in given sorted slice.\n\nfn subslice_without_first_value<T: Eq>(slice: &[T]) -> &[T] {\n\n match slice.first() {\n\n Some(target) => {\n\n let searching_range_end = repeat(())\n\n .scan(1, |acc, _| {\n\n *acc *= 2;\n\n Some(*acc)\n\n }) // iterate on all powers of 2\n\n .take_while(|&i| i < slice.len())\n\n .find(|&i| unsafe { slice.get_unchecked(i) != target })\n\n .unwrap_or_else(|| slice.len());\n\n\n\n let index = slice[..searching_range_end]\n\n .binary_search_by(|x| {\n\n if x.eq(target) {\n\n std::cmp::Ordering::Less\n\n } else {\n\n std::cmp::Ordering::Greater\n\n }\n\n })\n\n .unwrap_err();\n\n &slice[index..]\n\n }\n\n None => slice,\n\n }\n\n}\n\n\n", "file_path": "src/algorithms/merge_sort_raw_cut.rs", "rank": 78, "score": 46963.80248886025 }, { "content": "/// find subslice without first value in given sorted slice.\n\nfn subslice_without_first_value<T: Eq>(slice: &[T]) -> &[T] {\n\n match slice.first() {\n\n Some(target) => {\n\n let searching_range_end = repeat(())\n\n .scan(1, |acc, _| {\n\n *acc *= 2;\n\n Some(*acc)\n\n }) // iterate on all powers of 2\n\n .take_while(|&i| i < slice.len())\n\n .find(|&i| unsafe { slice.get_unchecked(i) != target })\n\n .unwrap_or_else(|| slice.len());\n\n\n\n let index = slice[..searching_range_end]\n\n .binary_search_by(|x| {\n\n if x.eq(target) {\n\n std::cmp::Ordering::Less\n\n } else {\n\n std::cmp::Ordering::Greater\n\n }\n\n })\n\n .unwrap_err();\n\n &slice[index..]\n\n }\n\n None => slice,\n\n }\n\n}\n\n\n", "file_path": "src/algorithms/merge_sort_raw_logs.rs", "rank": 79, "score": 46963.80248886025 }, { "content": "/// find subslice without last value in given sorted slice.\n\nfn subslice_without_last_value<T: Eq>(slice: &[T]) -> &[T] {\n\n match slice.split_last() {\n\n Some((target, slice)) => {\n\n let searching_range_start = repeat(())\n\n .scan(1, |acc, _| {\n\n *acc *= 2;\n\n Some(*acc)\n\n }) // iterate on all powers of 2\n\n .take_while(|&i| i < slice.len())\n\n .map(|i| slice.len() - i) // go farther and farther from end of slice\n\n .find(|&i| unsafe { slice.get_unchecked(i) != target })\n\n .unwrap_or(0);\n\n\n\n let index = slice[searching_range_start..]\n\n .binary_search_by(|x| {\n\n if x.eq(target) {\n\n std::cmp::Ordering::Greater\n\n } else {\n\n std::cmp::Ordering::Less\n\n }\n\n })\n\n .unwrap_err();\n\n &slice[0..(searching_range_start + index)]\n\n }\n\n None => slice,\n\n }\n\n}\n\n\n", "file_path": "src/algorithms/merge_sort_raw_logs.rs", "rank": 80, "score": 46963.80248886025 }, { "content": "/// find subslice without last value in given sorted slice.\n\nfn subslice_without_last_value<T: Eq>(slice: &[T]) -> &[T] {\n\n match slice.split_last() {\n\n Some((target, slice)) => {\n\n let searching_range_start = repeat(())\n\n .scan(1, |acc, _| {\n\n *acc *= 2;\n\n Some(*acc)\n\n }) // iterate on all powers of 2\n\n .take_while(|&i| i < slice.len())\n\n .map(|i| slice.len() - i) // go farther and farther from end of slice\n\n .find(|&i| unsafe { slice.get_unchecked(i) != target })\n\n .unwrap_or(0);\n\n\n\n let index = slice[searching_range_start..]\n\n .binary_search_by(|x| {\n\n if x.eq(target) {\n\n std::cmp::Ordering::Greater\n\n } else {\n\n std::cmp::Ordering::Less\n\n }\n\n })\n\n .unwrap_err();\n\n &slice[0..(searching_range_start + index)]\n\n }\n\n None => slice,\n\n }\n\n}\n\n\n", "file_path": "src/algorithms/merge_sort_swap_blocks.rs", "rank": 81, "score": 46963.80248886025 }, { "content": "/// find subslice without first value in given sorted slice.\n\nfn subslice_without_first_value<T: Eq>(slice: &[T]) -> &[T] {\n\n match slice.first() {\n\n Some(target) => {\n\n let searching_range_end = repeat(())\n\n .scan(1, |acc, _| {\n\n *acc *= 2;\n\n Some(*acc)\n\n }) // iterate on all powers of 2\n\n .take_while(|&i| i < slice.len())\n\n .find(|&i| unsafe { slice.get_unchecked(i) != target })\n\n .unwrap_or_else(|| slice.len());\n\n\n\n let index = slice[..searching_range_end]\n\n .binary_search_by(|x| {\n\n if x.eq(target) {\n\n std::cmp::Ordering::Less\n\n } else {\n\n std::cmp::Ordering::Greater\n\n }\n\n })\n\n .unwrap_err();\n\n &slice[index..]\n\n }\n\n None => slice,\n\n }\n\n}\n\n\n", "file_path": "src/algorithms/merge_sort_swap_blocks.rs", "rank": 82, "score": 46963.80248886025 }, { "content": "/// find subslice without last value in given sorted slice.\n\nfn subslice_without_last_value<T: Eq>(slice: &[T]) -> &[T] {\n\n match slice.split_last() {\n\n Some((target, slice)) => {\n\n let searching_range_start = repeat(())\n\n .scan(1, |acc, _| {\n\n *acc *= 2;\n\n Some(*acc)\n\n }) // iterate on all powers of 2\n\n .take_while(|&i| i < slice.len())\n\n .map(|i| slice.len() - i) // go farther and farther from end of slice\n\n .find(|&i| unsafe { slice.get_unchecked(i) != target })\n\n .unwrap_or(0);\n\n\n\n let index = slice[searching_range_start..]\n\n .binary_search_by(|x| {\n\n if x.eq(target) {\n\n std::cmp::Ordering::Greater\n\n } else {\n\n std::cmp::Ordering::Less\n\n }\n\n })\n\n .unwrap_err();\n\n &slice[0..(searching_range_start + index)]\n\n }\n\n None => slice,\n\n }\n\n}\n\n\n", "file_path": "src/algorithms/merge_sort_raw_cut.rs", "rank": 83, "score": 46963.80248886025 }, { "content": "/// Communicate between threads like a channel but only once.\n\npub fn small_channel<T: Send>() -> (SmallSender<T>, SmallReceiver<T>) {\n\n let channel = Arc::new(SmallChannel::new());\n\n (\n\n SmallSender {\n\n channel: channel.clone(),\n\n },\n\n SmallReceiver { channel },\n\n )\n\n}\n\n\n\nimpl<T> SmallReceiver<T> {\n\n pub fn recv(self) -> Option<T> {\n\n self.channel.request.store(true, Ordering::Relaxed);\n\n let mut channel = self.channel;\n\n loop {\n\n let r = Arc::try_unwrap(channel);\n\n match r {\n\n Ok(c) => return c.data.into_inner(),\n\n Err(ac) => channel = ac,\n\n }\n", "file_path": "src/smallchannel.rs", "rank": 84, "score": 46674.09294284101 }, { "content": "/// find subslice without last value in given sorted slice.\n\nfn subslice_without_last_value<T: Eq>(slice: &[T]) -> &[T] {\n\n match slice.split_last() {\n\n Some((target, slice)) => {\n\n let searching_range_start = repeat(())\n\n .scan(1, |acc, _| {\n\n *acc *= 2;\n\n Some(*acc)\n\n }) // iterate on all powers of 2\n\n .take_while(|&i| i < slice.len())\n\n .map(|i| slice.len() - i) // go farther and farther from end of slice\n\n .find(|&i| unsafe { slice.get_unchecked(i) != target })\n\n .unwrap_or(0);\n\n\n\n let index = slice[searching_range_start..]\n\n .binary_search_by(|x| {\n\n if x.eq(target) {\n\n std::cmp::Ordering::Greater\n\n } else {\n\n std::cmp::Ordering::Less\n\n }\n\n })\n\n .unwrap_err();\n\n &slice[0..(searching_range_start + index)]\n\n }\n\n None => slice,\n\n }\n\n}\n\n\n", "file_path": "src/algorithms/merge_sort_raw_cut_floor.rs", "rank": 85, "score": 46361.43144828646 }, { "content": "/// find subslice without first value in given sorted slice.\n\nfn subslice_without_first_value<T: Eq>(slice: &[T]) -> &[T] {\n\n match slice.first() {\n\n Some(target) => {\n\n let searching_range_end = repeat(())\n\n .scan(1, |acc, _| {\n\n *acc *= 2;\n\n Some(*acc)\n\n }) // iterate on all powers of 2\n\n .take_while(|&i| i < slice.len())\n\n .find(|&i| unsafe { slice.get_unchecked(i) != target })\n\n .unwrap_or_else(|| slice.len());\n\n\n\n let index = slice[..searching_range_end]\n\n .binary_search_by(|x| {\n\n if x.eq(target) {\n\n std::cmp::Ordering::Less\n\n } else {\n\n std::cmp::Ordering::Greater\n\n }\n\n })\n\n .unwrap_err();\n\n &slice[index..]\n\n }\n\n None => slice,\n\n }\n\n}\n\n\n", "file_path": "src/algorithms/merge_sort_raw_cut_ceil.rs", "rank": 86, "score": 46361.43144828646 }, { "content": "/// find subslice without last value in given sorted slice.\n\nfn subslice_without_last_value<T: Eq>(slice: &[T]) -> &[T] {\n\n match slice.split_last() {\n\n Some((target, slice)) => {\n\n let searching_range_start = repeat(())\n\n .scan(1, |acc, _| {\n\n *acc *= 2;\n\n Some(*acc)\n\n }) // iterate on all powers of 2\n\n .take_while(|&i| i < slice.len())\n\n .map(|i| slice.len() - i) // go farther and farther from end of slice\n\n .find(|&i| unsafe { slice.get_unchecked(i) != target })\n\n .unwrap_or(0);\n\n\n\n let index = slice[searching_range_start..]\n\n .binary_search_by(|x| {\n\n if x.eq(target) {\n\n std::cmp::Ordering::Greater\n\n } else {\n\n std::cmp::Ordering::Less\n\n }\n\n })\n\n .unwrap_err();\n\n &slice[0..(searching_range_start + index)]\n\n }\n\n None => slice,\n\n }\n\n}\n\n\n", "file_path": "src/algorithms/merge_sort_raw_cut_ceil.rs", "rank": 87, "score": 46361.43144828646 }, { "content": "/// find subslice without first value in given sorted slice.\n\nfn subslice_without_first_value<T: Eq>(slice: &[T]) -> &[T] {\n\n match slice.first() {\n\n Some(target) => {\n\n let searching_range_end = repeat(())\n\n .scan(1, |acc, _| {\n\n *acc *= 2;\n\n Some(*acc)\n\n }) // iterate on all powers of 2\n\n .take_while(|&i| i < slice.len())\n\n .find(|&i| unsafe { slice.get_unchecked(i) != target })\n\n .unwrap_or_else(|| slice.len());\n\n\n\n let index = slice[..searching_range_end]\n\n .binary_search_by(|x| {\n\n if x.eq(target) {\n\n std::cmp::Ordering::Less\n\n } else {\n\n std::cmp::Ordering::Greater\n\n }\n\n })\n\n .unwrap_err();\n\n &slice[index..]\n\n }\n\n None => slice,\n\n }\n\n}\n\n\n", "file_path": "src/algorithms/merge_sort_raw_cut_floor.rs", "rank": 88, "score": 46361.43144828646 }, { "content": "pub fn adaptive_sort_raw_with_policies<T: Ord + Copy + Send + Sync>(\n\n slice: &mut [T],\n\n sort_policy: Policy,\n\n fuse_policy: Policy,\n\n) {\n\n let mut tmp_slice1 = Vec::with_capacity(slice.base_length());\n\n let mut tmp_slice2 = Vec::with_capacity(slice.base_length());\n\n unsafe {\n\n tmp_slice1.set_len(slice.base_length());\n\n tmp_slice2.set_len(slice.base_length());\n\n }\n\n\n\n let slice_len = slice.len();\n\n let num_threads = rayon::current_num_threads();\n\n\n\n let slices = SortingSlices {\n\n s: vec![slice, tmp_slice1.as_mut_slice(), tmp_slice2.as_mut_slice()],\n\n i: 0,\n\n };\n\n\n", "file_path": "src/algorithms/merge_sort_raw.rs", "rank": 89, "score": 46140.67340070594 }, { "content": "pub fn adaptive_sort_no_copy_with_policies<T: Ord + Copy + Send + Sync>(\n\n slice: &mut [T],\n\n sort_policy: Policy,\n\n fuse_policy: Policy,\n\n) {\n\n let mut tmp_slice1 = Vec::with_capacity(slice.base_length());\n\n let mut tmp_slice2 = Vec::with_capacity(slice.base_length());\n\n unsafe {\n\n tmp_slice1.set_len(slice.base_length());\n\n tmp_slice2.set_len(slice.base_length());\n\n }\n\n\n\n let slice_len = slice.len();\n\n\n\n let block_size = sort_policy.get_min_block_size();\n\n\n\n let new_block_size = match block_size {\n\n Some(s) => {\n\n let recursions =\n\n (((slice_len as f64) / (s as f64)).log2().ceil() / 2.0 - 0.5).ceil() as usize * 2;\n", "file_path": "src/algorithms/merge_sort_no_copy.rs", "rank": 90, "score": 46140.67340070594 }, { "content": "pub fn adaptive_sort_raw_logs_with_policies<T: Ord + Copy + Send + Sync>(\n\n slice: &mut [T],\n\n sort_policy: Policy,\n\n fuse_policy: Policy,\n\n) {\n\n let mut tmp_slice1 = Vec::with_capacity(slice.base_length());\n\n let mut tmp_slice2 = Vec::with_capacity(slice.base_length());\n\n unsafe {\n\n tmp_slice1.set_len(slice.base_length());\n\n tmp_slice2.set_len(slice.base_length());\n\n }\n\n\n\n let slice_len = slice.len();\n\n let num_threads = rayon::current_num_threads();\n\n\n\n let slices = SortingSlices {\n\n s: vec![slice, tmp_slice1.as_mut_slice(), tmp_slice2.as_mut_slice()],\n\n i: 0,\n\n };\n\n #[cfg(feature = \"perf\")]\n", "file_path": "src/algorithms/merge_sort_raw_logs.rs", "rank": 91, "score": 44962.67525544029 }, { "content": "pub fn adaptive_sort_raw_cut_with_policies<T: Ord + Copy + Send + Sync>(\n\n slice: &mut [T],\n\n sort_policy: Policy,\n\n fuse_policy: Policy,\n\n block_size: usize,\n\n) {\n\n let mut tmp_slice1 = Vec::with_capacity(slice.base_length());\n\n let mut tmp_slice2 = Vec::with_capacity(slice.base_length());\n\n unsafe {\n\n tmp_slice1.set_len(slice.base_length());\n\n tmp_slice2.set_len(slice.base_length());\n\n }\n\n\n\n let slices = SortingSlices {\n\n s: vec![slice, tmp_slice1.as_mut_slice(), tmp_slice2.as_mut_slice()],\n\n i: 0,\n\n block_size: block_size,\n\n };\n\n\n\n let mut result_slices = slices.with_policy(sort_policy).map_reduce(\n", "file_path": "src/algorithms/merge_sort_raw_cut.rs", "rank": 92, "score": 44962.67525544029 }, { "content": "pub fn adaptive_sort_raw_with_policies_swap_blocks<T: Ord + Copy + Send + Sync>(\n\n slice: &mut [T],\n\n sort_policy: Policy,\n\n fuse_policy: Policy,\n\n) {\n\n let mut tmp_slice1 = Vec::with_capacity(slice.base_length());\n\n let mut tmp_slice2 = Vec::with_capacity(slice.base_length());\n\n unsafe {\n\n tmp_slice1.set_len(slice.base_length());\n\n tmp_slice2.set_len(slice.base_length());\n\n }\n\n\n\n let slices = SortingSlices {\n\n s: vec![slice, tmp_slice1.as_mut_slice(), tmp_slice2.as_mut_slice()],\n\n i: 0,\n\n };\n\n\n\n let mut result_slices = slices.with_policy(sort_policy).map_reduce(\n\n |mut slices| {\n\n slices.s[slices.i].sort();\n", "file_path": "src/algorithms/merge_sort_swap_blocks.rs", "rank": 93, "score": 44412.04970848745 }, { "content": "pub fn par_elements<'a, K: Send + Sync + Eq + Hash, S: BuildHasher>(\n\n hashset: &'a HashSet<K, S>,\n\n) -> impl AdaptiveIterator<Item = &'a K> {\n\n let (hashes, pairs) = unsafe { extract_hashset_slices(hashset) };\n\n hashes\n\n .into_adapt_iter()\n\n .zip(pairs.into_adapt_iter())\n\n .filter(|&(&h, _)| h != 0)\n\n .map(|(_, &(ref k, _))| k)\n\n}\n", "file_path": "src/iter/hash/mod.rs", "rank": 94, "score": 44026.32394262777 }, { "content": "pub fn adaptive_sort_raw_cut_floor_with_policies<T: Ord + Copy + Send + Sync>(\n\n slice: &mut [T],\n\n sort_policy: Policy,\n\n fuse_policy: Policy,\n\n) {\n\n let mut tmp_slice1 = Vec::with_capacity(slice.base_length());\n\n let mut tmp_slice2 = Vec::with_capacity(slice.base_length());\n\n unsafe {\n\n tmp_slice1.set_len(slice.base_length());\n\n tmp_slice2.set_len(slice.base_length());\n\n }\n\n\n\n let slices = SortingSlices {\n\n s: vec![slice, tmp_slice1.as_mut_slice(), tmp_slice2.as_mut_slice()],\n\n i: 0,\n\n };\n\n\n\n let mut result_slices = slices.with_policy(sort_policy).map_reduce(\n\n |mut slices| {\n\n slices.s[slices.i].sort();\n", "file_path": "src/algorithms/merge_sort_raw_cut_floor.rs", "rank": 95, "score": 43884.83147955083 }, { "content": "pub fn adaptive_sort_raw_cut_ceil_with_policies<T: Ord + Copy + Send + Sync>(\n\n slice: &mut [T],\n\n sort_policy: Policy,\n\n fuse_policy: Policy,\n\n) {\n\n let mut tmp_slice1 = Vec::with_capacity(slice.base_length());\n\n let mut tmp_slice2 = Vec::with_capacity(slice.base_length());\n\n unsafe {\n\n tmp_slice1.set_len(slice.base_length());\n\n tmp_slice2.set_len(slice.base_length());\n\n }\n\n\n\n let slices = SortingSlices {\n\n s: vec![slice, tmp_slice1.as_mut_slice(), tmp_slice2.as_mut_slice()],\n\n i: 0,\n\n };\n\n\n\n let mut result_slices = slices.with_policy(sort_policy).map_reduce(\n\n |mut slices| {\n\n slices.s[slices.i].sort();\n", "file_path": "src/algorithms/merge_sort_raw_cut_ceil.rs", "rank": 96, "score": 43884.83147955083 }, { "content": "pub fn adaptive_sort_with_policies<T: Ord + Copy + Send + Sync + std::fmt::Debug>(\n\n slice: &mut [T],\n\n sort_policy: Policy,\n\n fuse_policy: Policy,\n\n) {\n\n let mut tmp_slice1 = Vec::with_capacity(slice.base_length());\n\n let mut tmp_slice2 = Vec::with_capacity(slice.base_length());\n\n unsafe {\n\n tmp_slice1.set_len(slice.base_length());\n\n tmp_slice2.set_len(slice.base_length());\n\n }\n\n\n\n let slices = SortingSlices {\n\n s: vec![slice, tmp_slice1.as_mut_slice(), tmp_slice2.as_mut_slice()],\n\n i: 0,\n\n };\n\n\n\n let mut result_slices = slices.with_policy(sort_policy).map_reduce(\n\n |mut slices| {\n\n slices.s[slices.i].sort();\n", "file_path": "src/algorithms/merge_sort.rs", "rank": 97, "score": 43423.952902053985 }, { "content": "pub fn par_keys<'a, K: Send + Sync + Eq + Hash, V: Send + Sync, S: BuildHasher>(\n\n hashmap: &'a HashMap<K, V, S>,\n\n) -> impl AdaptiveIterator<Item = &'a K> {\n\n let (hashes, pairs) = unsafe { extract_hashmap_slices(hashmap) };\n\n hashes\n\n .into_adapt_iter()\n\n .zip(pairs.into_adapt_iter())\n\n .filter(|&(&h, _)| h != 0)\n\n .map(|(_, &(ref k, _))| k)\n\n}\n\n\n", "file_path": "src/iter/hash/mod.rs", "rank": 98, "score": 40594.9548211153 }, { "content": "pub fn par_iter<'a, K: Send + Sync + Eq + Hash, V: Send + Sync, S: BuildHasher>(\n\n hashmap: &'a HashMap<K, V, S>,\n\n) -> impl AdaptiveIterator<Item = (&'a K, &'a V)> {\n\n let (hashes, pairs) = unsafe { extract_hashmap_slices(hashmap) };\n\n hashes\n\n .into_adapt_iter()\n\n .zip(pairs.into_adapt_iter())\n\n .filter(|&(&h, _)| h != 0)\n\n .map(|(_, &(ref k, ref v))| (k, v))\n\n}\n\n\n", "file_path": "src/iter/hash/mod.rs", "rank": 99, "score": 40594.9548211153 } ]
Rust
src/main.rs
igoyak/igrepper
6b5b66d4a6b45382d3e8f45571b111c5e0f4b9a4
extern crate clap; extern crate libc; use clap::{App, Arg}; use inotify::{Inotify, WatchMask}; use libc::close; use libc::open; use std::env; use crate::igrepper::igrepper; use file_reading::{SourceInput, SourceProducer}; mod file_reading; mod igrepper; const PARAMETER_ERROR: &str = "Data can only be passed by STDIN if no file parameter is specified"; const DEFAULT_EDITOR_COMMAND: [&str; 3] = ["vim", "-R", "-"]; fn main() { let matches = App::new("igrepper") .version("1.3.1") .about("The interactive grepper") .arg( Arg::with_name("regex") .short("e") .long("regex") .value_name("REGEX") .help("Regular expression to preload") .takes_value(true), ) .arg( Arg::with_name("context") .short("c") .long("context") .value_name("CONTEXT") .help("Print CONTEXT num of output context") .takes_value(true), ) .arg( Arg::with_name("file") .help("Sets the input file to use. If not set, reads from stdin.") .index(1), ) .arg( Arg::with_name("word") .short("w") .long("word") .conflicts_with("regex") .help("Preload the regular expression '\\S+'"), ) .arg( Arg::with_name("follow") .short("f") .long("follow") .requires("file") .help("Reload the file as it changes. Requires [file] to be set."), ) .get_matches(); let file_option = matches.value_of("file"); let is_tty = unsafe { libc::isatty(libc::STDIN_FILENO as i32) } != 0; let mut file_path: Option<&str> = None; let source_producer: SourceProducer = if is_tty { let path = file_option.unwrap_or_else(|| { eprintln!("{}", PARAMETER_ERROR); std::process::exit(1); }); file_path = Some(path); SourceProducer { input: SourceInput::FilePath(path.to_string()), } } else { if file_option != None { eprintln!("{}", PARAMETER_ERROR); std::process::exit(1); } let source = file_reading::read_source_from_stdin(); reopen_stdin(); SourceProducer { input: SourceInput::FullInput(source), } }; let context: u32 = match matches.value_of("context") { None => 0, Some(context_string) => context_string.parse::<u32>().unwrap(), }; let initial_regex = if matches.is_present("word") { Some("\\S+") } else { matches.value_of("regex") }; let inotify = if matches.is_present("follow") { let mut inotify = Inotify::init() .expect("Failed to monitor file changes, error while initializing inotify instance"); inotify .add_watch( file_path.unwrap(), WatchMask::MODIFY | WatchMask::CLOSE_WRITE, ) .expect("Failed to add file watch"); Some(inotify) } else { None }; let external_editor: Vec<String> = get_external_editor(); igrepper( source_producer, context, initial_regex, inotify, external_editor, ); } fn get_external_editor() -> Vec<String> { if let Ok(a) = env::var("IGREPPER_EDITOR") { let editor_command: Vec<String> = a.split_ascii_whitespace().map(|s| s.to_string()).collect(); if editor_command.len() > 0 { return editor_command; } } DEFAULT_EDITOR_COMMAND .iter() .map(|s| s.to_string()) .collect() } fn reopen_stdin() { unsafe { let close_returncode = close(0); assert_eq!(close_returncode, 0, "Failed to close stdin"); let ptr = "/dev/tty\0".as_ptr() as *const i8; let open_returncode = open(ptr, 0); assert_eq!(open_returncode, 0, "Failed to open /dev/tty"); } }
extern crate clap; extern crate libc; use clap::{App, Arg}; use inotify::{Inotify, WatchMask}; use libc::close; use libc::open; use std::env; use crate::igrepper::igrepper; use file_reading::{SourceInput, SourceProducer}; mod file_reading; mod igrepper; const PARAMETER_ERROR: &str = "Data can only be passed by STDIN if no file parameter is specified"; const DEFAULT_EDITOR_COMMAND: [&str; 3] = ["vim", "-R", "-"]
.requires("file") .help("Reload the file as it changes. Requires [file] to be set."), ) .get_matches(); let file_option = matches.value_of("file"); let is_tty = unsafe { libc::isatty(libc::STDIN_FILENO as i32) } != 0; let mut file_path: Option<&str> = None; let source_producer: SourceProducer = if is_tty { let path = file_option.unwrap_or_else(|| { eprintln!("{}", PARAMETER_ERROR); std::process::exit(1); }); file_path = Some(path); SourceProducer { input: SourceInput::FilePath(path.to_string()), } } else { if file_option != None { eprintln!("{}", PARAMETER_ERROR); std::process::exit(1); } let source = file_reading::read_source_from_stdin(); reopen_stdin(); SourceProducer { input: SourceInput::FullInput(source), } }; let context: u32 = match matches.value_of("context") { None => 0, Some(context_string) => context_string.parse::<u32>().unwrap(), }; let initial_regex = if matches.is_present("word") { Some("\\S+") } else { matches.value_of("regex") }; let inotify = if matches.is_present("follow") { let mut inotify = Inotify::init() .expect("Failed to monitor file changes, error while initializing inotify instance"); inotify .add_watch( file_path.unwrap(), WatchMask::MODIFY | WatchMask::CLOSE_WRITE, ) .expect("Failed to add file watch"); Some(inotify) } else { None }; let external_editor: Vec<String> = get_external_editor(); igrepper( source_producer, context, initial_regex, inotify, external_editor, ); } fn get_external_editor() -> Vec<String> { if let Ok(a) = env::var("IGREPPER_EDITOR") { let editor_command: Vec<String> = a.split_ascii_whitespace().map(|s| s.to_string()).collect(); if editor_command.len() > 0 { return editor_command; } } DEFAULT_EDITOR_COMMAND .iter() .map(|s| s.to_string()) .collect() } fn reopen_stdin() { unsafe { let close_returncode = close(0); assert_eq!(close_returncode, 0, "Failed to close stdin"); let ptr = "/dev/tty\0".as_ptr() as *const i8; let open_returncode = open(ptr, 0); assert_eq!(open_returncode, 0, "Failed to open /dev/tty"); } }
; fn main() { let matches = App::new("igrepper") .version("1.3.1") .about("The interactive grepper") .arg( Arg::with_name("regex") .short("e") .long("regex") .value_name("REGEX") .help("Regular expression to preload") .takes_value(true), ) .arg( Arg::with_name("context") .short("c") .long("context") .value_name("CONTEXT") .help("Print CONTEXT num of output context") .takes_value(true), ) .arg( Arg::with_name("file") .help("Sets the input file to use. If not set, reads from stdin.") .index(1), ) .arg( Arg::with_name("word") .short("w") .long("word") .conflicts_with("regex") .help("Preload the regular expression '\\S+'"), ) .arg( Arg::with_name("follow") .short("f") .long("follow")
random
[ { "content": "fn read_source_from_file(file_path: &str) -> io::Result<Vec<String>> {\n\n let file = File::open(file_path)?;\n\n let reader = BufReader::new(file);\n\n let source: Vec<String> = reader.lines().filter_map(|line| line.ok()).collect();\n\n Ok(source)\n\n}\n\n\n", "file_path": "src/file_reading.rs", "rank": 0, "score": 73434.62674204345 }, { "content": "fn pipe_to_external_editor(command_and_arguments: Vec<String>, string: &String) {\n\n let command_path = command_and_arguments.first().unwrap();\n\n let command_arguments = &command_and_arguments[1..command_and_arguments.len()];\n\n\n\n let mut command = Command::new(command_path);\n\n let mut command = &mut command;\n\n for arg in command_arguments {\n\n command = command.arg(arg);\n\n }\n\n let error_message = format!(\n\n \"Failed to pipe to external editor '{}'\",\n\n command_and_arguments.join(\" \")\n\n );\n\n let mut child_process = command.stdin(Stdio::piped()).spawn().expect(&error_message);\n\n\n\n child_process\n\n .stdin\n\n .as_mut()\n\n .expect(&error_message)\n\n .write_all(string.as_bytes())\n\n .expect(&error_message);\n\n child_process.wait().expect(&error_message);\n\n}\n\n\n", "file_path": "src/igrepper/mod.rs", "rank": 1, "score": 60142.73630156242 }, { "content": "pub fn read_source_from_stdin() -> Vec<String> {\n\n let stdin = io::stdin();\n\n stdin.lock().lines().filter_map(|line| line.ok()).collect()\n\n}\n", "file_path": "src/file_reading.rs", "rank": 2, "score": 53118.318184478936 }, { "content": "/// Trims a single output line to fit the screen.\n\n/// Includes color information for each character.\n\n///\n\n/// A line may contain multiple matches and non-matches, which\n\n/// may lie fully within, partially outside or fully outside the\n\n/// current screen.\n\n///\n\n/// mm__mmmmm__mm___mm\n\n/// ^ ^\n\n/// └────────┘\n\n/// content width\n\n///\n\nfn trim_and_colorize_line<F: FnMut(&str) -> u32>(\n\n line_with_match_ranges: &LineWithMatches,\n\n pager_x: u32,\n\n content_width: u32,\n\n mut get_color: F,\n\n) -> StringWithColorIndexOrBreakLine {\n\n let mut chars_to_drop = pager_x;\n\n let mut chars_to_take = content_width;\n\n let mut display_line: Vec<StringWithColorIndex> = vec![];\n\n let original_line = &line_with_match_ranges.line;\n\n let mut cell_width = 0;\n\n let mut end_of_last_match = 0u32;\n\n\n\n // Returns a substring that fits horizontally on screen\n\n let mut trim_horizontally = |mut s: String| -> String {\n\n // full drop\n\n if chars_to_drop > s.chars().count() as u32 {\n\n chars_to_drop -= s.chars().count() as u32;\n\n return String::from(\"\");\n\n }\n", "file_path": "src/igrepper/trimming.rs", "rank": 3, "score": 52598.262320158145 }, { "content": "/// Returns the same string where every tab is replaced with 1-4 spaces,\n\n/// depending on the horizontal position of the tab character.\n\n///\n\n/// Example, with a single tab character in different places:\n\n/// ┌────────┐\n\n/// │ aaaa│\n\n/// │a aaaa│\n\n/// │aa aaaa│\n\n/// │aaa aaaa│\n\n/// └────────┘\n\nfn replace_tabs_with_spaces(current_steps: u32, input_string: &str) -> String {\n\n let tabstop = 4;\n\n let mut steps_taken = current_steps;\n\n let mut output_string = String::from(\"\");\n\n for s in input_string.chars() {\n\n if s == '\\t' {\n\n let tab_width = tabstop - steps_taken % tabstop;\n\n for _ in 0..tab_width {\n\n output_string.push(' ');\n\n }\n\n steps_taken += tab_width;\n\n } else if s.len_utf8() > 1 {\n\n steps_taken += 1;\n\n output_string.push('_'); // replace unicode chars, until proper support\n\n } else {\n\n steps_taken += 1;\n\n output_string.push(s);\n\n }\n\n }\n\n output_string.clone()\n\n}\n\n\n", "file_path": "src/igrepper/trimming.rs", "rank": 4, "score": 49326.446907521466 }, { "content": "pub fn igrepper(\n\n source_producer: SourceProducer,\n\n initial_context: u32,\n\n initial_regex: Option<&str>,\n\n inotify_option: Option<Inotify>,\n\n external_editor: Vec<String>,\n\n) {\n\n // Setup ncurses\n\n initscr();\n\n raw();\n\n keypad(stdscr(), true);\n\n noecho();\n\n curs_set(CURSOR_VISIBILITY::CURSOR_INVISIBLE);\n\n\n\n start_color();\n\n init_pair(COLOR_PAIR_DEFAULT, 231i16, 232i16);\n\n init_pair(COLOR_PAIR_RED, 1i16, 232i16);\n\n init_pair(COLOR_PAIR_ACTIVE_INPUT, 1i16, 7i16);\n\n init_pair(COLOR_PAIR_INACTIVE_INPUT, 248i16, 232i16);\n\n init_pair(COLOR_PAIR_BORDER, 8i16, 232i16);\n", "file_path": "src/igrepper/mod.rs", "rank": 5, "score": 48181.37213464582 }, { "content": "mod types;\n\n\n\nuse crate::file_reading::SourceProducer;\n\nuse crate::igrepper::constants::*;\n\nuse crate::igrepper::core::Core;\n\nuse crate::igrepper::output_generator::Len;\n\nuse crate::igrepper::rendering::clear_screen;\n\nuse crate::igrepper::state::{SearchLine, State};\n\nuse inotify::Inotify;\n\n\n\npub enum Message {\n\n Character(i32),\n\n ReloadFile,\n\n ErrorMessage(String),\n\n}\n\n\n\npub enum CharRequesterMessage {\n\n ReadyToReceiveChar,\n\n Exit,\n\n}\n\n\n", "file_path": "src/igrepper/mod.rs", "rank": 6, "score": 47500.784924547166 }, { "content": "use ncurses::{\n\n curs_set, endwin, getch, getmaxyx, init_pair, initscr, keypad, noecho, raw, refresh,\n\n start_color, stdscr, CURSOR_VISIBILITY, KEY_BACKSPACE, KEY_DOWN, KEY_ENTER, KEY_LEFT,\n\n KEY_NPAGE, KEY_PPAGE, KEY_RESIZE, KEY_RIGHT, KEY_UP,\n\n};\n\nuse std::cmp;\n\nuse std::io::Write;\n\nuse std::process::{Command, Stdio};\n\nuse std::sync::mpsc;\n\nuse std::{char, thread};\n\n\n\nextern crate ncurses;\n\nextern crate regex;\n\n\n\nmod constants;\n\nmod core;\n\npub mod output_generator;\n\npub mod rendering;\n\npub mod state;\n\nmod trimming;\n", "file_path": "src/igrepper/mod.rs", "rank": 7, "score": 47497.61625806284 }, { "content": " ),\n\n string\n\n );\n\n}\n\n\n\n#[cfg(test)]\n\nmod tests {\n\n use super::*;\n\n use pretty_assertions::assert_eq;\n\n\n\n #[test]\n\n fn construct_grep_one_line() {\n\n let search_lines: Vec<SearchLine> =\n\n vec![SearchLine::new(\"foo\".to_string(), 0, false, false)];\n\n assert_eq!(\n\n construct_grep_line(&search_lines),\n\n \"grep --perl-regexp \\'(?i)foo\\'\"\n\n );\n\n }\n\n\n", "file_path": "src/igrepper/mod.rs", "rank": 8, "score": 47490.74497823195 }, { "content": " }\n\n clear_screen();\n\n endwin();\n\n copy_full_to_clipboard_from_string(&core.get_full_output_string(&state));\n\n break;\n\n }\n\n F1 | F1_2 => {\n\n if !state.regex_valid() {\n\n continue;\n\n }\n\n clear_screen();\n\n endwin();\n\n pipe_to_external_editor(external_editor, &core.get_full_output_string(&state));\n\n break;\n\n }\n\n CTRL_H | KEY_BACKSPACE | ALTERNATIVE_BACKSPACE => {\n\n state = state.pop_search_char();\n\n state = page_y(0, state, &mut core)\n\n }\n\n c => {\n", "file_path": "src/igrepper/mod.rs", "rank": 9, "score": 47488.4008196999 }, { "content": " state = {\n\n let y = state.max_y() as i32;\n\n page_y(y / 2, state, &mut core)\n\n }\n\n }\n\n CTRL_L | KEY_RESIZE => {\n\n let (max_y, max_x) = get_screen_size();\n\n state = state.set_max_yx(max_y, max_x);\n\n refresh();\n\n }\n\n CTRL_R => {\n\n state = state.modify_context(-1);\n\n }\n\n CTRL_T => {\n\n state = state.modify_context(1);\n\n }\n\n CTRL_N | KEY_ENTER | 0xa => {\n\n state = state.accept_partial_match();\n\n }\n\n CTRL_P => {\n", "file_path": "src/igrepper/mod.rs", "rank": 10, "score": 47487.64879235037 }, { "content": " max_y,\n\n max_x,\n\n );\n\n let (tx, rx) = mpsc::channel();\n\n let (char_requester_tx, char_requester_rx) = mpsc::channel();\n\n\n\n if let Some(mut inotify) = inotify_option {\n\n let inotify_tx = tx.clone();\n\n thread::spawn(move || {\n\n let mut buffer = [0; 1024];\n\n\n\n loop {\n\n let events_result = inotify.read_events_blocking(&mut buffer);\n\n match events_result {\n\n Ok(events) => {\n\n if events.count() > 0 {\n\n inotify_tx.send(Message::ReloadFile).unwrap();\n\n }\n\n }\n\n Err(e) => {\n", "file_path": "src/igrepper/mod.rs", "rank": 11, "score": 47487.5818320871 }, { "content": " }\n\n }\n\n });\n\n\n\n loop {\n\n let render_state = core.get_render_state(&state);\n\n rendering::render(render_state);\n\n refresh();\n\n char_requester_tx\n\n .send(CharRequesterMessage::ReadyToReceiveChar)\n\n .unwrap();\n\n let message = rx.recv().unwrap();\n\n match message {\n\n Message::ReloadFile => {\n\n state = state.set_source_lines(source_producer.get_source());\n\n core.clear_cache();\n\n }\n\n Message::ErrorMessage(message) => {\n\n panic!(\"Inotify error: {}\", message);\n\n }\n", "file_path": "src/igrepper/mod.rs", "rank": 12, "score": 47487.54763054587 }, { "content": "\n\n #[test]\n\n fn construct_grep_with_single_quote() {\n\n let search_lines: Vec<SearchLine> =\n\n vec![SearchLine::new(\"isn't\".to_string(), 0, false, false)];\n\n assert_eq!(\n\n construct_grep_line(&search_lines),\n\n \"grep --perl-regexp \\'(?i)isn\\'\\\\\\'\\'t\\'\"\n\n );\n\n }\n\n}\n", "file_path": "src/igrepper/mod.rs", "rank": 13, "score": 47485.56188272884 }, { "content": " #[test]\n\n fn construct_grep_sensitive_and_inverted() {\n\n let search_lines: Vec<SearchLine> = vec![SearchLine::new(\"foo\".to_string(), 0, true, true)];\n\n assert_eq!(\n\n construct_grep_line(&search_lines),\n\n \"grep -v --perl-regexp \\'foo\\'\"\n\n );\n\n }\n\n\n\n #[test]\n\n fn construct_grep_context() {\n\n let search_lines: Vec<SearchLine> =\n\n vec![SearchLine::new(\"foo\".to_string(), 2, false, false)];\n\n assert_eq!(\n\n construct_grep_line(&search_lines),\n\n \"grep --context 2 --perl-regexp \\'(?i)foo\\'\"\n\n );\n\n }\n\n\n\n #[test]\n", "file_path": "src/igrepper/mod.rs", "rank": 14, "score": 47485.56188272884 }, { "content": " if let Some(new_char) = char::from_u32(c as u32) {\n\n state = state.push_search_char(new_char);\n\n state = page_y(0, state, &mut core)\n\n }\n\n }\n\n },\n\n }\n\n }\n\n}\n\n\n", "file_path": "src/igrepper/mod.rs", "rank": 15, "score": 47485.56188272884 }, { "content": " #[test]\n\n fn construct_grep_case_sensitive() {\n\n let search_lines: Vec<SearchLine> =\n\n vec![SearchLine::new(\"foo\".to_string(), 0, true, false)];\n\n assert_eq!(\n\n construct_grep_line(&search_lines),\n\n \"grep --perl-regexp \\'foo\\'\"\n\n );\n\n }\n\n\n\n #[test]\n\n fn construct_grep_inverted() {\n\n let search_lines: Vec<SearchLine> =\n\n vec![SearchLine::new(\"foo\".to_string(), 0, false, true)];\n\n assert_eq!(\n\n construct_grep_line(&search_lines),\n\n \"grep -v --perl-regexp \\'(?i)foo\\'\"\n\n );\n\n }\n\n\n", "file_path": "src/igrepper/mod.rs", "rank": 16, "score": 47485.56188272884 }, { "content": " state = state.revert_partial_match();\n\n }\n\n CTRL_I => {\n\n state = state.toggle_case_sensitivity();\n\n }\n\n CTRL_V => {\n\n state = state.toggle_inverted();\n\n }\n\n CTRL_G => {\n\n if !state.regex_valid() || state.empty_search_lines() {\n\n continue;\n\n }\n\n clear_screen();\n\n endwin();\n\n copy_grep_to_clipboard(&state.search_lines());\n\n break;\n\n }\n\n CTRL_E => {\n\n if !state.regex_valid() {\n\n continue;\n", "file_path": "src/igrepper/mod.rs", "rank": 17, "score": 47485.56188272884 }, { "content": " }\n\n macro_rules! variable {\n\n () => {\n\n \"{}\"\n\n };\n\n }\n\n macro_rules! newline {\n\n () => {\n\n \"\\n\"\n\n };\n\n }\n\n\n\n println!(\n\n concat!(\n\n copied_to_clipboard!(),\n\n bold!(),\n\n inverted!(),\n\n variable!(),\n\n reset!(),\n\n newline!()\n", "file_path": "src/igrepper/mod.rs", "rank": 18, "score": 47485.56188272884 }, { "content": "\n\n for (i, c) in MATCH_COLORS.iter().enumerate() {\n\n init_pair(i as i16 + 1, c.clone(), 232i16);\n\n }\n\n\n\n refresh();\n\n\n\n let (max_y, max_x) = get_screen_size();\n\n\n\n let mut core = core::Core::new();\n\n let mut state = state::State::new(\n\n source_producer.get_source(),\n\n vec![SearchLine::new(\n\n String::from(initial_regex.unwrap_or(\"\")),\n\n initial_context,\n\n false,\n\n false,\n\n )],\n\n 0,\n\n 0,\n", "file_path": "src/igrepper/mod.rs", "rank": 19, "score": 47485.56188272884 }, { "content": " Message::Character(ch) => match ch {\n\n KEY_LEFT => {\n\n state = {\n\n let widest = core.widest_line_seen_so_far(&state);\n\n state.page_x(-5, widest)\n\n }\n\n }\n\n KEY_RIGHT => {\n\n state = {\n\n let widest = core.widest_line_seen_so_far(&state);\n\n state.page_x(5, widest)\n\n }\n\n }\n\n KEY_UP => state = page_y(-1, state, &mut core),\n\n KEY_DOWN => state = page_y(1, state, &mut core),\n\n\n\n 3 => {\n\n clear_screen();\n\n endwin();\n\n break;\n", "file_path": "src/igrepper/mod.rs", "rank": 20, "score": 47485.56188272884 }, { "content": " }\n\n KEY_PPAGE => {\n\n state = {\n\n let y = state.max_y() as i32;\n\n page_y(-y, state, &mut core)\n\n }\n\n }\n\n KEY_NPAGE => {\n\n state = {\n\n let y = state.max_y() as i32;\n\n page_y(y, state, &mut core)\n\n }\n\n }\n\n CTRL_U => {\n\n state = {\n\n let y = state.max_y() as i32;\n\n page_y(-y / 2, state, &mut core)\n\n }\n\n }\n\n CTRL_D => {\n", "file_path": "src/igrepper/mod.rs", "rank": 21, "score": 47485.56188272884 }, { "content": " inotify_tx\n\n .send(Message::ErrorMessage(e.to_string()))\n\n .unwrap();\n\n }\n\n }\n\n }\n\n });\n\n }\n\n\n\n thread::spawn(move || loop {\n\n match char_requester_rx\n\n .recv()\n\n .unwrap_or(CharRequesterMessage::Exit)\n\n {\n\n CharRequesterMessage::ReadyToReceiveChar => {\n\n let ch = getch();\n\n tx.send(Message::Character(ch)).unwrap();\n\n }\n\n CharRequesterMessage::Exit => {\n\n break;\n", "file_path": "src/igrepper/mod.rs", "rank": 22, "score": 47485.56188272884 }, { "content": " fn construct_grep_context_is_ignored_when_inverted() {\n\n let search_lines: Vec<SearchLine> =\n\n vec![SearchLine::new(\"foo\".to_string(), 2, false, true)];\n\n assert_eq!(\n\n construct_grep_line(&search_lines),\n\n \"grep -v --perl-regexp \\'(?i)foo\\'\"\n\n );\n\n }\n\n\n\n #[test]\n\n fn construct_grep_multiple_lines() {\n\n let search_lines: Vec<SearchLine> = vec![\n\n SearchLine::new(\"foo\".to_string(), 0, false, false),\n\n SearchLine::new(\"bar\".to_string(), 1, true, false),\n\n ];\n\n assert_eq!(\n\n construct_grep_line(&search_lines),\n\n \"grep --perl-regexp \\'(?i)foo\\' | grep --context 1 --perl-regexp \\'bar\\'\"\n\n );\n\n }\n", "file_path": "src/igrepper/mod.rs", "rank": 23, "score": 47485.56188272884 }, { "content": "fn grep_path() -> String {\n\n return \"grep\".to_string();\n\n}\n\n\n", "file_path": "src/igrepper/mod.rs", "rank": 24, "score": 42804.84650605958 }, { "content": "fn copy_to_clipboard(string: &String) -> () {\n\n let mut child_process = Command::new(\"xsel\")\n\n .arg(\"--clipboard\")\n\n .arg(\"--input\")\n\n .stdin(Stdio::piped())\n\n .spawn()\n\n .expect(\"Failed to copy to clipboard\");\n\n\n\n child_process\n\n .stdin\n\n .as_mut()\n\n .unwrap()\n\n .write_all(string.as_bytes())\n\n .unwrap();\n\n child_process.wait().unwrap();\n\n}\n\n\n", "file_path": "src/igrepper/mod.rs", "rank": 25, "score": 41443.144438187424 }, { "content": "fn print_copied_to_clipboard(string: String) {\n\n macro_rules! copied_to_clipboard {\n\n () => {\n\n \"Copied to clipboard: \\n\\n\"\n\n };\n\n }\n\n macro_rules! bold {\n\n () => {\n\n \"\\x1b[0;1m\"\n\n };\n\n }\n\n macro_rules! inverted {\n\n () => {\n\n \"\\x1b[0;7m\"\n\n };\n\n }\n\n macro_rules! reset {\n\n () => {\n\n \"\\x1b[0;0m\"\n\n };\n", "file_path": "src/igrepper/mod.rs", "rank": 26, "score": 40165.40784108524 }, { "content": "fn get_screen_size() -> (u32, u32) {\n\n let mut y: i32 = 0;\n\n let mut x: i32 = 0;\n\n getmaxyx(stdscr(), &mut y, &mut x);\n\n (y as u32, x as u32)\n\n}\n\n\n", "file_path": "src/igrepper/mod.rs", "rank": 27, "score": 40165.40784108524 }, { "content": "fn copy_full_to_clipboard_from_string(string_to_copy: &String) -> () {\n\n copy_to_clipboard(&string_to_copy);\n\n print_copied_to_clipboard(string_to_copy.clone());\n\n}\n\n\n", "file_path": "src/igrepper/mod.rs", "rank": 28, "score": 37832.57038856002 }, { "content": "/// Tries to page vertically, may query more output lines.\n\nfn page_y(amount: i32, s: State, c: &mut Core) -> State {\n\n let wanted_ypage = cmp::max(0, s.pager_y() as i32 + amount) as u32;\n\n let mut output_lines_count: u32;\n\n\n\n let need_to_query = match c.get_current_output_length(&s) {\n\n Len::Is(n) => {\n\n output_lines_count = n;\n\n false\n\n }\n\n Len::AtLeast(n) => {\n\n output_lines_count = n;\n\n n < wanted_ypage\n\n }\n\n };\n\n\n\n if need_to_query {\n\n output_lines_count = c.is_output_length_at_least(&s, wanted_ypage + s.max_y());\n\n }\n\n s.page_y(amount, output_lines_count)\n\n}\n\n\n", "file_path": "src/igrepper/mod.rs", "rank": 29, "score": 37832.57038856002 }, { "content": "fn copy_grep_to_clipboard(search_lines: &Vec<SearchLine>) -> () {\n\n let grep_line = construct_grep_line(search_lines);\n\n copy_to_clipboard(&grep_line);\n\n print_copied_to_clipboard(grep_line);\n\n}\n\n\n", "file_path": "src/igrepper/mod.rs", "rank": 30, "score": 36764.90359933744 }, { "content": "fn construct_grep_line(search_lines: &Vec<SearchLine>) -> String {\n\n search_lines\n\n .iter()\n\n .filter(|l| !l.line.is_empty())\n\n .map(|l| {\n\n format!(\n\n \"{grep}{context}{inverted} --perl-regexp '{regex}'\",\n\n grep = grep_path(),\n\n context = if l.context > 0 && !l.inverse {\n\n format!(\" --context {}\", l.context)\n\n } else {\n\n String::from(\"\")\n\n },\n\n regex = l.line_with_sensitivity_prefix().replace(\"'\", \"'\\\\''\"),\n\n inverted = if l.inverse { \" -v\" } else { \"\" }\n\n )\n\n })\n\n .collect::<Vec<String>>()\n\n .join(\" | \")\n\n}\n\n\n", "file_path": "src/igrepper/mod.rs", "rank": 31, "score": 35755.843772720225 }, { "content": "use std::fs::File;\n\nuse std::io;\n\nuse std::io::{BufRead, BufReader};\n\n\n\n#[derive(Debug, Clone)]\n\npub enum SourceInput {\n\n FullInput(Vec<String>),\n\n FilePath(String),\n\n}\n\n\n\npub struct SourceProducer {\n\n pub input: SourceInput,\n\n}\n\n\n\nimpl SourceProducer {\n\n pub fn get_source(&self) -> Vec<String> {\n\n match &self.input {\n\n SourceInput::FilePath(path) => {\n\n read_source_from_file(path.as_str()).unwrap_or_else(|error| {\n\n eprintln!(\"Failed to open file '{}': {}\", path, error);\n\n std::process::exit(1);\n\n })\n\n }\n\n SourceInput::FullInput(full_input) => full_input.clone(),\n\n }\n\n }\n\n}\n\n\n", "file_path": "src/file_reading.rs", "rank": 32, "score": 32356.077533449272 }, { "content": "#!/usr/bin/env python3\n\n\n\nimport re\n\nimport curses\n\nfrom enum import Enum\n\nfrom subprocess import run, Popen, PIPE\n\nimport os\n\nimport sys\n\nimport argparse\n\nfrom typing import List\n\n\n\nfrom pathlib import Path\n\nimport logging\n\n\n\n\n\nBOLD = '\\033[1m'\n\nINVERTED = '\\033[7m'\n\nRESET = '\\033[0m'\n\nAVAILABLE_COLORS = 6\n\nFOOTER_LINE_NO = 2\n\nWORD_REGEX = '\\\\S+'\n\n\n\nCTRL_D = 4\n\nCTRL_G = 7\n\nCTRL_H = 8\n\nCTRL_I = 9\n\nCTRL_J = 10\n\nCTRL_K = 11\n\nCTRL_L = 12\n\nCTRL_N = 14\n\nCTRL_O = 15\n\nCTRL_P = 16\n\nCTRL_R = 18\n\nCTRL_T = 20\n\nCTRL_U = 21\n\nCTRL_V = 22\n\nCTRL_Y = 25 # suspends on mac..\n\nCTRL_9 = 57\n\nCTRL_8 = 263\n\nMAC_BACKSPACE = 127\n\n\n\ndebug = False\n\n\n\nclass Logger:\n\n log_file = '%s.log' % (Path().absolute() / Path(__file__).stem)\n\n FORMAT = '%(levelname)-5s:%(asctime)-15s:%(module)s.%(funcName)-s() ~ %(message)s'\n\n logging.basicConfig(filename=log_file, level=logging.INFO, format=FORMAT)\n\n log = logging.getLogger(__name__)\n\n\n\n\n\ndef log_with_debugging(func):\n\n \"\"\"\n\n Decorator to log exceptions when debug argument is passed in order to\n\n catch keycodes etc.\n\n \"\"\"\n\n def inner(*args, **kwargs):\n\n try:\n\n # TODO e.g. a -d2 argument to change this into debug\n\n # logging is set to INFO by default\n\n Logger.log.debug(args)\n\n return func(*args, **kwargs)\n\n except:\n\n if debug:\n\n Logger.log.exception('Arguments were: %r', args[1:])\n\n else:\n\n raise\n\n return inner\n\n\n\n\n\nclass DisplayMode(Enum):\n\n show_default = 1\n\n show_all = 2\n\n show_only_match = 3\n\n show_only_unique = 4 # each unique on separate line\n\n\n\n\n\ndef copy_to_clipboard(string):\n\n print('Copied to clipboard: \\n\\n' + BOLD + INVERTED + string + RESET + '\\n')\n\n p = Popen(clipboard_cmd(), stdin=PIPE)\n\n p.communicate(input=string.encode('utf-8'))\n\n\n\n\n\ndef clipboard_cmd() -> list:\n\n if sys.platform == 'darwin':\n\n return ['pbcopy']\n\n else:\n\n return ['xsel', '-bi']\n\n\n\n\n\ndef grep_cmd() -> list:\n\n \"\"\"\n\n Compatibility helper for macOS which by default doesn't have a GNU flavoured\n\n grep command and thus ```grep --perl-regexp``` is not a valid option\n\n \"\"\"\n\n grep_cmd = ['grep']\n\n if sys.platform == 'darwin':\n\n which_ggrep_query = str(run(['which', 'ggrep'], stdout=PIPE).stdout)\n\n if 'not found' in which_ggrep_query:\n\n grep_version_query = str(run(['grep', '--version'], stdout=PIPE).stdout)\n\n if 'BSD' in grep_version_query:\n\n print('Your grep is of BSD flavour and doesn\\'t support perl type regexp')\n\n print('( ' + grep_version_query.splitlines()[0] + ' )')\n\n print('Consider installing GNU grep: brew install grep')\n\n else:\n\n print('Unknown grep flavour.. trying \\'grep\\'')\n\n print('( ' + grep_version_query.splitlines()[0] + ' )')\n\n else:\n\n grep_cmd = ['ggrep']\n\n\n\n return grep_cmd\n\n\n\n\n\n\n\nclass Match:\n\n def __init__(self, regex_match):\n\n self.text = regex_match.group()\n\n self.start = regex_match.start()\n\n self.end = regex_match.end()\n\n self.unique_id = None\n\n\n\n\n\nclass Line:\n\n def __init__(self, orig_line_no: int, line_text: str, line_matches: List[Match], break_line=False) -> None:\n\n self.orig_line_no = orig_line_no\n\n self.line_text = line_text\n\n self.line_matches = line_matches\n\n self.break_line = break_line\n\n\n\n\n\nclass Search:\n\n \"\"\"\n\n Object created from input, keeps track of regex, matches, settings\n\n \"\"\"\n\n\n\n def __init__(self, input_lines: List[str], initial_context: int = 0) -> None:\n\n self.valid = True\n\n self.lines: List[List[Match]] = []\n\n self._input_lines = input_lines\n\n self.match_count = 0\n\n self.number_of_matched_lines = 0\n\n self.unique_match_count = 0\n\n self.selected_match = 0\n\n self.unique_matches: List[str] = []\n\n self.previous_searches: List[Search] = []\n\n self.ignore_case = True\n\n self.regex = ''\n\n self.output_lines: List[Line] = []\n\n self.context: int = initial_context\n\n\n\n def is_empty(self):\n\n return len(self.regex) == 0\n\n\n\n def next_match(self):\n\n if self.unique_matches:\n\n self.selected_match = (self.selected_match + 1) % self.unique_match_count\n\n\n\n def prev_match(self):\n\n if self.unique_matches:\n\n self.selected_match = (self.selected_match - 1 + self.unique_match_count) % self.unique_match_count\n\n\n\n def update(self, regex: str):\n\n self.regex = regex\n\n if self.is_empty():\n\n self.output_lines = []\n\n for orig_line_no, line in enumerate(self._input_lines):\n\n self.output_lines.append(Line(orig_line_no, line, []))\n\n return\n\n try:\n\n if self.ignore_case:\n\n rg = re.compile(self.regex, re.IGNORECASE)\n\n else:\n\n rg = re.compile(self.regex)\n\n self.valid = True\n\n except re.error:\n\n self.valid = False\n\n return\n\n self.output_lines = []\n\n output_lines_dict = {}\n\n self.lines = [[Match(x) for x in rg.finditer(l)] for l in self._input_lines]\n\n for orig_line_number, matches_on_line in enumerate(self.lines):\n\n if matches_on_line:\n\n match_line = Line(orig_line_number, self._input_lines[orig_line_number], matches_on_line)\n\n output_lines_dict[orig_line_number] = match_line # Override possible context line with a match line\n\n\n\n # Add context lines, including break lines\n\n if self.context > 0:\n\n first_context_line = True\n\n for context_line_no in range(orig_line_number - self.context, orig_line_number + self.context + 1):\n\n if context_line_no < 0 or context_line_no >= len(self._input_lines):\n\n continue\n\n if context_line_no in output_lines_dict:\n\n # Already exists\n\n continue\n\n if first_context_line and len(output_lines_dict) > 1 and context_line_no > 1 \\\n\n and context_line_no - 2 not in output_lines_dict:\n\n # create break\n\n b = Line(context_line_no - 1, '', [], break_line=True)\n\n output_lines_dict[context_line_no - 1] = b\n\n first_context_line = False\n\n output_lines_dict[context_line_no] = Line(context_line_no, self._input_lines[context_line_no],\n\n [])\n\n\n\n self.output_lines = [output_lines_dict[x] for x in sorted(output_lines_dict.keys())]\n\n\n\n matches = [match for line in self.lines for match in line]\n\n nonempty_matches = [match for match in matches if match]\n\n self.unique_matches = []\n\n for match in nonempty_matches:\n\n if match.text in self.unique_matches:\n\n match.unique_id = self.unique_matches.index(match.text)\n\n else:\n\n self.unique_matches.append(match.text)\n\n match.unique_id = len(self.unique_matches) - 1\n\n\n\n self.match_count = len(nonempty_matches)\n\n self.unique_match_count = len(self.unique_matches)\n\n self.number_of_matched_lines = len([x for x in self.lines if x])\n\n\n\n\n\nclass IGrepper:\n\n def __init__(self, input_lines: List[str], regex='', initial_context=0) -> None:\n\n self.win = curses.initscr()\n\n self.win.keypad(True)\n\n curses.start_color()\n\n\n\n curses.init_pair(1, curses.COLOR_RED, curses.COLOR_BLACK)\n\n curses.init_pair(2, curses.COLOR_GREEN, curses.COLOR_BLACK)\n\n curses.init_pair(3, curses.COLOR_YELLOW, curses.COLOR_BLACK)\n\n curses.init_pair(4, curses.COLOR_BLUE, curses.COLOR_BLACK)\n\n curses.init_pair(5, curses.COLOR_MAGENTA, curses.COLOR_BLACK)\n\n curses.init_pair(6, curses.COLOR_CYAN, curses.COLOR_BLACK)\n\n curses.init_pair(30, curses.COLOR_RED, curses.COLOR_WHITE)\n\n curses.init_pair(31, curses.COLOR_BLACK, curses.COLOR_WHITE)\n\n curses.init_pair(32, curses.COLOR_BLACK, curses.COLOR_BLACK)\n\n curses.use_default_colors()\n\n\n\n self.regex = regex\n\n self.input_lines = input_lines\n\n self.display_mode = DisplayMode.show_default\n\n self.pager_ypos = 0\n\n self.pager_xpos = 0\n\n self.search = Search(self.input_lines, initial_context=initial_context)\n\n self.quit = False\n\n\n\n def toggle_display_mode(self):\n\n if self.display_mode == DisplayMode.show_default:\n\n self.display_mode = DisplayMode.show_only_match\n\n elif self.display_mode == DisplayMode.show_only_match:\n\n self.display_mode = DisplayMode.show_all\n\n elif self.display_mode == DisplayMode.show_all:\n\n self.display_mode = DisplayMode.show_default\n\n\n\n def get_number_of_pager_lines(self):\n\n maxy, _ = self.win.getmaxyx()\n\n header_line_no = len(self.search.previous_searches) + 2\n\n pager_line_no = maxy - header_line_no - FOOTER_LINE_NO\n\n return pager_line_no\n\n\n\n def run(self):\n\n while not self.quit:\n\n self.search.update(self.regex)\n\n self.win.erase()\n\n render(search=self.search,\n\n window=self.win,\n\n pager_ypos=self.pager_ypos,\n\n pager_xpos=self.pager_xpos)\n\n self.win.refresh()\n\n char = self.win.getch()\n\n self.process_char(char)\n\n\n\n @log_with_debugging\n\n def process_char(self, char: int):\n\n if char < 0:\n\n # in tmux this is an option when the pane gets resized\n\n return\n\n elif char in (CTRL_H, curses.KEY_BACKSPACE, MAC_BACKSPACE):\n\n if len(self.regex) > 0:\n\n self.regex = self.regex[:-1]\n\n elif char in (CTRL_L, curses.KEY_RESIZE):\n\n pass # The curses window has been resized, so re-render it\n\n elif char == CTRL_N:\n\n if self.search.valid:\n\n previous_match_objects = self.search.previous_searches + [self.search]\n\n self.search = Search([l.line_text for l in self.search.output_lines if not l.break_line])\n\n self.search.previous_searches = previous_match_objects\n\n self.search.context = previous_match_objects[-1].context\n\n self.regex = ''\n\n elif char == CTRL_P:\n\n if self.search.previous_searches:\n\n self.search = self.search.previous_searches.pop()\n\n self.regex = self.search.regex\n\n elif char == CTRL_O:\n\n self.toggle_display_mode()\n\n elif char == CTRL_J:\n\n self.search.next_match()\n\n elif char == CTRL_K:\n\n self.search.prev_match()\n\n elif char == CTRL_G:\n\n self.endwin()\n\n grep_commands = []\n\n for m in self.search.previous_searches + [self.search]:\n\n options = '--perl-regexp '\n\n if m.ignore_case:\n\n options += '--ignore-case '\n\n if m.context > 0:\n\n options += '--context {} '.format(m.context)\n\n grep_commands.append(\"{} {}'{}' \".format(*grep_cmd(), options, m.regex.replace(\"'\", \"\\\\'\")))\n\n to_yank = ' | '.join(grep_commands)\n\n copy_to_clipboard(to_yank)\n\n self.quit = True\n\n elif char == CTRL_Y:\n\n if not self.search.unique_matches:\n\n return\n\n self.endwin()\n\n to_yank = self.search.unique_matches[self.search.selected_match]\n\n if to_yank:\n\n copy_to_clipboard(to_yank)\n\n self.quit = True\n\n elif char == CTRL_V:\n\n self.search.ignore_case = not self.search.ignore_case\n\n elif char == curses.KEY_DOWN:\n\n self.pager_ypos += 1\n\n elif char == curses.KEY_NPAGE:\n\n self.pager_ypos = self.pager_ypos + self.get_number_of_pager_lines()\n\n elif char == CTRL_D:\n\n self.pager_ypos = self.pager_ypos + int(self.get_number_of_pager_lines() / 2)\n\n elif char == curses.KEY_UP:\n\n self.pager_ypos = max(0, self.pager_ypos - 1)\n\n elif char == curses.KEY_PPAGE:\n\n self.pager_ypos = max(0, self.pager_ypos - self.get_number_of_pager_lines())\n\n elif char == CTRL_U:\n\n self.pager_ypos = max(0, self.pager_ypos - int(self.get_number_of_pager_lines() / 2))\n\n elif char == curses.KEY_RIGHT:\n\n self.pager_xpos += 1\n\n elif char == curses.KEY_LEFT:\n\n self.pager_xpos = max(0, self.pager_xpos - 1)\n\n elif char == CTRL_R:\n\n self.search.context = max(0, self.search.context - 1)\n\n elif char == CTRL_T:\n\n self.search.context += 1\n\n else:\n\n self.regex += chr(char)\n\n\n\n max_pager_ypos = max(0, len(self.search.output_lines) - self.get_number_of_pager_lines())\n\n self.pager_ypos = min(self.pager_ypos, max_pager_ypos)\n\n\n\n def endwin(self):\n\n self.win.erase()\n\n self.win.refresh()\n\n curses.endwin()\n\n\n\n\n\ndef render(search: Search, window, pager_ypos: int, pager_xpos: int):\n\n more_lines_after = True\n\n maxy, maxx = window.getmaxyx()\n\n footer_div_ypos = maxy - 2\n\n status_line_ypos = maxy - 1\n\n header_line_no = len(search.previous_searches) + 2\n\n pager_line_no = maxy - header_line_no - FOOTER_LINE_NO\n\n if pager_line_no < 1 or maxx < 5:\n\n try:\n\n window.addstr('window too small'[:maxx])\n\n except:\n\n pass\n\n return\n\n\n\n for m in search.previous_searches:\n\n window.addstr('{}\\n'.format(m.regex))\n\n\n\n regex_color = curses.color_pair(0) if search.valid else curses.color_pair(30)\n\n window.addstr('{}\\n'.format(search.regex), regex_color)\n\n header_char, header_color = ('^', curses.color_pair(31)) if pager_ypos > 0 else ('-', curses.color_pair(0))\n\n window.addstr(header_char * maxx, header_color)\n\n\n\n # trim output to visible by pager\n\n max_pager_ypos = max(0, len(search.output_lines) - pager_line_no)\n\n if pager_ypos >= max_pager_ypos:\n\n more_lines_after = False\n\n output_lines = search.output_lines[pager_ypos:pager_ypos + pager_line_no]\n\n\n\n # Fill break lines with text to display\n\n for l in output_lines:\n\n if l.break_line:\n\n l.line_text = '-' * maxx\n\n\n\n line_text_to_print = [line.line_text[pager_xpos:pager_xpos + maxx - 1] for line in output_lines]\n\n\n\n # write output\n\n window.addstr('\\n'.join(line_text_to_print))\n\n\n\n # highlight break lines\n\n for lineno, line_object in enumerate(output_lines):\n\n if line_object.break_line:\n\n color = curses.color_pair(32)\n\n window.chgat(lineno + header_line_no, 0 - pager_xpos, maxx, color | curses.A_BOLD)\n\n\n\n # highlight matches\n\n for lineno, line_object in enumerate(output_lines):\n\n for match in line_object.line_matches:\n\n # Only highlight if inside pager view\n\n def inside_pager(match_start, match_end, first_visible_x, last_visible_x):\n\n if match_start < first_visible_x or match_start > last_visible_x:\n\n return False\n\n if match_end < first_visible_x or match_end > last_visible_x:\n\n return False\n\n return True\n\n\n\n if inside_pager(match.start, match.end, pager_xpos, pager_xpos + maxx - 1):\n\n if match.unique_id == search.selected_match:\n\n color = curses.color_pair(31)\n\n else:\n\n color = curses.color_pair((match.unique_id % AVAILABLE_COLORS) + 1)\n\n window.chgat(lineno + header_line_no, match.start - pager_xpos, match.end - match.start,\n\n color | curses.A_BOLD)\n\n\n\n # Footer\n\n footer_char, footer_color = ('v', curses.color_pair(31)) if more_lines_after else ('-', curses.color_pair(0))\n\n window.addstr(footer_div_ypos, 0, footer_char * maxx, footer_color)\n\n case_sensitivity_text = \"[case insensitive], \" if search.ignore_case else \"[case sensitive], \"\n\n status_line = case_sensitivity_text + \\\n\n 'context: {}, '.format(search.context) + \\\n\n 'lines: {}, '.format(search.number_of_matched_lines) + \\\n\n 'matches: {}, '.format(search.match_count) + \\\n\n 'unique: {}, '.format(search.unique_match_count) + \\\n\n 'pag_y: {}, pag_x: {} '.format(pager_ypos, pager_xpos)\n\n status_line = status_line[:maxx - 1]\n\n window.addstr(status_line_ypos, 0, status_line)\n\n\n\n\n\ndef main():\n\n parser = argparse.ArgumentParser()\n\n parser.add_argument(\"file\", nargs='?')\n\n group = parser.add_mutually_exclusive_group()\n\n\n\n group.add_argument(\"-e\", \"--regexp\", action=\"store\", default='', help=\"Regular expression to preload\")\n\n group.add_argument(\"-w\", \"--word\", action=\"store_true\", help=\"Preload the regular expression '\\\\S+'\")\n\n parser.add_argument(\"-c\", \"--context\", action=\"store\", type=int, default=0,\n\n help=\"Print CONTEXT num of output context\")\n\n parser.add_argument(\"-d\", \"--debug\", action=\"store_true\", default=False)\n\n\n\n args = parser.parse_args()\n\n\n\n global debug\n\n debug = args.debug\n\n\n\n if sys.stdin.isatty():\n\n if not args.file:\n\n print('Data can only be passed by STDIN if no file parameter is specified', file=sys.stderr)\n\n exit(1)\n\n with open(args.file) as f:\n\n input_lines = f.read().split('\\n')\n\n else:\n\n if args.file:\n\n print('Data can only be passed by STDIN if no file parameter is specified', file=sys.stderr)\n\n exit(1)\n\n # Hack to read stdin from pipe and then from tty\n\n input_lines = ''.join(sys.stdin.read()).split('\\n')\n\n os.close(sys.stdin.fileno())\n\n sys.__stdin__ = sys.stdin = open('/dev/tty')\n\n\n\n initial_regex = args.regexp\n\n if args.word:\n\n initial_regex = WORD_REGEX\n\n try:\n\n f = IGrepper(input_lines, initial_regex, initial_context=args.context)\n\n f.run()\n\n finally:\n\n curses.endwin()\n\n\n\n\n\nif __name__ == '__main__':\n\n main()\n", "file_path": "python/igrepper/igrepper.py", "rank": 35, "score": 20447.53259241785 }, { "content": "class IGrepper:\n\n def __init__(self, input_lines: List[str], regex='', initial_context=0) -> None:\n\n self.win = curses.initscr()\n\n self.win.keypad(True)\n\n curses.start_color()\n\n\n\n curses.init_pair(1, curses.COLOR_RED, curses.COLOR_BLACK)\n\n curses.init_pair(2, curses.COLOR_GREEN, curses.COLOR_BLACK)\n\n curses.init_pair(3, curses.COLOR_YELLOW, curses.COLOR_BLACK)\n\n curses.init_pair(4, curses.COLOR_BLUE, curses.COLOR_BLACK)\n\n curses.init_pair(5, curses.COLOR_MAGENTA, curses.COLOR_BLACK)\n\n curses.init_pair(6, curses.COLOR_CYAN, curses.COLOR_BLACK)\n\n curses.init_pair(30, curses.COLOR_RED, curses.COLOR_WHITE)\n\n curses.init_pair(31, curses.COLOR_BLACK, curses.COLOR_WHITE)\n\n curses.init_pair(32, curses.COLOR_BLACK, curses.COLOR_BLACK)\n\n curses.use_default_colors()\n\n\n\n self.regex = regex\n\n self.input_lines = input_lines\n\n self.display_mode = DisplayMode.show_default\n\n self.pager_ypos = 0\n\n self.pager_xpos = 0\n\n self.search = Search(self.input_lines, initial_context=initial_context)\n\n self.quit = False\n\n\n\n def toggle_display_mode(self):\n\n if self.display_mode == DisplayMode.show_default:\n\n self.display_mode = DisplayMode.show_only_match\n\n elif self.display_mode == DisplayMode.show_only_match:\n\n self.display_mode = DisplayMode.show_all\n\n elif self.display_mode == DisplayMode.show_all:\n\n self.display_mode = DisplayMode.show_default\n\n\n\n def get_number_of_pager_lines(self):\n\n maxy, _ = self.win.getmaxyx()\n\n header_line_no = len(self.search.previous_searches) + 2\n\n pager_line_no = maxy - header_line_no - FOOTER_LINE_NO\n\n return pager_line_no\n\n\n\n def run(self):\n\n while not self.quit:\n\n self.search.update(self.regex)\n\n self.win.erase()\n\n render(search=self.search,\n\n window=self.win,\n\n pager_ypos=self.pager_ypos,\n\n pager_xpos=self.pager_xpos)\n\n self.win.refresh()\n\n char = self.win.getch()\n\n self.process_char(char)\n\n\n\n @log_with_debugging\n\n def process_char(self, char: int):\n\n if char < 0:\n\n # in tmux this is an option when the pane gets resized\n\n return\n\n elif char in (CTRL_H, curses.KEY_BACKSPACE, MAC_BACKSPACE):\n\n if len(self.regex) > 0:\n\n self.regex = self.regex[:-1]\n\n elif char in (CTRL_L, curses.KEY_RESIZE):\n\n pass # The curses window has been resized, so re-render it\n\n elif char == CTRL_N:\n\n if self.search.valid:\n\n previous_match_objects = self.search.previous_searches + [self.search]\n\n self.search = Search([l.line_text for l in self.search.output_lines if not l.break_line])\n\n self.search.previous_searches = previous_match_objects\n\n self.search.context = previous_match_objects[-1].context\n\n self.regex = ''\n\n elif char == CTRL_P:\n\n if self.search.previous_searches:\n\n self.search = self.search.previous_searches.pop()\n\n self.regex = self.search.regex\n\n elif char == CTRL_O:\n\n self.toggle_display_mode()\n\n elif char == CTRL_J:\n\n self.search.next_match()\n\n elif char == CTRL_K:\n\n self.search.prev_match()\n\n elif char == CTRL_G:\n\n self.endwin()\n\n grep_commands = []\n\n for m in self.search.previous_searches + [self.search]:\n\n options = '--perl-regexp '\n\n if m.ignore_case:\n\n options += '--ignore-case '\n\n if m.context > 0:\n\n options += '--context {} '.format(m.context)\n\n grep_commands.append(\"{} {}'{}' \".format(*grep_cmd(), options, m.regex.replace(\"'\", \"\\\\'\")))\n\n to_yank = ' | '.join(grep_commands)\n\n copy_to_clipboard(to_yank)\n\n self.quit = True\n\n elif char == CTRL_Y:\n\n if not self.search.unique_matches:\n\n return\n\n self.endwin()\n\n to_yank = self.search.unique_matches[self.search.selected_match]\n\n if to_yank:\n\n copy_to_clipboard(to_yank)\n\n self.quit = True\n\n elif char == CTRL_V:\n\n self.search.ignore_case = not self.search.ignore_case\n\n elif char == curses.KEY_DOWN:\n\n self.pager_ypos += 1\n\n elif char == curses.KEY_NPAGE:\n\n self.pager_ypos = self.pager_ypos + self.get_number_of_pager_lines()\n\n elif char == CTRL_D:\n\n self.pager_ypos = self.pager_ypos + int(self.get_number_of_pager_lines() / 2)\n\n elif char == curses.KEY_UP:\n\n self.pager_ypos = max(0, self.pager_ypos - 1)\n\n elif char == curses.KEY_PPAGE:\n\n self.pager_ypos = max(0, self.pager_ypos - self.get_number_of_pager_lines())\n\n elif char == CTRL_U:\n\n self.pager_ypos = max(0, self.pager_ypos - int(self.get_number_of_pager_lines() / 2))\n\n elif char == curses.KEY_RIGHT:\n\n self.pager_xpos += 1\n\n elif char == curses.KEY_LEFT:\n\n self.pager_xpos = max(0, self.pager_xpos - 1)\n\n elif char == CTRL_R:\n\n self.search.context = max(0, self.search.context - 1)\n\n elif char == CTRL_T:\n\n self.search.context += 1\n\n else:\n\n self.regex += chr(char)\n\n\n\n max_pager_ypos = max(0, len(self.search.output_lines) - self.get_number_of_pager_lines())\n\n self.pager_ypos = min(self.pager_ypos, max_pager_ypos)\n\n\n\n def endwin(self):\n\n self.win.erase()\n\n self.win.refresh()\n", "file_path": "python/igrepper/igrepper.py", "rank": 36, "score": 20137.486156299325 }, { "content": " def run(self):\n\n while not self.quit:\n\n self.search.update(self.regex)\n\n self.win.erase()\n\n render(search=self.search,\n\n window=self.win,\n\n pager_ypos=self.pager_ypos,\n\n pager_xpos=self.pager_xpos)\n\n self.win.refresh()\n\n char = self.win.getch()\n", "file_path": "python/igrepper/igrepper.py", "rank": 37, "score": 20137.486156299325 }, { "content": " def endwin(self):\n\n self.win.erase()\n\n self.win.refresh()\n", "file_path": "python/igrepper/igrepper.py", "rank": 38, "score": 20137.486156299325 }, { "content": "class Search:\n\n \"\"\"\n\n Object created from input, keeps track of regex, matches, settings\n\n \"\"\"\n\n\n\n def __init__(self, input_lines: List[str], initial_context: int = 0) -> None:\n\n self.valid = True\n\n self.lines: List[List[Match]] = []\n\n self._input_lines = input_lines\n\n self.match_count = 0\n\n self.number_of_matched_lines = 0\n\n self.unique_match_count = 0\n\n self.selected_match = 0\n\n self.unique_matches: List[str] = []\n\n self.previous_searches: List[Search] = []\n\n self.ignore_case = True\n\n self.regex = ''\n\n self.output_lines: List[Line] = []\n\n self.context: int = initial_context\n\n\n\n def is_empty(self):\n\n return len(self.regex) == 0\n\n\n\n def next_match(self):\n\n if self.unique_matches:\n\n self.selected_match = (self.selected_match + 1) % self.unique_match_count\n\n\n\n def prev_match(self):\n\n if self.unique_matches:\n\n self.selected_match = (self.selected_match - 1 + self.unique_match_count) % self.unique_match_count\n\n\n\n def update(self, regex: str):\n\n self.regex = regex\n\n if self.is_empty():\n\n self.output_lines = []\n\n for orig_line_no, line in enumerate(self._input_lines):\n\n self.output_lines.append(Line(orig_line_no, line, []))\n\n return\n\n try:\n\n if self.ignore_case:\n\n rg = re.compile(self.regex, re.IGNORECASE)\n\n else:\n\n rg = re.compile(self.regex)\n\n self.valid = True\n\n except re.error:\n\n self.valid = False\n\n return\n\n self.output_lines = []\n\n output_lines_dict = {}\n\n self.lines = [[Match(x) for x in rg.finditer(l)] for l in self._input_lines]\n\n for orig_line_number, matches_on_line in enumerate(self.lines):\n\n if matches_on_line:\n\n match_line = Line(orig_line_number, self._input_lines[orig_line_number], matches_on_line)\n\n output_lines_dict[orig_line_number] = match_line # Override possible context line with a match line\n\n\n\n # Add context lines, including break lines\n\n if self.context > 0:\n\n first_context_line = True\n\n for context_line_no in range(orig_line_number - self.context, orig_line_number + self.context + 1):\n\n if context_line_no < 0 or context_line_no >= len(self._input_lines):\n\n continue\n\n if context_line_no in output_lines_dict:\n\n # Already exists\n\n continue\n\n if first_context_line and len(output_lines_dict) > 1 and context_line_no > 1 \\\n\n and context_line_no - 2 not in output_lines_dict:\n\n # create break\n\n b = Line(context_line_no - 1, '', [], break_line=True)\n\n output_lines_dict[context_line_no - 1] = b\n\n first_context_line = False\n\n output_lines_dict[context_line_no] = Line(context_line_no, self._input_lines[context_line_no],\n\n [])\n\n\n\n self.output_lines = [output_lines_dict[x] for x in sorted(output_lines_dict.keys())]\n\n\n\n matches = [match for line in self.lines for match in line]\n\n nonempty_matches = [match for match in matches if match]\n\n self.unique_matches = []\n\n for match in nonempty_matches:\n\n if match.text in self.unique_matches:\n\n match.unique_id = self.unique_matches.index(match.text)\n\n else:\n\n self.unique_matches.append(match.text)\n\n match.unique_id = len(self.unique_matches) - 1\n\n\n\n self.match_count = len(nonempty_matches)\n\n self.unique_match_count = len(self.unique_matches)\n", "file_path": "python/igrepper/igrepper.py", "rank": 39, "score": 20137.486156299325 }, { "content": "class Logger:\n\n log_file = '%s.log' % (Path().absolute() / Path(__file__).stem)\n\n FORMAT = '%(levelname)-5s:%(asctime)-15s:%(module)s.%(funcName)-s() ~ %(message)s'\n\n logging.basicConfig(filename=log_file, level=logging.INFO, format=FORMAT)\n", "file_path": "python/igrepper/igrepper.py", "rank": 40, "score": 20137.486156299325 }, { "content": " def inner(*args, **kwargs):\n\n try:\n\n # TODO e.g. a -d2 argument to change this into debug\n\n # logging is set to INFO by default\n\n Logger.log.debug(args)\n\n return func(*args, **kwargs)\n\n except:\n\n if debug:\n\n Logger.log.exception('Arguments were: %r', args[1:])\n\n else:\n", "file_path": "python/igrepper/igrepper.py", "rank": 41, "score": 20137.486156299325 }, { "content": " def __init__(self, input_lines: List[str], regex='', initial_context=0) -> None:\n\n self.win = curses.initscr()\n\n self.win.keypad(True)\n\n curses.start_color()\n\n\n\n curses.init_pair(1, curses.COLOR_RED, curses.COLOR_BLACK)\n\n curses.init_pair(2, curses.COLOR_GREEN, curses.COLOR_BLACK)\n\n curses.init_pair(3, curses.COLOR_YELLOW, curses.COLOR_BLACK)\n\n curses.init_pair(4, curses.COLOR_BLUE, curses.COLOR_BLACK)\n\n curses.init_pair(5, curses.COLOR_MAGENTA, curses.COLOR_BLACK)\n\n curses.init_pair(6, curses.COLOR_CYAN, curses.COLOR_BLACK)\n\n curses.init_pair(30, curses.COLOR_RED, curses.COLOR_WHITE)\n\n curses.init_pair(31, curses.COLOR_BLACK, curses.COLOR_WHITE)\n\n curses.init_pair(32, curses.COLOR_BLACK, curses.COLOR_BLACK)\n\n curses.use_default_colors()\n\n\n\n self.regex = regex\n\n self.input_lines = input_lines\n\n self.display_mode = DisplayMode.show_default\n\n self.pager_ypos = 0\n\n self.pager_xpos = 0\n\n self.search = Search(self.input_lines, initial_context=initial_context)\n", "file_path": "python/igrepper/igrepper.py", "rank": 42, "score": 20137.486156299325 }, { "content": "class Match:\n\n def __init__(self, regex_match):\n\n self.text = regex_match.group()\n\n self.start = regex_match.start()\n\n self.end = regex_match.end()\n", "file_path": "python/igrepper/igrepper.py", "rank": 43, "score": 20137.486156299325 }, { "content": "def main():\n\n parser = argparse.ArgumentParser()\n\n parser.add_argument(\"file\", nargs='?')\n\n group = parser.add_mutually_exclusive_group()\n\n\n\n group.add_argument(\"-e\", \"--regexp\", action=\"store\", default='', help=\"Regular expression to preload\")\n\n group.add_argument(\"-w\", \"--word\", action=\"store_true\", help=\"Preload the regular expression '\\\\S+'\")\n\n parser.add_argument(\"-c\", \"--context\", action=\"store\", type=int, default=0,\n\n help=\"Print CONTEXT num of output context\")\n\n parser.add_argument(\"-d\", \"--debug\", action=\"store_true\", default=False)\n\n\n\n args = parser.parse_args()\n\n\n\n global debug\n\n debug = args.debug\n\n\n\n if sys.stdin.isatty():\n\n if not args.file:\n\n print('Data can only be passed by STDIN if no file parameter is specified', file=sys.stderr)\n\n exit(1)\n\n with open(args.file) as f:\n\n input_lines = f.read().split('\\n')\n\n else:\n\n if args.file:\n\n print('Data can only be passed by STDIN if no file parameter is specified', file=sys.stderr)\n\n exit(1)\n\n # Hack to read stdin from pipe and then from tty\n\n input_lines = ''.join(sys.stdin.read()).split('\\n')\n\n os.close(sys.stdin.fileno())\n\n sys.__stdin__ = sys.stdin = open('/dev/tty')\n\n\n\n initial_regex = args.regexp\n\n if args.word:\n\n initial_regex = WORD_REGEX\n\n try:\n\n f = IGrepper(input_lines, initial_regex, initial_context=args.context)\n\n f.run()\n\n finally:\n", "file_path": "python/igrepper/igrepper.py", "rank": 44, "score": 20137.486156299325 }, { "content": "def render(search: Search, window, pager_ypos: int, pager_xpos: int):\n\n more_lines_after = True\n\n maxy, maxx = window.getmaxyx()\n\n footer_div_ypos = maxy - 2\n\n status_line_ypos = maxy - 1\n\n header_line_no = len(search.previous_searches) + 2\n\n pager_line_no = maxy - header_line_no - FOOTER_LINE_NO\n\n if pager_line_no < 1 or maxx < 5:\n\n try:\n\n window.addstr('window too small'[:maxx])\n\n except:\n\n pass\n\n return\n\n\n\n for m in search.previous_searches:\n\n window.addstr('{}\\n'.format(m.regex))\n\n\n\n regex_color = curses.color_pair(0) if search.valid else curses.color_pair(30)\n\n window.addstr('{}\\n'.format(search.regex), regex_color)\n\n header_char, header_color = ('^', curses.color_pair(31)) if pager_ypos > 0 else ('-', curses.color_pair(0))\n\n window.addstr(header_char * maxx, header_color)\n\n\n\n # trim output to visible by pager\n\n max_pager_ypos = max(0, len(search.output_lines) - pager_line_no)\n\n if pager_ypos >= max_pager_ypos:\n\n more_lines_after = False\n\n output_lines = search.output_lines[pager_ypos:pager_ypos + pager_line_no]\n\n\n\n # Fill break lines with text to display\n\n for l in output_lines:\n\n if l.break_line:\n\n l.line_text = '-' * maxx\n\n\n\n line_text_to_print = [line.line_text[pager_xpos:pager_xpos + maxx - 1] for line in output_lines]\n\n\n\n # write output\n\n window.addstr('\\n'.join(line_text_to_print))\n\n\n\n # highlight break lines\n\n for lineno, line_object in enumerate(output_lines):\n\n if line_object.break_line:\n\n color = curses.color_pair(32)\n\n window.chgat(lineno + header_line_no, 0 - pager_xpos, maxx, color | curses.A_BOLD)\n\n\n\n # highlight matches\n\n for lineno, line_object in enumerate(output_lines):\n\n for match in line_object.line_matches:\n\n # Only highlight if inside pager view\n\n def inside_pager(match_start, match_end, first_visible_x, last_visible_x):\n\n if match_start < first_visible_x or match_start > last_visible_x:\n\n return False\n\n if match_end < first_visible_x or match_end > last_visible_x:\n\n return False\n\n return True\n\n\n\n if inside_pager(match.start, match.end, pager_xpos, pager_xpos + maxx - 1):\n\n if match.unique_id == search.selected_match:\n\n color = curses.color_pair(31)\n\n else:\n\n color = curses.color_pair((match.unique_id % AVAILABLE_COLORS) + 1)\n\n window.chgat(lineno + header_line_no, match.start - pager_xpos, match.end - match.start,\n\n color | curses.A_BOLD)\n\n\n\n # Footer\n\n footer_char, footer_color = ('v', curses.color_pair(31)) if more_lines_after else ('-', curses.color_pair(0))\n\n window.addstr(footer_div_ypos, 0, footer_char * maxx, footer_color)\n\n case_sensitivity_text = \"[case insensitive], \" if search.ignore_case else \"[case sensitive], \"\n\n status_line = case_sensitivity_text + \\\n\n 'context: {}, '.format(search.context) + \\\n\n 'lines: {}, '.format(search.number_of_matched_lines) + \\\n\n 'matches: {}, '.format(search.match_count) + \\\n\n 'unique: {}, '.format(search.unique_match_count) + \\\n\n 'pag_y: {}, pag_x: {} '.format(pager_ypos, pager_xpos)\n\n status_line = status_line[:maxx - 1]\n", "file_path": "python/igrepper/igrepper.py", "rank": 45, "score": 20137.486156299325 }, { "content": "class Line:\n\n def __init__(self, orig_line_no: int, line_text: str, line_matches: List[Match], break_line=False) -> None:\n\n self.orig_line_no = orig_line_no\n\n self.line_text = line_text\n\n self.line_matches = line_matches\n", "file_path": "python/igrepper/igrepper.py", "rank": 46, "score": 20137.486156299325 }, { "content": " def update(self, regex: str):\n\n self.regex = regex\n\n if self.is_empty():\n\n self.output_lines = []\n\n for orig_line_no, line in enumerate(self._input_lines):\n\n self.output_lines.append(Line(orig_line_no, line, []))\n\n return\n\n try:\n\n if self.ignore_case:\n\n rg = re.compile(self.regex, re.IGNORECASE)\n\n else:\n\n rg = re.compile(self.regex)\n\n self.valid = True\n\n except re.error:\n\n self.valid = False\n\n return\n\n self.output_lines = []\n\n output_lines_dict = {}\n\n self.lines = [[Match(x) for x in rg.finditer(l)] for l in self._input_lines]\n\n for orig_line_number, matches_on_line in enumerate(self.lines):\n\n if matches_on_line:\n\n match_line = Line(orig_line_number, self._input_lines[orig_line_number], matches_on_line)\n\n output_lines_dict[orig_line_number] = match_line # Override possible context line with a match line\n\n\n\n # Add context lines, including break lines\n\n if self.context > 0:\n\n first_context_line = True\n\n for context_line_no in range(orig_line_number - self.context, orig_line_number + self.context + 1):\n\n if context_line_no < 0 or context_line_no >= len(self._input_lines):\n\n continue\n\n if context_line_no in output_lines_dict:\n\n # Already exists\n\n continue\n\n if first_context_line and len(output_lines_dict) > 1 and context_line_no > 1 \\\n\n and context_line_no - 2 not in output_lines_dict:\n\n # create break\n\n b = Line(context_line_no - 1, '', [], break_line=True)\n\n output_lines_dict[context_line_no - 1] = b\n\n first_context_line = False\n\n output_lines_dict[context_line_no] = Line(context_line_no, self._input_lines[context_line_no],\n\n [])\n\n\n\n self.output_lines = [output_lines_dict[x] for x in sorted(output_lines_dict.keys())]\n\n\n\n matches = [match for line in self.lines for match in line]\n\n nonempty_matches = [match for match in matches if match]\n\n self.unique_matches = []\n\n for match in nonempty_matches:\n\n if match.text in self.unique_matches:\n\n match.unique_id = self.unique_matches.index(match.text)\n\n else:\n\n self.unique_matches.append(match.text)\n\n match.unique_id = len(self.unique_matches) - 1\n\n\n\n self.match_count = len(nonempty_matches)\n\n self.unique_match_count = len(self.unique_matches)\n", "file_path": "python/igrepper/igrepper.py", "rank": 47, "score": 20137.486156299325 }, { "content": " def is_empty(self):\n", "file_path": "python/igrepper/igrepper.py", "rank": 48, "score": 20137.486156299325 }, { "content": "def log_with_debugging(func):\n\n \"\"\"\n\n Decorator to log exceptions when debug argument is passed in order to\n\n catch keycodes etc.\n\n \"\"\"\n\n def inner(*args, **kwargs):\n\n try:\n\n # TODO e.g. a -d2 argument to change this into debug\n\n # logging is set to INFO by default\n\n Logger.log.debug(args)\n\n return func(*args, **kwargs)\n\n except:\n\n if debug:\n\n Logger.log.exception('Arguments were: %r', args[1:])\n\n else:\n\n raise\n", "file_path": "python/igrepper/igrepper.py", "rank": 49, "score": 19839.889750505805 }, { "content": " def process_char(self, char: int):\n\n if char < 0:\n\n # in tmux this is an option when the pane gets resized\n\n return\n\n elif char in (CTRL_H, curses.KEY_BACKSPACE, MAC_BACKSPACE):\n\n if len(self.regex) > 0:\n\n self.regex = self.regex[:-1]\n\n elif char in (CTRL_L, curses.KEY_RESIZE):\n\n pass # The curses window has been resized, so re-render it\n\n elif char == CTRL_N:\n\n if self.search.valid:\n\n previous_match_objects = self.search.previous_searches + [self.search]\n\n self.search = Search([l.line_text for l in self.search.output_lines if not l.break_line])\n\n self.search.previous_searches = previous_match_objects\n\n self.search.context = previous_match_objects[-1].context\n\n self.regex = ''\n\n elif char == CTRL_P:\n\n if self.search.previous_searches:\n\n self.search = self.search.previous_searches.pop()\n\n self.regex = self.search.regex\n\n elif char == CTRL_O:\n\n self.toggle_display_mode()\n\n elif char == CTRL_J:\n\n self.search.next_match()\n\n elif char == CTRL_K:\n\n self.search.prev_match()\n\n elif char == CTRL_G:\n\n self.endwin()\n\n grep_commands = []\n\n for m in self.search.previous_searches + [self.search]:\n\n options = '--perl-regexp '\n\n if m.ignore_case:\n\n options += '--ignore-case '\n\n if m.context > 0:\n\n options += '--context {} '.format(m.context)\n\n grep_commands.append(\"{} {}'{}' \".format(*grep_cmd(), options, m.regex.replace(\"'\", \"\\\\'\")))\n\n to_yank = ' | '.join(grep_commands)\n\n copy_to_clipboard(to_yank)\n\n self.quit = True\n\n elif char == CTRL_Y:\n\n if not self.search.unique_matches:\n\n return\n\n self.endwin()\n\n to_yank = self.search.unique_matches[self.search.selected_match]\n\n if to_yank:\n\n copy_to_clipboard(to_yank)\n\n self.quit = True\n\n elif char == CTRL_V:\n\n self.search.ignore_case = not self.search.ignore_case\n\n elif char == curses.KEY_DOWN:\n\n self.pager_ypos += 1\n\n elif char == curses.KEY_NPAGE:\n\n self.pager_ypos = self.pager_ypos + self.get_number_of_pager_lines()\n\n elif char == CTRL_D:\n\n self.pager_ypos = self.pager_ypos + int(self.get_number_of_pager_lines() / 2)\n\n elif char == curses.KEY_UP:\n\n self.pager_ypos = max(0, self.pager_ypos - 1)\n\n elif char == curses.KEY_PPAGE:\n\n self.pager_ypos = max(0, self.pager_ypos - self.get_number_of_pager_lines())\n\n elif char == CTRL_U:\n\n self.pager_ypos = max(0, self.pager_ypos - int(self.get_number_of_pager_lines() / 2))\n\n elif char == curses.KEY_RIGHT:\n\n self.pager_xpos += 1\n\n elif char == curses.KEY_LEFT:\n\n self.pager_xpos = max(0, self.pager_xpos - 1)\n\n elif char == CTRL_R:\n\n self.search.context = max(0, self.search.context - 1)\n\n elif char == CTRL_T:\n\n self.search.context += 1\n\n else:\n\n self.regex += chr(char)\n\n\n\n max_pager_ypos = max(0, len(self.search.output_lines) - self.get_number_of_pager_lines())\n", "file_path": "python/igrepper/igrepper.py", "rank": 50, "score": 19836.70176296697 }, { "content": " def next_match(self):\n\n if self.unique_matches:\n", "file_path": "python/igrepper/igrepper.py", "rank": 51, "score": 19836.70176296697 }, { "content": " def prev_match(self):\n\n if self.unique_matches:\n", "file_path": "python/igrepper/igrepper.py", "rank": 52, "score": 19836.70176296697 }, { "content": "def grep_cmd() -> list:\n\n \"\"\"\n\n Compatibility helper for macOS which by default doesn't have a GNU flavoured\n\n grep command and thus ```grep --perl-regexp``` is not a valid option\n\n \"\"\"\n\n grep_cmd = ['grep']\n\n if sys.platform == 'darwin':\n\n which_ggrep_query = str(run(['which', 'ggrep'], stdout=PIPE).stdout)\n\n if 'not found' in which_ggrep_query:\n\n grep_version_query = str(run(['grep', '--version'], stdout=PIPE).stdout)\n\n if 'BSD' in grep_version_query:\n\n print('Your grep is of BSD flavour and doesn\\'t support perl type regexp')\n\n print('( ' + grep_version_query.splitlines()[0] + ' )')\n\n print('Consider installing GNU grep: brew install grep')\n\n else:\n\n print('Unknown grep flavour.. trying \\'grep\\'')\n\n print('( ' + grep_version_query.splitlines()[0] + ' )')\n\n else:\n\n grep_cmd = ['ggrep']\n\n\n", "file_path": "python/igrepper/igrepper.py", "rank": 53, "score": 19836.70176296697 }, { "content": "class DisplayMode(Enum):\n\n show_default = 1\n\n show_all = 2\n\n show_only_match = 3\n", "file_path": "python/igrepper/igrepper.py", "rank": 54, "score": 19836.70176296697 }, { "content": "def copy_to_clipboard(string):\n\n print('Copied to clipboard: \\n\\n' + BOLD + INVERTED + string + RESET + '\\n')\n\n p = Popen(clipboard_cmd(), stdin=PIPE)\n", "file_path": "python/igrepper/igrepper.py", "rank": 55, "score": 19836.70176296697 }, { "content": "def clipboard_cmd() -> list:\n\n if sys.platform == 'darwin':\n\n return ['pbcopy']\n\n else:\n", "file_path": "python/igrepper/igrepper.py", "rank": 56, "score": 19836.70176296697 }, { "content": " def inside_pager(match_start, match_end, first_visible_x, last_visible_x):\n\n if match_start < first_visible_x or match_start > last_visible_x:\n\n return False\n\n if match_end < first_visible_x or match_end > last_visible_x:\n\n return False\n", "file_path": "python/igrepper/igrepper.py", "rank": 57, "score": 19836.70176296697 }, { "content": "def test_igrepper():\n\n wrote_output = False\n\n tty_inputs = [\n\n ['i', '.', CTRL_J, CTRL_J, CTRL_K, CTRL_H, CTRL_N, '\\\\', 'w', '+'],\n\n ['\\\\', 'd', CTRL_H, curses.KEY_BACKSPACE],\n\n [curses.KEY_DOWN, curses.KEY_DOWN, '.', '\\\\', 'd', CTRL_N, 'p', CTRL_I, '.', CTRL_P],\n\n ['l', CTRL_H]\n\n ]\n\n tty_inputs = [[ord(y) if type(y) == str else y for y in x] for x in tty_inputs]\n\n\n\n sample_names = ['simple', 'longlines']\n\n for sample_name in sample_names:\n\n for tty_input_no, tty_input in enumerate(tty_inputs):\n\n input_lines = get_sample(sample_name)\n\n output = run(input_lines, tty_input)\n\n try:\n\n with open('expected/{}_{}'.format(sample_name, tty_input_no)) as f:\n\n expected = json.load(f)\n\n if expected != output:\n\n with open('diffs/expected_{}_{}'.format(sample_name, tty_input_no), 'w') as f:\n\n f.write(str('\\n'.join([str(_) for _ in expected])))\n\n with open('diffs/actual_{}_{}'.format(sample_name, tty_input_no), 'w') as f:\n\n f.write(str('\\n'.join([str(_) for _ in output])))\n\n assert expected == output\n\n except FileNotFoundError:\n\n wrote_output = True\n\n with open('expected/{}_{}'.format(sample_name, tty_input_no), 'w') as f:\n\n json.dump(output, f)\n\n if wrote_output:\n\n print('Output files written, rerun test')\n\n assert False\n", "file_path": "python/test/test_igrepper.py", "rank": 58, "score": 19544.770491629708 }, { "content": " def toggle_display_mode(self):\n\n if self.display_mode == DisplayMode.show_default:\n\n self.display_mode = DisplayMode.show_only_match\n\n elif self.display_mode == DisplayMode.show_only_match:\n\n self.display_mode = DisplayMode.show_all\n\n elif self.display_mode == DisplayMode.show_all:\n", "file_path": "python/igrepper/igrepper.py", "rank": 59, "score": 19544.770491629708 }, { "content": " def get_number_of_pager_lines(self):\n\n maxy, _ = self.win.getmaxyx()\n\n header_line_no = len(self.search.previous_searches) + 2\n\n pager_line_no = maxy - header_line_no - FOOTER_LINE_NO\n", "file_path": "python/igrepper/igrepper.py", "rank": 60, "score": 19261.307144273112 }, { "content": "name = 'igrepper'\n\n\n", "file_path": "python/igrepper/__init__.py", "rank": 61, "score": 18564.33403336556 }, { "content": "import pytest\n\nimport unittest\n\nfrom unittest import mock\n\nfrom unittest.mock import Mock, patch\n\nimport subprocess\n\nfrom pprint import pprint\n\nimport json\n\nimport curses\n\n\n\nfrom unittest.mock import MagicMock\n\n\n\nfrom igrepper.igrepper import Search, DisplayMode, render, IGrepper\n\nfrom igrepper.igrepper import CTRL_I, CTRL_Y, CTRL_G, CTRL_K, CTRL_J, CTRL_P, CTRL_N, CTRL_H, CTRL_O\n\n\n\n\n\ndef get_sample(filename):\n\n with open('samples/{}'.format(filename)) as f:\n\n return ''.join(f.readlines()).split('\\n')\n\n\n\n\n\ndef grep(filename, regex):\n\n try:\n\n return subprocess.check_output(['grep', '-P', regex, './samples/{}'.format(filename)]) \\\n\n .decode('utf-8') \\\n\n .split('\\n')\n\n except ZeroDivisionError:\n\n return ''\n\n\n\n\n\ndef slog(m):\n\n import subprocess\n\n subprocess.run([\"notify-send\", str(m)])\n\n\n\n\n\nmock_color_pair = MagicMock(side_effect=lambda x: x)\n\n\n\n\n\[email protected](\"curses.initscr\", mock.MagicMock())\n\[email protected](\"curses.start_color\", mock.MagicMock())\n\[email protected](\"curses.init_pair\", mock.MagicMock())\n\[email protected](\"curses.use_default_colors\", mock.MagicMock())\n\[email protected](\"curses.color_pair\", mock_color_pair)\n\ndef test_igrepper():\n\n wrote_output = False\n\n tty_inputs = [\n\n ['i', '.', CTRL_J, CTRL_J, CTRL_K, CTRL_H, CTRL_N, '\\\\', 'w', '+'],\n\n ['\\\\', 'd', CTRL_H, curses.KEY_BACKSPACE],\n\n [curses.KEY_DOWN, curses.KEY_DOWN, '.', '\\\\', 'd', CTRL_N, 'p', CTRL_I, '.', CTRL_P],\n\n ['l', CTRL_H]\n\n ]\n\n tty_inputs = [[ord(y) if type(y) == str else y for y in x] for x in tty_inputs]\n\n\n\n sample_names = ['simple', 'longlines']\n\n for sample_name in sample_names:\n\n for tty_input_no, tty_input in enumerate(tty_inputs):\n\n input_lines = get_sample(sample_name)\n\n output = run(input_lines, tty_input)\n\n try:\n\n with open('expected/{}_{}'.format(sample_name, tty_input_no)) as f:\n\n expected = json.load(f)\n\n if expected != output:\n\n with open('diffs/expected_{}_{}'.format(sample_name, tty_input_no), 'w') as f:\n\n f.write(str('\\n'.join([str(_) for _ in expected])))\n\n with open('diffs/actual_{}_{}'.format(sample_name, tty_input_no), 'w') as f:\n\n f.write(str('\\n'.join([str(_) for _ in output])))\n\n assert expected == output\n\n except FileNotFoundError:\n\n wrote_output = True\n\n with open('expected/{}_{}'.format(sample_name, tty_input_no), 'w') as f:\n\n json.dump(output, f)\n\n if wrote_output:\n\n print('Output files written, rerun test')\n\n assert False\n\n return\n\n\n\n\n\ndef run(input_lines, tty_input):\n\n f = IGrepper(input_lines, '')\n\n f.win = MagicMock(return_value=3)\n\n f.win.refresh = MagicMock()\n\n f.win.getmaxyx = MagicMock(return_value=(30, 20))\n\n written = []\n\n\n\n def mock_getch(param=None):\n\n x = 0\n\n l = tty_input\n\n\n\n def inner():\n\n # sleep(0.1)\n\n nonlocal x\n\n if x >= len(l):\n\n f.quit = True\n\n return ord('d')\n\n ret = l[x]\n\n x += 1\n\n return ret\n\n\n\n return inner\n\n\n\n f.win.getch = Mock(side_effect=mock_getch())\n\n\n\n def mock_erase():\n\n written.append([])\n\n\n\n f.win.erase = Mock(side_effect=mock_erase)\n\n written = []\n\n\n\n def mock_addstr(a, b=None, c=None, d=None):\n\n written[-1].append([a, b, c, d])\n\n\n\n f.win.addstr = Mock(side_effect=mock_addstr)\n\n\n\n f.run()\n\n # pprint(written)\n\n return written\n", "file_path": "python/test/test_igrepper.py", "rank": 62, "score": 18183.076375281962 }, { "content": "def grep(filename, regex):\n\n try:\n\n return subprocess.check_output(['grep', '-P', regex, './samples/{}'.format(filename)]) \\\n\n .decode('utf-8') \\\n\n .split('\\n')\n\n except ZeroDivisionError:\n", "file_path": "python/test/test_igrepper.py", "rank": 63, "score": 17817.16343740712 }, { "content": "def run(input_lines, tty_input):\n\n f = IGrepper(input_lines, '')\n\n f.win = MagicMock(return_value=3)\n\n f.win.refresh = MagicMock()\n\n f.win.getmaxyx = MagicMock(return_value=(30, 20))\n\n written = []\n\n\n\n def mock_getch(param=None):\n\n x = 0\n\n l = tty_input\n\n\n\n def inner():\n\n # sleep(0.1)\n\n nonlocal x\n\n if x >= len(l):\n\n f.quit = True\n\n return ord('d')\n\n ret = l[x]\n\n x += 1\n\n return ret\n\n\n\n return inner\n\n\n\n f.win.getch = Mock(side_effect=mock_getch())\n\n\n\n def mock_erase():\n\n written.append([])\n\n\n\n f.win.erase = Mock(side_effect=mock_erase)\n\n written = []\n\n\n\n def mock_addstr(a, b=None, c=None, d=None):\n\n written[-1].append([a, b, c, d])\n\n\n\n f.win.addstr = Mock(side_effect=mock_addstr)\n\n\n\n f.run()\n\n # pprint(written)\n", "file_path": "python/test/test_igrepper.py", "rank": 64, "score": 17817.16343740712 }, { "content": " def inner():\n\n # sleep(0.1)\n\n nonlocal x\n\n if x >= len(l):\n\n f.quit = True\n\n return ord('d')\n\n ret = l[x]\n\n x += 1\n", "file_path": "python/test/test_igrepper.py", "rank": 65, "score": 17817.16343740712 }, { "content": "def slog(m):\n\n import subprocess\n", "file_path": "python/test/test_igrepper.py", "rank": 66, "score": 17817.16343740712 }, { "content": "def get_sample(filename):\n\n with open('samples/{}'.format(filename)) as f:\n", "file_path": "python/test/test_igrepper.py", "rank": 67, "score": 17465.687111235893 }, { "content": " def mock_addstr(a, b=None, c=None, d=None):\n", "file_path": "python/test/test_igrepper.py", "rank": 68, "score": 17465.687111235893 }, { "content": " def mock_getch(param=None):\n\n x = 0\n\n l = tty_input\n\n\n\n def inner():\n\n # sleep(0.1)\n\n nonlocal x\n\n if x >= len(l):\n\n f.quit = True\n\n return ord('d')\n\n ret = l[x]\n\n x += 1\n\n return ret\n\n\n", "file_path": "python/test/test_igrepper.py", "rank": 69, "score": 17465.687111235893 }, { "content": " def mock_erase():\n", "file_path": "python/test/test_igrepper.py", "rank": 70, "score": 17465.687111235893 }, { "content": " search_line: s,\n\n output_generator,\n\n },\n\n );\n\n }\n\n }\n\n}\n\n\n\n#[cfg(test)]\n\nmod tests {\n\n use super::*;\n\n use crate::igrepper::state::SearchLine;\n\n use std::collections::HashSet;\n\n\n\n use std::fs::File;\n\n use std::io::{Read, Write};\n\n use std::{fs, io};\n\n\n\n extern crate serde_json;\n\n\n", "file_path": "src/igrepper/core.rs", "rank": 71, "score": 16152.126717900803 }, { "content": "extern crate ncurses;\n\n\n\nuse crate::igrepper::constants::*;\n\nuse crate::igrepper::types::{RenderState, StringWithColorIndex, StringWithColorIndexOrBreakLine};\n\nuse ncurses::{\n\n box_, chtype, getmaxyx, mvaddstr, mvwaddstr, mvwhline, newwin, stdscr, wattroff, wattron,\n\n wbkgd, wrefresh, A_BOLD, A_REVERSE, COLOR_PAIR,\n\n};\n\n\n", "file_path": "src/igrepper/rendering.rs", "rank": 72, "score": 16148.227475286541 }, { "content": "use crate::igrepper::output_generator::{Len, OutputGenerator};\n\nuse crate::igrepper::state::{SearchLine, State};\n\nuse crate::igrepper::trimming::produce_render_state;\n\nuse crate::igrepper::types::RenderState;\n\nuse std::collections::HashMap;\n\n\n\n#[derive(Debug)]\n", "file_path": "src/igrepper/core.rs", "rank": 73, "score": 16147.385756880203 }, { "content": "use crate::igrepper::constants::*;\n\nuse crate::igrepper::output_generator::{Len, OutputGenerator};\n\nuse crate::igrepper::state::SearchLine;\n\nuse crate::igrepper::types::{\n\n Line, LineWithMatches, RenderState, StringWithColorIndex, StringWithColorIndexOrBreakLine,\n\n};\n\nuse std::cmp;\n\nuse std::collections::HashMap;\n\n\n\n/// Returns a state that can be rendered to the screen\n\n///\n\n/// <──────────── content_width ────────────>\n\n/// <──────────────── max_x ──────────────────>\n\n/// ^ ┌─────────────────────────────────────────┐\n\n/// │ │▓▓▓▓▓▓▓▓▓▓▓▓ │ <- input window, search lines\n\n/// │ │▓▓▓▓▓▓▓ │\n\n/// │ └─────────────────────────────────────────┘\n\n/// │ ┌─────────────────────────────────────────┐\n\n/// max_y │ │░░░░░░░░░░░░░░░░░░░░░ │ <- pager window, output lines\n\n/// │ │░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░ │\n\n/// │ │░░░░░░░░░ │\n\n/// │ │░░░░░░░░░░░░░ │\n\n/// │ └─────────────────────────────────────────┘\n\n/// v ▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓ <- status line\n\n///\n", "file_path": "src/igrepper/trimming.rs", "rank": 74, "score": 16146.474620962648 }, { "content": "use super::regex::{Error, Regex};\n\nuse crate::igrepper::constants::CASE_INSENSITIVE_PREFIX;\n\nuse crate::igrepper::trimming::{content_width, pager_content_height, pager_window_height};\n\nuse std::cmp;\n\n\n\n#[derive(Debug, Clone)]\n\npub struct State {\n\n source_lines: Vec<String>,\n\n search_lines: Vec<SearchLine>,\n\n last_valid_regex: Regex,\n\n pager_x: u32,\n\n pager_y: u32,\n\n max_y: u32,\n\n max_x: u32,\n\n}\n\n\n\n#[derive(Debug, Clone, PartialEq, Eq, PartialOrd, Ord, Hash)]\n\npub struct SearchLine {\n\n pub line: String,\n\n pub context: u32,\n", "file_path": "src/igrepper/state.rs", "rank": 75, "score": 16144.231770249027 }, { "content": "\n\n fn read_map_from_disk(test_name: &str) -> Result<HashMap<String, String>, io::Error> {\n\n let mut file = File::open(format!(\n\n \"{}/{}.snapshot.json\",\n\n SNAPSHOT_DIRECTORY, test_name\n\n ))?;\n\n let mut contents = String::new();\n\n file.read_to_string(&mut contents)?;\n\n let deserialized: HashMap<String, String> = serde_json::from_str(&contents).unwrap();\n\n Ok(deserialized)\n\n }\n\n\n\n fn write_to_disk(\n\n test_name: &str,\n\n test_results: &HashMap<String, String>,\n\n ) -> Result<(), io::Error> {\n\n let mut file = File::create(format!(\n\n \"{}/{}.snapshot.json\",\n\n SNAPSHOT_DIFF_DIRECTORY, test_name\n\n ))?;\n\n file.write_all(\n\n serde_json::to_string_pretty(&test_results)\n\n .unwrap()\n\n .as_ref(),\n\n )?;\n\n Ok(())\n\n }\n\n}\n", "file_path": "src/igrepper/core.rs", "rank": 76, "score": 16141.257959610617 }, { "content": "use crate::igrepper::state::SearchLine;\n\n\n\n#[derive(Debug, Clone)]\n\npub struct RenderState {\n\n pub regex_valid: bool,\n\n pub max_y: u32,\n\n pub max_x: u32,\n\n pub input_window_height: u32,\n\n pub pager_window_height: u32,\n\n pub output_search_lines: Vec<SearchLine>,\n\n pub output_display_lines: Vec<StringWithColorIndexOrBreakLine>,\n\n pub status_line: String,\n\n}\n\n\n\n#[derive(Debug, Clone)]\n\npub enum StringWithColorIndexOrBreakLine {\n\n StringWithColorIndex(Vec<StringWithColorIndex>),\n\n BreakLine,\n\n}\n\n\n", "file_path": "src/igrepper/types.rs", "rank": 77, "score": 16141.152348528702 }, { "content": "}\n\n\n\n#[cfg(test)]\n\nmod tests {\n\n use super::*;\n\n use pretty_assertions::assert_eq;\n\n\n\n #[test]\n\n #[should_panic(expected = \"The vector 'search_lines' in State must be non-empty\")]\n\n fn panic_on_empty_search_lines() {\n\n State::new(vec![], vec![], 0, 0, 0, 0);\n\n }\n\n\n\n #[test]\n\n #[should_panic(\n\n expected = \"All except the last line in 'search_lines' need to be valid regexes\"\n\n )]\n\n fn panic_on_invalid_initial_regex() {\n\n State::new(\n\n vec![],\n", "file_path": "src/igrepper/state.rs", "rank": 78, "score": 16140.966140067409 }, { "content": " }\n\n output_search_lines\n\n}\n\n\n\n#[cfg(test)]\n\nmod tests {\n\n use super::*;\n\n use pretty_assertions::assert_eq;\n\n\n\n #[test]\n\n fn replace_tabs_with_spaces_zero_current_steps() {\n\n assert_eq!(\" x\", replace_tabs_with_spaces(0, \"\\tx\"));\n\n assert_eq!(\"x x\", replace_tabs_with_spaces(0, \"x\\tx\"));\n\n assert_eq!(\"xx x\", replace_tabs_with_spaces(0, \"xx\\tx\"));\n\n assert_eq!(\"xxx x\", replace_tabs_with_spaces(0, \"xxx\\tx\"));\n\n assert_eq!(\"xxxx x\", replace_tabs_with_spaces(0, \"xxxx\\tx\"));\n\n }\n\n\n\n #[test]\n\n fn replace_tabs_with_spaces_different_current_steps() {\n\n assert_eq!(\" x\", replace_tabs_with_spaces(1, \"\\tx\"));\n\n assert_eq!(\" x\", replace_tabs_with_spaces(2, \"\\tx\"));\n\n assert_eq!(\" x\", replace_tabs_with_spaces(3, \"\\tx\"));\n\n assert_eq!(\" x\", replace_tabs_with_spaces(4, \"\\tx\"));\n\n }\n\n}\n", "file_path": "src/igrepper/trimming.rs", "rank": 79, "score": 16139.826856453017 }, { "content": " .into_string()\n\n .unwrap()\n\n .ends_with(\".snapshot.json\")\n\n {\n\n fs::remove_file(dir_entry.path()).unwrap();\n\n }\n\n }\n\n\n\n let source_lines_list = vec![\n\n vec![String::from(\"\")],\n\n vec![String::from(\"blah\")],\n\n vec![\n\n String::from(\"one\"),\n\n String::from(\"two\"),\n\n String::from(\"three\"),\n\n ],\n\n (0..100)\n\n .map(|i| String::from(format!(\"{}\", i)))\n\n .collect::<Vec<String>>(),\n\n ];\n", "file_path": "src/igrepper/core.rs", "rank": 80, "score": 16138.402214232761 }, { "content": " const SNAPSHOT_DIRECTORY: &str = \"tests/snapshots\";\n\n const SNAPSHOT_DIFF_DIRECTORY: &str = \"tests/snapshots_diff\";\n\n\n\n #[test]\n\n fn test_one() {\n\n let source_lines = vec![String::from(\"blah\")];\n\n let mut core = Core::new();\n\n let state = State::new(\n\n source_lines,\n\n vec![SearchLine::new(String::from(\"\"), 0, true, false)],\n\n 0,\n\n 0,\n\n 10,\n\n 10,\n\n );\n\n let output = core.get_render_state(&state);\n\n let serialized = format!(\"{:?}\", output);\n\n assert_eq!(serialized, \"RenderState { regex_valid: true, max_y: 10, max_x: 10, input_window_height: 3, pager_window_height: 6, output_search_lines: [SearchLine { line: \\\"\\\", context: 0, case_sensitive: true, inverse: false }], output_display_lines: [StringWithColorIndex([String(\\\"b\\\"), String(\\\"l\\\"), String(\\\"a\\\"), String(\\\"h\\\")])], status_line: \\\"matchedLin\\\" }\");\n\n }\n\n\n", "file_path": "src/igrepper/core.rs", "rank": 81, "score": 16138.349693304275 }, { "content": " wattroff(input_window, COLOR_PAIR(COLOR_PAIR_BORDER));\n\n\n\n for (i, search_line) in render_state.output_search_lines.iter().enumerate() {\n\n let mut line: &str = search_line.line.as_str();\n\n let mut x_start = 1i32;\n\n if search_line.inverse {\n\n wattron(input_window, COLOR_PAIR(COLOR_PAIR_BORDER));\n\n mvwaddstr(input_window, i as i32 + 1, x_start, \"!\");\n\n wattroff(input_window, COLOR_PAIR(COLOR_PAIR_BORDER));\n\n x_start += 1;\n\n }\n\n\n\n if line.starts_with(CASE_INSENSITIVE_PREFIX) {\n\n wattron(input_window, COLOR_PAIR(COLOR_PAIR_BORDER));\n\n mvwaddstr(input_window, i as i32 + 1, x_start, CASE_INSENSITIVE_PREFIX);\n\n wattroff(input_window, COLOR_PAIR(COLOR_PAIR_BORDER));\n\n x_start += CASE_INSENSITIVE_PREFIX.len() as i32;\n\n line = &line[4..line.len()];\n\n }\n\n if i == render_state.output_search_lines.len() - 1 {\n", "file_path": "src/igrepper/rendering.rs", "rank": 82, "score": 16138.239521693582 }, { "content": " pub case_sensitive: bool,\n\n pub inverse: bool,\n\n}\n\n\n\nimpl SearchLine {\n\n pub fn new(line: String, context: u32, case_sensitive: bool, inverse: bool) -> SearchLine {\n\n SearchLine {\n\n line,\n\n context,\n\n case_sensitive,\n\n inverse,\n\n }\n\n }\n\n\n\n pub fn line_with_sensitivity_prefix(&self) -> String {\n\n if self.case_sensitive {\n\n self.line.clone()\n\n } else {\n\n format!(\"{}{}\", CASE_INSENSITIVE_PREFIX, self.line)\n\n }\n\n }\n\n pub fn construct_regex(&self) -> Result<Regex, Error> {\n\n Regex::new(self.line_with_sensitivity_prefix().as_str())\n\n }\n\n}\n\n\n", "file_path": "src/igrepper/state.rs", "rank": 83, "score": 16137.963365556585 }, { "content": "pub const CASE_INSENSITIVE_PREFIX: &str = \"(?i)\";\n\n\n\npub static COLOR_PAIR_DEFAULT: i16 = 128;\n\npub static COLOR_PAIR_INACTIVE_INPUT: i16 = 129;\n\npub static COLOR_PAIR_ACTIVE_INPUT: i16 = 130;\n\npub static COLOR_PAIR_BORDER: i16 = 131; // grey\n\npub static COLOR_PAIR_RED: i16 = 132;\n\n\n\n#[allow(dead_code)]\n\npub static COLOR_PAIR_GREY: i16 = 8;\n\n\n\npub const MAX_MATCH_COLORS: usize = 18;\n\npub const MATCH_COLORS: [i16; 18] = [\n\n 1, // red\n\n 190, // green\n\n 27, // blue\n\n 214, // yellow orange\n\n 206, // pink\n\n 45, // cyan\n\n 5, // maroon?\n", "file_path": "src/igrepper/constants.rs", "rank": 84, "score": 16137.842445417296 }, { "content": " 2, // green\n\n 99, // blue\n\n 220, // yellow\n\n 213, // pinkish\n\n 147, // cyanish\n\n 111, 214, 129, 226, 215, 70,\n\n];\n\n\n\npub const CTRL_D: i32 = 'd' as i32 - 0x60;\n\npub const CTRL_E: i32 = 'e' as i32 - 0x60;\n\npub const CTRL_G: i32 = 'g' as i32 - 0x60;\n\npub const CTRL_H: i32 = 'h' as i32 - 0x60;\n\npub const CTRL_I: i32 = 'i' as i32 - 0x60;\n\npub const CTRL_L: i32 = 'l' as i32 - 0x60;\n\npub const CTRL_N: i32 = 'n' as i32 - 0x60;\n\npub const CTRL_P: i32 = 'p' as i32 - 0x60;\n\npub const CTRL_R: i32 = 'r' as i32 - 0x60;\n\npub const CTRL_T: i32 = 't' as i32 - 0x60;\n\npub const CTRL_U: i32 = 'u' as i32 - 0x60;\n\npub const CTRL_V: i32 = 'v' as i32 - 0x60;\n\npub const F1: i32 = 27;\n\npub const F1_2: i32 = 265;\n\npub const ALTERNATIVE_BACKSPACE: i32 = 127;\n", "file_path": "src/igrepper/constants.rs", "rank": 85, "score": 16137.58766388154 }, { "content": " // We want to colorize each unique match with the same color, so we create a closure\n\n // that keeps track of the matches seen so far.\n\n let mut matches_to_colors = HashMap::new();\n\n let mut color_number: u32 = 0;\n\n let mut get_color = |string: &str| -> u32 {\n\n let s = String::from(string);\n\n if !matches_to_colors.contains_key(&s) {\n\n matches_to_colors.insert(s, color_number);\n\n if color_number < MAX_MATCH_COLORS as u32 - 1 {\n\n color_number += 1;\n\n }\n\n }\n\n matches_to_colors[string]\n\n };\n\n\n\n visible_lines\n\n .iter()\n\n .map(|line| match line {\n\n Line::BreakLine => StringWithColorIndexOrBreakLine::BreakLine,\n\n Line::LineWithMatches(l) => {\n\n trim_and_colorize_line(l, pager_x, content_width, &mut get_color)\n\n }\n\n })\n\n .collect::<Vec<StringWithColorIndexOrBreakLine>>()\n\n}\n\n\n", "file_path": "src/igrepper/trimming.rs", "rank": 86, "score": 16137.575928050679 }, { "content": " pub fn search_lines(&self) -> Vec<SearchLine> {\n\n self.search_lines.clone()\n\n }\n\n pub fn search_line_strings(&self) -> Vec<String> {\n\n self.search_lines\n\n .iter()\n\n .cloned()\n\n .map(|s| s.line)\n\n .collect::<Vec<String>>()\n\n }\n\n\n\n pub fn source_lines(&self) -> Vec<String> {\n\n self.source_lines.clone()\n\n }\n\n\n\n pub fn regex_valid(&self) -> bool {\n\n return match self.regex() {\n\n Ok(_) => true,\n\n Err(_) => false,\n\n };\n", "file_path": "src/igrepper/state.rs", "rank": 87, "score": 16136.01170891032 }, { "content": " }\n\n }\n\n pub fn max_y(&self) -> u32 {\n\n self.max_y\n\n }\n\n pub fn max_x(&self) -> u32 {\n\n self.max_x\n\n }\n\n pub fn pager_y(&self) -> u32 {\n\n self.pager_y\n\n }\n\n pub fn pager_x(&self) -> u32 {\n\n self.pager_x\n\n }\n\n pub fn current_context(&self) -> u32 {\n\n self.search_lines.last().unwrap().context\n\n }\n\n pub fn inverted(&self) -> bool {\n\n self.search_lines.last().unwrap().inverse\n\n }\n", "file_path": "src/igrepper/state.rs", "rank": 88, "score": 16136.01170891032 }, { "content": " let string_with_match =\n\n &original_line[match_range.start as usize..match_range.end as usize];\n\n let color = get_color(string_with_match);\n\n\n\n let string_with_match = replace_tabs_with_spaces(cell_width as u32, string_with_match);\n\n cell_width += string_with_match.chars().count();\n\n\n\n let string_with_match = trim_horizontally(string_with_match);\n\n if !string_with_match.is_empty() {\n\n display_line.push(StringWithColorIndex::MatchString((\n\n String::from(string_with_match),\n\n color,\n\n )));\n\n }\n\n end_of_last_match = match_range.end;\n\n }\n\n // Process the string after the last match\n\n if let Some(last_match) = line_with_match_ranges.matches.last() {\n\n let string_after_last_match =\n\n replace_tabs_with_spaces(cell_width as u32, &original_line[last_match.end as usize..]);\n", "file_path": "src/igrepper/trimming.rs", "rank": 89, "score": 16136.01170891032 }, { "content": " // partial drop\n\n if chars_to_drop > 0 {\n\n s = s\n\n .chars()\n\n .into_iter()\n\n .skip(chars_to_drop as usize)\n\n .collect::<String>();\n\n chars_to_drop = 0;\n\n }\n\n // take\n\n if s.chars().count() as u32 > chars_to_take {\n\n let right_trimmed = s\n\n .chars()\n\n .into_iter()\n\n .take(chars_to_take as usize)\n\n .collect::<String>();\n\n chars_to_take = 0;\n\n return right_trimmed;\n\n }\n\n chars_to_take -= s.chars().count() as u32;\n", "file_path": "src/igrepper/trimming.rs", "rank": 90, "score": 16136.01170891032 }, { "content": " content_width(max_x),\n\n ),\n\n output_display_lines,\n\n status_line: status_line\n\n .chars()\n\n .into_iter()\n\n .take(max_x as usize)\n\n .collect(),\n\n }\n\n}\n\n\n", "file_path": "src/igrepper/trimming.rs", "rank": 91, "score": 16136.01170891032 }, { "content": " return s;\n\n };\n\n\n\n for match_range in &line_with_match_ranges.matches {\n\n // Process string between current position and the start of the next match\n\n if end_of_last_match < match_range.start {\n\n let string_before_match = replace_tabs_with_spaces(\n\n cell_width as u32,\n\n &original_line[end_of_last_match as usize..match_range.start as usize],\n\n );\n\n cell_width += string_before_match.chars().count();\n\n let string_before_match = trim_horizontally(string_before_match);\n\n if !string_before_match.is_empty() {\n\n display_line.push(StringWithColorIndex::String(String::from(\n\n string_before_match,\n\n )));\n\n }\n\n }\n\n\n\n // Process the current match on the line\n", "file_path": "src/igrepper/trimming.rs", "rank": 92, "score": 16136.01170891032 }, { "content": " )\n\n }\n\n\n\n fn new_with_regex(\n\n source_lines: Vec<String>,\n\n search_lines: Vec<SearchLine>,\n\n last_valid_regex: Regex,\n\n pager_x: u32,\n\n pager_y: u32,\n\n max_y: u32,\n\n max_x: u32,\n\n ) -> State {\n\n State {\n\n source_lines,\n\n search_lines,\n\n last_valid_regex,\n\n pager_x,\n\n pager_y,\n\n max_y,\n\n max_x,\n", "file_path": "src/igrepper/state.rs", "rank": 93, "score": 16136.01170891032 }, { "content": " .for_each(|l| {\n\n let regex_valid = l.construct_regex().is_ok();\n\n assert!(\n\n regex_valid,\n\n \"All except the last line in 'search_lines' need to be valid regexes\"\n\n );\n\n });\n\n let regex: Regex = search_lines\n\n .last()\n\n .unwrap()\n\n .construct_regex()\n\n .unwrap_or(default_regex());\n\n State::new_with_regex(\n\n source_lines,\n\n search_lines,\n\n regex,\n\n pager_x,\n\n pager_y,\n\n max_y,\n\n max_x,\n", "file_path": "src/igrepper/state.rs", "rank": 94, "score": 16136.01170891032 }, { "content": " let string_after_last_match = trim_horizontally(string_after_last_match);\n\n if !string_after_last_match.is_empty() {\n\n display_line.push(StringWithColorIndex::String(String::from(\n\n string_after_last_match,\n\n )));\n\n }\n\n } else {\n\n // No matches on this line\n\n let full_line_without_matches = replace_tabs_with_spaces(cell_width as u32, original_line);\n\n let full_line_without_matches = trim_horizontally(full_line_without_matches);\n\n if !full_line_without_matches.is_empty() {\n\n display_line.push(StringWithColorIndex::String(String::from(\n\n full_line_without_matches,\n\n )));\n\n }\n\n }\n\n return StringWithColorIndexOrBreakLine::StringWithColorIndex(display_line);\n\n}\n\n\n", "file_path": "src/igrepper/trimming.rs", "rank": 95, "score": 16136.01170891032 }, { "content": " );\n\n\n\n let matched_lines = match result_generator.len() {\n\n Len::Is(n) => format!(\"={}\", n),\n\n Len::AtLeast(n) => format!(\">{}\", n),\n\n };\n\n let status_line = format!(\n\n \"matchedLines{} pageY: {}, pageX: {}, context: {}\",\n\n matched_lines, pager_y, pager_x, context\n\n );\n\n\n\n RenderState {\n\n regex_valid,\n\n max_y,\n\n max_x,\n\n input_window_height,\n\n pager_window_height: pager_window_height(max_y, search_lines.len() as u32),\n\n output_search_lines: search_lines_display_format(\n\n input_window_height,\n\n search_lines,\n", "file_path": "src/igrepper/trimming.rs", "rank": 96, "score": 16136.01170891032 }, { "content": "### Configuration\n\n\n\n#### External editor\n\n\n\nSet the environment variable `IGREPPER_EDITOR` to a command and arguments, separated by whitespace, to customize which\n\neditor is used when pressing `F1`. The command must support reading from `STDIN`.\n\n\n\nExample `.bashrc` configuration:\n\n\n\n export IGREPPER_EDITOR=\"vim -R -\" # vim in read-only mode (default)\n\n export IGREPPER_EDITOR=\"code -\" # vscode\n\n export IGREPPER_EDITOR=\"nano -v -\" # nano in read-only mode\n\n\n\n## Supported platforms\n\n\n\nTested on Ubuntu 20.04\n\n\n\n## Known issues\n\n\n\n- No unicode support\n\n- Broken colors when using `screen`/`tmux` and `urxvt`. As a workaround, you can either:\n\n - Run `export TERM=rxvt-unicode-256color`\n\n - Add `term screen-256color` to your `.screenrc`\n\n\n\n## Dev dependencies\n\n\n\nUbuntu: `apt-get install libncurses-dev`\n\n\n\n## Release build\n\n\n\n`cargo build --release`\n\n`cargo publish`\n\n\n", "file_path": "index.md", "rank": 98, "score": 12.271052187897661 }, { "content": "### Configuration\n\n\n\n#### External editor\n\n\n\nSet the environment variable `IGREPPER_EDITOR` to a command and arguments, separated by whitespace, to customize which\n\neditor is used when pressing `F1`. The command must support reading from `STDIN`.\n\n\n\nExample `.bashrc` configuration:\n\n\n\n export IGREPPER_EDITOR=\"vim -R -\" # vim in read-only mode (default)\n\n export IGREPPER_EDITOR=\"code -\" # vscode\n\n export IGREPPER_EDITOR=\"nano -v -\" # nano in read-only mode\n\n\n\n## Supported platforms\n\n\n\nTested on Ubuntu 20.04\n\n\n\n## Known issues\n\n\n\n- No unicode support\n\n- Broken colors when using `screen`/`tmux` and `urxvt`. As a workaround, you can either:\n\n - Run `export TERM=rxvt-unicode-256color`\n\n - Add `term screen-256color` to your `.screenrc`\n\n\n\n## Dev dependencies\n\n\n\nUbuntu: `apt-get install libncurses-dev`\n\n\n\n## Release build\n\n\n\n`cargo build --release`\n\n`cargo publish`\n\n\n", "file_path": "README.md", "rank": 99, "score": 12.271052187897663 } ]
Rust
src/lib.rs
aymgm/Mirach
c10f00ed06de0b5ab925b54318e7b5c2e2f14352
#![allow(unused)] extern crate symbol; extern crate thiserror; use std::collections::HashMap; use symbol::Symbol; use thiserror::Error; mod llvm_wrapper; use llvm_wrapper as llvm; mod scope_stack; use scope_stack::{ScopeStack, ScopedValue}; mod func_stack; use func_stack::{FuncStackElem, FuncStack}; mod loop_stack; use loop_stack::LoopStackElem; #[cfg(test)] mod unit_tests; pub type Meta = (u32, u32, u32); #[derive(Error, Debug)] pub enum MirErr { #[error("Cannot create local variable at global scope")] LocalVarOnGlobal, #[error("`{0}` is not modifiable")] ConstNotModifiable(Symbol), #[error("Symbol `{0}` is not found. ")] SymbolNotFound(Symbol), #[error("Cannot get outer scope than static scope")] LeavingStaticScope, #[error("Must have value")] MustHaveValue, } #[derive(Debug)] pub struct MirTy { ty: Symbol, args: Vec<MirTy> } pub type Mir = Box<MirRaw>; #[derive(Debug)] pub enum MirRaw { Unit(Meta), Bool(bool, Meta), I64(i64, Meta), U64(u64, Meta), F32(f32, Meta), F64(f64, Meta), StrLit(String, Meta), DefConst(Symbol, Mir, Meta), DefVar(Symbol, MirTy, Mir, Meta), StoreVar(Symbol, Mir, Meta), Load(Symbol, Meta), IAdd(Mir, Mir, Meta), ISub(Mir, Mir, Meta), IMul(Mir, Mir, Meta), IDiv(Mir, Mir, bool, Meta), IMod(Mir, Mir, bool, Meta), IEq(Mir, Mir, Meta), INeq(Mir, Mir, Meta), ILt(Mir, Mir, bool, Meta), ILte(Mir, Mir, bool, Meta), IGt(Mir, Mir, bool, Meta), IGte(Mir, Mir,bool, Meta), FAdd(Mir, Mir, Meta), FSub(Mir, Mir, Meta), FMul(Mir, Mir, Meta), FDiv(Mir, Mir, Meta), FMod(Mir, Mir, Meta), LAnd(Mir, Mir, Meta), LOr(Mir, Mir, Meta), LNot(Mir, Meta), If(Mir, Mir, Mir, Meta), IfVoid(Vec<(Mir, Mir)>, Meta), While{label: Option<Symbol>, cond: Mir, body: Mir, meta: Meta}, DoWhile{label: Option<Symbol>, cond: Mir, body: Mir, meta: Meta}, Loop(Option<Symbol>, Mir, Meta), Continue(Option<Symbol>, Meta), Break(Option<Symbol>, Meta), Fun{name: Symbol, ty: MirTy, params: Vec<Symbol>, body: Mir, meta: Meta}, DeclExternFun{name: Symbol, ty: MirTy, meta: Meta}, Call(Mir, Vec<Mir>, Meta), Ret(Mir, Meta), RetUnit(Meta), Seq(Vec<Mir>, Meta), } pub struct Generator { ctx: llvm::Context, m: llvm::Module, b: llvm::Builder, scope_stack: ScopeStack, func_stack: FuncStack, loop_stack: Vec<LoopStackElem>, } impl Generator { fn new(mod_name: String)->Self { use llvm::*; let ctx = Context::new(); let m = Module::new(mod_name, &ctx); let b = Builder::new(&ctx); let scope_stack = ScopeStack::new(); let func_stack = FuncStack::new(); let loop_stack = Vec::new(); Self{ctx, m, b, scope_stack, func_stack, loop_stack} } fn dispose(&mut self) { self.b.dispose(); self.m.dispose(); self.ctx.dispose(); self.scope_stack.clear(); } fn dump_llvm_ir(&mut self) { self.m.dump(); } fn print_llvm_ir_to_file(&mut self, file: String) { self.m.print_to_file(file); } fn verify_module(&self){ self.m.verify(); } fn meta2str(meta: Meta)->String { format!("f{}l{}c{}", meta.0, meta.1, meta.2) } fn gen_ty(&mut self, ty: &MirTy)->llvm::Type { match ty.ty.as_str() { "Unit" => llvm::Type::void(&self.ctx), "Bool" => llvm::Type::int1(&self.ctx), "I8" => llvm::Type::int8(&self.ctx), "I64" => llvm::Type::int64(&self.ctx), "F32" => llvm::Type::float(&self.ctx), "F64" => llvm::Type::double(&self.ctx), "Fun" => { let mut it = ty.args.iter(); let ret_ty = it.next().expect("illegal function parameter"); let param_ty = it.map(|x| self.gen_ty(x)).collect::<Vec<_>>(); llvm::Type::function(self.gen_ty(ret_ty), &param_ty, false) }, "FunVarArgs" => { let mut it = ty.args.iter(); let ret_ty = it.next().expect("illegal function parameter"); let param_ty = it.map(|x| self.gen_ty(x)).collect::<Vec<_>>(); llvm::Type::function(self.gen_ty(ret_ty), &param_ty, true) }, "Ptr" => { let t = if ty.args.is_empty() { llvm::Type::void(&self.ctx) } else { self.gen_ty(&ty.args[0]) }; llvm::Type::ptr(t) }, _ => unimplemented!() } } fn gen(&mut self, mir: Mir)->Result<Option<llvm::Value>, MirErr> { use llvm::*; match *mir { MirRaw::Unit(_) => panic!("Unit can't be compiled"), MirRaw::Bool(b, _) => Ok(Some(Value::int1(&self.ctx, b))), MirRaw::I64(i, _) => Ok(Some(Value::int64(&self.ctx, i))), MirRaw::StrLit(s, _) => Ok(Some(self.b.global_string_ptr(s, "".into()))), MirRaw::DefConst(n, v, _) => { let v = self.gen(v)?.ok_or(MirErr::MustHaveValue)?; self.scope_stack.insert(n, ScopedValue::Const(v)); Ok(Some(v)) }, MirRaw::DefVar(n, t, v, _) => { let v = self.gen(v)?.ok_or(MirErr::MustHaveValue)?; let t = self.gen_ty(&t); let cbb = self.b.get_current_basic_block(); let m = self.func_stack.insert_alloca(&mut self.b, &cbb, &t).unwrap(); self.scope_stack.insert(n, ScopedValue::Var(t, m)); let r = self.scope_stack.set_value(&mut self.b, n, &v)?; Ok(Some(r)) }, MirRaw::StoreVar(n, v, _) => { let v = self.gen(v)?.ok_or(MirErr::MustHaveValue)?; let r = self.scope_stack.set_value(&mut self.b, n, &v)?; Ok(Some(r)) }, MirRaw::Load(n, _) => Ok(Some(self.scope_stack.get_value(&mut self.b, n).expect("variable not found"))), MirRaw::IAdd(l, r, m) => { let l = self.gen(l)?.ok_or(MirErr::MustHaveValue)?; let r = self.gen(r)?.ok_or(MirErr::MustHaveValue)?; Ok(Some(self.b.op_iadd(&l, &r, ""))) }, MirRaw::ISub(l, r, m) => { let l = self.gen(l)?.ok_or(MirErr::MustHaveValue)?; let r = self.gen(r)?.ok_or(MirErr::MustHaveValue)?; Ok(Some(self.b.op_isub(&l, &r, ""))) }, MirRaw::IMul(l, r, m) => { let l = self.gen(l)?.ok_or(MirErr::MustHaveValue)?; let r = self.gen(r)?.ok_or(MirErr::MustHaveValue)?; Ok(Some(self.b.op_imul(&l, &r, ""))) }, MirRaw::IDiv(l, r, u, m) => { let l = self.gen(l)?.ok_or(MirErr::MustHaveValue)?; let r = self.gen(r)?.ok_or(MirErr::MustHaveValue)?; Ok(Some(self.b.op_idiv(&l, &r, u,""))) }, MirRaw::IEq(l, r, m) => { let l = self.gen(l)?.ok_or(MirErr::MustHaveValue)?; let r = self.gen(r)?.ok_or(MirErr::MustHaveValue)?; Ok(Some(self.b.op_ieq(&l, &r, ""))) }, MirRaw::INeq(l, r, m) => { let l = self.gen(l)?.ok_or(MirErr::MustHaveValue)?; let r = self.gen(r)?.ok_or(MirErr::MustHaveValue)?; Ok(Some(self.b.op_ineq(&l, &r, ""))) }, MirRaw::IGt(l, r, u, m) => { let l = self.gen(l)?.ok_or(MirErr::MustHaveValue)?; let r = self.gen(r)?.ok_or(MirErr::MustHaveValue)?; Ok(Some(self.b.op_igt(&l, &r, u,""))) }, MirRaw::IGte(l, r, u, m) => { let l = self.gen(l)?.ok_or(MirErr::MustHaveValue)?; let r = self.gen(r)?.ok_or(MirErr::MustHaveValue)?; Ok(Some(self.b.op_igte(&l, &r, u,""))) }, MirRaw::ILt(l, r, u, m) => { let l = self.gen(l)?.ok_or(MirErr::MustHaveValue)?; let r = self.gen(r)?.ok_or(MirErr::MustHaveValue)?; Ok(Some(self.b.op_ilt(&l, &r, u,""))) }, MirRaw::ILte(l, r, u, m) => { let l = self.gen(l)?.ok_or(MirErr::MustHaveValue)?; let r = self.gen(r)?.ok_or(MirErr::MustHaveValue)?; Ok(Some(self.b.op_ilte(&l, &r, u,""))) }, MirRaw::LAnd(l, r, m) => { let f = self.func_stack.get_current().expect("LAnd instruction must be in a function").func; let bb0 = self.b.get_current_basic_block(); let bb1 = self.ctx.append_basic_block_after(&f, &bb0, format!("and_{}_rhs", Self::meta2str(m))); let bb2 = self.ctx.append_basic_block_after(&f, &bb1, format!("and_{}_end", Self::meta2str(m))); self.b.set_position_at_end_of(&bb0); let l = self.gen(l)?.ok_or(MirErr::MustHaveValue)?; self.b.cond_br(&l, &bb1, &bb2); self.b.set_position_at_end_of(&bb1); let r = self.gen(r)?.ok_or(MirErr::MustHaveValue)?; self.b.br(&bb2); self.b.set_position_at_end_of(&bb2); let mut phi = self.b.phi(&Type::int1(&self.ctx), ""); phi.add_incomings(&vec![bb0, bb1], &vec![l, r]); Ok(Some(phi.get_value())) }, MirRaw::LOr(l, r, m) => { let f = self.func_stack.get_current().expect("LOr instruction must be in a function").func; let bb0 = self.b.get_current_basic_block(); let bb1 = self.ctx.append_basic_block_after(&f, &bb0, format!("or_{}_rhs", Self::meta2str(m))); let bb2 = self.ctx.append_basic_block_after(&f, &bb1, format!("or_{}_end", Self::meta2str(m))); self.b.set_position_at_end_of(&bb0); let l = self.gen(l)?.ok_or(MirErr::MustHaveValue)?; self.b.cond_br(&l, &bb2, &bb1); self.b.set_position_at_end_of(&bb1); let r = self.gen(r)?.ok_or(MirErr::MustHaveValue)?; self.b.br(&bb2); self.b.set_position_at_end_of(&bb2); let mut phi = self.b.phi(&Type::int1(&self.ctx), ""); phi.add_incomings(&vec![bb0, bb1], &vec![l, r]); Ok(Some(phi.get_value())) }, MirRaw::LNot(x, m) => { let x = self.gen(x)?.ok_or(MirErr::MustHaveValue)?; Ok(Some(self.b.op_lnot(&x, ""))) }, MirRaw::If(cond, tbody, fbody, m) => { let f = self.func_stack.get_current().expect("If instruction must be in a function").func; let bb0 = self.b.get_current_basic_block(); let bb1 = self.ctx.append_basic_block_after(&f, &bb0, format!("if_{}_true", Self::meta2str(m))); let bb2 = self.ctx.append_basic_block_after(&f, &bb1, format!("if_{}_false", Self::meta2str(m))); let bb3 = self.ctx.append_basic_block_after(&f, &bb2, format!("if_{}_end", Self::meta2str(m))); self.b.set_position_at_end_of(&bb0); let cond = self.gen(cond)?.expect("condition expression can't be unit"); self.b.cond_br(&cond, &bb1, &bb2); self.b.set_position_at_end_of(&bb1); let tbody = self.gen(tbody)?.expect("true branch of if can't be unit"); self.b.br(&bb3); self.b.set_position_at_end_of(&bb2); let fbody = self.gen(fbody)?.expect("false branch of if can't be unit"); self.b.br(&bb3); self.b.set_position_at_end_of(&bb3); let mut phi = self.b.phi(&tbody.get_type(), ""); phi.add_incomings(&vec![bb1, bb2], &vec![tbody, fbody]); Ok(Some(phi.get_value())) }, MirRaw::IfVoid(bs, m) => { let len = bs.len(); let f = &self.func_stack.get_current().expect("IfVoid insruction must be in a function").func.clone(); let mut bbs = Vec::with_capacity(len); let bb_begin = self.b.get_current_basic_block(); let bb_end = self.ctx.append_basic_block(&f, format!("if_{}_end", Self::meta2str(m))); for i in 0..len { let bb0 = self.ctx.insert_basic_block_before(&bb_end, format!("if_{}_block{}_begin", Self::meta2str(m), i)); let bb1 = if i != len - 1 { self.ctx.insert_basic_block_before(&bb_end, format!("if_{}_block{}_end", Self::meta2str(m), i)) } else { bb_end.clone() }; bbs.push((bb0, bb1)); } self.b.set_position_at_end_of(&bb_begin); for x in bs.into_iter().enumerate() { let (i, (b0, b1)) = x; let (bb0, bb1) = &bbs[i]; let cond = self.gen(b0)?.ok_or(MirErr::MustHaveValue)?; self.b.cond_br(&cond, &bb0, &bb1); self.b.set_position_at_end_of(&bb0); self.gen(b1)?; self.b.br(&bb_end); self.b.set_position_at_end_of(&bb1); } Ok(None) }, MirRaw::Loop(l, b, m) => { let f = self.func_stack.get_current().expect("Loop instruction must be in a function").func; let bb_current = self.b.get_current_basic_block(); let bb_begin = self.ctx.append_basic_block_after(&f, &bb_current, format!("loop_{}_begin", Self::meta2str(m))); let bb_end = self.ctx.append_basic_block_after(&f, &bb_begin, format!("loop_{}_end", Self::meta2str(m))); self.b.set_position_at_end_of(&bb_begin); self.loop_stack.push(LoopStackElem {name: l, begin_bb: bb_begin.clone(), end_bb: bb_end.clone()}); self.scope_stack.enter_scope(); self.gen(b)?; if self.loop_stack.is_empty() || self.loop_stack.last().unwrap().name != l { panic!("loop stack is in unexpected state") } self.scope_stack.leave_scope()?; self.loop_stack.pop(); self.b.br(&bb_begin); self.b.set_position_at_end_of(&bb_end); Ok(None) }, MirRaw::Break(l, m) => { if self.loop_stack.is_empty() { panic!("break is not in a loop") } if let Some(n) = l { let mut iter = self.loop_stack.iter().rev(); while let Some(LoopStackElem{name: loop_label, begin_bb: _, end_bb: e}) = iter.next() { if let Some(n2) = loop_label { if &n == n2 { self.b.br(&e); return Ok(None); } } } panic!(format!("loop labeled {} is not found", n)) } else { let e = self.loop_stack.last().unwrap(); self.b.br(&e.end_bb); return Ok(None); } }, MirRaw::Fun{name, ty, params, body, meta} => { let ty = self.gen_ty(&ty); let f = self.m.add_function(name.as_str(), ty); self.scope_stack.insert(name, ScopedValue::Const(f.clone())); self.scope_stack.enter_scope(); let alloc = self.ctx.append_basic_block(&f, "alloc"); let entry = self.ctx.append_basic_block(&f, "entry"); self.b.set_position_at_end_of(&alloc); self.b.set_position_at_end_of(&entry); self.func_stack.push(FuncStackElem{func: f.clone(), alloca_bb: alloc.clone()}); let mut i: u32 = 0; for p in params { let v = f.get_param(i); self.scope_stack.insert(p, ScopedValue::Const(v)); i += 1; } self.gen(body)?; let current_bb = self.b.get_current_basic_block(); self.b.set_position_at_end_of(&alloc); self.b.br(&entry); self.b.set_position_at_end_of(&current_bb); self.func_stack.pop(); self.scope_stack.leave_scope()?; Ok(Some(f)) }, MirRaw::DeclExternFun{name, ty, meta} => { let ty = self.gen_ty(&ty); let f = self.m.add_function(name.as_str(), ty); self.scope_stack.insert(name, ScopedValue::Const(f.clone())); Ok(Some(f)) }, MirRaw::Ret(val, meta) => { let v = self.gen(val)?.ok_or(MirErr::MustHaveValue)?; Ok(Some(self.b.ret(&v))) }, MirRaw::RetUnit(meta) => { Ok(Some(self.b.ret_void())) }, MirRaw::Call(fun, args, meta) => { let mut a = vec!(); for x in args.into_iter() { a.push(self.gen(x)?.ok_or(MirErr::MustHaveValue)?) } let f = self.gen(fun)?.ok_or(MirErr::MustHaveValue)?; let name = ""; Ok(Some(self.b.call(&f, &a, name))) }, MirRaw::Seq(es, meta) => { if es.is_empty() {panic!("Seq never empty"); } let mut r = None; for e in es { r = self.gen(e)?; } Ok(r) }, _ => unimplemented!() } } } #[macro_export] macro_rules! ast { ( $id:ident : $($arg:expr),* ) => ( Mir::new(MirRaw::$id($($arg),*, (0,line!(),column!()))) ); ( $id:ident # $($name:ident : $arg:expr),* ) => { Mir::new(MirRaw::$id{$($name: $arg),*, meta: (0,line!(),column!())}) }; ( $($arg:expr);* ) => { Mir::new(MirRaw::Seq(vec![$($arg),*], (0,line!(),column!()))) }; } #[macro_export] macro_rules! ty { ([ $id:ident ]) => { MirTy{ty: stringify!($id).into(), args: vec![]}; }; ([$id:ident : $($t:tt),* ]) => { MirTy{ty: stringify!($id).into(), args: vec![$(ty!($t)),*]}; }; }
#![allow(unused)] extern crate symbol; extern crate thiserror; use std::collections::HashMap; use symbol::Symbol; use thiserror::Error; mod llvm_wrapper; use llvm_wrapper as llvm; mod scope_stack; use scope_stack::{ScopeStack, ScopedValue}; mod func_stack; use func_stack::{FuncStackElem, FuncStack}; mod loop_stack; use loop_stack::LoopStackElem; #[cfg(test)] mod unit_tests; pub type Meta = (u32, u32, u32); #[derive(Error, Debug)] pub enum MirErr { #[error("Cannot create local variable at global scope")] LocalVarOnGlobal, #[error("`{0}` is not modifiable")] ConstNotModifiable(Symbol), #[error("Symbol `{0}` is not found. ")] SymbolNotFound(Symbol), #[error("Cannot get outer scope than static scope")] LeavingStaticScope, #[error("Must have value")] MustHaveValue, } #[derive(Debug)] pub struct MirTy { ty: Symbol, args: Vec<MirTy> } pub type Mir = Box<MirRaw>; #[derive(Debug)] pub enum MirRaw { Unit(Meta), Bool(bool, Meta), I64(i64, Meta), U64(u64, Meta), F32(f32, Meta), F64(f64, Meta), StrLit(String, Meta), DefConst(Symbol, Mir, Meta), DefVar(Symbol, MirTy, Mir, Meta), StoreVar(Symbol, Mir, Meta), Load(Symbol, Meta), IAdd(Mir, Mir, Meta), ISub(Mir, Mir, Meta), IMul(Mir, Mir, Meta), IDiv(Mir, Mir, bool, Meta), IMod(Mir, Mir, bool, Meta), IEq(Mir, Mir, Meta), INeq(Mir, Mir, Meta), ILt(Mir, Mir, bool, Meta), ILte(Mir, Mir, bool, Meta), IGt(Mir, Mir, bool, Meta), IGte(Mir, Mir,bool, Meta), FAdd(Mir, Mir, Meta), FSub(Mir, Mir, Meta), FMul(Mir, Mir, Meta), FDiv(Mir, Mir, Meta), FMod(Mir, Mir, Meta), LAnd(Mir, Mir, Meta), LOr(Mir, Mir, Meta), LNot(Mir, Meta), If(Mir, Mir, Mir, Meta), IfVoid(Vec<(Mir, Mir)>, Meta), While{label: Option<Symbol>, cond: Mir, body: Mir, meta: Meta}, DoWhile{label: Option<Symbol>, cond: Mir, body: Mir, meta: Meta}, Loop(Option<Symbol>, Mir, Meta), Continue(Option<Symbol>, Meta), Break(Option<Symbol>, Meta), Fun{name: Symbol, ty: MirTy, params: Vec<Symbol>, body: Mir, meta: Meta}, DeclExternFun{name: Symbol, ty: MirTy, meta: Meta}, Call(Mir, Vec<Mir>, Meta), Ret(Mir, Meta), RetUnit(Meta), Seq(Vec<Mir>, Meta), } pub struct Generator { ctx: llvm::Context, m: llvm::Module, b: llvm::Builder, scope_stack: ScopeStack, func_stack: FuncStack, loop_stack: Vec<LoopStackElem>, } impl Generator { fn new(mod_name: String)->Self { use llvm::*; let ctx = Context::new(); let m = Module::new(mod_name, &ctx); let b = Builder::new(&ctx); let scope_stack = ScopeStack::new(); let func_stack = FuncStack::new(); let loop_stack = Vec::new(); Self{ctx, m, b, scope_stack, func_stack, loop_stack} } fn dispose(&mut self) { self.b.dispose(); self.m.dispose(); self.ctx.dispose(); self.scope_stack.clear(); } fn dump_llvm_ir(&mut self) { self.m.dump(); } fn print_llvm_ir_to_file(&mut self, file: String) { self.m.print_to_file(file); } fn verify_module(&self){ self.m.verify(); } fn meta2str(meta: Meta)->String { format!("f{}l{}c{}", meta.0, meta.1, meta.2) } fn gen_ty(&mut self, ty: &MirTy)->llvm::Type { match ty.ty.as_str() { "Unit" => llvm::Type::void(&self.ctx), "Bool" => llvm::Type::int1(&self.ctx), "I8" => llvm::Type::int8(&self.ctx), "I64" => llvm::Type::int64(&self.ctx), "F32" => llvm::Type::float(&self.ctx), "F64" => llvm::Type::double(&self.ctx), "Fun" => { let mut it = ty.args.iter(); let ret_ty = it.next().expect("illegal function parameter"); let param_ty = it.map(|x| self.gen_ty(x)).collect::<Vec<_>>(); llvm::Type::function(self.gen_ty(ret_ty), &param_ty, false) }, "FunVarArgs" => { let mut it = ty.args.iter(); let ret_ty = it.next().expect("illegal function parameter"); let param_ty = it.map(|x| self.gen_ty(x)).collect::<Vec<_>>(); llvm::Type::function(self.gen_ty(ret_ty), &param_ty, true) }, "Ptr" => { let t =
; llvm::Type::ptr(t) }, _ => unimplemented!() } } fn gen(&mut self, mir: Mir)->Result<Option<llvm::Value>, MirErr> { use llvm::*; match *mir { MirRaw::Unit(_) => panic!("Unit can't be compiled"), MirRaw::Bool(b, _) => Ok(Some(Value::int1(&self.ctx, b))), MirRaw::I64(i, _) => Ok(Some(Value::int64(&self.ctx, i))), MirRaw::StrLit(s, _) => Ok(Some(self.b.global_string_ptr(s, "".into()))), MirRaw::DefConst(n, v, _) => { let v = self.gen(v)?.ok_or(MirErr::MustHaveValue)?; self.scope_stack.insert(n, ScopedValue::Const(v)); Ok(Some(v)) }, MirRaw::DefVar(n, t, v, _) => { let v = self.gen(v)?.ok_or(MirErr::MustHaveValue)?; let t = self.gen_ty(&t); let cbb = self.b.get_current_basic_block(); let m = self.func_stack.insert_alloca(&mut self.b, &cbb, &t).unwrap(); self.scope_stack.insert(n, ScopedValue::Var(t, m)); let r = self.scope_stack.set_value(&mut self.b, n, &v)?; Ok(Some(r)) }, MirRaw::StoreVar(n, v, _) => { let v = self.gen(v)?.ok_or(MirErr::MustHaveValue)?; let r = self.scope_stack.set_value(&mut self.b, n, &v)?; Ok(Some(r)) }, MirRaw::Load(n, _) => Ok(Some(self.scope_stack.get_value(&mut self.b, n).expect("variable not found"))), MirRaw::IAdd(l, r, m) => { let l = self.gen(l)?.ok_or(MirErr::MustHaveValue)?; let r = self.gen(r)?.ok_or(MirErr::MustHaveValue)?; Ok(Some(self.b.op_iadd(&l, &r, ""))) }, MirRaw::ISub(l, r, m) => { let l = self.gen(l)?.ok_or(MirErr::MustHaveValue)?; let r = self.gen(r)?.ok_or(MirErr::MustHaveValue)?; Ok(Some(self.b.op_isub(&l, &r, ""))) }, MirRaw::IMul(l, r, m) => { let l = self.gen(l)?.ok_or(MirErr::MustHaveValue)?; let r = self.gen(r)?.ok_or(MirErr::MustHaveValue)?; Ok(Some(self.b.op_imul(&l, &r, ""))) }, MirRaw::IDiv(l, r, u, m) => { let l = self.gen(l)?.ok_or(MirErr::MustHaveValue)?; let r = self.gen(r)?.ok_or(MirErr::MustHaveValue)?; Ok(Some(self.b.op_idiv(&l, &r, u,""))) }, MirRaw::IEq(l, r, m) => { let l = self.gen(l)?.ok_or(MirErr::MustHaveValue)?; let r = self.gen(r)?.ok_or(MirErr::MustHaveValue)?; Ok(Some(self.b.op_ieq(&l, &r, ""))) }, MirRaw::INeq(l, r, m) => { let l = self.gen(l)?.ok_or(MirErr::MustHaveValue)?; let r = self.gen(r)?.ok_or(MirErr::MustHaveValue)?; Ok(Some(self.b.op_ineq(&l, &r, ""))) }, MirRaw::IGt(l, r, u, m) => { let l = self.gen(l)?.ok_or(MirErr::MustHaveValue)?; let r = self.gen(r)?.ok_or(MirErr::MustHaveValue)?; Ok(Some(self.b.op_igt(&l, &r, u,""))) }, MirRaw::IGte(l, r, u, m) => { let l = self.gen(l)?.ok_or(MirErr::MustHaveValue)?; let r = self.gen(r)?.ok_or(MirErr::MustHaveValue)?; Ok(Some(self.b.op_igte(&l, &r, u,""))) }, MirRaw::ILt(l, r, u, m) => { let l = self.gen(l)?.ok_or(MirErr::MustHaveValue)?; let r = self.gen(r)?.ok_or(MirErr::MustHaveValue)?; Ok(Some(self.b.op_ilt(&l, &r, u,""))) }, MirRaw::ILte(l, r, u, m) => { let l = self.gen(l)?.ok_or(MirErr::MustHaveValue)?; let r = self.gen(r)?.ok_or(MirErr::MustHaveValue)?; Ok(Some(self.b.op_ilte(&l, &r, u,""))) }, MirRaw::LAnd(l, r, m) => { let f = self.func_stack.get_current().expect("LAnd instruction must be in a function").func; let bb0 = self.b.get_current_basic_block(); let bb1 = self.ctx.append_basic_block_after(&f, &bb0, format!("and_{}_rhs", Self::meta2str(m))); let bb2 = self.ctx.append_basic_block_after(&f, &bb1, format!("and_{}_end", Self::meta2str(m))); self.b.set_position_at_end_of(&bb0); let l = self.gen(l)?.ok_or(MirErr::MustHaveValue)?; self.b.cond_br(&l, &bb1, &bb2); self.b.set_position_at_end_of(&bb1); let r = self.gen(r)?.ok_or(MirErr::MustHaveValue)?; self.b.br(&bb2); self.b.set_position_at_end_of(&bb2); let mut phi = self.b.phi(&Type::int1(&self.ctx), ""); phi.add_incomings(&vec![bb0, bb1], &vec![l, r]); Ok(Some(phi.get_value())) }, MirRaw::LOr(l, r, m) => { let f = self.func_stack.get_current().expect("LOr instruction must be in a function").func; let bb0 = self.b.get_current_basic_block(); let bb1 = self.ctx.append_basic_block_after(&f, &bb0, format!("or_{}_rhs", Self::meta2str(m))); let bb2 = self.ctx.append_basic_block_after(&f, &bb1, format!("or_{}_end", Self::meta2str(m))); self.b.set_position_at_end_of(&bb0); let l = self.gen(l)?.ok_or(MirErr::MustHaveValue)?; self.b.cond_br(&l, &bb2, &bb1); self.b.set_position_at_end_of(&bb1); let r = self.gen(r)?.ok_or(MirErr::MustHaveValue)?; self.b.br(&bb2); self.b.set_position_at_end_of(&bb2); let mut phi = self.b.phi(&Type::int1(&self.ctx), ""); phi.add_incomings(&vec![bb0, bb1], &vec![l, r]); Ok(Some(phi.get_value())) }, MirRaw::LNot(x, m) => { let x = self.gen(x)?.ok_or(MirErr::MustHaveValue)?; Ok(Some(self.b.op_lnot(&x, ""))) }, MirRaw::If(cond, tbody, fbody, m) => { let f = self.func_stack.get_current().expect("If instruction must be in a function").func; let bb0 = self.b.get_current_basic_block(); let bb1 = self.ctx.append_basic_block_after(&f, &bb0, format!("if_{}_true", Self::meta2str(m))); let bb2 = self.ctx.append_basic_block_after(&f, &bb1, format!("if_{}_false", Self::meta2str(m))); let bb3 = self.ctx.append_basic_block_after(&f, &bb2, format!("if_{}_end", Self::meta2str(m))); self.b.set_position_at_end_of(&bb0); let cond = self.gen(cond)?.expect("condition expression can't be unit"); self.b.cond_br(&cond, &bb1, &bb2); self.b.set_position_at_end_of(&bb1); let tbody = self.gen(tbody)?.expect("true branch of if can't be unit"); self.b.br(&bb3); self.b.set_position_at_end_of(&bb2); let fbody = self.gen(fbody)?.expect("false branch of if can't be unit"); self.b.br(&bb3); self.b.set_position_at_end_of(&bb3); let mut phi = self.b.phi(&tbody.get_type(), ""); phi.add_incomings(&vec![bb1, bb2], &vec![tbody, fbody]); Ok(Some(phi.get_value())) }, MirRaw::IfVoid(bs, m) => { let len = bs.len(); let f = &self.func_stack.get_current().expect("IfVoid insruction must be in a function").func.clone(); let mut bbs = Vec::with_capacity(len); let bb_begin = self.b.get_current_basic_block(); let bb_end = self.ctx.append_basic_block(&f, format!("if_{}_end", Self::meta2str(m))); for i in 0..len { let bb0 = self.ctx.insert_basic_block_before(&bb_end, format!("if_{}_block{}_begin", Self::meta2str(m), i)); let bb1 = if i != len - 1 { self.ctx.insert_basic_block_before(&bb_end, format!("if_{}_block{}_end", Self::meta2str(m), i)) } else { bb_end.clone() }; bbs.push((bb0, bb1)); } self.b.set_position_at_end_of(&bb_begin); for x in bs.into_iter().enumerate() { let (i, (b0, b1)) = x; let (bb0, bb1) = &bbs[i]; let cond = self.gen(b0)?.ok_or(MirErr::MustHaveValue)?; self.b.cond_br(&cond, &bb0, &bb1); self.b.set_position_at_end_of(&bb0); self.gen(b1)?; self.b.br(&bb_end); self.b.set_position_at_end_of(&bb1); } Ok(None) }, MirRaw::Loop(l, b, m) => { let f = self.func_stack.get_current().expect("Loop instruction must be in a function").func; let bb_current = self.b.get_current_basic_block(); let bb_begin = self.ctx.append_basic_block_after(&f, &bb_current, format!("loop_{}_begin", Self::meta2str(m))); let bb_end = self.ctx.append_basic_block_after(&f, &bb_begin, format!("loop_{}_end", Self::meta2str(m))); self.b.set_position_at_end_of(&bb_begin); self.loop_stack.push(LoopStackElem {name: l, begin_bb: bb_begin.clone(), end_bb: bb_end.clone()}); self.scope_stack.enter_scope(); self.gen(b)?; if self.loop_stack.is_empty() || self.loop_stack.last().unwrap().name != l { panic!("loop stack is in unexpected state") } self.scope_stack.leave_scope()?; self.loop_stack.pop(); self.b.br(&bb_begin); self.b.set_position_at_end_of(&bb_end); Ok(None) }, MirRaw::Break(l, m) => { if self.loop_stack.is_empty() { panic!("break is not in a loop") } if let Some(n) = l { let mut iter = self.loop_stack.iter().rev(); while let Some(LoopStackElem{name: loop_label, begin_bb: _, end_bb: e}) = iter.next() { if let Some(n2) = loop_label { if &n == n2 { self.b.br(&e); return Ok(None); } } } panic!(format!("loop labeled {} is not found", n)) } else { let e = self.loop_stack.last().unwrap(); self.b.br(&e.end_bb); return Ok(None); } }, MirRaw::Fun{name, ty, params, body, meta} => { let ty = self.gen_ty(&ty); let f = self.m.add_function(name.as_str(), ty); self.scope_stack.insert(name, ScopedValue::Const(f.clone())); self.scope_stack.enter_scope(); let alloc = self.ctx.append_basic_block(&f, "alloc"); let entry = self.ctx.append_basic_block(&f, "entry"); self.b.set_position_at_end_of(&alloc); self.b.set_position_at_end_of(&entry); self.func_stack.push(FuncStackElem{func: f.clone(), alloca_bb: alloc.clone()}); let mut i: u32 = 0; for p in params { let v = f.get_param(i); self.scope_stack.insert(p, ScopedValue::Const(v)); i += 1; } self.gen(body)?; let current_bb = self.b.get_current_basic_block(); self.b.set_position_at_end_of(&alloc); self.b.br(&entry); self.b.set_position_at_end_of(&current_bb); self.func_stack.pop(); self.scope_stack.leave_scope()?; Ok(Some(f)) }, MirRaw::DeclExternFun{name, ty, meta} => { let ty = self.gen_ty(&ty); let f = self.m.add_function(name.as_str(), ty); self.scope_stack.insert(name, ScopedValue::Const(f.clone())); Ok(Some(f)) }, MirRaw::Ret(val, meta) => { let v = self.gen(val)?.ok_or(MirErr::MustHaveValue)?; Ok(Some(self.b.ret(&v))) }, MirRaw::RetUnit(meta) => { Ok(Some(self.b.ret_void())) }, MirRaw::Call(fun, args, meta) => { let mut a = vec!(); for x in args.into_iter() { a.push(self.gen(x)?.ok_or(MirErr::MustHaveValue)?) } let f = self.gen(fun)?.ok_or(MirErr::MustHaveValue)?; let name = ""; Ok(Some(self.b.call(&f, &a, name))) }, MirRaw::Seq(es, meta) => { if es.is_empty() {panic!("Seq never empty"); } let mut r = None; for e in es { r = self.gen(e)?; } Ok(r) }, _ => unimplemented!() } } } #[macro_export] macro_rules! ast { ( $id:ident : $($arg:expr),* ) => ( Mir::new(MirRaw::$id($($arg),*, (0,line!(),column!()))) ); ( $id:ident # $($name:ident : $arg:expr),* ) => { Mir::new(MirRaw::$id{$($name: $arg),*, meta: (0,line!(),column!())}) }; ( $($arg:expr);* ) => { Mir::new(MirRaw::Seq(vec![$($arg),*], (0,line!(),column!()))) }; } #[macro_export] macro_rules! ty { ([ $id:ident ]) => { MirTy{ty: stringify!($id).into(), args: vec![]}; }; ([$id:ident : $($t:tt),* ]) => { MirTy{ty: stringify!($id).into(), args: vec![$(ty!($t)),*]}; }; }
if ty.args.is_empty() { llvm::Type::void(&self.ctx) } else { self.gen_ty(&ty.args[0]) }
if_condition
[ { "content": "fn run(name: String, mir: Mir)-> String {\n\n use std::process::*;\n\n use llvm_sys::target_machine::*;\n\n use llvm_wrapper::TargetMachine;\n\n let test_data_dir = \"testdata\";\n\n let prefix = if cfg!(target_os = \"windows\") {format!(\"{}\\\\\", test_data_dir)} else {format!(\"{}/\", test_data_dir)};\n\n let obj_path = format!(\"{}{}.o\", &prefix, &name);\n\n let exe_suffix = if cfg!(target_os = \"windows\") {\".exe\"} else {\"\"};\n\n let exe_path = format!(\"{}{}{}\", &prefix, &name, exe_suffix);\n\n let ll_path = format!(\"{}{}.ll\", &prefix, &name);\n\n let mut g = Generator::new(name);\n\n let v = g.gen(mir);\n\n\n\n g.verify_module();\n\n g.print_llvm_ir_to_file(ll_path);\n\n let tm = TargetMachine::new_host(LLVMCodeGenOptLevel::LLVMCodeGenLevelAggressive, LLVMRelocMode::LLVMRelocPIC, LLVMCodeModel::LLVMCodeModelDefault);\n\n\n\n tm.compile_to_file(&g.m, obj_path.clone(), LLVMCodeGenFileType::LLVMObjectFile).expect(\"failed to comile\");\n\n\n\n let compiled = Command::new(\"gcc\")\n", "file_path": "src/unit_tests.rs", "rank": 0, "score": 85999.84156414891 }, { "content": "#[test]\n\nfn variable() {\n\n let a = ast![\n\n ast!{\n\n DeclExternFun #\n\n name: \"printf\".into(),\n\n ty: ty!([FunVarArgs: [Unit], [Ptr: [I8]]])\n\n };\n\n ast!{\n\n Fun #\n\n name: \"variable\".into(),\n\n ty: ty!([Fun: [I64], [I64]]),\n\n params: vec![\"x\".into()],\n\n body: ast![\n\n ast!(DefVar : \"t\".into(), ty!([I64]), ast!(Load: \"x\".into()));\n\n \n\n ast!(StoreVar: \"t\".into(),\n\n ast!(IMul:\n\n ast!(Load: \"t\".into()),\n\n ast!(I64: 2)\n\n )\n", "file_path": "src/unit_tests.rs", "rank": 1, "score": 65940.75167254118 }, { "content": "#[test]\n\nfn add() {\n\n let a = ast![\n\n ast!{\n\n DeclExternFun #\n\n name: \"printf\".into(),\n\n ty: ty!([FunVarArgs: [Unit], [Ptr: [I8]]])\n\n };\n\n ast!{\n\n Fun #\n\n name: \"add\".into(),\n\n ty: ty!([Fun: [I64], [I64], [I64]]),\n\n params: vec![\"x\".into(), \"y\".into()],\n\n body: ast![\n\n ast!(DefConst : \"z\".into(),\n\n ast!(IAdd:\n\n ast!(Load: \"x\".into()),\n\n ast!(Load: \"y\".into())\n\n )\n\n );\n\n ast!(Ret: ast!(Load: \"z\".into()))\n", "file_path": "src/unit_tests.rs", "rank": 2, "score": 45898.155797033985 }, { "content": "#[test]\n\nfn recursion() {\n\n let a = ast![\n\n ast!{\n\n DeclExternFun #\n\n name: \"printf\".into(),\n\n ty: ty!([FunVarArgs: [Unit], [Ptr: [I8]]])\n\n };\n\n\n\n ast!{\n\n Fun #\n\n name: \"sum\".into(),\n\n ty: ty!([Fun: [I64], [I64]]),\n\n params: vec![\"x\".into()],\n\n body: ast![\n\n ast!(Ret :\n\n ast!(If :\n\n ast!(IEq: ast!(Load: \"x\".into()), ast!(I64: 0)),\n\n ast!(I64: 0),\n\n ast!(IAdd:\n\n ast!(Call : ast!(Load: \"sum\".into()), vec![\n", "file_path": "src/unit_tests.rs", "rank": 3, "score": 45898.155797033985 }, { "content": "#[test]\n\nfn lor() {\n\n let a = ast![\n\n ast!{\n\n DeclExternFun #\n\n name: \"printf\".into(),\n\n ty: ty!([FunVarArgs: [Unit], [Ptr: [I8]]])\n\n };\n\n ast!{\n\n Fun #\n\n name: \"main\".into(),\n\n ty: ty!([Fun: [I64]]),\n\n params: vec![],\n\n body: ast![\n\n ast!(IfVoid : vec![\n\n (\n\n ast!(LOr: ast!(Bool: false), ast!(Bool: false)),\n\n ast!(Call : ast!(Load: \"printf\".into()), vec![ast!(StrLit: \"a\".into())])\n\n ),\n\n ]);\n\n ast!(IfVoid : vec![\n", "file_path": "src/unit_tests.rs", "rank": 4, "score": 45898.155797033985 }, { "content": "#[test]\n\nfn if_expression() {\n\n let a = ast![\n\n ast!{\n\n DeclExternFun #\n\n name: \"printf\".into(),\n\n ty: ty!([FunVarArgs: [Unit], [Ptr: [I8]]])\n\n };\n\n ast!{\n\n Fun #\n\n name: \"main\".into(),\n\n ty: ty!([Fun: [I64]]),\n\n params: vec![],\n\n body: ast![\n\n ast!(DefConst : \"ret\".into(),\n\n ast!(If :\n\n ast!(ILte: ast!(I64: 1), ast!(I64: 2), false),\n\n ast!(I64: 42),\n\n ast!(I64: 43)\n\n )\n\n );\n", "file_path": "src/unit_tests.rs", "rank": 5, "score": 45898.155797033985 }, { "content": "#[test]\n\nfn land() {\n\n let a = ast![\n\n ast!{\n\n DeclExternFun #\n\n name: \"printf\".into(),\n\n ty: ty!([FunVarArgs: [Unit], [Ptr: [I8]]])\n\n };\n\n ast!{\n\n Fun #\n\n name: \"main\".into(),\n\n ty: ty!([Fun: [I64]]),\n\n params: vec![],\n\n body: ast![\n\n ast!(IfVoid : vec![\n\n (\n\n ast!(LAnd: ast!(Bool: false), ast!(Bool: false)),\n\n ast!(Call : ast!(Load: \"printf\".into()), vec![ast!(StrLit: \"a\".into())])\n\n ),\n\n ]);\n\n ast!(IfVoid : vec![\n", "file_path": "src/unit_tests.rs", "rank": 6, "score": 45898.155797033985 }, { "content": "#[test]\n\nfn if_void() {\n\n let a = ast![\n\n ast!{\n\n DeclExternFun #\n\n name: \"printf\".into(),\n\n ty: ty!([FunVarArgs: [Unit], [Ptr: [I8]]])\n\n };\n\n ast!{\n\n Fun #\n\n name: \"main\".into(),\n\n ty: ty!([Fun: [I64]]),\n\n params: vec![],\n\n body: ast![\n\n ast!(IfVoid : vec![\n\n (\n\n ast!(Bool: false),\n\n ast!(Call : ast!(Load: \"printf\".into()), vec![ast!(StrLit: \"%d\\n\".into()), ast!(I64: 43i64)])\n\n ),\n\n (\n\n ast!(Bool: true),\n\n ast!(Call : ast!(Load: \"printf\".into()), vec![ast!(StrLit: \"%d\\n\".into()), ast!(I64: 42i64)])\n\n ),\n\n ]);\n\n ast!(Ret: ast!(I64: 0))\n\n ]\n\n }\n\n ];\n\n assert_eq!(run(\"if_void\".into(), a).trim(), String::from(\"42\"));\n\n}\n\n\n", "file_path": "src/unit_tests.rs", "rank": 7, "score": 45898.155797033985 }, { "content": "#[test]\n\nfn hello_world() {\n\n let a = ast![\n\n ast!{\n\n DeclExternFun #\n\n name: \"printf\".into(),\n\n ty: ty!([FunVarArgs: [Unit], [Ptr: [I8]]])\n\n };\n\n ast!{\n\n Fun #\n\n name: \"main\".into(),\n\n ty: ty!([Fun: [I64]]),\n\n params: vec![],\n\n body: ast![\n\n ast!(Call : ast!(Load: \"printf\".into()), vec![ast!(StrLit: \"Hello, World!\\n\".into())]);\n\n ast!(Ret: ast!(I64: 0))\n\n ]\n\n }\n\n ];\n\n assert_eq!(run(\"hw\".into(), a).trim(), String::from(\"Hello, World!\"));\n\n}\n\n\n", "file_path": "src/unit_tests.rs", "rank": 8, "score": 43412.21902690114 }, { "content": "\n\n\n\nuse std::collections::HashMap;\n\nuse symbol::Symbol;\n\nuse super::{llvm_wrapper, MirErr,};\n\n\n\npub enum ScopedValue {\n\n Const(llvm_wrapper::Value),\n\n Var(llvm_wrapper::Type, llvm_wrapper::Value),\n\n}\n\n\n\npub struct ScopeStack(Vec<HashMap<Symbol, ScopedValue>>);\n\nimpl ScopeStack {\n\n pub fn new()->Self {\n\n ScopeStack(vec![HashMap::new()])\n\n }\n\n\n\n pub fn leave_scope(&mut self) -> Result<(), MirErr> {\n\n if self.0.is_empty() {\n\n return Err(MirErr::LeavingStaticScope)\n", "file_path": "src/scope_stack.rs", "rank": 9, "score": 21361.618892203165 }, { "content": " //let pt = llvm_wrapper::Type::ptr(*t);\n\n //let v = b.load_with_type(&pt, p, \"\");\n\n let v = b.load_with_type(t, p, \"\");\n\n //let v = b.load(p, \"\");\n\n Some(v)\n\n }\n\n }\n\n //return Some(*v);\n\n }\n\n }\n\n None\n\n }\n\n\n\n pub fn set_value(&self, b: &mut llvm_wrapper::Builder, sym: Symbol, val: &llvm_wrapper::Value)->Result<llvm_wrapper::Value, MirErr> {\n\n for hm in self.0.iter().rev() {\n\n if let Some(v) = hm.get(&sym) {\n\n return match v {\n\n ScopedValue::Const(c) => Err(MirErr::ConstNotModifiable(sym)),\n\n ScopedValue::Var(t, p) => {\n\n //let pt = llvm_wrapper::Type::ptr(*t);\n", "file_path": "src/scope_stack.rs", "rank": 10, "score": 21360.041075513444 }, { "content": " }\n\n self.0.pop();\n\n return Ok(())\n\n }\n\n pub fn enter_scope(&mut self) {\n\n self.0.push(HashMap::new());\n\n }\n\n\n\n pub fn insert(&mut self, sym: Symbol, v: ScopedValue) {\n\n if let Some(last) = self.0.last_mut() {\n\n last.insert(sym, v);\n\n }\n\n }\n\n\n\n pub fn get_value(&self, b: &mut llvm_wrapper::Builder, sym: Symbol)->Option<llvm_wrapper::Value> {\n\n for hm in self.0.iter().rev() {\n\n if let Some(v) = hm.get(&sym) {\n\n return match v {\n\n ScopedValue::Const(c) => Some(*c),\n\n ScopedValue::Var(t, p) => {\n", "file_path": "src/scope_stack.rs", "rank": 11, "score": 21354.33032917733 }, { "content": " //let v = b.load_with_type(&pt, p, \"\");\n\n let v = b.store(p, val);\n\n //let v = b.load(p, \"\");\n\n Ok(v)\n\n }\n\n }\n\n //return Some(*v);\n\n }\n\n }\n\n Err(MirErr::SymbolNotFound(sym))\n\n }\n\n\n\n pub fn clear(&mut self) {\n\n self.0.clear();\n\n }\n\n}\n", "file_path": "src/scope_stack.rs", "rank": 12, "score": 21348.105538844997 }, { "content": " ]\n\n };\n\n ast!{\n\n Fun #\n\n name: \"main\".into(),\n\n ty: ty!([Fun: [I64]]),\n\n params: vec![],\n\n body: ast![\n\n ast!(DefConst : \"z\".into(),\n\n ast!(Call : ast!(Load: \"add\".into()), vec![ast!(I64: 2), ast!(I64: 2)])\n\n );\n\n ast!(Call : ast!(Load: \"printf\".into()), vec![ast!(StrLit: \"%d\\n\".into()), ast!(Load: \"z\".into())]);\n\n ast!(Ret: ast!(I64: 0))\n\n ]\n\n }\n\n ];\n\n assert_eq!(run(\"add\".into(), a).trim(), String::from(\"4\"));\n\n}\n\n\n", "file_path": "src/unit_tests.rs", "rank": 13, "score": 20494.045828451817 }, { "content": " ast!(ISub : ast!(Load: \"x\".into()), ast!(I64 : 1))\n\n ]),\n\n ast!(Load : \"x\".into())\n\n )\n\n )\n\n )\n\n ]\n\n };\n\n\n\n ast!{\n\n Fun #\n\n name: \"main\".into(),\n\n ty: ty!([Fun: [I64]]),\n\n params: vec![],\n\n body: ast![\n\n ast!(Call : ast!(Load: \"printf\".into()), vec![\n\n ast!(StrLit: \"%d\\n\".into()),\n\n ast!(Call : ast!(Load: \"sum\".into()), vec![ast!(I64: 10)])\n\n ]);\n\n ast!(Ret: ast!(I64: 0))\n\n ]\n\n }\n\n ];\n\n assert_eq!(run(\"recursion\".into(), a).trim(), String::from(\"55\"));\n\n}", "file_path": "src/unit_tests.rs", "rank": 14, "score": 20493.951782904962 }, { "content": " );\n\n \n\n ast!(Ret: ast!(Load: \"t\".into()))\n\n ]\n\n };\n\n ast!{\n\n Fun #\n\n name: \"main\".into(),\n\n ty: ty!([Fun: [I64]]),\n\n params: vec![],\n\n body: ast![\n\n ast!(DefConst : \"ret\".into(),\n\n ast!(Call : ast!(Load: \"variable\".into()), vec![ast!(I64: 21)])\n\n );\n\n ast!(Call : ast!(Load: \"printf\".into()), vec![ast!(StrLit: \"%d\\n\".into()), ast!(Load: \"ret\".into())]);\n\n ast!(Ret: ast!(I64: 0))\n\n ]\n\n }\n\n ];\n\n assert_eq!(run(\"variable\".into(), a).trim(), String::from(\"42\"));\n\n}\n\n\n", "file_path": "src/unit_tests.rs", "rank": 15, "score": 20493.43737877979 }, { "content": " (\n\n ast!(LAnd: ast!(Bool: false), ast!(Bool: true)),\n\n ast!(Call : ast!(Load: \"printf\".into()), vec![ast!(StrLit: \"b\".into())])\n\n ),\n\n ]);\n\n ast!(IfVoid : vec![\n\n (\n\n ast!(LAnd: ast!(Bool: true), ast!(Bool: false)),\n\n ast!(Call : ast!(Load: \"printf\".into()), vec![ast!(StrLit: \"c\".into())])\n\n ),\n\n ]);\n\n ast!(IfVoid : vec![\n\n (\n\n ast!(LAnd: ast!(Bool: true), ast!(Bool: true)),\n\n ast!(Call : ast!(Load: \"printf\".into()), vec![ast!(StrLit: \"d\".into())])\n\n ),\n\n ]);\n\n\n\n ast!(Call : ast!(Load: \"printf\".into()), vec![ast!(StrLit: \"\\n\".into())]);\n\n ast!(Ret: ast!(I64: 0))\n\n ]\n\n }\n\n ];\n\n assert_eq!(run(\"land\".into(), a).trim(), String::from(\"d\"));\n\n}\n\n\n", "file_path": "src/unit_tests.rs", "rank": 16, "score": 20488.88647278717 }, { "content": " (\n\n ast!(LOr: ast!(Bool: false), ast!(Bool: true)),\n\n ast!(Call : ast!(Load: \"printf\".into()), vec![ast!(StrLit: \"b\".into())])\n\n ),\n\n ]);\n\n ast!(IfVoid : vec![\n\n (\n\n ast!(LOr: ast!(Bool: true), ast!(Bool: false)),\n\n ast!(Call : ast!(Load: \"printf\".into()), vec![ast!(StrLit: \"c\".into())])\n\n ),\n\n ]);\n\n ast!(IfVoid : vec![\n\n (\n\n ast!(LOr: ast!(Bool: true), ast!(Bool: true)),\n\n ast!(Call : ast!(Load: \"printf\".into()), vec![ast!(StrLit: \"d\".into())])\n\n ),\n\n ]);\n\n\n\n ast!(Call : ast!(Load: \"printf\".into()), vec![ast!(StrLit: \"\\n\".into())]);\n\n ast!(Ret: ast!(I64: 0))\n\n ]\n\n }\n\n ];\n\n assert_eq!(run(\"lor\".into(), a).trim(), String::from(\"bcd\"));\n\n}\n\n\n\n\n", "file_path": "src/unit_tests.rs", "rank": 17, "score": 20488.847731835656 }, { "content": " .arg(obj_path)\n\n .arg(\"-o\")\n\n .arg(&exe_path)\n\n .output()\n\n .expect(\"failed to compile\");\n\n if compiled.status.code().expect(\"gcc is killed by signal\") != 0 {\n\n let err = String::from_utf8(compiled.stderr).expect(\"illegal charactor in stderr\");\n\n eprintln!(\"compile error:\\n{}\", err);\n\n return \"\".into();\n\n }\n\n let result = Command::new(exe_path)\n\n .output()\n\n .expect(\"failed to compile\");\n\n if result.status.code().expect(\"execution is killed by signal\") != 0 {\n\n let err = String::from_utf8(result.stderr).expect(\"illegal charactor in stderr\");\n\n eprintln!(\"executin error:\\n{}\", err);\n\n \"\".into()\n\n } else {\n\n String::from_utf8(result.stdout).expect(\"illegal charactor in the result output\")\n\n }\n\n}\n", "file_path": "src/unit_tests.rs", "rank": 18, "score": 20484.889386384944 }, { "content": " ast!(Call : ast!(Load: \"printf\".into()), vec![\n\n ast!(StrLit: \"%d\\n\".into()),\n\n ast!(Load: \"ret\".into())\n\n ]);\n\n ast!(Ret: ast!(I64: 0))\n\n ]\n\n }\n\n ];\n\n assert_eq!(run(\"if_expression\".into(), a).trim(), String::from(\"42\"));\n\n}\n\n\n", "file_path": "src/unit_tests.rs", "rank": 19, "score": 20484.317490704514 }, { "content": "use super::*;\n\n\n", "file_path": "src/unit_tests.rs", "rank": 20, "score": 20482.71402136357 }, { "content": " unsafe {\n\n Value {\n\n value: LLVMBuildGlobalString(self.builder, cval.as_ptr(), cname.as_ptr())\n\n }\n\n }\n\n }\n\n\n\n pub fn call<StrT: Into<Vec<u8>>>(&mut self, fun: &Value, args: &Vec<Value>, name: StrT)->Value {\n\n let cname = CString::new(name).expect(\"CString::new failed\");\n\n let n = args.len() as u32;\n\n let mut cargs = args.iter().map(|x|{x.value}).collect::<Vec<LLVMValueRef>>();\n\n let p = cargs.as_mut_ptr();\n\n unsafe {\n\n Value {\n\n value: LLVMBuildCall(self.builder, fun.value, p, n, cname.as_ptr())\n\n }\n\n }\n\n }\n\n\n\n pub fn get_struct_elem<StrT: Into<Vec<u8>>>(&self, struct_: &Value, idx: u32, name: StrT)->Value {\n", "file_path": "src/llvm_wrapper.rs", "rank": 21, "score": 19107.44587111322 }, { "content": "\n\nimpl Module {\n\n pub fn new<StrT: Into<Vec<u8>>>(name: StrT, context: &Context)->Module {\n\n let cname = CString::new(name).expect(\"CString::new failed\");\n\n unsafe {\n\n let raw_mod = LLVMModuleCreateWithNameInContext(cname.as_ptr(), context.context);\n\n Module {module: raw_mod}\n\n }\n\n }\n\n\n\n pub fn add_function<StrT: Into<Vec<u8>>>(&mut self, name: StrT, ty: Type)->Value {\n\n let cname = CString::new(name).expect(\"CString::new failed\");\n\n unsafe{\n\n let ret = LLVMAddFunction(self.module, cname.as_ptr(), ty.type_);\n\n Value {value: ret}\n\n }\n\n }\n\n\n\n pub fn dump(&self) {\n\n unsafe {\n", "file_path": "src/llvm_wrapper.rs", "rank": 22, "score": 19107.178066159635 }, { "content": "extern crate llvm_sys as llvm;\n\nextern crate libc;\n\n\n\nuse std::ops::Deref;\n\nuse std::{mem, ptr};\n\nuse std::ffi::CString;\n\nuse llvm::prelude::*;\n\nuse llvm::core::*;\n\nuse llvm::target::*;\n\nuse llvm::target_machine::*;\n\nuse llvm::analysis::{LLVMVerifierFailureAction, LLVMVerifyModule, LLVMVerifyFunction};\n\n\n\n#[derive(Debug)]\n\npub struct Context {\n\n pub context: LLVMContextRef\n\n}\n\nimpl Context {\n\n pub fn new()->Context {\n\n unsafe {\n\n Context{context: LLVMContextCreate()}\n", "file_path": "src/llvm_wrapper.rs", "rank": 23, "score": 19106.807196948845 }, { "content": " Type { type_: LLVMDoubleTypeInContext(context.context) }\n\n }\n\n }\n\n pub fn ptr(ty: Type)->Type {\n\n unsafe {\n\n Type { type_: LLVMPointerType(ty.type_, 0) }\n\n }\n\n }\n\n pub fn label(context: &Context)->Type {\n\n unsafe {\n\n Type { type_: LLVMLabelTypeInContext(context.context) }\n\n }\n\n }\n\n pub fn function<IterT: Deref<Target=[Type]>>(return_type: Type, param_types: &IterT, is_vararg: bool)->Type {\n\n let n = param_types.len() as u32;\n\n let mut params = param_types.iter().map(|x|{x.type_}).collect::<Vec<LLVMTypeRef>>();\n\n let p = params.as_mut_ptr();\n\n unsafe {\n\n Type { type_: LLVMFunctionType(return_type.type_, p, if is_vararg {0} else {n}, if is_vararg {1} else {0}) }\n\n }\n", "file_path": "src/llvm_wrapper.rs", "rank": 24, "score": 19106.202809282982 }, { "content": " pub value: LLVMValueRef\n\n}\n\n\n\nimpl Value {\n\n pub fn dump(&self) {\n\n unsafe {\n\n LLVMDumpValue(self.value);\n\n }\n\n }\n\n\n\n pub fn get_param(&self, pos: u32)->Value {\n\n unsafe {\n\n Value {value: LLVMGetParam(self.value, pos)}\n\n }\n\n }\n\n\n\n pub fn int1(context: &Context, b: bool)->Value {\n\n unsafe {\n\n Value {value: LLVMConstInt(Type::int1(context).type_, if b {1} else {0} as u64, 1)}\n\n }\n", "file_path": "src/llvm_wrapper.rs", "rank": 25, "score": 19105.274462818474 }, { "content": " }\n\n\n\n pub fn struct_<IterT: Deref<Target=[Type]>>(context: &Context, elem_types: &IterT, is_packed: bool)->Type {\n\n let n = elem_types.len() as u32;\n\n let mut elems = elem_types.iter().map(|x|{x.type_}).collect::<Vec<LLVMTypeRef>>();\n\n let p = elems.as_mut_ptr();\n\n unsafe {\n\n Type { type_: LLVMStructTypeInContext(context.context, p, n, if is_packed {1} else {0}) }\n\n }\n\n }\n\n\n\n pub fn dump(&self) {\n\n unsafe {\n\n LLVMDumpType(self.type_);\n\n }\n\n }\n\n}\n\n\n\n#[derive(Debug, Clone, Copy)]\n\npub struct Value {\n", "file_path": "src/llvm_wrapper.rs", "rank": 26, "score": 19104.501227001467 }, { "content": " }\n\n }\n\n }\n\n\n\n pub fn debug_info(&self, line: u32, col: u32)->MetaData {\n\n unsafe {\n\n MetaData {\n\n meta_data: llvm_sys::debuginfo::LLVMDIBuilderCreateDebugLocation(self.context, line as libc::c_uint, col as libc::c_uint, std::ptr::null_mut(), std::ptr::null_mut())\n\n }\n\n }\n\n }\n\n pub fn dispose(&mut self) {\n\n unsafe { LLVMContextDispose(self.context); }\n\n }\n\n}\n\n\n\n#[derive(Debug)]\n\npub struct Module {\n\n pub module: LLVMModuleRef\n\n}\n", "file_path": "src/llvm_wrapper.rs", "rank": 27, "score": 19103.57866229578 }, { "content": "\n\n pub fn load_with_type<StrT: Into<Vec<u8>>>(&mut self, ty: &Type, ptr_val: &Value, name: StrT)->Value {\n\n let cname = CString::new(name).expect(\"CString::new failed\");\n\n unsafe {\n\n Value {\n\n value: LLVMBuildLoad2(self.builder, ty.type_, ptr_val.value, cname.as_ptr())\n\n }\n\n }\n\n }\n\n\n\n pub fn store(&mut self, ptr_val: &Value, val: &Value)->Value {\n\n unsafe {\n\n Value{\n\n value: LLVMBuildStore(self.builder, val.value, ptr_val.value)\n\n }\n\n }\n\n }\n\n pub fn global_string_ptr<StrT: Into<Vec<u8>>>(&mut self, val: StrT, name: StrT)->Value {\n\n let cval = CString::new(val).expect(\"CString::new failed\");\n\n let cname = CString::new(name).expect(\"CString::new failed\");\n", "file_path": "src/llvm_wrapper.rs", "rank": 28, "score": 19103.519626895337 }, { "content": "\n\n pub fn br(&mut self, dest: &BasicBlock)->Value {\n\n unsafe {\n\n Value {\n\n value: LLVMBuildBr(self.builder, dest.basic_block)\n\n }\n\n }\n\n }\n\n\n\n pub fn cond_br(&mut self, cond: &Value, true_clause: &BasicBlock, false_clause: &BasicBlock)->Value {\n\n unsafe {\n\n Value {\n\n value: LLVMBuildCondBr(self.builder, cond.value, true_clause.basic_block, false_clause.basic_block)\n\n }\n\n }\n\n }\n\n\n\n pub fn phi<StrT>(&mut self, ty: &Type, name: StrT)->Phi where StrT: Into<Vec<u8>> {\n\n let cname = CString::new(name).expect(\"CString::new failed\");\n\n unsafe {\n", "file_path": "src/llvm_wrapper.rs", "rank": 29, "score": 19103.027744503903 }, { "content": " }\n\n\n\n pub fn get_type(&self)->Type {\n\n unsafe {\n\n Type { type_: LLVMTypeOf(self.value) }\n\n }\n\n }\n\n}\n\n\n\n\n\n#[derive(Debug, Clone, Copy)]\n\npub struct Phi {\n\n pub value: LLVMValueRef\n\n}\n\n\n\nimpl Phi {\n\n pub fn add_incomings(&mut self, blocks: &Vec<BasicBlock>, values: &Vec<Value>) {\n\n if blocks.len() != values.len() {\n\n panic!(\"Phi#incomings' argument vectors must have same length\")\n\n }\n", "file_path": "src/llvm_wrapper.rs", "rank": 30, "score": 19102.034234834806 }, { "content": " }\n\n }\n\n\n\n pub fn alloca<StrT: Into<Vec<u8>>>(&mut self, ty: &Type, name: StrT)->Value {\n\n let cname = CString::new(name).expect(\"CString::new failed\");\n\n unsafe {\n\n Value {\n\n value: LLVMBuildAlloca(self.builder, ty.type_, cname.as_ptr())\n\n }\n\n }\n\n }\n\n\n\n pub fn load<StrT: Into<Vec<u8>>>(&mut self, ptr_val: &Value, name: StrT)->Value {\n\n let cname = CString::new(name).expect(\"CString::new failed\");\n\n unsafe {\n\n Value {\n\n value: LLVMBuildLoad(self.builder, ptr_val.value, cname.as_ptr())\n\n }\n\n }\n\n }\n", "file_path": "src/llvm_wrapper.rs", "rank": 31, "score": 19101.634371258067 }, { "content": " unsafe {\n\n Value {\n\n value: if is_unsigned {\n\n LLVMBuildICmp(self.builder, llvm::LLVMIntPredicate::LLVMIntUGE, lhs.value , rhs.value, cname.as_ptr())\n\n } else {\n\n LLVMBuildICmp(self.builder, llvm::LLVMIntPredicate::LLVMIntSGE, lhs.value , rhs.value, cname.as_ptr())\n\n }\n\n }\n\n }\n\n }\n\n}\n\n\n\nimpl Drop for Builder {\n\n fn drop(&mut self) {\n\n //unsafe {LLVMDisposeBuilder(self.builder);}\n\n }\n\n}\n\n\n\n#[derive(Debug, Clone, Copy)]\n\npub struct Type {\n", "file_path": "src/llvm_wrapper.rs", "rank": 32, "score": 19100.110947747955 }, { "content": " pub fn new_host(opt_level: LLVMCodeGenOptLevel, reloc_mode: LLVMRelocMode, code_model: LLVMCodeModel)->TargetMachine {\n\n unsafe {\n\n let cpu = CString::from_raw(LLVMGetHostCPUName());\n\n let feats = CString::from_raw(LLVMGetHostCPUFeatures());\n\n let tm = Self::new_native(cpu.as_bytes(), feats.as_bytes(), opt_level, reloc_mode, code_model);\n\n LLVMDisposeMessage(cpu.into_raw());\n\n LLVMDisposeMessage(feats.into_raw());\n\n tm\n\n }\n\n }\n\n\n\n\n\n pub fn compile_to_file<StrT: Into<Vec<u8>>>(&self, module: &Module, file_name: StrT, file_type: LLVMCodeGenFileType)->Result<(), &str> {\n\n unsafe {\n\n let cfname = CString::new(file_name).expect(\"CString::new failed\");\n\n let is_err = LLVMTargetMachineEmitToFile(self.target_machine, module.module, cfname.into_raw(), file_type, ptr::null_mut());\n\n if is_err != 0 {\n\n return Err(\"init\");\n\n }\n\n Ok(())\n\n }\n\n }\n\n pub fn dispose(&mut self) {\n\n unsafe{ LLVMDisposeTargetMachine(self.target_machine); }\n\n }\n\n}\n", "file_path": "src/llvm_wrapper.rs", "rank": 33, "score": 19099.939846359674 }, { "content": " LLVMBuildSDiv(self.builder, lhs.value, rhs.value, cname.as_ptr()) \n\n }\n\n }\n\n }\n\n }\n\n pub fn op_imod<StrT: Into<Vec<u8>>>(&mut self, lhs: &Value, rhs: &Value, is_unsigned: bool, name: StrT)->Value {\n\n let cname = CString::new(name).expect(\"CString::new failed\");\n\n unsafe {\n\n Value {\n\n value: if is_unsigned {\n\n LLVMBuildURem(self.builder, lhs.value, rhs.value, cname.as_ptr())\n\n } else {\n\n LLVMBuildSRem(self.builder, lhs.value, rhs.value, cname.as_ptr())\n\n }\n\n }\n\n }\n\n }\n\n\n\n pub fn op_lnot<StrT: Into<Vec<u8>>>(&mut self, arg: &Value, name: StrT)->Value {\n\n let cname = CString::new(name).expect(\"CString::new failed\");\n", "file_path": "src/llvm_wrapper.rs", "rank": 34, "score": 19099.893219314956 }, { "content": " let cname = CString::new(name).expect(\"CString::new failed\");\n\n unsafe {\n\n Value { value: LLVMBuildExtractValue(self.builder, struct_.value, idx, cname.as_ptr()) }\n\n }\n\n }\n\n\n\n pub fn get_array_elem<StrT: Into<Vec<u8>>>(&self, array: &Value, idx: &Value, name: StrT)->Value {\n\n let cname = CString::new(name).expect(\"CString::new failed\");\n\n unsafe {\n\n Value { value: LLVMBuildExtractElement(self.builder, array.value, idx.value, cname.as_ptr()) }\n\n }\n\n }\n\n\n\n pub fn set_struct_elem<StrT: Into<Vec<u8>>>(&self, struct_: &Value, idx: u32, elem: &Value, name: StrT)->Value {\n\n let cname = CString::new(name).expect(\"CString::new failed\");\n\n unsafe {\n\n Value { value: LLVMBuildInsertValue(self.builder, struct_.value, elem.value, idx, cname.as_ptr()) }\n\n }\n\n }\n\n\n", "file_path": "src/llvm_wrapper.rs", "rank": 35, "score": 19099.096791831726 }, { "content": " } else {\n\n LLVMBuildICmp(self.builder, llvm::LLVMIntPredicate::LLVMIntSLE, lhs.value , rhs.value, cname.as_ptr())\n\n }\n\n }\n\n }\n\n }\n\n pub fn op_igt<StrT: Into<Vec<u8>>>(&mut self, lhs: &Value, rhs: &Value, is_unsigned: bool, name: StrT)->Value {\n\n let cname = CString::new(name).expect(\"CString::new failed\");\n\n unsafe {\n\n Value {\n\n value: if is_unsigned {\n\n LLVMBuildICmp(self.builder, llvm::LLVMIntPredicate::LLVMIntUGT, lhs.value , rhs.value, cname.as_ptr())\n\n } else {\n\n LLVMBuildICmp(self.builder, llvm::LLVMIntPredicate::LLVMIntSGT, lhs.value , rhs.value, cname.as_ptr())\n\n }\n\n }\n\n }\n\n }\n\n pub fn op_igte<StrT: Into<Vec<u8>>>(&mut self, lhs: &Value, rhs: &Value, is_unsigned: bool, name: StrT)->Value {\n\n let cname = CString::new(name).expect(\"CString::new failed\");\n", "file_path": "src/llvm_wrapper.rs", "rank": 36, "score": 19099.02979005823 }, { "content": " }\n\n }\n\n pub fn op_ilt<StrT: Into<Vec<u8>>>(&mut self, lhs: &Value, rhs: &Value, is_unsigned: bool, name: StrT)->Value {\n\n let cname = CString::new(name).expect(\"CString::new failed\");\n\n unsafe {\n\n Value {\n\n value: if is_unsigned {\n\n LLVMBuildICmp(self.builder, llvm::LLVMIntPredicate::LLVMIntULT, lhs.value , rhs.value, cname.as_ptr())\n\n } else {\n\n LLVMBuildICmp(self.builder, llvm::LLVMIntPredicate::LLVMIntSLT, lhs.value , rhs.value, cname.as_ptr())\n\n }\n\n }\n\n }\n\n }\n\n pub fn op_ilte<StrT: Into<Vec<u8>>>(&mut self, lhs: &Value, rhs: &Value, is_unsigned: bool, name: StrT)->Value {\n\n let cname = CString::new(name).expect(\"CString::new failed\");\n\n unsafe {\n\n Value {\n\n value: if is_unsigned {\n\n LLVMBuildICmp(self.builder, llvm::LLVMIntPredicate::LLVMIntULE, lhs.value , rhs.value, cname.as_ptr())\n", "file_path": "src/llvm_wrapper.rs", "rank": 37, "score": 19098.910983930557 }, { "content": " unsafe {\n\n Value {\n\n value: LLVMBuildNot(self.builder, arg.value, cname.as_ptr())\n\n }\n\n }\n\n }\n\n pub fn op_ieq<StrT: Into<Vec<u8>>>(&mut self, lhs: &Value, rhs: &Value, name: StrT)->Value {\n\n let cname = CString::new(name).expect(\"CString::new failed\");\n\n unsafe {\n\n Value {\n\n value: LLVMBuildICmp(self.builder, llvm::LLVMIntPredicate::LLVMIntEQ, lhs.value , rhs.value, cname.as_ptr())\n\n }\n\n }\n\n }\n\n pub fn op_ineq<StrT: Into<Vec<u8>>>(&mut self, lhs: &Value, rhs: &Value, name: StrT)->Value {\n\n let cname = CString::new(name).expect(\"CString::new failed\");\n\n unsafe {\n\n Value {\n\n value: LLVMBuildICmp(self.builder, llvm::LLVMIntPredicate::LLVMIntNE, lhs.value , rhs.value, cname.as_ptr())\n\n }\n", "file_path": "src/llvm_wrapper.rs", "rank": 38, "score": 19098.69850224321 }, { "content": " value: LLVMBuildSub(self.builder, lhs.value, rhs.value, cname.as_ptr())\n\n }\n\n }\n\n }\n\n pub fn op_imul<StrT: Into<Vec<u8>>>(&mut self, lhs: &Value, rhs: &Value, name: StrT)->Value {\n\n let cname = CString::new(name).expect(\"CString::new failed\");\n\n unsafe {\n\n Value {\n\n value: LLVMBuildMul(self.builder, lhs.value, rhs.value, cname.as_ptr())\n\n }\n\n }\n\n }\n\n\n\n pub fn op_idiv<StrT: Into<Vec<u8>>>(&mut self, lhs: &Value, rhs: &Value, is_unsigned: bool, name: StrT)->Value {\n\n let cname = CString::new(name).expect(\"CString::new failed\");\n\n unsafe {\n\n Value {\n\n value: if is_unsigned {\n\n LLVMBuildUDiv(self.builder, lhs.value, rhs.value, cname.as_ptr())\n\n } else {\n", "file_path": "src/llvm_wrapper.rs", "rank": 39, "score": 19098.32846432424 }, { "content": " let l = blocks.len() as libc::c_uint;\n\n let mut bv = blocks.into_iter().map(|x|x.basic_block).collect::<Vec<_>>();\n\n let mut vv = values.into_iter().map(|x|x.value).collect::<Vec<_>>();\n\n let mut b = bv.as_mut_ptr();\n\n let mut v = vv.as_mut_ptr();\n\n unsafe {\n\n LLVMAddIncoming(self.value, v, b, l)\n\n }\n\n }\n\n\n\n pub fn add_incoming(&mut self, block: &BasicBlock, value: &Value) {\n\n let mut b = [block.basic_block];\n\n let mut v = [value.value];\n\n unsafe {\n\n LLVMAddIncoming(self.value, v.as_mut_ptr(), b.as_mut_ptr(), 1);\n\n } \n\n }\n\n\n\n pub fn get_value(&self)->Value {\n\n Value{\n", "file_path": "src/llvm_wrapper.rs", "rank": 40, "score": 19098.04804127515 }, { "content": " }\n\n\n\n pub fn dispose(&mut self) {\n\n unsafe {LLVMDisposeBuilder(self.builder);}\n\n }\n\n\n\n pub fn set_debug_info(&mut self, file: u32, line: u32, col: u32) {\n\n unimplemented!();\n\n }\n\n\n\n pub fn get_current_basic_block(&self)->BasicBlock {\n\n unsafe {\n\n BasicBlock {basic_block: LLVMGetInsertBlock(self.builder)}\n\n }\n\n }\n\n pub fn set_position_at_end_of(&mut self, bb: &BasicBlock) {\n\n unsafe {\n\n LLVMPositionBuilderAtEnd(self.builder, bb.basic_block);\n\n }\n\n }\n", "file_path": "src/llvm_wrapper.rs", "rank": 41, "score": 19097.916817618298 }, { "content": " }\n\n pub fn int8(context: &Context, i: i8)->Value {\n\n unsafe {\n\n Value {value: LLVMConstInt(Type::int8(context).type_, i as u64, 1)}\n\n }\n\n }\n\n pub fn int16(context: &Context, i: i16)->Value {\n\n unsafe {\n\n Value {value: LLVMConstInt(Type::int16(context).type_, i as u64, 1)}\n\n }\n\n }\n\n pub fn int32(context: &Context, i: i32)->Value {\n\n unsafe {\n\n Value {value: LLVMConstInt(Type::int32(context).type_, i as u64, 1)}\n\n }\n\n }\n\n pub fn int64(context: &Context, i: i64)->Value {\n\n unsafe {\n\n Value {value: LLVMConstInt(Type::int64(context).type_, i as u64, 1)}\n\n }\n", "file_path": "src/llvm_wrapper.rs", "rank": 42, "score": 19097.901364350648 }, { "content": " Phi {\n\n value: LLVMBuildPhi(self.builder, ty.type_, cname.as_ptr())\n\n }\n\n }\n\n }\n\n\n\n\n\n pub fn ret(&mut self, val: &Value)->Value {\n\n unsafe {\n\n Value {\n\n value: LLVMBuildRet(self.builder, val.value)\n\n }\n\n }\n\n }\n\n\n\n pub fn ret_void(&mut self)->Value {\n\n unsafe {\n\n Value {\n\n value: LLVMBuildRetVoid(self.builder)\n\n }\n", "file_path": "src/llvm_wrapper.rs", "rank": 43, "score": 19097.892452910877 }, { "content": "\n\n pub fn append_basic_block_after<StrT: Into<Vec<u8>>>(&mut self, fun: &Value, pos: &BasicBlock, name: StrT)->BasicBlock {\n\n let cname = CString::new(name).expect(\"CString::new failed\");\n\n unsafe {\n\n let next_bb = LLVMGetNextBasicBlock(pos.basic_block);\n\n if next_bb == std::ptr::null_mut() {\n\n BasicBlock {\n\n basic_block: LLVMAppendBasicBlockInContext(self.context, fun.value, cname.as_ptr())\n\n }\n\n } else {\n\n BasicBlock {\n\n basic_block: LLVMInsertBasicBlockInContext(self.context, next_bb, cname.as_ptr())\n\n }\n\n }\n\n }\n\n }\n\n pub fn last_basic_block(fun: &Value)->BasicBlock {\n\n unsafe {\n\n BasicBlock {\n\n basic_block: LLVMGetLastBasicBlock(fun.value)\n", "file_path": "src/llvm_wrapper.rs", "rank": 44, "score": 19097.840301073073 }, { "content": " }\n\n}\n\n\n\n#[derive(Debug)]\n\npub struct MetaData {\n\n pub meta_data: LLVMMetadataRef\n\n}\n\nimpl MetaData {\n\n}\n\n\n\n#[derive(Debug)]\n\npub struct TargetMachine {\n\n pub target_machine: LLVMTargetMachineRef\n\n}\n\n\n\nimpl TargetMachine {\n\n pub fn new<StrT: Into<Vec<u8>>>(triple: StrT, cpu: StrT, features: StrT, opt_level: LLVMCodeGenOptLevel, reloc_mode: LLVMRelocMode, code_model: LLVMCodeModel)->TargetMachine {\n\n unsafe {\n\n let ctriple = CString::new(triple).expect(\"CString::new failed\");\n\n let ccpu = CString::new(cpu).expect(\"CString::new failed\");\n", "file_path": "src/llvm_wrapper.rs", "rank": 45, "score": 19097.804552896883 }, { "content": " LLVMDumpModule(self.module);\n\n }\n\n }\n\n\n\n pub fn print_to_file<StrT: Into<Vec<u8>>>(&self, file: StrT) {\n\n let cfile = CString::new(file).expect(\"CString::new failed\");\n\n unsafe {\n\n let is_err = LLVMPrintModuleToFile(self.module, cfile.as_ptr(), std::ptr::null_mut());\n\n if is_err != 0 {\n\n panic!(\"failed to print module to file\")\n\n }\n\n }\n\n }\n\n\n\n pub fn verify(&self) {\n\n unsafe {\n\n LLVMVerifyModule(self.module, LLVMVerifierFailureAction::LLVMAbortProcessAction, std::ptr::null_mut());\n\n }\n\n }\n\n\n", "file_path": "src/llvm_wrapper.rs", "rank": 46, "score": 19097.61452709802 }, { "content": " pub fn dispose(&self) {\n\n unsafe {LLVMDisposeModule(self.module);}\n\n }\n\n}\n\n\n\nimpl Drop for Module {\n\n fn drop(&mut self) {\n\n // unsafe {LLVMDisposeModule(self.module);}\n\n }\n\n}\n\n\n\n#[derive(Debug)]\n\npub struct Builder {\n\n pub builder: LLVMBuilderRef\n\n}\n\nimpl Builder {\n\n pub fn new(context: &Context)->Builder {\n\n unsafe {\n\n Builder{ builder: LLVMCreateBuilderInContext(context.context) }\n\n }\n", "file_path": "src/llvm_wrapper.rs", "rank": 47, "score": 19097.32529197908 }, { "content": " value: self.value\n\n }\n\n }\n\n}\n\n\n\n#[derive(Debug, Clone)]\n\npub struct BasicBlock {\n\n pub basic_block: LLVMBasicBlockRef\n\n}\n\n\n\nimpl BasicBlock {\n\n pub fn move_before(&mut self, pos: &BasicBlock) {\n\n unsafe {\n\n LLVMMoveBasicBlockBefore(self.basic_block, pos.basic_block)\n\n }\n\n }\n\n pub fn move_after(&mut self, pos: &BasicBlock) {\n\n unsafe {\n\n LLVMMoveBasicBlockAfter(self.basic_block, pos.basic_block)\n\n }\n", "file_path": "src/llvm_wrapper.rs", "rank": 48, "score": 19096.549775046034 }, { "content": " pub fn set_array_elem<StrT: Into<Vec<u8>>>(&self, array: &Value, idx: &Value, name: StrT)->Value {\n\n let cname = CString::new(name).expect(\"CString::new failed\");\n\n unsafe {\n\n Value { value: LLVMBuildExtractElement(self.builder, array.value, idx.value, cname.as_ptr()) }\n\n }\n\n }\n\n\n\n pub fn op_iadd<StrT: Into<Vec<u8>>>(&mut self, lhs: &Value, rhs: &Value, name: StrT)->Value {\n\n let cname = CString::new(name).expect(\"CString::new failed\");\n\n unsafe {\n\n Value {\n\n value: LLVMBuildAdd(self.builder, lhs.value, rhs.value, cname.as_ptr())\n\n }\n\n }\n\n }\n\n\n\n pub fn op_isub<StrT: Into<Vec<u8>>>(&mut self, lhs: &Value, rhs: &Value, name: StrT)->Value {\n\n let cname = CString::new(name).expect(\"CString::new failed\");\n\n unsafe {\n\n Value {\n", "file_path": "src/llvm_wrapper.rs", "rank": 49, "score": 19096.29494953603 }, { "content": " let cfeatures = CString::new(features).expect(\"CString::new failed\");\n\n LLVM_InitializeAllTargets();\n\n LLVM_InitializeAllAsmPrinters();\n\n\n\n let mut target = mem::MaybeUninit::uninit().assume_init();\n\n let mut err = mem::MaybeUninit::uninit().assume_init();\n\n \n\n let is_ok = LLVMGetTargetFromTriple(ctriple.as_ptr(), &mut target, &mut err);\n\n if is_ok != 0 {\n\n let err = CString::from_raw(err);\n\n println!(\"{:?}\", &err);\n\n LLVMDisposeMessage(err.into_raw());\n\n }\n\n let tm = LLVMCreateTargetMachine(target, ctriple.as_ptr(), ccpu.as_ptr(), cfeatures.as_ptr(), opt_level, reloc_mode, code_model);\n\n TargetMachine{ target_machine: tm }\n\n }\n\n }\n\n pub fn new_native<StrT: Into<Vec<u8>>>(cpu: StrT, features: StrT, opt_level: LLVMCodeGenOptLevel, reloc_mode: LLVMRelocMode, code_model: LLVMCodeModel)->TargetMachine {\n\n unsafe {\n\n let ccpu = CString::new(cpu).expect(\"CString::new failed\");\n", "file_path": "src/llvm_wrapper.rs", "rank": 50, "score": 19096.093702226783 }, { "content": " let cfeatures = CString::new(features).expect(\"CString::new failed\");\n\n LLVM_InitializeNativeTarget();\n\n LLVM_InitializeNativeAsmPrinter();\n\n\n\n let triple = LLVMGetDefaultTargetTriple();\n\n let mut target = mem::MaybeUninit::uninit().assume_init();\n\n let mut err = mem::MaybeUninit::uninit().assume_init();\n\n \n\n let is_ok = LLVMGetTargetFromTriple(triple, &mut target, &mut err);\n\n if is_ok != 0 {\n\n let err = CString::from_raw(err);\n\n println!(\"{:?}\", &err);\n\n LLVMDisposeMessage(err.into_raw());\n\n }\n\n let tm = LLVMCreateTargetMachine(target, triple, ccpu.as_ptr(), cfeatures.as_ptr(), opt_level, reloc_mode, code_model);\n\n LLVMDisposeMessage(triple);\n\n TargetMachine{ target_machine: tm }\n\n }\n\n }\n\n\n", "file_path": "src/llvm_wrapper.rs", "rank": 51, "score": 19095.909433707304 }, { "content": " }\n\n }\n\n\n\n pub fn append_basic_block<StrT: Into<Vec<u8>>>(&mut self, fun: &Value, name: StrT)->BasicBlock {\n\n let cname = CString::new(name).expect(\"CString::new failed\");\n\n unsafe {\n\n BasicBlock {\n\n basic_block: LLVMAppendBasicBlockInContext(self.context, fun.value, cname.as_ptr())\n\n }\n\n }\n\n }\n\n\n\n pub fn insert_basic_block_before<StrT: Into<Vec<u8>>>(&mut self, pos: &BasicBlock, name: StrT)->BasicBlock {\n\n let cname = CString::new(name).expect(\"CString::new failed\");\n\n unsafe {\n\n BasicBlock {\n\n basic_block: LLVMInsertBasicBlockInContext(self.context, pos.basic_block, cname.as_ptr())\n\n }\n\n }\n\n }\n", "file_path": "src/llvm_wrapper.rs", "rank": 52, "score": 19095.24607509925 }, { "content": " pub type_: LLVMTypeRef\n\n}\n\nimpl Type {\n\n pub fn void(context: &Context)->Type {\n\n unsafe {\n\n Type { type_: LLVMVoidTypeInContext(context.context) }\n\n }\n\n }\n\n pub fn int1(context: &Context)->Type {\n\n unsafe {\n\n Type { type_: LLVMInt1TypeInContext(context.context) }\n\n }\n\n }\n\n pub fn int8(context: &Context)->Type {\n\n unsafe {\n\n Type { type_: LLVMInt8TypeInContext(context.context) }\n\n }\n\n }\n\n pub fn int16(context: &Context)->Type {\n\n unsafe {\n", "file_path": "src/llvm_wrapper.rs", "rank": 53, "score": 19094.075211827487 }, { "content": " Type { type_: LLVMInt16TypeInContext(context.context) }\n\n }\n\n }\n\n pub fn int32(context: &Context)->Type {\n\n unsafe {\n\n Type { type_: LLVMInt32TypeInContext(context.context) }\n\n }\n\n }\n\n pub fn int64(context: &Context)->Type {\n\n unsafe {\n\n Type { type_: LLVMInt64TypeInContext(context.context) }\n\n }\n\n }\n\n pub fn float(context: &Context)->Type {\n\n unsafe {\n\n Type { type_: LLVMFloatTypeInContext(context.context) }\n\n }\n\n }\n\n pub fn double(context: &Context)->Type {\n\n unsafe {\n", "file_path": "src/llvm_wrapper.rs", "rank": 54, "score": 19092.012612051018 }, { "content": " self.0.pop()\n\n }\n\n pub fn insert_alloca(&mut self, builder: &mut llvm::Builder, current_bb: &llvm::BasicBlock, ty: &llvm::Type)->Result<llvm::Value, MirErr> {\n\n let fse = self.get_current().ok_or(MirErr::LocalVarOnGlobal)?;\n\n let alloca_bb = &fse.alloca_bb;\n\n builder.set_position_at_end_of(alloca_bb);\n\n let ret = builder.alloca(ty, \"\");\n\n builder.set_position_at_end_of(current_bb);\n\n Ok(ret)\n\n }\n\n}", "file_path": "src/func_stack.rs", "rank": 65, "score": 20.52933707167307 }, { "content": "use super::{llvm, MirErr};\n\n\n\npub struct FuncStackElem {\n\n pub func: llvm::Value,\n\n pub alloca_bb: llvm::BasicBlock,\n\n}\n\n\n\n\n\npub struct FuncStack(Vec<FuncStackElem>);\n\nimpl FuncStack {\n\n pub fn new()->Self {\n\n FuncStack(Vec::new())\n\n }\n\n pub fn get_current(&mut self)->Option<&mut FuncStackElem> {\n\n self.0.last_mut()\n\n }\n\n pub fn push(&mut self, el: FuncStackElem) {\n\n self.0.push(el)\n\n }\n\n pub fn pop(&mut self)->Option<FuncStackElem> {\n", "file_path": "src/func_stack.rs", "rank": 68, "score": 18.519959576379883 }, { "content": "\n\nuse symbol::Symbol;\n\nuse super::llvm;\n\n\n\npub struct LoopStackElem {\n\n pub name: Option<Symbol>,\n\n pub begin_bb: llvm::BasicBlock,\n\n pub end_bb: llvm::BasicBlock,\n\n}\n", "file_path": "src/loop_stack.rs", "rank": 74, "score": 12.556434839809256 }, { "content": "# Mirach\n\n\n\n![](https://github.com/aymgm/Mirach/workflows/Test%20on%20Linux/badge.svg)\n\n![](https://github.com/aymgm/Mirach/workflows/Test%20on%20Windows/badge.svg)\n\n![](https://github.com/aymgm/Mirach/workflows/Test%20on%20Mac/badge.svg)\n\n\n\nMirach is a (work-in-progress) mid-layer intermediate representation for programming language implementations.\n\n\n\nThis library is on very early stage and not intended to be used for practical usage.\n\n\n\n## Build\n\n\n\n### Requirement\n\n - Rust 1.37+\n\n - Maybe older versions can compile, but not tested.\n\n - LibLLVM 8.0+\n\n - gcc\n\n\n\n### Test\n\nSee `.github/workflows`\n\n\n\n### License\n", "file_path": "README.md", "rank": 82, "score": 3.135008738528717 } ]
Rust
src/textures/render_texture.rs
e0328eric/dioteko
e1f4e017c449d0904ff722f2e3f58ea3a1489b98
use std::cell::Cell; use std::ptr::NonNull; use crate::ffi; pub(crate) struct RenderTextureRc { strong: Cell<usize>, weak: Cell<usize>, } impl RenderTextureRc { fn new() -> Self { Self { strong: Cell::new(1), weak: Cell::new(1), } } } trait RenderTextureRcControll { fn get_strong(&self) -> &Cell<usize>; fn get_weak(&self) -> &Cell<usize>; #[inline] fn strong(&self) -> usize { self.get_strong().get() } #[inline] fn weak(&self) -> usize { self.get_weak().get() } #[inline] fn inc_strong(&self) { self.get_strong().set(self.strong() + 1); } #[inline] fn dec_strong(&self) { self.get_strong().set(self.strong() - 1); } #[inline] fn inc_weak(&self) { self.get_weak().set(self.weak() + 1); } #[inline] fn dec_weak(&self) { self.get_weak().set(self.weak() - 1); } } pub struct RenderTexture { render_texture: ffi::RenderTexture, rc_count: NonNull<RenderTextureRc>, } pub type RenderTexture2D = RenderTexture; impl RenderTexture { pub fn load(width: i32, height: i32) -> Self { Self { render_texture: unsafe { ffi::LoadRenderTexture(width, height) }, rc_count: Box::leak(Box::new(RenderTextureRc::new())).into(), } } pub fn downgrade(val: &Self) -> WeakRenderTexture { val.inc_weak(); WeakRenderTexture { render_texture: val.render_texture, rc_count: val.rc_count, } } #[allow(dead_code)] #[inline] pub(crate) unsafe fn into_raw(self) -> (ffi::RenderTexture, NonNull<RenderTextureRc>) { (self.render_texture, self.rc_count) } #[allow(dead_code)] #[inline] pub(crate) unsafe fn from_raw( render_texture: ffi::RenderTexture, rc_count: NonNull<RenderTextureRc>, ) -> Self { Self { render_texture, rc_count, } } } impl Drop for RenderTexture { fn drop(&mut self) { self.dec_strong(); if self.strong() == 0 { unsafe { ffi::UnloadRenderTexture(self.render_texture) } self.dec_weak(); if self.weak() == 0 { drop(unsafe { Box::from_raw(self.rc_count.as_ptr()) }) } } } } pub struct WeakRenderTexture { render_texture: ffi::RenderTexture, rc_count: NonNull<RenderTextureRc>, } pub type WeakRenderTexture2D = WeakRenderTexture; impl WeakRenderTexture { pub fn upgrade(&self) -> Option<RenderTexture> { if self.strong() != 0 { Some(RenderTexture { render_texture: self.render_texture, rc_count: self.rc_count, }) } else { None } } #[allow(dead_code)] #[inline] pub(crate) unsafe fn into_raw(self) -> (ffi::RenderTexture, NonNull<RenderTextureRc>) { (self.render_texture, self.rc_count) } #[allow(dead_code)] #[inline] pub(crate) unsafe fn from_raw( render_texture: ffi::RenderTexture, rc_count: NonNull<RenderTextureRc>, ) -> Self { Self { render_texture, rc_count, } } } impl Clone for WeakRenderTexture { fn clone(&self) -> Self { self.inc_weak(); Self { render_texture: self.render_texture, rc_count: self.rc_count, } } } impl Drop for WeakRenderTexture { fn drop(&mut self) { self.dec_weak(); if self.weak() == 0 { drop(unsafe { Box::from_raw(self.rc_count.as_ptr()) }) } } } impl RenderTextureRcControll for RenderTexture { fn get_strong(&self) -> &Cell<usize> { unsafe { &self.rc_count.as_ref().strong } } fn get_weak(&self) -> &Cell<usize> { unsafe { &self.rc_count.as_ref().weak } } } impl RenderTextureRcControll for WeakRenderTexture { fn get_strong(&self) -> &Cell<usize> { unsafe { &self.rc_count.as_ref().strong } } fn get_weak(&self) -> &Cell<usize> { unsafe { &self.rc_count.as_ref().weak } } }
use std::cell::Cell; use std::ptr::NonNull; use crate::ffi; pub(crate) struct RenderTextureRc { strong: Cell<usize>, weak: Cell<usize>, } impl RenderTextureRc { fn new() -> Self { Self { strong: Cell::new(1), weak: Cell::new(1), } } } trait RenderTextureRcControll { fn get_strong(&self) -> &Cell<usize>; fn get_weak(&self) -> &Cell<usize>; #[inline] fn strong(&self) -> usize { self.get_strong().get() } #[inline] fn weak(&self) -> usize { self.get_weak().get() } #[inline] fn inc_strong(&self) { self.get_strong().set(self.strong() + 1); } #[inline] fn dec_strong(&self) { self.get_strong().set(self.strong() - 1); } #[inline] fn inc_weak(&self) { self.get_weak().set(self.weak() + 1); } #[inline] fn dec_weak(&self) { self.get_weak().set(self.weak() - 1); } } pub struct RenderTexture { render_texture: ffi::RenderTexture, rc_count: NonNull<RenderTextureRc>, } pub type RenderTexture2D = RenderTexture; impl RenderTexture { pub fn load(width: i32, height: i32) -> Self { Self { render_texture: unsafe { ffi::LoadRenderTexture(width, height) }, rc_count: Box::leak(Box::new(RenderTextureRc::new())).into(), } } pub fn downgrade(val: &Self) -> WeakRenderTexture { val.inc_weak(); WeakRenderTexture { render_texture: val.render_texture, rc_count: val.rc_count, } } #[allow(dead_code)] #[inline] pub(crate) unsafe fn into_raw(self) -> (ffi::RenderTexture, NonNull<RenderTextureRc>) { (self.render_texture, self.rc_count) } #[allow(dead_code)] #[inline] pub(crate) unsafe fn from_raw( render_texture: ffi::RenderTexture, rc_count: NonNull<RenderTextureRc>, ) -> Self { Self { render_texture, rc_count, } } } impl Drop for RenderTexture { fn drop(&mut self) { self.dec_strong(); if self.strong() == 0 { unsafe { ffi::UnloadRenderTexture(self.render_texture) } self.dec_weak(); if self.weak() == 0 { drop(unsafe { Box::from_raw(self.rc_count.as_ptr()) }) } } } } pub struct WeakRenderTexture { render_texture: ffi::RenderTexture, rc_count: NonNull<RenderTextureRc>, } pub type WeakRenderTexture2D = WeakRenderTexture; impl WeakRenderTexture { pub fn upgrade(&self) -> Option<RenderTexture> { if self.strong() != 0 { Some(RenderTexture { render_texture: self.render_texture, rc_count: self.rc_count, }) } else { None } }
render_texture: self.render_texture, rc_count: self.rc_count, } } } impl Drop for WeakRenderTexture { fn drop(&mut self) { self.dec_weak(); if self.weak() == 0 { drop(unsafe { Box::from_raw(self.rc_count.as_ptr()) }) } } } impl RenderTextureRcControll for RenderTexture { fn get_strong(&self) -> &Cell<usize> { unsafe { &self.rc_count.as_ref().strong } } fn get_weak(&self) -> &Cell<usize> { unsafe { &self.rc_count.as_ref().weak } } } impl RenderTextureRcControll for WeakRenderTexture { fn get_strong(&self) -> &Cell<usize> { unsafe { &self.rc_count.as_ref().strong } } fn get_weak(&self) -> &Cell<usize> { unsafe { &self.rc_count.as_ref().weak } } }
#[allow(dead_code)] #[inline] pub(crate) unsafe fn into_raw(self) -> (ffi::RenderTexture, NonNull<RenderTextureRc>) { (self.render_texture, self.rc_count) } #[allow(dead_code)] #[inline] pub(crate) unsafe fn from_raw( render_texture: ffi::RenderTexture, rc_count: NonNull<RenderTextureRc>, ) -> Self { Self { render_texture, rc_count, } } } impl Clone for WeakRenderTexture { fn clone(&self) -> Self { self.inc_weak(); Self {
random
[ { "content": "pub fn get_pixel_data_size(width: i32, height: i32, format: i32) -> i32 {\n\n // SAFETY: ffi\n\n unsafe { ffi::GetPixelDataSize(width, height, format) }\n\n}\n", "file_path": "src/textures/pixel.rs", "rank": 0, "score": 176877.2228604159 }, { "content": "pub fn draw_text(text: &str, pos_x: i32, pos_y: i32, font_size: i32, color: Color) {\n\n let text = CString::new(text).expect(\"[INTERNAL ERROR]: Cannot cast str into cstring\");\n\n\n\n // SAFETY: ffi\n\n unsafe { ffi::DrawText(text.as_ptr(), pos_x, pos_y, font_size, color.into()) }\n\n}\n", "file_path": "src/text/mod.rs", "rank": 1, "score": 122622.5210560094 }, { "content": "pub fn draw_circle_v(center: Vector2, radius: f32, color: Color) {\n\n // SAFETY: ffi\n\n unsafe { ffi::DrawCircleV(center.into(), radius, color.into()) }\n\n}\n", "file_path": "src/shapes/mod.rs", "rank": 2, "score": 71663.58458315712 }, { "content": "trait TextureRcControll {\n\n fn get_strong(&self) -> &Cell<usize>;\n\n fn get_weak(&self) -> &Cell<usize>;\n\n\n\n #[inline]\n\n fn strong(&self) -> usize {\n\n self.get_strong().get()\n\n }\n\n\n\n #[inline]\n\n fn weak(&self) -> usize {\n\n self.get_weak().get()\n\n }\n\n\n\n #[inline]\n\n fn inc_strong(&self) {\n\n self.get_strong().set(self.strong() + 1);\n\n }\n\n\n\n #[inline]\n", "file_path": "src/textures/texture.rs", "rank": 3, "score": 60519.212146170175 }, { "content": "fn main() -> dioteko::Result<()> {\n\n let window = WindowBuilder::new(SCREEN_WIDTH, SCREEN_HEIGHT, \"dioteko example\").build()?;\n\n\n\n while !window.should_close() {\n\n let painter = Painter::begin();\n\n\n\n painter.clear_background(BLANK);\n\n\n\n text::draw_text(\n\n \"from https://pixabay.com/photos/ink-feather-pen-quill-write-5067880/\",\n\n 50,\n\n 20,\n\n 15,\n\n YELLOW,\n\n );\n\n }\n\n\n\n Ok(())\n\n}\n", "file_path": "src/main.rs", "rank": 5, "score": 42014.76062991227 }, { "content": "#[test]\n\nfn bindgen_test_layout_Shader() {\n\n assert_eq!(\n\n ::std::mem::size_of::<Shader>(),\n\n 16usize,\n\n concat!(\"Size of: \", stringify!(Shader))\n\n );\n\n assert_eq!(\n\n ::std::mem::align_of::<Shader>(),\n\n 8usize,\n\n concat!(\"Alignment of \", stringify!(Shader))\n\n );\n\n assert_eq!(\n\n unsafe { &(*(::std::ptr::null::<Shader>())).id as *const _ as usize },\n\n 0usize,\n\n concat!(\n\n \"Offset of field: \",\n\n stringify!(Shader),\n\n \"::\",\n\n stringify!(id)\n\n )\n", "file_path": "dioteko-raylib-sys/src/bindings.rs", "rank": 6, "score": 38444.54320304184 }, { "content": "#[test]\n\nfn bindgen_test_layout_Model() {\n\n assert_eq!(\n\n ::std::mem::size_of::<Model>(),\n\n 120usize,\n\n concat!(\"Size of: \", stringify!(Model))\n\n );\n\n assert_eq!(\n\n ::std::mem::align_of::<Model>(),\n\n 8usize,\n\n concat!(\"Alignment of \", stringify!(Model))\n\n );\n\n assert_eq!(\n\n unsafe { &(*(::std::ptr::null::<Model>())).transform as *const _ as usize },\n\n 0usize,\n\n concat!(\n\n \"Offset of field: \",\n\n stringify!(Model),\n\n \"::\",\n\n stringify!(transform)\n\n )\n", "file_path": "dioteko-raylib-sys/src/bindings.rs", "rank": 7, "score": 38444.54320304184 }, { "content": "#[test]\n\nfn bindgen_test_layout_Matrix() {\n\n assert_eq!(\n\n ::std::mem::size_of::<Matrix>(),\n\n 64usize,\n\n concat!(\"Size of: \", stringify!(Matrix))\n\n );\n\n assert_eq!(\n\n ::std::mem::align_of::<Matrix>(),\n\n 4usize,\n\n concat!(\"Alignment of \", stringify!(Matrix))\n\n );\n\n assert_eq!(\n\n unsafe { &(*(::std::ptr::null::<Matrix>())).m0 as *const _ as usize },\n\n 0usize,\n\n concat!(\n\n \"Offset of field: \",\n\n stringify!(Matrix),\n\n \"::\",\n\n stringify!(m0)\n\n )\n", "file_path": "dioteko-raylib-sys/src/bindings.rs", "rank": 8, "score": 38444.54320304184 }, { "content": "#[test]\n\nfn bindgen_test_layout_Color() {\n\n assert_eq!(\n\n ::std::mem::size_of::<Color>(),\n\n 4usize,\n\n concat!(\"Size of: \", stringify!(Color))\n\n );\n\n assert_eq!(\n\n ::std::mem::align_of::<Color>(),\n\n 1usize,\n\n concat!(\"Alignment of \", stringify!(Color))\n\n );\n\n assert_eq!(\n\n unsafe { &(*(::std::ptr::null::<Color>())).r as *const _ as usize },\n\n 0usize,\n\n concat!(\"Offset of field: \", stringify!(Color), \"::\", stringify!(r))\n\n );\n\n assert_eq!(\n\n unsafe { &(*(::std::ptr::null::<Color>())).g as *const _ as usize },\n\n 1usize,\n\n concat!(\"Offset of field: \", stringify!(Color), \"::\", stringify!(g))\n", "file_path": "dioteko-raylib-sys/src/bindings.rs", "rank": 9, "score": 38444.54320304184 }, { "content": "#[test]\n\nfn bindgen_test_layout_Image() {\n\n assert_eq!(\n\n ::std::mem::size_of::<Image>(),\n\n 24usize,\n\n concat!(\"Size of: \", stringify!(Image))\n\n );\n\n assert_eq!(\n\n ::std::mem::align_of::<Image>(),\n\n 8usize,\n\n concat!(\"Alignment of \", stringify!(Image))\n\n );\n\n assert_eq!(\n\n unsafe { &(*(::std::ptr::null::<Image>())).data as *const _ as usize },\n\n 0usize,\n\n concat!(\n\n \"Offset of field: \",\n\n stringify!(Image),\n\n \"::\",\n\n stringify!(data)\n\n )\n", "file_path": "dioteko-raylib-sys/src/bindings.rs", "rank": 10, "score": 38444.54320304184 }, { "content": "#[test]\n\nfn bindgen_test_layout_Sound() {\n\n assert_eq!(\n\n ::std::mem::size_of::<Sound>(),\n\n 32usize,\n\n concat!(\"Size of: \", stringify!(Sound))\n\n );\n\n assert_eq!(\n\n ::std::mem::align_of::<Sound>(),\n\n 8usize,\n\n concat!(\"Alignment of \", stringify!(Sound))\n\n );\n\n assert_eq!(\n\n unsafe { &(*(::std::ptr::null::<Sound>())).stream as *const _ as usize },\n\n 0usize,\n\n concat!(\n\n \"Offset of field: \",\n\n stringify!(Sound),\n\n \"::\",\n\n stringify!(stream)\n\n )\n", "file_path": "dioteko-raylib-sys/src/bindings.rs", "rank": 11, "score": 38444.54320304184 }, { "content": "#[test]\n\nfn bindgen_test_layout_Music() {\n\n assert_eq!(\n\n ::std::mem::size_of::<Music>(),\n\n 48usize,\n\n concat!(\"Size of: \", stringify!(Music))\n\n );\n\n assert_eq!(\n\n ::std::mem::align_of::<Music>(),\n\n 8usize,\n\n concat!(\"Alignment of \", stringify!(Music))\n\n );\n\n assert_eq!(\n\n unsafe { &(*(::std::ptr::null::<Music>())).stream as *const _ as usize },\n\n 0usize,\n\n concat!(\n\n \"Offset of field: \",\n\n stringify!(Music),\n\n \"::\",\n\n stringify!(stream)\n\n )\n", "file_path": "dioteko-raylib-sys/src/bindings.rs", "rank": 12, "score": 38444.54320304184 }, { "content": "#[test]\n\nfn bindgen_test_layout_Rectangle() {\n\n assert_eq!(\n\n ::std::mem::size_of::<Rectangle>(),\n\n 16usize,\n\n concat!(\"Size of: \", stringify!(Rectangle))\n\n );\n\n assert_eq!(\n\n ::std::mem::align_of::<Rectangle>(),\n\n 4usize,\n\n concat!(\"Alignment of \", stringify!(Rectangle))\n\n );\n\n assert_eq!(\n\n unsafe { &(*(::std::ptr::null::<Rectangle>())).x as *const _ as usize },\n\n 0usize,\n\n concat!(\n\n \"Offset of field: \",\n\n stringify!(Rectangle),\n\n \"::\",\n\n stringify!(x)\n\n )\n", "file_path": "dioteko-raylib-sys/src/bindings.rs", "rank": 13, "score": 38444.54320304184 }, { "content": "#[test]\n\nfn bindgen_test_layout___double2() {\n\n assert_eq!(\n\n ::std::mem::size_of::<__double2>(),\n\n 16usize,\n\n concat!(\"Size of: \", stringify!(__double2))\n\n );\n\n assert_eq!(\n\n ::std::mem::align_of::<__double2>(),\n\n 8usize,\n\n concat!(\"Alignment of \", stringify!(__double2))\n\n );\n\n assert_eq!(\n\n unsafe { &(*(::std::ptr::null::<__double2>())).__sinval as *const _ as usize },\n\n 0usize,\n\n concat!(\n\n \"Offset of field: \",\n\n stringify!(__double2),\n\n \"::\",\n\n stringify!(__sinval)\n\n )\n", "file_path": "dioteko-raylib-sys/src/bindings.rs", "rank": 14, "score": 38444.54320304184 }, { "content": "#[test]\n\nfn bindgen_test_layout_float3() {\n\n assert_eq!(\n\n ::std::mem::size_of::<float3>(),\n\n 12usize,\n\n concat!(\"Size of: \", stringify!(float3))\n\n );\n\n assert_eq!(\n\n ::std::mem::align_of::<float3>(),\n\n 4usize,\n\n concat!(\"Alignment of \", stringify!(float3))\n\n );\n\n assert_eq!(\n\n unsafe { &(*(::std::ptr::null::<float3>())).v as *const _ as usize },\n\n 0usize,\n\n concat!(\"Offset of field: \", stringify!(float3), \"::\", stringify!(v))\n\n );\n\n}\n\n#[repr(C)]\n\n#[derive(Debug, Copy, Clone)]\n\npub struct float16 {\n\n pub v: [f32; 16usize],\n\n}\n", "file_path": "dioteko-raylib-sys/src/bindings.rs", "rank": 15, "score": 38444.54320304184 }, { "content": "#[test]\n\nfn bindgen_test_layout_Transform() {\n\n assert_eq!(\n\n ::std::mem::size_of::<Transform>(),\n\n 40usize,\n\n concat!(\"Size of: \", stringify!(Transform))\n\n );\n\n assert_eq!(\n\n ::std::mem::align_of::<Transform>(),\n\n 4usize,\n\n concat!(\"Alignment of \", stringify!(Transform))\n\n );\n\n assert_eq!(\n\n unsafe { &(*(::std::ptr::null::<Transform>())).translation as *const _ as usize },\n\n 0usize,\n\n concat!(\n\n \"Offset of field: \",\n\n stringify!(Transform),\n\n \"::\",\n\n stringify!(translation)\n\n )\n", "file_path": "dioteko-raylib-sys/src/bindings.rs", "rank": 16, "score": 38444.54320304184 }, { "content": "#[test]\n\nfn bindgen_test_layout_Wave() {\n\n assert_eq!(\n\n ::std::mem::size_of::<Wave>(),\n\n 24usize,\n\n concat!(\"Size of: \", stringify!(Wave))\n\n );\n\n assert_eq!(\n\n ::std::mem::align_of::<Wave>(),\n\n 8usize,\n\n concat!(\"Alignment of \", stringify!(Wave))\n\n );\n\n assert_eq!(\n\n unsafe { &(*(::std::ptr::null::<Wave>())).frameCount as *const _ as usize },\n\n 0usize,\n\n concat!(\n\n \"Offset of field: \",\n\n stringify!(Wave),\n\n \"::\",\n\n stringify!(frameCount)\n\n )\n", "file_path": "dioteko-raylib-sys/src/bindings.rs", "rank": 17, "score": 38444.54320304184 }, { "content": "#[test]\n\nfn bindgen_test_layout_Vector4() {\n\n assert_eq!(\n\n ::std::mem::size_of::<Vector4>(),\n\n 16usize,\n\n concat!(\"Size of: \", stringify!(Vector4))\n\n );\n\n assert_eq!(\n\n ::std::mem::align_of::<Vector4>(),\n\n 4usize,\n\n concat!(\"Alignment of \", stringify!(Vector4))\n\n );\n\n assert_eq!(\n\n unsafe { &(*(::std::ptr::null::<Vector4>())).x as *const _ as usize },\n\n 0usize,\n\n concat!(\n\n \"Offset of field: \",\n\n stringify!(Vector4),\n\n \"::\",\n\n stringify!(x)\n\n )\n", "file_path": "dioteko-raylib-sys/src/bindings.rs", "rank": 18, "score": 38444.54320304184 }, { "content": "#[test]\n\nfn bindgen_test_layout_Mesh() {\n\n assert_eq!(\n\n ::std::mem::size_of::<Mesh>(),\n\n 112usize,\n\n concat!(\"Size of: \", stringify!(Mesh))\n\n );\n\n assert_eq!(\n\n ::std::mem::align_of::<Mesh>(),\n\n 8usize,\n\n concat!(\"Alignment of \", stringify!(Mesh))\n\n );\n\n assert_eq!(\n\n unsafe { &(*(::std::ptr::null::<Mesh>())).vertexCount as *const _ as usize },\n\n 0usize,\n\n concat!(\n\n \"Offset of field: \",\n\n stringify!(Mesh),\n\n \"::\",\n\n stringify!(vertexCount)\n\n )\n", "file_path": "dioteko-raylib-sys/src/bindings.rs", "rank": 19, "score": 38444.54320304184 }, { "content": "#[test]\n\nfn bindgen_test_layout___float2() {\n\n assert_eq!(\n\n ::std::mem::size_of::<__float2>(),\n\n 8usize,\n\n concat!(\"Size of: \", stringify!(__float2))\n\n );\n\n assert_eq!(\n\n ::std::mem::align_of::<__float2>(),\n\n 4usize,\n\n concat!(\"Alignment of \", stringify!(__float2))\n\n );\n\n assert_eq!(\n\n unsafe { &(*(::std::ptr::null::<__float2>())).__sinval as *const _ as usize },\n\n 0usize,\n\n concat!(\n\n \"Offset of field: \",\n\n stringify!(__float2),\n\n \"::\",\n\n stringify!(__sinval)\n\n )\n", "file_path": "dioteko-raylib-sys/src/bindings.rs", "rank": 20, "score": 38444.54320304184 }, { "content": "#[test]\n\nfn bindgen_test_layout_exception() {\n\n assert_eq!(\n\n ::std::mem::size_of::<exception>(),\n\n 40usize,\n\n concat!(\"Size of: \", stringify!(exception))\n\n );\n\n assert_eq!(\n\n ::std::mem::align_of::<exception>(),\n\n 8usize,\n\n concat!(\"Alignment of \", stringify!(exception))\n\n );\n\n assert_eq!(\n\n unsafe { &(*(::std::ptr::null::<exception>())).type_ as *const _ as usize },\n\n 0usize,\n\n concat!(\n\n \"Offset of field: \",\n\n stringify!(exception),\n\n \"::\",\n\n stringify!(type_)\n\n )\n", "file_path": "dioteko-raylib-sys/src/bindings.rs", "rank": 21, "score": 38444.54320304184 }, { "content": "#[test]\n\nfn bindgen_test_layout_Texture() {\n\n assert_eq!(\n\n ::std::mem::size_of::<Texture>(),\n\n 20usize,\n\n concat!(\"Size of: \", stringify!(Texture))\n\n );\n\n assert_eq!(\n\n ::std::mem::align_of::<Texture>(),\n\n 4usize,\n\n concat!(\"Alignment of \", stringify!(Texture))\n\n );\n\n assert_eq!(\n\n unsafe { &(*(::std::ptr::null::<Texture>())).id as *const _ as usize },\n\n 0usize,\n\n concat!(\n\n \"Offset of field: \",\n\n stringify!(Texture),\n\n \"::\",\n\n stringify!(id)\n\n )\n", "file_path": "dioteko-raylib-sys/src/bindings.rs", "rank": 22, "score": 38444.54320304184 }, { "content": "#[test]\n\nfn bindgen_test_layout_float16() {\n\n assert_eq!(\n\n ::std::mem::size_of::<float16>(),\n\n 64usize,\n\n concat!(\"Size of: \", stringify!(float16))\n\n );\n\n assert_eq!(\n\n ::std::mem::align_of::<float16>(),\n\n 4usize,\n\n concat!(\"Alignment of \", stringify!(float16))\n\n );\n\n assert_eq!(\n\n unsafe { &(*(::std::ptr::null::<float16>())).v as *const _ as usize },\n\n 0usize,\n\n concat!(\n\n \"Offset of field: \",\n\n stringify!(float16),\n\n \"::\",\n\n stringify!(v)\n\n )\n", "file_path": "dioteko-raylib-sys/src/bindings.rs", "rank": 23, "score": 38444.54320304184 }, { "content": "#[test]\n\nfn bindgen_test_layout_Font() {\n\n assert_eq!(\n\n ::std::mem::size_of::<Font>(),\n\n 48usize,\n\n concat!(\"Size of: \", stringify!(Font))\n\n );\n\n assert_eq!(\n\n ::std::mem::align_of::<Font>(),\n\n 8usize,\n\n concat!(\"Alignment of \", stringify!(Font))\n\n );\n\n assert_eq!(\n\n unsafe { &(*(::std::ptr::null::<Font>())).baseSize as *const _ as usize },\n\n 0usize,\n\n concat!(\n\n \"Offset of field: \",\n\n stringify!(Font),\n\n \"::\",\n\n stringify!(baseSize)\n\n )\n", "file_path": "dioteko-raylib-sys/src/bindings.rs", "rank": 24, "score": 38444.54320304184 }, { "content": "#[test]\n\nfn bindgen_test_layout_Vector2() {\n\n assert_eq!(\n\n ::std::mem::size_of::<Vector2>(),\n\n 8usize,\n\n concat!(\"Size of: \", stringify!(Vector2))\n\n );\n\n assert_eq!(\n\n ::std::mem::align_of::<Vector2>(),\n\n 4usize,\n\n concat!(\"Alignment of \", stringify!(Vector2))\n\n );\n\n assert_eq!(\n\n unsafe { &(*(::std::ptr::null::<Vector2>())).x as *const _ as usize },\n\n 0usize,\n\n concat!(\n\n \"Offset of field: \",\n\n stringify!(Vector2),\n\n \"::\",\n\n stringify!(x)\n\n )\n", "file_path": "dioteko-raylib-sys/src/bindings.rs", "rank": 25, "score": 38444.54320304184 }, { "content": "#[test]\n\nfn bindgen_test_layout_Vector3() {\n\n assert_eq!(\n\n ::std::mem::size_of::<Vector3>(),\n\n 12usize,\n\n concat!(\"Size of: \", stringify!(Vector3))\n\n );\n\n assert_eq!(\n\n ::std::mem::align_of::<Vector3>(),\n\n 4usize,\n\n concat!(\"Alignment of \", stringify!(Vector3))\n\n );\n\n assert_eq!(\n\n unsafe { &(*(::std::ptr::null::<Vector3>())).x as *const _ as usize },\n\n 0usize,\n\n concat!(\n\n \"Offset of field: \",\n\n stringify!(Vector3),\n\n \"::\",\n\n stringify!(x)\n\n )\n", "file_path": "dioteko-raylib-sys/src/bindings.rs", "rank": 26, "score": 38444.54320304184 }, { "content": "#[test]\n\nfn bindgen_test_layout_Ray() {\n\n assert_eq!(\n\n ::std::mem::size_of::<Ray>(),\n\n 24usize,\n\n concat!(\"Size of: \", stringify!(Ray))\n\n );\n\n assert_eq!(\n\n ::std::mem::align_of::<Ray>(),\n\n 4usize,\n\n concat!(\"Alignment of \", stringify!(Ray))\n\n );\n\n assert_eq!(\n\n unsafe { &(*(::std::ptr::null::<Ray>())).position as *const _ as usize },\n\n 0usize,\n\n concat!(\n\n \"Offset of field: \",\n\n stringify!(Ray),\n\n \"::\",\n\n stringify!(position)\n\n )\n", "file_path": "dioteko-raylib-sys/src/bindings.rs", "rank": 27, "score": 38444.54320304184 }, { "content": "#[test]\n\nfn bindgen_test_layout_Material() {\n\n assert_eq!(\n\n ::std::mem::size_of::<Material>(),\n\n 40usize,\n\n concat!(\"Size of: \", stringify!(Material))\n\n );\n\n assert_eq!(\n\n ::std::mem::align_of::<Material>(),\n\n 8usize,\n\n concat!(\"Alignment of \", stringify!(Material))\n\n );\n\n assert_eq!(\n\n unsafe { &(*(::std::ptr::null::<Material>())).shader as *const _ as usize },\n\n 0usize,\n\n concat!(\n\n \"Offset of field: \",\n\n stringify!(Material),\n\n \"::\",\n\n stringify!(shader)\n\n )\n", "file_path": "dioteko-raylib-sys/src/bindings.rs", "rank": 28, "score": 38444.54320304184 }, { "content": "#[test]\n\nfn bindgen_test_layout_GlyphInfo() {\n\n assert_eq!(\n\n ::std::mem::size_of::<GlyphInfo>(),\n\n 40usize,\n\n concat!(\"Size of: \", stringify!(GlyphInfo))\n\n );\n\n assert_eq!(\n\n ::std::mem::align_of::<GlyphInfo>(),\n\n 8usize,\n\n concat!(\"Alignment of \", stringify!(GlyphInfo))\n\n );\n\n assert_eq!(\n\n unsafe { &(*(::std::ptr::null::<GlyphInfo>())).value as *const _ as usize },\n\n 0usize,\n\n concat!(\n\n \"Offset of field: \",\n\n stringify!(GlyphInfo),\n\n \"::\",\n\n stringify!(value)\n\n )\n", "file_path": "dioteko-raylib-sys/src/bindings.rs", "rank": 29, "score": 37342.631033426704 }, { "content": "#[test]\n\nfn bindgen_test_layout_AudioStream() {\n\n assert_eq!(\n\n ::std::mem::size_of::<AudioStream>(),\n\n 24usize,\n\n concat!(\"Size of: \", stringify!(AudioStream))\n\n );\n\n assert_eq!(\n\n ::std::mem::align_of::<AudioStream>(),\n\n 8usize,\n\n concat!(\"Alignment of \", stringify!(AudioStream))\n\n );\n\n assert_eq!(\n\n unsafe { &(*(::std::ptr::null::<AudioStream>())).buffer as *const _ as usize },\n\n 0usize,\n\n concat!(\n\n \"Offset of field: \",\n\n stringify!(AudioStream),\n\n \"::\",\n\n stringify!(buffer)\n\n )\n", "file_path": "dioteko-raylib-sys/src/bindings.rs", "rank": 30, "score": 37342.631033426704 }, { "content": "#[test]\n\nfn bindgen_test_layout_RenderTexture() {\n\n assert_eq!(\n\n ::std::mem::size_of::<RenderTexture>(),\n\n 44usize,\n\n concat!(\"Size of: \", stringify!(RenderTexture))\n\n );\n\n assert_eq!(\n\n ::std::mem::align_of::<RenderTexture>(),\n\n 4usize,\n\n concat!(\"Alignment of \", stringify!(RenderTexture))\n\n );\n\n assert_eq!(\n\n unsafe { &(*(::std::ptr::null::<RenderTexture>())).id as *const _ as usize },\n\n 0usize,\n\n concat!(\n\n \"Offset of field: \",\n\n stringify!(RenderTexture),\n\n \"::\",\n\n stringify!(id)\n\n )\n", "file_path": "dioteko-raylib-sys/src/bindings.rs", "rank": 31, "score": 37342.631033426704 }, { "content": "#[test]\n\nfn bindgen_test_layout_RayCollision() {\n\n assert_eq!(\n\n ::std::mem::size_of::<RayCollision>(),\n\n 32usize,\n\n concat!(\"Size of: \", stringify!(RayCollision))\n\n );\n\n assert_eq!(\n\n ::std::mem::align_of::<RayCollision>(),\n\n 4usize,\n\n concat!(\"Alignment of \", stringify!(RayCollision))\n\n );\n\n assert_eq!(\n\n unsafe { &(*(::std::ptr::null::<RayCollision>())).hit as *const _ as usize },\n\n 0usize,\n\n concat!(\n\n \"Offset of field: \",\n\n stringify!(RayCollision),\n\n \"::\",\n\n stringify!(hit)\n\n )\n", "file_path": "dioteko-raylib-sys/src/bindings.rs", "rank": 32, "score": 37342.631033426704 }, { "content": "#[test]\n\nfn bindgen_test_layout_Camera2D() {\n\n assert_eq!(\n\n ::std::mem::size_of::<Camera2D>(),\n\n 24usize,\n\n concat!(\"Size of: \", stringify!(Camera2D))\n\n );\n\n assert_eq!(\n\n ::std::mem::align_of::<Camera2D>(),\n\n 4usize,\n\n concat!(\"Alignment of \", stringify!(Camera2D))\n\n );\n\n assert_eq!(\n\n unsafe { &(*(::std::ptr::null::<Camera2D>())).offset as *const _ as usize },\n\n 0usize,\n\n concat!(\n\n \"Offset of field: \",\n\n stringify!(Camera2D),\n\n \"::\",\n\n stringify!(offset)\n\n )\n", "file_path": "dioteko-raylib-sys/src/bindings.rs", "rank": 33, "score": 37342.631033426704 }, { "content": "#[test]\n\nfn bindgen_test_layout_ModelAnimation() {\n\n assert_eq!(\n\n ::std::mem::size_of::<ModelAnimation>(),\n\n 24usize,\n\n concat!(\"Size of: \", stringify!(ModelAnimation))\n\n );\n\n assert_eq!(\n\n ::std::mem::align_of::<ModelAnimation>(),\n\n 8usize,\n\n concat!(\"Alignment of \", stringify!(ModelAnimation))\n\n );\n\n assert_eq!(\n\n unsafe { &(*(::std::ptr::null::<ModelAnimation>())).boneCount as *const _ as usize },\n\n 0usize,\n\n concat!(\n\n \"Offset of field: \",\n\n stringify!(ModelAnimation),\n\n \"::\",\n\n stringify!(boneCount)\n\n )\n", "file_path": "dioteko-raylib-sys/src/bindings.rs", "rank": 34, "score": 37342.631033426704 }, { "content": "#[test]\n\nfn bindgen_test_layout_BoneInfo() {\n\n assert_eq!(\n\n ::std::mem::size_of::<BoneInfo>(),\n\n 36usize,\n\n concat!(\"Size of: \", stringify!(BoneInfo))\n\n );\n\n assert_eq!(\n\n ::std::mem::align_of::<BoneInfo>(),\n\n 4usize,\n\n concat!(\"Alignment of \", stringify!(BoneInfo))\n\n );\n\n assert_eq!(\n\n unsafe { &(*(::std::ptr::null::<BoneInfo>())).name as *const _ as usize },\n\n 0usize,\n\n concat!(\n\n \"Offset of field: \",\n\n stringify!(BoneInfo),\n\n \"::\",\n\n stringify!(name)\n\n )\n", "file_path": "dioteko-raylib-sys/src/bindings.rs", "rank": 35, "score": 37342.631033426704 }, { "content": "#[test]\n\nfn bindgen_test_layout_Camera3D() {\n\n assert_eq!(\n\n ::std::mem::size_of::<Camera3D>(),\n\n 44usize,\n\n concat!(\"Size of: \", stringify!(Camera3D))\n\n );\n\n assert_eq!(\n\n ::std::mem::align_of::<Camera3D>(),\n\n 4usize,\n\n concat!(\"Alignment of \", stringify!(Camera3D))\n\n );\n\n assert_eq!(\n\n unsafe { &(*(::std::ptr::null::<Camera3D>())).position as *const _ as usize },\n\n 0usize,\n\n concat!(\n\n \"Offset of field: \",\n\n stringify!(Camera3D),\n\n \"::\",\n\n stringify!(position)\n\n )\n", "file_path": "dioteko-raylib-sys/src/bindings.rs", "rank": 36, "score": 37342.631033426704 }, { "content": "#[test]\n\nfn bindgen_test_layout_MaterialMap() {\n\n assert_eq!(\n\n ::std::mem::size_of::<MaterialMap>(),\n\n 28usize,\n\n concat!(\"Size of: \", stringify!(MaterialMap))\n\n );\n\n assert_eq!(\n\n ::std::mem::align_of::<MaterialMap>(),\n\n 4usize,\n\n concat!(\"Alignment of \", stringify!(MaterialMap))\n\n );\n\n assert_eq!(\n\n unsafe { &(*(::std::ptr::null::<MaterialMap>())).texture as *const _ as usize },\n\n 0usize,\n\n concat!(\n\n \"Offset of field: \",\n\n stringify!(MaterialMap),\n\n \"::\",\n\n stringify!(texture)\n\n )\n", "file_path": "dioteko-raylib-sys/src/bindings.rs", "rank": 37, "score": 37342.631033426704 }, { "content": "#[test]\n\nfn bindgen_test_layout_BoundingBox() {\n\n assert_eq!(\n\n ::std::mem::size_of::<BoundingBox>(),\n\n 24usize,\n\n concat!(\"Size of: \", stringify!(BoundingBox))\n\n );\n\n assert_eq!(\n\n ::std::mem::align_of::<BoundingBox>(),\n\n 4usize,\n\n concat!(\"Alignment of \", stringify!(BoundingBox))\n\n );\n\n assert_eq!(\n\n unsafe { &(*(::std::ptr::null::<BoundingBox>())).min as *const _ as usize },\n\n 0usize,\n\n concat!(\n\n \"Offset of field: \",\n\n stringify!(BoundingBox),\n\n \"::\",\n\n stringify!(min)\n\n )\n", "file_path": "dioteko-raylib-sys/src/bindings.rs", "rank": 38, "score": 37342.631033426704 }, { "content": "fn main() -> std::io::Result<()> {\n\n // Build raylib with cmake\n\n let dst = cmake::Config::new(\"./lib/raylib\")\n\n .very_verbose(true)\n\n .build();\n\n\n\n // Use prebuilt bindings.rs\n\n #[cfg(target_os = \"windows\")]\n\n fs::copy(\"src/bindings/windows_bindings.rs\", \"src/bindings.rs\")?;\n\n #[cfg(target_os = \"macos\")]\n\n fs::copy(\"src/bindings/macos_bindings.rs\", \"src/bindings.rs\")?;\n\n\n\n #[cfg(target_os = \"windows\")]\n\n println!(\"cargo:rustc-link-search=native={}\\\\lib\", dst.display());\n\n #[cfg(not(target_os = \"windows\"))]\n\n println!(\"cargo:rustc-link-search=native={}/lib\", dst.display());\n\n\n\n println!(\"cargo:rustc-link-lib=static=raylib\");\n\n\n\n #[cfg(target_os = \"windows\")]\n", "file_path": "dioteko-raylib-sys/build.rs", "rank": 39, "score": 37258.82506572956 }, { "content": "#[test]\n\nfn bindgen_test_layout_float3() {\n\n assert_eq!(\n\n ::std::mem::size_of::<float3>(),\n\n 12usize,\n\n concat!(\"Size of: \", stringify!(float3))\n\n );\n\n assert_eq!(\n\n ::std::mem::align_of::<float3>(),\n\n 4usize,\n\n concat!(\"Alignment of \", stringify!(float3))\n\n );\n\n assert_eq!(\n\n unsafe { &(*(::std::ptr::null::<float3>())).v as *const _ as usize },\n\n 0usize,\n\n concat!(\"Offset of field: \", stringify!(float3), \"::\", stringify!(v))\n\n );\n\n}\n\n#[repr(C)]\n\n#[derive(Debug, Copy, Clone)]\n\npub struct float16 {\n\n pub v: [f32; 16usize],\n\n}\n", "file_path": "dioteko-raylib-sys/src/bindings/macos_bindings.rs", "rank": 40, "score": 36315.606019205734 }, { "content": "#[test]\n\nfn bindgen_test_layout_Color() {\n\n assert_eq!(\n\n ::std::mem::size_of::<Color>(),\n\n 4usize,\n\n concat!(\"Size of: \", stringify!(Color))\n\n );\n\n assert_eq!(\n\n ::std::mem::align_of::<Color>(),\n\n 1usize,\n\n concat!(\"Alignment of \", stringify!(Color))\n\n );\n\n assert_eq!(\n\n unsafe { &(*(::std::ptr::null::<Color>())).r as *const _ as usize },\n\n 0usize,\n\n concat!(\"Offset of field: \", stringify!(Color), \"::\", stringify!(r))\n\n );\n\n assert_eq!(\n\n unsafe { &(*(::std::ptr::null::<Color>())).g as *const _ as usize },\n\n 1usize,\n\n concat!(\"Offset of field: \", stringify!(Color), \"::\", stringify!(g))\n", "file_path": "dioteko-raylib-sys/src/bindings/windows_bindings.rs", "rank": 41, "score": 36315.606019205734 }, { "content": "#[test]\n\nfn bindgen_test_layout_Rectangle() {\n\n assert_eq!(\n\n ::std::mem::size_of::<Rectangle>(),\n\n 16usize,\n\n concat!(\"Size of: \", stringify!(Rectangle))\n\n );\n\n assert_eq!(\n\n ::std::mem::align_of::<Rectangle>(),\n\n 4usize,\n\n concat!(\"Alignment of \", stringify!(Rectangle))\n\n );\n\n assert_eq!(\n\n unsafe { &(*(::std::ptr::null::<Rectangle>())).x as *const _ as usize },\n\n 0usize,\n\n concat!(\n\n \"Offset of field: \",\n\n stringify!(Rectangle),\n\n \"::\",\n\n stringify!(x)\n\n )\n", "file_path": "dioteko-raylib-sys/src/bindings/windows_bindings.rs", "rank": 42, "score": 36315.606019205734 }, { "content": "#[test]\n\nfn bindgen_test_layout_Transform() {\n\n assert_eq!(\n\n ::std::mem::size_of::<Transform>(),\n\n 40usize,\n\n concat!(\"Size of: \", stringify!(Transform))\n\n );\n\n assert_eq!(\n\n ::std::mem::align_of::<Transform>(),\n\n 4usize,\n\n concat!(\"Alignment of \", stringify!(Transform))\n\n );\n\n assert_eq!(\n\n unsafe { &(*(::std::ptr::null::<Transform>())).translation as *const _ as usize },\n\n 0usize,\n\n concat!(\n\n \"Offset of field: \",\n\n stringify!(Transform),\n\n \"::\",\n\n stringify!(translation)\n\n )\n", "file_path": "dioteko-raylib-sys/src/bindings/macos_bindings.rs", "rank": 43, "score": 36315.606019205734 }, { "content": "#[test]\n\nfn bindgen_test_layout_Texture() {\n\n assert_eq!(\n\n ::std::mem::size_of::<Texture>(),\n\n 20usize,\n\n concat!(\"Size of: \", stringify!(Texture))\n\n );\n\n assert_eq!(\n\n ::std::mem::align_of::<Texture>(),\n\n 4usize,\n\n concat!(\"Alignment of \", stringify!(Texture))\n\n );\n\n assert_eq!(\n\n unsafe { &(*(::std::ptr::null::<Texture>())).id as *const _ as usize },\n\n 0usize,\n\n concat!(\n\n \"Offset of field: \",\n\n stringify!(Texture),\n\n \"::\",\n\n stringify!(id)\n\n )\n", "file_path": "dioteko-raylib-sys/src/bindings/macos_bindings.rs", "rank": 44, "score": 36315.606019205734 }, { "content": "#[test]\n\nfn bindgen_test_layout_Ray() {\n\n assert_eq!(\n\n ::std::mem::size_of::<Ray>(),\n\n 24usize,\n\n concat!(\"Size of: \", stringify!(Ray))\n\n );\n\n assert_eq!(\n\n ::std::mem::align_of::<Ray>(),\n\n 4usize,\n\n concat!(\"Alignment of \", stringify!(Ray))\n\n );\n\n assert_eq!(\n\n unsafe { &(*(::std::ptr::null::<Ray>())).position as *const _ as usize },\n\n 0usize,\n\n concat!(\n\n \"Offset of field: \",\n\n stringify!(Ray),\n\n \"::\",\n\n stringify!(position)\n\n )\n", "file_path": "dioteko-raylib-sys/src/bindings/macos_bindings.rs", "rank": 45, "score": 36315.606019205734 }, { "content": "#[test]\n\nfn bindgen_test_layout_Mesh() {\n\n assert_eq!(\n\n ::std::mem::size_of::<Mesh>(),\n\n 112usize,\n\n concat!(\"Size of: \", stringify!(Mesh))\n\n );\n\n assert_eq!(\n\n ::std::mem::align_of::<Mesh>(),\n\n 8usize,\n\n concat!(\"Alignment of \", stringify!(Mesh))\n\n );\n\n assert_eq!(\n\n unsafe { &(*(::std::ptr::null::<Mesh>())).vertexCount as *const _ as usize },\n\n 0usize,\n\n concat!(\n\n \"Offset of field: \",\n\n stringify!(Mesh),\n\n \"::\",\n\n stringify!(vertexCount)\n\n )\n", "file_path": "dioteko-raylib-sys/src/bindings/windows_bindings.rs", "rank": 46, "score": 36315.606019205734 }, { "content": "#[test]\n\nfn bindgen_test_layout_Wave() {\n\n assert_eq!(\n\n ::std::mem::size_of::<Wave>(),\n\n 24usize,\n\n concat!(\"Size of: \", stringify!(Wave))\n\n );\n\n assert_eq!(\n\n ::std::mem::align_of::<Wave>(),\n\n 8usize,\n\n concat!(\"Alignment of \", stringify!(Wave))\n\n );\n\n assert_eq!(\n\n unsafe { &(*(::std::ptr::null::<Wave>())).frameCount as *const _ as usize },\n\n 0usize,\n\n concat!(\n\n \"Offset of field: \",\n\n stringify!(Wave),\n\n \"::\",\n\n stringify!(frameCount)\n\n )\n", "file_path": "dioteko-raylib-sys/src/bindings/macos_bindings.rs", "rank": 47, "score": 36315.606019205734 }, { "content": "#[test]\n\nfn bindgen_test_layout_exception() {\n\n assert_eq!(\n\n ::std::mem::size_of::<exception>(),\n\n 40usize,\n\n concat!(\"Size of: \", stringify!(exception))\n\n );\n\n assert_eq!(\n\n ::std::mem::align_of::<exception>(),\n\n 8usize,\n\n concat!(\"Alignment of \", stringify!(exception))\n\n );\n\n assert_eq!(\n\n unsafe { &(*(::std::ptr::null::<exception>())).type_ as *const _ as usize },\n\n 0usize,\n\n concat!(\n\n \"Offset of field: \",\n\n stringify!(exception),\n\n \"::\",\n\n stringify!(type_)\n\n )\n", "file_path": "dioteko-raylib-sys/src/bindings/macos_bindings.rs", "rank": 48, "score": 36315.606019205734 }, { "content": "#[test]\n\nfn bindgen_test_layout_Sound() {\n\n assert_eq!(\n\n ::std::mem::size_of::<Sound>(),\n\n 32usize,\n\n concat!(\"Size of: \", stringify!(Sound))\n\n );\n\n assert_eq!(\n\n ::std::mem::align_of::<Sound>(),\n\n 8usize,\n\n concat!(\"Alignment of \", stringify!(Sound))\n\n );\n\n assert_eq!(\n\n unsafe { &(*(::std::ptr::null::<Sound>())).stream as *const _ as usize },\n\n 0usize,\n\n concat!(\n\n \"Offset of field: \",\n\n stringify!(Sound),\n\n \"::\",\n\n stringify!(stream)\n\n )\n", "file_path": "dioteko-raylib-sys/src/bindings/macos_bindings.rs", "rank": 49, "score": 36315.606019205734 }, { "content": "#[test]\n\nfn bindgen_test_layout_Material() {\n\n assert_eq!(\n\n ::std::mem::size_of::<Material>(),\n\n 40usize,\n\n concat!(\"Size of: \", stringify!(Material))\n\n );\n\n assert_eq!(\n\n ::std::mem::align_of::<Material>(),\n\n 8usize,\n\n concat!(\"Alignment of \", stringify!(Material))\n\n );\n\n assert_eq!(\n\n unsafe { &(*(::std::ptr::null::<Material>())).shader as *const _ as usize },\n\n 0usize,\n\n concat!(\n\n \"Offset of field: \",\n\n stringify!(Material),\n\n \"::\",\n\n stringify!(shader)\n\n )\n", "file_path": "dioteko-raylib-sys/src/bindings/windows_bindings.rs", "rank": 50, "score": 36315.606019205734 }, { "content": "#[test]\n\nfn bindgen_test_layout_Music() {\n\n assert_eq!(\n\n ::std::mem::size_of::<Music>(),\n\n 48usize,\n\n concat!(\"Size of: \", stringify!(Music))\n\n );\n\n assert_eq!(\n\n ::std::mem::align_of::<Music>(),\n\n 8usize,\n\n concat!(\"Alignment of \", stringify!(Music))\n\n );\n\n assert_eq!(\n\n unsafe { &(*(::std::ptr::null::<Music>())).stream as *const _ as usize },\n\n 0usize,\n\n concat!(\n\n \"Offset of field: \",\n\n stringify!(Music),\n\n \"::\",\n\n stringify!(stream)\n\n )\n", "file_path": "dioteko-raylib-sys/src/bindings/macos_bindings.rs", "rank": 51, "score": 36315.606019205734 }, { "content": "#[test]\n\nfn bindgen_test_layout_Font() {\n\n assert_eq!(\n\n ::std::mem::size_of::<Font>(),\n\n 48usize,\n\n concat!(\"Size of: \", stringify!(Font))\n\n );\n\n assert_eq!(\n\n ::std::mem::align_of::<Font>(),\n\n 8usize,\n\n concat!(\"Alignment of \", stringify!(Font))\n\n );\n\n assert_eq!(\n\n unsafe { &(*(::std::ptr::null::<Font>())).baseSize as *const _ as usize },\n\n 0usize,\n\n concat!(\n\n \"Offset of field: \",\n\n stringify!(Font),\n\n \"::\",\n\n stringify!(baseSize)\n\n )\n", "file_path": "dioteko-raylib-sys/src/bindings/windows_bindings.rs", "rank": 52, "score": 36315.606019205734 }, { "content": "#[test]\n\nfn bindgen_test_layout_Mesh() {\n\n assert_eq!(\n\n ::std::mem::size_of::<Mesh>(),\n\n 112usize,\n\n concat!(\"Size of: \", stringify!(Mesh))\n\n );\n\n assert_eq!(\n\n ::std::mem::align_of::<Mesh>(),\n\n 8usize,\n\n concat!(\"Alignment of \", stringify!(Mesh))\n\n );\n\n assert_eq!(\n\n unsafe { &(*(::std::ptr::null::<Mesh>())).vertexCount as *const _ as usize },\n\n 0usize,\n\n concat!(\n\n \"Offset of field: \",\n\n stringify!(Mesh),\n\n \"::\",\n\n stringify!(vertexCount)\n\n )\n", "file_path": "dioteko-raylib-sys/src/bindings/macos_bindings.rs", "rank": 53, "score": 36315.606019205734 }, { "content": "#[test]\n\nfn bindgen_test_layout_Image() {\n\n assert_eq!(\n\n ::std::mem::size_of::<Image>(),\n\n 24usize,\n\n concat!(\"Size of: \", stringify!(Image))\n\n );\n\n assert_eq!(\n\n ::std::mem::align_of::<Image>(),\n\n 8usize,\n\n concat!(\"Alignment of \", stringify!(Image))\n\n );\n\n assert_eq!(\n\n unsafe { &(*(::std::ptr::null::<Image>())).data as *const _ as usize },\n\n 0usize,\n\n concat!(\n\n \"Offset of field: \",\n\n stringify!(Image),\n\n \"::\",\n\n stringify!(data)\n\n )\n", "file_path": "dioteko-raylib-sys/src/bindings/macos_bindings.rs", "rank": 54, "score": 36315.606019205734 }, { "content": "#[test]\n\nfn bindgen_test_layout_Model() {\n\n assert_eq!(\n\n ::std::mem::size_of::<Model>(),\n\n 120usize,\n\n concat!(\"Size of: \", stringify!(Model))\n\n );\n\n assert_eq!(\n\n ::std::mem::align_of::<Model>(),\n\n 8usize,\n\n concat!(\"Alignment of \", stringify!(Model))\n\n );\n\n assert_eq!(\n\n unsafe { &(*(::std::ptr::null::<Model>())).transform as *const _ as usize },\n\n 0usize,\n\n concat!(\n\n \"Offset of field: \",\n\n stringify!(Model),\n\n \"::\",\n\n stringify!(transform)\n\n )\n", "file_path": "dioteko-raylib-sys/src/bindings/macos_bindings.rs", "rank": 55, "score": 36315.606019205734 }, { "content": "#[test]\n\nfn bindgen_test_layout___double2() {\n\n assert_eq!(\n\n ::std::mem::size_of::<__double2>(),\n\n 16usize,\n\n concat!(\"Size of: \", stringify!(__double2))\n\n );\n\n assert_eq!(\n\n ::std::mem::align_of::<__double2>(),\n\n 8usize,\n\n concat!(\"Alignment of \", stringify!(__double2))\n\n );\n\n assert_eq!(\n\n unsafe { &(*(::std::ptr::null::<__double2>())).__sinval as *const _ as usize },\n\n 0usize,\n\n concat!(\n\n \"Offset of field: \",\n\n stringify!(__double2),\n\n \"::\",\n\n stringify!(__sinval)\n\n )\n", "file_path": "dioteko-raylib-sys/src/bindings/macos_bindings.rs", "rank": 56, "score": 36315.606019205734 }, { "content": "#[test]\n\nfn bindgen_test_layout_Color() {\n\n assert_eq!(\n\n ::std::mem::size_of::<Color>(),\n\n 4usize,\n\n concat!(\"Size of: \", stringify!(Color))\n\n );\n\n assert_eq!(\n\n ::std::mem::align_of::<Color>(),\n\n 1usize,\n\n concat!(\"Alignment of \", stringify!(Color))\n\n );\n\n assert_eq!(\n\n unsafe { &(*(::std::ptr::null::<Color>())).r as *const _ as usize },\n\n 0usize,\n\n concat!(\"Offset of field: \", stringify!(Color), \"::\", stringify!(r))\n\n );\n\n assert_eq!(\n\n unsafe { &(*(::std::ptr::null::<Color>())).g as *const _ as usize },\n\n 1usize,\n\n concat!(\"Offset of field: \", stringify!(Color), \"::\", stringify!(g))\n", "file_path": "dioteko-raylib-sys/src/bindings/macos_bindings.rs", "rank": 57, "score": 36315.606019205734 }, { "content": "#[test]\n\nfn bindgen_test_layout_Vector2() {\n\n assert_eq!(\n\n ::std::mem::size_of::<Vector2>(),\n\n 8usize,\n\n concat!(\"Size of: \", stringify!(Vector2))\n\n );\n\n assert_eq!(\n\n ::std::mem::align_of::<Vector2>(),\n\n 4usize,\n\n concat!(\"Alignment of \", stringify!(Vector2))\n\n );\n\n assert_eq!(\n\n unsafe { &(*(::std::ptr::null::<Vector2>())).x as *const _ as usize },\n\n 0usize,\n\n concat!(\n\n \"Offset of field: \",\n\n stringify!(Vector2),\n\n \"::\",\n\n stringify!(x)\n\n )\n", "file_path": "dioteko-raylib-sys/src/bindings/windows_bindings.rs", "rank": 58, "score": 36315.606019205734 }, { "content": "#[test]\n\nfn bindgen_test_layout_Vector4() {\n\n assert_eq!(\n\n ::std::mem::size_of::<Vector4>(),\n\n 16usize,\n\n concat!(\"Size of: \", stringify!(Vector4))\n\n );\n\n assert_eq!(\n\n ::std::mem::align_of::<Vector4>(),\n\n 4usize,\n\n concat!(\"Alignment of \", stringify!(Vector4))\n\n );\n\n assert_eq!(\n\n unsafe { &(*(::std::ptr::null::<Vector4>())).x as *const _ as usize },\n\n 0usize,\n\n concat!(\n\n \"Offset of field: \",\n\n stringify!(Vector4),\n\n \"::\",\n\n stringify!(x)\n\n )\n", "file_path": "dioteko-raylib-sys/src/bindings/macos_bindings.rs", "rank": 59, "score": 36315.606019205734 }, { "content": "#[test]\n\nfn bindgen_test_layout__Mbstatet() {\n\n assert_eq!(\n\n ::std::mem::size_of::<_Mbstatet>(),\n\n 8usize,\n\n concat!(\"Size of: \", stringify!(_Mbstatet))\n\n );\n\n assert_eq!(\n\n ::std::mem::align_of::<_Mbstatet>(),\n\n 4usize,\n\n concat!(\"Alignment of \", stringify!(_Mbstatet))\n\n );\n\n assert_eq!(\n\n unsafe { &(*(::std::ptr::null::<_Mbstatet>()))._Wchar as *const _ as usize },\n\n 0usize,\n\n concat!(\n\n \"Offset of field: \",\n\n stringify!(_Mbstatet),\n\n \"::\",\n\n stringify!(_Wchar)\n\n )\n", "file_path": "dioteko-raylib-sys/src/bindings/windows_bindings.rs", "rank": 60, "score": 36315.606019205734 }, { "content": "#[test]\n\nfn bindgen_test_layout_Shader() {\n\n assert_eq!(\n\n ::std::mem::size_of::<Shader>(),\n\n 16usize,\n\n concat!(\"Size of: \", stringify!(Shader))\n\n );\n\n assert_eq!(\n\n ::std::mem::align_of::<Shader>(),\n\n 8usize,\n\n concat!(\"Alignment of \", stringify!(Shader))\n\n );\n\n assert_eq!(\n\n unsafe { &(*(::std::ptr::null::<Shader>())).id as *const _ as usize },\n\n 0usize,\n\n concat!(\n\n \"Offset of field: \",\n\n stringify!(Shader),\n\n \"::\",\n\n stringify!(id)\n\n )\n", "file_path": "dioteko-raylib-sys/src/bindings/windows_bindings.rs", "rank": 61, "score": 36315.606019205734 }, { "content": "#[test]\n\nfn bindgen_test_layout___float2() {\n\n assert_eq!(\n\n ::std::mem::size_of::<__float2>(),\n\n 8usize,\n\n concat!(\"Size of: \", stringify!(__float2))\n\n );\n\n assert_eq!(\n\n ::std::mem::align_of::<__float2>(),\n\n 4usize,\n\n concat!(\"Alignment of \", stringify!(__float2))\n\n );\n\n assert_eq!(\n\n unsafe { &(*(::std::ptr::null::<__float2>())).__sinval as *const _ as usize },\n\n 0usize,\n\n concat!(\n\n \"Offset of field: \",\n\n stringify!(__float2),\n\n \"::\",\n\n stringify!(__sinval)\n\n )\n", "file_path": "dioteko-raylib-sys/src/bindings/macos_bindings.rs", "rank": 62, "score": 36315.606019205734 }, { "content": "#[test]\n\nfn bindgen_test_layout_Matrix() {\n\n assert_eq!(\n\n ::std::mem::size_of::<Matrix>(),\n\n 64usize,\n\n concat!(\"Size of: \", stringify!(Matrix))\n\n );\n\n assert_eq!(\n\n ::std::mem::align_of::<Matrix>(),\n\n 4usize,\n\n concat!(\"Alignment of \", stringify!(Matrix))\n\n );\n\n assert_eq!(\n\n unsafe { &(*(::std::ptr::null::<Matrix>())).m0 as *const _ as usize },\n\n 0usize,\n\n concat!(\n\n \"Offset of field: \",\n\n stringify!(Matrix),\n\n \"::\",\n\n stringify!(m0)\n\n )\n", "file_path": "dioteko-raylib-sys/src/bindings/macos_bindings.rs", "rank": 63, "score": 36315.606019205734 }, { "content": "#[test]\n\nfn bindgen_test_layout_Matrix() {\n\n assert_eq!(\n\n ::std::mem::size_of::<Matrix>(),\n\n 64usize,\n\n concat!(\"Size of: \", stringify!(Matrix))\n\n );\n\n assert_eq!(\n\n ::std::mem::align_of::<Matrix>(),\n\n 4usize,\n\n concat!(\"Alignment of \", stringify!(Matrix))\n\n );\n\n assert_eq!(\n\n unsafe { &(*(::std::ptr::null::<Matrix>())).m0 as *const _ as usize },\n\n 0usize,\n\n concat!(\n\n \"Offset of field: \",\n\n stringify!(Matrix),\n\n \"::\",\n\n stringify!(m0)\n\n )\n", "file_path": "dioteko-raylib-sys/src/bindings/windows_bindings.rs", "rank": 64, "score": 36315.606019205734 }, { "content": "#[test]\n\nfn bindgen_test_layout_NPatchInfo() {\n\n assert_eq!(\n\n ::std::mem::size_of::<NPatchInfo>(),\n\n 36usize,\n\n concat!(\"Size of: \", stringify!(NPatchInfo))\n\n );\n\n assert_eq!(\n\n ::std::mem::align_of::<NPatchInfo>(),\n\n 4usize,\n\n concat!(\"Alignment of \", stringify!(NPatchInfo))\n\n );\n\n assert_eq!(\n\n unsafe { &(*(::std::ptr::null::<NPatchInfo>())).source as *const _ as usize },\n\n 0usize,\n\n concat!(\n\n \"Offset of field: \",\n\n stringify!(NPatchInfo),\n\n \"::\",\n\n stringify!(source)\n\n )\n", "file_path": "dioteko-raylib-sys/src/bindings.rs", "rank": 65, "score": 36315.606019205734 }, { "content": "#[test]\n\nfn bindgen_test_layout_Vector2() {\n\n assert_eq!(\n\n ::std::mem::size_of::<Vector2>(),\n\n 8usize,\n\n concat!(\"Size of: \", stringify!(Vector2))\n\n );\n\n assert_eq!(\n\n ::std::mem::align_of::<Vector2>(),\n\n 4usize,\n\n concat!(\"Alignment of \", stringify!(Vector2))\n\n );\n\n assert_eq!(\n\n unsafe { &(*(::std::ptr::null::<Vector2>())).x as *const _ as usize },\n\n 0usize,\n\n concat!(\n\n \"Offset of field: \",\n\n stringify!(Vector2),\n\n \"::\",\n\n stringify!(x)\n\n )\n", "file_path": "dioteko-raylib-sys/src/bindings/macos_bindings.rs", "rank": 66, "score": 36315.606019205734 }, { "content": "#[test]\n\nfn bindgen_test_layout_Rectangle() {\n\n assert_eq!(\n\n ::std::mem::size_of::<Rectangle>(),\n\n 16usize,\n\n concat!(\"Size of: \", stringify!(Rectangle))\n\n );\n\n assert_eq!(\n\n ::std::mem::align_of::<Rectangle>(),\n\n 4usize,\n\n concat!(\"Alignment of \", stringify!(Rectangle))\n\n );\n\n assert_eq!(\n\n unsafe { &(*(::std::ptr::null::<Rectangle>())).x as *const _ as usize },\n\n 0usize,\n\n concat!(\n\n \"Offset of field: \",\n\n stringify!(Rectangle),\n\n \"::\",\n\n stringify!(x)\n\n )\n", "file_path": "dioteko-raylib-sys/src/bindings/macos_bindings.rs", "rank": 67, "score": 36315.606019205734 }, { "content": "#[test]\n\nfn bindgen_test_layout_float16() {\n\n assert_eq!(\n\n ::std::mem::size_of::<float16>(),\n\n 64usize,\n\n concat!(\"Size of: \", stringify!(float16))\n\n );\n\n assert_eq!(\n\n ::std::mem::align_of::<float16>(),\n\n 4usize,\n\n concat!(\"Alignment of \", stringify!(float16))\n\n );\n\n assert_eq!(\n\n unsafe { &(*(::std::ptr::null::<float16>())).v as *const _ as usize },\n\n 0usize,\n\n concat!(\n\n \"Offset of field: \",\n\n stringify!(float16),\n\n \"::\",\n\n stringify!(v)\n\n )\n", "file_path": "dioteko-raylib-sys/src/bindings/macos_bindings.rs", "rank": 68, "score": 36315.606019205734 }, { "content": "#[test]\n\nfn bindgen_test_layout_Material() {\n\n assert_eq!(\n\n ::std::mem::size_of::<Material>(),\n\n 40usize,\n\n concat!(\"Size of: \", stringify!(Material))\n\n );\n\n assert_eq!(\n\n ::std::mem::align_of::<Material>(),\n\n 8usize,\n\n concat!(\"Alignment of \", stringify!(Material))\n\n );\n\n assert_eq!(\n\n unsafe { &(*(::std::ptr::null::<Material>())).shader as *const _ as usize },\n\n 0usize,\n\n concat!(\n\n \"Offset of field: \",\n\n stringify!(Material),\n\n \"::\",\n\n stringify!(shader)\n\n )\n", "file_path": "dioteko-raylib-sys/src/bindings/macos_bindings.rs", "rank": 69, "score": 36315.606019205734 }, { "content": "#[test]\n\nfn bindgen_test_layout_VrStereoConfig() {\n\n assert_eq!(\n\n ::std::mem::size_of::<VrStereoConfig>(),\n\n 304usize,\n\n concat!(\"Size of: \", stringify!(VrStereoConfig))\n\n );\n\n assert_eq!(\n\n ::std::mem::align_of::<VrStereoConfig>(),\n\n 4usize,\n\n concat!(\"Alignment of \", stringify!(VrStereoConfig))\n\n );\n\n assert_eq!(\n\n unsafe { &(*(::std::ptr::null::<VrStereoConfig>())).projection as *const _ as usize },\n\n 0usize,\n\n concat!(\n\n \"Offset of field: \",\n\n stringify!(VrStereoConfig),\n\n \"::\",\n\n stringify!(projection)\n\n )\n", "file_path": "dioteko-raylib-sys/src/bindings.rs", "rank": 70, "score": 36315.606019205734 }, { "content": "#[test]\n\nfn bindgen_test_layout_Vector3() {\n\n assert_eq!(\n\n ::std::mem::size_of::<Vector3>(),\n\n 12usize,\n\n concat!(\"Size of: \", stringify!(Vector3))\n\n );\n\n assert_eq!(\n\n ::std::mem::align_of::<Vector3>(),\n\n 4usize,\n\n concat!(\"Alignment of \", stringify!(Vector3))\n\n );\n\n assert_eq!(\n\n unsafe { &(*(::std::ptr::null::<Vector3>())).x as *const _ as usize },\n\n 0usize,\n\n concat!(\n\n \"Offset of field: \",\n\n stringify!(Vector3),\n\n \"::\",\n\n stringify!(x)\n\n )\n", "file_path": "dioteko-raylib-sys/src/bindings/windows_bindings.rs", "rank": 71, "score": 36315.606019205734 }, { "content": "#[test]\n\nfn bindgen_test_layout_Font() {\n\n assert_eq!(\n\n ::std::mem::size_of::<Font>(),\n\n 48usize,\n\n concat!(\"Size of: \", stringify!(Font))\n\n );\n\n assert_eq!(\n\n ::std::mem::align_of::<Font>(),\n\n 8usize,\n\n concat!(\"Alignment of \", stringify!(Font))\n\n );\n\n assert_eq!(\n\n unsafe { &(*(::std::ptr::null::<Font>())).baseSize as *const _ as usize },\n\n 0usize,\n\n concat!(\n\n \"Offset of field: \",\n\n stringify!(Font),\n\n \"::\",\n\n stringify!(baseSize)\n\n )\n", "file_path": "dioteko-raylib-sys/src/bindings/macos_bindings.rs", "rank": 72, "score": 36315.606019205734 }, { "content": "#[test]\n\nfn bindgen_test_layout__complex() {\n\n assert_eq!(\n\n ::std::mem::size_of::<_complex>(),\n\n 16usize,\n\n concat!(\"Size of: \", stringify!(_complex))\n\n );\n\n assert_eq!(\n\n ::std::mem::align_of::<_complex>(),\n\n 8usize,\n\n concat!(\"Alignment of \", stringify!(_complex))\n\n );\n\n assert_eq!(\n\n unsafe { &(*(::std::ptr::null::<_complex>())).x as *const _ as usize },\n\n 0usize,\n\n concat!(\n\n \"Offset of field: \",\n\n stringify!(_complex),\n\n \"::\",\n\n stringify!(x)\n\n )\n", "file_path": "dioteko-raylib-sys/src/bindings/windows_bindings.rs", "rank": 73, "score": 36315.606019205734 }, { "content": "#[test]\n\nfn bindgen_test_layout_Vector3() {\n\n assert_eq!(\n\n ::std::mem::size_of::<Vector3>(),\n\n 12usize,\n\n concat!(\"Size of: \", stringify!(Vector3))\n\n );\n\n assert_eq!(\n\n ::std::mem::align_of::<Vector3>(),\n\n 4usize,\n\n concat!(\"Alignment of \", stringify!(Vector3))\n\n );\n\n assert_eq!(\n\n unsafe { &(*(::std::ptr::null::<Vector3>())).x as *const _ as usize },\n\n 0usize,\n\n concat!(\n\n \"Offset of field: \",\n\n stringify!(Vector3),\n\n \"::\",\n\n stringify!(x)\n\n )\n", "file_path": "dioteko-raylib-sys/src/bindings/macos_bindings.rs", "rank": 74, "score": 36315.606019205734 }, { "content": "#[test]\n\nfn bindgen_test_layout_Transform() {\n\n assert_eq!(\n\n ::std::mem::size_of::<Transform>(),\n\n 40usize,\n\n concat!(\"Size of: \", stringify!(Transform))\n\n );\n\n assert_eq!(\n\n ::std::mem::align_of::<Transform>(),\n\n 4usize,\n\n concat!(\"Alignment of \", stringify!(Transform))\n\n );\n\n assert_eq!(\n\n unsafe { &(*(::std::ptr::null::<Transform>())).translation as *const _ as usize },\n\n 0usize,\n\n concat!(\n\n \"Offset of field: \",\n\n stringify!(Transform),\n\n \"::\",\n\n stringify!(translation)\n\n )\n", "file_path": "dioteko-raylib-sys/src/bindings/windows_bindings.rs", "rank": 75, "score": 36315.606019205734 }, { "content": "#[test]\n\nfn bindgen_test_layout__exception() {\n\n assert_eq!(\n\n ::std::mem::size_of::<_exception>(),\n\n 40usize,\n\n concat!(\"Size of: \", stringify!(_exception))\n\n );\n\n assert_eq!(\n\n ::std::mem::align_of::<_exception>(),\n\n 8usize,\n\n concat!(\"Alignment of \", stringify!(_exception))\n\n );\n\n assert_eq!(\n\n unsafe { &(*(::std::ptr::null::<_exception>())).type_ as *const _ as usize },\n\n 0usize,\n\n concat!(\n\n \"Offset of field: \",\n\n stringify!(_exception),\n\n \"::\",\n\n stringify!(type_)\n\n )\n", "file_path": "dioteko-raylib-sys/src/bindings/windows_bindings.rs", "rank": 76, "score": 36315.606019205734 }, { "content": "#[test]\n\nfn bindgen_test_layout_Sound() {\n\n assert_eq!(\n\n ::std::mem::size_of::<Sound>(),\n\n 32usize,\n\n concat!(\"Size of: \", stringify!(Sound))\n\n );\n\n assert_eq!(\n\n ::std::mem::align_of::<Sound>(),\n\n 8usize,\n\n concat!(\"Alignment of \", stringify!(Sound))\n\n );\n\n assert_eq!(\n\n unsafe { &(*(::std::ptr::null::<Sound>())).stream as *const _ as usize },\n\n 0usize,\n\n concat!(\n\n \"Offset of field: \",\n\n stringify!(Sound),\n\n \"::\",\n\n stringify!(stream)\n\n )\n", "file_path": "dioteko-raylib-sys/src/bindings/windows_bindings.rs", "rank": 77, "score": 36315.606019205734 }, { "content": "#[test]\n\nfn bindgen_test_layout_float16() {\n\n assert_eq!(\n\n ::std::mem::size_of::<float16>(),\n\n 64usize,\n\n concat!(\"Size of: \", stringify!(float16))\n\n );\n\n assert_eq!(\n\n ::std::mem::align_of::<float16>(),\n\n 4usize,\n\n concat!(\"Alignment of \", stringify!(float16))\n\n );\n\n assert_eq!(\n\n unsafe { &(*(::std::ptr::null::<float16>())).v as *const _ as usize },\n\n 0usize,\n\n concat!(\n\n \"Offset of field: \",\n\n stringify!(float16),\n\n \"::\",\n\n stringify!(v)\n\n )\n", "file_path": "dioteko-raylib-sys/src/bindings/windows_bindings.rs", "rank": 78, "score": 36315.606019205734 }, { "content": "#[test]\n\nfn bindgen_test_layout_Image() {\n\n assert_eq!(\n\n ::std::mem::size_of::<Image>(),\n\n 24usize,\n\n concat!(\"Size of: \", stringify!(Image))\n\n );\n\n assert_eq!(\n\n ::std::mem::align_of::<Image>(),\n\n 8usize,\n\n concat!(\"Alignment of \", stringify!(Image))\n\n );\n\n assert_eq!(\n\n unsafe { &(*(::std::ptr::null::<Image>())).data as *const _ as usize },\n\n 0usize,\n\n concat!(\n\n \"Offset of field: \",\n\n stringify!(Image),\n\n \"::\",\n\n stringify!(data)\n\n )\n", "file_path": "dioteko-raylib-sys/src/bindings/windows_bindings.rs", "rank": 79, "score": 36315.606019205734 }, { "content": "#[test]\n\nfn bindgen_test_layout___va_list_tag() {\n\n assert_eq!(\n\n ::std::mem::size_of::<__va_list_tag>(),\n\n 24usize,\n\n concat!(\"Size of: \", stringify!(__va_list_tag))\n\n );\n\n assert_eq!(\n\n ::std::mem::align_of::<__va_list_tag>(),\n\n 8usize,\n\n concat!(\"Alignment of \", stringify!(__va_list_tag))\n\n );\n\n assert_eq!(\n\n unsafe { &(*(::std::ptr::null::<__va_list_tag>())).gp_offset as *const _ as usize },\n\n 0usize,\n\n concat!(\n\n \"Offset of field: \",\n\n stringify!(__va_list_tag),\n\n \"::\",\n\n stringify!(gp_offset)\n\n )\n", "file_path": "dioteko-raylib-sys/src/bindings.rs", "rank": 80, "score": 36315.606019205734 }, { "content": "#[test]\n\nfn bindgen_test_layout_Shader() {\n\n assert_eq!(\n\n ::std::mem::size_of::<Shader>(),\n\n 16usize,\n\n concat!(\"Size of: \", stringify!(Shader))\n\n );\n\n assert_eq!(\n\n ::std::mem::align_of::<Shader>(),\n\n 8usize,\n\n concat!(\"Alignment of \", stringify!(Shader))\n\n );\n\n assert_eq!(\n\n unsafe { &(*(::std::ptr::null::<Shader>())).id as *const _ as usize },\n\n 0usize,\n\n concat!(\n\n \"Offset of field: \",\n\n stringify!(Shader),\n\n \"::\",\n\n stringify!(id)\n\n )\n", "file_path": "dioteko-raylib-sys/src/bindings/macos_bindings.rs", "rank": 81, "score": 36315.606019205734 }, { "content": "#[test]\n\nfn bindgen_test_layout_Wave() {\n\n assert_eq!(\n\n ::std::mem::size_of::<Wave>(),\n\n 24usize,\n\n concat!(\"Size of: \", stringify!(Wave))\n\n );\n\n assert_eq!(\n\n ::std::mem::align_of::<Wave>(),\n\n 8usize,\n\n concat!(\"Alignment of \", stringify!(Wave))\n\n );\n\n assert_eq!(\n\n unsafe { &(*(::std::ptr::null::<Wave>())).frameCount as *const _ as usize },\n\n 0usize,\n\n concat!(\n\n \"Offset of field: \",\n\n stringify!(Wave),\n\n \"::\",\n\n stringify!(frameCount)\n\n )\n", "file_path": "dioteko-raylib-sys/src/bindings/windows_bindings.rs", "rank": 82, "score": 36315.606019205734 }, { "content": "#[test]\n\nfn bindgen_test_layout_float3() {\n\n assert_eq!(\n\n ::std::mem::size_of::<float3>(),\n\n 12usize,\n\n concat!(\"Size of: \", stringify!(float3))\n\n );\n\n assert_eq!(\n\n ::std::mem::align_of::<float3>(),\n\n 4usize,\n\n concat!(\"Alignment of \", stringify!(float3))\n\n );\n\n assert_eq!(\n\n unsafe { &(*(::std::ptr::null::<float3>())).v as *const _ as usize },\n\n 0usize,\n\n concat!(\"Offset of field: \", stringify!(float3), \"::\", stringify!(v))\n\n );\n\n}\n\n#[repr(C)]\n\n#[derive(Debug, Copy, Clone)]\n\npub struct float16 {\n\n pub v: [f32; 16usize],\n\n}\n", "file_path": "dioteko-raylib-sys/src/bindings/windows_bindings.rs", "rank": 83, "score": 36315.606019205734 }, { "content": "#[test]\n\nfn bindgen_test_layout_Model() {\n\n assert_eq!(\n\n ::std::mem::size_of::<Model>(),\n\n 120usize,\n\n concat!(\"Size of: \", stringify!(Model))\n\n );\n\n assert_eq!(\n\n ::std::mem::align_of::<Model>(),\n\n 8usize,\n\n concat!(\"Alignment of \", stringify!(Model))\n\n );\n\n assert_eq!(\n\n unsafe { &(*(::std::ptr::null::<Model>())).transform as *const _ as usize },\n\n 0usize,\n\n concat!(\n\n \"Offset of field: \",\n\n stringify!(Model),\n\n \"::\",\n\n stringify!(transform)\n\n )\n", "file_path": "dioteko-raylib-sys/src/bindings/windows_bindings.rs", "rank": 84, "score": 36315.606019205734 }, { "content": "#[test]\n\nfn bindgen_test_layout_Vector4() {\n\n assert_eq!(\n\n ::std::mem::size_of::<Vector4>(),\n\n 16usize,\n\n concat!(\"Size of: \", stringify!(Vector4))\n\n );\n\n assert_eq!(\n\n ::std::mem::align_of::<Vector4>(),\n\n 4usize,\n\n concat!(\"Alignment of \", stringify!(Vector4))\n\n );\n\n assert_eq!(\n\n unsafe { &(*(::std::ptr::null::<Vector4>())).x as *const _ as usize },\n\n 0usize,\n\n concat!(\n\n \"Offset of field: \",\n\n stringify!(Vector4),\n\n \"::\",\n\n stringify!(x)\n\n )\n", "file_path": "dioteko-raylib-sys/src/bindings/windows_bindings.rs", "rank": 85, "score": 36315.606019205734 }, { "content": "#[test]\n\nfn bindgen_test_layout_Texture() {\n\n assert_eq!(\n\n ::std::mem::size_of::<Texture>(),\n\n 20usize,\n\n concat!(\"Size of: \", stringify!(Texture))\n\n );\n\n assert_eq!(\n\n ::std::mem::align_of::<Texture>(),\n\n 4usize,\n\n concat!(\"Alignment of \", stringify!(Texture))\n\n );\n\n assert_eq!(\n\n unsafe { &(*(::std::ptr::null::<Texture>())).id as *const _ as usize },\n\n 0usize,\n\n concat!(\n\n \"Offset of field: \",\n\n stringify!(Texture),\n\n \"::\",\n\n stringify!(id)\n\n )\n", "file_path": "dioteko-raylib-sys/src/bindings/windows_bindings.rs", "rank": 86, "score": 36315.606019205734 }, { "content": "#[test]\n\nfn bindgen_test_layout_Ray() {\n\n assert_eq!(\n\n ::std::mem::size_of::<Ray>(),\n\n 24usize,\n\n concat!(\"Size of: \", stringify!(Ray))\n\n );\n\n assert_eq!(\n\n ::std::mem::align_of::<Ray>(),\n\n 4usize,\n\n concat!(\"Alignment of \", stringify!(Ray))\n\n );\n\n assert_eq!(\n\n unsafe { &(*(::std::ptr::null::<Ray>())).position as *const _ as usize },\n\n 0usize,\n\n concat!(\n\n \"Offset of field: \",\n\n stringify!(Ray),\n\n \"::\",\n\n stringify!(position)\n\n )\n", "file_path": "dioteko-raylib-sys/src/bindings/windows_bindings.rs", "rank": 87, "score": 36315.606019205734 }, { "content": "#[test]\n\nfn bindgen_test_layout_VrDeviceInfo() {\n\n assert_eq!(\n\n ::std::mem::size_of::<VrDeviceInfo>(),\n\n 64usize,\n\n concat!(\"Size of: \", stringify!(VrDeviceInfo))\n\n );\n\n assert_eq!(\n\n ::std::mem::align_of::<VrDeviceInfo>(),\n\n 4usize,\n\n concat!(\"Alignment of \", stringify!(VrDeviceInfo))\n\n );\n\n assert_eq!(\n\n unsafe { &(*(::std::ptr::null::<VrDeviceInfo>())).hResolution as *const _ as usize },\n\n 0usize,\n\n concat!(\n\n \"Offset of field: \",\n\n stringify!(VrDeviceInfo),\n\n \"::\",\n\n stringify!(hResolution)\n\n )\n", "file_path": "dioteko-raylib-sys/src/bindings.rs", "rank": 88, "score": 36315.606019205734 }, { "content": "#[test]\n\nfn bindgen_test_layout_Music() {\n\n assert_eq!(\n\n ::std::mem::size_of::<Music>(),\n\n 48usize,\n\n concat!(\"Size of: \", stringify!(Music))\n\n );\n\n assert_eq!(\n\n ::std::mem::align_of::<Music>(),\n\n 8usize,\n\n concat!(\"Alignment of \", stringify!(Music))\n\n );\n\n assert_eq!(\n\n unsafe { &(*(::std::ptr::null::<Music>())).stream as *const _ as usize },\n\n 0usize,\n\n concat!(\n\n \"Offset of field: \",\n\n stringify!(Music),\n\n \"::\",\n\n stringify!(stream)\n\n )\n", "file_path": "dioteko-raylib-sys/src/bindings/windows_bindings.rs", "rank": 89, "score": 36315.606019205734 }, { "content": "#[test]\n\nfn bindgen_test_layout_RenderTexture() {\n\n assert_eq!(\n\n ::std::mem::size_of::<RenderTexture>(),\n\n 44usize,\n\n concat!(\"Size of: \", stringify!(RenderTexture))\n\n );\n\n assert_eq!(\n\n ::std::mem::align_of::<RenderTexture>(),\n\n 4usize,\n\n concat!(\"Alignment of \", stringify!(RenderTexture))\n\n );\n\n assert_eq!(\n\n unsafe { &(*(::std::ptr::null::<RenderTexture>())).id as *const _ as usize },\n\n 0usize,\n\n concat!(\n\n \"Offset of field: \",\n\n stringify!(RenderTexture),\n\n \"::\",\n\n stringify!(id)\n\n )\n", "file_path": "dioteko-raylib-sys/src/bindings/macos_bindings.rs", "rank": 90, "score": 35356.084927280426 }, { "content": "#[test]\n\nfn bindgen_test_layout_Camera2D() {\n\n assert_eq!(\n\n ::std::mem::size_of::<Camera2D>(),\n\n 24usize,\n\n concat!(\"Size of: \", stringify!(Camera2D))\n\n );\n\n assert_eq!(\n\n ::std::mem::align_of::<Camera2D>(),\n\n 4usize,\n\n concat!(\"Alignment of \", stringify!(Camera2D))\n\n );\n\n assert_eq!(\n\n unsafe { &(*(::std::ptr::null::<Camera2D>())).offset as *const _ as usize },\n\n 0usize,\n\n concat!(\n\n \"Offset of field: \",\n\n stringify!(Camera2D),\n\n \"::\",\n\n stringify!(offset)\n\n )\n", "file_path": "dioteko-raylib-sys/src/bindings/macos_bindings.rs", "rank": 91, "score": 35356.084927280426 }, { "content": "#[test]\n\nfn bindgen_test_layout_AudioStream() {\n\n assert_eq!(\n\n ::std::mem::size_of::<AudioStream>(),\n\n 24usize,\n\n concat!(\"Size of: \", stringify!(AudioStream))\n\n );\n\n assert_eq!(\n\n ::std::mem::align_of::<AudioStream>(),\n\n 8usize,\n\n concat!(\"Alignment of \", stringify!(AudioStream))\n\n );\n\n assert_eq!(\n\n unsafe { &(*(::std::ptr::null::<AudioStream>())).buffer as *const _ as usize },\n\n 0usize,\n\n concat!(\n\n \"Offset of field: \",\n\n stringify!(AudioStream),\n\n \"::\",\n\n stringify!(buffer)\n\n )\n", "file_path": "dioteko-raylib-sys/src/bindings/macos_bindings.rs", "rank": 92, "score": 35356.084927280426 }, { "content": "#[test]\n\nfn bindgen_test_layout_RayCollision() {\n\n assert_eq!(\n\n ::std::mem::size_of::<RayCollision>(),\n\n 32usize,\n\n concat!(\"Size of: \", stringify!(RayCollision))\n\n );\n\n assert_eq!(\n\n ::std::mem::align_of::<RayCollision>(),\n\n 4usize,\n\n concat!(\"Alignment of \", stringify!(RayCollision))\n\n );\n\n assert_eq!(\n\n unsafe { &(*(::std::ptr::null::<RayCollision>())).hit as *const _ as usize },\n\n 0usize,\n\n concat!(\n\n \"Offset of field: \",\n\n stringify!(RayCollision),\n\n \"::\",\n\n stringify!(hit)\n\n )\n", "file_path": "dioteko-raylib-sys/src/bindings/macos_bindings.rs", "rank": 93, "score": 35356.084927280426 }, { "content": "#[test]\n\nfn bindgen_test_layout_MaterialMap() {\n\n assert_eq!(\n\n ::std::mem::size_of::<MaterialMap>(),\n\n 28usize,\n\n concat!(\"Size of: \", stringify!(MaterialMap))\n\n );\n\n assert_eq!(\n\n ::std::mem::align_of::<MaterialMap>(),\n\n 4usize,\n\n concat!(\"Alignment of \", stringify!(MaterialMap))\n\n );\n\n assert_eq!(\n\n unsafe { &(*(::std::ptr::null::<MaterialMap>())).texture as *const _ as usize },\n\n 0usize,\n\n concat!(\n\n \"Offset of field: \",\n\n stringify!(MaterialMap),\n\n \"::\",\n\n stringify!(texture)\n\n )\n", "file_path": "dioteko-raylib-sys/src/bindings/macos_bindings.rs", "rank": 94, "score": 35356.084927280426 }, { "content": "#[test]\n\nfn bindgen_test_layout_BoneInfo() {\n\n assert_eq!(\n\n ::std::mem::size_of::<BoneInfo>(),\n\n 36usize,\n\n concat!(\"Size of: \", stringify!(BoneInfo))\n\n );\n\n assert_eq!(\n\n ::std::mem::align_of::<BoneInfo>(),\n\n 4usize,\n\n concat!(\"Alignment of \", stringify!(BoneInfo))\n\n );\n\n assert_eq!(\n\n unsafe { &(*(::std::ptr::null::<BoneInfo>())).name as *const _ as usize },\n\n 0usize,\n\n concat!(\n\n \"Offset of field: \",\n\n stringify!(BoneInfo),\n\n \"::\",\n\n stringify!(name)\n\n )\n", "file_path": "dioteko-raylib-sys/src/bindings/macos_bindings.rs", "rank": 95, "score": 35356.084927280426 }, { "content": "#[test]\n\nfn bindgen_test_layout_GlyphInfo() {\n\n assert_eq!(\n\n ::std::mem::size_of::<GlyphInfo>(),\n\n 40usize,\n\n concat!(\"Size of: \", stringify!(GlyphInfo))\n\n );\n\n assert_eq!(\n\n ::std::mem::align_of::<GlyphInfo>(),\n\n 8usize,\n\n concat!(\"Alignment of \", stringify!(GlyphInfo))\n\n );\n\n assert_eq!(\n\n unsafe { &(*(::std::ptr::null::<GlyphInfo>())).value as *const _ as usize },\n\n 0usize,\n\n concat!(\n\n \"Offset of field: \",\n\n stringify!(GlyphInfo),\n\n \"::\",\n\n stringify!(value)\n\n )\n", "file_path": "dioteko-raylib-sys/src/bindings/macos_bindings.rs", "rank": 96, "score": 35356.084927280426 }, { "content": "#[test]\n\nfn bindgen_test_layout_ModelAnimation() {\n\n assert_eq!(\n\n ::std::mem::size_of::<ModelAnimation>(),\n\n 24usize,\n\n concat!(\"Size of: \", stringify!(ModelAnimation))\n\n );\n\n assert_eq!(\n\n ::std::mem::align_of::<ModelAnimation>(),\n\n 8usize,\n\n concat!(\"Alignment of \", stringify!(ModelAnimation))\n\n );\n\n assert_eq!(\n\n unsafe { &(*(::std::ptr::null::<ModelAnimation>())).boneCount as *const _ as usize },\n\n 0usize,\n\n concat!(\n\n \"Offset of field: \",\n\n stringify!(ModelAnimation),\n\n \"::\",\n\n stringify!(boneCount)\n\n )\n", "file_path": "dioteko-raylib-sys/src/bindings/macos_bindings.rs", "rank": 97, "score": 35356.084927280426 }, { "content": "#[test]\n\nfn bindgen_test_layout_Camera3D() {\n\n assert_eq!(\n\n ::std::mem::size_of::<Camera3D>(),\n\n 44usize,\n\n concat!(\"Size of: \", stringify!(Camera3D))\n\n );\n\n assert_eq!(\n\n ::std::mem::align_of::<Camera3D>(),\n\n 4usize,\n\n concat!(\"Alignment of \", stringify!(Camera3D))\n\n );\n\n assert_eq!(\n\n unsafe { &(*(::std::ptr::null::<Camera3D>())).position as *const _ as usize },\n\n 0usize,\n\n concat!(\n\n \"Offset of field: \",\n\n stringify!(Camera3D),\n\n \"::\",\n\n stringify!(position)\n\n )\n", "file_path": "dioteko-raylib-sys/src/bindings/macos_bindings.rs", "rank": 98, "score": 35356.084927280426 }, { "content": "#[test]\n\nfn bindgen_test_layout_BoundingBox() {\n\n assert_eq!(\n\n ::std::mem::size_of::<BoundingBox>(),\n\n 24usize,\n\n concat!(\"Size of: \", stringify!(BoundingBox))\n\n );\n\n assert_eq!(\n\n ::std::mem::align_of::<BoundingBox>(),\n\n 4usize,\n\n concat!(\"Alignment of \", stringify!(BoundingBox))\n\n );\n\n assert_eq!(\n\n unsafe { &(*(::std::ptr::null::<BoundingBox>())).min as *const _ as usize },\n\n 0usize,\n\n concat!(\n\n \"Offset of field: \",\n\n stringify!(BoundingBox),\n\n \"::\",\n\n stringify!(min)\n\n )\n", "file_path": "dioteko-raylib-sys/src/bindings/macos_bindings.rs", "rank": 99, "score": 35356.084927280426 } ]
Rust
rosetta-i18n/src/serde_helpers.rs
baptiste0928/rosetta
039a69493dc5517d7778b9fb4ed0fa57375cc44e
use std::borrow::Cow; use serde::{de, ser}; use crate::LanguageId; impl ser::Serialize for LanguageId<'_> { fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error> where S: ser::Serializer, { serializer.serialize_str(&self.0) } } impl<'de> de::Deserialize<'de> for LanguageId<'de> { fn deserialize<D>(deserializer: D) -> Result<Self, D::Error> where D: de::Deserializer<'de>, { let value = Cow::deserialize(deserializer)?; match Self::validate(&value) { Some(language_id) => Ok(language_id), None => Err(de::Error::custom(format!( "`{}` is not a valid ISO 693-1 language id", value ))), } } } pub mod as_language { use serde::{de, ser, Deserialize, Serialize}; use crate::{Language, LanguageId}; pub fn deserialize<'de, D, T>(deserializer: D) -> Result<T, D::Error> where D: de::Deserializer<'de>, T: Language, { let language_id = LanguageId::deserialize(deserializer)?; match T::from_language_id(&language_id) { Some(value) => Ok(value), None => Err(de::Error::custom("language `{}` is not supported")), } } pub fn serialize<S, T>(val: &T, serializer: S) -> Result<S::Ok, S::Error> where S: ser::Serializer, T: Language, { val.language_id().serialize(serializer) } } pub mod as_language_with_fallback { use serde::{de, ser, Deserialize, Serialize}; use crate::{Language, LanguageId}; pub fn deserialize<'de, D, T>(deserializer: D) -> Result<T, D::Error> where D: de::Deserializer<'de>, T: Language, { let language_id = LanguageId::deserialize(deserializer)?; match T::from_language_id(&language_id) { Some(value) => Ok(value), None => Ok(T::fallback()), } } pub fn serialize<S, T>(val: &T, serializer: S) -> Result<S::Ok, S::Error> where S: ser::Serializer, T: Language, { val.language_id().serialize(serializer) } } #[cfg(test)] mod tests { use serde::{Deserialize, Serialize}; use serde_test::{assert_de_tokens, assert_de_tokens_error, assert_tokens, Token}; use crate::Language; use super::{as_language, as_language_with_fallback, LanguageId}; #[test] fn serde_language_id() { let lang_id = LanguageId::new("en"); assert_tokens(&lang_id, &[Token::String("en")]); } #[test] fn serde_invalid_language_id() { assert_de_tokens_error::<LanguageId>( &[Token::String("invalid")], "`invalid` is not a valid ISO 693-1 language id", ) } #[test] fn serde_as_language() { #[derive(Debug, PartialEq, Eq)] struct Lang; impl Language for Lang { fn from_language_id(language_id: &LanguageId) -> Option<Self> { match language_id.value() { "en" => Some(Self), _ => None, } } fn language_id(&self) -> LanguageId { LanguageId::new("en") } fn fallback() -> Self { unimplemented!() } } #[derive(Debug, Serialize, Deserialize, PartialEq, Eq)] struct LanguageStruct { #[serde(with = "as_language")] lang: Lang, } let value = LanguageStruct { lang: Lang }; assert_tokens( &value, &[ Token::Struct { name: "LanguageStruct", len: 1, }, Token::Str("lang"), Token::String("en"), Token::StructEnd, ], ); } #[test] fn serde_as_language_fallback() { #[derive(Debug, PartialEq, Eq)] struct Lang; impl Language for Lang { fn from_language_id(language_id: &LanguageId) -> Option<Self> { match language_id.value() { "en" => Some(Self), _ => None, } } fn language_id(&self) -> LanguageId { LanguageId::new("en") } fn fallback() -> Self { Self } } #[derive(Debug, Serialize, Deserialize, PartialEq, Eq)] struct LanguageStruct { #[serde(with = "as_language_with_fallback")] lang: Lang, } let value = LanguageStruct { lang: Lang }; assert_de_tokens( &value, &[ Token::Struct { name: "LanguageStruct", len: 1, }, Token::Str("lang"), Token::String("fr"), Token::StructEnd, ], ); } }
use std::borrow::Cow; use serde::{de, ser}; use crate::LanguageId; impl ser::Serialize for LanguageId<'_> { fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error> where S: ser::Serializer, { serializer.serialize_str(&self.0) } } impl<'de> de::Deserialize<'de> for LanguageId<'de> { fn deserialize<D>(deserializer: D) -> Result<Self, D::Error> where D: de::Deserializer<'de>, { let value = Cow::deserialize(deserializer)?; match Self::validate(&value) { Some(language_id) => Ok(language_id), None => Err(de::Error::custom(format!( "`{}` is not a valid ISO 693-1 language id", value ))), } } } pub mod as_language { use serde::{de, ser, Deserialize, Serialize}; use crate::{Language, LanguageId}; pub fn deserialize<'de, D, T>(deserializer: D) -> Result<T, D::Error> where D: de::Deserializer<'de>, T: Language, { let language_id = LanguageId::deserialize(deserializer)?; match T::from_language_id(&language_id) { Some(value) => Ok(value), None => Err(de::Error::custom("language `{}` is not supported")), } } pub fn serialize<S, T>(val: &T, serializer: S) -> Result<S::Ok, S::Error> where S: ser::Serializer, T: Language, { val.language_id().serialize(serializer) } } pub mod as_language_with_fallback { use serde::{de, ser, Deserialize, Serialize}; use crate::{Language, LanguageId}; pub fn deserialize<'de, D, T>(deserializer: D) -> Result<T, D::Error> where D: de::Deserializer<'de>, T: Language, { let language_id = LanguageId::deserialize(deserializer)?; match T::from_language_id(&language_id) { Some(value) => Ok(value), None => Ok(T::fallback()), } } pub fn serialize<S, T>(val: &T, serializer: S) -> Result<S::Ok, S::Error> where S: ser::Serializer, T: Language, { val.language_id().serialize(serializer) } } #[cfg(test)] mod tests { use serde::{Deserialize, Serialize}; use serde_test::{assert_de_tokens, assert_de_tokens_error, assert_tokens, Token}; use crate::Language; use super::{as_language, as_language_with_fallback, LanguageId}; #[test] fn serde_language_id() { let lang_id = LanguageId::new("en"); assert_tokens(&lang_id, &[Token::String("en")]); } #[test] fn serde_invalid_language_id() { assert_de_tokens_error::<LanguageId>( &[Token::String("invalid")], "`invalid` is not a valid ISO 693-1 language id", ) } #[test] fn serde_as_language() { #[derive(Debug, PartialEq, Eq)] struct Lang; impl Language for Lang { fn from_language_id(language_id: &LanguageId) -> Option<Self> { match language_id.value() { "en" => Some(Self), _ => None, } } fn language_id(&self) -> LanguageId { LanguageId::new("en") } fn fallback() -> Self { unimplemented!() } } #[derive(Debug, Serialize, Deserialize, PartialEq, Eq)] struct LanguageStruct { #[serde(with = "as_language")] lang: Lang, } let value = LanguageStruct { lang: Lang };
; } #[test] fn serde_as_language_fallback() { #[derive(Debug, PartialEq, Eq)] struct Lang; impl Language for Lang { fn from_language_id(language_id: &LanguageId) -> Option<Self> { match language_id.value() { "en" => Some(Self), _ => None, } } fn language_id(&self) -> LanguageId { LanguageId::new("en") } fn fallback() -> Self { Self } } #[derive(Debug, Serialize, Deserialize, PartialEq, Eq)] struct LanguageStruct { #[serde(with = "as_language_with_fallback")] lang: Lang, } let value = LanguageStruct { lang: Lang }; assert_de_tokens( &value, &[ Token::Struct { name: "LanguageStruct", len: 1, }, Token::Str("lang"), Token::String("fr"), Token::StructEnd, ], ); } }
assert_tokens( &value, &[ Token::Struct { name: "LanguageStruct", len: 1, }, Token::Str("lang"), Token::String("en"), Token::StructEnd, ], )
call_expression
[ { "content": "/// Helper function that return an default [`RosettaBuilder`].\n\npub fn config() -> RosettaBuilder {\n\n RosettaBuilder::default()\n\n}\n\n\n\n/// Builder used to configure Rosetta code generation.\n\n#[derive(Debug, Clone, PartialEq, Eq, Default)]\n\npub struct RosettaBuilder {\n\n files: HashMap<String, PathBuf>,\n\n fallback: Option<String>,\n\n name: Option<String>,\n\n output: Option<PathBuf>,\n\n}\n\n\n\nimpl RosettaBuilder {\n\n /// Register a new translation source\n\n pub fn source(mut self, lang: impl Into<String>, path: impl Into<String>) -> Self {\n\n self.files.insert(lang.into(), PathBuf::from(path.into()));\n\n self\n\n }\n\n\n", "file_path": "rosetta-build/src/builder.rs", "rank": 0, "score": 67401.68664251306 }, { "content": "/// Trait implemented by languages structs generated by `rosetta-build`.\n\npub trait Language: Sized {\n\n /// Initialize this type from a [`LanguageId`].\n\n ///\n\n /// The method returns [`None`] if the provided language id is not supported\n\n /// by the struct.\n\n fn from_language_id(language_id: &LanguageId) -> Option<Self>;\n\n /// Convert this struct to a [`LanguageId`].\n\n fn language_id(&self) -> LanguageId;\n\n /// Get the fallback language of this type.\n\n ///\n\n /// This fallback value can be used like a default value.\n\n fn fallback() -> Self;\n\n}\n\n\n\n/// Generic language type that implement the [`Language`] trait.\n\n///\n\n/// This type can be used as a default generic type when sharing models between multiple\n\n/// crates that does not necessarily use translations.\n\n///\n\n/// ## Panics\n", "file_path": "rosetta-i18n/src/lib.rs", "rank": 1, "score": 60964.21965313104 }, { "content": "/// Trait for language data providers.\n\n///\n\n/// This trait is implemented on types that provide data used\n\n/// to localize strings in a given language. See [`DefaultProvider`]\n\n/// for an example implementation.\n\npub trait LanguageProvider: Sized {\n\n /// Initialize the provider from a language identifier.\n\n ///\n\n /// This method deliberately cannot fail. If a invalid\n\n /// value is provided, you should either return a default\n\n /// or a generic value.\n\n fn from_id(language_id: &LanguageId) -> Self;\n\n\n\n /// Select the appropriate [`PluralCategory`] for a given number.\n\n fn plural(&self, number: u64) -> PluralCategory;\n\n}\n\n\n\n/// CLDR Plural category.\n\n///\n\n/// This type represent a plural category as defined in [Unicode CLDR Plural Rules].\n\n///\n\n/// [Unicode CLDR Plural Rules]: https://cldr.unicode.org/index/cldr-spec/plural-rules\n\n#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]\n\npub enum PluralCategory {\n\n /// Zero plural category.\n", "file_path": "rosetta-i18n/src/provider.rs", "rank": 2, "score": 59565.63700734033 }, { "content": "fn main() -> Result<(), Box<dyn std::error::Error>> {\n\n rosetta_build::config()\n\n .source(\"fr\", \"locales/fr.json\")\n\n .source(\"en\", \"locales/en.json\")\n\n .fallback(\"en\")\n\n .generate()?;\n\n\n\n Ok(())\n\n}\n", "file_path": "rosetta-test/build.rs", "rank": 3, "score": 53463.99939851613 }, { "content": "/// Open a file and read its content as a JSON [`JsonValue`]\n\nfn open_file(path: &Path) -> Result<JsonValue, BuildError> {\n\n let content = match std::fs::read_to_string(path) {\n\n Ok(content) => content,\n\n Err(error) => {\n\n return Err(BuildError::FileRead {\n\n file: path.to_path_buf(),\n\n source: error,\n\n })\n\n }\n\n };\n\n\n\n match content.parse::<JsonValue>() {\n\n Ok(parsed) => Ok(parsed),\n\n Err(error) => Err(BuildError::JsonParse {\n\n file: path.to_path_buf(),\n\n source: error,\n\n }),\n\n }\n\n}\n\n\n\n/// Format a file with rustfmt\n", "file_path": "rosetta-build/src/builder.rs", "rank": 4, "score": 50758.549350043206 }, { "content": "#[derive(Debug, Clone, PartialEq, Eq)]\n\nstruct ParsedFile {\n\n keys: HashMap<String, ParsedKey>,\n\n}\n\n\n\nimpl ParsedFile {\n\n /// Parse a JSON [`JsonValue`] as a translations file\n\n fn parse(file: JsonValue) -> Result<Self, ParseError> {\n\n let input = match file {\n\n JsonValue::Object(map) => map,\n\n _ => return Err(ParseError::InvalidRoot),\n\n };\n\n\n\n let mut keys = HashMap::with_capacity(input.len());\n\n for (key, value) in input {\n\n let parsed = ParsedKey::parse(&key, value)?;\n\n keys.insert(key, parsed);\n\n }\n\n\n\n Ok(ParsedFile { keys })\n\n }\n\n}\n\n\n\n/// Raw representation of a parsed key\n", "file_path": "rosetta-build/src/parser.rs", "rank": 5, "score": 39626.0184768827 }, { "content": "#[derive(Debug, Clone, PartialEq, Eq)]\n\nstruct ParsedKeyData<'a> {\n\n language: LanguageId,\n\n key: &'a str,\n\n parsed: ParsedKey,\n\n}\n\n\n\n#[cfg(test)]\n\nmod tests {\n\n use super::{TranslationData, TranslationKey};\n\n use crate::{\n\n builder::LanguageId,\n\n error::ParseError,\n\n parser::{FormattedKey, SimpleKey},\n\n };\n\n\n\n use maplit::{hashmap, hashset};\n\n use tinyjson::JsonValue;\n\n\n\n macro_rules! json {\n\n ($value:tt) => {\n", "file_path": "rosetta-build/src/parser.rs", "rank": 6, "score": 36319.46550561306 }, { "content": "#[cfg(feature = \"rustfmt\")]\n\nfn rustfmt(path: &Path) -> Result<(), BuildError> {\n\n use std::process::Command;\n\n\n\n Command::new(env::var(\"RUSTFMT\").unwrap_or_else(|_| \"rustfmt\".to_string()))\n\n .args(&[\"--emit\", \"files\"])\n\n .arg(path)\n\n .output()\n\n .map_err(BuildError::Fmt)?;\n\n\n\n Ok(())\n\n}\n\n\n\n#[cfg(test)]\n\nmod tests {\n\n use super::RosettaConfig;\n\n use crate::{\n\n builder::{LanguageId, RosettaBuilder},\n\n error::ConfigError,\n\n };\n\n\n", "file_path": "rosetta-build/src/builder.rs", "rank": 7, "score": 30301.349692733173 }, { "content": " assert_eq!(Lang::En.display_age(30, \"John\"), \"John is 30 years old.\");\n\n assert_eq!(Lang::Fr.display_age(30, \"John\"), \"John a 30 ans.\");\n\n }\n\n\n\n #[test]\n\n fn test_fallback() {\n\n assert_eq!(Lang::Fr.fallback_key(), Lang::En.fallback_key());\n\n assert_eq!(Lang::fallback(), Lang::En);\n\n }\n\n\n\n #[test]\n\n fn test_from_language_id() {\n\n let en = LanguageId::new(\"en\");\n\n let fr = LanguageId::new(\"fr\");\n\n let de = LanguageId::new(\"de\");\n\n\n\n assert_eq!(Lang::from_language_id(&en), Some(Lang::En));\n\n assert_eq!(Lang::from_language_id(&fr), Some(Lang::Fr));\n\n assert_eq!(Lang::from_language_id(&de), None);\n\n }\n\n\n\n #[test]\n\n fn test_to_language_id() {\n\n assert_eq!(Lang::En.language_id().value(), \"en\");\n\n assert_eq!(Lang::Fr.language_id().value(), \"fr\");\n\n }\n\n}\n", "file_path": "rosetta-test/src/lib.rs", "rank": 8, "score": 28718.03674785358 }, { "content": "//! Tests for rosetta i18n library\n\n//!\n\n//! This crate is only used to test code generated by rosetta-build\n\n//! and does not expose anything useful.\n\n\n\n#[cfg(test)]\n\nmod tests {\n\n use std::{fmt::Debug, hash::Hash};\n\n\n\n use rosetta_i18n::{Language, LanguageId};\n\n use static_assertions::assert_impl_all;\n\n\n\n rosetta_i18n::include_translations!();\n\n\n\n assert_impl_all!(\n\n Lang: Language,\n\n Debug,\n\n Clone,\n\n Copy,\n\n Eq,\n", "file_path": "rosetta-test/src/lib.rs", "rank": 9, "score": 28711.876868389805 }, { "content": " PartialEq,\n\n Hash,\n\n Send,\n\n Sync\n\n );\n\n\n\n #[test]\n\n fn test_simple() {\n\n assert_eq!(Lang::En.hello(), \"Hello world!\");\n\n assert_eq!(Lang::Fr.hello(), \"Bonjour le monde !\");\n\n }\n\n\n\n #[test]\n\n fn test_formatted() {\n\n assert_eq!(Lang::En.hello_name(\"John\"), \"Hello John!\");\n\n assert_eq!(Lang::Fr.hello_name(\"John\"), \"Bonjour John !\");\n\n }\n\n\n\n #[test]\n\n fn test_formatted_multiple() {\n", "file_path": "rosetta-test/src/lib.rs", "rank": 10, "score": 28704.49724128703 }, { "content": " ///\n\n /// ```\n\n /// # use rosetta_i18n::LanguageId;\n\n /// let language_id = LanguageId::new(\"en\");\n\n /// assert_eq!(language_id.value(), \"en\");\n\n /// ```\n\n ///\n\n /// [ISO 693-1]: https://en.wikipedia.org/wiki/ISO_639-1\n\n /// [`validate`]: LanguageId::validate\n\n pub fn new(value: impl Into<Cow<'a, str>>) -> Self {\n\n Self(value.into())\n\n }\n\n\n\n /// Return a reference of the inner value.\n\n pub fn value(&self) -> &str {\n\n &self.0\n\n }\n\n\n\n /// Convert the type into a [`String`].\n\n pub fn into_inner(self) -> String {\n\n self.0.into_owned()\n\n }\n\n}\n", "file_path": "rosetta-i18n/src/lib.rs", "rank": 24, "score": 30.805734890205308 }, { "content": "///\n\n/// This type holds a string representing a language in the [ISO 693-1] format (two-letter code).\n\n/// The inner value is stored in a [`Cow`] to avoid allocation when possible.\n\n///\n\n/// ## Validation\n\n/// The type inner value is not validated unless the [`validate`] method is used to initialize the instance.\n\n/// Generally, you should use this method to initialize this type.\n\n///\n\n/// The performed validation only checks that the provided *looks like* an [ISO 693-1]language identifier\n\n/// (2 character alphanumeric ascii string).\n\n///\n\n/// ## Serde support\n\n/// This type implements the `Serialize` and `Deserialize` traits if the `serde` feature is enabled.\n\n/// Deserialization will fail if the value is not an ISO 639-1 language identifier.\n\n///\n\n/// ## Example\n\n/// ```\n\n/// use rosetta_i18n::LanguageId;\n\n///\n\n/// let language_id = LanguageId::new(\"fr\");\n", "file_path": "rosetta-i18n/src/lib.rs", "rank": 25, "score": 29.594207986988337 }, { "content": " /// assert!(LanguageId::validate(\"invalid\").is_none());\n\n /// ```\n\n ///\n\n /// [`new`]: LanguageId::new\n\n /// [ISO 693-1]: https://en.wikipedia.org/wiki/ISO_639-1\n\n pub fn validate(value: &str) -> Option<Self> {\n\n let valid_length = value.len() == 2;\n\n let ascii_alphabetic = value.chars().all(|c| c.is_ascii_alphabetic());\n\n\n\n if valid_length && ascii_alphabetic {\n\n Some(Self(Cow::Owned(value.to_ascii_lowercase())))\n\n } else {\n\n None\n\n }\n\n }\n\n\n\n /// Initialize a new [`LanguageId`] from a string.\n\n ///\n\n /// The provided value must be an [ISO 693-1] encoded language id.\n\n /// If you want to validate the value, use [`validate`] instead.\n", "file_path": "rosetta-i18n/src/lib.rs", "rank": 26, "score": 29.24916003210182 }, { "content": "/// assert_eq!(language_id.value(), \"fr\");\n\n///\n\n/// let language_id = LanguageId::validate(\"fr\");\n\n/// assert!(language_id.is_some());\n\n/// ```\n\n///\n\n/// [ISO 693-1]: https://en.wikipedia.org/wiki/ISO_639-1\n\n/// [`validate`]: LanguageId::validate\n\n#[derive(Debug, Clone, PartialEq, Eq, Hash)]\n\npub struct LanguageId<'a>(Cow<'a, str>);\n\n\n\nimpl<'a> LanguageId<'a> {\n\n /// Initialize a new valid [`LanguageId`].\n\n ///\n\n /// Unlike [`new`], this method ensures that the provided\n\n /// value is a valid [ISO 693-1] encoded language id.\n\n ///\n\n /// ```\n\n /// # use rosetta_i18n::LanguageId;\n\n /// assert!(LanguageId::validate(\"fr\").is_some());\n", "file_path": "rosetta-i18n/src/lib.rs", "rank": 27, "score": 26.328968094113414 }, { "content": "//! Easy-to-use i18n library for Rust, based on code generation.\n\n//!\n\n//! ## Usage\n\n//! Please read the [documentation] to learn how to use this library.\n\n//!\n\n//! ```ignore\n\n//! mod translations {\n\n//! rosetta_i18n::include_translations!();\n\n//! }\n\n//!\n\n//! fn main() {\n\n//! assert_eq!(Lang::En.hello(), \"Hello world!\");\n\n//! }\n\n//! ```\n\n//!\n\n//! ## Serde support\n\n//! This crate provide serialization and deserialization of languages types with Serde.\n\n//! The `serde` feature must be enabled.\n\n//!\n\n//! [documentation]: https://baptiste0928.github.io/rosetta/\n", "file_path": "rosetta-i18n/src/lib.rs", "rank": 28, "score": 25.51327157680277 }, { "content": "/// ISO 639-1 language identifier.\n\n///\n\n/// Language identifier can be validated using the [`FromStr`] trait.\n\n/// It only checks if the string *looks like* a language identifier (2 character alphanumeric ascii string).\n\n#[derive(Debug, Clone, PartialEq, Eq, Hash)]\n\npub(crate) struct LanguageId(pub String);\n\n\n\nimpl LanguageId {\n\n pub(crate) fn value(&self) -> &str {\n\n &self.0\n\n }\n\n}\n\n\n\nimpl FromStr for LanguageId {\n\n type Err = ConfigError;\n\n\n\n fn from_str(s: &str) -> Result<Self, Self::Err> {\n\n let valid_length = s.len() == 2;\n\n let ascii_alphabetic = s.chars().all(|c| c.is_ascii_alphabetic());\n\n\n", "file_path": "rosetta-build/src/builder.rs", "rank": 29, "score": 25.434354090655447 }, { "content": "/// The [`fallback`] method of the [`Language`] trait is not implemented and will panic if called.\n\n///\n\n/// [`fallback`]: Language::fallback\n\npub struct GenericLanguage(String);\n\n\n\nimpl Language for GenericLanguage {\n\n fn from_language_id(language_id: &LanguageId) -> Option<Self> {\n\n Some(Self(language_id.value().into()))\n\n }\n\n\n\n fn language_id(&self) -> LanguageId {\n\n LanguageId::new(&self.0)\n\n }\n\n\n\n fn fallback() -> Self {\n\n unimplemented!(\"GenericLanguage has no fallback language\")\n\n }\n\n}\n\n\n\n/// ISO 639-1 language identifier.\n", "file_path": "rosetta-i18n/src/lib.rs", "rank": 30, "score": 24.084912466645655 }, { "content": " .clone()\n\n .map(|(lang, ident)| quote!(#lang => ::core::option::Option::Some(Self::#ident)));\n\n\n\n let to_language_id_arms = language_id_idents\n\n .map(|(lang, ident)| quote!(Self::#ident => ::rosetta_i18n::LanguageId::new(#lang)));\n\n\n\n quote! {\n\n impl ::rosetta_i18n::Language for #name {\n\n fn from_language_id(language_id: &::rosetta_i18n::LanguageId) -> ::core::option::Option<Self> {\n\n match language_id.value() {\n\n #(#from_language_id_arms,)*\n\n _ => ::core::option::Option::None\n\n }\n\n }\n\n\n\n fn language_id(&self) -> ::rosetta_i18n::LanguageId {\n\n match self {\n\n #(#to_language_id_arms,)*\n\n }\n\n }\n\n\n\n fn fallback() -> Self {\n\n Self::#fallback\n\n }\n\n }\n\n }\n\n }\n\n}\n", "file_path": "rosetta-build/src/gen.rs", "rank": 31, "score": 23.585149847857288 }, { "content": " if valid_length && ascii_alphabetic {\n\n Ok(Self(s.to_ascii_lowercase()))\n\n } else {\n\n Err(ConfigError::InvalidLanguage(s.into()))\n\n }\n\n }\n\n}\n\n\n\nimpl Display for LanguageId {\n\n fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {\n\n write!(f, \"{}\", self.0)\n\n }\n\n}\n\n\n\n/// Configuration for Rosetta code generation\n\n///\n\n/// A [`RosettaBuilder`] is provided to construct and validate configuration.\n\n#[derive(Debug, Clone, PartialEq, Eq)]\n\npub(crate) struct RosettaConfig {\n\n pub fallback: (LanguageId, PathBuf),\n", "file_path": "rosetta-build/src/builder.rs", "rank": 32, "score": 22.194302152459002 }, { "content": "\n\n#[derive(Debug, Clone, PartialEq, Eq)]\n\n/// Simple string key, without any formatting or plurals\n\npub(crate) struct SimpleKey {\n\n /// The key value for the fallback language\n\n pub(crate) fallback: String,\n\n /// Key values for other languages\n\n pub(crate) others: HashMap<LanguageId, String>,\n\n}\n\n\n\nimpl SimpleKey {\n\n /// Inserts a new raw [`ParsedKey`] in this [`SimpleKey`]\n\n fn insert_parsed(&mut self, data: ParsedKeyData) -> Result<(), ParseError> {\n\n match data.parsed {\n\n ParsedKey::Simple(value) => self.others.insert(data.language, value),\n\n _ => {\n\n return Err(ParseError::InvalidType {\n\n key: data.key.into(),\n\n expected: \"string\",\n\n })\n", "file_path": "rosetta-build/src/parser.rs", "rank": 33, "score": 20.249612491227495 }, { "content": " ///\n\n /// In some languages, such as Japanese, Chinese, Korean, and Thai, this is the only plural category.\n\n Other,\n\n}\n\n\n\n/// Default built-in data provider.\n\n///\n\n/// This type is a default provider implementation provided for\n\n/// simple use cases or testing purposes. **It only implements\n\n/// few common latin languages.** You should implement [`LanguageProvider`]\n\n/// yourself if you want to support more languages.\n\n///\n\n/// The [`En`](DefaultProvider::En) variant is used when an unknown\n\n/// [`LanguageId`] is provided.\n\n#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]\n\npub enum DefaultProvider {\n\n /// English\n\n En,\n\n /// Spanish\n\n Es,\n", "file_path": "rosetta-i18n/src/provider.rs", "rank": 34, "score": 19.519692030873404 }, { "content": " use std::path::PathBuf;\n\n\n\n use maplit::hashmap;\n\n\n\n #[test]\n\n fn config_simple() -> Result<(), Box<dyn std::error::Error>> {\n\n let config = RosettaBuilder::default()\n\n .source(\"en\", \"translations/en.json\")\n\n .source(\"fr\", \"translations/fr.json\")\n\n .fallback(\"en\")\n\n .build()?;\n\n\n\n let expected = RosettaConfig {\n\n fallback: (\n\n LanguageId(\"en\".into()),\n\n PathBuf::from(\"translations/en.json\"),\n\n ),\n\n others: hashmap! { LanguageId(\"fr\".into()) => PathBuf::from(\"translations/fr.json\") },\n\n name: \"Lang\".to_string(),\n\n output: None,\n", "file_path": "rosetta-build/src/builder.rs", "rank": 35, "score": 19.291807981566144 }, { "content": " /// French\n\n Fr,\n\n /// German\n\n De,\n\n /// Italian\n\n It,\n\n}\n\n\n\nimpl LanguageProvider for DefaultProvider {\n\n fn from_id(language_id: &LanguageId) -> Self {\n\n match language_id.value() {\n\n \"es\" => Self::Es,\n\n \"fr\" => Self::Fr,\n\n \"de\" => Self::De,\n\n \"it\" => Self::It,\n\n _ => Self::En,\n\n }\n\n }\n\n\n\n fn plural(&self, number: u64) -> PluralCategory {\n", "file_path": "rosetta-i18n/src/provider.rs", "rank": 36, "score": 19.017276131377688 }, { "content": "\n\n quote!(format!(#value, #(#params),*))\n\n }\n\n\n\n /// Generate implementation for `rosetta_i18n::Language` trait.\n\n fn impl_language(&self) -> TokenStream {\n\n let name = &self.name;\n\n let fallback = Ident::new(\n\n &self.fallback.value().to_case(Case::Pascal),\n\n Span::call_site(),\n\n );\n\n\n\n let language_id_idents = self.languages.iter().map(|lang| lang.value()).map(|lang| {\n\n (\n\n lang,\n\n Ident::new(&lang.to_case(Case::Pascal), Span::call_site()),\n\n )\n\n });\n\n\n\n let from_language_id_arms = language_id_idents\n", "file_path": "rosetta-build/src/gen.rs", "rank": 37, "score": 19.006296282012087 }, { "content": " InvalidFallback,\n\n}\n\n\n\nimpl Error for ConfigError {}\n\n\n\nimpl Display for ConfigError {\n\n fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {\n\n match self {\n\n ConfigError::InvalidLanguage(value) => {\n\n write!(f, \"`{}` is not a valid language identifier\", value)\n\n }\n\n ConfigError::MissingSource => {\n\n write!(f, \"at least one translations source file is required\")\n\n }\n\n ConfigError::MissingFallback => write!(f, \"a fallback language must be provided\"),\n\n ConfigError::InvalidFallback => write!(\n\n f,\n\n \"no source corresponding to the fallback language was found\"\n\n ),\n\n }\n", "file_path": "rosetta-build/src/error.rs", "rank": 38, "score": 18.537534533397352 }, { "content": " Some(lang) => {\n\n let lang = lang.parse::<LanguageId>()?;\n\n\n\n match files.remove_entry(&lang) {\n\n Some(entry) => entry,\n\n None => return Err(ConfigError::InvalidFallback),\n\n }\n\n }\n\n None => return Err(ConfigError::MissingFallback),\n\n };\n\n\n\n Ok(RosettaConfig {\n\n fallback,\n\n others: files,\n\n name: self.name.unwrap_or_else(|| \"Lang\".to_string()),\n\n output: self.output,\n\n })\n\n }\n\n}\n\n\n", "file_path": "rosetta-build/src/builder.rs", "rank": 39, "score": 18.441394440960092 }, { "content": " }\n\n };\n\n\n\n Ok(())\n\n }\n\n}\n\n\n\n#[derive(Debug, Clone, PartialEq, Eq)]\n\n/// Simple string key with formatting\n\npub(crate) struct FormattedKey {\n\n /// The key value for the fallback language\n\n pub(crate) fallback: String,\n\n /// Key values for other languages\n\n pub(crate) others: HashMap<LanguageId, String>,\n\n /// List of parameters in the value\n\n pub(crate) parameters: HashSet<String>,\n\n}\n\n\n\nimpl FormattedKey {\n\n /// Inserts a new [`ParsedKey`] in this [`SimpleKey`]\n", "file_path": "rosetta-build/src/parser.rs", "rank": 40, "score": 18.243187052588365 }, { "content": "## Generating code from translation files\n\nIt is now that the magic happens. Rosetta lets you generate a Rust type from your translation files.\n\nFor that, it use a [build script](https://doc.rust-lang.org/cargo/reference/build-scripts.html) which will be run each time you edit a translation file.\n\n\n\nWe need to create a `build.rs` file at the root folder of the crate (same folder as the `Cargo.toml` file).\n\n\n\n`build.rs`\n\n```rust\n\nfn main() -> Result<(), Box<dyn std::error::Error>> {\n\n rosetta_build::config()\n\n .source(\"en\", \"locales/en.json\")\n\n .source(\"fr\", \"locales/fr.json\")\n\n .fallback(\"en\")\n\n .generate()?;\n\n\n\n Ok(())\n\n}\n\n```\n\n\n\nThis script use the `rosetta_build` crate. In this example, we define two languages with [ISO 639-1](https://en.wikipedia.org/wiki/ISO_639-1)\n\nlanguage identifiers: `en` and `fr`. The `en` language is defined as fallback and will be used if a key is not defined in other languages.\n\n\n\nThe `.generate()` method is responsible for code generation. By default, the output file will be generated in a folder inside the `target` directory (`OUT_DIR` env variable). \n\n\n\n## Using the generated type\n\nThe generated type (named `Lang` except if you defined another name - see the previous section) must be included in your code with the `include_translations`\n\nmacro. A good practice is to isolate it in a dedicated module.\n\n\n\nEach translation key is transformed into a method, and each language into an enum variant. Parameters are sorted alphabetically to avoid silent breaking changes\n\nwhen reordering.\n\n\n\n`src/main.rs`\n\n```rust\n\nmod translations {\n\n rosetta_i18n::include_translations!();\n\n}\n\n\n\nfn main() {\n\n use translations::Lang;\n\n\n\n println!(\"{}\", Lang::En.hello()); // Hello world!\n\n println!(\"{}\", Lang::En.hello_name(\"Rust\")); // Hello Rust!\n\n}\n\n```\n\n\n", "file_path": "book/src/getting_started.md", "rank": 41, "score": 18.066443094129017 }, { "content": "//! Errors returned when generating code.\n\n\n\nuse std::{\n\n error::Error,\n\n fmt::{self, Display},\n\n path::PathBuf,\n\n};\n\n\n\n/// Error type returned when the configuration passed to [`RosettaBuilder`] is invalid.\n\n///\n\n/// [`RosettaBuilder`]: crate::RosettaBuilder\n\n#[derive(Debug, Clone, PartialEq, Eq)]\n\npub enum ConfigError {\n\n /// Invalid language identifier\n\n InvalidLanguage(String),\n\n /// No source provided\n\n MissingSource,\n\n /// No fallback language provided\n\n MissingFallback,\n\n /// The fallback language doesn't match any source\n", "file_path": "rosetta-build/src/error.rs", "rank": 42, "score": 17.680165701811212 }, { "content": "\n\nuse crate::{\n\n builder::{LanguageId, RosettaConfig},\n\n parser::{FormattedKey, SimpleKey, TranslationData, TranslationKey},\n\n};\n\n\n\n/// Type storing state and configuration for the code generator\n\n#[derive(Debug, Clone, PartialEq, Eq)]\n\npub(crate) struct CodeGenerator<'a> {\n\n keys: &'a HashMap<String, TranslationKey>,\n\n languages: Vec<&'a LanguageId>,\n\n fallback: &'a LanguageId,\n\n name: Ident,\n\n}\n\n\n\nimpl<'a> CodeGenerator<'a> {\n\n /// Initialize a new [`CodeGenerator`]\n\n pub(crate) fn new(data: &'a TranslationData, config: &'a RosettaConfig) -> Self {\n\n let name = Ident::new(&config.name, Span::call_site());\n\n\n", "file_path": "rosetta-build/src/gen.rs", "rank": 43, "score": 17.59265169956682 }, { "content": " .map(|lang| Ident::new(lang, Span::call_site()));\n\n\n\n let language_impl = self.impl_language();\n\n let methods = self.keys.iter().map(|(key, value)| match value {\n\n TranslationKey::Simple(inner) => self.method_simple(key, inner),\n\n TranslationKey::Formatted(inner) => self.method_formatted(key, inner),\n\n });\n\n\n\n quote! {\n\n /// Language type generated by the [rosetta](https://github.com/baptiste0928/rosetta) i18n library.\n\n #[derive(Debug, Clone, Copy, Eq, PartialEq, Hash)]\n\n pub enum #name {\n\n #(#fields),*\n\n }\n\n\n\n impl #name {\n\n #(#methods)*\n\n }\n\n\n\n #language_impl\n", "file_path": "rosetta-build/src/gen.rs", "rank": 44, "score": 17.485632750133092 }, { "content": " let file = json!({ \"hello\": [\"Hello world!\"] });\n\n let parsed = TranslationData::from_fallback(file);\n\n assert_eq!(\n\n parsed,\n\n Err(ParseError::InvalidValue {\n\n key: \"hello\".to_string()\n\n })\n\n );\n\n }\n\n\n\n #[test]\n\n fn parse_invalid_parameter() {\n\n let en = json!({ \"hello\": \"Hello {name}!\" });\n\n let fr = json!({ \"hello\": \"Bonjour {surname} !\" });\n\n\n\n let mut parsed = TranslationData::from_fallback(en).unwrap();\n\n let result = parsed.parse_file(LanguageId(\"fr\".into()), fr);\n\n\n\n let expected = ParseError::InvalidParameters {\n\n key: \"hello\".to_string(),\n\n missing: vec![\"name\".to_string()],\n\n unknown: vec![\"surname\".to_string()],\n\n };\n\n assert_eq!(result, Err(expected));\n\n }\n\n}\n", "file_path": "rosetta-build/src/parser.rs", "rank": 45, "score": 17.46218079639582 }, { "content": " /// Invalid language identifier (not ISO 693-1 compliant)\n\n InvalidLanguageId { value: String },\n\n}\n\n\n\nimpl Error for ParseError {}\n\n\n\nimpl Display for ParseError {\n\n fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {\n\n match self {\n\n ParseError::InvalidRoot => write!(f, \"file root must be a json object\"),\n\n ParseError::InvalidValue { key } => write!(f, \"`{}` has an invalid type\", key),\n\n ParseError::InvalidType { key, expected } => write!(\n\n f,\n\n \"`{}` doesn't match previous parsed key (expected {})\",\n\n key, expected\n\n ),\n\n ParseError::InvalidParameters {\n\n key,\n\n missing,\n\n unknown,\n", "file_path": "rosetta-build/src/error.rs", "rank": 46, "score": 17.443983105481163 }, { "content": " others: hashmap! {\n\n LanguageId(\"fr\".into()) => \"Bonjour {name} !\".to_string()\n\n },\n\n parameters: hashset! { \"name\".to_string() },\n\n });\n\n\n\n assert_eq!(parsed.keys.get(\"hello\").unwrap(), &expected);\n\n\n\n Ok(())\n\n }\n\n\n\n #[test]\n\n fn parse_invalid_root() {\n\n let file = json!(\"invalid\");\n\n let parsed = TranslationData::from_fallback(file);\n\n assert_eq!(parsed, Err(ParseError::InvalidRoot));\n\n }\n\n\n\n #[test]\n\n fn parse_invalid_value() {\n", "file_path": "rosetta-build/src/parser.rs", "rank": 47, "score": 17.336920056952668 }, { "content": " } => write!(\n\n f,\n\n \"invalid parameters supplied to `{}` (missing: {:?}, unknown: {:?})\",\n\n key, missing, unknown\n\n ),\n\n ParseError::InvalidLanguageId { value } => write!(\n\n f,\n\n \"`{}` is not a valid ISO 693-1 language identifier\",\n\n value\n\n ),\n\n }\n\n }\n\n}\n", "file_path": "rosetta-build/src/error.rs", "rank": 48, "score": 17.06531743794218 }, { "content": "\n\n assert_eq!(\n\n config,\n\n Err(ConfigError::InvalidLanguage(\"invalid\".to_string()))\n\n );\n\n }\n\n\n\n #[test]\n\n fn config_missing_fallback() {\n\n let config = RosettaBuilder::default()\n\n .source(\"en\", \"translations/en.json\")\n\n .source(\"fr\", \"translations/fr.json\")\n\n .build();\n\n\n\n assert_eq!(config, Err(ConfigError::MissingFallback));\n\n }\n\n\n\n #[test]\n\n fn config_invalid_fallback() {\n\n let config = RosettaBuilder::default()\n\n .source(\"en\", \"translations/en.json\")\n\n .source(\"fr\", \"translations/fr.json\")\n\n .fallback(\"de\")\n\n .build();\n\n\n\n assert_eq!(config, Err(ConfigError::InvalidFallback));\n\n }\n\n}\n", "file_path": "rosetta-build/src/builder.rs", "rank": 49, "score": 17.029126512995365 }, { "content": "//! Code generation for the Rosetta i18n library.\n\n//!\n\n//! # Usage\n\n//! Code generation works within [build script]. You only need to configure source files and\n\n//! the fallback language. Please read the [documentation] for more information.\n\n//!\n\n//! ```no_run\n\n//! rosetta_build::config()\n\n//! .source(\"fr\", \"locales/fr.json\")\n\n//! .source(\"en\", \"locales/en.json\")\n\n//! .fallback(\"en\")\n\n//! .generate();\n\n//! ```\n\n//!\n\n//! [build script]: https://doc.rust-lang.org/cargo/reference/build-scripts.html\n\n//! [documentation]: https://baptiste0928.github.io/rosetta/\n\n\n\npub mod error;\n\n\n\nmod builder;\n\nmod gen;\n\nmod parser;\n\n\n\npub use crate::builder::{config, RosettaBuilder};\n", "file_path": "rosetta-build/src/lib.rs", "rank": 50, "score": 16.363871496225666 }, { "content": "//! Translations files parsing\n\n//!\n\n//! Files are parsed as [TranslationData] from a provided [JsonValue].\n\n//! Parsed keys are represented as [TranslationKey].\n\n\n\nuse std::collections::{HashMap, HashSet};\n\n\n\nuse lazy_static::lazy_static;\n\nuse regex::Regex;\n\nuse tinyjson::JsonValue;\n\n\n\nuse crate::{builder::LanguageId, error::ParseError};\n\n\n\n/// Data structure containing all translation keys\n\n///\n\n/// This struct should be initialized with the fallback language,\n\n/// then keys will be populated with other languages using the [`parse_file`] method.\n\n///\n\n/// [`parse_file`]: Self::parse_file\n\n#[derive(Debug, Clone, PartialEq, Eq)]\n", "file_path": "rosetta-build/src/parser.rs", "rank": 51, "score": 16.15478741783433 }, { "content": " };\n\n\n\n assert_eq!(config, expected);\n\n\n\n Ok(())\n\n }\n\n\n\n #[test]\n\n fn config_missing_source() {\n\n let config = RosettaBuilder::default().build();\n\n assert_eq!(config, Err(ConfigError::MissingSource));\n\n }\n\n\n\n #[test]\n\n fn config_invalid_language() {\n\n let config = RosettaBuilder::default()\n\n .source(\"en\", \"translations/en.json\")\n\n .source(\"invalid\", \"translations/fr.json\")\n\n .fallback(\"en\")\n\n .build();\n", "file_path": "rosetta-build/src/builder.rs", "rank": 52, "score": 16.068596142297654 }, { "content": " CodeGenerator {\n\n keys: &data.keys,\n\n languages: config.languages(),\n\n fallback: &config.fallback.0,\n\n name,\n\n }\n\n }\n\n\n\n /// Generate code as a [`TokenStream`]\n\n pub(crate) fn generate(&self) -> TokenStream {\n\n // Transform as PascalCase strings\n\n let languages: Vec<_> = self\n\n .languages\n\n .iter()\n\n .map(|lang| lang.value().to_case(Case::Pascal))\n\n .collect();\n\n\n\n let name = &self.name;\n\n let fields = languages\n\n .iter()\n", "file_path": "rosetta-build/src/gen.rs", "rank": 53, "score": 15.91885312134688 }, { "content": " stringify!($value).parse::<JsonValue>().unwrap()\n\n };\n\n }\n\n\n\n #[test]\n\n fn parse_simple() -> Result<(), Box<dyn std::error::Error>> {\n\n let en = json!({ \"hello\": \"Hello world!\" });\n\n let fr = json!({ \"hello\": \"Bonjour le monde !\" });\n\n\n\n let mut parsed = TranslationData::from_fallback(en)?;\n\n parsed.parse_file(LanguageId(\"fr\".into()), fr)?;\n\n\n\n assert_eq!(parsed.keys.len(), 1);\n\n assert!(parsed.keys.get(\"hello\").is_some());\n\n\n\n let expected = TranslationKey::Simple(SimpleKey {\n\n fallback: \"Hello world!\".to_string(),\n\n others: hashmap! {\n\n LanguageId(\"fr\".into()) => \"Bonjour le monde !\".to_string()\n\n },\n", "file_path": "rosetta-build/src/parser.rs", "rank": 54, "score": 15.832042772005213 }, { "content": " /// Register the fallback locale\n\n pub fn fallback(mut self, lang: impl Into<String>) -> Self {\n\n self.fallback = Some(lang.into());\n\n self\n\n }\n\n\n\n /// Define a custom name for the output type\n\n pub fn name(mut self, name: impl Into<String>) -> Self {\n\n self.name = Some(name.into());\n\n self\n\n }\n\n\n\n /// Change the default output of generated files\n\n pub fn output(mut self, path: impl Into<PathBuf>) -> Self {\n\n self.output = Some(path.into());\n\n self\n\n }\n\n\n\n /// Generate locale files and write them to the output location\n\n pub fn generate(self) -> Result<(), BuildError> {\n", "file_path": "rosetta-build/src/builder.rs", "rank": 55, "score": 15.527539460128036 }, { "content": " self.build()?.generate()?;\n\n Ok(())\n\n }\n\n\n\n /// Validate configuration and build a [`RosettaConfig`]\n\n fn build(self) -> Result<RosettaConfig, ConfigError> {\n\n let mut files: HashMap<LanguageId, PathBuf> = self\n\n .files\n\n .into_iter()\n\n .map(|(lang, path)| {\n\n let lang = lang.parse::<LanguageId>()?;\n\n Ok((lang, path))\n\n })\n\n .collect::<Result<_, _>>()?;\n\n\n\n if files.is_empty() {\n\n return Err(ConfigError::MissingSource);\n\n }\n\n\n\n let fallback = match self.fallback {\n", "file_path": "rosetta-build/src/builder.rs", "rank": 56, "score": 15.457484168053636 }, { "content": " }\n\n }\n\n\n\n /// Generate method for [`TranslationKey::Simple`]\n\n fn method_simple(&self, key: &str, data: &SimpleKey) -> TokenStream {\n\n let name = Ident::new(&key.to_case(Case::Snake), Span::call_site());\n\n let fallback = &data.fallback;\n\n let arms = data\n\n .others\n\n .iter()\n\n .map(|(language, value)| self.match_arm_simple(language, value));\n\n\n\n quote! {\n\n #[allow(clippy::match_single_binding)]\n\n pub fn #name(&self) -> &'static str {\n\n match self {\n\n #(#arms,)*\n\n _ => #fallback\n\n }\n\n }\n", "file_path": "rosetta-build/src/gen.rs", "rank": 57, "score": 15.212360494726449 }, { "content": "pub(crate) struct TranslationData {\n\n /// Parsed translation keys\n\n pub(crate) keys: HashMap<String, TranslationKey>,\n\n}\n\n\n\nimpl TranslationData {\n\n /// Initialize a [`TranslationData`] instance from the fallback language\n\n pub(crate) fn from_fallback(file: JsonValue) -> Result<Self, ParseError> {\n\n let parsed = ParsedFile::parse(file)?;\n\n let keys = parsed\n\n .keys\n\n .into_iter()\n\n .map(|(key, value)| (key, TranslationKey::from_parsed(value)))\n\n .collect();\n\n\n\n Ok(Self { keys })\n\n }\n\n\n\n /// Parse a language file and insert its content into the current [`TranslationData`]\n\n pub(crate) fn parse_file(\n", "file_path": "rosetta-build/src/parser.rs", "rank": 58, "score": 15.12417138458822 }, { "content": " .map(|param| Ident::new(param, Span::call_site()))\n\n .map(|param| quote!(#param: impl ::std::fmt::Display));\n\n\n\n let arms = data\n\n .others\n\n .iter()\n\n .map(|(language, value)| self.match_arm_formatted(language, value, &data.parameters));\n\n let fallback = self.format_formatted(&data.fallback, &data.parameters);\n\n\n\n quote! {\n\n #[allow(clippy::match_single_binding)]\n\n pub fn #name(&self, #(#params),*) -> ::std::string::String {\n\n match self {\n\n #(#arms,)*\n\n _ => #fallback\n\n }\n\n }\n\n }\n\n }\n\n\n", "file_path": "rosetta-build/src/gen.rs", "rank": 59, "score": 15.114890796586078 }, { "content": "# Optional features\n\n\n\nThe `rosetta-i18n` and `rosetta-build` crates allow to turn on some additional features with [Cargo features](https://doc.rust-lang.org/cargo/reference/features.html).\n\nMost of these requires additional dependencies and are not enabled by default.\n\n\n\n> To enable a feature, you need to add a `feature` key in the `Cargo.toml` file like the following example:\n\n>\n\n> ```toml\n\n> rosetta-i18n = { version = \"0.1\", features = [\"serde\"] }\n\n> ``` \n\n\n\n## `rosetta-i18n`\n\n\n\n- `serde`: enable [Serde](https://serde.rs/) support, providing `Serialize` and `Deserialize` implementation for some types. Utility functions to serialize and deserialize\n\ngenerated types are also provided.\n\n\n\n## `rosetta-build`\n\n\n\n- `rustfmt` *(enabled by default)*: format generated code with [rustfmt](https://github.com/rust-lang/rustfmt). Disable this feature if `rustfmt` is not installed in your computer.\n", "file_path": "book/src/optional_features.md", "rank": 60, "score": 14.955736148152878 }, { "content": " /// Generate match arm for [`TranslationKey::Formatted`]\n\n fn match_arm_formatted(\n\n &self,\n\n language: &LanguageId,\n\n value: &str,\n\n parameters: &HashSet<String>,\n\n ) -> TokenStream {\n\n let name = &self.name;\n\n let format_value = self.format_formatted(value, parameters);\n\n let lang = Ident::new(&language.value().to_case(Case::Pascal), Span::call_site());\n\n\n\n quote! { #name::#lang => #format_value }\n\n }\n\n\n\n /// Generate `format!` for [`TranslationKey::Formatted`]\n\n fn format_formatted(&self, value: &str, parameters: &HashSet<String>) -> TokenStream {\n\n let params = parameters\n\n .iter()\n\n .map(|param| Ident::new(param, Span::call_site()))\n\n .map(|param| quote!(#param = #param));\n", "file_path": "rosetta-build/src/gen.rs", "rank": 61, "score": 14.906733524538504 }, { "content": " fn from(error: std::env::VarError) -> Self {\n\n Self::Var(error)\n\n }\n\n}\n\n\n\n/// Error type returned when a parsing error occurs.\n\n#[derive(Debug, Clone, PartialEq, Eq)]\n\npub enum ParseError {\n\n /// File root is not a JSON object\n\n InvalidRoot,\n\n /// Invalid key type (raw parsing)\n\n InvalidValue { key: String },\n\n /// Invalid key type (doesn't match previous parsed keys)\n\n InvalidType { key: String, expected: &'static str },\n\n /// Invalid parameters supplied to interpolated key (missing and/or unknown parameters)\n\n InvalidParameters {\n\n key: String,\n\n missing: Vec<String>,\n\n unknown: Vec<String>,\n\n },\n", "file_path": "rosetta-build/src/error.rs", "rank": 62, "score": 14.45559076265221 }, { "content": " }\n\n }\n\n\n\n /// Generate match arm for [`TranslationKey::Simple`]\n\n fn match_arm_simple(&self, language: &LanguageId, value: &str) -> TokenStream {\n\n let name = &self.name;\n\n let lang = Ident::new(&language.value().to_case(Case::Pascal), Span::call_site());\n\n\n\n quote! { #name::#lang => #value }\n\n }\n\n\n\n /// Generate method for [`TranslationKey::Formatted`]\n\n fn method_formatted(&self, key: &str, data: &FormattedKey) -> TokenStream {\n\n let name = Ident::new(&key.to_case(Case::Snake), Span::call_site());\n\n\n\n // Sort parameters alphabetically to have consistent ordering\n\n let mut sorted = Vec::from_iter(&data.parameters);\n\n sorted.sort_by_key(|s| s.to_lowercase());\n\n let params = sorted\n\n .iter()\n", "file_path": "rosetta-build/src/gen.rs", "rank": 63, "score": 14.40827698799853 }, { "content": " pub others: HashMap<LanguageId, PathBuf>,\n\n pub name: String,\n\n pub output: Option<PathBuf>,\n\n}\n\n\n\nimpl RosettaConfig {\n\n /// Returns a list of the languages\n\n pub fn languages(&self) -> Vec<&LanguageId> {\n\n let mut languages: Vec<&LanguageId> =\n\n self.others.iter().map(|(language, _)| language).collect();\n\n languages.push(&self.fallback.0);\n\n languages\n\n }\n\n\n\n /// Generate locale files and write them to the output location\n\n pub fn generate(&self) -> Result<(), BuildError> {\n\n let fallback_content = open_file(&self.fallback.1)?;\n\n let mut parsed = parser::TranslationData::from_fallback(fallback_content)?;\n\n println!(\n\n \"cargo:rerun-if-changed={}\",\n", "file_path": "rosetta-build/src/builder.rs", "rank": 64, "score": 14.133732584359972 }, { "content": "//! provider::{LanguageProvider, PluralCategory}\n\n//! };\n\n//!\n\n//! /// A provider that only works for French.\n\n//! struct FrenchProvider;\n\n//!\n\n//! impl LanguageProvider for FrenchProvider {\n\n//! fn from_id(_language_id: &LanguageId) -> Self {\n\n//! Self\n\n//! }\n\n//!\n\n//! fn plural(&self, number: u64) -> PluralCategory {\n\n//! match number {\n\n//! 0 | 1 => PluralCategory::One,\n\n//! _ => PluralCategory::Other\n\n//! }\n\n//! }\n\n//! }\n\n//! ```\n\n//!\n", "file_path": "rosetta-i18n/src/provider.rs", "rank": 65, "score": 13.80951443782168 }, { "content": " });\n\n\n\n assert_eq!(parsed.keys.get(\"hello\").unwrap(), &expected);\n\n\n\n Ok(())\n\n }\n\n\n\n #[test]\n\n fn parse_formatted() -> Result<(), Box<dyn std::error::Error>> {\n\n let en = json!({ \"hello\": \"Hello {name}!\" });\n\n let fr = json!({ \"hello\": \"Bonjour {name} !\" });\n\n\n\n let mut parsed = TranslationData::from_fallback(en)?;\n\n parsed.parse_file(LanguageId(\"fr\".into()), fr)?;\n\n\n\n assert_eq!(parsed.keys.len(), 1);\n\n assert!(parsed.keys.get(\"hello\").is_some());\n\n\n\n let expected = TranslationKey::Formatted(FormattedKey {\n\n fallback: \"Hello {name}!\".to_string(),\n", "file_path": "rosetta-build/src/parser.rs", "rank": 66, "score": 13.334638933109597 }, { "content": " &mut self,\n\n language: LanguageId,\n\n file: JsonValue,\n\n ) -> Result<(), ParseError> {\n\n let parsed = ParsedFile::parse(file)?;\n\n\n\n for (key, parsed) in parsed.keys {\n\n match self.keys.get_mut(&key) {\n\n Some(translation_key) => {\n\n let data = ParsedKeyData {\n\n language: language.clone(),\n\n key: &key,\n\n parsed,\n\n };\n\n translation_key.insert_parsed(data)?\n\n }\n\n None => println!(\n\n \"cargo:warning=Key `{}` exists in {} but not in fallback language\",\n\n key, language\n\n ),\n", "file_path": "rosetta-build/src/parser.rs", "rank": 67, "score": 13.084694273511516 }, { "content": " }\n\n }\n\n\n\n fn parse_string(value: String) -> Self {\n\n lazy_static! {\n\n static ref RE: Regex = Regex::new(r\"\\{([a-z_]+)\\}\").unwrap();\n\n }\n\n\n\n let matches: HashSet<_> = RE\n\n .captures_iter(&value)\n\n .map(|capture| capture[1].to_string())\n\n .collect();\n\n\n\n if matches.is_empty() {\n\n Self::Simple(value)\n\n } else {\n\n Self::Formatted {\n\n value,\n\n parameters: matches,\n\n }\n\n }\n\n }\n\n}\n\n\n\n/// Data associated with a parsed key.\n\n///\n\n/// Used in [`TranslationKey::insert_parsed`].\n", "file_path": "rosetta-build/src/parser.rs", "rank": 68, "score": 11.845823992109285 }, { "content": " };\n\n }\n\n\n\n Ok(())\n\n }\n\n}\n\n\n\n/// A parsed translation key\n\n///\n\n/// This enum can be constructed by parsing a translation file with [TranslationData].\n\n#[derive(Debug, Clone, PartialEq, Eq)]\n\npub(crate) enum TranslationKey {\n\n Simple(SimpleKey),\n\n Formatted(FormattedKey),\n\n}\n\n\n\nimpl TranslationKey {\n\n /// Initialize a new [TranslationKey] from a [`ParsedKey`]\n\n fn from_parsed(parsed: ParsedKey) -> Self {\n\n match parsed {\n", "file_path": "rosetta-build/src/parser.rs", "rank": 69, "score": 11.824043510341268 }, { "content": "#![cfg_attr(docsrs, feature(doc_cfg))]\n\n\n\nuse std::borrow::Cow;\n\n\n\n#[doc(hidden)]\n\npub mod provider;\n\n#[cfg(feature = \"serde\")]\n\n#[cfg_attr(docsrs, doc(cfg(feature = \"serde\")))]\n\npub mod serde_helpers;\n\n\n\n/// Include the generated translations.\n\n///\n\n/// The generated code will be included in the file as if it were a direct element of it.\n\n/// It is recommended to wrap the generated code in its own module:\n\n///\n\n/// ```ignore\n\n/// mod translations {\n\n/// rosetta_18n::include_translations!();\n\n/// }\n\n/// ```\n", "file_path": "rosetta-i18n/src/lib.rs", "rank": 70, "score": 11.756171047887202 }, { "content": " fn insert_parsed(&mut self, data: ParsedKeyData) -> Result<(), ParseError> {\n\n let (value, parameters) = match data.parsed {\n\n ParsedKey::Formatted { value, parameters } => (value, parameters),\n\n _ => {\n\n return Err(ParseError::InvalidType {\n\n key: data.key.into(),\n\n expected: \"formatted string\",\n\n })\n\n }\n\n };\n\n\n\n if parameters == self.parameters {\n\n self.others.insert(data.language, value);\n\n Ok(())\n\n } else {\n\n let missing: Vec<_> = self.parameters.difference(&parameters).cloned().collect();\n\n let unknown: Vec<_> = parameters.difference(&self.parameters).cloned().collect();\n\n\n\n Err(ParseError::InvalidParameters {\n\n key: data.key.into(),\n\n missing,\n\n unknown,\n\n })\n\n }\n\n }\n\n}\n\n\n\n/// Raw representation of a parsed file\n\n#[derive(Debug, Clone, PartialEq, Eq)]\n", "file_path": "rosetta-build/src/parser.rs", "rank": 71, "score": 11.301022948556074 }, { "content": "# Getting started\n\n\n\nThe following guide explains how to use `rosetta-i18` and `rosetta-build` to manage your translations.\n\nPlease refer to other sections in this documentation or to the API documentation for in depth explanations.\n\n\n\n## Installation\n\nRosetta is separated into two crates: `rosetta-i18n` and `rosetta-build`. To install both, add the following to your `Cargo.toml`:\n\n\n\n```toml\n\n[dependencies]\n\nrosetta-i18n = \"0.1\"\n\n\n\n[build-dependencies]\n\nrosetta-build = \"0.1\"\n\n```\n\n\n\n`rosetta-build` is used inside a build script and must be a build dependency.\n\n\n\n## Writing translations files\n\nRosetta use JSON translation files, which is similar to the one used by many other translation libraries and this widely supported.\n\nWe need to put these files somewhere, for example in a `/locales` directory.\n\n\n\n`locales/en.json`\n\n```json\n\n{\n\n \"hello\": \"Hello world!\",\n\n \"hello_name\": \"Hello {name}!\"\n\n}\n\n```\n\n\n\nIn this example, we defined two keys, `hello` and `hello_name`. The first is a static string, whereas the second contains the `name` variable which will be\n\nreplaced at runtime by the value of your choice.\n\n\n\nCreate a file for each language you want to be supported by your application. It is not required that all files contain all keys: we will define the fallback language later.\n\n\n", "file_path": "book/src/getting_started.md", "rank": 72, "score": 10.775651288004312 }, { "content": "# Useful extensions\n\n\n\nIf you are using [Visual Studio Code](https://code.visualstudio.com/), here is some useful extensions you can use.\n\n\n\n## Using with Rust Analyzer\n\n[rust-analyzer](https://rust-analyzer.github.io/) is a popular extension providing completion and more for Rust files.\n\nIf the generated code is not correctly loaded, add the following line to the `.vscode/settings.json` file:\n\n\n\n```json\n\n\"rust-analyzer.cargo.loadOutDirsFromCheck\": true\n\n```\n\n\n\n## Using with i18n ally\n\n[i18n ally](https://github.com/lokalise/i18n-ally) is an all-in-one i18n extension for VS Code that provide inline annotation of translated strings in your code.\n\n\n\n![i18n ally example usage](./i18n-ally.png)\n\n\n\n*i18n ally* supports [custom translations frameworks](https://github.com/lokalise/i18n-ally/wiki/Custom-Framework) by adding a simple config file.\n\nBecause code generated by Rosetta looks like any Rust method, the following configuration will consider that any method of a variable named `lang`\n\nor an enum named `Lang` is a translation key. It's not perfect as trait methods are also considered by the extension as translations keys, but it\n\nwork well in most case.\n\n\n\nCreate a `.vscode/i18n-ally-custom-framework.yml` file with the following content to enable Rosetta support. Edit this configuration if you are not\n\nusing `lang` as variable name.\n\n```yaml\n\n# .vscode/i18n-ally-custom-framework.yml\n\nlanguageIds:\n\n - rust\n\n\n\nusageMatchRegex:\n\n - \"[^\\\\w\\\\d]Lang::[A-z]+\\\\.([a-z_]+)\\\\(.*\\\\)\"\n\n - \"[^\\\\w\\\\d]lang\\\\.([a-z_]+)\\\\(.*\\\\)\"\n\n\n\n# If set to true, only enables this custom framework (will disable all built-in frameworks)\n\nmonopoly: true\n\n```\n", "file_path": "book/src/tips/extensions.md", "rank": 73, "score": 10.672875450823998 }, { "content": "//! Language data providers.\n\n//!\n\n//! This module contains types and traits for language data providers.\n\n//! Data providers are responsible of providing data to localize strings\n\n//! in given languages, such a plural rules.\n\n//!\n\n//! As Rosetta aims to be simple to use and maintain, we do not provide\n\n//! ready-to-use providers for every languages. We only provide a [`DefaultProvider`]\n\n//! which works for few common latin languages. However, you a free to implement\n\n//! providers for languages you need to support.\n\n//!\n\n//! ## Implementing a provider\n\n//! If you need to support extra languages that are not in the default provider,\n\n//! you should create a type that implement [`LanguageProvider`]. This type\n\n//! can then be used as a generic parameter of language type created by `rosetta-build`.\n\n//!\n\n//! Example implementation:\n\n//! ```\n\n//! use rosetta_i18n::{\n\n//! LanguageId,\n", "file_path": "rosetta-i18n/src/provider.rs", "rank": 74, "score": 10.482725689305395 }, { "content": "# Build options\n\n\n\nThe following is an exhaustive reference of all configurable build options.\n\n\n\nThese options are provided as methods of the [`RosettaBuilder`](https://docs.rs/rosetta-build/*/rosetta_build/struct.RosettaBuilder.html) type.\n\n\n\n**Required options :**\n\n- [`.fallback()`](https://docs.rs/rosetta-build/*/rosetta_build/struct.RosettaBuilder.html#method.fallback): register the fallback language with a given language identifier and path\n\n- [`.source()`](https://docs.rs/rosetta-build/*/rosetta_build/struct.RosettaBuilder.html#method.source): register an additional translation source with a given language identifier and path\n\n\n\n**Additional options :**\n\n- [`.name()`](https://docs.rs/rosetta-build/*/rosetta_build/struct.RosettaBuilder.html#method.name): use a custom name for the generate type (`Lang` by default)\n\n- [`.output()`](https://docs.rs/rosetta-build/*/rosetta_build/struct.RosettaBuilder.html#method.output): export the type in another output location (`OUT_DIR` by default)\n\n\n\nMore information in the [`RosettaBuilder` API documentation](https://docs.rs/rosetta-build/*/rosetta_build/struct.RosettaBuilder.html).\n", "file_path": "book/src/reference/build_options.md", "rank": 75, "score": 10.311246938522174 }, { "content": " match self {\n\n Self::En | Self::Es | Self::De | Self::It => match number {\n\n 1 => PluralCategory::One,\n\n _ => PluralCategory::Other,\n\n },\n\n Self::Fr => match number {\n\n 0 | 1 => PluralCategory::One,\n\n _ => PluralCategory::Other,\n\n },\n\n }\n\n }\n\n}\n", "file_path": "rosetta-i18n/src/provider.rs", "rank": 76, "score": 9.887671764082064 }, { "content": "//! Code generation\n\n//!\n\n//! # Generated code\n\n//! The generated code consists of a single enum (called by default `Lang`),\n\n//! which expose pub(crate)lic method for each of the translation keys. These\n\n//! methods returns a `&'static str` where possible, otherwise a `String`.\n\n//!\n\n//! # Usage\n\n//! The code generator is contained within the [`CodeGenerator`] struct.\n\n//! Calling [`generate`](CodeGenerator::generate) will produce a [TokenStream]\n\n//! with the generated code. Internal methods used to generate the output are not exposed.\n\n\n\nuse std::{\n\n collections::{HashMap, HashSet},\n\n iter::FromIterator,\n\n};\n\n\n\nuse convert_case::{Case, Casing};\n\nuse proc_macro2::{Ident, Span, TokenStream};\n\nuse quote::quote;\n", "file_path": "rosetta-build/src/gen.rs", "rank": 77, "score": 9.592794875740855 }, { "content": "# JSON file format\n\n\n\nThe following is an exhaustive reference of the [JSON](https://en.wikipedia.org/wiki/JSON) file format used for translations.\n\n\n\n> **Note:** nested keys are not yet available.\n\n\n\n## Simple key\n\nA simple translation key is a static string key without any variable interpolation. The `{` and `}` characters are not allowed.\n\n\n\n```json\n\n{\n\n \"simple\": \"Hello world!\"\n\n}\n\n```\n\n\n\n## String formatting\n\nYou can add variables inside keys to insert dynamic content at runtime. Variable name should be in `snake_case` surrounded by `{` and `}` characters.\n\n\n\n```json\n\n{\n\n \"formatted\": \"I like three things: {first}, {second} and Rust.\"\n\n}\n\n```\n\n\n\nYou can add as many parameters as you want. The same parameter can be inserted several times.\n\nLanguages that are not fallback languages **must** have the same parameters as the fallback language.\n", "file_path": "book/src/reference/json_format.md", "rank": 78, "score": 8.030985797908654 }, { "content": " self.fallback.1.to_string_lossy()\n\n );\n\n\n\n for (language, path) in &self.others {\n\n let content = open_file(path)?;\n\n parsed.parse_file(language.clone(), content)?;\n\n println!(\"cargo:rerun-if-changed={}\", path.to_string_lossy());\n\n }\n\n\n\n let generated = gen::CodeGenerator::new(&parsed, self).generate();\n\n\n\n let output = match &self.output {\n\n Some(path) => path.clone(),\n\n None => Path::new(&env::var(\"OUT_DIR\")?).join(\"rosetta_output.rs\"),\n\n };\n\n\n\n let mut file = File::create(&output)?;\n\n file.write_all(generated.to_string().as_bytes())?;\n\n\n\n if cfg!(feature = \"rustfmt\") {\n\n rustfmt(&output)?;\n\n }\n\n\n\n Ok(())\n\n }\n\n}\n\n\n", "file_path": "rosetta-build/src/builder.rs", "rank": 79, "score": 8.005112293137437 }, { "content": " ParsedKey::Simple(value) => TranslationKey::Simple(SimpleKey {\n\n fallback: value,\n\n others: HashMap::new(),\n\n }),\n\n ParsedKey::Formatted { value, parameters } => TranslationKey::Formatted(FormattedKey {\n\n fallback: value,\n\n others: HashMap::new(),\n\n parameters,\n\n }),\n\n }\n\n }\n\n\n\n /// Inserts a new raw [`ParsedKey`] in this [`TranslationKey`]\n\n fn insert_parsed(&mut self, data: ParsedKeyData) -> Result<(), ParseError> {\n\n match self {\n\n TranslationKey::Simple(inner) => inner.insert_parsed(data),\n\n TranslationKey::Formatted(inner) => inner.insert_parsed(data),\n\n }\n\n }\n\n}\n", "file_path": "rosetta-build/src/parser.rs", "rank": 80, "score": 7.412424310533758 }, { "content": "\n\nimpl From<ConfigError> for BuildError {\n\n fn from(error: ConfigError) -> Self {\n\n Self::Config(error)\n\n }\n\n}\n\n\n\nimpl From<ParseError> for BuildError {\n\n fn from(error: ParseError) -> Self {\n\n Self::Parse(error)\n\n }\n\n}\n\n\n\nimpl From<std::io::Error> for BuildError {\n\n fn from(error: std::io::Error) -> Self {\n\n Self::FileWrite(error)\n\n }\n\n}\n\n\n\nimpl From<std::env::VarError> for BuildError {\n", "file_path": "rosetta-build/src/error.rs", "rank": 81, "score": 7.15339923494674 }, { "content": "# Overview\n\n\n\nRosetta is an easy-to-use Rust [internationalization](https://en.wikipedia.org/wiki/Internationalization_and_localization)\n\nlibrary powered by code generation. Unlike other libraries, translation files are parsed and embedded into the\n\nresulting binary at build-time. This provide a better developer experience and reduce runtime overheat.\n\n\n\n\n\nUsing your translation files in your project is (almost) as easy as that:\n\n```rust\n\nrosetta_i18n::include_translations!();\n\n\n\nprintln!(\"{}\", Lang::En.hello(\"world\")); // Hello, world!\n\n```\n\n\n\nThe following documentation aims to provide an exhaustive guide about using Rosetta in your project.\n\nSee [Getting started](./getting_started.md) to get an usage overview.\n\n\n\n## Related links\n\nHere are all the links related to the project:\n\n\n\n- **[GitHub repository](https://github.com/baptiste0928/rosetta)** - where the development happen, feel free to contribute!\n\n- [`rosetta-i18n` on crates.io](https://crates.io/crates/rosetta-i18n) - main crate containing all useful runtime features.\n\n- [`rosetta-build` on crates.io](https://crates.io/crates/rosetta-build) - crate used for code generation.\n\n- [`rosetta-i18n`](https://docs.rs/rosetta-i18n/) and [`rosetta-build`](https://docs.rs/rosetta-build/) on **docs.rs** - up-to-date API documentation.\n\n\n\n> Please give a ⭐ to the GitHub repository if you use Rosetta.\n\n\n\n## Support\n\nIf you encounter bugs or need help using Rosetta, here's what to do:\n\n\n\n- **If you need help with Rosetta**, [open a new discussion](https://github.com/baptiste0928/rosetta/discussions) on the GitHub repository.\n\n- **To report a bug or suggest a new feature**, [open a new issue](https://github.com/baptiste0928/rosetta/issues) on the GitHub repository.\n\n\n", "file_path": "book/src/overview.md", "rank": 82, "score": 6.857384499006747 }, { "content": "//! ## CLDR Data\n\n//! The reference source for locale data is [Unicode CLDR], an exhaustive dataset\n\n//! containing information about plural cases, number formatting and many more for\n\n//! most languages in the world.\n\n//!\n\n//! Many i18n Rust libraries such as `intl_pluralrules` bundle data from CLDR, and\n\n//! others like `icu4x` must be configured with an external CLDR data source.\n\n//! However, as the CLDR dataset is large and we only need a small subset of it,\n\n//! we did not choose to use it directly: most applications use only a few languages,\n\n//! so implementing a data provider manually is not much work. If you need to use the\n\n//! entire CLDR dataset, Rosetta might not be the good choice for you.\n\n//!\n\n//! If you need to implement a custom language provider, **it is strongly recommended to rely on\n\n//! CLDR data**. You can easily find this online (e.g. [plural rules]).\n\n//!\n\n//! [Unicode CLDR]: https://cldr.unicode.org/\n\n//! [plural rules]: https://unicode-org.github.io/cldr-staging/charts/37/supplemental/language_plural_rules.html\n\n\n\nuse crate::LanguageId;\n\n\n\n/// Trait for language data providers.\n\n///\n\n/// This trait is implemented on types that provide data used\n\n/// to localize strings in a given language. See [`DefaultProvider`]\n\n/// for an example implementation.\n", "file_path": "rosetta-i18n/src/provider.rs", "rank": 83, "score": 6.813510317020549 }, { "content": "\n\nimpl Error for BuildError {}\n\n\n\nimpl Display for BuildError {\n\n fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {\n\n match self {\n\n BuildError::Config(error) => write!(f, \"invalid configuration: {}\", error),\n\n BuildError::FileRead { file, source } => {\n\n write!(f, \"failed to read `{:?}`: {}\", file, source)\n\n }\n\n BuildError::FileWrite(error) => write!(f, \"failed to write output: {}\", error),\n\n BuildError::JsonParse { file, source } => {\n\n write!(f, \"failed to load {:?}: {}\", file, source)\n\n }\n\n BuildError::Parse(error) => write!(f, \"failed to parse translations: {}\", error),\n\n BuildError::Var(error) => write!(f, \"failed to read environment variable: {}\", error),\n\n BuildError::Fmt(error) => write!(f, \"failed to run rustfmt: {}\", error),\n\n }\n\n }\n\n}\n", "file_path": "rosetta-build/src/error.rs", "rank": 84, "score": 5.955058024640261 }, { "content": "use std::{\n\n collections::HashMap,\n\n env,\n\n fmt::{self, Display},\n\n fs::File,\n\n io::Write,\n\n path::{Path, PathBuf},\n\n str::FromStr,\n\n};\n\n\n\nuse tinyjson::JsonValue;\n\n\n\nuse crate::{\n\n error::{BuildError, ConfigError},\n\n gen, parser,\n\n};\n\n\n\n/// Helper function that return an default [`RosettaBuilder`].\n", "file_path": "rosetta-build/src/builder.rs", "rank": 85, "score": 5.430497875506406 }, { "content": " ///\n\n /// Used in Arabic, Latvian, and others.\n\n Zero,\n\n /// One plural category.\n\n ///\n\n /// Used for the singular form in many languages.\n\n One,\n\n /// Two plural category.\n\n ///\n\n /// Used in Arabic, Hebrew, Slovenian, and others.\n\n Two,\n\n /// Few plural category.\n\n ///\n\n /// Used in Romanian, Polish, Russian, and others.\n\n Few,\n\n /// Many plural category.\n\n ///\n\n /// Used in Polish, Russian, Ukrainian, and others.\n\n Many,\n\n /// Other plural category, used as a catch-all.\n", "file_path": "rosetta-i18n/src/provider.rs", "rank": 86, "score": 5.36110931458553 }, { "content": "# rosetta-i18n\n\n[![Crates.io](https://img.shields.io/crates/v/rosetta-i18n)](https://crates.io/crates/rosetta-i18n)\n\n[![dependency status](https://deps.rs/repo/github/baptiste0928/rosetta/status.svg)](https://deps.rs/repo/github/baptiste0928/rosetta)\n\n[![docs.rs](https://img.shields.io/docsrs/rosetta-i18n)](https://docs.rs/rosetta-i18n/)\n\n[![CI](https://github.com/baptiste0928/rosetta/actions/workflows/ci.yaml/badge.svg?event=push)](https://github.com/baptiste0928/rosetta/actions/workflows/ci.yaml)\n\n\n\n**rosetta-i18n** is an easy-to-use and opinionated Rust internationalization (i18n) library powered by code generation.\n\n\n\n```rust\n\nrosetta_i18n::include_translations!();\n\n\n\nprintln!(Lang::En.hello(\"world\")); // Hello, world!\n\n```\n\n\n\n**[Documentation](https://baptiste0928.github.io/rosetta/)**\n\n\n\n## Features\n\n- **No runtime errors.** Translation files are parsed at build time, so your code will never fail due to translations anymore.\n\n- **No dependencies.** This crate aims to have the smallest runtime overheat compared to raw strings. There is no additional dependencies at runtime.\n\n- **Standard JSON format.** Translations are written in JSON file with a syntax used by many other i18n libraries. Therefore, most translation services support it out of the box.\n\n- **String formatting** is supported.\n\n\n\n## Installation\n\nRosetta is separated into two crates, `rosetta-i18n` and `rosetta-build`. To install both, add the following to your `Cargo.toml`:\n\n\n\n```toml\n\n[dependencies]\n\nrosetta-i18n = \"0.1\"\n\n\n\n[build-dependencies]\n\nrosetta-build = \"0.1\"\n\n```\n\n\n\n## Documentation\n\n\n\nThe documentation is available on https://baptiste0928.github.io/rosetta/.\n\n\n\nYou can also read the API documentation on *docs.rs*: [`rosetta-i18n`](https://docs.rs/rosetta-i18n/)\n\nand [`rosetta-build`](https://docs.rs/rosetta-build/).\n\n\n\n## Contributing\n\nThere is no particular contribution guidelines, feel free to open a new PR to improve the code. If you want to introduce a new feature, please create an issue before.\n", "file_path": "rosetta-build/README.md", "rank": 87, "score": 5.155351021002799 }, { "content": "# rosetta-i18n\n\n[![Crates.io](https://img.shields.io/crates/v/rosetta-i18n)](https://crates.io/crates/rosetta-i18n)\n\n[![dependency status](https://deps.rs/repo/github/baptiste0928/rosetta/status.svg)](https://deps.rs/repo/github/baptiste0928/rosetta)\n\n[![docs.rs](https://img.shields.io/docsrs/rosetta-i18n)](https://docs.rs/rosetta-i18n/)\n\n[![CI](https://github.com/baptiste0928/rosetta/actions/workflows/ci.yaml/badge.svg?event=push)](https://github.com/baptiste0928/rosetta/actions/workflows/ci.yaml)\n\n\n\n**rosetta-i18n** is an easy-to-use and opinionated Rust internationalization (i18n) library powered by code generation.\n\n\n\n```rust\n\nrosetta_i18n::include_translations!();\n\n\n\nprintln!(Lang::En.hello(\"world\")); // Hello, world!\n\n```\n\n\n\n**[Documentation](https://baptiste0928.github.io/rosetta/)**\n\n\n\n## Features\n\n- **No runtime errors.** Translation files are parsed at build time, so your code will never fail due to translations anymore.\n\n- **No dependencies.** This crate aims to have the smallest runtime overheat compared to raw strings. There is no additional dependencies at runtime.\n\n- **Standard JSON format.** Translations are written in JSON file with a syntax used by many other i18n libraries. Therefore, most translation services support it out of the box.\n\n- **String formatting** is supported.\n\n\n\n## Installation\n\nRosetta is separated into two crates, `rosetta-i18n` and `rosetta-build`. To install both, add the following to your `Cargo.toml`:\n\n\n\n```toml\n\n[dependencies]\n\nrosetta-i18n = \"0.1\"\n\n\n\n[build-dependencies]\n\nrosetta-build = \"0.1\"\n\n```\n\n\n\n## Documentation\n\n\n\nThe documentation is available on https://baptiste0928.github.io/rosetta/.\n\n\n\nYou can also read the API documentation on *docs.rs*: [`rosetta-i18n`](https://docs.rs/rosetta-i18n/)\n\nand [`rosetta-build`](https://docs.rs/rosetta-build/).\n\n\n\n## Contributing\n\nThere is no particular contribution guidelines, feel free to open a new PR to improve the code. If you want to introduce a new feature, please create an issue before.\n", "file_path": "rosetta-i18n/README.md", "rank": 88, "score": 5.155351021002799 }, { "content": "# rosetta-i18n\n\n[![Crates.io](https://img.shields.io/crates/v/rosetta-i18n)](https://crates.io/crates/rosetta-i18n)\n\n[![dependency status](https://deps.rs/repo/github/baptiste0928/rosetta/status.svg)](https://deps.rs/repo/github/baptiste0928/rosetta)\n\n[![docs.rs](https://img.shields.io/docsrs/rosetta-i18n)](https://docs.rs/rosetta-i18n/)\n\n[![CI](https://github.com/baptiste0928/rosetta/actions/workflows/ci.yaml/badge.svg?event=push)](https://github.com/baptiste0928/rosetta/actions/workflows/ci.yaml)\n\n\n\n**rosetta-i18n** is an easy-to-use and opinionated Rust internationalization (i18n) library powered by code generation.\n\n\n\n```rust\n\nrosetta_i18n::include_translations!();\n\n\n\nprintln!(Lang::En.hello(\"world\")); // Hello, world!\n\n```\n\n\n\n**[Documentation](https://baptiste0928.github.io/rosetta/)**\n\n\n\n## Features\n\n- **No runtime errors.** Translation files are parsed at build time, so your code will never fail due to translations anymore.\n\n- **No dependencies.** This crate aims to have the smallest runtime overheat compared to raw strings. There is no additional dependencies at runtime.\n\n- **Standard JSON format.** Translations are written in JSON file with a syntax used by many other i18n libraries. Therefore, most translation services support it out of the box.\n\n- **String formatting** is supported.\n\n\n\n## Installation\n\nRosetta is separated into two crates, `rosetta-i18n` and `rosetta-build`. To install both, add the following to your `Cargo.toml`:\n\n\n\n```toml\n\n[dependencies]\n\nrosetta-i18n = \"0.1\"\n\n\n\n[build-dependencies]\n\nrosetta-build = \"0.1\"\n\n```\n\n\n\n## Documentation\n\n\n\nThe documentation is available on https://baptiste0928.github.io/rosetta/.\n\n\n\nYou can also read the API documentation on *docs.rs*: [`rosetta-i18n`](https://docs.rs/rosetta-i18n/)\n\nand [`rosetta-build`](https://docs.rs/rosetta-build/).\n\n\n\n## Contributing\n\nThere is no particular contribution guidelines, feel free to open a new PR to improve the code. If you want to introduce a new feature, please create an issue before.\n", "file_path": "README.md", "rank": 89, "score": 5.155351021002799 }, { "content": "///\n\n/// This only works if the `rosetta-build` output file has been unmodified.\n\n/// Otherwise, use the following pattern to include the file:\n\n///\n\n/// ```ignore\n\n/// include!(\"/relative/path/to/rosetta_output.rs\");\n\n/// ```\n\n#[macro_export]\n\nmacro_rules! include_translations {\n\n () => {\n\n include!(concat!(env!(\"OUT_DIR\"), \"/rosetta_output.rs\"));\n\n };\n\n}\n\n\n\n/// Trait implemented by languages structs generated by `rosetta-build`.\n", "file_path": "rosetta-i18n/src/lib.rs", "rank": 90, "score": 4.066469013751265 }, { "content": "#[derive(Debug, Clone, PartialEq, Eq)]\n\nenum ParsedKey {\n\n /// Simple string key\n\n Simple(String),\n\n /// String key with formatted values\n\n ///\n\n /// Example : `Hello {name}!`\n\n Formatted {\n\n /// The raw key value\n\n value: String,\n\n /// List of parameters in the value\n\n parameters: HashSet<String>,\n\n },\n\n}\n\n\n\nimpl ParsedKey {\n\n /// Parse a JSON [`Value`] as a key\n\n fn parse(key: &str, value: JsonValue) -> Result<Self, ParseError> {\n\n match value {\n\n JsonValue::String(value) => Ok(Self::parse_string(value)),\n\n _ => Err(ParseError::InvalidValue { key: key.into() }),\n", "file_path": "rosetta-build/src/parser.rs", "rank": 91, "score": 3.5035047862751387 }, { "content": " }\n\n}\n\n\n\n/// Error type returned when the code generation failed for some reason.\n\n#[derive(Debug)]\n\npub enum BuildError {\n\n Config(ConfigError),\n\n FileRead {\n\n file: PathBuf,\n\n source: std::io::Error,\n\n },\n\n FileWrite(std::io::Error),\n\n JsonParse {\n\n file: PathBuf,\n\n source: tinyjson::JsonParseError,\n\n },\n\n Parse(ParseError),\n\n Var(std::env::VarError),\n\n Fmt(std::io::Error),\n\n}\n", "file_path": "rosetta-build/src/error.rs", "rank": 92, "score": 2.1102340099880417 } ]
Rust
src/store/encoding/raw/primitive_enc.rs
meerkatdb/meerkat
26ecee08251401fcb240fa6b8d382df590762eae
use std::convert::TryInto; use std::mem::size_of; use anyhow::Result; use async_trait::async_trait; use crate::store::encoding::bitmap_rle; use crate::store::encoding::{BlockEncoder, BlockSink}; use crate::store::indexing_buffer::PrimitiveBuffer; use crate::store::segment_metadata::column_layout::EncoderLayout; use crate::store::segment_metadata::NoLayout; use crate::store::encoding::varint::Encoder as _; pub struct Encoder<T> { remaining: PrimitiveBuffer<T>, encoded_data: Vec<u8>, bitmap_encoder: bitmap_rle::Encoder, min_block_size: usize, num_rows: u32, } impl<T: Send + Sync + Clone> Encoder<T> { pub fn new(block_size: usize, nullable: bool) -> Self { Self { remaining: PrimitiveBuffer::new(nullable), encoded_data: Vec::with_capacity(block_size as usize), bitmap_encoder: bitmap_rle::Encoder::new(), min_block_size: block_size, num_rows: 0, } } async fn write_block<S: BlockSink + Send>( &mut self, buf: &PrimitiveBuffer<T>, start: usize, end: usize, bit_pos: usize, sink: &mut S, ) -> Result<EncodeResult> { let result = encode_primitive_buffer( buf, start, end, bit_pos, &mut self.encoded_data, &mut self.bitmap_encoder, ); self.add_rows(result.num_rows); sink.write_block(self.num_rows - 1, &self.encoded_data) .await?; Ok(result) } async fn write_remaining<S: BlockSink + Send>(&mut self, sink: &mut S) -> Result<EncodeResult> { let result = encode_primitive_buffer( &self.remaining, 0, self.remaining.len(), 0, &mut self.encoded_data, &mut self.bitmap_encoder, ); self.add_rows(result.num_rows); sink.write_block(self.num_rows - 1, &self.encoded_data) .await?; Ok(result) } fn add_rows(&mut self, num_rows: usize) { self.num_rows = self .num_rows .checked_add((num_rows).try_into().expect("segment overflow")) .expect("segment overflow"); } } #[async_trait] impl<T: Send + Sync + Clone, S: BlockSink + Send> BlockEncoder<PrimitiveBuffer<T>, S> for Encoder<T> { async fn encode(&mut self, buffer: &PrimitiveBuffer<T>, sink: &mut S) -> Result<()> { let mut buf_pos = 0; let mut validity_pos = 0; if self.remaining.len() > 0 { let remaining_size = self.remaining.len() * std::mem::size_of::<T>(); let chunk_end = chunk(buffer, 0, self.min_block_size - remaining_size); validity_pos = self.remaining.append_from(buffer, 0, chunk_end, 0); buf_pos = chunk_end; if self.remaining.len() < self.min_block_size { return Ok(()); } self.write_remaining(sink).await?; self.remaining.clear(); } while buf_pos < buffer.len() { let chunk_end = chunk(buffer, buf_pos, self.min_block_size); let chunk_len = chunk_end - buf_pos; let chunk_size = chunk_len * size_of::<T>(); if chunk_size < self.min_block_size { self.remaining .append_from(buffer, buf_pos, chunk_end, validity_pos); return Ok(()); } let result = self .write_block(buffer, buf_pos, chunk_end, validity_pos, sink) .await?; buf_pos = chunk_end; validity_pos = result.last_validity_pos; } Ok(()) } async fn flush(&mut self, sink: &mut S) -> Result<EncoderLayout> { if self.remaining.len() > 0 { self.write_remaining(sink).await?; } Ok(EncoderLayout::Plain(NoLayout {})) } } fn encode_primitive_buffer<T: Clone>( buf: &PrimitiveBuffer<T>, start: usize, end: usize, bit_pos: usize, encoded_data: &mut Vec<u8>, bitmap_encoder: &mut bitmap_rle::Encoder, ) -> EncodeResult { encoded_data.clear(); let block_len = end - start; let block_size = size_of::<T>() * block_len; encoded_data.put_varint(block_size as u64); encoded_data.extend_from_slice(to_byte_slice(&buf.values()[start..end])); match buf.validity() { Some(ref mut validity) => { bitmap_encoder.clear(); let last_bit_pos = bitmap_encoder.put_from(validity, bit_pos, block_len); bitmap_encoder.flush(); encoded_data.extend_from_slice(bitmap_encoder.encoded_values()); EncodeResult { num_rows: last_bit_pos, last_validity_pos: last_bit_pos, } } None => EncodeResult { num_rows: block_len, last_validity_pos: 0, }, } } #[derive(Debug)] struct EncodeResult { num_rows: usize, last_validity_pos: usize, } fn chunk<T: Clone>(buffer: &PrimitiveBuffer<T>, start: usize, min_size: usize) -> usize { let chunk_len = min_size / size_of::<T>() + ((min_size % size_of::<T>() != 0) as usize); let end = start + chunk_len; if end > buffer.len() { return buffer.len(); } end } fn to_byte_slice<'a, T>(src: &'a [T]) -> &'a [u8] { unsafe { std::slice::from_raw_parts::<u8>( src.as_ptr() as *const u8, std::mem::size_of::<T>() * src.len(), ) } } #[cfg(test)] mod test { use crate::store::encoding::test::SinkMock; use super::*; #[tokio::test] async fn test_remaining() { let mut buf: PrimitiveBuffer<i32> = PrimitiveBuffer::new(true); buf.append(10); let mut sink_mock = SinkMock::new(); let mut encoder = Encoder::new(1000, true); encoder.encode(&buf, &mut sink_mock).await.unwrap(); assert_eq!(sink_mock.blocks.len(), 0); encoder.flush(&mut sink_mock).await.unwrap(); assert_eq!(sink_mock.blocks.len(), 1); } #[tokio::test] async fn test_encoder() { let mut buf: PrimitiveBuffer<i32> = PrimitiveBuffer::new(true); for i in 0..1005 { buf.append(i); } let mut sink_mock = SinkMock::new(); let mut encoder = Encoder::new(100, true); encoder.encode(&buf, &mut sink_mock).await.unwrap(); assert_eq!(sink_mock.blocks.len(), 40); encoder.flush(&mut sink_mock).await.unwrap(); assert_eq!(sink_mock.blocks.len(), 41); } }
use std::convert::TryInto; use std::mem::size_of; use anyhow::Result; use async_trait::async_trait; use crate::store::encoding::bitmap_rle; use crate::store::encoding::{BlockEncoder, BlockSink}; use crate::store::indexing_buffer::PrimitiveBuffer; use crate::store::segment_metadata::column_layout::EncoderLayout; use crate::store::segment_metadata::NoLayout; use crate::store::encoding::varint::Encoder as _; pub struct Encoder<T> { remaining: PrimitiveBuffer<T>, encoded_data: Vec<u8>, bitmap_encoder: bitmap_rle::Encoder, min_block_size: usize, num_rows: u32, } impl<T: Send + Sync + Clone> Encoder<T> { pub fn new(block_size: usize, nullable: bool) -> Self { Self { remaining: PrimitiveBuffer::new(nullable), encoded_data: Vec::with_capacity(block_size as usize), bitmap_encoder: bitmap_rle::Encoder::new(), min_block_size: block_size, num_rows: 0, } } async fn write_block<S: BlockSink + Send>( &mut self, buf: &PrimitiveBuffer<T>, start: usize, end: usize, bit_pos: usize, sink: &mut S, ) -> Result<EncodeResult> { let result = encode_primitive_buffer( buf, start, end, bit_pos, &mut self.encoded_data, &mut self.bitmap_encoder, ); self.add_rows(result.num_rows); sink.write_block(self.num_rows - 1, &self.encoded_data) .await?; Ok(result) } async fn write_remaining<S: BlockSink + Send>(&mut self, sink: &mut S) -> Result<EncodeResult> { let result =
; self.add_rows(result.num_rows); sink.write_block(self.num_rows - 1, &self.encoded_data) .await?; Ok(result) } fn add_rows(&mut self, num_rows: usize) { self.num_rows = self .num_rows .checked_add((num_rows).try_into().expect("segment overflow")) .expect("segment overflow"); } } #[async_trait] impl<T: Send + Sync + Clone, S: BlockSink + Send> BlockEncoder<PrimitiveBuffer<T>, S> for Encoder<T> { async fn encode(&mut self, buffer: &PrimitiveBuffer<T>, sink: &mut S) -> Result<()> { let mut buf_pos = 0; let mut validity_pos = 0; if self.remaining.len() > 0 { let remaining_size = self.remaining.len() * std::mem::size_of::<T>(); let chunk_end = chunk(buffer, 0, self.min_block_size - remaining_size); validity_pos = self.remaining.append_from(buffer, 0, chunk_end, 0); buf_pos = chunk_end; if self.remaining.len() < self.min_block_size { return Ok(()); } self.write_remaining(sink).await?; self.remaining.clear(); } while buf_pos < buffer.len() { let chunk_end = chunk(buffer, buf_pos, self.min_block_size); let chunk_len = chunk_end - buf_pos; let chunk_size = chunk_len * size_of::<T>(); if chunk_size < self.min_block_size { self.remaining .append_from(buffer, buf_pos, chunk_end, validity_pos); return Ok(()); } let result = self .write_block(buffer, buf_pos, chunk_end, validity_pos, sink) .await?; buf_pos = chunk_end; validity_pos = result.last_validity_pos; } Ok(()) } async fn flush(&mut self, sink: &mut S) -> Result<EncoderLayout> { if self.remaining.len() > 0 { self.write_remaining(sink).await?; } Ok(EncoderLayout::Plain(NoLayout {})) } } fn encode_primitive_buffer<T: Clone>( buf: &PrimitiveBuffer<T>, start: usize, end: usize, bit_pos: usize, encoded_data: &mut Vec<u8>, bitmap_encoder: &mut bitmap_rle::Encoder, ) -> EncodeResult { encoded_data.clear(); let block_len = end - start; let block_size = size_of::<T>() * block_len; encoded_data.put_varint(block_size as u64); encoded_data.extend_from_slice(to_byte_slice(&buf.values()[start..end])); match buf.validity() { Some(ref mut validity) => { bitmap_encoder.clear(); let last_bit_pos = bitmap_encoder.put_from(validity, bit_pos, block_len); bitmap_encoder.flush(); encoded_data.extend_from_slice(bitmap_encoder.encoded_values()); EncodeResult { num_rows: last_bit_pos, last_validity_pos: last_bit_pos, } } None => EncodeResult { num_rows: block_len, last_validity_pos: 0, }, } } #[derive(Debug)] struct EncodeResult { num_rows: usize, last_validity_pos: usize, } fn chunk<T: Clone>(buffer: &PrimitiveBuffer<T>, start: usize, min_size: usize) -> usize { let chunk_len = min_size / size_of::<T>() + ((min_size % size_of::<T>() != 0) as usize); let end = start + chunk_len; if end > buffer.len() { return buffer.len(); } end } fn to_byte_slice<'a, T>(src: &'a [T]) -> &'a [u8] { unsafe { std::slice::from_raw_parts::<u8>( src.as_ptr() as *const u8, std::mem::size_of::<T>() * src.len(), ) } } #[cfg(test)] mod test { use crate::store::encoding::test::SinkMock; use super::*; #[tokio::test] async fn test_remaining() { let mut buf: PrimitiveBuffer<i32> = PrimitiveBuffer::new(true); buf.append(10); let mut sink_mock = SinkMock::new(); let mut encoder = Encoder::new(1000, true); encoder.encode(&buf, &mut sink_mock).await.unwrap(); assert_eq!(sink_mock.blocks.len(), 0); encoder.flush(&mut sink_mock).await.unwrap(); assert_eq!(sink_mock.blocks.len(), 1); } #[tokio::test] async fn test_encoder() { let mut buf: PrimitiveBuffer<i32> = PrimitiveBuffer::new(true); for i in 0..1005 { buf.append(i); } let mut sink_mock = SinkMock::new(); let mut encoder = Encoder::new(100, true); encoder.encode(&buf, &mut sink_mock).await.unwrap(); assert_eq!(sink_mock.blocks.len(), 40); encoder.flush(&mut sink_mock).await.unwrap(); assert_eq!(sink_mock.blocks.len(), 41); } }
encode_primitive_buffer( &self.remaining, 0, self.remaining.len(), 0, &mut self.encoded_data, &mut self.bitmap_encoder, )
call_expression
[ { "content": "#[inline]\n\npub fn encode_varint(mut value: u64, buf: &mut [u8]) -> usize {\n\n let mut i = 0;\n\n while value >= 0x80 {\n\n buf[i] = ((value & 0x7F) | 0x80) as u8;\n\n value >>= 7;\n\n i += 1;\n\n }\n\n buf[i] = value as u8;\n\n i += 1;\n\n i\n\n}\n\n\n\n/// Decodes a LEB128-encoded variable length integer from the slice, returning the value and the\n\n/// number of bytes read.\n\n///\n\n/// Based loosely on [`ReadVarint64FromArray`][1].\n\n///\n\n/// ## Safety\n\n///\n\n/// The caller must ensure that `bytes` is non-empty and either `bytes.len() >= 10` or the last\n\n/// element in bytes is < `0x80`.\n\n///\n\n/// ## Note:\n\n///\n\n/// This is a safe version of the [`decode_varint_slice`][2]\n\n///\n\n/// [1]: https://github.com/google/protobuf/blob/3.3.x/src/google/protobuf/io/coded_stream.cc#L365-L406\n\n/// [2]: https://github.com/tokio-rs/prost/blob/c3b7037a7f2c56cef327b41ca32a8c4e9ce5a41c/src/encoding.rs#L80\n", "file_path": "src/store/encoding/varint.rs", "rank": 0, "score": 164679.53483326946 }, { "content": "#[inline]\n\npub fn decode_varint(buf: &[u8]) -> Result<(u64, usize)> {\n\n // Fully unrolled varint decoding loop. Splitting into 32-bit pieces gives better performance.\n\n\n\n let mut b: u8;\n\n let mut part0: u32;\n\n b = buf[0];\n\n part0 = u32::from(b);\n\n if b < 0x80 {\n\n return Ok((u64::from(part0), 1));\n\n };\n\n part0 -= 0x80;\n\n b = buf[1];\n\n part0 += u32::from(b) << 7;\n\n if b < 0x80 {\n\n return Ok((u64::from(part0), 2));\n\n };\n\n part0 -= 0x80 << 7;\n\n b = buf[2];\n\n part0 += u32::from(b) << 14;\n\n if b < 0x80 {\n", "file_path": "src/store/encoding/varint.rs", "rank": 1, "score": 161626.728660977 }, { "content": "pub fn decode(encoded_data: &[u8], decoded_data: &mut [u32]) {\n\n let mut decoder = Decoder::new(encoded_data, decoded_data);\n\n decoder.decode();\n\n}\n\n\n\n#[cfg(test)]\n\nmod test {\n\n use super::*;\n\n\n\n fn bit_positions(values: &[bool]) -> Vec<u32> {\n\n values\n\n .iter()\n\n .enumerate()\n\n .filter(|elem| *elem.1)\n\n .map(|elem| elem.0 as u32)\n\n .collect()\n\n }\n\n\n\n fn roundtrip_test(values: &[bool]) -> Vec<u8> {\n\n let bit_positions = bit_positions(values);\n", "file_path": "src/store/encoding/bitmap_rle.rs", "rank": 2, "score": 149210.05437160644 }, { "content": "pub fn ceil8(value: usize) -> usize {\n\n value / 8 + ((value % 8 != 0) as usize)\n\n}\n", "file_path": "src/store/encoding/util.rs", "rank": 4, "score": 106562.10059496657 }, { "content": "/// Returns the nearest multiple of `factor` that is `>=` than `num`. Here `factor` must\n\n/// be a power of 2.\n\npub fn round_upto_power_of_2(num: usize, factor: usize) -> usize {\n\n debug_assert!(factor > 0 && (factor & (factor - 1)) == 0);\n\n (num + (factor - 1)) & !(factor - 1)\n\n}\n\n\n", "file_path": "src/store/encoding/util.rs", "rank": 5, "score": 99836.06957984477 }, { "content": "#[inline]\n\npub fn encoded_len_varint(value: u64) -> usize {\n\n // Based on [VarintSize64][1].\n\n // [1]: https://github.com/google/protobuf/blob/3.3.x/src/google/protobuf/io/coded_stream.h#L1301-L1309\n\n ((((value | 1).leading_zeros() ^ 63) * 9 + 73) / 64) as usize\n\n}\n\n\n", "file_path": "src/store/encoding/varint.rs", "rank": 6, "score": 93101.27528709441 }, { "content": "pub fn chunk(buffer: &BinaryBuffer, start_pos: usize, min_size: u64) -> BinaryChunk {\n\n let start_offset = buffer.offsets()[start_pos];\n\n\n\n let maybe_end_pos = buffer.offsets()[start_pos..]\n\n .iter()\n\n .find_position(|offset| (*offset - start_offset) as u64 >= min_size);\n\n\n\n let (end_pos, end_offset) = match maybe_end_pos {\n\n Some(pos) => (pos.0, *pos.1),\n\n None => (\n\n buffer.offsets().len() - 1,\n\n buffer.offsets()[buffer.offsets().len() - 1],\n\n ),\n\n };\n\n\n\n BinaryChunk {\n\n start_pos,\n\n end_pos,\n\n start_offset,\n\n end_offset,\n", "file_path": "src/store/encoding/raw/binary_enc.rs", "rank": 7, "score": 92243.5647681646 }, { "content": "fn main() -> Result<(), String> {\n\n built::write_built_file().expect(\"Failed to acquire build-time information\");\n\n\n\n tonic_build::configure()\n\n .build_server(true)\n\n .build_client(true)\n\n .out_dir(\"src/store\")\n\n .compile(&[\"src/store/segment_metadata.proto\"], &[\"src/store/\"])\n\n .map_err(|err| format!(\"protobuf compilation failed: {}\", err))\n\n}\n", "file_path": "build.rs", "rank": 8, "score": 91676.17525526401 }, { "content": "#[async_trait]\n\npub trait BlockSink {\n\n async fn write_block(&mut self, row_id: u32, block_data: &[u8]) -> Result<()>;\n\n}\n\n\n", "file_path": "src/store/encoding/mod.rs", "rank": 9, "score": 88011.62181280783 }, { "content": "pub fn new_u64_encoder<S>(\n\n encoder: Encoding,\n\n block_size: usize,\n\n nullable: bool,\n\n) -> Result<Box<dyn BlockEncoder<Uint64Buffer, S>>>\n\nwhere\n\n S: BlockSink + Send,\n\n{\n\n match encoder {\n\n Encoding::Raw => Ok(Box::new(raw::primitive_enc::Encoder::new(\n\n block_size, nullable,\n\n ))),\n\n _ => Err(anyhow!(\"invalid encoder for u64 data {:?}\", encoder)),\n\n }\n\n}\n\n\n", "file_path": "src/store/encoding/mod.rs", "rank": 11, "score": 76984.19069944591 }, { "content": "pub fn new_f64_encoder<S>(\n\n encoder: Encoding,\n\n block_size: usize,\n\n nullable: bool,\n\n) -> Result<Box<dyn BlockEncoder<Float64Buffer, S>>>\n\nwhere\n\n S: BlockSink + Send,\n\n{\n\n match encoder {\n\n Encoding::Raw => Ok(Box::new(raw::primitive_enc::Encoder::new(\n\n block_size, nullable,\n\n ))),\n\n _ => Err(anyhow!(\"invalid encoder for f64 data {:?}\", encoder)),\n\n }\n\n}\n\n\n", "file_path": "src/store/encoding/mod.rs", "rank": 12, "score": 76984.19069944591 }, { "content": "pub fn new_binary_encoder<S>(\n\n encoder: Encoding,\n\n block_size: u32,\n\n nullable: bool,\n\n) -> Result<Box<dyn BlockEncoder<BinaryBuffer, S>>>\n\nwhere\n\n S: BlockSink + Send,\n\n{\n\n match encoder {\n\n Encoding::Snappy => Ok(Box::new(snappy::snappy_enc::Encoder::new(\n\n block_size, nullable,\n\n ))),\n\n Encoding::Raw => Ok(Box::new(raw::binary_enc::Encoder::new(\n\n block_size, nullable,\n\n ))),\n\n _ => Err(anyhow!(\"invalid encoder for binary data {:?}\", encoder)),\n\n }\n\n}\n\n\n\n#[cfg(test)]\n", "file_path": "src/store/encoding/mod.rs", "rank": 13, "score": 76984.19069944591 }, { "content": "pub fn new_i32_encoder<S>(\n\n encoder: Encoding,\n\n block_size: usize,\n\n nullable: bool,\n\n) -> Result<Box<dyn BlockEncoder<Int32Buffer, S>>>\n\nwhere\n\n S: BlockSink + Send,\n\n{\n\n match encoder {\n\n Encoding::Raw => Ok(Box::new(raw::primitive_enc::Encoder::new(\n\n block_size, nullable,\n\n ))),\n\n _ => Err(anyhow!(\"invalid encoder for i32 data {:?}\", encoder)),\n\n }\n\n}\n\n\n", "file_path": "src/store/encoding/mod.rs", "rank": 14, "score": 76984.19069944591 }, { "content": "pub fn new_i64_encoder<S>(\n\n encoder: Encoding,\n\n block_size: usize,\n\n nullable: bool,\n\n) -> Result<Box<dyn BlockEncoder<Int64Buffer, S>>>\n\nwhere\n\n S: BlockSink + Send,\n\n{\n\n match encoder {\n\n Encoding::Raw => Ok(Box::new(raw::primitive_enc::Encoder::new(\n\n block_size, nullable,\n\n ))),\n\n _ => Err(anyhow!(\"invalid encoder for i64 data {:?}\", encoder)),\n\n }\n\n}\n\n\n", "file_path": "src/store/encoding/mod.rs", "rank": 15, "score": 76984.19069944591 }, { "content": "#[async_trait]\n\npub trait BlockEncoder<B, S: BlockSink> {\n\n async fn encode(&mut self, buffer: &B, sink: &mut S) -> Result<()>;\n\n async fn flush(&mut self, sink: &mut S) -> Result<EncoderLayout>;\n\n}\n\n\n", "file_path": "src/store/encoding/mod.rs", "rank": 16, "score": 74553.8712098914 }, { "content": "#[derive(Debug)]\n\nstruct EncodeResult {\n\n num_rows: usize,\n\n last_validity_pos: usize,\n\n}\n\n\n", "file_path": "src/store/encoding/raw/binary_enc.rs", "rank": 18, "score": 71981.7040968837 }, { "content": "#[derive(Debug, StructOpt)]\n\nstruct Args {\n\n /// The directory where MeerkatDB stores its data\n\n #[structopt(long, env = \"MK_DB_PATH\", parse(from_os_str))]\n\n db_path: PathBuf,\n\n /// The gossip port.\n\n #[structopt(long, default_value = \"7775\", env = \"MK_GOSSIP_PORT\")]\n\n gossip_port: u16,\n\n /// Comma-separated list of public IP addresses or hostnames\n\n /// used for bootstrapping new nodes.\n\n #[structopt(long, env = \"MK_SEEDS\")]\n\n seeds: Option<String>,\n\n}\n\n\n\nconst NO_VERSION_HELP_TEMPLATE: &str = \"\n\nUSAGE:\n\n {usage}\n\n\n\n{all-args}\";\n\n\n", "file_path": "src/main.rs", "rank": 19, "score": 52205.53550493117 }, { "content": "fn main() {\n\n println!(\"meerkat {}\", build::short_info());\n\n\n\n let long_info = build::long_info();\n\n\n\n let clap = Args::clap()\n\n .version(long_info.as_ref())\n\n .global_setting(AppSettings::UnifiedHelpMessage)\n\n .template(NO_VERSION_HELP_TEMPLATE);\n\n\n\n let args = Args::from_clap(&clap.get_matches());\n\n\n\n let conf = Config {\n\n db_path: args.db_path,\n\n gossip_port: args.gossip_port,\n\n seeds: args\n\n .seeds\n\n .unwrap_or_default()\n\n .split(',')\n\n .map(|s| s.trim().to_string())\n\n .collect(),\n\n };\n\n\n\n let mut server = server::Meerkat::new(conf);\n\n\n\n // TODO(gvelo): add panic handler, signal handlers, etc.\n\n\n\n server.start();\n\n}\n", "file_path": "src/main.rs", "rank": 20, "score": 46991.78108762704 }, { "content": "/// byte-aligned bitmap RLE decoder.\n\n/// The current implementation decode the bitmap to a sorted lists of integers\n\n/// corresponding to the positions of the set bits.\n\nstruct Decoder<'a> {\n\n encoded_data: &'a [u8],\n\n decoded_data: &'a mut [u32],\n\n encoded_data_pos: usize,\n\n decoded_data_pos: usize,\n\n bitmap_pos: u32,\n\n}\n\n\n\nimpl<'a> Decoder<'a> {\n\n /// Return a new decoder.\n\n /// `decoded_data` should have enough room to accommodate the decoded values\n\n /// otherwise `decode()` will panic.\n\n pub fn new(encoded_data: &'a [u8], decoded_data: &'a mut [u32]) -> Self {\n\n Self {\n\n encoded_data,\n\n decoded_data,\n\n encoded_data_pos: 0,\n\n decoded_data_pos: 0,\n\n bitmap_pos: 0,\n\n }\n", "file_path": "src/store/encoding/bitmap_rle.rs", "rank": 21, "score": 46963.81236849515 }, { "content": "pub trait Encoder {\n\n fn put_varint(&mut self, value: u64);\n\n}\n\n\n\nimpl Encoder for Vec<u8> {\n\n fn put_varint(&mut self, value: u64) {\n\n let mut buf = [0u8; MAX_VARINT_LEN];\n\n let enc_len = encode_varint(value, buf.as_mut_slice());\n\n self.extend_from_slice(&buf[..enc_len]);\n\n }\n\n}\n\n\n\n#[cfg(test)]\n\nmod test {\n\n use super::*;\n\n\n\n #[test]\n\n fn varint() {\n\n fn check(value: u64, expected_bytes: &[u8]) {\n\n let mut buf: [u8; MAX_VARINT_LEN] = [0; MAX_VARINT_LEN];\n", "file_path": "src/store/encoding/varint.rs", "rank": 22, "score": 42642.64779744456 }, { "content": "#[async_trait]\n\npub trait BlockReader {\n\n type Buf: AsRef<[u8]>;\n\n\n\n /// Read a single block.\n\n async fn read_block(&self, range: BlockRange) -> io::Result<Self::Buf>;\n\n\n\n /// Read a batch of Blocks.\n\n /// Blocks are returned in the same order as read_ops\n\n fn read_blocks(\n\n &self,\n\n read_ops: Vec<ReadOp>,\n\n ) -> BoxStream<'_, Result<Block<Self::Buf>, BlockError>>;\n\n fn len(&self) -> u64;\n\n}\n\n\n\n/// Helper fn brought from tokio::fs to asyncify some IO operations.\n\nasync fn asyncify<F, T>(f: F) -> io::Result<T>\n\nwhere\n\n F: FnOnce() -> io::Result<T> + Send + 'static,\n\n T: Send + 'static,\n", "file_path": "src/store/io/mod.rs", "rank": 23, "score": 41634.289899558564 }, { "content": "fn encode_binary_buffer(\n\n buf: &BinaryBuffer,\n\n chunk: &BinaryChunk,\n\n bit_pos: usize,\n\n encoded_data: &mut Vec<u8>,\n\n offset_deltas: &mut Vec<u32>,\n\n bitmap_encoder: &mut bitmap_rle::Encoder,\n\n offset_encoder: &mut OffsetEncoder,\n\n) -> EncodeResult {\n\n encoded_data.clear();\n\n\n\n encoded_data.put_varint(chunk.size as u64);\n\n encoded_data\n\n .extend_from_slice(&buf.data()[chunk.start_offset as usize..chunk.end_offset as usize]);\n\n\n\n offset_deltas.clear();\n\n\n\n // add the offsets deltas.\n\n for i in chunk.start_pos..chunk.end_pos {\n\n offset_deltas.push(buf.item_len(i));\n", "file_path": "src/store/encoding/raw/binary_enc.rs", "rank": 24, "score": 40603.49774904359 }, { "content": "#[async_trait]\n\npub trait ColumnIndex<B> {\n\n fn index(&mut self, buffer: &B) -> Result<()>;\n\n async fn flush(&mut self, writer: &mut BlockWriter) -> Result<ColumnIndexLayout>;\n\n}\n", "file_path": "src/store/index/mod.rs", "rank": 25, "score": 39587.84828149916 }, { "content": "/// Index and write the blocks produced by the encoder.\n\npub struct BlockSinkImpl<'a> {\n\n data_writer: &'a mut BlockWriter,\n\n block_index: &'a mut BlockIndex,\n\n}\n\n\n\nimpl<'a> BlockSinkImpl<'a> {\n\n pub fn new(block_writer: &'a mut BlockWriter, block_index: &'a mut BlockIndex) -> Self {\n\n Self {\n\n data_writer: block_writer,\n\n block_index: block_index,\n\n }\n\n }\n\n pub fn block_index(&mut self) -> &mut BlockIndex {\n\n self.block_index\n\n }\n\n}\n\n\n\n#[async_trait]\n\nimpl BlockSink for BlockSinkImpl<'_> {\n\n async fn write_block(&mut self, row_id: u32, block_data: &[u8]) -> Result<()> {\n\n self.data_writer.write_block(block_data).await?;\n\n self.block_index.index_block(row_id, self.data_writer.pos());\n\n Ok(())\n\n }\n\n}\n", "file_path": "src/store/block_sink.rs", "rank": 27, "score": 29700.7347786216 }, { "content": "// Copyright 2021 The Meerkat Authors\n\n// Licensed under the Apache License, Version 2.0 (the \"License\");\n\n// you may not use this file except in compliance with the License.\n\n// You may obtain a copy of the License at\n\n//\n\n// http://www.apache.org/licenses/LICENSE-2.0\n\n//\n\n// Unless required by applicable law or agreed to in writing, software\n\n// distributed under the License is distributed on an \"AS IS\" BASIS,\n\n// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n\n// See the License for the specific language governing permissions and\n\n// limitations under the License.\n\n\n\nuse anyhow::Result;\n\nuse async_trait::async_trait;\n\n\n\nuse crate::store::block_index::BlockIndex;\n\nuse crate::store::encoding::BlockSink;\n\nuse crate::store::io::BlockWriter;\n\n\n", "file_path": "src/store/block_sink.rs", "rank": 28, "score": 29691.495800033255 }, { "content": "pub struct Encoder {}\n\n\n\nimpl Encoder {\n\n pub fn new(block_size: u32, nullable: bool) -> Self {\n\n Self {}\n\n }\n\n}\n\n\n\n#[async_trait]\n\nimpl<S: BlockSink + Send> BlockEncoder<BinaryBuffer, S> for Encoder {\n\n async fn encode(&mut self, buffer: &BinaryBuffer, sink: &mut S) -> anyhow::Result<()> {\n\n sink.write_block(43243, b\"snappy\").await?;\n\n Ok(())\n\n }\n\n\n\n async fn flush(&mut self, sink: &mut S) -> anyhow::Result<EncoderLayout> {\n\n Ok(EncoderLayout::Snappy(NoLayout {}))\n\n }\n\n}\n", "file_path": "src/store/encoding/snappy/snappy_enc.rs", "rank": 30, "score": 28.451373239974718 }, { "content": " .await?;\n\n\n\n Ok(result)\n\n }\n\n\n\n async fn write_remaining<S: BlockSink + Send>(&mut self, sink: &mut S) -> Result<EncodeResult> {\n\n let chunk = BinaryChunk {\n\n start_pos: 0,\n\n end_pos: self.remaining.offsets().len() - 1,\n\n start_offset: 0,\n\n end_offset: *self.remaining.offsets().last().unwrap(),\n\n size: *self.remaining.offsets().last().unwrap(),\n\n len: self.remaining.len(),\n\n };\n\n\n\n let result = encode_binary_buffer(\n\n &self.remaining,\n\n &chunk,\n\n 0,\n\n &mut self.encoded_data,\n", "file_path": "src/store/encoding/raw/binary_enc.rs", "rank": 34, "score": 23.25472648090225 }, { "content": "\n\n async fn read_block(&self, range: BlockRange) -> io::Result<Self::Buf> {\n\n let file = self.file.clone();\n\n asyncify(move || {\n\n let buf_len = range.end - range.start;\n\n let mut buf: Vec<u8> = vec![0; buf_len as usize];\n\n file.read_exact_at(buf.as_mut_slice(), range.start)\n\n .map(|_| buf)\n\n })\n\n .await\n\n }\n\n\n\n fn read_blocks(\n\n &self,\n\n read_ops: Vec<ReadOp>,\n\n ) -> BoxStream<'_, Result<Block<Self::Buf>, BlockError>> {\n\n iter(read_ops)\n\n .map(move |op| async move { (self.read_block(op.block_range.to_owned()).await, op) })\n\n .buffered(BLOCK_BUFFER_SIZE)\n\n .map(|op_result| match op_result.0 {\n", "file_path": "src/store/io/unix_disk_block_reader.rs", "rank": 35, "score": 22.862870289152273 }, { "content": "\n\n#[async_trait]\n\nimpl<S: BlockSink + Send> BlockEncoder<BinaryBuffer, S> for Encoder {\n\n async fn encode(&mut self, buffer: &BinaryBuffer, sink: &mut S) -> Result<()> {\n\n let mut buf_pos = 0;\n\n let mut validity_pos = 0;\n\n\n\n if self.remaining.len() > 0 {\n\n let remaining_size = self.remaining.data().len();\n\n\n\n let chunk = chunk(buffer, 0, self.min_block_size - remaining_size as u64);\n\n\n\n validity_pos = self\n\n .remaining\n\n .append_from(buffer, chunk.start_pos, chunk.end_pos, 0);\n\n buf_pos = chunk.end_pos;\n\n\n\n if self.remaining.data().len() < self.min_block_size as usize {\n\n return Ok(());\n\n }\n", "file_path": "src/store/encoding/raw/binary_enc.rs", "rank": 36, "score": 22.569678130179337 }, { "content": " size: end_offset - start_offset,\n\n len: end_pos - start_pos,\n\n }\n\n}\n\n\n\n#[cfg(test)]\n\nmod test {\n\n use super::*;\n\n use crate::store::encoding::test::SinkMock;\n\n\n\n #[tokio::test]\n\n async fn test_remaining() {\n\n let mut buf = BinaryBuffer::new(true);\n\n buf.append(b\"test\");\n\n let mut sink_mock = SinkMock::new();\n\n let mut encoder = Encoder::new(1000, true);\n\n encoder.encode(&buf, &mut sink_mock).await.unwrap();\n\n assert_eq!(sink_mock.blocks.len(), 0);\n\n encoder.flush(&mut sink_mock).await.unwrap();\n\n assert_eq!(sink_mock.blocks.len(), 1);\n", "file_path": "src/store/encoding/raw/binary_enc.rs", "rank": 37, "score": 21.61827314582031 }, { "content": " /// Append a null value to the buffer.\n\n /// This methos will panic if the buffer is not nullable.\n\n pub fn append_null(&mut self) {\n\n match self.validity {\n\n Some(ref mut validity) => validity.append(false),\n\n None => panic!(\"null append on non-nullable buffer\"),\n\n }\n\n }\n\n\n\n pub fn append_from(\n\n &mut self,\n\n buf: &PrimitiveBuffer<T>,\n\n start: usize,\n\n end: usize,\n\n validity_pos: usize,\n\n ) -> usize {\n\n self.values.extend_from_slice(&buf.values[start..end]);\n\n\n\n assert!(u32::MAX as usize > self.values.len());\n\n\n", "file_path": "src/store/indexing_buffer.rs", "rank": 38, "score": 20.367708196852757 }, { "content": " }\n\n }\n\n\n\n pub fn item_len(&self, idx: usize) -> u32 {\n\n self.offsets[idx + 1] - self.offsets[idx]\n\n }\n\n\n\n pub fn append_from(\n\n &mut self,\n\n buf: &BinaryBuffer,\n\n start: usize,\n\n end: usize,\n\n validity_pos: usize,\n\n ) -> usize {\n\n let start_offset = buf.offsets[start];\n\n let end_offset = buf.offsets[end];\n\n let chunk_len = end - start;\n\n\n\n let mut last_item_offset = *self.offsets.last().unwrap_or(&0u32);\n\n\n", "file_path": "src/store/indexing_buffer.rs", "rank": 39, "score": 20.256391580932537 }, { "content": " async fn write_block<S: BlockSink + Send>(\n\n &mut self,\n\n buf: &BinaryBuffer,\n\n chunk: &BinaryChunk,\n\n bit_pos: usize,\n\n sink: &mut S,\n\n ) -> Result<EncodeResult> {\n\n let result = encode_binary_buffer(\n\n buf,\n\n chunk,\n\n bit_pos,\n\n &mut self.encoded_data,\n\n &mut self.offset_deltas,\n\n &mut self.bitmap_encoder,\n\n &mut self.offset_encoder,\n\n );\n\n\n\n self.add_rows(result.num_rows);\n\n\n\n sink.write_block(self.num_rows - 1, &self.encoded_data)\n", "file_path": "src/store/encoding/raw/binary_enc.rs", "rank": 40, "score": 19.564552091140968 }, { "content": "\n\n /// Wait for pending operations and flushes all internal buffers.\n\n pub async fn flush(&mut self) -> std::io::Result<()> {\n\n self.file.flush().await\n\n }\n\n\n\n /// Sync all OS-internal metadata to disk.\n\n /// This function will attempt to ensure that all in-core data reaches\n\n /// the filesystem before returning.\n\n pub async fn sync(&mut self) -> std::io::Result<()> {\n\n self.file.sync_all().await\n\n }\n\n\n\n pub fn pos(&self) -> u64 {\n\n self.pos\n\n }\n\n}\n", "file_path": "src/store/io/default_block_writer.rs", "rank": 41, "score": 18.892454816076466 }, { "content": " .await\n\n .context(\"cannot flush data file\")\n\n }\n\n\n\n /// Sync all in-memory data to disk.\n\n async fn sync(mut self) -> Result<()> {\n\n self.index_writer\n\n .sync()\n\n .await\n\n .context(\"cannot sync index file\")?;\n\n self.data_writer\n\n .sync()\n\n .await\n\n .context(\"cannot sync data file\")\n\n }\n\n}\n\n\n\n/// Used to write a single column to the segment.\n\npub struct ColumnWriter<'a, B> {\n\n column_info: ColumnInfo,\n", "file_path": "src/store/segment_writer.rs", "rank": 42, "score": 18.782176259411028 }, { "content": " Ok(())\n\n }\n\n\n\n async fn flush(&mut self, sink: &mut S) -> Result<EncoderLayout> {\n\n if self.remaining.len() > 0 {\n\n self.write_remaining(sink).await?;\n\n }\n\n\n\n Ok(EncoderLayout::Plain(NoLayout {}))\n\n }\n\n}\n\n\n\n#[derive(Debug)]\n", "file_path": "src/store/encoding/raw/binary_enc.rs", "rank": 43, "score": 18.685494798882228 }, { "content": " pub async fn close(&mut self) -> Result<()> {\n\n let encoder_layout = self.encoder.flush(&mut self.block_sink).await?;\n\n\n\n let block_ndex_layout = self\n\n .block_sink\n\n .block_index()\n\n .flush(&mut self.index_writer)\n\n .await?;\n\n\n\n let column_index_layout = match self.column_index {\n\n Some(ref mut column_index) => Some(column_index.flush(&mut self.index_writer).await?),\n\n None => None,\n\n };\n\n\n\n // TODO(gvelo): add missing stats.\n\n let column_meta = segment_metadata::ColumnMeta {\n\n name: self.column_info.name.clone(),\n\n column_type: self.column_info.column_type.into(),\n\n nullable: self.column_info.nullable,\n\n encoding: self.column_info.encoding.into(),\n", "file_path": "src/store/segment_writer.rs", "rank": 44, "score": 18.452676328421212 }, { "content": "\n\n self.write_remaining(sink).await?;\n\n\n\n self.remaining.clear();\n\n }\n\n\n\n while buf_pos < buffer.offsets().len() {\n\n let chunk = chunk(&buffer, buf_pos, self.min_block_size);\n\n if (chunk.size as u64) < self.min_block_size {\n\n self.remaining\n\n .append_from(buffer, chunk.start_pos, chunk.end_pos, validity_pos);\n\n return Ok(());\n\n }\n\n\n\n let result = self.write_block(buffer, &chunk, validity_pos, sink).await?;\n\n\n\n buf_pos = chunk.end_pos;\n\n validity_pos = result.last_validity_pos;\n\n }\n\n\n", "file_path": "src/store/encoding/raw/binary_enc.rs", "rank": 45, "score": 17.416607245873376 }, { "content": "mod test {\n\n use super::*;\n\n\n\n #[derive(Debug)]\n\n pub struct CapturedBlock {\n\n row_id: u32,\n\n block_data: Vec<u8>,\n\n }\n\n\n\n pub struct SinkMock {\n\n pub blocks: Vec<CapturedBlock>,\n\n }\n\n\n\n impl SinkMock {\n\n pub fn new() -> Self {\n\n Self { blocks: Vec::new() }\n\n }\n\n }\n\n\n\n #[async_trait]\n", "file_path": "src/store/encoding/mod.rs", "rank": 46, "score": 17.37586659570281 }, { "content": " metadata: &'a mut Metadata,\n\n block_sink: BlockSinkImpl<'a>,\n\n index_writer: &'a mut BlockWriter,\n\n encoder: Box<dyn BlockEncoder<B, BlockSinkImpl<'a>>>,\n\n column_index: Option<Box<dyn ColumnIndex<B>>>,\n\n}\n\n\n\nimpl<'a, B> ColumnWriter<'a, B> {\n\n /// Index a Buffer.\n\n pub async fn write(&mut self, buf: &B) -> Result<()> {\n\n self.encoder.encode(buf, &mut self.block_sink).await?;\n\n\n\n if let Some(ref mut column_index) = self.column_index {\n\n column_index.index(&buf)?;\n\n }\n\n\n\n Ok(())\n\n }\n\n\n\n /// Close the ColumnWriter and flush indexes data to disk.\n", "file_path": "src/store/segment_writer.rs", "rank": 48, "score": 17.062083830252142 }, { "content": "/// Note: This writer perform a `spawn_blocking()` call for every block write to\n\n/// asyncify the operation. This is probably very inefficient.\n\n/// Future implementations will take advantage of the new `io_uring` API or\n\n/// use `AIO/DIO`.\n\npub struct Writer {\n\n file: File,\n\n pos: u64,\n\n}\n\n\n\nimpl Writer {\n\n pub async fn new(path: impl AsRef<Path>) -> std::io::Result<Self> {\n\n let file = File::create(path).await?;\n\n Ok(Self { file: file, pos: 0 })\n\n }\n\n\n\n /// Write a single block to disk.\n\n pub async fn write_block(&mut self, block: &[u8]) -> std::io::Result<()> {\n\n self.pos += block.len() as u64;\n\n self.file.write_all(block).await\n\n }\n", "file_path": "src/store/io/default_block_writer.rs", "rank": 49, "score": 16.35173072054909 }, { "content": " offset_deltas: Vec<u32>,\n\n bitmap_encoder: bitmap_rle::Encoder,\n\n offset_encoder: OffsetEncoder,\n\n min_block_size: u64,\n\n num_rows: u32,\n\n}\n\n\n\nimpl Encoder {\n\n pub fn new(block_size: u32, nullable: bool) -> Self {\n\n Self {\n\n remaining: BinaryBuffer::new(nullable),\n\n encoded_data: Vec::with_capacity(block_size as usize),\n\n offset_deltas: Vec::with_capacity(1024),\n\n bitmap_encoder: bitmap_rle::Encoder::new(),\n\n offset_encoder: OffsetEncoder::new(),\n\n min_block_size: block_size as u64,\n\n num_rows: 0,\n\n }\n\n }\n\n\n", "file_path": "src/store/encoding/raw/binary_enc.rs", "rank": 50, "score": 16.042024504524445 }, { "content": " }\n\n\n\n #[tokio::test]\n\n async fn test_encoder() {\n\n let mut buf = BinaryBuffer::new(true);\n\n buf.append(b\"test1\");\n\n buf.append(b\"test2\");\n\n buf.append(b\"test3\");\n\n let mut sink_mock = SinkMock::new();\n\n let mut encoder = Encoder::new(10, true);\n\n encoder.encode(&buf, &mut sink_mock).await.unwrap();\n\n assert_eq!(sink_mock.blocks.len(), 1);\n\n encoder.flush(&mut sink_mock).await.unwrap();\n\n assert_eq!(sink_mock.blocks.len(), 2);\n\n }\n\n}\n", "file_path": "src/store/encoding/raw/binary_enc.rs", "rank": 51, "score": 15.96785645836117 }, { "content": "\n\nimpl BoolBuffer {\n\n pub fn new(nullable: bool) -> Self {\n\n let validity = match nullable {\n\n true => Some(Bitmap::new()),\n\n false => None,\n\n };\n\n\n\n Self {\n\n values: Bitmap::new(),\n\n validity: validity,\n\n len: 0,\n\n }\n\n }\n\n\n\n /// Append a new non-null value to the buffer.\n\n pub fn append(&mut self, value: bool) {\n\n self.values.append(value);\n\n if let Some(ref mut validity) = self.validity {\n\n validity.append(true);\n", "file_path": "src/store/indexing_buffer.rs", "rank": 53, "score": 15.472928404296958 }, { "content": " }\n\n}\n\n\n\n#[derive(Debug)]\n\npub struct BinaryChunk {\n\n pub start_pos: usize,\n\n pub end_pos: usize,\n\n pub start_offset: u32,\n\n pub end_offset: u32,\n\n pub size: u32,\n\n pub len: usize,\n\n}\n\n\n", "file_path": "src/store/encoding/raw/binary_enc.rs", "rank": 54, "score": 15.388154255121197 }, { "content": " for i in start..end {\n\n last_item_offset += buf.item_len(i);\n\n self.offsets.push(last_item_offset);\n\n }\n\n\n\n self.data\n\n .extend_from_slice(&buf.data()[start_offset as usize..end_offset as usize]);\n\n\n\n assert!(u32::MAX as usize > self.data.len());\n\n\n\n if let Some(ref validity_src) = buf.validity {\n\n let validity_dst = self\n\n .validity\n\n .as_mut()\n\n .expect(\"trying to append validity on a non-nullable buffer\");\n\n validity_dst.append_from(validity_src, validity_pos, chunk_len)\n\n } else {\n\n assert!(self.validity.is_none(), \"missing validity bitmap\");\n\n chunk_len\n\n }\n", "file_path": "src/store/indexing_buffer.rs", "rank": 57, "score": 14.932713780155053 }, { "content": " }\n\n\n\n self.len += 1;\n\n }\n\n\n\n pub fn append_from(&mut self, src: &Bitmap, start_pos: usize, num_of_items: usize) -> usize {\n\n let mut items = 0;\n\n let mut bit_pos = start_pos;\n\n while items < num_of_items {\n\n let bit_value = src.is_set(bit_pos);\n\n self.append(bit_value);\n\n items += bit_value as usize;\n\n bit_pos += 1;\n\n }\n\n bit_pos\n\n }\n\n\n\n pub fn is_set(&self, idx: usize) -> bool {\n\n assert!(idx < self.len);\n\n (self.values[idx >> 3] & BIT_MASK[idx & 7]) != 0\n", "file_path": "src/store/indexing_buffer.rs", "rank": 58, "score": 14.696776350142322 }, { "content": " pub fn new(nullable: bool) -> Self {\n\n let validity = match nullable {\n\n true => Some(Bitmap::new()),\n\n false => None,\n\n };\n\n\n\n Self {\n\n values: Vec::new(),\n\n validity: validity,\n\n }\n\n }\n\n\n\n /// Append a non-null value to the buffer\n\n pub fn append(&mut self, value: T) {\n\n self.values.push(value);\n\n if let Some(ref mut validity) = self.validity {\n\n validity.append(true);\n\n }\n\n }\n\n\n", "file_path": "src/store/indexing_buffer.rs", "rank": 59, "score": 14.681182545629419 }, { "content": "pub struct Config {\n\n pub db_path: PathBuf,\n\n pub gossip_port: u16,\n\n pub seeds: Vec<String>,\n\n}\n\n\n\npub struct Meerkat {\n\n conf: Config,\n\n}\n\n\n\nimpl Meerkat {\n\n pub fn new(conf: Config) -> Self {\n\n Self { conf }\n\n }\n\n\n\n pub fn start(&mut self) {\n\n self.init_logging();\n\n let span = span!(Level::TRACE, \"meerkat\");\n\n let _guard = span.enter();\n\n info!(\"starting\");\n", "file_path": "src/server/mod.rs", "rank": 60, "score": 14.547624112741643 }, { "content": " len: 0,\n\n }\n\n }\n\n\n\n pub fn with_capacity(cap: usize) -> Self {\n\n Self {\n\n values: vec![0; cap >> 3],\n\n len: 0,\n\n }\n\n }\n\n\n\n pub fn append(&mut self, set: bool) {\n\n let idx = self.len >> 3;\n\n\n\n if idx == self.values.len() {\n\n self.values.resize(self.values.len() * 2, 0);\n\n }\n\n\n\n if set {\n\n self.values[idx] |= BIT_MASK[self.len & 7];\n", "file_path": "src/store/indexing_buffer.rs", "rank": 61, "score": 14.023856288150329 }, { "content": "/// ```\n\n///\n\nuse std::convert::TryInto;\n\n\n\nuse anyhow::Result;\n\nuse async_trait::async_trait;\n\nuse itertools::Itertools;\n\n\n\nuse crate::store::encoding::bitmap_rle;\n\nuse crate::store::encoding::offsets::OffsetEncoder;\n\nuse crate::store::encoding::{BlockEncoder, BlockSink};\n\nuse crate::store::indexing_buffer::BinaryBuffer;\n\nuse crate::store::segment_metadata::column_layout::EncoderLayout;\n\nuse crate::store::segment_metadata::NoLayout;\n\n\n\nuse crate::store::encoding::varint::Encoder as _;\n\n\n\npub struct Encoder {\n\n remaining: BinaryBuffer,\n\n encoded_data: Vec<u8>,\n", "file_path": "src/store/encoding/raw/binary_enc.rs", "rank": 62, "score": 13.685470923093522 }, { "content": " file: Arc<File>,\n\n len: u64,\n\n}\n\n\n\nimpl Reader {\n\n pub async fn new<P: AsRef<Path>>(path: P) -> io::Result<Self> {\n\n let path = path.as_ref().to_owned();\n\n let file = asyncify(|| File::open(path)).await?;\n\n let metadata = file.metadata()?;\n\n\n\n Ok(Reader {\n\n file: Arc::new(file),\n\n len: metadata.len(),\n\n })\n\n }\n\n}\n\n\n\n#[async_trait]\n\nimpl BlockReader for Reader {\n\n type Buf = Vec<u8>;\n", "file_path": "src/store/io/unix_disk_block_reader.rs", "rank": 63, "score": 13.536411609898956 }, { "content": " impl BlockSink for SinkMock {\n\n async fn write_block(&mut self, row_id: u32, block_data: &[u8]) -> Result<()> {\n\n self.blocks.push(CapturedBlock {\n\n row_id: row_id,\n\n block_data: Vec::from(block_data),\n\n });\n\n Ok(())\n\n }\n\n }\n\n}\n", "file_path": "src/store/encoding/mod.rs", "rank": 64, "score": 13.37063390246107 }, { "content": "}\n\n\n\n/// A growable sparse encoded buffer for binary types.\n\n/// Buffer items are stored sequentially and offsets to each item are stored\n\n/// in a separated offset buffer.\n\npub struct BinaryBuffer {\n\n data: Vec<u8>,\n\n offsets: Vec<u32>,\n\n validity: Option<Bitmap>,\n\n}\n\n\n\nimpl BinaryBuffer {\n\n pub fn new(nullable: bool) -> Self {\n\n let validity = match nullable {\n\n true => Some(Bitmap::new()),\n\n false => None,\n\n };\n\n\n\n Self {\n\n data: Vec::new(),\n", "file_path": "src/store/indexing_buffer.rs", "rank": 65, "score": 13.32598300790763 }, { "content": " self.bit_pos = 0;\n\n self.append(self.byte);\n\n self.byte = 0;\n\n }\n\n }\n\n\n\n pub fn put_from(&mut self, bitmap: &Bitmap, start_pos: usize, num_valids: usize) -> usize {\n\n let mut items = 0;\n\n let mut bit_pos = start_pos;\n\n while items < num_valids {\n\n let bit_value = bitmap.is_set(bit_pos);\n\n self.put(bit_value);\n\n items += bit_value as usize;\n\n bit_pos += 1;\n\n }\n\n bit_pos\n\n }\n\n\n\n /// flush the internal buffer and encode pending values.\n\n /// once the encoder is flushed use `encoded_values()` to access the encoded\n", "file_path": "src/store/encoding/bitmap_rle.rs", "rank": 66, "score": 13.32361633958093 }, { "content": "#[derive(Clone, PartialEq, ::prost::Message)]\n\npub struct Int32Stats {}\n\n#[derive(Clone, PartialEq, ::prost::Message)]\n\npub struct Int64Stats {}\n\n#[derive(Clone, PartialEq, ::prost::Message)]\n\npub struct Float64Stats {}\n\n#[derive(Clone, PartialEq, ::prost::Message)]\n\npub struct StringStats {}\n\n#[derive(Clone, PartialEq, ::prost::Message)]\n\npub struct ColumnMeta {\n\n #[prost(string, tag = \"1\")]\n\n pub name: ::prost::alloc::string::String,\n\n #[prost(enumeration = \"ColumnType\", tag = \"2\")]\n\n pub column_type: i32,\n\n #[prost(bool, tag = \"3\")]\n\n pub nullable: bool,\n\n #[prost(enumeration = \"Encoding\", tag = \"4\")]\n\n pub encoding: i32,\n\n #[prost(uint32, tag = \"8\")]\n\n pub cardinality: u32,\n", "file_path": "src/store/segment_metadata.rs", "rank": 67, "score": 13.294659880194388 }, { "content": " &mut self.offset_deltas,\n\n &mut self.bitmap_encoder,\n\n &mut self.offset_encoder,\n\n );\n\n\n\n self.add_rows(result.num_rows);\n\n\n\n sink.write_block(self.num_rows - 1, &self.encoded_data)\n\n .await?;\n\n\n\n Ok(result)\n\n }\n\n\n\n fn add_rows(&mut self, num_rows: usize) {\n\n self.num_rows = self\n\n .num_rows\n\n .checked_add((num_rows).try_into().expect(\"segment overflow\"))\n\n .expect(\"segment overflow\");\n\n }\n\n}\n", "file_path": "src/store/encoding/raw/binary_enc.rs", "rank": 68, "score": 13.231586189861822 }, { "content": " pub fn new() -> Self {\n\n Self {\n\n encoded_values: Vec::new(),\n\n byte: 0,\n\n bit_pos: 0,\n\n buffer: vec![],\n\n repeat_count: 0,\n\n last_value: 0,\n\n run_start_pos: 0,\n\n state: State::Init,\n\n }\n\n }\n\n\n\n /// encode a single bit\n\n pub fn put(&mut self, set: bool) {\n\n if set {\n\n self.byte |= BIT_MASK[self.bit_pos];\n\n }\n\n self.bit_pos += 1;\n\n if self.bit_pos == 8 {\n", "file_path": "src/store/encoding/bitmap_rle.rs", "rank": 69, "score": 12.908488653431627 }, { "content": " self.block_row_id.clear();\n\n self.block_offset.clear();\n\n }\n\n\n\n /// flush the index to disk.\n\n pub async fn flush(&self, block_writer: &mut BlockWriter) -> Result<BlockIndexLayout> {\n\n Ok(BlockIndexLayout {\n\n range: Some(Range { start: 0, end: 0 }),\n\n })\n\n }\n\n}\n", "file_path": "src/store/block_index.rs", "rank": 70, "score": 12.567191684261932 }, { "content": " segment_writer.write_headers().await?;\n\n\n\n Ok(segment_writer)\n\n }\n\n\n\n async fn write_headers(&mut self) -> Result<()> {\n\n self.index_writer\n\n .write_block(&INDEX_FILE_SIGNATURE)\n\n .await\n\n .context(\"cannot write index header\")?;\n\n\n\n self.data_writer\n\n .write_block(&DATA_FILE_SIGNATURE)\n\n .await\n\n .context(\"cannot write index header\")\n\n }\n\n\n\n /// Creates a new ColumnWriter for BinaryBuffers.\n\n pub fn new_binary_column_writer(\n\n &mut self,\n", "file_path": "src/store/segment_writer.rs", "rank": 71, "score": 12.399241417121594 }, { "content": " }\n\n\n\n pub fn len(&self) -> usize {\n\n self.len\n\n }\n\n\n\n pub fn clear(&mut self) {\n\n self.len = 0;\n\n self.values.resize(INITIAL_BITMAP_CAP, 0);\n\n }\n\n}\n\n\n\n/// A growable sparse encoded buffer for primitive values.\n\n/// Non-null values are stores sequentially, Nulls are encoded using a bitmap.\n\npub struct PrimitiveBuffer<T> {\n\n values: Vec<T>,\n\n validity: Option<Bitmap>,\n\n}\n\n\n\nimpl<T: Clone> PrimitiveBuffer<T> {\n", "file_path": "src/store/indexing_buffer.rs", "rank": 72, "score": 12.076903931925546 }, { "content": " None => false,\n\n }\n\n }\n\n\n\n /// Clear all existing data from this buffer.\n\n pub fn clear(&mut self) {\n\n self.data.clear();\n\n self.offsets.truncate(1);\n\n if let Some(ref mut validity) = self.validity {\n\n validity.clear();\n\n };\n\n }\n\n}\n\n\n\n/// A growable sparse encoded buffer for bool values.\n\npub struct BoolBuffer {\n\n values: Bitmap,\n\n validity: Option<Bitmap>,\n\n len: usize,\n\n}\n", "file_path": "src/store/indexing_buffer.rs", "rank": 73, "score": 11.805683297669642 }, { "content": " block_offset: Vec<u64>,\n\n block_row_id: Vec<u32>,\n\n}\n\n\n\nimpl BlockIndex {\n\n pub fn new() -> Self {\n\n Self {\n\n block_offset: Vec::new(),\n\n block_row_id: Vec::new(),\n\n }\n\n }\n\n\n\n /// Add a new block to the index\n\n pub fn index_block(&mut self, row_id: u32, offset: u64) {\n\n self.block_offset.push(offset);\n\n self.block_row_id.push(row_id);\n\n }\n\n\n\n /// clear the index\n\n pub fn clear(&mut self) {\n", "file_path": "src/store/block_index.rs", "rank": 74, "score": 11.689752953581063 }, { "content": "use futures::stream::BoxStream;\n\nuse tokio::task::spawn_blocking;\n\n\n\nmod default_block_writer;\n\nmod unix_disk_block_reader;\n\npub use default_block_writer::Writer as BlockWriter;\n\n\n\n/// Block Read Operation.\n\n#[derive(Clone, Debug)]\n\npub struct ReadOp {\n\n /// Block offset info.\n\n block_range: BlockRange,\n\n /// User data attached to the op.\n\n op_info: OpInfo,\n\n}\n\n\n\n/// BlockRange defines the start and end offset of a block.\n\n#[derive(Clone, Debug)]\n\npub struct BlockRange {\n\n start: u64,\n", "file_path": "src/store/io/mod.rs", "rank": 75, "score": 11.63211799487603 }, { "content": "use crate::store::index::ColumnIndex;\n\nuse crate::store::indexing_buffer::BinaryBuffer;\n\nuse crate::store::segment_metadata;\n\nuse crate::store::segment_metadata::{ColumnType, Encoding, IndexType, Metadata};\n\n\n\nuse super::io::BlockWriter;\n\n\n\nconst DATA_FILE_SIGNATURE: [u8; 13] = *b\"MEERKAT_DATA1\";\n\nconst INDEX_FILE_SIGNATURE: [u8; 12] = *b\"MEERKAT_IDX1\";\n\nconst DATA_FILE_EXT: &str = \"dat\";\n\nconst INDEX_FILE_EXT: &str = \"idx\";\n\nconst BLOCK_SIZE: u32 = 1 << 7; // 128k block size\n\n\n\n/// ColumnInfo provides details about the column to be indexed.\n\npub struct ColumnInfo {\n\n pub name: String,\n\n pub column_type: ColumnType,\n\n pub encoding: Encoding,\n\n pub index_type: IndexType,\n\n pub nullable: bool,\n", "file_path": "src/store/segment_writer.rs", "rank": 76, "score": 11.580611002719007 }, { "content": " /// Returns true if the buffer accepts non-null values.\n\n pub fn is_nullable(&self) -> bool {\n\n self.validity.is_some()\n\n }\n\n\n\n /// Returns true if the buffer has null items.\n\n pub fn has_nulls(&self) -> bool {\n\n match self.validity {\n\n Some(ref validity) => validity.len() - self.values.len() != 0,\n\n None => false,\n\n }\n\n }\n\n\n\n /// Clear all existing data from this buffer.\n\n pub fn clear(&mut self) {\n\n self.values.clear();\n\n if let Some(ref mut validity) = self.validity {\n\n validity.clear();\n\n }\n\n }\n", "file_path": "src/store/indexing_buffer.rs", "rank": 77, "score": 11.477700181106101 }, { "content": "use std::convert::TryInto;\n\n\n\nconst BIT_MASK: [u8; 8] = [1, 2, 4, 8, 16, 32, 64, 128];\n\nconst INITIAL_BITMAP_CAP: usize = 1024;\n\n\n\npub type Int32Buffer = PrimitiveBuffer<i32>;\n\npub type Int64Buffer = PrimitiveBuffer<i64>;\n\npub type Uint64Buffer = PrimitiveBuffer<u64>;\n\npub type Float64Buffer = PrimitiveBuffer<f64>;\n\n\n\n/// A reusable growable bitmap.\n\npub struct Bitmap {\n\n values: Vec<u8>,\n\n len: usize,\n\n}\n\n\n\nimpl Bitmap {\n\n pub fn new() -> Self {\n\n Self {\n\n values: vec![0; INITIAL_BITMAP_CAP],\n", "file_path": "src/store/indexing_buffer.rs", "rank": 78, "score": 11.475760340746733 }, { "content": " pub fn validity(&self) -> &Bitmap {\n\n &self.validity.as_ref().unwrap()\n\n }\n\n\n\n /// The number of items stored in this buffer. ( including non-null )\n\n pub fn len(&self) -> usize {\n\n self.len\n\n }\n\n\n\n /// Returns true if the buffer accepts non-null values.\n\n pub fn is_nullable(&self) -> bool {\n\n self.validity.is_some()\n\n }\n\n\n\n /// Returns true if the buffer has null items.\n\n pub fn has_nulls(&self) -> bool {\n\n !(self.values.len() == self.len)\n\n }\n\n\n\n /// Clear all existing data from this buffer.\n", "file_path": "src/store/indexing_buffer.rs", "rank": 79, "score": 11.245790742569287 }, { "content": "\n\nimpl OffsetEncoder {\n\n pub fn new() -> Self {\n\n Self {\n\n bitpacker: BitPacker4x::new(),\n\n }\n\n }\n\n\n\n /// Encode a list of offsets into a Vec.\n\n /// ```text\n\n /// ┌───────────────────┬─────────────────────────┐\n\n /// │ Bitpack Num Bytes │ Bitpacked Delta Offsets │\n\n /// │ 1 Byte │ N Byte │\n\n /// └───────────────────┴─────────────────────────┘\n\n /// ```\n\n pub fn encode(&mut self, src: &mut Vec<u32>, dst: &mut Vec<u8>) {\n\n let num_values = src.len();\n\n\n\n let len_padded = round_upto_power_of_2(src.len(), BitPacker4x::BLOCK_LEN);\n\n src.resize(len_padded, 0);\n", "file_path": "src/store/encoding/offsets.rs", "rank": 80, "score": 10.70709648663707 }, { "content": " self.offsets.len() - 1\n\n }\n\n\n\n /// Returns the number of items stored in this buffer. ( including nulls )\n\n pub fn num_values(&self) -> usize {\n\n match self.validity {\n\n Some(ref validity) => validity.len(),\n\n None => self.len(),\n\n }\n\n }\n\n\n\n /// Returns true if the buffer accepts non-null values.\n\n pub fn is_nullable(&self) -> bool {\n\n self.validity.is_some()\n\n }\n\n\n\n /// Returns true if the buffer has null items.\n\n pub fn has_nulls(&self) -> bool {\n\n match self.validity {\n\n Some(ref validity) => validity.len() - self.len() != 0,\n", "file_path": "src/store/indexing_buffer.rs", "rank": 81, "score": 10.692525314766925 }, { "content": "//!┌──────────────────────────────────────────────────────────────────────────────┐\n\n//!│┌─────────────┐ ┌────────────┐ ┌─────────────┐ ┌────────────┐ ┌──────────────┐│\n\n//!││ ColumnIndex │ │ BlockIndex │ │ ColumnIndex │ │ BlockIndex │ │ Metadata ││\n\n//!││ Column A │ │ Column A │ │ Column B │ │ Column B │ │(ProtoBuf enc)││\n\n//!│└─────────────┘ └────────────┘ └─────────────┘ └────────────┘ └──────────────┘│\n\n//!└──────────────────────────────────────────────────────────────────────────────┘\n\n//!```\n\n//!\n\n\n\nuse std::collections::HashMap;\n\nuse std::path::Path;\n\n\n\nuse anyhow::{Context, Result};\n\nuse prost::Message;\n\nuse uuid::Uuid;\n\n\n\nuse crate::store::block_index::BlockIndex;\n\nuse crate::store::block_sink::BlockSinkImpl;\n\nuse crate::store::encoding;\n\nuse crate::store::encoding::BlockEncoder;\n", "file_path": "src/store/segment_writer.rs", "rank": 82, "score": 10.688535193350845 }, { "content": " }\n\n\n\n /// Returns a reference to the stored values.\n\n pub fn data(&self) -> &[u8] {\n\n self.data.as_slice()\n\n }\n\n\n\n /// Returns a slice containing the values offsets\n\n pub fn offsets(&self) -> &[u32] {\n\n self.offsets.as_slice()\n\n }\n\n\n\n /// Returns a ref to the validity bitmap.\n\n /// Panic if the buffer is not nullable.\n\n pub fn validity(&self) -> Option<&Bitmap> {\n\n self.validity.as_ref()\n\n }\n\n\n\n /// Returns the number of not nulls items stored in this buffer.\n\n pub fn len(&self) -> usize {\n", "file_path": "src/store/indexing_buffer.rs", "rank": 83, "score": 10.516277190006797 }, { "content": " let num_values = end - start;\n\n\n\n if let Some(ref validity_src) = buf.validity {\n\n let validity_dst = self\n\n .validity\n\n .as_mut()\n\n .expect(\"trying to append validity on a non-nullable buffer\");\n\n\n\n validity_dst.append_from(validity_src, validity_pos, num_values)\n\n } else {\n\n assert!(self.validity.is_none(), \"missing validity bitmap\");\n\n num_values\n\n }\n\n }\n\n\n\n /// Returns the values stored in this buffer.\n\n /// This is a sparse representation so only non-null values are returned.\n\n pub fn values(&self) -> &[T] {\n\n &self.values\n\n }\n", "file_path": "src/store/indexing_buffer.rs", "rank": 84, "score": 10.32475923598529 }, { "content": " column_info: ColumnInfo,\n\n ) -> Result<ColumnWriter<'_, BinaryBuffer>> {\n\n self.block_index.clear();\n\n\n\n let encoder =\n\n encoding::new_binary_encoder(column_info.encoding, BLOCK_SIZE, column_info.nullable)?;\n\n\n\n let block_sink = BlockSinkImpl::new(&mut self.data_writer, &mut self.block_index);\n\n\n\n Ok(ColumnWriter {\n\n column_info: column_info,\n\n metadata: &mut self.segment_meta,\n\n encoder: encoder,\n\n block_sink: block_sink,\n\n index_writer: &mut self.index_writer,\n\n column_index: None,\n\n })\n\n }\n\n\n\n /// Close the SegmentWriter and flush any pending data.\n", "file_path": "src/store/segment_writer.rs", "rank": 85, "score": 10.271856936807566 }, { "content": " end: u64,\n\n}\n\n\n\n/// OpInfo contains user data attached to the read operation.\n\n/// OpInfo is intended to be used by the application after op completion.\n\n#[derive(Debug, PartialEq, Clone)]\n\npub enum OpInfo {\n\n /// Nonspecific block used to fetch auxiliary data from segments like\n\n /// pointers to metadata blocks.\n\n GenericBlock,\n\n /// Blocks containing index related data ( inverted indexes,\n\n /// FST, Bloom filters, etc )\n\n IndexBlock,\n\n /// Represent a column data block with its first row id.\n\n DataBlock { first_row_id: u32 },\n\n}\n\n\n\n/// Block data.\n\npub struct Block<Buf: AsRef<[u8]>> {\n\n /// The buffer containing the block data\n", "file_path": "src/store/io/mod.rs", "rank": 86, "score": 10.268152192687104 }, { "content": " return Ok((u64::from(part0), 3));\n\n };\n\n part0 -= 0x80 << 14;\n\n b = buf[3];\n\n part0 += u32::from(b) << 21;\n\n if b < 0x80 {\n\n return Ok((u64::from(part0), 4));\n\n };\n\n part0 -= 0x80 << 21;\n\n let value = u64::from(part0);\n\n\n\n let mut part1: u32;\n\n b = buf[4];\n\n part1 = u32::from(b);\n\n if b < 0x80 {\n\n return Ok((value + (u64::from(part1) << 28), 5));\n\n };\n\n part1 -= 0x80;\n\n b = buf[5];\n\n part1 += u32::from(b) << 7;\n", "file_path": "src/store/encoding/varint.rs", "rank": 87, "score": 9.92109356072022 }, { "content": " offsets: vec![0; 1],\n\n validity: validity,\n\n }\n\n }\n\n\n\n /// Append a non-null value.\n\n pub fn append(&mut self, value: &[u8]) {\n\n self.data.extend_from_slice(value);\n\n let value_offset: u32 = self.data.len().try_into().expect(\"BinaryBuffer overflow\");\n\n self.offsets.push(value_offset);\n\n if let Some(ref mut validity) = self.validity {\n\n validity.append(true);\n\n }\n\n }\n\n\n\n /// Append a null value to the buffer.\n\n pub fn append_null(&mut self) {\n\n match self.validity {\n\n Some(ref mut validity) => validity.append(false),\n\n None => panic!(\"null append on non-nullable buffer\"),\n", "file_path": "src/store/indexing_buffer.rs", "rank": 88, "score": 9.778761024466007 }, { "content": " async fn close(&mut self) -> Result<()> {\n\n let metadata_bytes = self.segment_meta.encode_to_vec();\n\n let metadata_pos = self.index_writer.pos();\n\n\n\n self.index_writer\n\n .write_block(&metadata_bytes)\n\n .await\n\n .context(\"cannot write metadata\")?;\n\n\n\n self.index_writer\n\n .write_block(&metadata_pos.to_le_bytes())\n\n .await\n\n .context(\"cannot write index footer\")?;\n\n\n\n self.index_writer\n\n .flush()\n\n .await\n\n .context(\"cannot flush index file\")?;\n\n self.data_writer\n\n .flush()\n", "file_path": "src/store/segment_writer.rs", "rank": 89, "score": 9.615906096325624 }, { "content": " if b < 0x80 {\n\n return Ok((value + (u64::from(part1) << 28), 6));\n\n };\n\n part1 -= 0x80 << 7;\n\n b = buf[6];\n\n part1 += u32::from(b) << 14;\n\n if b < 0x80 {\n\n return Ok((value + (u64::from(part1) << 28), 7));\n\n };\n\n part1 -= 0x80 << 14;\n\n b = buf[7];\n\n part1 += u32::from(b) << 21;\n\n if b < 0x80 {\n\n return Ok((value + (u64::from(part1) << 28), 8));\n\n };\n\n part1 -= 0x80 << 21;\n\n let value = value + ((u64::from(part1)) << 28);\n\n\n\n let mut part2: u32;\n\n b = buf[8];\n", "file_path": "src/store/encoding/varint.rs", "rank": 90, "score": 9.561367503629274 }, { "content": " pub uncompressed_size: u64,\n\n #[prost(uint32, tag = \"7\")]\n\n pub num_rows: u32,\n\n #[prost(map = \"string, message\", tag = \"8\")]\n\n pub columns_meta: ::std::collections::HashMap<::prost::alloc::string::String, ColumnMeta>,\n\n}\n\n#[derive(Clone, PartialEq, ::prost::Message)]\n\npub struct Range {\n\n #[prost(uint64, tag = \"1\")]\n\n pub start: u64,\n\n #[prost(uint64, tag = \"2\")]\n\n pub end: u64,\n\n}\n\n#[derive(Clone, PartialEq, ::prost::Message)]\n\npub struct Metadata {\n\n #[prost(message, optional, tag = \"1\")]\n\n pub segment_meta: ::core::option::Option<SegmentMeta>,\n\n #[prost(map = \"string, message\", tag = \"2\")]\n\n pub columns_layout: ::std::collections::HashMap<::prost::alloc::string::String, ColumnLayout>,\n\n}\n", "file_path": "src/store/segment_metadata.rs", "rank": 91, "score": 9.486903689100151 }, { "content": " .try_into()\n\n .expect(\"cannot decode frame, frame len overflow\");\n\n\n\n if header & 1 == 1 {\n\n let bitmap_start = self.encoded_data_pos;\n\n let bitmap_end = self.encoded_data_pos + len as usize;\n\n self.encoded_data_pos += len as usize;\n\n return Frame::Bitmap {\n\n bytes: &self.encoded_data[bitmap_start..bitmap_end],\n\n };\n\n };\n\n\n\n let frame = Frame::Run {\n\n len: len,\n\n value: self.encoded_data[self.encoded_data_pos],\n\n };\n\n\n\n self.encoded_data_pos += 1;\n\n\n\n frame\n", "file_path": "src/store/encoding/bitmap_rle.rs", "rank": 92, "score": 9.137785022943271 }, { "content": " /// Create a new segment on disk.\n\n /// Segment and index files are created using `path` as the base path.\n\n /// File names are generated by encoding the `segment_id` in Base64.\n\n pub async fn new<P: AsRef<Path>>(path: P, segment_info: SegmentInfo) -> Result<Self> {\n\n let segment_id_str =\n\n base64::encode_config(segment_info.segment_id.as_bytes(), base64::URL_SAFE_NO_PAD);\n\n\n\n let data_file_name = format!(\"{}.{}\", segment_id_str, DATA_FILE_EXT);\n\n let index_file_name = format!(\"{}.{}\", segment_id_str, INDEX_FILE_EXT);\n\n\n\n let data_path = path.as_ref().join(&data_file_name);\n\n let index_path = path.as_ref().join(&index_file_name);\n\n\n\n let index_writer = BlockWriter::new(index_path)\n\n .await\n\n .context(\"cannot create index writer\")?;\n\n\n\n let data_writer = BlockWriter::new(data_path)\n\n .await\n\n .context(\"cannot create data writer\")?;\n", "file_path": "src/store/segment_writer.rs", "rank": 93, "score": 9.120445291308739 }, { "content": " };\n\n self.len += 1;\n\n }\n\n\n\n /// Append a new value to the buffer.\n\n pub fn append_null(&mut self) {\n\n match self.validity {\n\n Some(ref mut validity) => validity.append(false),\n\n None => panic!(\"null append on non-nullable buffer\"),\n\n };\n\n self.len += 1;\n\n }\n\n\n\n /// Returns a reference to the internal value bitmap.\n\n pub fn values(&self) -> &Bitmap {\n\n &self.values\n\n }\n\n\n\n /// Returns a ref to the validity bitmap.\n\n /// Panic if the buffer is not nullable.\n", "file_path": "src/store/indexing_buffer.rs", "rank": 94, "score": 8.946237715673497 }, { "content": " }\n\n /// Decode the internal buffer and return the number of values decoded.\n\n pub fn decode(&mut self) -> usize {\n\n while self.encoded_data_pos < self.encoded_data.len() {\n\n match self.read_frame() {\n\n Frame::Run { len, value } => self.decode_run(len, value),\n\n Frame::Bitmap { bytes } => self.decode_bitmap(bytes),\n\n }\n\n }\n\n self.decoded_data_pos\n\n }\n\n\n\n pub fn read_frame(&mut self) -> Frame<'a> {\n\n let (header, bytes_read) =\n\n varint::decode_varint(&self.encoded_data[self.encoded_data_pos..])\n\n .expect(\"cannot decode bitmap\");\n\n\n\n self.encoded_data_pos += bytes_read;\n\n\n\n let len: u32 = (header >> 1)\n", "file_path": "src/store/encoding/bitmap_rle.rs", "rank": 95, "score": 8.905217083568619 }, { "content": " pub fn clear(&mut self) {\n\n self.values.clear();\n\n if let Some(ref mut validity) = self.validity {\n\n validity.clear();\n\n };\n\n self.len = 0;\n\n }\n\n}\n\n\n\n#[cfg(test)]\n\nmod test {\n\n use rand::Rng;\n\n\n\n use super::*;\n\n\n\n #[test]\n\n fn bitmap_rnd_test() {\n\n let mut rng = rand::thread_rng();\n\n let len = rng.gen_range(0..2048);\n\n let mut values = vec![false; len];\n", "file_path": "src/store/indexing_buffer.rs", "rank": 96, "score": 8.83604686652231 }, { "content": "// Copyright 2021 The Meerkat Authors\n\n// Licensed under the Apache License, Version 2.0 (the \"License\");\n\n// you may not use this file except in compliance with the License.\n\n// You may obtain a copy of the License at\n\n//\n\n// http://www.apache.org/licenses/LICENSE-2.0\n\n//\n\n// Unless required by applicable law or agreed to in writing, software\n\n// distributed under the License is distributed on an \"AS IS\" BASIS,\n\n// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n\n// See the License for the specific language governing permissions and\n\n// limitations under the License.\n\n\n\nuse anyhow::anyhow;\n\nuse anyhow::Result;\n\n\n\npub const MAX_VARINT_LEN: usize = 10;\n\n\n\n#[inline]\n", "file_path": "src/store/encoding/varint.rs", "rank": 97, "score": 8.804946969616262 }, { "content": "\n\n let num_bits = self.bitpacker.num_bits(src);\n\n\n\n dst.push(num_bits);\n\n\n\n let encoded_data_start = dst.len();\n\n\n\n let mut chunk_start = encoded_data_start;\n\n\n\n dst.resize(dst.len() + ceil8(num_bits as usize * len_padded), 0);\n\n\n\n for chunk in src.chunks(BitPacker4x::BLOCK_LEN) {\n\n let compressed_len = self\n\n .bitpacker\n\n .compress(chunk, &mut dst[chunk_start..], num_bits);\n\n chunk_start += compressed_len;\n\n }\n\n\n\n // trim to remove the encoded padding.\n\n let encoded_data_len = encoded_data_start + ceil8(num_bits as usize * num_values);\n\n\n\n dst.resize(encoded_data_len, 0);\n\n }\n\n}\n", "file_path": "src/store/encoding/offsets.rs", "rank": 98, "score": 8.747330242502844 }, { "content": "\n\n let mut buffer = BinaryBuffer::new(false);\n\n buffer.append(\"test\".as_bytes());\n\n\n\n col_writer.write(&buffer).await.unwrap();\n\n col_writer.write(&buffer).await.unwrap();\n\n col_writer.close().await.unwrap();\n\n }\n\n\n\n segment_writer.close().await.unwrap();\n\n segment_writer.sync().await.unwrap();\n\n }\n\n}\n", "file_path": "src/store/segment_writer.rs", "rank": 99, "score": 8.727337709624068 } ]
Rust
src/filters/tests.rs
dsaxton/feroxbuster
45efaa738850f7644683d927cffc5661e97307c4
use super::*; use ::fuzzyhash::FuzzyHash; use ::regex::Regex; #[test] fn wildcard_filter_default() { let wcf = WildcardFilter::default(); assert_eq!(wcf.size, u64::MAX); assert_eq!(wcf.dynamic, u64::MAX); } #[test] fn wildcard_filter_as_any() { let filter = WildcardFilter::default(); let filter2 = WildcardFilter::default(); assert!(filter.box_eq(filter2.as_any())); assert_eq!( *filter.as_any().downcast_ref::<WildcardFilter>().unwrap(), filter ); } #[test] fn lines_filter_as_any() { let filter = LinesFilter { line_count: 1 }; let filter2 = LinesFilter { line_count: 1 }; assert!(filter.box_eq(filter2.as_any())); assert_eq!(filter.line_count, 1); assert_eq!( *filter.as_any().downcast_ref::<LinesFilter>().unwrap(), filter ); } #[test] fn words_filter_as_any() { let filter = WordsFilter { word_count: 1 }; let filter2 = WordsFilter { word_count: 1 }; assert!(filter.box_eq(filter2.as_any())); assert_eq!(filter.word_count, 1); assert_eq!( *filter.as_any().downcast_ref::<WordsFilter>().unwrap(), filter ); } #[test] fn size_filter_as_any() { let filter = SizeFilter { content_length: 1 }; let filter2 = SizeFilter { content_length: 1 }; assert!(filter.box_eq(filter2.as_any())); assert_eq!(filter.content_length, 1); assert_eq!( *filter.as_any().downcast_ref::<SizeFilter>().unwrap(), filter ); } #[test] fn status_code_filter_as_any() { let filter = StatusCodeFilter { filter_code: 200 }; let filter2 = StatusCodeFilter { filter_code: 200 }; assert!(filter.box_eq(filter2.as_any())); assert_eq!(filter.filter_code, 200); assert_eq!( *filter.as_any().downcast_ref::<StatusCodeFilter>().unwrap(), filter ); } #[test] fn regex_filter_as_any() { let raw = r".*\.txt$"; let compiled = Regex::new(raw).unwrap(); let compiled2 = Regex::new(raw).unwrap(); let filter = RegexFilter { compiled, raw_string: raw.to_string(), }; let filter2 = RegexFilter { compiled: compiled2, raw_string: raw.to_string(), }; assert!(filter.box_eq(filter2.as_any())); assert_eq!(filter.raw_string, r".*\.txt$"); assert_eq!( *filter.as_any().downcast_ref::<RegexFilter>().unwrap(), filter ); } #[test] fn wildcard_should_filter_when_static_wildcard_found() { let mut resp = FeroxResponse::default(); resp.set_wildcard(true); resp.set_url("http://localhost"); resp.set_text( "pellentesque diam volutpat commodo sed egestas egestas fringilla phasellus faucibus", ); let filter = WildcardFilter { size: 83, dynamic: 0, dont_filter: false, }; assert!(filter.should_filter_response(&resp)); } #[test] fn wildcard_should_filter_when_static_wildcard_len_is_zero() { let mut resp = FeroxResponse::default(); resp.set_wildcard(true); resp.set_url("http://localhost"); let filter = WildcardFilter::new(false); assert!(filter.should_filter_response(&resp)); } #[test] fn wildcard_should_filter_when_dynamic_wildcard_found() { let mut resp = FeroxResponse::default(); resp.set_wildcard(true); resp.set_url("http://localhost/stuff"); resp.set_text("pellentesque diam volutpat commodo sed egestas egestas fringilla"); let filter = WildcardFilter { size: 0, dynamic: 59, dont_filter: false, }; println!("resp: {:?}: filter: {:?}", resp, filter); assert!(filter.should_filter_response(&resp)); } #[test] fn regexfilter_should_filter_when_regex_matches_on_response_body() { let mut resp = FeroxResponse::default(); resp.set_url("http://localhost/stuff"); resp.set_text("im a body response hurr durr!"); let raw = r"response...rr"; let filter = RegexFilter { raw_string: raw.to_string(), compiled: Regex::new(raw).unwrap(), }; assert!(filter.should_filter_response(&resp)); } #[test] fn similarity_filter_is_accurate() { let mut resp = FeroxResponse::default(); resp.set_url("http://localhost/stuff"); resp.set_text("sitting"); let mut filter = SimilarityFilter { text: FuzzyHash::new("kitten").to_string(), threshold: 95, }; assert!(!filter.should_filter_response(&resp)); resp.set_text(""); filter.text = String::new(); filter.threshold = 100; assert!(!filter.should_filter_response(&resp)); resp.set_text("some data to hash for the purposes of running a test"); filter.text = FuzzyHash::new("some data to hash for the purposes of running a te").to_string(); filter.threshold = 17; assert!(filter.should_filter_response(&resp)); } #[test] fn similarity_filter_as_any() { let filter = SimilarityFilter { text: String::from("stuff"), threshold: 95, }; let filter2 = SimilarityFilter { text: String::from("stuff"), threshold: 95, }; assert!(filter.box_eq(filter2.as_any())); assert_eq!(filter.text, "stuff"); assert_eq!( *filter.as_any().downcast_ref::<SimilarityFilter>().unwrap(), filter ); }
use super::*; use ::fuzzyhash::FuzzyHash; use ::regex::Regex; #[test] fn wildcard_filter_default() { let wcf = WildcardFilter::default(); assert_eq!(wcf.size, u64::MAX); assert_eq!(wcf.dynamic, u64::MAX); } #[test] fn wildcard_filter_as_any() { let filter = WildcardFilter::default(); let filter2 = WildcardFilter::default(); assert!(filter.box_eq(filter2.as_any())); assert_eq!( *filter.as_any().downcast_ref::<WildcardFilter>().unwrap(), filter ); } #[test] fn lines_filter_as_any() { let filter = LinesFilter { line_count: 1 }; let filter2 = LinesFilter { line_count: 1 }; assert!(filter.box_eq(filter2.as_any())); assert_eq!(filter.line_count, 1); assert_eq!( *filter.as_any().downcast_ref::<LinesFilter>().unwrap(), filter ); } #[test] fn words_filter_as_any() { let filter = WordsFilter { word_count: 1 }; let filter2 = WordsFilter { word_count: 1 }; assert!(filter.box_eq(filter2.as_any())); assert_eq!(filter.word_count, 1); assert_eq!( *filter.as_any().downcast_ref::<WordsFilter>().unwrap(), filter ); } #[test] fn size_filter_as_any() { let filter = SizeFilter { content_length: 1 }; let filter2 = SizeFilter { content_length: 1 }; assert!(filter.box_eq(filter2.as_any())); assert_eq!(filter.content_length, 1); assert_eq!( *filter.as_any().downcast_ref::<SizeFilter>().unwrap(), filter ); } #[test] fn status_code_filter_as_any() { let filter = StatusCodeFilter { filter_code: 200 }; let filter2 = StatusCodeFilter { filter_code: 200 }; assert!(filter.box_eq(filter2.as_any())); assert_eq!(filter.filter_code, 200); assert_eq!( *filter.as_any().downcast_ref::<StatusCodeFilter>().unwrap(), filter ); } #[test] fn regex_filter_as_any() { let raw = r".*\.txt$"; let compiled = Regex::new(raw).unwrap(); let compiled2 = Regex::new(raw).unwrap(); let filter = RegexFilter { compiled, raw_string: raw.to_string(), }; let filter2 = RegexFilter { compiled: compiled2, raw_string: raw.to_string(), }; assert!(filter.box_eq(filter2.as_an
#[test] fn wildcard_should_filter_when_static_wildcard_found() { let mut resp = FeroxResponse::default(); resp.set_wildcard(true); resp.set_url("http://localhost"); resp.set_text( "pellentesque diam volutpat commodo sed egestas egestas fringilla phasellus faucibus", ); let filter = WildcardFilter { size: 83, dynamic: 0, dont_filter: false, }; assert!(filter.should_filter_response(&resp)); } #[test] fn wildcard_should_filter_when_static_wildcard_len_is_zero() { let mut resp = FeroxResponse::default(); resp.set_wildcard(true); resp.set_url("http://localhost"); let filter = WildcardFilter::new(false); assert!(filter.should_filter_response(&resp)); } #[test] fn wildcard_should_filter_when_dynamic_wildcard_found() { let mut resp = FeroxResponse::default(); resp.set_wildcard(true); resp.set_url("http://localhost/stuff"); resp.set_text("pellentesque diam volutpat commodo sed egestas egestas fringilla"); let filter = WildcardFilter { size: 0, dynamic: 59, dont_filter: false, }; println!("resp: {:?}: filter: {:?}", resp, filter); assert!(filter.should_filter_response(&resp)); } #[test] fn regexfilter_should_filter_when_regex_matches_on_response_body() { let mut resp = FeroxResponse::default(); resp.set_url("http://localhost/stuff"); resp.set_text("im a body response hurr durr!"); let raw = r"response...rr"; let filter = RegexFilter { raw_string: raw.to_string(), compiled: Regex::new(raw).unwrap(), }; assert!(filter.should_filter_response(&resp)); } #[test] fn similarity_filter_is_accurate() { let mut resp = FeroxResponse::default(); resp.set_url("http://localhost/stuff"); resp.set_text("sitting"); let mut filter = SimilarityFilter { text: FuzzyHash::new("kitten").to_string(), threshold: 95, }; assert!(!filter.should_filter_response(&resp)); resp.set_text(""); filter.text = String::new(); filter.threshold = 100; assert!(!filter.should_filter_response(&resp)); resp.set_text("some data to hash for the purposes of running a test"); filter.text = FuzzyHash::new("some data to hash for the purposes of running a te").to_string(); filter.threshold = 17; assert!(filter.should_filter_response(&resp)); } #[test] fn similarity_filter_as_any() { let filter = SimilarityFilter { text: String::from("stuff"), threshold: 95, }; let filter2 = SimilarityFilter { text: String::from("stuff"), threshold: 95, }; assert!(filter.box_eq(filter2.as_any())); assert_eq!(filter.text, "stuff"); assert_eq!( *filter.as_any().downcast_ref::<SimilarityFilter>().unwrap(), filter ); }
y())); assert_eq!(filter.raw_string, r".*\.txt$"); assert_eq!( *filter.as_any().downcast_ref::<RegexFilter>().unwrap(), filter ); }
function_block-function_prefixed
[]
Rust
plan_b/src/map.rs
PoHuit/plan-b
12121a5e9c542b2486a2fd33ba06bcebfeba6b65
use std::collections::HashMap; use std::error::Error; use std::fs::File; use std::slice; use libflate::gzip; #[derive(Clone, Copy, Debug, PartialEq, Eq, PartialOrd, Ord, Hash)] pub struct SystemId(usize); #[derive(Debug)] pub struct SystemInfo { pub system_id: SystemId, pub name: String, pub stargates: Vec<SystemId>, pub system_index: usize, } #[derive(Debug)] pub struct Map { systems: Vec<SystemInfo>, by_system_id: HashMap<SystemId, usize>, by_name: HashMap<String, usize>, } mod json_repr { use std::collections::HashMap; use serde::{de, Deserialize, Deserializer}; use serde_json::{self, Value}; use std::str::FromStr; fn de_from_f64<'de, D>(deserializer: D) -> Result<f64, D::Error> where D: Deserializer<'de>, { let v = Value::deserialize(deserializer)?; let e = "an f64 literal or string"; match v { Value::Number(v) => Ok(v.as_f64().unwrap()), Value::String(s) => f64::from_str(&s).map_err(de::Error::custom), Value::Null => { let ue = de::Unexpected::Other("null"); Err(de::Error::invalid_value(ue, &e)) } Value::Bool(b) => { let ue = de::Unexpected::Bool(b); Err(de::Error::invalid_value(ue, &e)) } Value::Array(_) => { let ue = de::Unexpected::Seq; Err(de::Error::invalid_value(ue, &e)) } Value::Object(_) => { let ue = de::Unexpected::Map; Err(de::Error::invalid_value(ue, &e)) } } } #[derive(Deserialize)] pub struct Destination { pub stargate_id: usize, pub system_id: usize, } #[derive(Deserialize)] pub struct Point { #[serde(deserialize_with = "de_from_f64")] pub x: f64, #[serde(deserialize_with = "de_from_f64")] pub y: f64, #[serde(deserialize_with = "de_from_f64")] pub z: f64, } #[derive(Deserialize)] pub struct Stargate { pub destination: Destination, pub name: String, pub position: Point, pub stargate_id: usize, pub system_id: usize, pub type_id: usize, } #[derive(Deserialize)] pub struct Planet { pub asteroid_belts: Option<Vec<usize>>, pub moons: Option<Vec<usize>>, pub planet_id: usize, } #[derive(Deserialize)] pub struct System { pub constellation_id: usize, pub name: String, pub planets: Option<Vec<Planet>>, pub position: Point, pub security_class: Option<String>, pub security_status: f64, pub star_id: Option<usize>, pub stargates: Option<Vec<usize>>, pub stations: Option<Vec<usize>>, pub system_id: usize, } #[derive(Deserialize)] pub struct Map { pub stargates: HashMap<usize, Stargate>, pub systems: HashMap<usize, System>, } } fn find_map_file() -> Result<File, Box<dyn Error>> { let mut f = None; for fname in [ "./static/eve-map.json.gz", "./eve-map.json.gz", "/usr/local/share/eve-map.json.gz", ] .iter() { f = Some(File::open(fname)); if let Some(Ok(f)) = f { return Ok(f); } } f.unwrap().map_err(|e| Box::new(e) as Box<dyn Error>) } impl Map { pub fn fetch() -> Result<Map, Box<dyn Error>> { let map_file = find_map_file()?; let gunzip = gzip::Decoder::new(map_file)?; let map: json_repr::Map = serde_json::from_reader(gunzip)?; let mut by_system_id = HashMap::new(); let mut by_name = HashMap::new(); let mut systems = Vec::with_capacity(map.systems.len()); let mut system_index = 0; for (system_id, system) in &map.systems { let system_id = SystemId(*system_id); let stargates: Vec<SystemId>; match system.stargates { None => continue, Some(ref stargate_ids) => { stargates = stargate_ids .iter() .map(|s| SystemId(map.stargates[s].destination.system_id)) .collect() } } let system_info = SystemInfo { system_id, name: system.name.clone(), stargates, system_index, }; systems.push(system_info); by_system_id.insert(system_id, system_index); by_name.insert(system.name.clone(), system_index); system_index += 1; } Ok(Map { systems, by_system_id, by_name, }) } pub fn by_name<'a>(&'a self, name: &'a str) -> Option<&'a SystemInfo> { self.by_name.get(name).map(|i| &self.systems[*i]) } pub fn by_system_id(&self, id: SystemId) -> &SystemInfo { let i = self .by_system_id .get(&id) .expect("by_system_id: invalid SystemId"); &self.systems[*i] } pub fn systems(&self) -> slice::Iter<'_, SystemInfo> { self.systems.iter() } pub fn systems_ref(&self) -> &[SystemInfo] { &self.systems } }
use std::collections::HashMap; use std::error::Error; use std::fs::File; use std::slice; use libflate::gzip; #[derive(Clone, Copy, Debug, PartialEq, Eq, PartialOrd, Ord, Hash)] pub struct SystemId(usize); #[derive(Debug)] pub struct SystemInfo { pub system_id: SystemId, pub name: String, pub stargates: Vec<SystemId>, pub system_index: usize, } #[derive(Debug)] pub struct Map { systems: Vec<SystemInfo>, by_system_id: HashMap<SystemId, usize>, by_name: HashMap<String, usize>, } mod json_repr { use std::collections::HashMap; use serde::{de, Deserialize, Deserializer}; use serde_json::{self, Value}; use std::str::FromStr; fn de_from_f64<'de, D>(deserializer: D) -> Result<f64, D::Error> where D: Deserializer<'de>, { let v = Value::deserialize(deserializer)?; let e = "an f64 literal or string"; match v { Value::Number(v) => Ok(v.as_f64().unwrap()), Value::String(s) => f64::from_str(&s).map_err(de::Error::custom), Value::Null => { let ue = de::Unexpected::Other("null"); Err(de::Error::invalid_value(ue, &e)) } Value::Bool(b) => { let ue = de::Unexpected::Bool(b); Err(de::Error::invalid_value(ue, &e)) }
#[derive(Deserialize)] pub struct Destination { pub stargate_id: usize, pub system_id: usize, } #[derive(Deserialize)] pub struct Point { #[serde(deserialize_with = "de_from_f64")] pub x: f64, #[serde(deserialize_with = "de_from_f64")] pub y: f64, #[serde(deserialize_with = "de_from_f64")] pub z: f64, } #[derive(Deserialize)] pub struct Stargate { pub destination: Destination, pub name: String, pub position: Point, pub stargate_id: usize, pub system_id: usize, pub type_id: usize, } #[derive(Deserialize)] pub struct Planet { pub asteroid_belts: Option<Vec<usize>>, pub moons: Option<Vec<usize>>, pub planet_id: usize, } #[derive(Deserialize)] pub struct System { pub constellation_id: usize, pub name: String, pub planets: Option<Vec<Planet>>, pub position: Point, pub security_class: Option<String>, pub security_status: f64, pub star_id: Option<usize>, pub stargates: Option<Vec<usize>>, pub stations: Option<Vec<usize>>, pub system_id: usize, } #[derive(Deserialize)] pub struct Map { pub stargates: HashMap<usize, Stargate>, pub systems: HashMap<usize, System>, } } fn find_map_file() -> Result<File, Box<dyn Error>> { let mut f = None; for fname in [ "./static/eve-map.json.gz", "./eve-map.json.gz", "/usr/local/share/eve-map.json.gz", ] .iter() { f = Some(File::open(fname)); if let Some(Ok(f)) = f { return Ok(f); } } f.unwrap().map_err(|e| Box::new(e) as Box<dyn Error>) } impl Map { pub fn fetch() -> Result<Map, Box<dyn Error>> { let map_file = find_map_file()?; let gunzip = gzip::Decoder::new(map_file)?; let map: json_repr::Map = serde_json::from_reader(gunzip)?; let mut by_system_id = HashMap::new(); let mut by_name = HashMap::new(); let mut systems = Vec::with_capacity(map.systems.len()); let mut system_index = 0; for (system_id, system) in &map.systems { let system_id = SystemId(*system_id); let stargates: Vec<SystemId>; match system.stargates { None => continue, Some(ref stargate_ids) => { stargates = stargate_ids .iter() .map(|s| SystemId(map.stargates[s].destination.system_id)) .collect() } } let system_info = SystemInfo { system_id, name: system.name.clone(), stargates, system_index, }; systems.push(system_info); by_system_id.insert(system_id, system_index); by_name.insert(system.name.clone(), system_index); system_index += 1; } Ok(Map { systems, by_system_id, by_name, }) } pub fn by_name<'a>(&'a self, name: &'a str) -> Option<&'a SystemInfo> { self.by_name.get(name).map(|i| &self.systems[*i]) } pub fn by_system_id(&self, id: SystemId) -> &SystemInfo { let i = self .by_system_id .get(&id) .expect("by_system_id: invalid SystemId"); &self.systems[*i] } pub fn systems(&self) -> slice::Iter<'_, SystemInfo> { self.systems.iter() } pub fn systems_ref(&self) -> &[SystemInfo] { &self.systems } }
Value::Array(_) => { let ue = de::Unexpected::Seq; Err(de::Error::invalid_value(ue, &e)) } Value::Object(_) => { let ue = de::Unexpected::Map; Err(de::Error::invalid_value(ue, &e)) } } }
function_block-function_prefix_line
[ { "content": "// Look up the given system name in the map, and panic if\n\n// not found. This should be cleaned up.\n\nfn find_system(map: &Map, name: &str) -> SystemId {\n\n map.by_name(name)\n\n .unwrap_or_else(|| panic!(\"could not find {} in map\", name))\n\n .system_id\n\n}\n\n\n", "file_path": "cmdline/src/main.rs", "rank": 0, "score": 117023.97244430365 }, { "content": "/// Return a shortest route if one exists.\n\npub fn shortest_route(map: &Map, start: SystemId, goal: SystemId) -> Option<Vec<SystemId>> {\n\n // Find single-source shortest paths from start up to goal.\n\n let waypoints = bfs(map, start, Some(goal));\n\n\n\n // Set up state and walk route.\n\n let cur = waypoints.get(&goal)?;\n\n let mut route = Vec::with_capacity(cur.dist as usize);\n\n let mut next_stop = cur.parent;\n\n route.push(cur.cur);\n\n while let Some(system_id) = next_stop {\n\n route.push(system_id);\n\n let cur = waypoints[&system_id].clone();\n\n next_stop = cur.parent;\n\n }\n\n\n\n // Route was walked in reverse order. Reverse and return\n\n // it.\n\n route.reverse();\n\n Some(route)\n\n}\n", "file_path": "plan_b/src/search.rs", "rank": 1, "score": 103333.62657553214 }, { "content": "// Single-source shortest path via Breadth-First Search.\n\n// Returns a waypoint map for further processing.\n\nfn bfs(map: &Map, start: SystemId, goal: Option<SystemId>) -> HashMap<SystemId, Waypoint> {\n\n // Set up data structures and run the search.\n\n let mut q = VecDeque::with_capacity(map.systems_ref().len());\n\n let mut closed = HashMap::new();\n\n q.push_back(Waypoint::new(0, start, None));\n\n loop {\n\n // Examine best waypoint.\n\n let waypoint = match q.pop_front() {\n\n Some(waypoint) => waypoint,\n\n None => return closed,\n\n };\n\n if closed.contains_key(&waypoint.cur) {\n\n continue;\n\n }\n\n closed.insert(waypoint.cur, waypoint.clone());\n\n\n\n // If we have found the goal, we are done.\n\n if goal == Some(waypoint.cur) {\n\n return closed;\n\n }\n\n\n\n // Open the children of the current system.\n\n let map_info = map.by_system_id(waypoint.cur);\n\n for child in map_info.stargates.iter() {\n\n let child_waypoint = Waypoint::new(waypoint.dist + 1, *child, Some(waypoint.cur));\n\n q.push_back(child_waypoint);\n\n }\n\n }\n\n}\n\n\n", "file_path": "plan_b/src/search.rs", "rank": 2, "score": 99114.071556484 }, { "content": "/// Compute the diameter of New Eden, with other interesting\n\n/// info.\n\npub fn diameter(map: &Map) -> DiameterInfo {\n\n // Collect needed info.\n\n let systems = map.systems_ref();\n\n let hops = apsp(map);\n\n let n = systems.len();\n\n\n\n // Reconstruct max diameter and incrementally update\n\n // max endpoints.\n\n let mut diameter = 0;\n\n let mut longest = Vec::new();\n\n for i in 0..n {\n\n for j in i + 1..n {\n\n if let Some(ref hop) = &hops[[i, j]] {\n\n let dist = hop.dist;\n\n if dist > diameter {\n\n diameter = dist;\n\n longest.clear();\n\n }\n\n if dist == diameter {\n\n let iid = systems[i].system_id;\n", "file_path": "plan_b/src/search.rs", "rank": 3, "score": 89230.97000565389 }, { "content": "/// Compute an all-pairs shortest-path route table.\n\npub fn apsp(map: &Map) -> APSPTable {\n\n // Set up necessary info.\n\n let systems = map.systems_ref();\n\n let n = systems.len();\n\n let mut hops: Array2<Option<Hop>> = Array2::from_elem((n, n), None);\n\n\n\n // Use iterated single-source shortest-path search to update\n\n // all hops.\n\n for start in systems {\n\n let j = start.system_index;\n\n let routes = bfs(map, start.system_id, None);\n\n for waypoint in routes.values() {\n\n let parent_info = match waypoint.parent {\n\n None => {\n\n assert!(waypoint.cur == start.system_id);\n\n continue;\n\n }\n\n Some(system_id) => map.by_system_id(system_id),\n\n };\n\n let parent_index = parent_info.system_index;\n", "file_path": "plan_b/src/search.rs", "rank": 4, "score": 89230.97000565389 }, { "content": "// Display a given route, one system per line.\n\nfn show_route(map: &Map, route: &[SystemId]) {\n\n for system_id in route {\n\n let system = map.by_system_id(*system_id);\n\n println!(\"{}\", system.name);\n\n }\n\n}\n\n\n", "file_path": "cmdline/src/main.rs", "rank": 5, "score": 87168.56141364669 }, { "content": "// Find a shortest route by name, or panic if none exists.\n\nfn find_route(map: &Map, start: &str, goal: &str) -> Vec<SystemId> {\n\n let start_id = find_system(&map, start);\n\n let goal_id = find_system(&map, goal);\n\n shortest_route(&map, start_id, goal_id)\n\n .unwrap_or_else(|| panic!(\"no route found from {} to {}\", start, goal))\n\n}\n\n\n", "file_path": "cmdline/src/main.rs", "rank": 6, "score": 73026.26109835858 }, { "content": "// Find all shortest routes by name, or panic if none exists.\n\nfn find_all_routes(map: &Map, start: &str, goal: &str) -> Vec<Vec<SystemId>> {\n\n let start_id = find_system(&map, start);\n\n let goal_id = find_system(&map, goal);\n\n let apsp = apsp(&map);\n\n shortest_routes_apsp(&map, &apsp, start_id, goal_id)\n\n .unwrap_or_else(|| panic!(\"no route found from {} to {}\", start, goal))\n\n}\n\n\n\n#[test]\n", "file_path": "cmdline/src/main.rs", "rank": 7, "score": 70256.86912879148 }, { "content": "#[allow(clippy::too_many_arguments)]\n\npub fn alt_routes(\n\n _map: &Map,\n\n _apsp: &APSPTable,\n\n _start: SystemId,\n\n _goal: SystemId,\n\n _max_routes: usize,\n\n _sharing: f64,\n\n _local_opt: f64,\n\n _ub_stretch: f64,\n\n) -> Vec<Vec<SystemId>> {\n\n unimplemented!(\"compute alternate routes\")\n\n}\n\n\n", "file_path": "plan_b/src/search.rs", "rank": 8, "score": 64939.49602188138 }, { "content": "/// Reconstruct shortest routes from start to goal, if any,\n\n/// using the APSP table.\n\npub fn shortest_routes_apsp(\n\n map: &Map,\n\n apsp: &APSPTable,\n\n start: SystemId,\n\n goal: SystemId,\n\n) -> Option<Vec<Vec<SystemId>>> {\n\n let systems = map.systems_ref();\n\n let mut start = map.by_system_id(start).system_index;\n\n let goal = map.by_system_id(goal).system_index;\n\n let full_hop = match apsp[[start, goal]] {\n\n Some(ref hop) => hop,\n\n None => return None,\n\n };\n\n let mut dist = full_hop.dist;\n\n let mut routes: Vec<Vec<SystemId>> = Vec::new();\n\n let mut route: Vec<SystemId> = vec![systems[start].system_id];\n\n while start != goal {\n\n assert!(dist > 0);\n\n let next_neighbors = &apsp[[start, goal]].as_ref().expect(\"missing hop\").next;\n\n let n = next_neighbors.len();\n", "file_path": "plan_b/src/search.rs", "rank": 9, "score": 63358.58807304525 }, { "content": "#[derive(Clone, PartialOrd, Ord, PartialEq, Eq)]\n\nstruct Waypoint {\n\n /// Distance from start.\n\n dist: usize,\n\n /// System id of current system.\n\n cur: SystemId,\n\n /// Next hop back toward parent, if not at start.\n\n parent: Option<SystemId>,\n\n}\n\n\n\nimpl Waypoint {\n\n /// Create a new waypoint; mild syntactic sugar.\n\n fn new(dist: usize, cur: SystemId, parent: Option<SystemId>) -> Waypoint {\n\n Waypoint { dist, cur, parent }\n\n }\n\n}\n\n\n", "file_path": "plan_b/src/search.rs", "rank": 11, "score": 39120.593629051655 }, { "content": "#[derive(FromForm)]\n\nstruct RouteSpec {\n\n from: String,\n\n to: String,\n\n}\n\n\n", "file_path": "web/src/main.rs", "rank": 12, "score": 38125.98512144048 }, { "content": "struct StaticPath(PathBuf);\n\n\n\n// Display the Plan B front page.\n\n#[get(\"/\")]\n\nasync fn front_page(\n\n static_path: &State<StaticPath>,\n\n) -> Result<NamedFile, rocket::response::Debug<std::io::Error>> {\n\n let path = static_path.0.join(\"plan-b.html\");\n\n Ok(NamedFile::open(path).await?)\n\n}\n\n\n\n// Display the Plan B favicon.\n\n#[get(\"/favicon.ico\")]\n\nasync fn favicon(\n\n static_path: &State<StaticPath>,\n\n) -> Result<NamedFile, rocket::response::Debug<std::io::Error>> {\n\n let path = static_path.0.join(\"plan-b-favicon.ico\");\n\n Ok(NamedFile::open(path).await?)\n\n}\n\n\n", "file_path": "web/src/main.rs", "rank": 13, "score": 34435.98434540164 }, { "content": "// Command-line Plan B. */\n\nfn main() {\n\n // Set up the map.\n\n let map = Map::fetch().expect(\"could not open map\");\n\n\n\n // Get and process the arguments.\n\n let opt = Opt::from_args();\n\n\n\n // Just do diameter.\n\n match opt {\n\n Opt::Diameter => {\n\n // Run the diameter calculation and display the result.\n\n let diameter_info = diameter(&map);\n\n println!(\"diameter {}\", diameter_info.diameter);\n\n for (start, end) in diameter_info.longest {\n\n let start = &map.by_system_id(start).name;\n\n let end = &map.by_system_id(end).name;\n\n println!(\"{} → {}\", start, end);\n\n }\n\n }\n\n Opt::Route { all, start, goal } => {\n", "file_path": "cmdline/src/main.rs", "rank": 14, "score": 33682.46072936741 }, { "content": "// Check for correct computation of a long route.\n\nfn short_route_north_south() {\n\n let map = Map::fetch().expect(\"could not open map\");\n\n let route = find_route(&map, \"B-GC1T\", \"2UK4-N\");\n\n assert_eq!(80, route.len());\n\n}\n\n\n", "file_path": "cmdline/src/main.rs", "rank": 15, "score": 31148.883604466406 }, { "content": "# Copyright © 2018 Po Huit\n\n# [This program is licensed under the \"MIT License\"]\n\n# Please see the file LICENSE in the source\n\n# distribution of this software for license terms.\n\n\n\n# Fetch EVE systems and stargates using ESI\n\n\n\nfrom time import sleep\n\nimport http.client as client\n\nimport json\n\nfrom sys import stdout, stderr\n\nimport threading\n\n\n\n# Where to fetch the maps from.\n\nesi_endpoint = \"esi.evetech.net\"\n\n# What version to fetch.\n\nesi_version = \"latest\"\n\n# Number of retries before giving up.\n\nmax_retries = 5\n\n# How long to wait between retries (secs).\n\nretry_timeout = 5.0\n\n# How long to wait before reopening the connection (secs).\n\nreopen_timeout = 5.0\n\n# Delay inserted to max at given request rate (per sec).\n\nrequest_rate = 20.0\n\n# Number of simultaneous fetch threads to spawn.\n\nnthreads = 20\n\n\n\n# https://stackoverflow.com/a/312464\n\ndef chunks(l, n):\n\n \"Yield n equal-sized chunks from l.\"\n\n nl = len(l)\n\n nchunk = nl // n\n\n for i in range(0, nl, nchunk):\n\n yield l[i:i + nchunk]\n\n\n\ndef log(*args):\n\n \"Print to stdout and flush.\"\n\n print(*args)\n\n stdout.flush()\n\n\n\n# Thread-local storage.\n\ntls = threading.local()\n\n\n\ndef ccp_request(path):\n\n \"Make an ESI request.\"\n\n url = \"/\" + esi_version + \"/\" + path + \"/\"\n\n for retries in range(max_retries):\n\n try:\n\n if retries == 1:\n\n sleep(reopen_timeout)\n\n tls.connection.close()\n\n tls.connection = client.HTTPSConnection(esi_endpoint)\n\n else:\n\n sleep(1.0/request_rate)\n\n tls.connection.request('GET', url)\n\n response = tls.connection.getresponse()\n\n if response.status == 200:\n\n try:\n\n return json.load(response)\n\n except json.decoder.JSONDecodeError as e:\n\n print(\"json error: \", e, file=stderr)\n\n else:\n\n print(\"bad response status: \", response.status, file=stderr)\n\n except client.HTTPException as e:\n\n print(\"http error: \", e.code, file=stderr)\n\n if retries < max_retries - 1:\n\n sleep(retry_timeout)\n\n print(\"fetch failed for\", url, file=stderr)\n\n exit(1)\n\n\n\n# Map of retrieved systems and stargates.\n\nby_system_id = dict()\n\nby_stargate_id = dict()\n\n\n\n# A thread worker.\n\ndef worker(systems):\n\n \"Fetch the given systems' information via ESI.\"\n\n global by_system_id, by_stargate_id\n\n tls.connection = client.HTTPSConnection(esi_endpoint)\n\n tls.by_system_id = dict()\n\n tls.by_stargate_id = dict()\n\n\n\n # Grab the systems.\n\n for system_id in systems:\n\n system = ccp_request('universe/systems/' + str(system_id))\n\n log(system['name'])\n\n tls.by_system_id[system_id] = system\n\n\n\n # Grab the stargates for each system.\n\n for system_id, system in tls.by_system_id.items():\n\n if 'stargates' not in system:\n\n continue\n\n stargates = system['stargates']\n\n for stargate_id in stargates:\n\n stargate = ccp_request('universe/stargates/' + str(stargate_id))\n\n log(system['name'], \"->\", stargate_id)\n\n tls.by_stargate_id[stargate_id] = stargate\n\n\n\n # Move system and stargate information to the global map.\n\n for system_id, system in tls.by_system_id.items():\n\n by_system_id[system_id] = system\n\n for stargate_id, stargate in tls.by_stargate_id.items():\n\n by_stargate_id[stargate_id] = stargate\n\n\n\n# Open the master connection and get a list of systems.\n\ntls.connection = client.HTTPSConnection(esi_endpoint)\n\nsystems = ccp_request('universe/systems')\n\nnsystems = len(systems)\n\nlog(nsystems, \"systems\")\n\n\n\n# Start and collect the threads.\n\nthreads = [threading.Thread(target=worker, args=(chunk,))\n\n for chunk in chunks(systems, nthreads)]\n\nfor t in threads:\n\n t.start()\n\nfor t in threads:\n\n t.join()\n\n\n\n# Write the output JSON.\n\ninfo = {'systems': by_system_id, 'stargates': by_stargate_id}\n\nwith open('eve-map.json', 'w') as dumpfile:\n\n json.dump(info, dumpfile)\n", "file_path": "fetch-map/fetch-map.py", "rank": 16, "score": 29851.816845574245 }, { "content": "#[launch]\n\nfn rocket() -> Rocket<Build> {\n\n async fn attach_path(rocket: Rocket<Build>) -> Rocket<Build> {\n\n let static_path = [\"web\", \"static\"].iter().collect();\n\n rocket.manage(StaticPath(static_path))\n\n }\n\n\n\n rocket::build()\n\n .attach(AdHoc::on_ignite(\"Static Path\", attach_path))\n\n .manage(Map::fetch().expect(\"could not load map\"))\n\n .mount(\"/\", routes![front_page, favicon, search_route])\n\n}\n", "file_path": "web/src/main.rs", "rank": 17, "score": 29169.95833939705 }, { "content": "def worker(systems):\n\n \"Fetch the given systems' information via ESI.\"\n\n global by_system_id, by_stargate_id\n\n tls.connection = client.HTTPSConnection(esi_endpoint)\n\n tls.by_system_id = dict()\n\n tls.by_stargate_id = dict()\n\n\n\n # Grab the systems.\n\n for system_id in systems:\n\n system = ccp_request('universe/systems/' + str(system_id))\n\n log(system['name'])\n\n tls.by_system_id[system_id] = system\n\n\n\n # Grab the stargates for each system.\n\n for system_id, system in tls.by_system_id.items():\n\n if 'stargates' not in system:\n\n continue\n\n stargates = system['stargates']\n\n for stargate_id in stargates:\n\n stargate = ccp_request('universe/stargates/' + str(stargate_id))\n\n log(system['name'], \"->\", stargate_id)\n\n tls.by_stargate_id[stargate_id] = stargate\n\n\n\n # Move system and stargate information to the global map.\n\n for system_id, system in tls.by_system_id.items():\n\n by_system_id[system_id] = system\n\n for stargate_id, stargate in tls.by_stargate_id.items():\n", "file_path": "fetch-map/fetch-map.py", "rank": 18, "score": 20018.460892841595 }, { "content": "def log(*args):\n\n \"Print to stdout and flush.\"\n\n print(*args)\n", "file_path": "fetch-map/fetch-map.py", "rank": 19, "score": 20016.182537207114 }, { "content": "def chunks(l, n):\n\n \"Yield n equal-sized chunks from l.\"\n\n nl = len(l)\n\n nchunk = nl // n\n\n for i in range(0, nl, nchunk):\n", "file_path": "fetch-map/fetch-map.py", "rank": 20, "score": 20016.182537207114 }, { "content": "def ccp_request(path):\n\n \"Make an ESI request.\"\n\n url = \"/\" + esi_version + \"/\" + path + \"/\"\n\n for retries in range(max_retries):\n\n try:\n\n if retries == 1:\n\n sleep(reopen_timeout)\n\n tls.connection.close()\n\n tls.connection = client.HTTPSConnection(esi_endpoint)\n\n else:\n\n sleep(1.0/request_rate)\n\n tls.connection.request('GET', url)\n\n response = tls.connection.getresponse()\n\n if response.status == 200:\n\n try:\n\n return json.load(response)\n\n except json.decoder.JSONDecodeError as e:\n\n print(\"json error: \", e, file=stderr)\n\n else:\n\n print(\"bad response status: \", response.status, file=stderr)\n\n except client.HTTPException as e:\n\n print(\"http error: \", e.code, file=stderr)\n\n if retries < max_retries - 1:\n\n sleep(retry_timeout)\n\n print(\"fetch failed for\", url, file=stderr)\n", "file_path": "fetch-map/fetch-map.py", "rank": 21, "score": 19481.781200272606 }, { "content": " /// length equal to diameter.\n\n pub longest: Vec<(SystemId, SystemId)>,\n\n}\n\n\n\n/// An entry in the all-pairs shortest-path table.\n\n#[derive(Clone)]\n\npub struct Hop {\n\n /// System indices of next hops.\n\n pub next: Vec<usize>,\n\n /// Distance from start to here.\n\n pub dist: usize,\n\n}\n\n\n\n/// Table of all-pairs shortest paths.\n\npub type APSPTable = Array2<Option<Hop>>;\n\n\n\n/// An intermediate step in the BFS shortest path search.\n\n#[derive(Clone, PartialOrd, Ord, PartialEq, Eq)]\n", "file_path": "plan_b/src/search.rs", "rank": 33, "score": 10.441021939920512 }, { "content": "// Process an EVE route request.\n\n#[post(\"/\", data = \"<route_spec>\")]\n\nasync fn search_route(route_spec: Form<RouteSpec>, map: &State<Map>) -> Option<String> {\n\n let from = map.by_name(&route_spec.from)?;\n\n let to = map.by_name(&route_spec.to)?;\n\n let route: Vec<String> = shortest_route(&map, from.system_id, to.system_id)?\n\n .iter()\n\n .map(|system_id| map.by_system_id(*system_id).name.to_string())\n\n .collect();\n\n Some(route.join(\"\\n\"))\n\n}\n\n\n\n// Plan B web service.\n", "file_path": "web/src/main.rs", "rank": 34, "score": 9.436274634800276 }, { "content": "// Copyright © 2018 Po Huit\n\n// [This program is licensed under the \"MIT License\"]\n\n// Please see the file LICENSE in the source\n\n// distribution of this software for license terms.\n\n\n\n//! Search functionality for Plan B.\n\n\n\nuse std::cmp::Ordering;\n\nuse std::collections::HashMap;\n\nuse std::collections::VecDeque;\n\n\n\nuse ndarray::Array2;\n\n\n\nuse crate::map::*;\n\n\n\n/// Results from a `diameter()` calculation.\n\npub struct DiameterInfo {\n\n /// Diameter of EVE.\n\n pub diameter: usize,\n\n /// List of endpoints with shortest route of\n", "file_path": "plan_b/src/search.rs", "rank": 35, "score": 8.800051914713123 }, { "content": "// Copyright © 2018 Po Huit\n\n// [This program is licensed under the \"MIT License\"]\n\n// Please see the file LICENSE in the source\n\n// distribution of this software for license terms.\n\n\n\n//! Plan B: EVE route planner library with options\n\n//!\n\n//! This crate provides facilities for routing in the New\n\n//! Eden universe.\n\n\n\npub mod map;\n\npub mod search;\n\n\n\npub use crate::map::*;\n\npub use crate::search::*;\n", "file_path": "plan_b/src/lib.rs", "rank": 36, "score": 8.675575999490093 }, { "content": "#[derive(StructOpt, Debug)]\n\n#[structopt(name = \"plan-b\")]\n\nenum Opt {\n\n Diameter,\n\n Route {\n\n #[structopt(short = \"a\", long = \"all\")]\n\n all: bool,\n\n #[structopt(name = \"START\")]\n\n start: String,\n\n #[structopt(name = \"GOAL\")]\n\n goal: String,\n\n },\n\n}\n\n\n", "file_path": "cmdline/src/main.rs", "rank": 37, "score": 7.449286342606429 }, { "content": "// Copyright © 2018 Po Huit\n\n// [This program is licensed under the \"MIT License\"]\n\n// Please see the file LICENSE in the source\n\n// distribution of this software for license terms.\n\n\n\n// Plan B: EVE route planner with options\n\n// Command-line demo client\n\n\n\nuse structopt::StructOpt;\n\n\n\nuse plan_b::*;\n\n\n\n// Command-line arguments\n\n\n\n#[derive(StructOpt, Debug)]\n\n#[structopt(name = \"plan-b\")]\n", "file_path": "cmdline/src/main.rs", "rank": 38, "score": 7.152226259867621 }, { "content": "### Get The Map Data (Optional)\n\n\n\nI have included `eve-map.json.gz` in the repository\n\ntop-level containing EVE System and Stargate data in\n\ncompressed JSON. Copy this file to `/usr/local/share` on\n\nyour box and ideally you should be set.\n\n\n\nEVE Systems and Stargates have been changing recently. If\n\nyou need to regather the map data, go to the `fetch-map`\n\ndirectory and run `python3 fetch-map.py`. This should run\n\nfor less than 30 minutes with a decent Internet connection,\n\nand will create `eve-map.json` by fetching the necessary\n\ndata from [CCP](https://www.ccpgames.com/)'s Tranquility\n\nserver using\n\n[ESI](http://eveonline-third-party-documentation.readthedocs.io/en/latest/esi/).\n\nCompress this file with `gzip` and you're ready to proceed\n\nas above.\n\n\n\n### Build The Rust Code\n\n\n\n1. Get the relevant version of Rust installed on your\n\n system.\n\n\n\n2. Run `cargo build --release` from the top-level directory.\n\n\n\nThe build will take a few minutes, and then the code should\n\nbe ready to go.\n\n\n\n## License\n\n\n\nThis program is licensed under the \"MIT License\". Please\n\nsee the file LICENSE in the source distribution of this\n\nsoftware for license terms.\n\n\n\n## Acknowlegements\n\n\n\nThanks to Sparky Doosan for the name. Thanks to my EVE\n\nOnline software development class for being part of the\n\nproject. Thanks to Sergio Benitez *et al* for the Rocket web\n\nframework, and to the various Rust developers whose crates\n\nare used by my project.\n", "file_path": "README.md", "rank": 39, "score": 6.692146434954286 }, { "content": " let cur_info = map.by_system_id(waypoint.cur);\n\n let i = cur_info.system_index;\n\n let old_hop = hops[[i, j]].take();\n\n match old_hop {\n\n Some(mut hop) => {\n\n match hop.dist.cmp(&waypoint.dist) {\n\n Ordering::Greater => {\n\n hop.dist = waypoint.dist;\n\n hop.next = vec![parent_index];\n\n }\n\n Ordering::Equal => {\n\n hop.next.push(parent_index);\n\n println!(\"multiple {:?}\", hop.next);\n\n }\n\n Ordering::Less => (),\n\n }\n\n hops[[i, j]] = Some(hop);\n\n }\n\n None => {\n\n let new_hop = Some(Hop {\n", "file_path": "plan_b/src/search.rs", "rank": 40, "score": 4.779569416476959 }, { "content": "# \"Plan B\": An EVE Route Planner With Options\n\nCopyright (c) 2018 Po Huit\n\n\n\n*Plan B (thanks to Cousin Rob for the name) is an EVE route\n\nplanner that offers reasonable alternative routes.* Plan B\n\nwas inspired by the alternate routes facility in Google\n\nMaps. Sometimes the \"best\" route isn't quite the\n\nfastest/shortest one: this tool can give you options.\n\n\n\nPlan B will allow selecting start, end and waypoints from\n\nany named system, your current location taken from EVE,\n\nlocation of personal assets, or commonly-used systems such\n\nas trade hubs. Given the route specification, Plan B will\n\ncompute some number of differentiated routes optimized for\n\ntravel time. It can enter a sparsified set of waypoints for\n\nthe route into EVE, or can present successive jumps as you\n\ntravel through space.\n\n\n\n## Partial Roadmap\n\n\n\n* Version 0.1, 1 May 2018: Command-line tool. Accepts\n\n starting and ending system by name. Computes shortest\n\n route and displays it in a reasonable ASCII format.\n\n\n\n* Version 0.2, 8 May 2018: Presents as a browser app.\n\n\n\n* Version 0.3, 15 May 2018: Computes *k*-best routes\n\n and displays them in a reasonable ASCII format.\n\n\n\n* Version 0.4, 22 May 2018: Acquires current location via\n\n ESI. Can post selected route by setting waypoints via ESI.\n\n Shows next jump during travel.\n\n\n\n* Version 0.3, 29 May 2018: Provides a visual route map with\n\n a route selection interface. Heuristic prioritizes\n\n differentiated routes.\n", "file_path": "docs/vision.md", "rank": 41, "score": 4.216635357977088 }, { "content": "// Copyright © 2018 Po Huit\n\n// [This program is licensed under the \"MIT License\"]\n\n// Please see the file LICENSE in the source\n\n// distribution of this software for license terms.\n\n\n\n// Plan B: EVE route planner with options\n\n// Web client\n\n\n\nuse std::path::PathBuf;\n\n\n\nuse rocket::fairing::AdHoc;\n\nuse rocket::form::Form;\n\nuse rocket::fs::NamedFile;\n\nuse rocket::*;\n\n\n\nuse plan_b::*;\n\n\n\n// Need to wrap the EVE route spec for use in endpoints.\n\n// XXX The word \"route\" is ambiguous in this code.\n\n#[derive(FromForm)]\n", "file_path": "web/src/main.rs", "rank": 42, "score": 3.9879116327873882 }, { "content": " assert!(n > 0);\n\n if n > 1 {\n\n for neighbor in next_neighbors {\n\n let neighbor = &systems[*neighbor];\n\n let finishes =\n\n shortest_routes_apsp(map, apsp, neighbor.system_id, systems[goal].system_id)\n\n .expect(\"could not extend route\");\n\n for rest in finishes {\n\n assert!(rest.len() == dist);\n\n let mut full = route.clone();\n\n full.extend(rest);\n\n routes.push(full);\n\n }\n\n }\n\n return Some(routes);\n\n }\n\n let next = next_neighbors[0];\n\n route.push(systems[next].system_id);\n\n dist -= 1;\n\n start = next;\n\n }\n\n routes.push(route);\n\n Some(routes)\n\n}\n\n\n", "file_path": "plan_b/src/search.rs", "rank": 43, "score": 3.6737209960964217 }, { "content": "# Plan B\n\nCopyright (c) 2018 Po Huit\n\n\n\nPlan B is an [EVE Online](http://eveonline.com) route\n\nplanner. Plan B currently calculates a shortest route, but\n\nis eventually intended to show reasonable alternative routes\n\nalso (hence the name).\n\n\n\nThis is very much a work-in-progress. See `vision.md` and\n\n`reqs.md` in `docs/` for a roadmap and status.\n\n\n\nSee *Build* below for detailed build instructions.\n\n\n\n## Usage\n\n\n\nThe core of this project is a Rust library \"crate\",\n\n`plan_b`, containing most of the Plan B logic and\n\ninternals. There are two user interfaces provided to this\n\nlibrary: one command-line and one web.\n\n\n\n### Run The Command-Line Client\n\n\n\nFirst follow the *Build* instructions below. Then\n\n\n\n cargo run -p cmdline --release route <start> <dest>\n\n\n\nto find and to display a shortest route from the system\n\nnamed *start* to the system named *dest*. The code will take\n\na few seconds to load the map, a millisecond or so to find\n\nand display the route, and then will print all the hops, one\n\nper line, on stdout.\n\n\n\nSay\n\n\n\n cargo run -p cmdline --release diameter\n\n\n\nto calculate the\n\n[diameter](http://schildwall.phbv3.de/topology.html)\n\nof New Eden and show the endpoints of the three longest\n\nshortest routes. The code will take a few seconds to\n\ncompute the answer.\n\n\n\n### Run The Webserver\n\n\n\nPlan B can also run as a web service, powered by the\n\n[Rocket](https://github.com/SergioBenitez/Rocket)\n\nRust web framework. \n\n\n\nFirst follow the *Build* instructions below. Then, to start\n\nPlan B Web, `cd` into the `web/` directory and\n\n\n\n cargo run -p web --release\n\n\n\nIt will take a couple of seconds to load the EVE map before\n\nthe server starts processing requests. The server currently\n\nlistens on `localhost:9146`.\n\n\n\n## Build\n\n\n\nThis project is written mostly in Rust, with a little Python\n\nfor convenience. It has only been used/tested on Linux.\n\nThe build process is reasonably simple.\n\n\n", "file_path": "README.md", "rank": 44, "score": 3.265396097624795 }, { "content": " // Show all routes.\n\n if all {\n\n let mut routes = find_all_routes(&map, &start, &goal);\n\n let last = routes.pop().unwrap();\n\n for route in routes {\n\n show_route(&map, &route);\n\n println!();\n\n }\n\n show_route(&map, &last);\n\n return;\n\n }\n\n // Get the destination, find the route and display it.\n\n let route = find_route(&map, &start, &goal);\n\n show_route(&map, &route);\n\n }\n\n }\n\n}\n", "file_path": "cmdline/src/main.rs", "rank": 45, "score": 2.6073053963557724 }, { "content": " let jid = systems[j].system_id;\n\n longest.push((iid, jid));\n\n }\n\n }\n\n }\n\n }\n\n\n\n // Return the accumulated info.\n\n DiameterInfo { diameter, longest }\n\n}\n\n\n", "file_path": "plan_b/src/search.rs", "rank": 46, "score": 2.4533126811406696 }, { "content": "1. Accept starting and ending location [R] [done]\n\n2. Compute a shortest route between endpoints [R] [done]\n\n5. Access EVE map data [R] [done]\n\n15. End-to-end routing time less than 10 seconds [R]\n\n3. Compute multiple short routes between endpoints [HD]\n\n4. Enter a computed route into the EVE client [HD]\n\n12. Provide a visual map [HD]\n\n13. Prioritize differentiated routes [HD]\n\n6. Provide shortcuts for location entry\n\n 6a. Current location [O]\n\n 6b. Asset locations [O]\n\n 7b. Well-known places [O]\n\n7. Support waypoint specification [O]\n\n8. Provide a web interface [HD] [done]\n\n9. Optimize route option presentation [O]\n\n10. Rate routes by extra metrics (not length) [O]\n\n11. Optimize routes by travel time [O]\n\n14. Sparsify waypoints [O]\n", "file_path": "docs/reqs.md", "rank": 47, "score": 1.3788484229911977 }, { "content": "\n\n/// Compute and rank all admissable at-most-single-via\n\n/// alternative routes, returning up to *k* best. Based on a\n\n/// metric from\n\n///\n\n/// > *Alternative Routes in Road Networks* \n\n/// > Ittai Abraham, Daniel Delling, Andrew V. Goldberg, Renato F. Werneck \n\n/// > Proc. Experimental Algorithms, 9th International Symposium (SEA 2010) \n\n/// > Naples, Italy May 2010 \n\n///\n\n/// Optimization constraints are:\n\n///\n\n/// * `max_routes`: Maximum number of routes to be returned\n\n/// (including shortest).\n\n/// * `sharing`: Maximum percentage of sharing of a route\n\n/// with the shortest route.\n\n/// * `local_opt`: Percentage of the shortest route length\n\n/// over which the route must be locally optimal (all subroutes\n\n/// of this length are shortest routes).\n\n/// * `ub_stretch`: Percentage of \"stretch\" (extra jumps\n\n/// beyond shortest route) allowed along any subroute of a\n\n/// route.\n\n///\n\n/// The objective function is a heuristic based on the\n\n/// settings of the optimization constraints.\n\n///\n\n/// If there is no route from `start` to `goal`, `None` will\n\n/// be returned. Otherwise, the route list is guaranteed to\n\n/// include at least the shortest route.\n", "file_path": "plan_b/src/search.rs", "rank": 48, "score": 0.9126581237194711 } ]
Rust
src/keyassignment.rs
bcully/wezterm
ea401e1f58ca5a088ac5d5e1d7963f36269afb76
use crate::config::configuration; use crate::mux::domain::DomainId; use serde::{Deserialize, Serialize}; use std::collections::HashMap; use std::path::PathBuf; use term::{KeyCode, KeyModifiers}; #[derive(Debug, Clone, Deserialize, Serialize)] pub enum SpawnTabDomain { DefaultDomain, CurrentTabDomain, Domain(DomainId), DomainName(String), } impl Default for SpawnTabDomain { fn default() -> Self { Self::CurrentTabDomain } } #[derive(Default, Debug, Clone, Deserialize, Serialize)] pub struct SpawnCommand { pub label: Option<String>, pub args: Option<Vec<String>>, pub cwd: Option<PathBuf>, #[serde(default)] pub set_environment_variables: HashMap<String, String>, #[serde(default)] pub domain: SpawnTabDomain, } #[derive(Debug, Clone, Deserialize, Serialize)] pub enum KeyAssignment { SpawnTab(SpawnTabDomain), SpawnWindow, ToggleFullScreen, Copy, Paste, ActivateTabRelative(isize), IncreaseFontSize, DecreaseFontSize, ResetFontSize, ActivateTab(usize), SendString(String), Nop, Hide, Show, CloseCurrentTab, ReloadConfiguration, MoveTabRelative(isize), MoveTab(usize), ScrollByPage(isize), ShowTabNavigator, HideApplication, QuitApplication, SpawnCommandInNewTab(SpawnCommand), SpawnCommandInNewWindow(SpawnCommand), ShowLauncher, } pub struct KeyMap(HashMap<(KeyCode, KeyModifiers), KeyAssignment>); impl KeyMap { pub fn new() -> Self { let mut map = configuration() .key_bindings() .expect("keys section of config to be valid"); macro_rules! m { ($([$mod:expr, $code:expr, $action:expr]),* $(,)?) => { $( map.entry(($code, $mod)).or_insert($action); )* }; }; use KeyAssignment::*; let ctrl_shift = KeyModifiers::CTRL | KeyModifiers::SHIFT; m!( [KeyModifiers::SHIFT, KeyCode::Insert, Paste], [KeyModifiers::SUPER, KeyCode::Char('c'), Copy], [KeyModifiers::SUPER, KeyCode::Char('v'), Paste], [ctrl_shift, KeyCode::Char('C'), Copy], [ctrl_shift, KeyCode::Char('V'), Paste], [KeyModifiers::ALT, KeyCode::Char('\n'), ToggleFullScreen], [KeyModifiers::ALT, KeyCode::Char('\r'), ToggleFullScreen], [KeyModifiers::ALT, KeyCode::Enter, ToggleFullScreen], [KeyModifiers::SUPER, KeyCode::Char('m'), Hide], [KeyModifiers::SUPER, KeyCode::Char('n'), SpawnWindow], [ctrl_shift, KeyCode::Char('M'), Hide], [ctrl_shift, KeyCode::Char('N'), SpawnWindow], [KeyModifiers::CTRL, KeyCode::Char('-'), DecreaseFontSize], [KeyModifiers::CTRL, KeyCode::Char('0'), ResetFontSize], [KeyModifiers::CTRL, KeyCode::Char('='), IncreaseFontSize], [KeyModifiers::SUPER, KeyCode::Char('-'), DecreaseFontSize], [KeyModifiers::SUPER, KeyCode::Char('0'), ResetFontSize], [KeyModifiers::SUPER, KeyCode::Char('='), IncreaseFontSize], [ KeyModifiers::SUPER, KeyCode::Char('t'), SpawnTab(SpawnTabDomain::CurrentTabDomain) ], [ ctrl_shift, KeyCode::Char('T'), SpawnTab(SpawnTabDomain::CurrentTabDomain) ], [ KeyModifiers::SUPER | KeyModifiers::SHIFT, KeyCode::Char('T'), SpawnTab(SpawnTabDomain::CurrentTabDomain) ], [KeyModifiers::SUPER, KeyCode::Char('1'), ActivateTab(0)], [KeyModifiers::SUPER, KeyCode::Char('2'), ActivateTab(1)], [KeyModifiers::SUPER, KeyCode::Char('3'), ActivateTab(2)], [KeyModifiers::SUPER, KeyCode::Char('4'), ActivateTab(3)], [KeyModifiers::SUPER, KeyCode::Char('5'), ActivateTab(4)], [KeyModifiers::SUPER, KeyCode::Char('6'), ActivateTab(5)], [KeyModifiers::SUPER, KeyCode::Char('7'), ActivateTab(6)], [KeyModifiers::SUPER, KeyCode::Char('8'), ActivateTab(7)], [KeyModifiers::SUPER, KeyCode::Char('9'), ActivateTab(8)], [KeyModifiers::SUPER, KeyCode::Char('w'), CloseCurrentTab], [ctrl_shift, KeyCode::Char('1'), ActivateTab(0)], [ctrl_shift, KeyCode::Char('2'), ActivateTab(1)], [ctrl_shift, KeyCode::Char('3'), ActivateTab(2)], [ctrl_shift, KeyCode::Char('4'), ActivateTab(3)], [ctrl_shift, KeyCode::Char('5'), ActivateTab(4)], [ctrl_shift, KeyCode::Char('6'), ActivateTab(5)], [ctrl_shift, KeyCode::Char('7'), ActivateTab(6)], [ctrl_shift, KeyCode::Char('8'), ActivateTab(7)], [ctrl_shift, KeyCode::Char('9'), ActivateTab(8)], [ctrl_shift, KeyCode::Char('W'), CloseCurrentTab], [ KeyModifiers::SUPER | KeyModifiers::SHIFT, KeyCode::Char('['), ActivateTabRelative(-1) ], [ KeyModifiers::SUPER | KeyModifiers::SHIFT, KeyCode::Char('{'), ActivateTabRelative(-1) ], [ KeyModifiers::SUPER | KeyModifiers::SHIFT, KeyCode::Char(']'), ActivateTabRelative(1) ], [ KeyModifiers::SUPER | KeyModifiers::SHIFT, KeyCode::Char('}'), ActivateTabRelative(1) ], [KeyModifiers::SUPER, KeyCode::Char('r'), ReloadConfiguration], [ctrl_shift, KeyCode::Char('R'), ReloadConfiguration], [ctrl_shift, KeyCode::PageUp, MoveTabRelative(-1)], [ctrl_shift, KeyCode::PageDown, MoveTabRelative(1)], [KeyModifiers::SHIFT, KeyCode::PageUp, ScrollByPage(-1)], [KeyModifiers::SHIFT, KeyCode::PageDown, ScrollByPage(1)], [KeyModifiers::ALT, KeyCode::Char('9'), ShowTabNavigator], ); #[cfg(target_os = "macos")] m!([KeyModifiers::SUPER, KeyCode::Char('h'), HideApplication],); Self(map) } pub fn lookup(&self, key: KeyCode, mods: KeyModifiers) -> Option<KeyAssignment> { self.0 .get(&(key.normalize_shift_to_upper_case(mods), mods)) .cloned() } }
use crate::config::configuration; use crate::mux::domain::DomainId; use serde::{Deserialize, Serialize}; use std::collections::HashMap; use std::path::PathBuf; use term::{KeyCode, KeyModifiers}; #[derive(Debug, Clone, Deserialize, Serialize)] pub enum SpawnTabDomain { DefaultDomain, CurrentTabDomain, Domain(DomainId), DomainName(String), } impl Default for SpawnTabDomain { fn default() -> Self { Self::CurrentTabDomain } } #[derive(Default, Debug, Clone, Deserialize, Serialize)] pub struct SpawnCommand { pub label: Option<String>, pub args: Option<Vec<String>>, pub cwd: Option<PathBuf>, #[serde(default)] pub set_environment_variables: HashMap<String, String>, #[serde(default)] pub domain: SpawnTabDomain, } #[derive(Debug, Clone, Deserialize, Serialize)] pub enum KeyAssignment { SpawnTab(SpawnTabDomain), SpawnWindow, ToggleFullScreen, Copy, Paste, ActivateTabRelative(isize), IncreaseFontSize, DecreaseFontSize, ResetFontSize, ActivateTab(usize), SendString(String), Nop, Hide, Show, CloseCurrentTab, ReloadConfiguration, MoveTabRelative(isize), MoveTab(usize), ScrollByPage(isize), ShowTabNavigator, HideApplication, QuitApplication, SpawnCommandInNewTab(SpawnCommand), SpawnCommandInNewWindow(SpawnCommand), ShowLauncher, } pub struct KeyMap(HashMap<(KeyCode, KeyModifiers), KeyAssignment>); impl KeyMap { pub fn new() -> Self { let mut map = configuration() .key_bindings() .expect("keys section of config to be valid"); macro_rules! m { ($([$mod:expr, $code:expr, $action:expr]),* $(,)?) => { $( map.entry(($code, $mod)).or_insert($action); )* }; }; use KeyAssignment::*; let ctrl_shift = KeyModifiers::CTRL | KeyModifiers::SHIFT; m!( [KeyModifiers::SHIFT, KeyCode::Insert, Paste], [KeyModifiers::SUPER, KeyCode::Char('c'), Copy], [KeyModifiers::SUPER, KeyCode::Char('v'), Paste], [ctrl_shift, KeyCode::Char('C'), Copy], [ctrl_shift, KeyCode::Char('V'), Paste], [KeyModifiers::ALT, KeyCode::Char('\n'), ToggleFullScreen], [KeyModifiers::ALT, KeyCode::Char('\r'), ToggleFullScreen], [KeyModifiers::ALT, KeyCode::Enter, ToggleFullScreen], [KeyModifiers::SUPER, KeyCode::Char('m'), Hide], [KeyModifiers::SUPER, KeyCode::Char('n'), SpawnWindow], [ctrl_shift, KeyCode::Char('M'), Hide], [ctrl_shift, KeyCode::Char('N'), SpawnWindow], [KeyModifiers::CTRL, KeyCode::Char('-'), DecreaseFontSize], [KeyModifiers::CTRL, KeyCode::Char('0'), ResetFontSize], [KeyModifiers::CTRL, KeyCode::Char('='), IncreaseFontSize], [KeyModifiers::SUPER, KeyCode::Char('-'), DecreaseFontSize], [KeyModifiers::SUPER, KeyCode::Char('0'), ResetFontSize], [KeyModifiers::SUPER, KeyCode::Char('='), IncreaseFontSize], [ KeyModifiers::SUPER, KeyCode::Char('t'), SpawnTab(SpawnTabDomain::CurrentTabDomain) ], [ ctrl_shift, KeyCode::Char('T'), SpawnTab(SpawnTabDomain::CurrentTabDomain) ], [ KeyModifiers::SUPER | KeyModifiers::SHIFT, KeyCode::Char('T'), SpawnTab(SpawnTabDomain::CurrentTabDomain) ], [KeyModifiers::SUPER, KeyCode::Char('1'), ActivateTab(0)], [KeyModifiers::SUPE
pub fn lookup(&self, key: KeyCode, mods: KeyModifiers) -> Option<KeyAssignment> { self.0 .get(&(key.normalize_shift_to_upper_case(mods), mods)) .cloned() } }
R, KeyCode::Char('2'), ActivateTab(1)], [KeyModifiers::SUPER, KeyCode::Char('3'), ActivateTab(2)], [KeyModifiers::SUPER, KeyCode::Char('4'), ActivateTab(3)], [KeyModifiers::SUPER, KeyCode::Char('5'), ActivateTab(4)], [KeyModifiers::SUPER, KeyCode::Char('6'), ActivateTab(5)], [KeyModifiers::SUPER, KeyCode::Char('7'), ActivateTab(6)], [KeyModifiers::SUPER, KeyCode::Char('8'), ActivateTab(7)], [KeyModifiers::SUPER, KeyCode::Char('9'), ActivateTab(8)], [KeyModifiers::SUPER, KeyCode::Char('w'), CloseCurrentTab], [ctrl_shift, KeyCode::Char('1'), ActivateTab(0)], [ctrl_shift, KeyCode::Char('2'), ActivateTab(1)], [ctrl_shift, KeyCode::Char('3'), ActivateTab(2)], [ctrl_shift, KeyCode::Char('4'), ActivateTab(3)], [ctrl_shift, KeyCode::Char('5'), ActivateTab(4)], [ctrl_shift, KeyCode::Char('6'), ActivateTab(5)], [ctrl_shift, KeyCode::Char('7'), ActivateTab(6)], [ctrl_shift, KeyCode::Char('8'), ActivateTab(7)], [ctrl_shift, KeyCode::Char('9'), ActivateTab(8)], [ctrl_shift, KeyCode::Char('W'), CloseCurrentTab], [ KeyModifiers::SUPER | KeyModifiers::SHIFT, KeyCode::Char('['), ActivateTabRelative(-1) ], [ KeyModifiers::SUPER | KeyModifiers::SHIFT, KeyCode::Char('{'), ActivateTabRelative(-1) ], [ KeyModifiers::SUPER | KeyModifiers::SHIFT, KeyCode::Char(']'), ActivateTabRelative(1) ], [ KeyModifiers::SUPER | KeyModifiers::SHIFT, KeyCode::Char('}'), ActivateTabRelative(1) ], [KeyModifiers::SUPER, KeyCode::Char('r'), ReloadConfiguration], [ctrl_shift, KeyCode::Char('R'), ReloadConfiguration], [ctrl_shift, KeyCode::PageUp, MoveTabRelative(-1)], [ctrl_shift, KeyCode::PageDown, MoveTabRelative(1)], [KeyModifiers::SHIFT, KeyCode::PageUp, ScrollByPage(-1)], [KeyModifiers::SHIFT, KeyCode::PageDown, ScrollByPage(1)], [KeyModifiers::ALT, KeyCode::Char('9'), ShowTabNavigator], ); #[cfg(target_os = "macos")] m!([KeyModifiers::SUPER, KeyCode::Char('h'), HideApplication],); Self(map) }
function_block-function_prefixed
[ { "content": "#[allow(dead_code)]\n\npub fn use_default_configuration() {\n\n CONFIG.use_defaults();\n\n}\n\n\n", "file_path": "src/config/mod.rs", "rank": 0, "score": 314081.53445833473 }, { "content": "fn default_term() -> String {\n\n \"xterm-256color\".into()\n\n}\n\n\n", "file_path": "src/config/mod.rs", "rank": 1, "score": 238236.00334725823 }, { "content": "/// Returns a handle to the current configuration\n\npub fn configuration() -> ConfigHandle {\n\n CONFIG.get()\n\n}\n\n\n", "file_path": "src/config/mod.rs", "rank": 2, "score": 238167.09313609218 }, { "content": "/// Computes the r1 - r2, which may result in up to two non-overlapping ranges.\n\npub fn range_subtract<T: Integer + Copy + Debug>(\n\n r1: &Range<T>,\n\n r2: &Range<T>,\n\n) -> (Option<Range<T>>, Option<Range<T>>) {\n\n let i_start = max(r1.start, r2.start);\n\n let i_end = min(r1.end, r2.end);\n\n\n\n if i_end > i_start {\n\n let a = if i_start == r1.start {\n\n // Intersection overlaps with the LHS\n\n None\n\n } else {\n\n // The LHS up to the intersection\n\n Some(r1.start..r1.end.min(i_start))\n\n };\n\n\n\n let b = if i_end == r1.end {\n\n // Intersection overlaps with the RHS\n\n None\n\n } else {\n", "file_path": "rangeset/src/lib.rs", "rank": 3, "score": 220664.2971474543 }, { "content": "/// Computes the intersection of r1 and r2\n\npub fn range_intersection<T: Integer + Copy + Debug>(\n\n r1: &Range<T>,\n\n r2: &Range<T>,\n\n) -> Option<Range<T>> {\n\n let start = max(r1.start, r2.start);\n\n let end = min(r1.end, r2.end);\n\n\n\n if end > start {\n\n Some(start..end)\n\n } else {\n\n None\n\n }\n\n}\n\n\n", "file_path": "rangeset/src/lib.rs", "rank": 4, "score": 220664.2971474543 }, { "content": "fn default_harfbuzz_features() -> Vec<String> {\n\n [\"kern\", \"liga\", \"clig\"]\n\n .iter()\n\n .map(|&s| s.to_string())\n\n .collect()\n\n}\n\n\n", "file_path": "src/config/mod.rs", "rank": 5, "score": 220020.2477154443 }, { "content": "/// If there was an error loading the preferred configuration,\n\n/// return it, otherwise return the current configuration\n\npub fn configuration_result() -> Result<ConfigHandle, Error> {\n\n if let Some(error) = CONFIG.get_error() {\n\n bail!(\"{}\", error);\n\n }\n\n Ok(CONFIG.get())\n\n}\n\n\n", "file_path": "src/config/mod.rs", "rank": 6, "score": 213010.3537474827 }, { "content": "/// If the GUI has been started, pops up a window with the supplied error\n\n/// message framed as a configuration error.\n\n/// If there is no GUI front end, generates a toast notification instead.\n\npub fn show_configuration_error_message(err: &str) {\n\n log::error!(\"While (re)loading configuration: {}\", err);\n\n if crate::frontend::has_gui_front_end() {\n\n let ui = get_error_window();\n\n\n\n let mut wrapped = textwrap::fill(&err, 78);\n\n wrapped.push_str(\"\\n\");\n\n ui.output_str(&wrapped);\n\n } else {\n\n crate::toast_notification(\"Wezterm Configuration\", &err);\n\n }\n\n}\n", "file_path": "src/connui.rs", "rank": 7, "score": 208789.15350728892 }, { "content": "pub trait TerminalConfiguration: std::fmt::Debug {\n\n /// Returns a generation counter for the active\n\n /// configuration. If the implementation may be\n\n /// changed at runtime, it must increment the generation\n\n /// number with each change so that any caches maintained\n\n /// by the terminal can be flushed.\n\n fn generation(&self) -> usize {\n\n 0\n\n }\n\n\n\n fn scrollback_size(&self) -> usize {\n\n 3500\n\n }\n\n\n\n // TODO: expose is_double_click_word in config file\n\n fn is_double_click_word(&self, s: &str) -> bool {\n\n match s.len() {\n\n 1 => match s.chars().nth(0).unwrap() {\n\n ' ' | '\\t' | '\\n' | '{' | '[' | '}' | ']' | '(' | ')' | '\"' | '\\'' => false,\n\n _ => true,\n", "file_path": "term/src/config.rs", "rank": 8, "score": 207345.3466448267 }, { "content": "fn client_domains(config: &config::ConfigHandle) -> Vec<ClientDomainConfig> {\n\n let mut domains = vec![];\n\n for unix_dom in &config.unix_domains {\n\n domains.push(ClientDomainConfig::Unix(unix_dom.clone()));\n\n }\n\n\n\n for ssh_dom in &config.ssh_domains {\n\n domains.push(ClientDomainConfig::Ssh(ssh_dom.clone()));\n\n }\n\n\n\n for tls_client in &config.tls_clients {\n\n domains.push(ClientDomainConfig::Tls(tls_client.clone()));\n\n }\n\n domains\n\n}\n\n\n", "file_path": "src/main.rs", "rank": 9, "score": 202752.54959449064 }, { "content": "/// A convenience around `tabulate_output` that returns a String holding\n\n/// the formatted data.\n\npub fn tabulate_output_as_string<S: std::string::ToString>(\n\n columns: &[Column],\n\n rows: &[Vec<S>],\n\n) -> Result<String, std::io::Error> {\n\n let mut output: Vec<u8> = vec![];\n\n tabulate_output(columns, rows, &mut output)?;\n\n String::from_utf8(output)\n\n .map_err(|e| std::io::Error::new(std::io::ErrorKind::Other, format!(\"{}\", e)))\n\n}\n\n\n\n#[cfg(test)]\n\nmod test {\n\n use super::*;\n\n\n\n #[test]\n\n fn basics() {\n\n let cols = vec![\n\n Column {\n\n name: \"hello\".to_string(),\n\n alignment: Alignment::Left,\n", "file_path": "tabout/src/lib.rs", "rank": 10, "score": 200588.06677912368 }, { "content": "pub fn reload() {\n\n CONFIG.reload();\n\n}\n\n\n", "file_path": "src/config/mod.rs", "rank": 11, "score": 198978.6273745949 }, { "content": "/// Construct a new instance of Terminal.\n\n/// The terminal will have a renderer that is influenced by the configuration\n\n/// in the provided `Capabilities` instance.\n\n/// The terminal will explicitly open `/dev/tty` on Unix systems and\n\n/// `CONIN$` and `CONOUT$` on Windows systems, so that it should yield a\n\n/// functioning console with minimal headaches.\n\n/// If you have a more advanced use case you will want to look to the\n\n/// constructors for `UnixTerminal` and `WindowsTerminal` and call whichever\n\n/// one is most suitable for your needs.\n\npub fn new_terminal(caps: Capabilities) -> Result<impl Terminal, Error> {\n\n SystemTerminal::new(caps)\n\n}\n\n\n\npub(crate) fn cast<T: NumCast + Display + Copy, U: NumCast>(n: T) -> Result<U, Error> {\n\n num::cast(n).ok_or_else(|| anyhow!(\"{} is out of bounds for this system\", n))\n\n}\n", "file_path": "termwiz/src/terminal/mod.rs", "rank": 12, "score": 198294.84309624424 }, { "content": "pub fn alloc_domain_id() -> DomainId {\n\n DOMAIN_ID.fetch_add(1, ::std::sync::atomic::Ordering::Relaxed)\n\n}\n\n\n", "file_path": "src/mux/domain.rs", "rank": 13, "score": 195460.86522342544 }, { "content": "pub fn poll_for_read(pfd: &mut [pollfd]) {\n\n if let Err(e) = poll(pfd, None) {\n\n log::error!(\"poll failed for {}\", e);\n\n }\n\n}\n", "file_path": "src/server/pollable.rs", "rank": 14, "score": 192395.5317651396 }, { "content": "#[derive(Debug, Clone)]\n\nstruct Node<Value: Debug> {\n\n label: u8,\n\n children: Vec<Node<Value>>,\n\n value: Option<Value>,\n\n}\n\n\n\nimpl<Value: Debug> Node<Value> {\n\n fn new(label: u8) -> Self {\n\n Self {\n\n label,\n\n children: Vec::new(),\n\n value: None,\n\n }\n\n }\n\n\n\n fn insert(&mut self, key: &[u8], value: Value) {\n\n if key.is_empty() {\n\n // We've reached the leaf\n\n self.value = Some(value);\n\n return;\n", "file_path": "termwiz/src/keymap.rs", "rank": 15, "score": 191547.27836662636 }, { "content": "fn run_serial(config: config::ConfigHandle, opts: &SerialCommand) -> anyhow::Result<()> {\n\n let fontconfig = Rc::new(FontConfiguration::new());\n\n\n\n let mut serial = portable_pty::serial::SerialTty::new(&opts.port);\n\n if let Some(baud) = opts.baud {\n\n serial.set_baud_rate(serial::BaudRate::from_speed(baud));\n\n }\n\n\n\n let pty_system = Box::new(serial);\n\n let domain: Arc<dyn Domain> = Arc::new(LocalDomain::with_pty_system(\"local\", pty_system));\n\n let mux = Rc::new(mux::Mux::new(Some(domain.clone())));\n\n Mux::set_mux(&mux);\n\n\n\n let front_end = opts.front_end.unwrap_or(config.front_end);\n\n let gui = front_end.try_new()?;\n\n block_on(domain.attach())?; // FIXME: blocking\n\n\n\n let window_id = mux.new_empty_window();\n\n let tab = block_on(domain.spawn(config.initial_size(), None, None, window_id))?; // FIXME: blocking\n\n gui.spawn_new_window(&fontconfig, &tab, window_id)?;\n\n\n\n maybe_show_configuration_error_window();\n\n gui.run_forever()\n\n}\n\n\n", "file_path": "src/main.rs", "rank": 16, "score": 189034.79257529034 }, { "content": "#[cfg(not(target_os = \"macos\"))]\n\n#[doc(hidden)]\n\npub fn poll_impl(pfd: &mut [pollfd], duration: Option<Duration>) -> anyhow::Result<usize> {\n\n let poll_result = unsafe {\n\n libc::poll(\n\n pfd.as_mut_ptr(),\n\n pfd.len() as _,\n\n duration\n\n .map(|wait| wait.as_millis() as libc::c_int)\n\n .unwrap_or(-1),\n\n )\n\n };\n\n if poll_result < 0 {\n\n Err(std::io::Error::last_os_error().into())\n\n } else {\n\n Ok(poll_result as usize)\n\n }\n\n}\n\n\n\n// macOS has a broken poll(2) implementation, so we introduce a layer to deal with that here\n\n#[cfg(target_os = \"macos\")]\n\nmod macos {\n", "file_path": "filedescriptor/src/unix.rs", "rank": 17, "score": 180656.0278122101 }, { "content": "#[doc(hidden)]\n\npub fn poll_impl(pfd: &mut [pollfd], duration: Option<Duration>) -> anyhow::Result<usize> {\n\n let poll_result = unsafe {\n\n WSAPoll(\n\n pfd.as_mut_ptr(),\n\n pfd.len() as _,\n\n duration\n\n .map(|wait| wait.as_millis() as libc::c_int)\n\n .unwrap_or(-1),\n\n )\n\n };\n\n if poll_result < 0 {\n\n Err(std::io::Error::last_os_error().into())\n\n } else {\n\n Ok(poll_result as usize)\n\n }\n\n}\n\n\n\n#[cfg(test)]\n\nmod test {\n\n use std::io::{Read, Write};\n", "file_path": "filedescriptor/src/windows.rs", "rank": 18, "score": 180656.0278122101 }, { "content": "/// Create a `Terminal` with the recommended settings for use with\n\n/// a `LineEditor`.\n\npub fn line_editor_terminal() -> anyhow::Result<impl Terminal> {\n\n let hints = ProbeHints::new_from_env().mouse_reporting(Some(false));\n\n let caps = Capabilities::new_with_hints(hints)?;\n\n new_terminal(caps)\n\n}\n", "file_path": "termwiz/src/lineedit/mod.rs", "rank": 19, "score": 176215.83619597735 }, { "content": "pub fn compute_load_flags_from_config() -> i32 {\n\n let config = configuration();\n\n let flags = match (config.font_hinting, config.font_antialias) {\n\n (FontHinting::VerticalSubpixel, _) | (_, FontAntiAliasing::Subpixel) => {\n\n render_mode_to_load_target(FT_Render_Mode::FT_RENDER_MODE_LCD)\n\n }\n\n (FontHinting::None, _) => {\n\n render_mode_to_load_target(FT_Render_Mode::FT_RENDER_MODE_NORMAL) | FT_LOAD_NO_HINTING\n\n }\n\n (FontHinting::Vertical, FontAntiAliasing::None)\n\n | (FontHinting::Full, FontAntiAliasing::None) => {\n\n render_mode_to_load_target(FT_Render_Mode::FT_RENDER_MODE_MONO)\n\n }\n\n (FontHinting::Vertical, _) => {\n\n render_mode_to_load_target(FT_Render_Mode::FT_RENDER_MODE_LIGHT)\n\n }\n\n (FontHinting::Full, _) => render_mode_to_load_target(FT_Render_Mode::FT_RENDER_MODE_NORMAL),\n\n };\n\n\n\n // If the bitmaps are in color, we want those!\n", "file_path": "src/font/ftwrap.rs", "rank": 20, "score": 174712.9417615445 }, { "content": "/// Computes the effective padding for the RHS.\n\n/// This is needed because the default is 0, but if the user has\n\n/// enabled the scroll bar then they will expect it to have a reasonable\n\n/// size unless they've specified differently.\n\npub fn effective_right_padding(config: &ConfigHandle, render_metrics: &RenderMetrics) -> u16 {\n\n if config.enable_scroll_bar && config.window_padding.right == 0 {\n\n render_metrics.cell_size.width as u16\n\n } else {\n\n config.window_padding.right as u16\n\n }\n\n}\n\n\n\nimpl TermWindow {\n\n pub fn new_window(\n\n config: &ConfigHandle,\n\n fontconfig: &Rc<FontConfiguration>,\n\n tab: &Rc<dyn Tab>,\n\n mux_window_id: MuxWindowId,\n\n ) -> anyhow::Result<()> {\n\n let dims = tab.renderer().get_dimensions();\n\n let physical_rows = dims.viewport_rows;\n\n let physical_cols = dims.cols;\n\n\n\n let render_metrics = RenderMetrics::new(fontconfig);\n", "file_path": "src/frontend/gui/termwindow.rs", "rank": 21, "score": 173462.14851210613 }, { "content": "/// Returns true if r1 intersects r2\n\npub fn intersects_range<T: Integer + Copy + Debug>(r1: &Range<T>, r2: &Range<T>) -> bool {\n\n let start = max(r1.start, r2.start);\n\n let end = min(r1.end, r2.end);\n\n\n\n end > start\n\n}\n\n\n", "file_path": "rangeset/src/lib.rs", "rank": 22, "score": 168810.16820727626 }, { "content": "/// Given a set of column headers and the row content,\n\n/// automatically compute the column widths and then format\n\n/// the data to the output stream.\n\n/// If a given row has more columns than are defined in the\n\n/// columns slice, then a left aligned column with no label\n\n/// will be assumed.\n\npub fn tabulate_output<S: std::string::ToString, W: std::io::Write>(\n\n columns: &[Column],\n\n rows: &[Vec<S>],\n\n output: &mut W,\n\n) -> Result<(), std::io::Error> {\n\n let mut col_widths: Vec<usize> = columns\n\n .iter()\n\n .map(|c| unicode_column_width(&c.name))\n\n .collect();\n\n\n\n let mut display_rows: Vec<Vec<String>> = vec![];\n\n for src_row in rows {\n\n let dest_row: Vec<String> = src_row.iter().map(|col| col.to_string()).collect();\n\n for (idx, col) in dest_row.iter().enumerate() {\n\n let col_width = unicode_column_width(col);\n\n if let Some(width) = col_widths.get_mut(idx) {\n\n *width = (*width).max(col_width);\n\n } else {\n\n col_widths.push(col_width);\n\n }\n", "file_path": "tabout/src/lib.rs", "rank": 23, "score": 168062.85152929602 }, { "content": "fn build_colors() -> HashMap<String, RgbColor> {\n\n let mut map = HashMap::new();\n\n let rgb_txt = include_str!(\"rgb.txt\");\n\n for line in rgb_txt.lines() {\n\n let mut fields = line.split_ascii_whitespace();\n\n let red = fields.next().unwrap();\n\n let green = fields.next().unwrap();\n\n let blue = fields.next().unwrap();\n\n let name = fields.collect::<Vec<&str>>().join(\" \");\n\n\n\n let name = name.to_ascii_lowercase();\n\n map.insert(\n\n name,\n\n RgbColor::new(\n\n red.parse().unwrap(),\n\n green.parse().unwrap(),\n\n blue.parse().unwrap(),\n\n ),\n\n );\n\n }\n", "file_path": "termwiz/src/color.rs", "rank": 24, "score": 167105.69813682782 }, { "content": "pub fn use_ime(enable: bool) {\n\n USE_IME.store(enable, Ordering::Relaxed);\n\n}\n\n\n", "file_path": "window/src/os/macos/window.rs", "rank": 25, "score": 166143.0785886669 }, { "content": "fn read_pipe_with_timeout(mut file: FileDescriptor) -> anyhow::Result<String> {\n\n let mut result = Vec::new();\n\n\n\n file.set_non_blocking(true)?;\n\n let mut pfd = libc::pollfd {\n\n fd: file.as_raw_fd(),\n\n events: libc::POLLIN,\n\n revents: 0,\n\n };\n\n\n\n let mut buf = [0u8; 8192];\n\n\n\n loop {\n\n if unsafe { libc::poll(&mut pfd, 1, 3000) == 1 } {\n\n match file.read(&mut buf) {\n\n Ok(size) if size == 0 => {\n\n break;\n\n }\n\n Ok(size) => {\n\n result.extend_from_slice(&buf[..size]);\n", "file_path": "window/src/os/wayland/window.rs", "rank": 26, "score": 163219.43290904915 }, { "content": "#[derive(Default)]\n\nstruct CopyAndPaste {\n\n owned: Option<String>,\n\n request: Option<Promise<String>>,\n\n time: u32,\n\n}\n\n\n\npub(crate) struct XWindowInner {\n\n window_id: xcb::xproto::Window,\n\n conn: Rc<XConnection>,\n\n callbacks: Box<dyn WindowCallbacks>,\n\n window_context: Context,\n\n width: u16,\n\n height: u16,\n\n expose: VecDeque<Rect>,\n\n paint_all: bool,\n\n buffer_image: BufferImage,\n\n cursor: Option<MouseCursor>,\n\n cursors: HashMap<Option<MouseCursor>, XcbCursor>,\n\n copy_and_paste: CopyAndPaste,\n\n #[cfg(feature = \"opengl\")]\n\n gl_state: Option<Rc<glium::backend::Context>>,\n\n}\n\n\n", "file_path": "window/src/os/x11/window.rs", "rank": 27, "score": 162067.23650713416 }, { "content": "pub fn pki_dir() -> anyhow::Result<PathBuf> {\n\n compute_runtime_dir().map(|d| d.join(\"pki\"))\n\n}\n\n\n", "file_path": "src/config/mod.rs", "rank": 28, "score": 161796.68132783248 }, { "content": "#[async_trait(?Send)]\n\npub trait Domain: Downcast {\n\n /// Spawn a new command within this domain\n\n async fn spawn(\n\n &self,\n\n size: PtySize,\n\n command: Option<CommandBuilder>,\n\n command_dir: Option<String>,\n\n window: WindowId,\n\n ) -> Result<Rc<dyn Tab>, Error>;\n\n\n\n /// Returns false if the `spawn` method will never succeed.\n\n /// There are some internal placeholder domains that are\n\n /// pre-created with local UI that we do not want to allow\n\n /// to show in the launcher/menu as launchable items.\n\n fn spawnable(&self) -> bool {\n\n true\n\n }\n\n\n\n /// Returns the domain id, which is useful for obtaining\n\n /// a handle on the domain later.\n", "file_path": "src/mux/domain.rs", "rank": 29, "score": 161426.91173336148 }, { "content": "fn default_dpi() -> f64 {\n\n 96.0\n\n}\n\n\n", "file_path": "src/config/mod.rs", "rank": 30, "score": 160448.22986023952 }, { "content": "fn default_true() -> bool {\n\n true\n\n}\n\n\n", "file_path": "src/config/mod.rs", "rank": 31, "score": 160448.22986023952 }, { "content": "fn maybe_show_configuration_error_window() {\n\n if let Err(err) = config::configuration_result() {\n\n let err = format!(\"{:#}\", err);\n\n connui::show_configuration_error_message(&err);\n\n }\n\n}\n\n\n", "file_path": "src/main.rs", "rank": 32, "score": 159415.26054695036 }, { "content": "fn default_read_timeout() -> Duration {\n\n Duration::from_secs(60)\n\n}\n\n\n", "file_path": "src/config/mod.rs", "rank": 33, "score": 155702.9137414586 }, { "content": "fn default_font_size() -> f64 {\n\n 10.0\n\n}\n\n\n", "file_path": "src/config/mod.rs", "rank": 34, "score": 155702.9137414586 }, { "content": "fn default_initial_cols() -> u16 {\n\n 80\n\n}\n\n\n", "file_path": "src/config/mod.rs", "rank": 35, "score": 155702.9137414586 }, { "content": "fn default_scrollback_lines() -> usize {\n\n 3500\n\n}\n\n\n", "file_path": "src/config/mod.rs", "rank": 36, "score": 155702.9137414586 }, { "content": "fn default_write_timeout() -> Duration {\n\n Duration::from_secs(60)\n\n}\n", "file_path": "src/config/mod.rs", "rank": 37, "score": 155702.9137414586 }, { "content": "fn default_initial_rows() -> u16 {\n\n 24\n\n}\n\n\n", "file_path": "src/config/mod.rs", "rank": 38, "score": 155702.9137414586 }, { "content": "fn default_background() -> RgbColor {\n\n RgbColor::new(0x0b, 0x00, 0x22)\n\n}\n\n\n", "file_path": "src/config/color.rs", "rank": 39, "score": 155702.9137414586 }, { "content": "fn do_domain_attach(domain: DomainId) {\n\n promise::spawn::spawn(async move {\n\n let mux = Mux::get().unwrap();\n\n let domain = mux\n\n .get_domain(domain)\n\n .ok_or_else(|| anyhow!(\"launcher attach called with unresolvable domain id!?\"))?;\n\n domain.attach().await\n\n });\n\n}\n", "file_path": "src/frontend/gui/overlay/launcher.rs", "rank": 40, "score": 155525.34400353648 }, { "content": "fn csi_u_encode(buf: &mut String, c: char, mods: KeyModifiers) -> Result<(), Error> {\n\n if ENABLE_CSI_U {\n\n write!(buf, \"\\x1b[{};{}u\", c as u32, 1 + encode_modifiers(mods))?;\n\n } else {\n\n // FIXME: this ignores the modifiers completely. That's sort of\n\n // OK, but eg: CTRL-SPACE should really send a NUL byte in that\n\n // case, so this isn't great\n\n write!(buf, \"{}\", c)?;\n\n }\n\n Ok(())\n\n}\n\n\n", "file_path": "term/src/terminalstate.rs", "rank": 41, "score": 154862.46641019516 }, { "content": "struct EnumDeserializer<'lua> {\n\n variant: String,\n\n value: Option<Value<'lua>>,\n\n}\n\n\n\nimpl<'de, 'lua> EnumAccess<'de> for EnumDeserializer<'lua> {\n\n type Error = Error;\n\n type Variant = VariantDeserializer<'lua>;\n\n\n\n fn variant_seed<V>(self, seed: V) -> Result<(V::Value, VariantDeserializer<'lua>), Error>\n\n where\n\n V: DeserializeSeed<'de>,\n\n {\n\n let variant = self.variant.into_deserializer();\n\n let visitor = VariantDeserializer { value: self.value };\n\n seed.deserialize(variant).map(|v| (v, visitor))\n\n }\n\n}\n\n\n", "file_path": "src/scripting/serde_lua/mod.rs", "rank": 42, "score": 153892.55373061638 }, { "content": "pub fn feature_from_string(s: &str) -> Result<hb_feature_t, Error> {\n\n unsafe {\n\n let mut feature = mem::zeroed();\n\n ensure!(\n\n hb_feature_from_string(\n\n s.as_ptr() as *const i8,\n\n s.len() as i32,\n\n &mut feature as *mut _,\n\n ) != 0,\n\n \"failed to create feature from {}\",\n\n s\n\n );\n\n Ok(feature)\n\n }\n\n}\n\n\n\npub struct Font {\n\n font: *mut hb_font_t,\n\n}\n\n\n\nimpl Drop for Font {\n\n fn drop(&mut self) {\n\n unsafe {\n\n hb_font_destroy(self.font);\n\n }\n\n }\n\n}\n\n\n", "file_path": "src/font/hbwrap.rs", "rank": 43, "score": 151705.10821408877 }, { "content": "pub fn language_from_string(s: &str) -> Result<hb_language_t, Error> {\n\n unsafe {\n\n let lang = hb_language_from_string(s.as_ptr() as *const i8, s.len() as i32);\n\n ensure!(!lang.is_null(), \"failed to convert {} to language\");\n\n Ok(lang)\n\n }\n\n}\n\n\n", "file_path": "src/font/hbwrap.rs", "rank": 44, "score": 151705.10821408877 }, { "content": "/// Translates non-printable X11 keysym to KeyCode\n\n/// for missing keys, look into `/usr/include/X11/keysymdef.h`\n\n/// and/or define them in KeyCode.\n\npub fn keysym_to_keycode(keysym: u32) -> Option<KeyCode> {\n\n let utf32 = xkbcommon::xkb::keysym_to_utf32(keysym);\n\n if utf32 >= 0x20 {\n\n // Unsafety: this is ok because we trust that keysym_to_utf32\n\n // is only going to return valid utf32 codepoints.\n\n // Note that keysym_to_utf32 returns 0 for no match.\n\n unsafe {\n\n return Some(KeyCode::Char(std::char::from_u32_unchecked(utf32)));\n\n }\n\n }\n\n\n\n use xkbcommon::xkb::keysyms::*;\n\n #[allow(non_upper_case_globals)]\n\n Some(match keysym {\n\n KEY_Escape => KeyCode::Char('\\u{1b}'),\n\n KEY_Tab => KeyCode::Char('\\t'),\n\n\n\n KEY_BackSpace => KeyCode::Char('\\u{8}'),\n\n KEY_Return => KeyCode::Char('\\r'),\n\n KEY_Insert => KeyCode::Insert,\n", "file_path": "window/src/os/xkeysyms.rs", "rank": 45, "score": 151444.54831960393 }, { "content": "#[doc(hidden)]\n\npub fn socketpair_impl() -> anyhow::Result<(FileDescriptor, FileDescriptor)> {\n\n init_winsock();\n\n\n\n let s = socket(AF_INET, SOCK_STREAM, 0)?;\n\n\n\n let mut in_addr: SOCKADDR_IN = unsafe { std::mem::zeroed() };\n\n in_addr.sin_family = AF_INET as _;\n\n unsafe {\n\n *in_addr.sin_addr.S_un.S_addr_mut() = htonl(INADDR_LOOPBACK);\n\n }\n\n\n\n unsafe {\n\n if bind(\n\n s.as_raw_handle() as _,\n\n std::mem::transmute(&in_addr),\n\n std::mem::size_of_val(&in_addr) as _,\n\n ) != 0\n\n {\n\n bail!(\"bind failed: {}\", IoError::last_os_error());\n\n }\n", "file_path": "filedescriptor/src/windows.rs", "rank": 46, "score": 151443.21410888745 }, { "content": "#[cfg(not(target_os = \"linux\"))]\n\n#[doc(hidden)]\n\npub fn socketpair_impl() -> anyhow::Result<(FileDescriptor, FileDescriptor)> {\n\n let mut fds = [-1i32; 2];\n\n let res = unsafe { libc::socketpair(libc::PF_LOCAL, libc::SOCK_STREAM, 0, fds.as_mut_ptr()) };\n\n if res == -1 {\n\n bail!(\n\n \"failed to create a socketpair: {:?}\",\n\n std::io::Error::last_os_error()\n\n )\n\n } else {\n\n let mut read = FileDescriptor {\n\n handle: OwnedHandle {\n\n handle: fds[0],\n\n handle_type: (),\n\n },\n\n };\n\n let mut write = FileDescriptor {\n\n handle: OwnedHandle {\n\n handle: fds[1],\n\n handle_type: (),\n\n },\n\n };\n\n read.handle.cloexec()?;\n\n write.handle.cloexec()?;\n\n Ok((read, write))\n\n }\n\n}\n\n\n\npub use libc::{pollfd, POLLERR, POLLHUP, POLLIN, POLLOUT};\n\nuse std::time::Duration;\n\n\n", "file_path": "filedescriptor/src/unix.rs", "rank": 47, "score": 151443.21410888745 }, { "content": "fn default_cursor_blink_rate() -> u64 {\n\n 800\n\n}\n\n\n", "file_path": "src/config/mod.rs", "rank": 48, "score": 151294.22259518565 }, { "content": "fn default_swap_backspace_and_delete() -> bool {\n\n // cfg!(target_os = \"macos\")\n\n // See: https://github.com/wez/wezterm/issues/88\n\n false\n\n}\n\n\n", "file_path": "src/config/mod.rs", "rank": 49, "score": 151294.22259518565 }, { "content": "/// Examines a set of FileDescriptors to see if some of them are ready for I/O,\n\n/// or if certain events have occurred on them.\n\n///\n\n/// This uses the system native readiness checking mechanism, which on Windows\n\n/// means that it does NOT use IOCP and that this only works with sockets on\n\n/// Windows. If you need IOCP then the `mio` crate is recommended for a much\n\n/// more scalable solution.\n\n///\n\n/// On macOS, the `poll(2)` implementation has problems when used with eg: pty\n\n/// descriptors, so this implementation of poll uses the `select(2)` interface\n\n/// under the covers. That places a limit on the maximum file descriptor value\n\n/// that can be passed to poll. If a file descriptor is out of range then an\n\n/// error will returned. This limitation could potentially be lifted in the\n\n/// future.\n\n///\n\n/// On Windows, `WSAPoll` is used to implement readiness checking, which has\n\n/// the consequence that it can only be used with sockets.\n\n///\n\n/// If `duration` is `None`, then `poll` will block until any of the requested\n\n/// events are ready. Otherwise, `duration` specifies how long to wait for\n\n/// readiness before giving up.\n\n///\n\n/// The return value is the number of entries that were satisfied; `0` means\n\n/// that none were ready after waiting for the specified duration.\n\n///\n\n/// The `pfd` array is mutated and the `revents` field is updated to indicate\n\n/// which of the events were received.\n\npub fn poll(pfd: &mut [pollfd], duration: Option<Duration>) -> anyhow::Result<usize> {\n\n poll_impl(pfd, duration)\n\n}\n\n\n", "file_path": "filedescriptor/src/lib.rs", "rank": 50, "score": 151285.51028691535 }, { "content": "/// Used to prevent the stats thread from trying to write to stderr\n\n/// when we're running in proxy mode\n\npub fn disable_stats_printing() {\n\n ENABLE_STAT_PRINT.store(false, Ordering::SeqCst);\n\n}\n\n\n\nimpl Inner {\n\n fn run(inner: Arc<Mutex<Inner>>) {\n\n let mut last_print = Instant::now();\n\n\n\n let cols = vec![\n\n Column {\n\n name: \"STAT\".to_string(),\n\n alignment: Alignment::Left,\n\n },\n\n Column {\n\n name: \"p50\".to_string(),\n\n alignment: Alignment::Left,\n\n },\n\n Column {\n\n name: \"p75\".to_string(),\n\n alignment: Alignment::Left,\n", "file_path": "src/stats.rs", "rank": 51, "score": 150823.2300458696 }, { "content": "pub fn tabulate_for_terminal(\n\n columns: &[Column],\n\n rows: &[Vec<Vec<Change>>],\n\n spacer: CellAttributes,\n\n result: &mut Vec<Change>,\n\n) {\n\n let mut col_widths: Vec<usize> = columns\n\n .iter()\n\n .map(|c| unicode_column_width(&c.name))\n\n .collect();\n\n\n\n for row in rows {\n\n for (idx, col) in row.iter().enumerate() {\n\n let col_width = unicode_column_width_of_change_slice(col);\n\n if let Some(width) = col_widths.get_mut(idx) {\n\n *width = (*width).max(col_width);\n\n } else {\n\n col_widths.push(col_width);\n\n }\n\n }\n", "file_path": "tabout/src/lib.rs", "rank": 52, "score": 150818.02484114756 }, { "content": "pub fn ssh_connect_with_ui(\n\n remote_address: &str,\n\n username: &str,\n\n ui: &mut ConnectionUI,\n\n) -> anyhow::Result<ssh2::Session> {\n\n let mut sess = ssh2::Session::new()?;\n\n\n\n let (remote_address, remote_host_name, port) = {\n\n let parts: Vec<&str> = remote_address.split(':').collect();\n\n\n\n if parts.len() == 2 {\n\n (remote_address.to_string(), parts[0], parts[1].parse()?)\n\n } else {\n\n (format!(\"{}:22\", remote_address), remote_address, 22)\n\n }\n\n };\n\n\n\n ui.output_str(&format!(\"Connecting to {} using SSH\\n\", remote_address));\n\n\n\n let tcp = TcpStream::connect(&remote_address)\n", "file_path": "src/ssh.rs", "rank": 53, "score": 150818.02484114756 }, { "content": "fn de_keycode<'de, D>(deserializer: D) -> Result<KeyCode, D::Error>\n\nwhere\n\n D: Deserializer<'de>,\n\n{\n\n let s = String::deserialize(deserializer)?;\n\n\n\n macro_rules! m {\n\n ($($val:ident),* $(,)?) => {\n\n $(\n\n if s == stringify!($val) {\n\n return Ok(KeyCode::$val);\n\n }\n\n )*\n\n }\n\n }\n\n\n\n m!(\n\n Hyper,\n\n Super,\n\n Meta,\n", "file_path": "src/config/keys.rs", "rank": 54, "score": 150471.9523843119 }, { "content": "struct LuaMapSerializer<'lua> {\n\n lua: &'lua Lua,\n\n table: Table<'lua>,\n\n key: Option<Value<'lua>>,\n\n}\n\n\n\nimpl<'lua> serde::ser::SerializeMap for LuaMapSerializer<'lua> {\n\n type Ok = Value<'lua>;\n\n type Error = Error;\n\n\n\n fn serialize_key<T: Serialize + ?Sized>(&mut self, key: &T) -> Result<(), Error> {\n\n let key = key.serialize(LuaSerializer { lua: self.lua })?;\n\n self.key.replace(key);\n\n Ok(())\n\n }\n\n\n\n fn serialize_value<T: Serialize + ?Sized>(&mut self, value: &T) -> Result<(), Error> {\n\n let value = value.serialize(LuaSerializer { lua: self.lua })?;\n\n let key = self\n\n .key\n", "file_path": "src/scripting/serde_lua/ser.rs", "rank": 55, "score": 149776.0211852123 }, { "content": "pub fn launcher(\n\n _tab_id: TabId,\n\n domain_id_of_current_tab: DomainId,\n\n mut term: TermWizTerminal,\n\n mux_window_id: WindowId,\n\n domains: Vec<(DomainId, DomainState, String)>,\n\n clipboard: ClipboardHelper,\n\n size: PtySize,\n\n) -> anyhow::Result<()> {\n\n let mut active_idx = 0;\n\n let mut entries = vec![];\n\n\n\n // Pull in the user defined entries from the launch_menu\n\n // section of the configuration.\n\n for item in &configuration().launch_menu {\n\n entries.push(Entry::Spawn {\n\n label: match item.label.as_ref() {\n\n Some(label) => label.to_string(),\n\n None => match item.args.as_ref() {\n\n Some(args) => args.join(\" \"),\n", "file_path": "src/frontend/gui/overlay/launcher.rs", "rank": 56, "score": 147661.48957922898 }, { "content": "fn default_active_tab() -> TabBarColor {\n\n TabBarColor {\n\n bg_color: RgbColor::new(0x2b, 0x20, 0x42),\n\n fg_color: RgbColor::new(0xc0, 0xc0, 0xc0),\n\n ..TabBarColor::default()\n\n }\n\n}\n\n\n\nimpl Default for TabBarColors {\n\n fn default() -> Self {\n\n Self {\n\n background: default_background(),\n\n inactive_tab: default_inactive_tab(),\n\n inactive_tab_hover: default_inactive_tab_hover(),\n\n active_tab: default_active_tab(),\n\n }\n\n }\n\n}\n\n\n\n#[derive(Debug, Deserialize, Serialize, Clone)]\n\npub struct ColorSchemeFile {\n\n /// The color palette\n\n pub colors: Palette,\n\n}\n\nimpl_lua_conversion!(ColorSchemeFile);\n", "file_path": "src/config/color.rs", "rank": 57, "score": 147187.56394977972 }, { "content": "fn default_inactive_tab() -> TabBarColor {\n\n TabBarColor {\n\n bg_color: RgbColor::new(0x1b, 0x10, 0x32),\n\n fg_color: RgbColor::new(0x80, 0x80, 0x80),\n\n ..TabBarColor::default()\n\n }\n\n}\n", "file_path": "src/config/color.rs", "rank": 58, "score": 147187.56394977972 }, { "content": "/// Set up a lua context for executing some code.\n\n/// The path to the directory containing the configuration is\n\n/// passed in and is used to pre-set some global values in\n\n/// the environment.\n\n///\n\n/// The `package.path` is configured to search the user's\n\n/// wezterm specific config paths for lua modules, should\n\n/// they choose to `require` additional code from their config.\n\n///\n\n/// A `wezterm` module is registered so that the script can\n\n/// `require \"wezterm\"` and call into functions provided by\n\n/// wezterm. The wezterm module contains:\n\n/// * `executable_dir` - the directory containing the wezterm\n\n/// executable. This is potentially useful for portable\n\n/// installs on Windows.\n\n/// * `config_dir` - the directory containing the wezterm\n\n/// configuration.\n\n/// * `log_error` - a function that logs to stderr (or the server\n\n/// log file for daemonized wezterm).\n\n/// * `target_triple` - the rust compilation target triple.\n\n/// * `version` - the version of the running wezterm instance.\n\n/// * `home_dir` - the path to the user's home directory\n\n///\n\n/// In addition to this, the lua standard library, except for\n\n/// the `debug` module, is also available to the script.\n\npub fn make_lua_context(config_dir: &Path) -> anyhow::Result<Lua> {\n\n let lua = Lua::new();\n\n\n\n {\n\n let globals = lua.globals();\n\n // This table will be the `wezterm` module in the script\n\n let wezterm_mod = lua.create_table()?;\n\n\n\n let package: Table = globals.get(\"package\")?;\n\n let package_path: String = package.get(\"path\")?;\n\n let mut path_array: Vec<String> = package_path.split(\";\").map(|s| s.to_owned()).collect();\n\n\n\n fn prefix_path(array: &mut Vec<String>, path: &Path) {\n\n array.insert(0, format!(\"{}/?.lua\", path.display()));\n\n array.insert(1, format!(\"{}/?/init.lua\", path.display()));\n\n }\n\n\n\n prefix_path(&mut path_array, &crate::config::HOME_DIR.join(\".wezterm\"));\n\n prefix_path(\n\n &mut path_array,\n", "file_path": "src/scripting/mod.rs", "rank": 59, "score": 145043.31888205768 }, { "content": "pub fn running_under_wsl() -> bool {\n\n #[cfg(unix)]\n\n unsafe {\n\n let mut name: libc::utsname = std::mem::zeroed();\n\n if libc::uname(&mut name) == 0 {\n\n let version = std::ffi::CStr::from_ptr(name.version.as_ptr())\n\n .to_string_lossy()\n\n .into_owned();\n\n return version.contains(\"Microsoft\");\n\n }\n\n };\n\n\n\n false\n\n}\n\n\n\n#[derive(Clone, Debug)]\n\npub struct SshParameters {\n\n pub username: String,\n\n pub host_and_port: String,\n\n}\n\n\n", "file_path": "src/main.rs", "rank": 60, "score": 144912.2975601416 }, { "content": "pub fn tab_navigator(\n\n tab_id: TabId,\n\n mut term: TermWizTerminal,\n\n tab_list: Vec<(String, TabId)>,\n\n mux_window_id: WindowId,\n\n) -> anyhow::Result<()> {\n\n let mut active_tab_idx = tab_list\n\n .iter()\n\n .position(|(_title, id)| *id == tab_id)\n\n .unwrap_or(0);\n\n\n\n fn render(\n\n active_tab_idx: usize,\n\n tab_list: &[(String, TabId)],\n\n term: &mut TermWizTerminal,\n\n ) -> anyhow::Result<()> {\n\n // let dims = term.get_screen_size()?;\n\n let mut changes = vec![\n\n Change::ClearScreen(ColorAttribute::Default),\n\n Change::CursorPosition {\n", "file_path": "src/frontend/gui/overlay/tabnavigator.rs", "rank": 61, "score": 144728.87377160304 }, { "content": "fn default_inactive_tab_hover() -> TabBarColor {\n\n TabBarColor {\n\n bg_color: RgbColor::new(0x3b, 0x30, 0x52),\n\n fg_color: RgbColor::new(0x90, 0x90, 0x90),\n\n italic: true,\n\n ..TabBarColor::default()\n\n }\n\n}\n", "file_path": "src/config/color.rs", "rank": 62, "score": 143352.9281060507 }, { "content": "fn default_ratelimit_output_bytes_per_second() -> u32 {\n\n 400_000\n\n}\n\n\n", "file_path": "src/config/mod.rs", "rank": 63, "score": 143352.9281060507 }, { "content": "fn default_ratelimit_line_prefetches_per_second() -> u32 {\n\n 10\n\n}\n\n\n", "file_path": "src/config/mod.rs", "rank": 64, "score": 143352.9281060507 }, { "content": "pub fn spawn_tls_listener(tls_server: &TlsDomainServer) -> Result<(), Error> {\n\n openssl::init();\n\n\n\n let mut acceptor = SslAcceptor::mozilla_modern(SslMethod::tls())?;\n\n\n\n let cert_file = tls_server\n\n .pem_cert\n\n .clone()\n\n .unwrap_or_else(|| PKI.server_pem());\n\n acceptor\n\n .set_certificate_file(&cert_file, SslFiletype::PEM)\n\n .context(format!(\n\n \"set_certificate_file to {} for TLS listener\",\n\n cert_file.display()\n\n ))?;\n\n\n\n if let Some(chain_file) = tls_server.pem_ca.as_ref() {\n\n acceptor\n\n .set_certificate_chain_file(&chain_file)\n\n .context(format!(\n", "file_path": "src/server/listener/ossl.rs", "rank": 65, "score": 142460.09771250325 }, { "content": "fn default_hyperlink_rules() -> Vec<hyperlink::Rule> {\n\n vec![\n\n // URL with a protocol\n\n hyperlink::Rule::new(r\"\\b\\w+://(?:[\\w.-]+)\\.[a-z]{2,15}\\S*\\b\", \"$0\").unwrap(),\n\n // implicit mailto link\n\n hyperlink::Rule::new(r\"\\b\\w+@[\\w-]+(\\.[\\w-]+)+\\b\", \"mailto:$0\").unwrap(),\n\n ]\n\n}\n\n\n", "file_path": "src/config/mod.rs", "rank": 66, "score": 141954.4579265662 }, { "content": "fn run_ssh(config: config::ConfigHandle, opts: SshCommand) -> anyhow::Result<()> {\n\n let front_end_selection = opts.front_end.unwrap_or(config.front_end);\n\n let gui = front_end_selection.try_new()?;\n\n\n\n // Set up the mux with no default domain; there's a good chance that\n\n // we'll need to show authentication UI and we don't want its domain\n\n // to become the default domain.\n\n let mux = Rc::new(mux::Mux::new(None));\n\n Mux::set_mux(&mux);\n\n\n\n // Keep the frontend alive until we've run through the ssh authentication\n\n // phase. This is passed into the thread and dropped when it is done.\n\n let activity = Activity::new();\n\n\n\n // Initiate an ssh connection; since that is a blocking process with\n\n // callbacks, we have to run it in another thread\n\n promise::spawn::spawn(async {\n\n if let Err(err) = async_run_ssh(opts).await {\n\n terminate_with_error(err);\n\n }\n\n // This captures the activity ownership into this future, but also\n\n // ensures that we drop it either when we error out, or if not,\n\n // only once we reach this point in the processing flow.\n\n drop(activity);\n\n });\n\n\n\n maybe_show_configuration_error_window();\n\n gui.run_forever()\n\n}\n\n\n", "file_path": "src/main.rs", "rank": 67, "score": 141044.47714134792 }, { "content": "struct PtyFd(pub FileDescriptor);\n\nimpl std::ops::Deref for PtyFd {\n\n type Target = FileDescriptor;\n\n fn deref(&self) -> &FileDescriptor {\n\n &self.0\n\n }\n\n}\n\nimpl std::ops::DerefMut for PtyFd {\n\n fn deref_mut(&mut self) -> &mut FileDescriptor {\n\n &mut self.0\n\n }\n\n}\n\n\n\nimpl Read for PtyFd {\n\n fn read(&mut self, buf: &mut [u8]) -> Result<usize, io::Error> {\n\n match self.0.read(buf) {\n\n Err(ref e)\n\n if e.kind() == io::ErrorKind::Other && e.raw_os_error() == Some(libc::EIO) =>\n\n {\n\n // EIO indicates that the slave pty has been closed.\n", "file_path": "pty/src/unix.rs", "rank": 68, "score": 141035.83346253418 }, { "content": "fn scrollback_size(config: &Arc<dyn TerminalConfiguration>, allow_scrollback: bool) -> usize {\n\n if allow_scrollback {\n\n config.scrollback_size()\n\n } else {\n\n 0\n\n }\n\n}\n\n\n\nimpl Screen {\n\n /// Create a new Screen with the specified dimensions.\n\n /// The Cells in the viewable portion of the screen are set to the\n\n /// default cell attributes.\n\n pub fn new(\n\n physical_rows: usize,\n\n physical_cols: usize,\n\n config: &Arc<dyn TerminalConfiguration>,\n\n allow_scrollback: bool,\n\n ) -> Screen {\n\n let physical_rows = physical_rows.max(1);\n\n let physical_cols = physical_cols.max(1);\n", "file_path": "term/src/screen.rs", "rank": 69, "score": 140136.98934509914 }, { "content": "/// There isn't really a child process on the end of the serial connection,\n\n/// so all of the Child trait impls are NOP\n\nstruct SerialChild {\n\n _port: Handle,\n\n}\n\n\n\n// An anemic impl of Debug to satisfy some indirect trait bounds\n\nimpl std::fmt::Debug for SerialChild {\n\n fn fmt(&self, fmt: &mut std::fmt::Formatter) -> Result<(), std::fmt::Error> {\n\n fmt.debug_struct(\"SerialChild\").finish()\n\n }\n\n}\n\n\n\nimpl Child for SerialChild {\n\n fn try_wait(&mut self) -> IoResult<Option<ExitStatus>> {\n\n Ok(None)\n\n }\n\n\n\n fn kill(&mut self) -> IoResult<()> {\n\n Ok(())\n\n }\n\n\n\n fn wait(&mut self) -> IoResult<ExitStatus> {\n\n Err(std::io::Error::new(\n\n std::io::ErrorKind::WouldBlock,\n\n \"cannot wait for a serial connection to die\",\n\n ))\n\n }\n\n}\n\n\n", "file_path": "pty/src/serial.rs", "rank": 70, "score": 139842.24726775143 }, { "content": "struct ConfigInner {\n\n config: Arc<Config>,\n\n error: Option<String>,\n\n generation: usize,\n\n watcher: Option<notify::RecommendedWatcher>,\n\n}\n\n\n\nimpl ConfigInner {\n\n fn new() -> Self {\n\n Self {\n\n config: Arc::new(Config::default_config()),\n\n error: None,\n\n generation: 0,\n\n watcher: None,\n\n }\n\n }\n\n\n\n fn watch_path(&mut self, path: PathBuf) {\n\n if self.watcher.is_none() {\n\n let (tx, rx) = std::sync::mpsc::channel();\n", "file_path": "src/config/mod.rs", "rank": 71, "score": 139581.51867338447 }, { "content": "fn run_terminal_gui(config: config::ConfigHandle, opts: StartCommand) -> anyhow::Result<()> {\n\n #[cfg(unix)]\n\n {\n\n if opts.daemonize {\n\n let stdout = config.daemon_options.open_stdout()?;\n\n let stderr = config.daemon_options.open_stderr()?;\n\n let home_dir = dirs::home_dir().ok_or_else(|| anyhow!(\"can't find home dir\"))?;\n\n let mut daemonize = daemonize::Daemonize::new()\n\n .stdout(stdout)\n\n .stderr(stderr)\n\n .working_directory(home_dir.clone());\n\n\n\n if !running_under_wsl() {\n\n // pid file locking is only partly function when running under\n\n // WSL 1; it is possible for the pid file to exist after a reboot\n\n // and for attempts to open and lock it to fail when there are no\n\n // other processes that might possibly hold a lock on it.\n\n // So, we only use a pid file when not under WSL.\n\n daemonize = daemonize.pid_file(config.daemon_options.pid_file());\n\n }\n", "file_path": "src/main.rs", "rank": 72, "score": 139168.3739861754 }, { "content": "fn run_mux_client(config: config::ConfigHandle, opts: &ConnectCommand) -> anyhow::Result<()> {\n\n let client_config = client_domains(&config)\n\n .into_iter()\n\n .find(|c| c.name() == opts.domain_name)\n\n .ok_or_else(|| {\n\n anyhow!(\n\n \"no multiplexer domain with name `{}` was found in the configuration\",\n\n opts.domain_name\n\n )\n\n })?;\n\n\n\n let domain: Arc<dyn Domain> = Arc::new(ClientDomain::new(client_config));\n\n let mux = Rc::new(mux::Mux::new(Some(domain.clone())));\n\n Mux::set_mux(&mux);\n\n\n\n let front_end_selection = opts.front_end.unwrap_or(config.front_end);\n\n let gui = front_end_selection.try_new()?;\n\n let opts = opts.clone();\n\n\n\n let cmd = if !opts.prog.is_empty() {\n", "file_path": "src/main.rs", "rank": 73, "score": 139168.3739861754 }, { "content": "/// Returns true if a GUI frontend has been initialized, which implies that\n\n/// it makes sense (and is safe) to use the window crate and associated\n\n/// functionality\n\npub fn has_gui_front_end() -> bool {\n\n HAS_GUI_FRONT_END.load(Ordering::Acquire)\n\n}\n\n\n", "file_path": "src/frontend/mod.rs", "rank": 74, "score": 138828.1677360721 }, { "content": "pub fn is_opengl_enabled() -> bool {\n\n USE_OPENGL.load(Ordering::Acquire)\n\n}\n\n\n\nimpl GuiFrontEnd {\n\n pub fn try_new_no_opengl() -> anyhow::Result<Rc<dyn FrontEnd>> {\n\n USE_OPENGL.store(false, Ordering::Release);\n\n Self::try_new()\n\n }\n\n\n\n pub fn try_new() -> anyhow::Result<Rc<dyn FrontEnd>> {\n\n #[cfg(all(unix, not(target_os = \"macos\")))]\n\n {\n\n if !configuration().enable_wayland {\n\n Connection::disable_wayland();\n\n }\n\n }\n\n let connection = Connection::init()?;\n\n let front_end = Rc::new(GuiFrontEnd { connection });\n\n Ok(front_end)\n", "file_path": "src/frontend/gui/mod.rs", "rank": 75, "score": 138823.14649059705 }, { "content": "fn username_from_env() -> anyhow::Result<String> {\n\n #[cfg(unix)]\n\n const USER: &str = \"USER\";\n\n #[cfg(windows)]\n\n const USER: &str = \"USERNAME\";\n\n\n\n std::env::var(USER).with_context(|| format!(\"while resolving {} env var\", USER))\n\n}\n\n\n\nimpl Display for SshParameters {\n\n fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {\n\n write!(f, \"{}@{}\", self.username, self.host_and_port)\n\n }\n\n}\n\n\n\nimpl FromStr for SshParameters {\n\n type Err = anyhow::Error;\n\n\n\n fn from_str(s: &str) -> Result<Self, Self::Err> {\n\n let parts: Vec<&str> = s.split('@').collect();\n", "file_path": "src/main.rs", "rank": 76, "score": 137810.98071593218 }, { "content": "/// Spawn a new thread to execute the provided function.\n\n/// Returns a JoinHandle that implements the Future trait\n\n/// and that can be used to await and yield the return value\n\n/// from the thread.\n\n/// Can be called from any thread.\n\npub fn spawn_into_new_thread<F, T>(f: F) -> JoinHandle<Result<T>, ()>\n\nwhere\n\n F: FnOnce() -> Result<T>,\n\n F: Send + 'static,\n\n T: Send + 'static,\n\n{\n\n let (tx, rx) = sync_channel(1);\n\n\n\n // Holds the waker that may later observe\n\n // during the Future::poll call.\n\n struct WakerHolder {\n\n waker: Mutex<Option<Waker>>,\n\n }\n\n\n\n let holder = Arc::new(WakerHolder {\n\n waker: Mutex::new(None),\n\n });\n\n\n\n let thread_waker = Arc::clone(&holder);\n\n std::thread::spawn(move || {\n", "file_path": "promise/src/spawn.rs", "rank": 77, "score": 137128.12957441923 }, { "content": "#[derive(PartialEq, Eq, Hash)]\n\nstruct ShapeCacheKey((TextStyle, String));\n\n\n\npub struct TermWindow {\n\n pub window: Option<Window>,\n\n /// When we most recently received keyboard focus\n\n focused: Option<Instant>,\n\n fonts: Rc<FontConfiguration>,\n\n /// Window dimensions and dpi\n\n dimensions: Dimensions,\n\n /// Terminal dimensions\n\n terminal_size: PtySize,\n\n mux_window_id: MuxWindowId,\n\n render_metrics: RenderMetrics,\n\n render_state: RenderState,\n\n keys: KeyMap,\n\n show_tab_bar: bool,\n\n show_scroll_bar: bool,\n\n tab_bar: TabBarState,\n\n last_mouse_coords: (usize, i64),\n\n scroll_drag_start: Option<isize>,\n", "file_path": "src/frontend/gui/termwindow.rs", "rank": 78, "score": 136770.9732797 }, { "content": "pub fn alloc_tab_id() -> TabId {\n\n TAB_ID.fetch_add(1, ::std::sync::atomic::Ordering::Relaxed)\n\n}\n\n\n\nconst PASTE_CHUNK_SIZE: usize = 1024;\n\n\n", "file_path": "src/mux/tab.rs", "rank": 79, "score": 136091.4395824771 }, { "content": "struct Performer<'a, F: FnMut(Action) + 'a> {\n\n callback: &'a mut F,\n\n}\n\n\n\nimpl<'a, F: FnMut(Action)> VTActor for Performer<'a, F> {\n\n fn print(&mut self, c: char) {\n\n (self.callback)(Action::Print(c));\n\n }\n\n\n\n fn execute_c0_or_c1(&mut self, byte: u8) {\n\n match num::FromPrimitive::from_u8(byte) {\n\n Some(code) => (self.callback)(Action::Control(code)),\n\n None => error!(\"impossible C0/C1 control code {:?} was dropped\", byte),\n\n }\n\n }\n\n\n\n fn dcs_hook(\n\n &mut self,\n\n params: &[i64],\n\n intermediates: &[u8],\n", "file_path": "termwiz/src/escape/parser/mod.rs", "rank": 80, "score": 135930.60291677318 }, { "content": "#[derive(Debug)]\n\n#[repr(C)]\n\nstruct NSRangePointer(*mut NSRange);\n\n\n\nimpl std::fmt::Debug for NSRange {\n\n fn fmt(&self, fmt: &mut std::fmt::Formatter) -> std::result::Result<(), std::fmt::Error> {\n\n fmt.debug_struct(\"NSRange\")\n\n .field(\"location\", &self.0.location)\n\n .field(\"length\", &self.0.length)\n\n .finish()\n\n }\n\n}\n\n\n\nunsafe impl objc::Encode for NSRange {\n\n fn encode() -> objc::Encoding {\n\n let encoding = format!(\n\n \"{{NSRange={}{}}}\",\n\n NSUInteger::encode().as_str(),\n\n NSUInteger::encode().as_str()\n\n );\n\n unsafe { objc::Encoding::from_str(&encoding) }\n\n }\n", "file_path": "window/src/os/macos/window.rs", "rank": 81, "score": 134396.94684789018 }, { "content": "#[allow(unused)]\n\npub fn message_box_ok(message: &str) {\n\n let title = \"wezterm\";\n\n let message = message.to_string();\n\n\n\n promise::spawn::block_on(run(60, 10, move |mut term| {\n\n term.render(&[\n\n Change::Title(title.to_string()),\n\n Change::Text(message.to_string()),\n\n ])\n\n .map_err(Error::msg)?;\n\n\n\n let mut editor = LineEditor::new(&mut term);\n\n editor.set_prompt(\"press enter to continue.\");\n\n\n\n let mut host = NopLineEditorHost::default();\n\n editor.read_line(&mut host).ok();\n\n Ok(())\n\n }))\n\n .ok();\n\n}\n", "file_path": "src/termwiztermtab.rs", "rank": 82, "score": 133901.4596532491 }, { "content": "/// Represents a child process spawned into the pty.\n\n/// This handle can be used to wait for or terminate that child process.\n\npub trait Child: std::fmt::Debug {\n\n /// Poll the child to see if it has completed.\n\n /// Does not block.\n\n /// Returns None if the has not yet terminated,\n\n /// else returns its exit status.\n\n fn try_wait(&mut self) -> IoResult<Option<ExitStatus>>;\n\n /// Terminate the child process\n\n fn kill(&mut self) -> IoResult<()>;\n\n /// Blocks execution until the child process has completed,\n\n /// yielding its exit status.\n\n fn wait(&mut self) -> IoResult<ExitStatus>;\n\n}\n\n\n", "file_path": "pty/src/lib.rs", "rank": 83, "score": 132672.4752218515 }, { "content": "fn schedule_show_window(hwnd: HWindow, show: bool) {\n\n // ShowWindow can call to the window proc and may attempt\n\n // to lock inner, so we avoid locking it ourselves here\n\n promise::spawn::spawn(async move {\n\n unsafe {\n\n ShowWindow(hwnd.0, if show { SW_NORMAL } else { SW_HIDE });\n\n }\n\n });\n\n}\n\n\n\nimpl WindowOpsMut for WindowInner {\n\n fn close(&mut self) {\n\n let hwnd = self.hwnd;\n\n promise::spawn::spawn(async move {\n\n unsafe {\n\n DestroyWindow(hwnd.0);\n\n }\n\n });\n\n }\n\n\n", "file_path": "window/src/os/windows/window.rs", "rank": 84, "score": 132611.98002672498 }, { "content": "pub fn spawn_listener() -> anyhow::Result<()> {\n\n let config = configuration();\n\n for unix_dom in &config.unix_domains {\n\n let mut listener = local::LocalListener::with_domain(unix_dom)?;\n\n thread::spawn(move || {\n\n listener.run();\n\n });\n\n }\n\n\n\n for tls_server in &config.tls_servers {\n\n ossl::spawn_tls_listener(tls_server)?;\n\n }\n\n Ok(())\n\n}\n", "file_path": "src/server/listener/mod.rs", "rank": 85, "score": 131169.75274512914 }, { "content": "struct Paste {\n\n tab_id: TabId,\n\n text: String,\n\n offset: usize,\n\n}\n\n\n", "file_path": "src/mux/tab.rs", "rank": 86, "score": 130714.53523470456 }, { "content": "struct HeadlessImpl {\n\n rx: Receiver<UIRequest>,\n\n}\n\n\n\nimpl HeadlessImpl {\n\n fn run(&mut self) -> anyhow::Result<()> {\n\n loop {\n\n match self.rx.recv_timeout(Duration::from_millis(200)) {\n\n Ok(UIRequest::Close) => break,\n\n Ok(UIRequest::Output(changes)) => {\n\n log::trace!(\"Output: {:?}\", changes);\n\n }\n\n Ok(UIRequest::Input { mut respond, .. }) => {\n\n respond.result(Err(anyhow!(\"Input requested from headless context\")));\n\n }\n\n Ok(UIRequest::Sleep {\n\n mut respond,\n\n reason,\n\n duration,\n\n }) => {\n", "file_path": "src/connui.rs", "rank": 87, "score": 130709.20361767446 }, { "content": "#[derive(Debug, StructOpt, Clone)]\n\nstruct SerialCommand {\n\n #[structopt(\n\n long = \"front-end\",\n\n possible_values = &FrontEndSelection::variants(),\n\n case_insensitive = true\n\n )]\n\n front_end: Option<FrontEndSelection>,\n\n\n\n /// Set the baud rate. The default is 9600 baud.\n\n #[structopt(long = \"baud\")]\n\n baud: Option<usize>,\n\n\n\n /// Specifies the serial device name.\n\n /// On Windows systems this can be a name like `COM0`.\n\n /// On posix systems this will be something like `/dev/ttyUSB0`\n\n #[structopt(parse(from_os_str))]\n\n port: OsString,\n\n}\n\n\n", "file_path": "src/main.rs", "rank": 88, "score": 130708.46399346109 }, { "content": "struct Master {\n\n port: Handle,\n\n}\n\n\n\nimpl Write for Master {\n\n fn write(&mut self, buf: &[u8]) -> Result<usize, std::io::Error> {\n\n self.port.lock().unwrap().write(buf)\n\n }\n\n\n\n fn flush(&mut self) -> Result<(), std::io::Error> {\n\n self.port.lock().unwrap().flush()\n\n }\n\n}\n\n\n\nimpl MasterPty for Master {\n\n fn resize(&self, _size: PtySize) -> anyhow::Result<()> {\n\n // Serial ports have no concept of size\n\n Ok(())\n\n }\n\n\n", "file_path": "pty/src/serial.rs", "rank": 89, "score": 130691.46734269164 }, { "content": "struct Slave {\n\n port: Handle,\n\n}\n\n\n\nimpl SlavePty for Slave {\n\n fn spawn_command(&self, cmd: CommandBuilder) -> anyhow::Result<Box<dyn Child>> {\n\n ensure!(\n\n cmd.is_default_prog(),\n\n \"can only use default prog commands with serial tty implementations\"\n\n );\n\n Ok(Box::new(SerialChild {\n\n _port: Arc::clone(&self.port),\n\n }))\n\n }\n\n}\n\n\n", "file_path": "pty/src/serial.rs", "rank": 90, "score": 130691.46734269164 }, { "content": "struct Reader {\n\n fd: FileDescriptor,\n\n}\n\n\n\nimpl Read for Reader {\n\n fn read(&mut self, buf: &mut [u8]) -> Result<usize, std::io::Error> {\n\n loop {\n\n match self.fd.read(buf) {\n\n Ok(size) => {\n\n if size == 0 {\n\n // Read timeout, but we expect to mostly hit this.\n\n // It just means that there was no data available\n\n // right now.\n\n continue;\n\n }\n\n return Ok(size);\n\n }\n\n Err(e) => {\n\n log::error!(\"serial read error: {}\", e);\n\n return Err(e);\n\n }\n\n }\n\n }\n\n }\n\n}\n", "file_path": "pty/src/serial.rs", "rank": 91, "score": 130691.46734269164 }, { "content": "pub fn start_overlay<T, F>(\n\n term_window: &TermWindow,\n\n tab: &Rc<dyn Tab>,\n\n func: F,\n\n) -> (\n\n Rc<dyn Tab>,\n\n Pin<Box<dyn std::future::Future<Output = Option<anyhow::Result<T>>>>>,\n\n)\n\nwhere\n\n T: Send + 'static,\n\n F: Send + 'static + FnOnce(TabId, TermWizTerminal) -> anyhow::Result<T>,\n\n{\n\n let tab_id = tab.tab_id();\n\n let dims = tab.renderer().get_dimensions();\n\n let (tw_term, tw_tab) = allocate(dims.cols, dims.viewport_rows);\n\n\n\n let window = term_window.window.clone().unwrap();\n\n\n\n let future = promise::spawn::spawn_into_new_thread(move || {\n\n let res = func(tab_id, tw_term);\n\n TermWindow::schedule_cancel_overlay(window, tab_id);\n\n res\n\n });\n\n\n\n (Rc::new(tw_tab), Box::pin(future))\n\n}\n", "file_path": "src/frontend/gui/overlay/mod.rs", "rank": 92, "score": 128618.99259462155 }, { "content": "fn numstr_or_empty(x: &Option<i64>) -> String {\n\n match x {\n\n Some(x) => format!(\"{}\", x),\n\n None => \"\".to_owned(),\n\n }\n\n}\n\n\n\nimpl Display for Window {\n\n fn fmt(&self, f: &mut Formatter) -> Result<(), FmtError> {\n\n match self {\n\n Window::DeIconify => write!(f, \"1t\"),\n\n Window::Iconify => write!(f, \"2t\"),\n\n Window::MoveWindow { x, y } => write!(f, \"3;{};{}t\", x, y),\n\n Window::ResizeWindowPixels { width, height } => write!(\n\n f,\n\n \"4;{};{}t\",\n\n numstr_or_empty(width),\n\n numstr_or_empty(height)\n\n ),\n\n Window::RaiseWindow => write!(f, \"5t\"),\n", "file_path": "termwiz/src/escape/csi.rs", "rank": 93, "score": 127908.17939652345 }, { "content": "/// Returns the number of cells visually occupied by a grapheme.\n\n/// The input string must be a single grapheme.\n\npub fn grapheme_column_width(s: &str) -> usize {\n\n // Due to this issue:\n\n // https://github.com/unicode-rs/unicode-width/issues/4\n\n // we cannot simply use the unicode-width crate to compute\n\n // the desired value.\n\n // Let's check for emoji-ness for ourselves first\n\n use xi_unicode::EmojiExt;\n\n for c in s.chars() {\n\n if c.is_emoji_modifier_base() || c.is_emoji_modifier() {\n\n // treat modifier sequences as double wide\n\n return 2;\n\n }\n\n }\n\n UnicodeWidthStr::width(s)\n\n}\n\n\n\n/// Models a change in the attributes of a cell in a stream of changes.\n\n/// Each variant specifies one of the possible attributes; the corresponding\n\n/// value holds the new value to be used for that attribute.\n\n#[derive(Debug, Clone, Eq, PartialEq, Serialize, Deserialize)]\n", "file_path": "termwiz/src/cell.rs", "rank": 94, "score": 127010.31351913599 }, { "content": "/// Returns the number of cells visually occupied by a sequence\n\n/// of graphemes\n\npub fn unicode_column_width(s: &str) -> usize {\n\n use unicode_segmentation::UnicodeSegmentation;\n\n s.graphemes(true).map(grapheme_column_width).sum()\n\n}\n\n\n", "file_path": "termwiz/src/cell.rs", "rank": 95, "score": 127005.07279134821 }, { "content": "#[inline]\n\npub fn succeeded(error: FT_Error) -> bool {\n\n error == freetype::FT_Err_Ok as FT_Error\n\n}\n\n\n", "file_path": "src/font/ftwrap.rs", "rank": 96, "score": 127005.07279134821 }, { "content": "struct ConnectionUIImpl {\n\n term: termwiztermtab::TermWizTerminal,\n\n rx: Receiver<UIRequest>,\n\n}\n\n\n\nimpl ConnectionUIImpl {\n\n fn run(&mut self) -> anyhow::Result<()> {\n\n loop {\n\n match self.rx.recv_timeout(Duration::from_millis(200)) {\n\n Ok(UIRequest::Close) => break,\n\n Ok(UIRequest::Output(changes)) => self.term.render(&changes)?,\n\n Ok(UIRequest::Input {\n\n prompt,\n\n echo: true,\n\n mut respond,\n\n }) => {\n\n respond.result(self.input_prompt(&prompt));\n\n }\n\n Ok(UIRequest::Input {\n\n prompt,\n", "file_path": "src/connui.rs", "rank": 97, "score": 127000.26941823492 }, { "content": "/// Returns true if r1 intersects r2\n\npub fn intersects_range<T: Ord + Copy>(r1: Range<T>, r2: Range<T>) -> bool {\n\n use std::cmp::{max, min};\n\n let start = max(r1.start, r2.start);\n\n let end = min(r1.end, r2.end);\n\n\n\n end > start\n\n}\n\n\n\n/// Position allows referring to an absolute visible row number\n\n/// or a position relative to some existing row number (typically\n\n/// where the cursor is located). Both of the cases are represented\n\n/// as signed numbers so that the math and error checking for out\n\n/// of range values can be deferred to the point where we execute\n\n/// the request.\n\n#[derive(Debug)]\n\npub enum Position {\n\n Absolute(VisibleRowIndex),\n\n Relative(i64),\n\n}\n\n\n", "file_path": "term/src/lib.rs", "rank": 98, "score": 125913.85235403676 } ]
Rust
src/console.rs
osenft/libtock-rs
55e498a4342ef7a56d1e78ac2d434a0c0e5f410d
use crate::callback::Identity0Consumer; use crate::executor; use crate::futures; use crate::result::TockResult; use crate::syscalls; use core::cell::Cell; use core::fmt; use core::fmt::Write; use core::mem; static mut CONSOLE: Option<Console> = None; const DRIVER_NUMBER: usize = 1; mod command_nr { pub const WRITE: usize = 1; } mod subscribe_nr { pub const SET_ALARM: usize = 1; } mod allow_nr { pub const SHARE_BUFFER: usize = 1; } #[non_exhaustive] pub struct ConsoleDriver; impl ConsoleDriver { pub fn create_console(self) { let console = Console { allow_buffer: [0; 64], }; console.set_global_console(); } } pub struct Console { allow_buffer: [u8; 64], } pub static mut MISSED_PRINT: bool = false; pub fn get_global_console() -> Option<Console> { unsafe { if let Some(con) = CONSOLE.take() { Some(con) } else { MISSED_PRINT = true; None } } } impl Console { pub fn write<S: AsRef<[u8]>>(&mut self, text: S) -> TockResult<()> { let mut not_written_yet = text.as_ref(); while !not_written_yet.is_empty() { let num_bytes_to_print = self.allow_buffer.len().min(not_written_yet.len()); self.allow_buffer[..num_bytes_to_print] .copy_from_slice(&not_written_yet[..num_bytes_to_print]); self.flush(num_bytes_to_print)?; not_written_yet = &not_written_yet[num_bytes_to_print..]; } Ok(()) } fn flush(&mut self, num_bytes_to_print: usize) -> TockResult<()> { let shared_memory = syscalls::allow( DRIVER_NUMBER, allow_nr::SHARE_BUFFER, &mut self.allow_buffer[..num_bytes_to_print], )?; let is_written = Cell::new(false); let mut is_written_alarm = || is_written.set(true); let subscription = syscalls::subscribe::<Identity0Consumer, _>( DRIVER_NUMBER, subscribe_nr::SET_ALARM, &mut is_written_alarm, )?; syscalls::command(DRIVER_NUMBER, command_nr::WRITE, num_bytes_to_print, 0)?; unsafe { executor::block_on(futures::wait_until(|| is_written.get())) }; mem::drop(subscription); mem::drop(shared_memory); Ok(()) } pub fn set_global_console(mut self) { unsafe { if MISSED_PRINT { let _ = write!(self, "A print was dropped while the console was locked"); MISSED_PRINT = false; } CONSOLE = Some(self); } } } impl fmt::Write for Console { fn write_str(&mut self, string: &str) -> Result<(), fmt::Error> { self.write(string).map_err(|_| fmt::Error) } } #[macro_export] macro_rules! println { () => ({ println!("") }); ($msg:expr) => ({ if let Some(mut console) = $crate::console::get_global_console() { use core::fmt::Write; let _ = writeln!(console, $msg); console.set_global_console(); } }); ($fmt:expr, $($arg:tt)+) => ({ if let Some(mut console) = $crate::console::get_global_console() { use core::fmt::Write; let _ = writeln!(console, "{}", format_args!($fmt, $($arg)+)); console.set_global_console(); } }); } #[macro_export] macro_rules! print { () => ({ print!("") }); ($msg:expr) => ({ if let Some(mut console) = $crate::console::get_global_console() { use core::fmt::Write; let _ = write!(console, $msg); console.set_global_console(); } }); ($fmt:expr, $($arg:tt)+) => ({ if let Some(mut console) = $crate::console::get_global_console() { use core::fmt::Write; let _ = write!(console, "{}", format_args!($fmt, $($arg)+)); console.set_global_console(); } }); }
use crate::callback::Identity0Consumer; use crate::executor; use crate::futures; use crate::result::TockResult; use crate::syscalls; use core::cell::Cell; use core::fmt; use core::fmt::Write; use core::mem; static mut CONSOLE: Option<Console> = None; const DRIVER_NUMBER: usize = 1; mod command_nr { pub const WRITE: usize = 1; } mod subscribe_nr { pub const SET_ALARM: usize = 1; } mod allow_nr { pub const SHARE_BUFFER: usize = 1; } #[non_exhaustive] pub struct ConsoleDriver; impl ConsoleDriver { pub fn create_console(self) { let console = Console { allow_buffer: [0; 64], }; console.set_global_console(); } } pub struct Console { allow_buffer: [u8; 64], } pub static mut MISSED_PRINT: bool = false; pu
impl Console { pub fn write<S: AsRef<[u8]>>(&mut self, text: S) -> TockResult<()> { let mut not_written_yet = text.as_ref(); while !not_written_yet.is_empty() { let num_bytes_to_print = self.allow_buffer.len().min(not_written_yet.len()); self.allow_buffer[..num_bytes_to_print] .copy_from_slice(&not_written_yet[..num_bytes_to_print]); self.flush(num_bytes_to_print)?; not_written_yet = &not_written_yet[num_bytes_to_print..]; } Ok(()) } fn flush(&mut self, num_bytes_to_print: usize) -> TockResult<()> { let shared_memory = syscalls::allow( DRIVER_NUMBER, allow_nr::SHARE_BUFFER, &mut self.allow_buffer[..num_bytes_to_print], )?; let is_written = Cell::new(false); let mut is_written_alarm = || is_written.set(true); let subscription = syscalls::subscribe::<Identity0Consumer, _>( DRIVER_NUMBER, subscribe_nr::SET_ALARM, &mut is_written_alarm, )?; syscalls::command(DRIVER_NUMBER, command_nr::WRITE, num_bytes_to_print, 0)?; unsafe { executor::block_on(futures::wait_until(|| is_written.get())) }; mem::drop(subscription); mem::drop(shared_memory); Ok(()) } pub fn set_global_console(mut self) { unsafe { if MISSED_PRINT { let _ = write!(self, "A print was dropped while the console was locked"); MISSED_PRINT = false; } CONSOLE = Some(self); } } } impl fmt::Write for Console { fn write_str(&mut self, string: &str) -> Result<(), fmt::Error> { self.write(string).map_err(|_| fmt::Error) } } #[macro_export] macro_rules! println { () => ({ println!("") }); ($msg:expr) => ({ if let Some(mut console) = $crate::console::get_global_console() { use core::fmt::Write; let _ = writeln!(console, $msg); console.set_global_console(); } }); ($fmt:expr, $($arg:tt)+) => ({ if let Some(mut console) = $crate::console::get_global_console() { use core::fmt::Write; let _ = writeln!(console, "{}", format_args!($fmt, $($arg)+)); console.set_global_console(); } }); } #[macro_export] macro_rules! print { () => ({ print!("") }); ($msg:expr) => ({ if let Some(mut console) = $crate::console::get_global_console() { use core::fmt::Write; let _ = write!(console, $msg); console.set_global_console(); } }); ($fmt:expr, $($arg:tt)+) => ({ if let Some(mut console) = $crate::console::get_global_console() { use core::fmt::Write; let _ = write!(console, "{}", format_args!($fmt, $($arg)+)); console.set_global_console(); } }); }
b fn get_global_console() -> Option<Console> { unsafe { if let Some(con) = CONSOLE.take() { Some(con) } else { MISSED_PRINT = true; None } } }
function_block-function_prefixed
[ { "content": "fn write_as_hex(buffer: &mut [u8], value: usize) {\n\n write_formatted(buffer, value, 0x10_00_00_00, 0x10);\n\n}\n\n\n", "file_path": "src/debug/mod.rs", "rank": 0, "score": 260874.68899420756 }, { "content": "fn hex(mut n: usize, buf: &mut [u8]) -> usize {\n\n let mut i = buf.len() - 1;\n\n\n\n loop {\n\n let d = (n % 16) as u8;\n\n *buf.get_mut(i)\n\n .unwrap_or_else(|| unsafe { assume_unreachable!() }) =\n\n if d < 10 { d + b'0' } else { (d - 10) + b'a' };\n\n n = n / 16;\n\n\n\n i -= 1;\n\n if n == 0 {\n\n break;\n\n }\n\n }\n\n\n\n *buf.get_mut(i)\n\n .unwrap_or_else(|| unsafe { assume_unreachable!() }) = b'x';\n\n i -= 1;\n\n\n", "file_path": "ufmt/src/impls/ptr.rs", "rank": 1, "score": 246931.88689777494 }, { "content": "fn write_formatted(buffer: &mut [u8], value: usize, start: usize, base: usize) {\n\n let mut scanning = start;\n\n let mut remainder = value;\n\n let mut position = 2;\n\n buffer[0..2].clone_from_slice(b\"0x\");\n\n\n\n while scanning > 0 {\n\n let digit = remainder / scanning;\n\n buffer[position] = render_digit(digit as u8) as u8;\n\n\n\n remainder %= scanning;\n\n scanning /= base;\n\n position += 1;\n\n }\n\n}\n\n\n", "file_path": "src/debug/mod.rs", "rank": 2, "score": 245940.09904675628 }, { "content": "/// It is safe to return a 'static immutable slice, as the Tock kernel doesn't change the layout of\n\n/// flash regions during the application's lifetime.\n\npub fn get_flash_region(i: usize) -> Option<&'static [u8]> {\n\n if i < get_flash_regions_count() {\n\n let start_addr = unsafe { syscalls::raw::memop(8, i) } as usize;\n\n let start_ptr = start_addr as *const u8;\n\n let end_addr = unsafe { syscalls::raw::memop(9, i) } as usize;\n\n // This assumes that the kernel sends consistent results, i.e. start <= end.\n\n let len = end_addr - start_addr;\n\n Some(unsafe { slice::from_raw_parts(start_ptr, len) })\n\n } else {\n\n None\n\n }\n\n}\n\n\n\n/// Set the top of the stack\n\n/// # Safety\n\n/// Setting the stack_top and heap_start addresses are marked as unsafe as they should only be called\n\n/// by the entry point to setup the allocator. Updating these values afterwards can lead to incorrect\n\n/// debug output from the kernel.\n\n///\n\n/// Alternate allocator implementations may still find this useful in the future.\n", "file_path": "core/src/memop.rs", "rank": 3, "score": 240397.10150512645 }, { "content": "/// Increment the memory break\n\npub fn increment_brk(increment: usize) -> Option<*const u8> {\n\n let result = unsafe { syscalls::raw::memop(1, increment) };\n\n if result >= 0 {\n\n Some(result as *const u8)\n\n } else {\n\n None\n\n }\n\n}\n\n\n", "file_path": "core/src/memop.rs", "rank": 4, "score": 240215.87057066505 }, { "content": "pub fn get_flash_region_start(i: usize) -> Option<*const u8> {\n\n if i < get_flash_regions_count() {\n\n Some(unsafe { syscalls::raw::memop(8, i) as *const u8 })\n\n } else {\n\n None\n\n }\n\n}\n\n\n", "file_path": "core/src/memop.rs", "rank": 5, "score": 235934.05623353895 }, { "content": "pub fn get_flash_region_end(i: usize) -> Option<*const u8> {\n\n if i < get_flash_regions_count() {\n\n Some(unsafe { syscalls::raw::memop(9, i) as *const u8 })\n\n } else {\n\n None\n\n }\n\n}\n\n\n", "file_path": "core/src/memop.rs", "rank": 6, "score": 235934.05623353895 }, { "content": "pub fn get_brk() -> *const u8 {\n\n unsafe { syscalls::raw::memop(1, 0) as *const u8 }\n\n}\n\n\n", "file_path": "core/src/memop.rs", "rank": 7, "score": 235020.71324931894 }, { "content": "fn usize(n: usize, buf: &mut [u8]) -> &str {\n\n uxx!(n, buf)\n\n}\n\n\n\nimpl uDebug for u8 {\n\n fn fmt<W>(&self, f: &mut Formatter<'_, W>) -> Result<(), W::Error>\n\n where\n\n W: uWrite + ?Sized,\n\n {\n\n let mut buf: [u8; 3] = unsafe { crate::uninitialized() };\n\n\n\n f.write_str(usize(usize::from(*self), &mut buf))\n\n }\n\n}\n\n\n\nimpl uDisplay for u8 {\n\n #[inline(always)]\n\n fn fmt<W>(&self, f: &mut Formatter<'_, W>) -> Result<(), W::Error>\n\n where\n\n W: uWrite + ?Sized,\n", "file_path": "ufmt/src/impls/uxx.rs", "rank": 8, "score": 234970.00004344998 }, { "content": "pub fn get_flash_end() -> *const u8 {\n\n unsafe { syscalls::raw::memop(5, 0) as *const u8 }\n\n}\n\n\n", "file_path": "core/src/memop.rs", "rank": 9, "score": 230966.62295605947 }, { "content": "pub fn get_grant_start() -> *const u8 {\n\n unsafe { syscalls::raw::memop(6, 0) as *const u8 }\n\n}\n\n\n", "file_path": "core/src/memop.rs", "rank": 10, "score": 230966.62295605947 }, { "content": "pub fn get_mem_start() -> *const u8 {\n\n unsafe { syscalls::raw::memop(2, 0) as *const u8 }\n\n}\n\n\n", "file_path": "core/src/memop.rs", "rank": 11, "score": 230966.62295605947 }, { "content": "pub fn get_mem_end() -> *const u8 {\n\n unsafe { syscalls::raw::memop(3, 0) as *const u8 }\n\n}\n\n\n", "file_path": "core/src/memop.rs", "rank": 12, "score": 230966.62295605947 }, { "content": "pub fn get_flash_start() -> *const u8 {\n\n unsafe { syscalls::raw::memop(4, 0) as *const u8 }\n\n}\n\n\n", "file_path": "core/src/memop.rs", "rank": 13, "score": 230966.62295605947 }, { "content": "#[allow(dead_code)]\n\nfn static_lifetime(x: &'static mut u32) {\n\n fn foo(x: &'static mut u32) -> *mut u32 {\n\n x as *mut u32\n\n }\n\n\n\n uwrite!(&mut String::new(), \"{:?}\", foo(x)).ok();\n\n}\n\n\n\n// test dynamically sized writer\n", "file_path": "ufmt/tests/vs-std-write.rs", "rank": 14, "score": 210138.96581872035 }, { "content": "fn isize(n: isize, buf: &mut [u8]) -> &str {\n\n ixx!(usize, n, buf)\n\n}\n\n\n\nimpl uDebug for i8 {\n\n fn fmt<W>(&self, f: &mut Formatter<'_, W>) -> Result<(), W::Error>\n\n where\n\n W: uWrite + ?Sized,\n\n {\n\n let mut buf: [u8; 4] = unsafe { crate::uninitialized() };\n\n\n\n f.write_str(isize(isize::from(*self), &mut buf))\n\n }\n\n}\n\n\n\nimpl uDisplay for i8 {\n\n #[inline(always)]\n\n fn fmt<W>(&self, f: &mut Formatter<'_, W>) -> Result<(), W::Error>\n\n where\n\n W: uWrite + ?Sized,\n", "file_path": "ufmt/src/impls/ixx.rs", "rank": 15, "score": 191110.53096937636 }, { "content": "pub fn find(buffer: &[u8], kind: u8) -> Option<&[u8]> {\n\n let mut iter = buffer[8..].iter().enumerate();\n\n let buffer_len = buffer.len();\n\n\n\n loop {\n\n match iter.next() {\n\n Some((_, &len)) => match iter.next() {\n\n Some((i, potentialkind)) => {\n\n if potentialkind == &kind {\n\n if (8 + i) + len as usize > buffer_len {\n\n return None;\n\n } else {\n\n return Some(&buffer[9 + i..8 + i + len as usize]);\n\n }\n\n } else if len > 0 {\n\n for _ in 0..len - 1 {\n\n iter.next();\n\n }\n\n } else {\n\n return None;\n\n }\n\n }\n\n _ => return None,\n\n },\n\n None => return None,\n\n }\n\n }\n\n}\n\n\n", "file_path": "src/ble_parser.rs", "rank": 16, "score": 180349.90587605393 }, { "content": "fn safe_copy(origin: &[u8], destination: &mut [u8]) {\n\n let amount = origin.len().min(destination.len());\n\n let origin = &origin[0..amount];\n\n let destination = &mut destination[0..amount];\n\n destination.copy_from_slice(origin);\n\n}\n", "file_path": "core/src/shared_memory.rs", "rank": 17, "score": 178255.38883089134 }, { "content": "pub fn extract_for_service(service: [u8; 2], data: &[u8]) -> Option<&[u8]> {\n\n if data.len() > 1 {\n\n if service[0] == data[0] && service[1] == data[1] {\n\n Some(&data[2..])\n\n } else {\n\n None\n\n }\n\n } else {\n\n None\n\n }\n\n}\n\n\n\n#[cfg(test)]\n\nmod test {\n\n use crate::ble_parser::*;\n\n use crate::simple_ble::BUFFER_SIZE_SCAN;\n\n\n\n #[test]\n\n fn extracts_data_for_ids_correctly() {\n\n let mut buf = [0; BUFFER_SIZE_SCAN];\n", "file_path": "src/ble_parser.rs", "rank": 18, "score": 175378.63498282197 }, { "content": "fn number_to_bits(n: u8) -> [bool; 8] {\n\n match n {\n\n 1 => [false, false, false, true, false, true, false, false],\n\n 2 => [true, false, true, true, false, false, true, true],\n\n 3 => [true, false, true, true, false, true, true, false],\n\n 4 => [true, true, false, true, false, true, false, false],\n\n 5 => [true, true, true, false, false, true, true, false],\n\n 6 => [true, true, true, false, false, true, true, true],\n\n 7 => [false, false, true, true, false, true, false, false],\n\n 8 => [true, true, true, true, false, true, true, true],\n\n 9 => [true, true, true, true, false, true, true, false],\n\n 0 => [false, true, true, true, false, true, true, true],\n\n _ => [false, false, false, false, true, false, false, false],\n\n }\n\n}\n\n\n\n// Example works on a shift register on P0.03, P0.04, P0.28\n\n#[libtock::main]\n\nasync fn main() -> TockResult<()> {\n\n let mut drivers = libtock::retrieve_drivers()?;\n", "file_path": "examples/seven_segment.rs", "rank": 19, "score": 174989.60816077993 }, { "content": "pub fn subscribe_fn(\n\n driver_number: usize,\n\n subscribe_number: usize,\n\n callback: extern \"C\" fn(usize, usize, usize, usize),\n\n userdata: usize,\n\n) -> Result<(), SubscribeError> {\n\n let return_code = unsafe {\n\n raw::subscribe(\n\n driver_number,\n\n subscribe_number,\n\n callback as *const _,\n\n userdata,\n\n )\n\n };\n\n\n\n if return_code == 0 {\n\n Ok(())\n\n } else {\n\n Err(SubscribeError {\n\n driver_number,\n\n subscribe_number,\n\n return_code,\n\n })\n\n }\n\n}\n\n\n", "file_path": "core/src/syscalls/mod.rs", "rank": 20, "score": 167953.14999824454 }, { "content": "#[inline(never)]\n\nfn increment_static_mut() -> usize {\n\n static mut STATIC: usize = 0;\n\n\n\n unsafe {\n\n STATIC += 1;\n\n STATIC\n\n }\n\n}\n\n\n", "file_path": "examples-features/libtock_test.rs", "rank": 22, "score": 162349.95911149937 }, { "content": "pub fn command(\n\n driver_number: usize,\n\n command_number: usize,\n\n arg1: usize,\n\n arg2: usize,\n\n) -> Result<usize, CommandError> {\n\n let return_code = unsafe { raw::command(driver_number, command_number, arg1, arg2) };\n\n if return_code >= 0 {\n\n Ok(return_code as usize)\n\n } else {\n\n Err(CommandError {\n\n driver_number,\n\n command_number,\n\n arg1,\n\n arg2,\n\n return_code,\n\n })\n\n }\n\n}\n\n\n", "file_path": "core/src/syscalls/mod.rs", "rank": 23, "score": 161269.0658285392 }, { "content": "pub fn allow(\n\n driver_number: usize,\n\n allow_number: usize,\n\n buffer_to_share: &mut [u8],\n\n) -> Result<SharedMemory, AllowError> {\n\n let len = buffer_to_share.len();\n\n let return_code = unsafe {\n\n raw::allow(\n\n driver_number,\n\n allow_number,\n\n buffer_to_share.as_mut_ptr(),\n\n len,\n\n )\n\n };\n\n if return_code == 0 {\n\n Ok(SharedMemory::new(\n\n driver_number,\n\n allow_number,\n\n buffer_to_share,\n\n ))\n\n } else {\n\n Err(AllowError {\n\n driver_number,\n\n allow_number,\n\n return_code,\n\n })\n\n }\n\n}\n", "file_path": "core/src/syscalls/mod.rs", "rank": 24, "score": 161269.0658285392 }, { "content": "/// [command1_insecure()] is a variant of [command()] that only sets the first\n\n/// argument in the system call interface. It has the benefit of generating\n\n/// simpler assembly than [command()], but it leaves the second argument's register\n\n/// as-is which leaks it to the kernel driver being called. Prefer to use\n\n/// [command()] instead of [command1_insecure()], unless the benefit of generating\n\n/// simpler assembly outweighs the drawbacks of potentially leaking arbitrary\n\n/// information to the driver you are calling.\n\n///\n\n/// At the moment, the only suitable use case for [command1_insecure()] is the low\n\n/// level debug interface.\n\npub fn command1_insecure(\n\n driver_number: usize,\n\n command_number: usize,\n\n arg: usize,\n\n) -> Result<usize, CommandError> {\n\n let return_code = unsafe { raw::command1(driver_number, command_number, arg) };\n\n if return_code >= 0 {\n\n Ok(return_code as usize)\n\n } else {\n\n Err(CommandError {\n\n driver_number,\n\n command_number,\n\n arg1: arg,\n\n arg2: 0,\n\n return_code,\n\n })\n\n }\n\n}\n\n\n", "file_path": "core/src/syscalls/mod.rs", "rank": 25, "score": 157852.56573264214 }, { "content": "pub fn print_stack_pointer() {\n\n let mut buffer = [b'\\n'; 15];\n\n buffer[0..4].clone_from_slice(b\"SP: \");\n\n write_as_hex(&mut buffer[4..15], core_debug::get_stack_pointer());\n\n let drivers = unsafe { drivers::retrieve_drivers_unsafe() };\n\n drivers.console.create_console();\n\n println!(\"{:?}\", buffer);\n\n}\n\n\n\n#[inline(always)]\n\n/// Dumps address\n\n/// # Safety\n\n/// dereferences pointer without check - may lead to access violation.\n\npub unsafe fn dump_address(address: *const usize) {\n\n let mut buffer = [b' '; 28];\n\n write_as_hex(&mut buffer[0..10], address as usize);\n\n buffer[10] = b':';\n\n write_as_hex(&mut buffer[12..22], *address);\n\n for index in 0..4 {\n\n let byte = *(address as *const u8).offset(index);\n", "file_path": "src/debug/mod.rs", "rank": 26, "score": 157848.62577694777 }, { "content": "fn write(input: TokenStream, newline: bool) -> TokenStream {\n\n let input = parse_macro_input!(input as Input);\n\n\n\n let formatter = &input.formatter;\n\n let literal = input.literal;\n\n\n\n let mut format = literal.value();\n\n if newline {\n\n format.push('\\n');\n\n }\n\n let pieces = match parse(&format, literal.span()) {\n\n Err(e) => return e.to_compile_error().into(),\n\n Ok(pieces) => pieces,\n\n };\n\n\n\n let required_args = pieces.iter().filter(|piece| !piece.is_str()).count();\n\n let supplied_args = input.args.len();\n\n if supplied_args < required_args {\n\n return parse::Error::new(\n\n literal.span(),\n", "file_path": "ufmt/macros/src/lib.rs", "rank": 27, "score": 157349.94452190035 }, { "content": "pub fn subscribe(cb: extern \"C\" fn(usize, usize, usize, usize), ud: usize) -> TockResult<()> {\n\n syscalls::subscribe_fn(DRIVER_NUM, 0, cb, ud)?;\n\n Ok(())\n\n}\n\n\n", "file_path": "src/sensors/ninedof.rs", "rank": 28, "score": 150712.040466724 }, { "content": "fn render_digit(digit: u8) -> char {\n\n if digit < 10 {\n\n (b'0' + digit) as char\n\n } else {\n\n (b'a' + digit - 10) as char\n\n }\n\n}\n", "file_path": "src/debug/mod.rs", "rank": 29, "score": 149687.82035208348 }, { "content": "pub fn get_stack_pointer() -> usize {\n\n panic!(\"No generic implementation.\")\n\n}\n", "file_path": "core/src/debug/platform.rs", "rank": 30, "score": 148200.36448161938 }, { "content": "pub fn get_flash_regions_count() -> usize {\n\n unsafe { syscalls::raw::memop(7, 0) as usize }\n\n}\n\n\n", "file_path": "core/src/memop.rs", "rank": 31, "score": 148200.36448161938 }, { "content": "/// For tests: Run the closure recording the syscalls which are invoked in during the run of the closure.\n\npub fn run_recording_events<R, C: FnMut(&NextReturn) -> R>(mut f: C) -> Vec<Event> {\n\n NEXT_OUTPUT.with(|n| n.set(0));\n\n NEXT_OUTPUT.with(|n| f(n));\n\n let mut output = Vec::new();\n\n EVENTS.with(|e| output.append(&mut e.borrow_mut()));\n\n output\n\n}\n\n\n\nthread_local!(static EVENTS: RefCell<Vec<Event>> = RefCell::new(Vec::new()));\n\nthread_local!(static NEXT_OUTPUT: NextReturn = NextReturn { next_return: Cell::new(0) });\n\n\n\n#[derive(Clone, Debug, PartialEq)]\n\n/// For tests: syscall event\n\npub enum Event {\n\n YieldK,\n\n Subscribe(\n\n usize,\n\n usize,\n\n *const unsafe extern \"C\" fn(usize, usize, usize, usize),\n\n usize,\n", "file_path": "core/src/syscalls/platform.rs", "rank": 32, "score": 146698.3801706697 }, { "content": "pub fn get_stack_pointer() -> usize {\n\n let stack_pointer;\n\n unsafe { llvm_asm!(\"mv $0, sp\" : \"=r\"(stack_pointer) : : : \"volatile\") };\n\n stack_pointer\n\n}\n", "file_path": "core/src/debug/platform_riscv32.rs", "rank": 33, "score": 145341.1732582029 }, { "content": "pub fn get_stack_pointer() -> usize {\n\n let stack_pointer;\n\n unsafe { llvm_asm!(\"mov $0, sp\" : \"=r\"(stack_pointer) : : : \"volatile\") };\n\n stack_pointer\n\n}\n", "file_path": "core/src/debug/platform_arm.rs", "rank": 34, "score": 145341.1732582029 }, { "content": "fn test_succeeded(input: String, failed_tests: &mut Vec<String>) -> Option<bool> {\n\n let success = input.contains(\"[ OK ]\");\n\n let failure = input.contains(\"[ FAILURE ]\");\n\n let input = input.replace(\"[ OK ]\", \"\");\n\n let input = input.replace(\"[ FAILURE ]\", \"\");\n\n let input = input.trim();\n\n if input == \"Test suite finished with state SUCCESS\" && success {\n\n return Some(true);\n\n } else if input == \"Test suite finished with state FAILURE\" && !success {\n\n return Some(false);\n\n } else if failure {\n\n failed_tests.push(input.to_string());\n\n }\n\n None\n\n}\n\n\n", "file_path": "test_runner/src/main.rs", "rank": 35, "score": 140853.68761404086 }, { "content": "#[inline(always)] // Improve reliability for relocation issues\n\npub fn low_level_print2(value1: usize, value2: usize) {\n\n let _ = syscalls::command(DRIVER_NUMBER, command_nr::PRINT2, value1, value2);\n\n}\n", "file_path": "src/debug/low_level_debug.rs", "rank": 36, "score": 140643.60022011615 }, { "content": "#[inline(always)] // Improve reliability for relocation issues\n\npub fn low_level_print1(value: usize) {\n\n let _ = syscalls::command1_insecure(DRIVER_NUMBER, command_nr::PRINT1, value);\n\n}\n\n\n\n/// Use the LowLevelDebug capsule (if present) to print two numbers. If the\n\n/// capsule is not present, this is a no-op.\n", "file_path": "src/debug/low_level_debug.rs", "rank": 37, "score": 139611.2756939174 }, { "content": "pub fn subscribe<C: Consumer<T>, T>(\n\n driver_number: usize,\n\n subscribe_number: usize,\n\n payload: &mut T,\n\n) -> Result<CallbackSubscription, SubscribeError> {\n\n extern \"C\" fn c_callback<T, C: Consumer<T>>(\n\n arg1: usize,\n\n arg2: usize,\n\n arg3: usize,\n\n data: usize,\n\n ) {\n\n let payload = unsafe { &mut *(data as *mut T) };\n\n C::consume(payload, arg1, arg2, arg3);\n\n }\n\n\n\n subscribe_fn(\n\n driver_number,\n\n subscribe_number,\n\n c_callback::<T, C>,\n\n payload as *mut _ as usize,\n\n )\n\n .map(|_| CallbackSubscription::new(driver_number, subscribe_number))\n\n}\n\n\n", "file_path": "core/src/syscalls/mod.rs", "rank": 38, "score": 137224.45077879986 }, { "content": "#[inline(always)] // Improve reliability for relocation issues\n\npub fn low_level_status_code(code: usize) {\n\n let _ = syscalls::command1_insecure(DRIVER_NUMBER, command_nr::ALERT_CODE, code);\n\n}\n\n\n\n/// Use the LowLevelDebug capsule (if present) to print a single number. If the\n\n/// capsule is not present, this is a no-op.\n", "file_path": "src/debug/low_level_debug.rs", "rank": 39, "score": 137053.86909356245 }, { "content": "#[test]\n\nfn struct_() {\n\n #[derive(Debug, uDebug)]\n\n struct Braces {}\n\n\n\n #[derive(Debug, uDebug)]\n\n struct Parens();\n\n\n\n #[derive(Debug, Default, uDebug)]\n\n struct I32(i32);\n\n\n\n #[derive(Debug, Default, uDebug)]\n\n struct Tuple(i32, i32);\n\n\n\n #[derive(Debug, Default, uDebug)]\n\n struct Pair {\n\n x: i32,\n\n y: i32,\n\n }\n\n\n\n #[derive(Debug, Default, uDebug)]\n", "file_path": "ufmt/tests/vs-std-write.rs", "rank": 40, "score": 135452.95650915944 }, { "content": "pub trait Sensor<Reading: Copy + From<(usize, usize, usize)>> {\n\n fn driver_num(&self) -> usize;\n\n\n\n fn read(&mut self) -> TockResult<Reading> {\n\n let res: Cell<Option<Reading>> = Cell::new(None);\n\n let driver_num = self.driver_num();\n\n syscalls::subscribe_fn(driver_num, 0, cb::<Reading>, unsafe {\n\n mem::transmute(&res)\n\n })?;\n\n syscalls::command(driver_num, 1, 0, 0)?;\n\n Ok(unsafe { executor::block_on(futures::wait_for_value(|| res.get())) })\n\n }\n\n}\n\n\n\nmacro_rules! single_value_sensor {\n\n ($sensor_name:ident, $type_name:ident, $driver_num:expr) => {\n\n #[derive(Copy, Clone, Eq, PartialEq, Debug)]\n\n pub struct $type_name {\n\n value: i32,\n\n }\n", "file_path": "src/sensors/mod.rs", "rank": 41, "score": 134384.6538391415 }, { "content": "/// Provides access to a global instance of type `Target`. Every call to\n\n/// `locate()` on a given Locator type should return a reference to the same\n\n/// instance of `Target`. An instance of `Locator` generally isn't instantiated\n\n/// directly; instead, its type is passed to where it is needed via generic\n\n/// arguments.\n\n///\n\n/// For convenience, Locator provides a `FreeCallback` implementation for every\n\n/// `MethodCallback` implementation that `Target` has.\n\npub trait Locator: 'static {\n\n type Target;\n\n fn locate() -> &'static Self::Target;\n\n}\n\n\n\nimpl<L: Locator, AsyncResponse> FreeCallback<AsyncResponse> for L\n\nwhere\n\n L::Target: MethodCallback<AsyncResponse>,\n\n{\n\n fn call(context: CallbackContext, response: AsyncResponse) {\n\n L::locate().call(context, response);\n\n }\n\n}\n", "file_path": "platform/src/async_traits.rs", "rank": 42, "score": 126162.79201849413 }, { "content": "// Do not inline this to prevent compiler optimizations\n\nfn foo() -> &'static str {\n\n \"foo\"\n\n}\n\n\n", "file_path": "examples-features/libtock_test.rs", "rank": 43, "score": 120758.37498139402 }, { "content": "// Clears this thread's Kernel instance. This allows the Kernel to be\n\n// deallocated, and should be called by Kernel's Drop implementation.\n\npub fn clear_kernel() {\n\n THREAD_KERNEL.with(|thread_kernel| thread_kernel.kernel.replace(Weak::new()));\n\n}\n\n\n\n// Retrieves this thread's Kernel instance, if one is available.\n", "file_path": "unittest/src/kernel/thread_local.rs", "rank": 44, "score": 119647.4076842722 }, { "content": "pub fn start_magnetometer_reading() -> TockResult<()> {\n\n syscalls::command(DRIVER_NUM, 100, 0, 0)?;\n\n Ok(())\n\n}\n\n\n", "file_path": "src/sensors/ninedof.rs", "rank": 45, "score": 114161.56921220015 }, { "content": "pub fn start_accel_reading() -> TockResult<()> {\n\n syscalls::command(DRIVER_NUM, 1, 0, 0)?;\n\n Ok(())\n\n}\n\n\n", "file_path": "src/sensors/ninedof.rs", "rank": 46, "score": 114161.56921220015 }, { "content": "pub fn start_gyroscope_reading() -> TockResult<()> {\n\n syscalls::command(DRIVER_NUM, 200, 0, 0)?;\n\n Ok(())\n\n}\n", "file_path": "src/sensors/ninedof.rs", "rank": 47, "score": 114161.56921220015 }, { "content": "#[allow(non_camel_case_types)]\n\npub trait uWrite {\n\n /// The error associated to this writer\n\n type Error;\n\n\n\n /// Writes a string slice into this writer, returning whether the write succeeded.\n\n ///\n\n /// This method can only succeed if the entire string slice was successfully written, and this\n\n /// method will not return until all data has been written or an error occurs.\n\n fn write_str(&mut self, s: &str) -> Result<(), Self::Error>;\n\n\n\n /// Writes a [`char`] into this writer, returning whether the write succeeded.\n\n ///\n\n /// A single [`char`] may be encoded as more than one byte. This method can only succeed if the\n\n /// entire byte sequence was successfully written, and this method will not return until all\n\n /// data has been written or an error occurs.\n\n fn write_char(&mut self, c: char) -> Result<(), Self::Error> {\n\n let mut buf: [u8; 4] = unsafe { uninitialized() };\n\n self.write_str(c.encode_utf8(&mut buf))\n\n }\n\n}\n", "file_path": "ufmt/write/src/lib.rs", "rank": 48, "score": 112297.913444708 }, { "content": "fn is_over(timer: ActiveTimer, now: u32) -> bool {\n\n now.wrapping_sub(timer.set_at) >= timer.instant.wrapping_sub(timer.set_at)\n\n}\n\n\n", "file_path": "src/timer.rs", "rank": 49, "score": 110179.50501254841 }, { "content": "/// Retrieve [Drivers] struct. Returns struct only once.\n\npub fn retrieve_drivers() -> Result<Drivers, DriversAlreadyTakenError> {\n\n static mut DRIVER_TAKEN: bool = false;\n\n\n\n unsafe {\n\n if DRIVER_TAKEN {\n\n Err(DriversAlreadyTakenError)\n\n } else {\n\n DRIVER_TAKEN = true;\n\n Ok(retrieve_drivers_unsafe())\n\n }\n\n }\n\n}\n\n\n\n/// Retrieve [Drivers] struct without check whether it has already been taken\n\n/// at a different point.\n\n/// # Safety\n\n/// This shall only used in special situations where drivers cannot be passed as arguments\n\n/// as in the panic handler. Otherwise global mutable state (as shared buffers) may be exposed\n\n/// in an unsafe manner.\n\npub unsafe fn retrieve_drivers_unsafe() -> Drivers {\n", "file_path": "src/drivers.rs", "rank": 50, "score": 104787.57561639708 }, { "content": "#[proc_macro_derive(uDebug)]\n\npub fn debug(input: TokenStream) -> TokenStream {\n\n let input = parse_macro_input!(input as DeriveInput);\n\n\n\n let mut generics = input.generics;\n\n\n\n for param in &mut generics.params {\n\n if let GenericParam::Type(type_param) = param {\n\n type_param.bounds.push(parse_quote!(ufmt::uDebug));\n\n }\n\n }\n\n\n\n let (impl_generics, ty_generics, where_clause) = generics.split_for_impl();\n\n\n\n let ident = &input.ident;\n\n let ts = match input.data {\n\n Data::Struct(data) => {\n\n let ident_s = ident.to_string();\n\n\n\n let body = match data.fields {\n\n Fields::Named(fields) => {\n", "file_path": "ufmt/macros/src/lib.rs", "rank": 51, "score": 104782.19608375992 }, { "content": "// Sets this thread's Kernel instance. If this thread already has a Kernel\n\n// instance, this panics with a message indicating the name of the existing\n\n// Kernel instance, as it was presumably leaked.\n\npub fn set_kernel(kernel: &Rc<Kernel>) {\n\n THREAD_KERNEL.with(|thread_kernel| {\n\n let existing_weak = thread_kernel.kernel.replace(Rc::downgrade(kernel));\n\n if let Some(existing_kernel) = existing_weak.upgrade() {\n\n existing_kernel.report_leaked();\n\n }\n\n });\n\n}\n\n\n\n// Reference to this thread's Kernel instance, if one has been initialized. This\n\n// is a weak reference so that when a unit test is done with its Kernel, the\n\n// following cleanup can happen:\n\n// 1. The test drops its Rc<Kernel> instances.\n\n// 2. The strong count drops to 0 so the Kernel is dropped.\n\n// 3. Kernel's Drop implementation clears out THREAD_KERNEL, removing the weak\n\n// reference.\n\n// 4. The backing storage holding the Kernel is deallocated.\n\nthread_local!(static THREAD_KERNEL: ThreadKernelRef = ThreadKernelRef::new());\n\n\n", "file_path": "unittest/src/kernel/thread_local.rs", "rank": 52, "score": 104782.19608375992 }, { "content": "#[proc_macro_hack]\n\npub fn uwriteln(input: TokenStream) -> TokenStream {\n\n write(input, true)\n\n}\n\n\n", "file_path": "ufmt/macros/src/lib.rs", "rank": 53, "score": 104782.19608375992 }, { "content": "#[allow(unused)] // TODO: Remove when a system call is implemented.\n\npub fn get_kernel() -> Option<Rc<Kernel>> {\n\n let clone = THREAD_KERNEL.with(|thread_kernel| {\n\n let weak = thread_kernel.kernel.replace(Weak::new());\n\n let clone = weak.clone();\n\n thread_kernel.kernel.replace(weak);\n\n clone\n\n });\n\n clone.upgrade()\n\n}\n\n\n", "file_path": "unittest/src/kernel/thread_local.rs", "rank": 54, "score": 104782.19608375992 }, { "content": "#[proc_macro_hack]\n\npub fn uwrite(input: TokenStream) -> TokenStream {\n\n write(input, false)\n\n}\n\n\n", "file_path": "ufmt/macros/src/lib.rs", "rank": 55, "score": 104782.19608375992 }, { "content": "fn left_is_later(alarm_1: ActiveTimer, alarm_2: ActiveTimer) -> bool {\n\n if alarm_1.set_at <= alarm_1.instant && alarm_2.set_at <= alarm_2.instant {\n\n return alarm_1.instant > alarm_2.instant;\n\n }\n\n if alarm_1.set_at <= alarm_1.instant && alarm_2.set_at >= alarm_2.instant {\n\n return false;\n\n }\n\n if alarm_1.set_at >= alarm_1.instant && alarm_2.set_at <= alarm_2.instant {\n\n return true;\n\n }\n\n if alarm_1.set_at >= alarm_1.instant && alarm_2.set_at >= alarm_2.instant {\n\n return alarm_1.instant > alarm_2.instant;\n\n }\n\n false\n\n}\n\n\n\n#[cfg(test)]\n\nmod test {\n\n use super::*;\n\n #[test]\n", "file_path": "src/timer.rs", "rank": 56, "score": 104448.34124002371 }, { "content": "#[repr(C)]\n\nstruct LayoutHeader {\n\n got_sym_start: usize,\n\n got_start: usize,\n\n got_size: usize,\n\n data_sym_start: usize,\n\n data_start: usize,\n\n data_size: usize,\n\n bss_start: usize,\n\n bss_size: usize,\n\n reldata_start: usize,\n\n stack_size: usize,\n\n}\n\n\n\n//Procedural macro to generate a function to read APP_HEAP_SIZE\n\nlibtock_codegen::make_read_env_var!(\"APP_HEAP_SIZE\");\n\n\n\n/// Rust setup, called by _start. Uses the extern \"C\" calling convention so that\n\n/// the assembly in _start knows how to call it (the Rust ABI is not defined).\n\n/// Sets up the data segment (including relocations) and the heap, then calls\n\n/// into the rustc-generated main(). This cannot use mutable global variables or\n", "file_path": "core/src/entry_point/mod.rs", "rank": 57, "score": 103529.25799730714 }, { "content": "// Takes the 4 least-significant bits of x, and turn the 4 leds on/off accordingly.\n\nfn blink_nibble(leds_driver: &LedsDriver, x: u8) -> TockResult<()> {\n\n for i in 0..4 {\n\n let led = leds_driver.get(i)?;\n\n if (x >> i) & 1 != 0 {\n\n led.on()?;\n\n } else {\n\n led.off()?;\n\n }\n\n }\n\n Ok(())\n\n}\n", "file_path": "examples/blink_random.rs", "rank": 58, "score": 102109.01456700351 }, { "content": "#[proc_macro]\n\npub fn make_read_env_var(input: TokenStream) -> TokenStream {\n\n let env_arg = syn::parse_macro_input!(input as syn::LitStr);\n\n let env_var_name = env_arg.value();\n\n let app_size = match std::env::var(&env_var_name) {\n\n Ok(r) => r,\n\n Err(_r) => {\n\n return syn::Error::new(\n\n env_arg.span(),\n\n format!(\"Failed to find {} in environment, is it set?\", env_var_name),\n\n )\n\n .to_compile_error()\n\n .into()\n\n }\n\n };\n\n let size = match app_size.parse::<usize>() {\n\n Ok(r) => r,\n\n Err(_r) => {\n\n return syn::Error::new(\n\n env_arg.span(),\n\n format!(\"Environment var {} can't be parsed to usize\", env_var_name),\n", "file_path": "codegen/src/lib.rs", "rank": 59, "score": 101477.08322395183 }, { "content": "#[proc_macro_attribute]\n\npub fn main(_: TokenStream, input: TokenStream) -> TokenStream {\n\n generate_main_wrapped(input.into()).into()\n\n}\n\n\n", "file_path": "codegen/src/lib.rs", "rank": 60, "score": 98623.30763495783 }, { "content": "#[test]\n\nfn ptr() {\n\n cmp!(\"{:?}\", 1 as *const u8);\n\n cmp!(\"{:?}\", 0xf as *const u8);\n\n cmp!(\"{:?}\", 0xff as *const u8);\n\n cmp!(\"{:?}\", 0xfff as *const u8);\n\n cmp!(\"{:?}\", 0xffff as *const u8);\n\n cmp!(\"{:?}\", 0xfffff as *const u8);\n\n cmp!(\"{:?}\", 0xffffff as *const u8);\n\n cmp!(\"{:?}\", 0xfffffff as *const u8);\n\n cmp!(\"{:?}\", 0xffffffff as *const u8);\n\n\n\n #[cfg(target_pointer_width = \"64\")]\n\n cmp!(\"{:?}\", 0xfffffffff as *const u8);\n\n}\n\n\n", "file_path": "ufmt/tests/vs-std-write.rs", "rank": 61, "score": 98211.16988909591 }, { "content": "#[test]\n\nfn uxx() {\n\n cmp!(\"{}\", 0u8);\n\n cmp!(\"{}\", 10u8);\n\n cmp!(\"{}\", 100u8);\n\n\n\n // extreme values\n\n cmp!(\"{}\", u8::max_value());\n\n cmp!(\"{}\", u16::max_value());\n\n cmp!(\"{}\", u32::max_value());\n\n cmp!(\"{}\", u64::max_value());\n\n cmp!(\"{}\", u128::max_value());\n\n cmp!(\"{}\", usize::max_value());\n\n}\n\n\n", "file_path": "ufmt/tests/vs-std-write.rs", "rank": 62, "score": 98211.16988909591 }, { "content": "#[test]\n\nfn slice() {\n\n cmp!(\"{:?}\", [0; 0]);\n\n cmp!(\"{:?}\", [0]);\n\n cmp!(\"{:?}\", [0, 1]);\n\n\n\n cmp!(\"{:#?}\", [0; 0]);\n\n cmp!(\"{:#?}\", [0]);\n\n cmp!(\"{:#?}\", [0, 1]);\n\n}\n\n\n", "file_path": "ufmt/tests/vs-std-write.rs", "rank": 63, "score": 98211.16988909591 }, { "content": "#[test]\n\nfn fmt() {\n\n cmp!(\"Hello, world!\");\n\n cmp!(\"The answer is {}\", 42);\n\n}\n\n\n", "file_path": "ufmt/tests/vs-std-write.rs", "rank": 64, "score": 98211.16988909591 }, { "content": "#[test]\n\nfn map() {\n\n fn x() -> BTreeMap<i32, i32> {\n\n let mut m = BTreeMap::new();\n\n m.insert(1, 2);\n\n m.insert(3, 4);\n\n m\n\n }\n\n\n\n cmp!(\"{:?}\", BTreeMap::<(), ()>::new());\n\n cmp!(\"{:?}\", x());\n\n\n\n cmp!(\"{:#?}\", BTreeMap::<(), ()>::new());\n\n cmp!(\"{:#?}\", x());\n\n}\n\n\n", "file_path": "ufmt/tests/vs-std-write.rs", "rank": 65, "score": 98211.16988909591 }, { "content": "#[test]\n\nfn uwriteln() {\n\n let mut s = String::new();\n\n uwriteln!(&mut s, \"Hello\").unwrap();\n\n uwriteln!(&mut s, \"World\",).unwrap();\n\n assert_eq!(s, \"Hello\\nWorld\\n\");\n\n}\n\n\n", "file_path": "ufmt/tests/vs-std-write.rs", "rank": 66, "score": 98211.16988909591 }, { "content": "#[test]\n\nfn core() {\n\n cmp!(\"{:?}\", None::<i32>);\n\n cmp!(\"{:#?}\", None::<i32>);\n\n\n\n cmp!(\"{:?}\", Some(0));\n\n cmp!(\"{:#?}\", Some(0));\n\n\n\n cmp!(\"{:?}\", Ok::<_, ()>(1));\n\n cmp!(\"{:#?}\", Ok::<_, ()>(1));\n\n\n\n cmp!(\"{:?}\", Err::<(), _>(2));\n\n cmp!(\"{:#?}\", Err::<(), _>(2));\n\n}\n\n\n", "file_path": "ufmt/tests/vs-std-write.rs", "rank": 67, "score": 98211.16988909591 }, { "content": "#[test]\n\nfn set() {\n\n fn x() -> BTreeSet<i32> {\n\n let mut m = BTreeSet::new();\n\n m.insert(1);\n\n m.insert(3);\n\n m\n\n }\n\n\n\n cmp!(\"{:?}\", BTreeSet::<()>::new());\n\n cmp!(\"{:?}\", x());\n\n\n\n cmp!(\"{:#?}\", BTreeSet::<()>::new());\n\n cmp!(\"{:#?}\", x());\n\n}\n\n\n", "file_path": "ufmt/tests/vs-std-write.rs", "rank": 68, "score": 98211.16988909591 }, { "content": "#[test]\n\nfn ixx() {\n\n // sanity check\n\n cmp!(\"{}\", 0i8);\n\n cmp!(\"{}\", 10i8);\n\n cmp!(\"{}\", 100i8);\n\n\n\n // extreme values\n\n cmp!(\"{}\", i8::min_value());\n\n cmp!(\"{}\", i8::max_value());\n\n cmp!(\"{}\", i16::min_value());\n\n cmp!(\"{}\", i16::max_value());\n\n cmp!(\"{}\", i32::min_value());\n\n cmp!(\"{}\", i32::max_value());\n\n cmp!(\"{}\", i64::min_value());\n\n cmp!(\"{}\", i64::max_value());\n\n cmp!(\"{}\", i128::min_value());\n\n cmp!(\"{}\", i128::max_value());\n\n cmp!(\"{}\", isize::min_value());\n\n cmp!(\"{}\", isize::max_value());\n\n}\n\n\n", "file_path": "ufmt/tests/vs-std-write.rs", "rank": 69, "score": 98211.16988909591 }, { "content": "#[test]\n\nfn dst() {\n\n #[allow(rust_2018_idioms)] // false positive?\n\n struct Cursor<B>\n\n where\n\n B: ?Sized,\n\n {\n\n pos: usize,\n\n buffer: B,\n\n }\n\n\n\n impl<B> Cursor<B> {\n\n fn new(buffer: B) -> Self {\n\n Cursor { pos: 0, buffer }\n\n }\n\n }\n\n\n\n impl uWrite for Cursor<[u8]> {\n\n type Error = Infallible;\n\n\n\n fn write_str(&mut self, s: &str) -> Result<(), Infallible> {\n", "file_path": "ufmt/tests/vs-std-write.rs", "rank": 70, "score": 98211.16988909591 }, { "content": "#[test]\n\nfn generic() {\n\n #[derive(uDebug, Debug)]\n\n struct X<T>(T);\n\n\n\n cmp!(\"{:?}\", X(0));\n\n\n\n #[derive(uDebug, Debug)]\n\n enum Y<T> {\n\n Z(T),\n\n }\n\n\n\n cmp!(\"{:?}\", Y::Z(0));\n\n}\n\n\n\n// compile-pass test\n", "file_path": "ufmt/tests/vs-std-write.rs", "rank": 71, "score": 98211.16988909591 }, { "content": "#[test]\n\nfn enum_() {\n\n #[derive(Debug, uDebug)]\n\n enum X {\n\n A,\n\n B(u8, u16),\n\n C { x: u8, y: u16 },\n\n }\n\n\n\n cmp!(\"{:?}\", X::A);\n\n cmp!(\"{:?}\", X::B(0, 1));\n\n cmp!(\"{:?}\", X::C { x: 0, y: 1 });\n\n\n\n cmp!(\"{:#?}\", X::A);\n\n cmp!(\"{:#?}\", X::B(0, 1));\n\n cmp!(\"{:#?}\", X::C { x: 0, y: 1 });\n\n}\n\n\n", "file_path": "ufmt/tests/vs-std-write.rs", "rank": 72, "score": 98211.16988909591 }, { "content": "#[test]\n\nfn tuples() {\n\n cmp!(\"{:?}\", ());\n\n cmp!(\"{:?}\", (1,));\n\n cmp!(\"{:?}\", (1, 2));\n\n cmp!(\"{:?}\", (1, 2, 3));\n\n cmp!(\"{:?}\", (1, 2, 3, 4));\n\n cmp!(\"{:?}\", (1, 2, 3, 4, 5));\n\n cmp!(\"{:?}\", (1, 2, 3, 4, 5, 6));\n\n cmp!(\"{:?}\", (1, 2, 3, 4, 5, 6, 7));\n\n cmp!(\"{:?}\", (1, 2, 3, 4, 5, 6, 7, 8));\n\n cmp!(\"{:?}\", (1, 2, 3, 4, 5, 6, 7, 8, 9));\n\n cmp!(\"{:?}\", (1, 2, 3, 4, 5, 6, 7, 8, 9, 10));\n\n cmp!(\"{:?}\", (1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11));\n\n cmp!(\"{:?}\", (1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12));\n\n\n\n cmp!(\"{:#?}\", ());\n\n cmp!(\"{:#?}\", (1,));\n\n cmp!(\"{:#?}\", (1, 2));\n\n}\n\n\n", "file_path": "ufmt/tests/vs-std-write.rs", "rank": 73, "score": 98211.16988909591 }, { "content": "#[test]\n\nfn recursion() {\n\n #[derive(uDebug, Debug)]\n\n struct Node {\n\n value: i32,\n\n next: Option<Box<Node>>,\n\n }\n\n\n\n fn x() -> Node {\n\n let tail = Node {\n\n value: 0,\n\n next: None,\n\n };\n\n Node {\n\n value: 1,\n\n next: Some(Box::new(tail)),\n\n }\n\n }\n\n\n\n cmp!(\"{:?}\", x());\n\n cmp!(\"{:#?}\", x());\n\n}\n\n\n", "file_path": "ufmt/tests/vs-std-write.rs", "rank": 74, "score": 98211.16988909591 }, { "content": "#[test]\n\nfn formatter_uwrite() {\n\n #[derive(uDebug)]\n\n struct X;\n\n\n\n struct Y;\n\n\n\n impl uDebug for Y {\n\n fn fmt<W>(&self, f: &mut Formatter<'_, W>) -> Result<(), W::Error>\n\n where\n\n W: uWrite + ?Sized,\n\n {\n\n uwrite!(f, \"{:?}\", X)\n\n }\n\n }\n\n\n\n assert_eq!(uformat!(\"{:?}\", Y).unwrap(), \"X\")\n\n}\n\n\n", "file_path": "ufmt/tests/vs-std-write.rs", "rank": 75, "score": 95933.44601782714 }, { "content": "fn poll<F: Future>(pinned_future: Pin<&mut F>) -> Poll<F::Output> {\n\n let waker = unsafe { Waker::from_raw(get_dummy_waker()) };\n\n let mut context = Context::from_waker(&waker);\n\n pinned_future.poll(&mut context)\n\n}\n\n\n", "file_path": "src/executor.rs", "rank": 76, "score": 93334.65658062579 }, { "content": "fn get_current_ticks() -> TockResult<usize> {\n\n syscalls::command(DRIVER_NUMBER, command_nr::GET_CLOCK_VALUE, 0, 0).map_err(|err| err.into())\n\n}\n", "file_path": "src/timer.rs", "rank": 77, "score": 90450.8660097265 }, { "content": "fn get_clock_frequency() -> TockResult<usize> {\n\n syscalls::command(DRIVER_NUMBER, command_nr::GET_CLOCK_FREQUENCY, 0, 0)\n\n .map_err(|err| err.into())\n\n}\n\n\n", "file_path": "src/timer.rs", "rank": 78, "score": 90450.8660097265 }, { "content": "fn stop_alarm_at(instant: usize) -> TockResult<()> {\n\n match syscalls::command(DRIVER_NUMBER, command_nr::STOP_ALARM, instant, 0) {\n\n Ok(_) => Ok(()),\n\n Err(error) => match error.return_code {\n\n EALREADY => Ok(()),\n\n _ => Err(TockError::Command(error)),\n\n },\n\n }\n\n}\n\n\n", "file_path": "src/timer.rs", "rank": 79, "score": 89092.95942787723 }, { "content": "fn set_alarm_at(instant: usize) -> TockResult<()> {\n\n syscalls::command(DRIVER_NUMBER, command_nr::SET_ALARM, instant, 0)\n\n .map(|_| ())\n\n .map_err(|err| err.into())\n\n}\n\n\n", "file_path": "src/timer.rs", "rank": 80, "score": 89092.95942787723 }, { "content": "fn mk_ident(i: usize) -> Ident {\n\n Ident::new(&format!(\"__{}\", i), Span::call_site())\n\n}\n\n\n", "file_path": "ufmt/macros/src/lib.rs", "rank": 81, "score": 89092.95942787723 }, { "content": "// `}}` -> `}`\n\nfn unescape<'l>(mut literal: &'l str, span: Span) -> parse::Result<Cow<'l, str>> {\n\n if literal.contains('}') {\n\n let mut buf = String::new();\n\n\n\n while literal.contains('}') {\n\n const ERR: &str = \"format string contains an unmatched right brace\";\n\n let mut parts = literal.splitn(2, '}');\n\n\n\n match (parts.next(), parts.next()) {\n\n (Some(left), Some(right)) => {\n\n const ESCAPED_BRACE: &str = \"}\";\n\n\n\n if right.starts_with(ESCAPED_BRACE) {\n\n buf.push_str(left);\n\n buf.push('}');\n\n\n\n literal = &right[ESCAPED_BRACE.len()..];\n\n } else {\n\n return Err(parse::Error::new(span, ERR));\n\n }\n", "file_path": "ufmt/macros/src/lib.rs", "rank": 82, "score": 87772.84663674218 }, { "content": "fn parse<'l>(mut literal: &'l str, span: Span) -> parse::Result<Vec<Piece<'l>>> {\n\n let mut pieces = vec![];\n\n\n\n let mut buf = String::new();\n\n loop {\n\n let mut parts = literal.splitn(2, '{');\n\n match (parts.next(), parts.next()) {\n\n // empty string literal\n\n (None, None) => break,\n\n\n\n // end of the string literal\n\n (Some(s), None) => {\n\n if buf.is_empty() {\n\n if !s.is_empty() {\n\n pieces.push(Piece::Str(unescape(s, span)?));\n\n }\n\n } else {\n\n buf.push_str(&unescape(s, span)?);\n\n\n\n pieces.push(Piece::Str(Cow::Owned(buf)));\n", "file_path": "ufmt/macros/src/lib.rs", "rank": 83, "score": 87772.84663674218 }, { "content": "struct Callback;\n\n\n", "file_path": "src/timer.rs", "rank": 84, "score": 72550.48989833565 }, { "content": "struct PrettyTime {\n\n mins: usize,\n\n secs: usize,\n\n ms: usize,\n\n}\n\n\n\nimpl PrettyTime {\n\n fn from_ms(ms: usize) -> PrettyTime {\n\n PrettyTime {\n\n ms: ms % 1000,\n\n secs: (ms / 1000) % 60,\n\n mins: ms / (60 * 1000),\n\n }\n\n }\n\n}\n\n\n\nimpl core::fmt::Display for PrettyTime {\n\n fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {\n\n if self.mins != 0 {\n\n write!(f, \"{}m\", self.mins)?\n\n }\n\n write!(f, \"{}.{:03}s\", self.secs, self.ms)\n\n }\n\n}\n", "file_path": "examples/timer.rs", "rank": 85, "score": 71148.70644114655 }, { "content": "#[derive(Default)]\n\nstruct CbData {\n\n res: Cell<NinedofReading>,\n\n ready: Cell<bool>,\n\n}\n\n\n\nimpl NinedofDriver {\n\n pub fn read_acceleration(&mut self) -> TockResult<NinedofReading> {\n\n let res: CbData = Default::default();\n\n subscribe(Self::cb, unsafe { mem::transmute(&res) })?;\n\n start_accel_reading()?;\n\n unsafe { executor::block_on(futures::wait_until(|| res.ready.get())) };\n\n Ok(res.res.get())\n\n }\n\n\n\n pub fn read_magnetometer(&mut self) -> TockResult<NinedofReading> {\n\n let res: CbData = Default::default();\n\n subscribe(Self::cb, unsafe { mem::transmute(&res) })?;\n\n start_magnetometer_reading()?;\n\n unsafe { executor::block_on(futures::wait_until(|| res.ready.get())) };\n\n Ok(res.res.get())\n", "file_path": "src/sensors/ninedof.rs", "rank": 86, "score": 69839.21782410031 }, { "content": "struct HmacEventConsumer;\n\n\n\nimpl<CB: FnMut(usize, usize)> Consumer<CB> for HmacEventConsumer {\n\n fn consume(callback: &mut CB, result: usize, digest: usize, _: usize) {\n\n callback(result, digest);\n\n }\n\n}\n\n\n\npub struct HmacKeyBuffer {\n\n buffer: [u8; KEY_BUFFER_SIZE],\n\n}\n\n\n\nimpl Default for HmacKeyBuffer {\n\n fn default() -> Self {\n\n HmacKeyBuffer {\n\n buffer: [0; KEY_BUFFER_SIZE],\n\n }\n\n }\n\n}\n\n\n", "file_path": "src/hmac.rs", "rank": 87, "score": 69839.21782410031 }, { "content": "struct TimerEventConsumer;\n\n\n\nimpl<CB: FnMut(ClockValue, Alarm)> Consumer<WithCallback<'_, CB>> for TimerEventConsumer {\n\n fn consume(data: &mut WithCallback<CB>, clock_value: usize, alarm_id: usize, _: usize) {\n\n (data.callback)(\n\n ClockValue {\n\n num_ticks: clock_value as isize,\n\n clock_frequency: data.clock_frequency,\n\n },\n\n Alarm { alarm_id },\n\n );\n\n }\n\n}\n\n\n\nimpl<'a, CB: FnMut(ClockValue, Alarm)> WithCallback<'a, CB> {\n\n pub fn init(&'a mut self) -> TockResult<Timer<'a>> {\n\n let num_notifications =\n\n syscalls::command(DRIVER_NUMBER, command_nr::IS_DRIVER_AVAILABLE, 0, 0)?;\n\n\n\n let clock_frequency =\n", "file_path": "src/timer.rs", "rank": 88, "score": 69839.21782410031 }, { "content": "struct GpioEventConsumer;\n\n\n\nimpl<CB: Fn(usize, GpioState)> Consumer<CB> for GpioEventConsumer {\n\n fn consume(callback: &mut CB, gpio_num: usize, gpio_state: usize, _: usize) {\n\n let gpio_state = match gpio_state {\n\n 0 => GpioState::Low,\n\n 1 => GpioState::High,\n\n _ => return,\n\n };\n\n callback(gpio_num, gpio_state);\n\n }\n\n}\n\n\n\n#[derive(Copy, Clone, Debug, Eq, PartialEq)]\n\npub enum GpioState {\n\n Low,\n\n High,\n\n}\n\n\n\nimpl From<GpioState> for bool {\n", "file_path": "src/gpio.rs", "rank": 89, "score": 69839.21782410031 }, { "content": "struct Input {\n\n formatter: Expr,\n\n _comma: Token![,],\n\n literal: LitStr,\n\n _comma2: Option<Token![,]>,\n\n args: Punctuated<Expr, Token![,]>,\n\n}\n\n\n\nimpl Parse for Input {\n\n fn parse(input: ParseStream) -> parse::Result<Self> {\n\n let formatter = input.parse()?;\n\n let _comma = input.parse()?;\n\n let literal = input.parse()?;\n\n\n\n if input.is_empty() {\n\n Ok(Input {\n\n formatter,\n\n _comma,\n\n literal,\n\n _comma2: None,\n", "file_path": "ufmt/macros/src/lib.rs", "rank": 90, "score": 69839.21782410031 }, { "content": "struct ButtonsEventConsumer;\n\n\n\nimpl<CB: Fn(usize, ButtonState)> Consumer<CB> for ButtonsEventConsumer {\n\n fn consume(callback: &mut CB, button_num: usize, button_state: usize, _: usize) {\n\n let button_state = match button_state {\n\n 0 => ButtonState::Released,\n\n 1 => ButtonState::Pressed,\n\n _ => return,\n\n };\n\n callback(button_num, button_state);\n\n }\n\n}\n\n\n\npub struct Buttons<'a> {\n\n num_buttons: usize,\n\n curr_button: usize,\n\n lifetime: PhantomData<&'a ()>,\n\n}\n\n\n\nimpl<'a> Iterator for Buttons<'a> {\n", "file_path": "src/buttons.rs", "rank": 91, "score": 69839.21782410031 }, { "content": "struct TockAllocator;\n\n\n\nunsafe impl GlobalAlloc for TockAllocator {\n\n unsafe fn alloc(&self, layout: Layout) -> *mut u8 {\n\n HEAP.allocate_first_fit(layout)\n\n .ok()\n\n .map_or(ptr::null_mut(), NonNull::as_ptr)\n\n }\n\n\n\n unsafe fn dealloc(&self, ptr: *mut u8, layout: Layout) {\n\n HEAP.deallocate(NonNull::new_unchecked(ptr), layout)\n\n }\n\n}\n\n\n\n#[global_allocator]\n\nstatic ALLOCATOR: TockAllocator = TockAllocator;\n\n\n\n#[cfg(not(feature = \"custom_alloc_error_handler\"))]\n\n#[alloc_error_handler]\n\nunsafe fn alloc_error_handler(_: Layout) -> ! {\n", "file_path": "core/src/alloc.rs", "rank": 92, "score": 69839.21782410031 }, { "content": "struct AdcEventConsumer;\n\n\n\nimpl<CB: FnMut(usize, usize)> Consumer<CB> for AdcEventConsumer {\n\n fn consume(data: &mut CB, _: usize, channel: usize, value: usize) {\n\n data(channel, value);\n\n }\n\n}\n\n\n\nimpl<'a> Adc<'a> {\n\n pub fn init_buffer(&self, buffer: &'a mut AdcBuffer) -> TockResult<SharedMemory> {\n\n syscalls::allow(DRIVER_NUMBER, allow_nr::BUFFER, &mut buffer.buffer).map_err(Into::into)\n\n }\n\n\n\n pub fn init_alt_buffer(&self, alt_buffer: &'a mut AdcBuffer) -> TockResult<SharedMemory> {\n\n syscalls::allow(DRIVER_NUMBER, allow_nr::BUFFER_ALT, &mut alt_buffer.buffer)\n\n .map_err(Into::into)\n\n }\n\n\n\n /// Return the number of available channels\n\n pub fn count(&self) -> usize {\n", "file_path": "src/adc.rs", "rank": 93, "score": 69839.21782410031 }, { "content": "// Indicates the toolchain in the build config is unavailable.\n\nstruct ToolchainUnavailable;\n\n\n", "file_path": "runtime/extern_asm.rs", "rank": 94, "score": 69839.21782410031 }, { "content": "struct ParallelTimerConsumer;\n\n\n\nimpl<'a> Consumer<Callback> for ParallelTimerConsumer {\n\n fn consume(_: &mut Callback, _: usize, _: usize, _: usize) {}\n\n}\n\n\n\n/// Activated time driver. Updates current time in the context and manages\n\n/// active alarms.\n\n/// Example usage (sleep for 1 second):\n\n/// ```no_run\n\n/// # use libtock::result::TockResult;\n\n/// # use libtock::timer::Duration;\n\n/// # async fn doc() -> TockResult<()> {\n\n/// # let mut drivers = libtock::retrieve_drivers()?;\n\n/// # let mut timer_driver = drivers.timer.create_timer_driver();\n\n/// let timer_driver = timer_driver.activate()?;\n\n/// timer_driver.sleep(Duration::from_ms(1000)).await?;\n\n/// # Ok(())\n\n/// # }\n\n/// ```\n", "file_path": "src/timer.rs", "rank": 95, "score": 69839.21782410031 }, { "content": "struct CtapEventConsumer;\n\n\n\nimpl<CB: FnMut(usize, usize)> Consumer<CB> for CtapEventConsumer {\n\n fn consume(callback: &mut CB, sent: usize, _: usize, _: usize) {\n\n callback(sent, 0);\n\n }\n\n}\n\n\n\npub struct CtapRecvBuffer {\n\n buffer: [u8; RECV_BUFFER_SIZE],\n\n}\n\n\n\nimpl Default for CtapRecvBuffer {\n\n fn default() -> Self {\n\n CtapRecvBuffer {\n\n buffer: [0; RECV_BUFFER_SIZE],\n\n }\n\n }\n\n}\n\n\n", "file_path": "src/ctap.rs", "rank": 96, "score": 69839.21782410031 }, { "content": "#[derive(Eq, PartialEq, PartialOrd, Ord)]\n\nstruct Example {\n\n name: String,\n\n arch: &'static str,\n\n path: std::path::PathBuf,\n\n}\n\n\n", "file_path": "tools/print_sizes/src/main.rs", "rank": 97, "score": 68613.19938127112 }, { "content": "#[derive(Serialize)]\n\nstruct LedCommand {\n\n pub nr: u8,\n\n pub st: bool,\n\n}\n\n\n\n#[libtock::main]\n\nasync fn main() -> TockResult<()> {\n\n let mut drivers = libtock::retrieve_drivers()?;\n\n let leds_driver = drivers.leds.init_driver()?;\n\n let mut timer_driver = drivers.timer.create_timer_driver();\n\n let timer_driver = timer_driver.activate()?;\n\n let mut ble_advertising_driver = drivers.ble_advertising.create_driver();\n\n\n\n let led = leds_driver.leds().next().unwrap();\n\n\n\n let uuid: [u8; 2] = [0x00, 0x18];\n\n\n\n let payload = corepack::to_bytes(LedCommand { nr: 2, st: true }).unwrap();\n\n\n\n let mut buffer = BleAdvertisingDriver::create_advertising_buffer();\n", "file_path": "examples-features/simple_ble.rs", "rank": 98, "score": 68613.19938127112 }, { "content": "#[derive(Deserialize)]\n\nstruct LedCommand {\n\n pub nr: u8,\n\n pub st: bool,\n\n}\n\n\n\n#[libtock::main]\n\nasync fn main() -> TockResult<()> {\n\n let mut drivers = libtock::retrieve_drivers()?;\n\n let leds_driver = drivers.leds.init_driver()?;\n\n\n\n let mut ble_scanning_driver_factory = drivers.ble_scanning;\n\n let mut ble_scanning_driver = ble_scanning_driver_factory.create_driver();\n\n let mut ble_scanning_driver_sharing = ble_scanning_driver.share_memory()?;\n\n let ble_scanning_driver_scanning = ble_scanning_driver_sharing.start()?;\n\n\n\n loop {\n\n let value = ble_scanning_driver_scanning.stream_values().await;\n\n ble_parser::find(&value, simple_ble::gap_data::SERVICE_DATA as u8)\n\n .and_then(|service_data| ble_parser::extract_for_service([91, 79], service_data))\n\n .and_then(|payload| corepack::from_bytes::<LedCommand>(&payload).ok())\n\n .and_then(|msg| leds_driver.get(msg.nr as usize).ok())\n\n .and_then(|led| led.on().ok());\n\n }\n\n}\n", "file_path": "examples-features/ble_scanning.rs", "rank": 99, "score": 68613.19938127112 } ]
Rust
src/run/parser/portal2_live_timer.rs
AntyMew/livesplit-core
b59a45ddd85c914121d279df38ad5b0e581bd512
use std::io::{self, BufRead}; use std::result::Result as StdResult; use std::num::ParseFloatError; use {GameTime, Run, Segment, TimeSpan}; quick_error! { #[derive(Debug)] pub enum Error { ExpectedMap {} ExpectedMapName {} ExpectedDifferentMapName {} ExpectedStartTicks {} ExpectedEndTicks {} Ticks(err: ParseFloatError) { from() } Io(err: io::Error) { from() } } } pub type Result<T> = StdResult<T, Error>; static CHAPTERS: [(&str, &[&str]); 9] = [ ( "Chapter 1 - The Courtesy Call", &[ "sp_a1_intro1", "sp_a1_intro2", "sp_a1_intro3", "sp_a1_intro4", "sp_a1_intro5", "sp_a1_intro6", "sp_a1_intro7", "sp_a1_wakeup", "sp_a2_intro", ], ), ( "Chapter 2 - The Cold Boot", &[ "sp_a2_laser_intro", "sp_a2_laser_stairs", "sp_a2_dual_lasers", "sp_a2_laser_over_goo", "sp_a2_catapult_intro", "sp_a2_trust_fling", "sp_a2_pit_flings", "sp_a2_fizzler_intro", ], ), ( "Chapter 3 - The Return", &[ "sp_a2_sphere_peek", "sp_a2_ricochet", "sp_a2_bridge_intro", "sp_a2_bridge_the_gap", "sp_a2_laser_relays", "sp_a2_turret_intro", "sp_a2_turret_blocker", "sp_a2_laser_vs_turret", "sp_a2_pull_the_rug", ], ), ( "Chapter 4 - The Surprise", &[ "sp_a2_column_blocker", "sp_a2_laser_chaining", "sp_a2_triple_laser", "sp_a2_bts1", "sp_a2_bts2", ], ), ( "Chapter 5 - The Escape", &[ "sp_a2_bts3", "sp_a2_bts4", "sp_a2_bts5", "sp_a2_bts6", "sp_a2_core", ], ), ( "Chapter 6 - The Fall", &[ "sp_a3_00", "sp_a3_01", "sp_a3_03", "sp_a3_jump_intro", "sp_a3_bomb_flings", "sp_a3_crazy_box", "sp_a3_transition01", ], ), ( "Chapter 7 - The Reunion", &[ "sp_a3_speed_ramp", "sp_a3_speed_flings", "sp_a3_speed_flings", "sp_a3_speed_flings", "sp_a3_portal_intro", "sp_a3_end", ], ), ( "Chapter 8 - The Itch", &[ "sp_a4_intro", "sp_a4_tb_intro", "sp_a4_tb_trust_drop", "sp_a4_tb_wall_button", "sp_a4_tb_polarity", "sp_a4_tb_catch", "sp_a4_stop_the_box", "sp_a4_laser_catapult", "sp_a4_laser_platform", "sp_a4_speed_tb_catch", "sp_a4_jump_polarity", "sp_a4_jump_polarity", ], ), ( "Chapter 9 - The Part Where...", &[ "sp_a4_finale1", "sp_a4_finale2", "sp_a4_finale3", "sp_a4_finale4", ], ), ]; pub fn parse<R: BufRead>(source: R) -> Result<Run> { let mut run = Run::new(); run.set_game_name("Portal 2"); run.set_category_name("Any%"); let mut lines = source.lines().peekable(); lines.next(); let mut aggregate_ticks = 0.0; for &(chapter_name, maps) in &CHAPTERS { for &map in maps { let line = lines.next().ok_or(Error::ExpectedMap)??; let mut splits = line.split(','); let map_name = splits.next().ok_or(Error::ExpectedMapName)?; if map_name != map { return Err(Error::ExpectedDifferentMapName); } let start_ticks: f64 = splits.next().ok_or(Error::ExpectedStartTicks)?.parse()?; let end_ticks: f64 = splits.next().ok_or(Error::ExpectedEndTicks)?.parse()?; let map_ticks = end_ticks - start_ticks; aggregate_ticks += map_ticks; } let time = GameTime(Some(TimeSpan::from_seconds(aggregate_ticks / 60.0))).into(); let mut segment = Segment::new(chapter_name); segment.set_personal_best_split_time(time); run.push_segment(segment); } Ok(run) }
use std::io::{self, BufRead}; use std::result::Result as StdResult; use std::num::ParseFloatError; use {GameTime, Run, Segment, TimeSpan}; quick_error! { #[derive(Debug)] pub enum Error { ExpectedMap {} ExpectedMapName {} ExpectedDifferentMapName {} ExpectedStartTicks {} ExpectedEndTicks {} Ticks(err: ParseFloatError) { from() } Io(err: io::Error) { from() } } } pub type Result<T> = StdResult<T, Error>; static CHAPTERS: [(&str, &[&str]); 9] = [ ( "Chapter 1 - The Courtesy Call", &[ "sp_a1_intro1", "sp_a1_intro2", "sp_a1_intro3", "sp_a1_intro4", "sp_a1_intro5", "sp_a1_intro6", "sp_a1_intro7", "sp_a1_wakeup", "sp_a2_intro", ], ), ( "Chapter 2 - The Cold Boot", &[ "sp_a2_laser_intro", "sp_a2_laser_stairs", "sp_a2_dual_lasers", "sp_a2_laser_over_goo", "sp_a2_catapult_intro", "sp_a2_trust_fling", "sp_a2_pit_flings", "sp_a2_fizzler_intro", ], ), ( "Chapter 3 - The Return", &[ "sp_a2_sphere_peek", "sp_a2_ricochet", "sp_a2_bridge_intro", "sp_a2_bridge_the_gap", "sp_a2_laser_relays", "sp_a2_turret_intro", "sp_a2_turret_blocker", "sp_a2_laser_vs_turret", "sp_a2_pull_the_rug", ], ), ( "Chapter 4 - The Surprise", &[ "sp_a2_column_blocker", "sp_a2_laser_chaining", "sp_a2_triple_laser", "sp_a2_bts1", "sp_a2_bts2", ], ), ( "Chapter 5 - The Escape", &[ "sp_a2_bts3", "sp_a2_bts4", "sp_a2_bts5", "sp_a2_bts6", "sp_a2_core", ], ), ( "Chapter 6 - The Fall", &[ "sp_a3_00", "sp_a3_01", "sp_a3_03", "sp_a3_jump_intro", "sp_a3_bomb_flings", "sp_a3_crazy_box", "sp_a3_transition01", ], ), ( "Chapter 7 - The Reunion", &[ "sp_a3_speed_ramp", "sp_a3_speed_flings", "sp_a3_speed_flings", "sp_a3_speed_flings", "sp_a3_portal_intro", "sp_a3_end", ], ), ( "Chapter 8 - The Itch", &[ "sp_a4_intro", "sp_a4_tb_intro", "sp_a4_tb_trust_drop", "sp_a4_tb_wall_button", "sp_a4_tb_polarity", "sp_a4_tb_catch", "sp_a4_stop_the_box", "sp_a4_laser_catapult", "sp_a4_laser_platform", "sp_a4_speed_tb_catch", "sp_a4_jump_polarity", "sp_a4_jump_polarity", ], ), ( "Chapter 9 - The Part Where...", &[ "sp_a4_finale1", "sp_a4_finale2", "sp_a4_finale3", "sp_a4_finale4", ], ), ]; pub fn parse<R: BufRead>(source: R) -> Result<Run> { let mut run = Run::new(); run.set_game_name("Portal 2"); run.set_category_name("Any%"); let mut lines = source.lines().peekable(); lines.next(); let mut aggregate_ticks = 0.0; for &(chapter_name, maps) in &CHAPTERS { for &map in maps { let line = lines.next().ok_or(Error::ExpectedMap)??; let mut splits = line.split(','); let map_name = s
plits.next().ok_or(Error::ExpectedMapName)?; if map_name != map { return Err(Error::ExpectedDifferentMapName); } let start_ticks: f64 = splits.next().ok_or(Error::ExpectedStartTicks)?.parse()?; let end_ticks: f64 = splits.next().ok_or(Error::ExpectedEndTicks)?.parse()?; let map_ticks = end_ticks - start_ticks; aggregate_ticks += map_ticks; } let time = GameTime(Some(TimeSpan::from_seconds(aggregate_ticks / 60.0))).into(); let mut segment = Segment::new(chapter_name); segment.set_personal_best_split_time(time); run.push_segment(segment); } Ok(run) }
function_block-function_prefixed
[ { "content": "/// Attempts to parse a ShitSplit splits file.\n\npub fn parse<R: BufRead>(source: R) -> Result<Run> {\n\n let mut run = Run::new();\n\n\n\n let mut lines = source.lines();\n\n\n\n let line = lines.next().ok_or(Error::Empty)??;\n\n let mut splits = line.split('|');\n\n let category_name = splits.next().ok_or(Error::ExpectedCategoryName)?;\n\n if !category_name.starts_with('#') {\n\n return Err(Error::ExpectedCategoryName);\n\n }\n\n run.set_category_name(&category_name[1..]);\n\n run.set_attempt_count(splits.next().ok_or(Error::ExpectedAttemptCount)?.parse()?);\n\n let mut total_time = TimeSpan::zero();\n\n let mut next_line = lines.next();\n\n while let Some(line) = next_line {\n\n let line = line?;\n\n if line.is_empty() {\n\n break;\n\n }\n", "file_path": "src/run/parser/shit_split.rs", "rank": 0, "score": 406131.28029111156 }, { "content": "/// Attempts to parse a Llanfair splits file.\n\npub fn parse<R: Read + Seek>(mut source: R) -> Result<Run> {\n\n let mut buf = Vec::new();\n\n let mut buf2 = Vec::new();\n\n\n\n // The protocol is documented here:\n\n // https://docs.oracle.com/javase/7/docs/platform/serialization/spec/protocol.html\n\n\n\n const HEADER: [u8; 30] = [\n\n 0xAC, 0xED, // Magic\n\n 0x00, 0x05, // Version\n\n 0x73, // New Object\n\n 0x72, // New Class Declaration\n\n 0x00, 0x16, // Length of Class Name\n\n // org.fenix.llanfair.Run\n\n 0x6F, 0x72, 0x67, 0x2E, 0x66, 0x65, 0x6E, 0x69, 0x78, 0x2E, 0x6C,\n\n 0x6C, 0x61, 0x6E, 0x66, 0x61, 0x69, 0x72, 0x2E, 0x52, 0x75, 0x6E,\n\n ];\n\n let mut header_buf = [0; 30];\n\n source.read_exact(&mut header_buf)?;\n\n if HEADER != header_buf {\n", "file_path": "src/run/parser/llanfair.rs", "rank": 1, "score": 395260.7945296408 }, { "content": "/// Attempts to parse a FaceSplit splits file. In addition to the source to\n\n/// parse, you need to specify if additional files for the icons should be\n\n/// loaded from the file system. If you are using livesplit-core in a\n\n/// server-like environment, set this to `false`. Only client-side applications\n\n/// should set this to `true`.\n\npub fn parse<R: BufRead>(source: R, load_icons: bool) -> Result<Run> {\n\n let mut run = Run::new();\n\n let mut icon_buf = Vec::new();\n\n let mut lines = source.lines();\n\n\n\n run.set_category_name(lines.next().ok_or(Error::ExpectedTitle)??);\n\n lines.next(); // TODO Store Goal\n\n run.set_attempt_count(lines.next().ok_or(Error::ExpectedAttemptCount)??.parse()?);\n\n lines.next(); // TODO Store runs completed somehow\n\n\n\n for line in lines {\n\n let line = line?;\n\n let mut splits = line.splitn(5, '-');\n\n\n\n let segment_name = replace(\n\n splits.next().ok_or(Error::ExpectedSegmentName)?,\n\n r#\"\"?\"\"#,\n\n \"-\",\n\n );\n\n let mut segment = Segment::new(segment_name);\n", "file_path": "src/run/parser/face_split.rs", "rank": 2, "score": 384368.0084616477 }, { "content": "pub fn end_tag<R: BufRead>(reader: &mut Reader<R>, buf: &mut Vec<u8>) -> Result<()> {\n\n let mut depth = 0;\n\n loop {\n\n buf.clear();\n\n match reader.read_event(buf)? {\n\n Event::Start(_) => {\n\n depth += 1;\n\n }\n\n Event::End(_) => {\n\n if depth == 0 {\n\n return Ok(());\n\n }\n\n depth -= 1;\n\n }\n\n Event::Eof => return Err(Error::UnexpectedEndOfFile),\n\n _ => {}\n\n }\n\n }\n\n}\n\n\n", "file_path": "src/run/parser/xml_util.rs", "rank": 3, "score": 370383.9671795637 }, { "content": "/// Attempts to parse a splits file used by the Llanfair Rewrite.\n\npub fn parse<R: BufRead>(source: R) -> Result<Run> {\n\n let reader = &mut Reader::from_reader(source);\n\n reader.expand_empty_elements(true);\n\n reader.trim_text(true);\n\n\n\n let mut buf = Vec::with_capacity(4096);\n\n let mut image_buf = Vec::with_capacity(4096);\n\n\n\n let mut run = Run::new();\n\n\n\n parse_base(reader, &mut buf, b\"run\", |reader, tag| {\n\n parse_children(reader, tag.into_buf(), |reader, tag| {\n\n if tag.name() == b\"game\" {\n\n text(reader, tag.into_buf(), |t| run.set_game_name(t))\n\n } else if tag.name() == b\"category\" {\n\n text(reader, tag.into_buf(), |t| run.set_category_name(t))\n\n } else if tag.name() == b\"platform\" {\n\n text(reader, tag.into_buf(), |t| {\n\n run.metadata_mut().set_platform_name(t)\n\n })\n", "file_path": "src/run/parser/llanfair2.rs", "rank": 4, "score": 369044.25932902587 }, { "content": "/// Attempts to parse a Time Split Tracker splits file. In addition to the\n\n/// source to parse, you can specify the path of the splits file, which is then\n\n/// use to load the run log file from the file system. This is entirely\n\n/// optional. If you are using livesplit-core in a server-like environment, set\n\n/// this to `None`. Only client-side applications should provide the path here.\n\npub fn parse<R: BufRead>(source: R, path_for_loading_other_files: Option<PathBuf>) -> Result<Run> {\n\n let mut run = Run::new();\n\n let mut buf = Vec::new();\n\n let path = path_for_loading_other_files;\n\n\n\n let mut lines = source.lines();\n\n\n\n let line = lines.next().ok_or(Error::Empty)??;\n\n let mut splits = line.split('\\t');\n\n run.set_attempt_count(splits.next().ok_or(Error::ExpectedAttemptCount)?.parse()?);\n\n run.set_offset(splits.next().ok_or(Error::ExpectedOffset)?.parse()?);\n\n\n\n catch! {\n\n let path = path.as_ref()?.with_file_name(splits.next()?);\n\n let image = Image::from_file(path, &mut buf).ok()?;\n\n run.set_game_icon(image);\n\n };\n\n\n\n let line = lines.next().ok_or(Error::ExpectedTitleLine)??;\n\n let mut splits = line.split('\\t');\n", "file_path": "src/run/parser/time_split_tracker.rs", "rank": 5, "score": 365813.4060894018 }, { "content": "/// Attempts to parse a splits file used by Gered's Llanfair fork.\n\npub fn parse<R: BufRead>(source: R) -> Result<Run> {\n\n let reader = &mut Reader::from_reader(source);\n\n reader.expand_empty_elements(true);\n\n reader.trim_text(true);\n\n\n\n let mut buf = Vec::with_capacity(4096);\n\n let mut buf2 = Vec::with_capacity(4096);\n\n\n\n let mut run = Run::new();\n\n\n\n parse_base(reader, &mut buf, b\"Run\", |reader, tag| {\n\n single_child(reader, tag.into_buf(), b\"Run\", |reader, tag| {\n\n single_child(reader, tag.into_buf(), b\"default\", |reader, tag| {\n\n parse_children(reader, tag.into_buf(), |reader, tag| {\n\n if tag.name() == b\"name\" {\n\n text(reader, tag.into_buf(), |t| run.set_game_name(t))\n\n } else if tag.name() == b\"subTitle\" {\n\n text(reader, tag.into_buf(), |t| run.set_category_name(t))\n\n } else if tag.name() == b\"delayedStart\" {\n\n time_span(reader, tag.into_buf(), |t| {\n", "file_path": "src/run/parser/llanfair_gered.rs", "rank": 6, "score": 365617.52582715993 }, { "content": "/// Attempts to parse a WSplit splits file. In addition to the source to parse,\n\n/// you need to specify if additional files for the icons should be loaded from\n\n/// the file system. If you are using livesplit-core in a server-like\n\n/// environment, set this to `false`. Only client-side applications should set\n\n/// this to `true`.\n\npub fn parse<R: BufRead>(source: R, load_icons: bool) -> Result<Run> {\n\n let mut run = Run::new();\n\n let mut icon_buf = Vec::new();\n\n let mut icons_list = Vec::new();\n\n let mut old_run_exists = false;\n\n let mut goal = None;\n\n\n\n for line in source.lines() {\n\n let line = line?;\n\n if !line.is_empty() {\n\n if line.starts_with(\"Title=\") {\n\n run.set_category_name(&line[\"Title=\".len()..]);\n\n } else if line.starts_with(\"Attempts=\") {\n\n run.set_attempt_count(line[\"Attempts=\".len()..].parse()?);\n\n } else if line.starts_with(\"Offset=\") {\n\n let offset = &line[\"Offset=\".len()..];\n\n if !offset.is_empty() {\n\n run.set_offset(TimeSpan::from_milliseconds(-offset.parse::<f64>()?));\n\n }\n\n } else if line.starts_with(\"Size=\") {\n", "file_path": "src/run/parser/wsplit.rs", "rank": 8, "score": 349049.4223232381 }, { "content": "/// Attempts to parse a SplitterZ splits file. In addition to the source to\n\n/// parse, you need to specify if additional files for the icons should be\n\n/// loaded from the file system. If you are using livesplit-core in a\n\n/// server-like environment, set this to `false`. Only client-side applications\n\n/// should set this to `true`.\n\npub fn parse<R: BufRead>(source: R, load_icons: bool) -> Result<Run> {\n\n let mut run = Run::new();\n\n\n\n let mut icon_buf = Vec::new();\n\n\n\n let mut lines = source.lines();\n\n let line = lines.next().ok_or(Error::Empty)??;\n\n let mut splits = line.split(',');\n\n // Title Stuff here, do later\n\n run.set_category_name(unescape(splits.next().ok_or(Error::ExpectedCategoryName)?));\n\n run.set_attempt_count(splits.next().ok_or(Error::ExpectedAttemptCount)?.parse()?);\n\n\n\n for line in lines {\n\n let line = line?;\n\n if !line.is_empty() {\n\n let mut splits = line.split(',');\n\n\n\n let mut segment =\n\n Segment::new(unescape(splits.next().ok_or(Error::ExpectedSegmentName)?));\n\n\n", "file_path": "src/run/parser/splitterz.rs", "rank": 9, "score": 349048.37022025493 }, { "content": "pub fn parse_children<R, F>(reader: &mut Reader<R>, buf: &mut Vec<u8>, mut f: F) -> Result<()>\n\nwhere\n\n R: BufRead,\n\n F: FnMut(&mut Reader<R>, Tag) -> Result<()>,\n\n{\n\n unsafe {\n\n let ptr_buf: *mut Vec<u8> = buf;\n\n loop {\n\n buf.clear();\n\n match reader.read_event(buf)? {\n\n Event::Start(start) => {\n\n let tag = Tag::new(start, ptr_buf);\n\n f(reader, tag)?;\n\n }\n\n Event::End(_) => return Ok(()),\n\n Event::Eof => return Err(Error::UnexpectedEndOfFile),\n\n _ => {}\n\n }\n\n }\n\n }\n\n}\n\n\n", "file_path": "src/run/parser/xml_util.rs", "rank": 10, "score": 347472.4843738981 }, { "content": "pub fn text<R, F>(reader: &mut Reader<R>, buf: &mut Vec<u8>, f: F) -> Result<()>\n\nwhere\n\n R: BufRead,\n\n F: FnOnce(Cow<str>),\n\n{\n\n text_err(reader, buf, |t| {\n\n f(t);\n\n Ok(())\n\n })\n\n}\n\n\n", "file_path": "src/run/parser/xml_util.rs", "rank": 11, "score": 345034.0015186216 }, { "content": "fn read_string<R: Read>(mut source: R, buf: &mut Vec<u8>, max_length: u64) -> Result<&str> {\n\n let str_length = source.read_u16::<BE>()? as usize;\n\n if str_length as u64 > max_length {\n\n return Err(Error::LengthOutOfBounds);\n\n }\n\n buf.clear();\n\n buf.reserve(str_length);\n\n unsafe { buf.set_len(str_length) };\n\n source.read_exact(buf)?;\n\n from_utf8(buf).map_err(Into::into)\n\n}\n\n\n", "file_path": "src/run/parser/llanfair.rs", "rank": 12, "score": 344714.01074575784 }, { "content": "/// Attempts to parse a Splitty splits file.\n\npub fn parse<R: Read>(source: R) -> Result<Run> {\n\n let mut run = Run::new();\n\n\n\n let splits: Splits = from_reader(source)?;\n\n\n\n run.set_game_name(splits.run_name);\n\n run.set_attempt_count(splits.run_count);\n\n run.set_offset(TimeSpan::from_milliseconds(-splits.start_delay));\n\n\n\n let method = if splits.timer_type == 0 {\n\n TimingMethod::RealTime\n\n } else {\n\n TimingMethod::GameTime\n\n };\n\n\n\n for split in splits.splits {\n\n let mut segment = Segment::new(split.name);\n\n segment.set_personal_best_split_time(parse_time(split.pb_split, method));\n\n segment.set_best_segment_time(parse_time(split.split_best, method));\n\n\n\n run.push_segment(segment);\n\n }\n\n\n\n Ok(run)\n\n}\n", "file_path": "src/run/parser/splitty.rs", "rank": 13, "score": 344573.5682842084 }, { "content": "/// Attempts to parse a worstrun splits file.\n\npub fn parse<R: Read>(source: R) -> Result<Run> {\n\n let mut run = Run::new();\n\n\n\n let splits: Splits = from_reader(source)?;\n\n\n\n if let Some(game) = splits.game {\n\n run.set_game_name(game);\n\n }\n\n if let Some(category) = splits.category {\n\n run.set_category_name(category);\n\n }\n\n\n\n if let Some(initial_delay) = splits.initial_delay {\n\n run.set_offset(-TimeSpan::from_milliseconds(initial_delay as _));\n\n }\n\n\n\n // worstrun splits don't actually store the PB splits. Instead they store\n\n // the last attempt's split times. Therefore we include that as a single\n\n // attempt in the history.\n\n let mut attempt_time = Time::default();\n", "file_path": "src/run/parser/worstrun.rs", "rank": 14, "score": 344573.5682842084 }, { "content": "/// Attempts to parse an Urn splits file.\n\npub fn parse<R: Read>(source: R) -> Result<Run> {\n\n let mut run = Run::new();\n\n\n\n let splits: Splits = from_reader(source)?;\n\n\n\n if let Some(title) = splits.title {\n\n run.set_category_name(title);\n\n }\n\n if let Some(attempt_count) = splits.attempt_count {\n\n run.set_attempt_count(attempt_count);\n\n }\n\n if let Some(start_delay) = splits.start_delay {\n\n run.set_offset(-start_delay.parse()?);\n\n }\n\n\n\n // Best Split Times can be used for the Segment History Every single best\n\n // split time should be included as its own run, since the best split times\n\n // could be apart from each other less than the best segments, so we have to\n\n // assume they are from different runs.\n\n let mut attempt_history_index = 1;\n", "file_path": "src/run/parser/urn.rs", "rank": 15, "score": 344573.5682842084 }, { "content": "pub fn text_err<R, F>(reader: &mut Reader<R>, buf: &mut Vec<u8>, f: F) -> Result<()>\n\nwhere\n\n R: BufRead,\n\n F: FnOnce(Cow<str>) -> Result<()>,\n\n{\n\n text_as_bytes_err(reader, buf, |b| f(decode_cow_text(b)?))\n\n}\n\n\n", "file_path": "src/run/parser/xml_util.rs", "rank": 16, "score": 341572.93318230007 }, { "content": "/// Attempts to parse a LiveSplit splits file. In addition to the source to\n\n/// parse, you can provide a path to the splits file, which helps saving the\n\n/// splits file again later.\n\npub fn parse<R: BufRead>(source: R, path: Option<PathBuf>) -> Result<Run> {\n\n let reader = &mut Reader::from_reader(source);\n\n reader.expand_empty_elements(true);\n\n reader.trim_text(true);\n\n\n\n let mut buf = Vec::with_capacity(4096);\n\n let mut buf2 = Vec::with_capacity(4096);\n\n\n\n let mut run = Run::new();\n\n\n\n let mut required_flags = 0u8;\n\n\n\n parse_base(reader, &mut buf, b\"Run\", |reader, tag| {\n\n let mut version = Version(1, 0, 0, 0);\n\n optional_attribute_err(&tag, b\"version\", |t| {\n\n version = parse_version(t)?;\n\n Ok(())\n\n })?;\n\n\n\n parse_children(reader, tag.into_buf(), |reader, tag| {\n", "file_path": "src/run/parser/livesplit.rs", "rank": 17, "score": 341433.570997658 }, { "content": "/// Attempts to parse a SourceLiveTimer splits file.\n\npub fn parse<R: Read>(source: R) -> Result<Run> {\n\n let mut run = Run::new();\n\n let splits: Splits = from_reader(source)?;\n\n\n\n if splits.Category.starts_with(\"Portal 2\") {\n\n run.set_game_name(\"Portal 2\");\n\n } else if splits.Category.starts_with(\"Portal\") {\n\n run.set_game_name(\"Portal\");\n\n } else if splits.Category.starts_with(\"Half Life 2\") {\n\n run.set_game_name(\"Half Life 2\");\n\n }\n\n\n\n if let Some(run_name) = splits.RunName {\n\n if run_name != splits.Category {\n\n run.set_category_name(run_name);\n\n } else {\n\n run.set_category_name(splits.Category);\n\n }\n\n } else {\n\n run.set_category_name(splits.Category);\n", "file_path": "src/run/parser/source_live_timer.rs", "rank": 18, "score": 337608.6269766367 }, { "content": "/// Attempts to parse a splits file by invoking the corresponding parser for the\n\n/// file format detected. A path to the splits file can be provided, which helps\n\n/// saving the splits file again later. Additionally you need to specify if\n\n/// additional files, like external images are allowed to be loaded. If you are\n\n/// using livesplit-core in a server-like environment, set this to `false`. Only\n\n/// client-side applications should set this to `true`.\n\npub fn parse<R>(mut source: R, path: Option<PathBuf>, load_files: bool) -> Result<ParsedRun>\n\nwhere\n\n R: BufRead + Seek,\n\n{\n\n let files_path =\n\n if load_files { path.clone() } else { None };\n\n\n\n source.seek(SeekFrom::Start(0))?;\n\n if let Ok(run) = livesplit::parse(&mut source, path) {\n\n return Ok(parsed(run, TimerKind::LiveSplit));\n\n }\n\n\n\n source.seek(SeekFrom::Start(0))?;\n\n if let Ok(run) = wsplit::parse(&mut source, load_files) {\n\n return Ok(parsed(run, TimerKind::WSplit));\n\n }\n\n\n\n source.seek(SeekFrom::Start(0))?;\n\n if let Ok(run) = splitterz::parse(&mut source, load_files) {\n\n return Ok(parsed(run, TimerKind::SplitterZ));\n", "file_path": "src/run/parser/composite.rs", "rank": 19, "score": 337177.96393728536 }, { "content": "pub fn text_parsed<R, F, T>(reader: &mut Reader<R>, buf: &mut Vec<u8>, f: F) -> Result<()>\n\nwhere\n\n R: BufRead,\n\n F: FnOnce(T),\n\n T: str::FromStr,\n\n <T as str::FromStr>::Err: Into<Error>,\n\n{\n\n text_err(reader, buf, |t| {\n\n f(t.parse().map_err(Into::into)?);\n\n Ok(())\n\n })\n\n}\n\n\n", "file_path": "src/run/parser/xml_util.rs", "rank": 20, "score": 335619.33199421014 }, { "content": "pub fn text_as_bytes_err<R, F, T>(reader: &mut Reader<R>, buf: &mut Vec<u8>, f: F) -> Result<T>\n\nwhere\n\n R: BufRead,\n\n F: FnOnce(Cow<[u8]>) -> Result<T>,\n\n{\n\n let val;\n\n loop {\n\n buf.clear();\n\n match reader.read_event(buf)? {\n\n Event::Start(_) => return Err(Error::UnexpectedElement),\n\n Event::End(_) => {\n\n return f(Cow::Borrowed(&[]));\n\n }\n\n Event::Text(text) | Event::CData(text) => {\n\n let text = text.unescaped()?;\n\n val = f(text)?;\n\n break;\n\n }\n\n Event::Eof => return Err(Error::UnexpectedEndOfFile),\n\n _ => {}\n\n }\n\n }\n\n end_tag_immediately(reader, buf)?;\n\n Ok(val)\n\n}\n\n\n", "file_path": "src/run/parser/xml_util.rs", "rank": 21, "score": 326720.0650592072 }, { "content": "fn parse_history(run: &mut Run, path: Option<PathBuf>) -> StdResult<(), ()> {\n\n if let Some(mut path) = path {\n\n path.set_extension(\"\");\n\n let mut path = path.into_os_string();\n\n path.push(\"-RunLog.txt\");\n\n let path = PathBuf::from(path);\n\n\n\n let lines = BufReader::new(File::open(path).map_err(|_| ())?).lines();\n\n let mut attempt_id = 1;\n\n\n\n for line in lines.skip(1) {\n\n let line = line.map_err(|_| ())?;\n\n let mut splits = line.split('\\t');\n\n let time_stamp = splits.next().ok_or(())?;\n\n let started = Utc.datetime_from_str(time_stamp, \"%Y/%m/%d %R\")\n\n .map_err(|_| ())?;\n\n let completed = splits.next().ok_or(())? == \"C\";\n\n let split_times: Vec<_> = splits\n\n .map(parse_time_optional)\n\n .collect::<Result<_>>()\n", "file_path": "src/run/parser/time_split_tracker.rs", "rank": 22, "score": 322181.44872668025 }, { "content": "fn parse_segment<R: BufRead>(\n\n reader: &mut Reader<R>,\n\n buf: &mut Vec<u8>,\n\n image_buf: &mut Vec<u8>,\n\n) -> Result<Segment> {\n\n let mut segment = Segment::new(\"\");\n\n\n\n parse_children(reader, buf, |reader, tag| {\n\n if tag.name() == b\"name\" {\n\n text(reader, tag.into_buf(), |t| segment.set_name(t))\n\n } else if tag.name() == b\"icon\" {\n\n image(reader, tag.into_buf(), image_buf, |i| segment.set_icon(i))\n\n } else if tag.name() == b\"time\" {\n\n time(reader, tag.into_buf(), |t| {\n\n segment.set_personal_best_split_time(t)\n\n })\n\n } else if tag.name() == b\"best\" {\n\n time(reader, tag.into_buf(), |t| segment.set_best_segment_time(t))\n\n } else {\n\n end_tag(reader, tag.into_buf())\n\n }\n\n })?;\n\n\n\n Ok(segment)\n\n}\n\n\n", "file_path": "src/run/parser/llanfair2.rs", "rank": 23, "score": 317512.7513076049 }, { "content": "fn parse_segment<R: BufRead>(\n\n version: Version,\n\n reader: &mut Reader<R>,\n\n buf: &mut Vec<u8>,\n\n buf2: &mut Vec<u8>,\n\n run: &mut Run,\n\n) -> Result<Segment> {\n\n let mut segment = Segment::new(\"\");\n\n\n\n parse_children(reader, buf, |reader, tag| {\n\n if tag.name() == b\"Name\" {\n\n text(reader, tag.into_buf(), |t| segment.set_name(t))\n\n } else if tag.name() == b\"Icon\" {\n\n image(reader, tag.into_buf(), buf2, |i| segment.set_icon(i))\n\n } else if tag.name() == b\"SplitTimes\" {\n\n if version >= Version(1, 3, 0, 0) {\n\n parse_children(reader, tag.into_buf(), |reader, tag| {\n\n if tag.name() == b\"SplitTime\" {\n\n let mut comparison = String::new();\n\n attribute(&tag, b\"name\", |t| {\n", "file_path": "src/run/parser/livesplit.rs", "rank": 24, "score": 317512.7513076049 }, { "content": "pub fn reencode_children<R>(\n\n reader: &mut Reader<R>,\n\n buf: &mut Vec<u8>,\n\n target_buf: &mut Vec<u8>,\n\n) -> Result<()>\n\nwhere\n\n R: BufRead,\n\n{\n\n reader.expand_empty_elements(false);\n\n let mut writer = Writer::new(target_buf);\n\n let mut depth = 0;\n\n loop {\n\n buf.clear();\n\n match reader.read_event(buf)? {\n\n Event::Start(start) => {\n\n depth += 1;\n\n writer.write_event(Event::Start(start))?;\n\n }\n\n Event::End(end) => {\n\n if depth == 0 {\n", "file_path": "src/run/parser/xml_util.rs", "rank": 25, "score": 316502.77924647264 }, { "content": "fn end_tag_immediately<R: BufRead>(reader: &mut Reader<R>, buf: &mut Vec<u8>) -> Result<()> {\n\n loop {\n\n buf.clear();\n\n match reader.read_event(buf)? {\n\n Event::Start(_) => return Err(Error::UnexpectedElement),\n\n Event::End(_) => return Ok(()),\n\n Event::Eof => return Err(Error::UnexpectedEndOfFile),\n\n _ => {}\n\n }\n\n }\n\n}\n\n\n", "file_path": "src/run/parser/xml_util.rs", "rank": 26, "score": 314470.4320033457 }, { "content": "pub fn parse_base<R, F>(\n\n reader: &mut Reader<R>,\n\n buf: &mut Vec<u8>,\n\n tag: &[u8],\n\n mut f: F,\n\n) -> Result<()>\n\nwhere\n\n R: BufRead,\n\n F: FnMut(&mut Reader<R>, Tag) -> Result<()>,\n\n{\n\n unsafe {\n\n let ptr_buf: *mut Vec<u8> = buf;\n\n loop {\n\n buf.clear();\n\n match reader.read_event(buf)? {\n\n Event::Start(start) => if start.name() == tag {\n\n let tag = Tag::new(start, ptr_buf);\n\n return f(reader, tag);\n\n } else {\n\n return Err(Error::ElementNotFound);\n\n },\n\n Event::Eof => return Err(Error::UnexpectedEndOfFile),\n\n _ => {}\n\n }\n\n }\n\n }\n\n}\n\n\n", "file_path": "src/run/parser/xml_util.rs", "rank": 27, "score": 307417.20048802486 }, { "content": "fn time<R, F>(reader: &mut Reader<R>, buf: &mut Vec<u8>, mut f: F) -> Result<()>\n\nwhere\n\n R: BufRead,\n\n F: FnMut(Time),\n\n{\n\n time_span(reader, buf, |t| f(RealTime(Some(t)).into()))\n\n}\n\n\n", "file_path": "src/run/parser/llanfair2.rs", "rank": 28, "score": 301359.40021951485 }, { "content": "pub fn single_child<R, F, T>(\n\n reader: &mut Reader<R>,\n\n buf: &mut Vec<u8>,\n\n tag: &[u8],\n\n mut f: F,\n\n) -> Result<T>\n\nwhere\n\n R: BufRead,\n\n F: FnMut(&mut Reader<R>, Tag) -> Result<T>,\n\n{\n\n let mut val = None;\n\n parse_children(reader, buf, |reader, t| {\n\n if t.name() == tag && val.is_none() {\n\n val = Some(f(reader, t)?);\n\n Ok(())\n\n } else {\n\n end_tag(reader, t.into_buf())\n\n }\n\n })?;\n\n val.ok_or(Error::ElementNotFound)\n\n}\n\n\n", "file_path": "src/run/parser/xml_util.rs", "rank": 29, "score": 298952.69552757125 }, { "content": "fn time_span<R, F>(reader: &mut Reader<R>, buf: &mut Vec<u8>, mut f: F) -> Result<()>\n\nwhere\n\n R: BufRead,\n\n F: FnMut(TimeSpan),\n\n{\n\n single_child(reader, buf, b\"value\", |reader, tag| {\n\n text_err(reader, tag.into_buf(), |text| {\n\n let milliseconds = text.parse::<i64>()?;\n\n f(TimeSpan::from_milliseconds(milliseconds as f64));\n\n Ok(())\n\n })\n\n })\n\n}\n\n\n", "file_path": "src/run/parser/llanfair2.rs", "rank": 30, "score": 298506.93146648555 }, { "content": "fn time<R, F>(reader: &mut Reader<R>, buf: &mut Vec<u8>, f: F) -> Result<()>\n\nwhere\n\n R: BufRead,\n\n F: FnOnce(Time),\n\n{\n\n let mut time = Time::new();\n\n\n\n parse_children(reader, buf, |reader, tag| {\n\n if tag.name() == b\"RealTime\" {\n\n time_span_opt(reader, tag.into_buf(), |t| {\n\n time.real_time = t;\n\n })\n\n } else if tag.name() == b\"GameTime\" {\n\n time_span_opt(reader, tag.into_buf(), |t| {\n\n time.game_time = t;\n\n })\n\n } else {\n\n end_tag(reader, tag.into_buf())\n\n }\n\n })?;\n\n\n\n f(time);\n\n\n\n Ok(())\n\n}\n\n\n", "file_path": "src/run/parser/livesplit.rs", "rank": 31, "score": 294871.409218041 }, { "content": "fn time<R, F>(reader: &mut Reader<R>, buf: &mut Vec<u8>, f: F) -> Result<()>\n\nwhere\n\n R: BufRead,\n\n F: FnOnce(Time),\n\n{\n\n time_span(reader, buf, |t| f(RealTime(Some(t)).into()))\n\n}\n\n\n", "file_path": "src/run/parser/llanfair_gered.rs", "rank": 32, "score": 291843.3583058326 }, { "content": "fn time_span<R, F>(reader: &mut Reader<R>, buf: &mut Vec<u8>, f: F) -> Result<()>\n\nwhere\n\n R: BufRead,\n\n F: FnOnce(TimeSpan),\n\n{\n\n text_err(reader, buf, |text| {\n\n let time_span = || -> Result<TimeSpan> {\n\n if let (Some(dot_index), Some(colon_index)) = (text.find('.'), text.find(':')) {\n\n if dot_index < colon_index {\n\n let days = TimeSpan::from_days(text[..dot_index].parse()?);\n\n let time = text[dot_index + 1..].parse()?;\n\n return Ok(days + time);\n\n }\n\n }\n\n text.parse().map_err(Into::into)\n\n }()?;\n\n f(time_span);\n\n Ok(())\n\n })\n\n}\n\n\n", "file_path": "src/run/parser/livesplit.rs", "rank": 33, "score": 291843.3583058326 }, { "content": "fn time_old<R, F>(reader: &mut Reader<R>, buf: &mut Vec<u8>, f: F) -> Result<()>\n\nwhere\n\n R: BufRead,\n\n F: FnOnce(Time),\n\n{\n\n time_span_opt(reader, buf, |t| f(Time::new().with_real_time(t)))\n\n}\n\n\n", "file_path": "src/run/parser/livesplit.rs", "rank": 34, "score": 291843.3583058326 }, { "content": "fn parse_segment<R>(\n\n total_time: &mut TimeSpan,\n\n reader: &mut Reader<R>,\n\n buf: &mut Vec<u8>,\n\n buf2: &mut Vec<u8>,\n\n) -> Result<Segment>\n\nwhere\n\n R: BufRead,\n\n{\n\n single_child(reader, buf, b\"Segment\", |reader, tag| {\n\n single_child(reader, tag.into_buf(), b\"default\", |reader, tag| {\n\n let mut segment = Segment::new(\"\");\n\n let mut defer_setting_run_time = false;\n\n\n\n parse_children(reader, tag.into_buf(), |reader, tag| {\n\n if tag.name() == b\"name\" {\n\n text(reader, tag.into_buf(), |t| segment.set_name(t))\n\n } else if tag.name() == b\"bestTime\" {\n\n single_child(reader, tag.into_buf(), b\"milliseconds\", |reader, tag| {\n\n time(reader, tag.into_buf(), |t| {\n", "file_path": "src/run/parser/llanfair_gered.rs", "rank": 35, "score": 290023.33948337496 }, { "content": "fn time_span_opt<R, F>(reader: &mut Reader<R>, buf: &mut Vec<u8>, f: F) -> Result<()>\n\nwhere\n\n R: BufRead,\n\n F: FnOnce(Option<TimeSpan>),\n\n{\n\n text_err(reader, buf, |text| {\n\n let time_span = || -> Result<Option<TimeSpan>> {\n\n if text.is_empty() {\n\n return Ok(None);\n\n }\n\n if let (Some(dot_index), Some(colon_index)) = (text.find('.'), text.find(':')) {\n\n if dot_index < colon_index {\n\n let days = TimeSpan::from_days(text[..dot_index].parse()?);\n\n let time = text[dot_index + 1..].parse()?;\n\n return Ok(Some(days + time));\n\n }\n\n }\n\n Ok(Some(text.parse()?))\n\n }()?;\n\n f(time_span);\n\n Ok(())\n\n })\n\n}\n\n\n", "file_path": "src/run/parser/livesplit.rs", "rank": 36, "score": 288902.89620879054 }, { "content": "fn time_span<R, F>(reader: &mut Reader<R>, buf: &mut Vec<u8>, f: F) -> Result<()>\n\nwhere\n\n R: BufRead,\n\n F: FnOnce(TimeSpan),\n\n{\n\n text_err(reader, buf, |text| {\n\n let milliseconds = text.parse::<i64>()?;\n\n f(TimeSpan::from_milliseconds(milliseconds as f64));\n\n Ok(())\n\n })\n\n}\n\n\n", "file_path": "src/run/parser/llanfair_gered.rs", "rank": 37, "score": 288902.89620879054 }, { "content": "fn replace<'a>(text: &'a str, a: &'a str, b: &str) -> Cow<'a, str> {\n\n if text.contains(a) {\n\n text.replace(a, b).into()\n\n } else {\n\n text.into()\n\n }\n\n}\n\n\n", "file_path": "src/run/parser/face_split.rs", "rank": 38, "score": 287425.1913310289 }, { "content": "fn fix_history_from_none_best_segments(segment: &mut Segment, method: TimingMethod) {\n\n // Only do anything if the Best Segment Time is gone for the Segment in question\n\n if segment.best_segment_time()[method].is_none() {\n\n // Keep only the skipped segments\n\n segment\n\n .segment_history_mut()\n\n .retain(|&(_, time)| time[method].is_none());\n\n }\n\n}\n\n\n", "file_path": "src/run/run.rs", "rank": 39, "score": 282242.8798440294 }, { "content": "fn fix_history_from_best_segment_times(segment: &mut Segment, method: TimingMethod) {\n\n if let Some(best_segment) = segment.best_segment_time()[method] {\n\n for &mut (_, ref mut time) in segment.segment_history_mut().iter_mut() {\n\n // Make sure no times in the history are lower than the Best Segment\n\n if let Some(ref mut time) = time[method] {\n\n if *time < best_segment {\n\n *time = best_segment;\n\n }\n\n }\n\n }\n\n }\n\n}\n\n\n\n/// Iterator that iterates over all the comparisons. This includes both the\n\n/// custom comparisons defined by the user and the Comparison Generators.\n\npub struct ComparisonsIter<'a> {\n\n custom: &'a [String],\n\n generators: &'a [Box<ComparisonGenerator>],\n\n}\n\n\n", "file_path": "src/run/run.rs", "rank": 40, "score": 282242.8798440294 }, { "content": "fn parse_time_optional(time: &str) -> Result<Option<TimeSpan>> {\n\n let time: TimeSpan = time.parse()?;\n\n if time == TimeSpan::zero() {\n\n Ok(None)\n\n } else {\n\n Ok(Some(time))\n\n }\n\n}\n\n\n", "file_path": "src/run/parser/time_split_tracker.rs", "rank": 41, "score": 280976.00362890534 }, { "content": "fn parse_run_history<R: BufRead>(\n\n version: Version,\n\n reader: &mut Reader<R>,\n\n buf: &mut Vec<u8>,\n\n run: &mut Run,\n\n) -> Result<()> {\n\n if version >= Version(1, 5, 0, 0) {\n\n end_tag(reader, buf)\n\n } else if version >= Version(1, 4, 1, 0) {\n\n parse_children(reader, buf, |reader, tag| {\n\n let mut index = 0;\n\n attribute_err(&tag, b\"id\", |t| {\n\n index = t.parse()?;\n\n Ok(())\n\n })?;\n\n time(reader, tag.into_buf(), |time| {\n\n run.add_attempt_with_index(time, index, None, None, None);\n\n })\n\n })\n\n } else {\n", "file_path": "src/run/parser/livesplit.rs", "rank": 42, "score": 280586.4274338598 }, { "content": "fn parse_metadata<R: BufRead>(\n\n version: Version,\n\n reader: &mut Reader<R>,\n\n buf: &mut Vec<u8>,\n\n metadata: &mut RunMetadata,\n\n) -> Result<()> {\n\n if version >= Version(1, 6, 0, 0) {\n\n parse_children(reader, buf, |reader, tag| {\n\n if tag.name() == b\"Run\" {\n\n attribute(&tag, b\"id\", |t| metadata.set_run_id(t))?;\n\n end_tag(reader, tag.into_buf())\n\n } else if tag.name() == b\"Platform\" {\n\n attribute_err(&tag, b\"usesEmulator\", |t| {\n\n metadata.set_emulator_usage(parse_bool(t)?);\n\n Ok(())\n\n })?;\n\n text(reader, tag.into_buf(), |t| metadata.set_platform_name(t))\n\n } else if tag.name() == b\"Region\" {\n\n text(reader, tag.into_buf(), |t| metadata.set_region_name(t))\n\n } else if tag.name() == b\"Variables\" {\n", "file_path": "src/run/parser/livesplit.rs", "rank": 43, "score": 273094.0837176175 }, { "content": "fn parse_attempt_history<R: BufRead>(\n\n version: Version,\n\n reader: &mut Reader<R>,\n\n buf: &mut Vec<u8>,\n\n run: &mut Run,\n\n) -> Result<()> {\n\n if version >= Version(1, 5, 0, 0) {\n\n parse_children(reader, buf, |reader, tag| {\n\n let mut time = Time::new();\n\n let mut pause_time = None;\n\n let mut index = None;\n\n let (mut started, mut started_synced) = (None, false);\n\n let (mut ended, mut ended_synced) = (None, false);\n\n\n\n parse_attributes(&tag, |k, v| {\n\n if k == b\"id\" {\n\n index = Some(v.get()?.parse()?);\n\n } else if k == b\"started\" {\n\n started = Some(parse_date_time(v.get()?)?);\n\n } else if k == b\"isStartedSynced\" {\n", "file_path": "src/run/parser/livesplit.rs", "rank": 44, "score": 269683.3924823979 }, { "content": "fn parse_time(time: &str) -> Result<Time> {\n\n // Replace \",\" by \".\" as \",\" wouldn't parse\n\n let time: TimeSpan = replace(time, \",\", \".\").parse()?;\n\n // Skipped is stored as a zero time in FaceSplit Splits\n\n if time == TimeSpan::zero() {\n\n Ok(Time::default())\n\n } else {\n\n Ok(RealTime(Some(time)).into())\n\n }\n\n}\n\n\n", "file_path": "src/run/parser/face_split.rs", "rank": 45, "score": 267885.59374803706 }, { "content": "fn generate(segments: &mut [Segment], method: TimingMethod) {\n\n let mut attempt_id = None;\n\n for segment in segments.iter_mut().rev() {\n\n if let Some(max_index) = segment.segment_history().try_get_max_index() {\n\n attempt_id = Some(max_index);\n\n break;\n\n }\n\n }\n\n\n\n if let Some(attempt_id) = attempt_id {\n\n let mut remaining_segments = segments.iter_mut();\n\n\n\n let mut total_time = TimeSpan::zero();\n\n for segment in remaining_segments.by_ref() {\n\n let segment_time = segment.segment_history().get(attempt_id).map(|t| t[method]);\n\n\n\n let split_time = match segment_time {\n\n Some(Some(segment_time)) => {\n\n total_time += segment_time;\n\n Some(total_time)\n", "file_path": "src/comparison/latest_run.rs", "rank": 46, "score": 264265.43568286207 }, { "content": "pub fn parse_attributes<'a, F>(tag: &BytesStart<'a>, mut f: F) -> Result<()>\n\nwhere\n\n F: FnMut(&[u8], AttributeValue) -> Result<bool>,\n\n{\n\n for attribute in tag.attributes() {\n\n let attribute = attribute?;\n\n let key = attribute.key;\n\n if !f(key, AttributeValue(&attribute))? {\n\n return Ok(());\n\n }\n\n }\n\n Ok(())\n\n}\n\n\n", "file_path": "src/run/parser/xml_util.rs", "rank": 47, "score": 264085.4683863106 }, { "content": "pub fn attribute<'a, F>(tag: &BytesStart<'a>, key: &[u8], mut f: F) -> Result<()>\n\nwhere\n\n F: FnMut(Cow<str>),\n\n{\n\n attribute_err(tag, key, |t| {\n\n f(t);\n\n Ok(())\n\n })\n\n}\n", "file_path": "src/run/parser/xml_util.rs", "rank": 48, "score": 256025.59166858182 }, { "content": "/// Calculates how much time could be saved on the remainder of the run with the\n\n/// given comparison. This information is based on the best segments.\n\n/// Considering the best segments don't represent theoretically perfect segment\n\n/// times, this information is only an approximation of how much time can\n\n/// actually be saved. This information is always live, so the total possible\n\n/// time save will shrink towards zero throughout the run and when time is lost\n\n/// on a segment. The time returned by this function can never be below zero.\n\npub fn calculate_total(timer: &Timer, segment_index: usize, comparison: &str) -> TimeSpan {\n\n let mut total = TimeSpan::zero();\n\n\n\n for index in segment_index..timer.run().len() {\n\n if let Some(time_save) = calculate(timer, index, comparison, true) {\n\n total += time_save;\n\n }\n\n }\n\n\n\n total\n\n}\n", "file_path": "src/analysis/possible_time_save.rs", "rank": 49, "score": 253154.82721880524 }, { "content": "pub fn attribute_err<'a, F>(tag: &BytesStart<'a>, key: &[u8], mut f: F) -> Result<()>\n\nwhere\n\n F: FnMut(Cow<str>) -> Result<()>,\n\n{\n\n let mut called = false;\n\n parse_attributes(tag, |k, v| {\n\n if k == key {\n\n f(v.get()?)?;\n\n called = true;\n\n Ok(false)\n\n } else {\n\n Ok(true)\n\n }\n\n })?;\n\n if called {\n\n Ok(())\n\n } else {\n\n Err(Error::AttributeNotFound)\n\n }\n\n}\n\n\n", "file_path": "src/run/parser/xml_util.rs", "rank": 50, "score": 252721.49325567868 }, { "content": "fn vec_as_string<F, R>(vec: &mut Vec<u8>, f: F) -> R\n\nwhere\n\n F: FnOnce(&mut String) -> R,\n\n{\n\n let taken = replace(vec, Vec::new());\n\n let mut string = String::from_utf8(taken).unwrap();\n\n let result = f(&mut string);\n\n let bytes = string.into_bytes();\n\n replace(vec, bytes);\n\n result\n\n}\n\n\n", "file_path": "src/run/saver/livesplit.rs", "rank": 51, "score": 252196.4510397031 }, { "content": "fn unescape(text: &str) -> Cow<str> {\n\n if text.contains('‡') {\n\n text.replace('‡', \",\").into()\n\n } else {\n\n text.into()\n\n }\n\n}\n\n\n", "file_path": "src/run/parser/splitterz.rs", "rank": 52, "score": 251987.38503079087 }, { "content": "fn generate(segments: &mut [Segment], attempts: &[Attempt], method: TimingMethod) {\n\n for attempt in attempts {\n\n let id = attempt.index();\n\n let mut total_time = TimeSpan::zero();\n\n\n\n for segment in segments.iter_mut() {\n\n if let Some(time) = segment.segment_history().get(id) {\n\n if let Some(time) = time[method] {\n\n total_time += time;\n\n\n\n let comp = &mut segment.comparison_mut(NAME)[method];\n\n if comp.map_or(true, |c| total_time < c) {\n\n *comp = Some(total_time);\n\n }\n\n }\n\n } else {\n\n break;\n\n }\n\n }\n\n }\n", "file_path": "src/comparison/best_split_times.rs", "rank": 53, "score": 249834.39191888124 }, { "content": "pub fn optional_attribute_err<'a, F>(tag: &BytesStart<'a>, key: &[u8], mut f: F) -> Result<()>\n\nwhere\n\n F: FnMut(Cow<str>) -> Result<()>,\n\n{\n\n parse_attributes(tag, |k, v| {\n\n if k == key {\n\n f(v.get()?)?;\n\n Ok(false)\n\n } else {\n\n Ok(true)\n\n }\n\n })\n\n}\n\n\n", "file_path": "src/run/parser/xml_util.rs", "rank": 54, "score": 249528.38298716611 }, { "content": "fn image<R, F>(\n\n reader: &mut Reader<R>,\n\n buf: &mut Vec<u8>,\n\n image_buf: &mut Vec<u8>,\n\n mut f: F,\n\n) -> Result<()>\n\nwhere\n\n R: BufRead,\n\n F: FnMut(&[u8]),\n\n{\n\n let (mut width, mut height) = (None, None);\n\n image_buf.clear();\n\n\n\n single_child(reader, buf, b\"javax.swing.ImageIcon\", |reader, tag| {\n\n parse_children(reader, tag.into_buf(), |reader, tag| {\n\n if tag.name() == b\"default\" {\n\n parse_children(reader, tag.into_buf(), |reader, tag| {\n\n if tag.name() == b\"height\" {\n\n text_parsed(reader, tag.into_buf(), |t: u32| height = Some(t))\n\n } else if tag.name() == b\"width\" {\n", "file_path": "src/run/parser/llanfair2.rs", "rank": 55, "score": 244960.3184649352 }, { "content": "fn image<R, F>(\n\n reader: &mut Reader<R>,\n\n result: &mut Vec<u8>,\n\n image_buf: &mut Vec<u8>,\n\n f: F,\n\n) -> Result<()>\n\nwhere\n\n R: BufRead,\n\n F: FnOnce(&[u8]),\n\n{\n\n text_as_bytes_err(reader, result, |text| {\n\n if text.len() >= 216 {\n\n image_buf.clear();\n\n if base64::decode_config_buf(&text[212..], base64::STANDARD, image_buf).is_ok() {\n\n f(&image_buf[2..image_buf.len() - 1]);\n\n return Ok(());\n\n }\n\n }\n\n f(&[]);\n\n Ok(())\n\n })\n\n}\n\n\n", "file_path": "src/run/parser/livesplit.rs", "rank": 56, "score": 244960.3184649352 }, { "content": "/// Shortens a comparison name. If the name of the comparison matches one of the\n\n/// comparison generators, the short name of that comparison generator is\n\n/// returned. Otherwise the comparison name is returned without being shortened.\n\n/// Additional shortening logic for other comparison names may happen in the\n\n/// future.\n\npub fn shorten(comparison: &str) -> &str {\n\n match comparison {\n\n personal_best::NAME => personal_best::SHORT_NAME,\n\n average_segments::NAME => average_segments::SHORT_NAME,\n\n balanced_pb::NAME => balanced_pb::SHORT_NAME,\n\n best_segments::NAME => best_segments::SHORT_NAME,\n\n best_split_times::NAME => best_split_times::SHORT_NAME,\n\n latest_run::NAME => latest_run::SHORT_NAME,\n\n none::NAME => none::SHORT_NAME,\n\n worst_segments::NAME => worst_segments::SHORT_NAME,\n\n c => c,\n\n }\n\n}\n\n\n", "file_path": "src/comparison/mod.rs", "rank": 57, "score": 242659.1680288752 }, { "content": "fn image<R, F>(\n\n reader: &mut Reader<R>,\n\n tag_buf: &mut Vec<u8>,\n\n buf: &mut Vec<u8>,\n\n mut f: F,\n\n) -> Result<()>\n\nwhere\n\n R: BufRead,\n\n F: FnMut(&[u8]),\n\n{\n\n single_child(reader, tag_buf, b\"ImageIcon\", |reader, tag| {\n\n let tag_buf = tag.into_buf();\n\n let (width, height, image) = text_as_bytes_err(reader, tag_buf, |t| {\n\n buf.clear();\n\n base64::decode_config_buf(&t, STANDARD, buf).map_err(|_| Error::ElementNotFound)?;\n\n\n\n let (width, height);\n\n {\n\n let mut cursor = Cursor::new(&buf);\n\n cursor.seek(SeekFrom::Current(0xD1))?;\n", "file_path": "src/run/parser/llanfair_gered.rs", "rank": 58, "score": 241265.726205783 }, { "content": "fn time_span_from_ticks(category_name: &str, ticks: u64) -> TimeSpan {\n\n let seconds = if category_name.starts_with(\"Portal 2\") {\n\n ticks as f64 / 30.0\n\n } else {\n\n // Game is either Portal or Half Life 2\n\n ticks as f64 / 66.6666666666667\n\n };\n\n\n\n TimeSpan::from_seconds(seconds)\n\n}\n\n\n", "file_path": "src/run/parser/source_live_timer.rs", "rank": 59, "score": 238444.16095302935 }, { "content": "fn run_with_splits(timer: &mut Timer, splits: &[f64]) {\n\n timer.start();\n\n timer.initialize_game_time();\n\n timer.pause_game_time();\n\n\n\n for &split in splits {\n\n timer.set_game_time(TimeSpan::from_seconds(split));\n\n timer.split();\n\n }\n\n\n\n timer.reset(true);\n\n}\n\n\n", "file_path": "benches/balanced_pb.rs", "rank": 60, "score": 236793.28921614707 }, { "content": "fn next_timing_method(run: &Run, predictions: &mut Vec<Option<TimeSpan>>, method: TimingMethod) {\n\n let segments = run.segments();\n\n\n\n predictions.clear();\n\n predictions.resize(segments.len() + 1, None);\n\n best::calculate(segments, predictions, true, false, method);\n\n}\n", "file_path": "src/run/editor/cleaning.rs", "rank": 61, "score": 235792.5409717362 }, { "content": "fn get_ll_type(ty: &Type) -> &str {\n\n match (ty.kind, ty.name.as_str()) {\n\n (TypeKind::Ref, \"c_char\") | (_, \"Json\") => \"'CString'\",\n\n (TypeKind::Ref, _) | (TypeKind::RefMut, _) => \"'pointer'\",\n\n (_, t) if !ty.is_custom => match t {\n\n \"i8\" => \"'int8'\",\n\n \"i16\" => \"'int16'\",\n\n \"i32\" => \"'int32'\",\n\n \"i64\" => \"'int64'\",\n\n \"u8\" => \"'uint8'\",\n\n \"u16\" => \"'uint16'\",\n\n \"u32\" => \"'uint32'\",\n\n \"u64\" => \"'uint64'\",\n\n \"usize\" => \"'size_t'\",\n\n \"f32\" => \"'float'\",\n\n \"f64\" => \"'double'\",\n\n \"bool\" => \"'bool'\",\n\n \"()\" => \"'void'\",\n\n \"c_char\" => \"'char'\",\n\n x => x,\n\n },\n\n _ => \"'pointer'\",\n\n }\n\n}\n\n\n", "file_path": "capi/bind_gen/src/node.rs", "rank": 62, "score": 231729.64676333073 }, { "content": "fn get_ll_type(ty: &Type) -> &str {\n\n match (ty.kind, ty.name.as_str()) {\n\n (TypeKind::Ref, \"c_char\") | (_, \"Json\") => r#\"\"string\"\"#,\n\n (TypeKind::Value, \"()\") => \"null\",\n\n _ => r#\"\"number\"\"#,\n\n }\n\n}\n\n\n", "file_path": "capi/bind_gen/src/emscripten.rs", "rank": 63, "score": 231729.64676333073 }, { "content": "fn get_ll_type(ty: &Type) -> &str {\n\n match (ty.kind, ty.name.as_str()) {\n\n (TypeKind::Ref, \"c_char\") => \"string\",\n\n (TypeKind::Ref, _) | (TypeKind::RefMut, _) => \"pointer\",\n\n (_, t) if !ty.is_custom => match t {\n\n \"i8\" => \"int8\",\n\n \"i16\" => \"int16\",\n\n \"i32\" => \"int32\",\n\n \"i64\" => \"int64\",\n\n \"u8\" => \"uint8\",\n\n \"u16\" => \"uint16\",\n\n \"u32\" => \"uint32\",\n\n \"u64\" => \"uint64\",\n\n \"usize\" => \"size_t\",\n\n \"f32\" => \"float\",\n\n \"f64\" => \"double\",\n\n \"bool\" => \"bool\",\n\n \"()\" => \"void\",\n\n \"c_char\" => \"char\",\n\n \"Json\" => \"string\",\n\n x => x,\n\n },\n\n _ => \"pointer\",\n\n }\n\n}\n\n\n", "file_path": "capi/bind_gen/src/ruby.rs", "rank": 64, "score": 231729.64676333073 }, { "content": "fn get_ll_type(ty: &Type) -> &str {\n\n match (ty.kind, ty.name.as_str()) {\n\n (TypeKind::Ref, \"c_char\") => \"c_char_p\",\n\n (TypeKind::Ref, _) | (TypeKind::RefMut, _) => \"c_void_p\",\n\n (_, t) if !ty.is_custom => match t {\n\n \"i8\" => \"c_int8\",\n\n \"i16\" => \"c_int16\",\n\n \"i32\" => \"c_int32\",\n\n \"i64\" => \"c_int64\",\n\n \"u8\" => \"c_uint8\",\n\n \"u16\" => \"c_uint16\",\n\n \"u32\" => \"c_uint32\",\n\n \"u64\" => \"c_uint64\",\n\n \"usize\" => \"c_size_t\",\n\n \"f32\" => \"c_float\",\n\n \"f64\" => \"c_double\",\n\n \"bool\" => \"c_bool\",\n\n \"()\" => \"None\",\n\n \"c_char\" => \"c_char\",\n\n \"Json\" => \"c_char_p\",\n\n x => x,\n\n },\n\n _ => \"c_void_p\",\n\n }\n\n}\n\n\n", "file_path": "capi/bind_gen/src/python.rs", "rank": 65, "score": 231729.64676333073 }, { "content": "fn run_with_splits(timer: &mut Timer, splits: &[f64]) {\n\n timer.start();\n\n timer.initialize_game_time();\n\n timer.pause_game_time();\n\n\n\n for &split in splits {\n\n timer.set_game_time(TimeSpan::from_seconds(split));\n\n timer.split();\n\n }\n\n\n\n timer.reset(true);\n\n}\n\n\n", "file_path": "src/comparison/tests/balanced_pb.rs", "rank": 66, "score": 230669.53161145866 }, { "content": "fn get_type(ty: &Type) -> Cow<str> {\n\n let mut name = Cow::Borrowed(match ty.name.as_str() {\n\n \"i8\" => \"int8_t\",\n\n \"i16\" => \"int16_t\",\n\n \"i32\" => \"int32_t\",\n\n \"i64\" => \"int64_t\",\n\n \"u8\" => \"uint8_t\",\n\n \"u16\" => \"uint16_t\",\n\n \"u32\" => \"uint32_t\",\n\n \"u64\" => \"uint64_t\",\n\n \"usize\" => \"size_t\",\n\n \"f32\" => \"float\",\n\n \"f64\" => \"double\",\n\n \"bool\" => \"bool\",\n\n \"()\" => \"void\",\n\n \"c_char\" => \"char\",\n\n \"Json\" => \"char const*\",\n\n x => x,\n\n });\n\n match (ty.is_custom, ty.kind) {\n", "file_path": "capi/bind_gen/src/c.rs", "rank": 67, "score": 229652.73770580027 }, { "content": "fn get_ll_type(ty: &Type) -> &str {\n\n match (ty.kind, ty.name.as_str()) {\n\n (TypeKind::Ref, \"c_char\") => \"String\",\n\n (TypeKind::Ref, _) | (TypeKind::RefMut, _) => \"Pointer\",\n\n (_, t) if !ty.is_custom => {\n\n match t {\n\n \"i8\" => \"byte\",\n\n \"i16\" => \"short\",\n\n \"i32\" => \"int\",\n\n \"i64\" => \"long\",\n\n \"u8\" => \"byte\",\n\n \"u16\" => \"short\",\n\n \"u32\" => \"int\",\n\n \"u64\" => \"long\",\n\n \"usize\" => \"NativeLong\", // Not really correct\n\n \"f32\" => \"float\",\n\n \"f64\" => \"double\",\n\n \"bool\" => \"byte\",\n\n \"()\" => \"void\",\n\n \"c_char\" => \"byte\",\n\n \"Json\" => \"String\",\n\n x => x,\n\n }\n\n }\n\n _ => \"Pointer\",\n\n }\n\n}\n\n\n", "file_path": "capi/bind_gen/src/java/jna.rs", "rank": 68, "score": 229492.01979600653 }, { "content": "fn get_ll_type(ty: &Type) -> &str {\n\n match (ty.kind, ty.name.as_str()) {\n\n (TypeKind::Ref, \"c_char\") => \"String\",\n\n (TypeKind::Ref, _) | (TypeKind::RefMut, _) => \"UnsafeMutableRawPointer?\",\n\n (_, t) if !ty.is_custom => match t {\n\n \"i8\" => \"Int8\",\n\n \"i16\" => \"Int16\",\n\n \"i32\" => \"Int32\",\n\n \"i64\" => \"Int64\",\n\n \"u8\" => \"UInt8\",\n\n \"u16\" => \"UInt16\",\n\n \"u32\" => \"UInt32\",\n\n \"u64\" => \"UInt64\",\n\n \"usize\" => \"size_t\",\n\n \"f32\" => \"Float\",\n\n \"f64\" => \"Double\",\n\n \"bool\" => \"Bool\",\n\n \"()\" => \"()\",\n\n \"c_char\" => \"UInt8\",\n\n \"Json\" => \"String\",\n\n x => x,\n\n },\n\n _ => \"UnsafeMutableRawPointer?\",\n\n }\n\n}\n\n\n", "file_path": "capi/bind_gen/src/swift/code.rs", "rank": 69, "score": 229492.01979600653 }, { "content": "fn parse_time(time: &str) -> Result<Time> {\n\n let real_time = time.parse::<TimeSpan>()?;\n\n\n\n // Empty Time is stored as zero\n\n let real_time = if real_time != TimeSpan::zero() {\n\n Some(real_time)\n\n } else {\n\n None\n\n };\n\n\n\n Ok(Time::new().with_real_time(real_time))\n\n}\n\n\n", "file_path": "src/run/parser/urn.rs", "rank": 70, "score": 228334.6395258629 }, { "content": "fn generate(segments: &mut [Segment], method: TimingMethod) {\n\n let mut accumulated = Some(TimeSpan::zero());\n\n\n\n for i in 0..segments.len() {\n\n // TODO Borrowcheck. if accumulated.is_some() is only necessary because\n\n // we can't assign to the outer variable otherwise.\n\n if accumulated.is_some() {\n\n let (mut total_weights, mut total_time) = (0.0, 0.0);\n\n let mut current_weight = 1.0;\n\n\n\n for &(id, time) in segments[i].segment_history().iter_actual_runs().rev() {\n\n if let Some(time) = time[method] {\n\n // Skip all the combined segments\n\n let skip = catch! {\n\n segments[i.checked_sub(1)?].segment_history().get(id)?[method].is_none()\n\n }.unwrap_or(false);\n\n\n\n if !skip {\n\n total_weights += current_weight;\n\n total_time += current_weight * time.total_seconds();\n", "file_path": "src/comparison/average_segments.rs", "rank": 71, "score": 228052.30151884176 }, { "content": "/// Calculates the current pace of the active attempt based on the comparison\n\n/// provided. If there's no active attempt, the final time of the comparison is\n\n/// returned instead.\n\npub fn calculate(timer: &Timer, comparison: &str) -> Option<TimeSpan> {\n\n let timing_method = timer.current_timing_method();\n\n let last_segment = timer.run().segments().last().unwrap();\n\n\n\n match timer.current_phase() {\n\n TimerPhase::Running | TimerPhase::Paused => {\n\n let mut delta = analysis::last_delta(\n\n timer.run(),\n\n timer.current_split_index().unwrap(),\n\n comparison,\n\n timing_method,\n\n ).unwrap_or_default();\n\n\n\n catch! {\n\n let live_delta = timer.current_time()[timing_method]?\n\n - timer.current_split().unwrap().comparison(comparison)[timing_method]?;\n\n\n\n if live_delta > delta {\n\n delta = live_delta;\n\n }\n", "file_path": "src/analysis/current_pace.rs", "rank": 72, "score": 227384.4896637884 }, { "content": "fn get_c_type(ty: &Type) -> Cow<str> {\n\n let mut name = Cow::Borrowed(match ty.name.as_str() {\n\n \"i8\" => \"int8_t\",\n\n \"i16\" => \"int16_t\",\n\n \"i32\" => \"int32_t\",\n\n \"i64\" => \"int64_t\",\n\n \"u8\" => \"uint8_t\",\n\n \"u16\" => \"uint16_t\",\n\n \"u32\" => \"uint32_t\",\n\n \"u64\" => \"uint64_t\",\n\n \"usize\" => \"size_t\",\n\n \"f32\" => \"float\",\n\n \"f64\" => \"double\",\n\n \"bool\" => \"bool\",\n\n \"()\" => \"void\",\n\n \"c_char\" => \"char\",\n\n \"Json\" => \"char const*\",\n\n x => x,\n\n });\n\n match (ty.is_custom, ty.kind) {\n", "file_path": "capi/bind_gen/src/jni_cpp.rs", "rank": 73, "score": 225099.99641402514 }, { "content": "fn get_type(ty: &Type) -> Cow<str> {\n\n let mut name = Cow::Borrowed(match ty.name.as_str() {\n\n \"i8\" => \"int8_t\",\n\n \"i16\" => \"int16_t\",\n\n \"i32\" => \"int32_t\",\n\n \"i64\" => \"int64_t\",\n\n \"u8\" => \"uint8_t\",\n\n \"u16\" => \"uint16_t\",\n\n \"u32\" => \"uint32_t\",\n\n \"u64\" => \"uint64_t\",\n\n \"usize\" => \"size_t\",\n\n \"f32\" => \"float\",\n\n \"f64\" => \"double\",\n\n \"bool\" => \"bool\",\n\n \"()\" => \"void\",\n\n \"c_char\" => \"char\",\n\n \"Json\" => \"char const*\",\n\n x => x,\n\n });\n\n match (ty.is_custom, ty.kind) {\n", "file_path": "capi/bind_gen/src/swift/header.rs", "rank": 74, "score": 225099.99641402514 }, { "content": "/// Calculates the delta of the current attempt to the comparison provided.\n\n/// Additionally a value is returned that indicates whether the delta value is a\n\n/// live delta. A live delta indicates that the value is actively changing at\n\n/// the moment. This may be the case when the current attempt is slower than the\n\n/// comparison at the current split.\n\npub fn calculate(timer: &Timer, comparison: &str) -> (Option<TimeSpan>, bool) {\n\n let timing_method = timer.current_timing_method();\n\n let last_segment = timer.run().segments().last().unwrap();\n\n\n\n let mut use_live_delta = false;\n\n\n\n let time = match timer.current_phase() {\n\n TimerPhase::Running | TimerPhase::Paused => {\n\n let mut delta = analysis::last_delta(\n\n timer.run(),\n\n timer.current_split_index().unwrap(),\n\n comparison,\n\n timing_method,\n\n );\n\n\n\n catch! {\n\n let live_delta = timer.current_time()[timing_method]?\n\n - timer.current_split().unwrap().comparison(comparison)[timing_method]?;\n\n\n\n if live_delta > delta.unwrap_or_default() {\n", "file_path": "src/analysis/delta.rs", "rank": 75, "score": 223220.64329286222 }, { "content": "/// Saves a Run as a LiveSplit splits file (*.lss). Use the `save_timer`\n\n/// function if the Run is in use by a timer in order to properly save the\n\n/// current attempt as well.\n\npub fn save_run<W: Write>(run: &Run, writer: W) -> Result<()> {\n\n let writer = &mut Writer::new(writer);\n\n\n\n let buf = &mut Vec::new();\n\n let image_buf = &mut Cow::Borrowed(&LSS_IMAGE_HEADER[..]);\n\n\n\n writer.write_event(Event::Decl(BytesDecl::new(b\"1.0\", Some(b\"UTF-8\"), None)))?;\n\n writer.write_event(Event::Start(BytesStart::borrowed(\n\n br#\"Run version=\"1.7.0\"\"#,\n\n 3,\n\n )))?;\n\n\n\n image(\n\n writer,\n\n new_tag(b\"GameIcon\"),\n\n run.game_icon(),\n\n buf,\n\n image_buf,\n\n )?;\n\n text(writer, new_tag(b\"GameName\"), run.game_name())?;\n", "file_path": "src/run/saver/livesplit.rs", "rank": 76, "score": 223171.0362542923 }, { "content": "fn run_with_splits_opt(timer: &mut Timer, splits: &[Option<f64>]) {\n\n timer.start();\n\n timer.initialize_game_time();\n\n timer.pause_game_time();\n\n\n\n for &split in splits {\n\n if let Some(split) = split {\n\n timer.set_game_time(TimeSpan::from_seconds(split));\n\n timer.split();\n\n } else {\n\n timer.skip_split();\n\n }\n\n }\n\n\n\n timer.reset(true);\n\n}\n\n\n", "file_path": "src/comparison/tests/balanced_pb.rs", "rank": 77, "score": 222649.71887083745 }, { "content": "fn get_ll_type(ty: &Type, output: bool) -> &str {\n\n match (ty.kind, ty.name.as_str()) {\n\n (TypeKind::Ref, \"c_char\") => if output {\n\n \"LSCoreString\"\n\n } else {\n\n \"string\"\n\n },\n\n (TypeKind::Ref, _) | (TypeKind::RefMut, _) => \"IntPtr\",\n\n (_, t) if !ty.is_custom => match t {\n\n \"i8\" => \"sbyte\",\n\n \"i16\" => \"short\",\n\n \"i32\" => \"int\",\n\n \"i64\" => \"long\",\n\n \"u8\" => \"byte\",\n\n \"u16\" => \"ushort\",\n\n \"u32\" => \"uint\",\n\n \"u64\" => \"ulong\",\n\n \"usize\" => \"UIntPtr\",\n\n \"f32\" => \"float\",\n\n \"f64\" => \"double\",\n", "file_path": "capi/bind_gen/src/csharp.rs", "rank": 78, "score": 218943.317392228 }, { "content": "fn get_jni_type<'a>(ty: &'a Type) -> &'a str {\n\n match (ty.kind, ty.name.as_str()) {\n\n (TypeKind::Ref, \"c_char\") => \"jstring\",\n\n (TypeKind::Ref, _) | (TypeKind::RefMut, _) => \"jlong\",\n\n (_, t) if !ty.is_custom => match t {\n\n \"i8\" => \"jbyte\",\n\n \"i16\" => \"jshort\",\n\n \"i32\" => \"jint\",\n\n \"i64\" => \"jlong\",\n\n \"u8\" => \"jbyte\",\n\n \"u16\" => \"jshort\",\n\n \"u32\" => \"jint\",\n\n \"u64\" => \"jlong\",\n\n \"usize\" => \"jlong\",\n\n \"f32\" => \"jfloat\",\n\n \"f64\" => \"jdouble\",\n\n \"bool\" => \"jboolean\",\n\n \"()\" => \"void\",\n\n \"c_char\" => \"jbyte\",\n\n \"Json\" => \"jstring\",\n\n x => x,\n\n },\n\n _ => \"jlong\",\n\n }\n\n}\n\n\n", "file_path": "capi/bind_gen/src/jni_cpp.rs", "rank": 79, "score": 217462.1328441915 }, { "content": "fn get_ll_type<'a>(ty: &'a Type) -> &'a str {\n\n match (ty.kind, ty.name.as_str()) {\n\n (TypeKind::Ref, \"c_char\") => \"String\",\n\n (TypeKind::Ref, _) | (TypeKind::RefMut, _) => \"Long\",\n\n (_, t) if !ty.is_custom => match t {\n\n \"i8\" => \"Byte\",\n\n \"i16\" => \"Short\",\n\n \"i32\" => \"Int\",\n\n \"i64\" => \"Long\",\n\n \"u8\" => \"Byte\",\n\n \"u16\" => \"Short\",\n\n \"u32\" => \"Int\",\n\n \"u64\" => \"Long\",\n\n \"usize\" => \"Long\",\n\n \"f32\" => \"Float\",\n\n \"f64\" => \"Double\",\n\n \"bool\" => \"Boolean\",\n\n \"()\" => \"Unit\",\n\n \"c_char\" => \"Byte\",\n\n \"Json\" => \"String\",\n\n x => x,\n\n },\n\n _ => \"Long\",\n\n }\n\n}\n\n\n", "file_path": "capi/bind_gen/src/kotlin/jni.rs", "rank": 80, "score": 217462.1328441915 }, { "content": "fn get_ll_type<'a>(ty: &'a Type) -> &'a str {\n\n match (ty.kind, ty.name.as_str()) {\n\n (TypeKind::Ref, \"c_char\") => \"String\",\n\n (TypeKind::Ref, _) | (TypeKind::RefMut, _) => \"long\",\n\n (_, t) if !ty.is_custom => match t {\n\n \"i8\" => \"byte\",\n\n \"i16\" => \"short\",\n\n \"i32\" => \"int\",\n\n \"i64\" => \"long\",\n\n \"u8\" => \"byte\",\n\n \"u16\" => \"short\",\n\n \"u32\" => \"int\",\n\n \"u64\" => \"long\",\n\n \"usize\" => \"long\",\n\n \"f32\" => \"float\",\n\n \"f64\" => \"double\",\n\n \"bool\" => \"boolean\",\n\n \"()\" => \"void\",\n\n \"c_char\" => \"byte\",\n\n \"Json\" => \"String\",\n\n x => x,\n\n },\n\n _ => \"long\",\n\n }\n\n}\n\n\n", "file_path": "capi/bind_gen/src/java/jni.rs", "rank": 81, "score": 217462.1328441915 }, { "content": "pub fn write<W: Write>(mut writer: W, classes: &BTreeMap<String, Class>) -> Result<()> {\n\n write!(\n\n writer,\n\n \"{}\",\n\n r#\"#ifndef LIVESPLIT_CORE_H\n\n#define LIVESPLIT_CORE_H\n\n\n\n#ifdef __cplusplus\n\n#define restrict __restrict\n\nnamespace LiveSplit {\n\nextern \"C\" {\n\n#endif\n\n\n\n#include <stdint.h>\n\n#include <stddef.h>\n\n#include <stdbool.h>\n\n\n\n\"#\n\n )?;\n\n\n", "file_path": "capi/bind_gen/src/c.rs", "rank": 82, "score": 215612.56264072756 }, { "content": "/// Helper function for accessing either the given comparison or a Timer's\n\n/// current comparison if the given comparison is `None`.\n\npub fn or_current<'a>(comparison: Option<&'a str>, timer: &'a Timer) -> &'a str {\n\n comparison.unwrap_or_else(|| timer.current_comparison())\n\n}\n\n\n", "file_path": "src/comparison/mod.rs", "rank": 83, "score": 214396.48371550645 }, { "content": "pub fn write<W: Write>(mut writer: W, classes: &BTreeMap<String, Class>) -> Result<()> {\n\n write!(writer,\n\n \"{}\",\n\n r#\"#!/usr/bin/env python3\n\n# coding: utf-8\n\n\n\nimport sys, ctypes\n\nfrom ctypes import c_char_p, c_void_p, c_int8, c_int16, c_int32, c_int64, c_uint8, c_uint16, c_uint32, c_uint64, c_size_t, c_float, c_double, c_bool, c_char, c_byte\n\n\n\nprefix = {'win32': ''}.get(sys.platform, './lib')\n\nextension = {'darwin': '.dylib', 'win32': '.dll'}.get(sys.platform, '.so')\n\nlivesplit_core_native = ctypes.cdll.LoadLibrary(prefix + \"livesplit_core\" + extension)\n\n\"#)?;\n\n\n\n for class in classes.values() {\n\n for function in class\n\n .static_fns\n\n .iter()\n\n .chain(class.own_fns.iter())\n\n .chain(class.shared_fns.iter())\n", "file_path": "capi/bind_gen/src/python.rs", "rank": 84, "score": 213122.1095245434 }, { "content": "pub fn write<W: Write>(mut writer: W, classes: &BTreeMap<String, Class>) -> Result<()> {\n\n write!(\n\n writer,\n\n \"{}\",\n\n r#\"using System;\n\nusing System.Runtime.InteropServices;\n\nusing System.Text;\n\nusing System.IO;\n\n\n\nnamespace LiveSplitCore\n\n{\"#\n\n )?;\n\n\n\n for (class_name, class) in classes {\n\n let class_name_ref = format!(\"{}Ref\", class_name);\n\n let class_name_ref_mut = format!(\"{}RefMut\", class_name);\n\n\n\n write_class_comments(&mut writer, &class.comments)?;\n\n\n\n write!(\n", "file_path": "capi/bind_gen/src/csharp.rs", "rank": 85, "score": 213122.1095245434 }, { "content": "fn parse_bool<S: AsRef<str>>(text: S) -> Result<bool> {\n\n match text.as_ref() {\n\n \"True\" => Ok(true),\n\n \"False\" => Ok(false),\n\n _ => Err(Error::Bool),\n\n }\n\n}\n\n\n", "file_path": "src/run/parser/livesplit.rs", "rank": 86, "score": 211854.26423362474 }, { "content": "fn parse_version<S: AsRef<str>>(version: S) -> Result<Version> {\n\n let splits = version.as_ref().split('.');\n\n let mut v = [1, 0, 0, 0];\n\n for (d, s) in v.iter_mut().zip(splits) {\n\n *d = s.parse()?;\n\n }\n\n Ok(Version(v[0], v[1], v[2], v[3]))\n\n}\n\n\n", "file_path": "src/run/parser/livesplit.rs", "rank": 87, "score": 211854.26423362474 }, { "content": "fn decode_cow_text(cow: Cow<[u8]>) -> Result<Cow<str>> {\n\n Ok(match cow {\n\n Cow::Borrowed(b) => Cow::Borrowed(str::from_utf8(b)?),\n\n Cow::Owned(o) => Cow::Owned(String::from_utf8(o)?),\n\n })\n\n}\n\n\n", "file_path": "src/run/parser/xml_util.rs", "rank": 88, "score": 211051.91058796988 }, { "content": "pub fn write<W: Write>(mut writer: W, classes: &BTreeMap<String, Class>) -> Result<()> {\n\n write!(\n\n writer,\n\n r#\"import LiveSplitCoreNative\n\n\"#\n\n )?;\n\n\n\n for (class_name, class) in classes {\n\n let class_name_ref = format!(\"{}Ref\", class_name);\n\n let class_name_ref_mut = format!(\"{}RefMut\", class_name);\n\n\n\n write_class_comments(&mut writer, &class.comments)?;\n\n\n\n write!(\n\n writer,\n\n r#\"\n\npublic class {class} {{\n\n var ptr: UnsafeMutableRawPointer?\"#,\n\n class = class_name_ref\n\n )?;\n", "file_path": "capi/bind_gen/src/swift/code.rs", "rank": 89, "score": 210712.59455309427 }, { "content": "pub fn write<W: Write>(mut writer: W, classes: &BTreeMap<String, Class>) -> Result<()> {\n\n write!(writer,\n\n \"{}\",\n\n r#\"#include <jni.h>\n\n#include <string>\n\n#include \"livesplit_core.h\"\n\n\n\nusing namespace LiveSplit;\n\n\n\nextern \"C\" JNIEXPORT jlong Java_livesplitcore_LiveSplitCoreNative_Run_1parseString(JNIEnv* jni_env, jobject, jstring data, jstring path, jboolean load_files) {\n\n auto cstr_data = jni_env->GetStringUTFChars(data, nullptr);\n\n auto cstr_path = jni_env->GetStringUTFChars(path, nullptr);\n\n auto result = (jlong)Run_parse(cstr_data, strlen(cstr_data), cstr_path, (uint8_t)load_files);\n\n jni_env->ReleaseStringUTFChars(path, cstr_path);\n\n jni_env->ReleaseStringUTFChars(data, cstr_data);\n\n return result;\n\n}\n\n\"#)?;\n\n\n\n for (class_name, class) in classes {\n", "file_path": "capi/bind_gen/src/jni_cpp.rs", "rank": 90, "score": 210712.5945530943 }, { "content": "pub fn write<W: Write>(mut writer: W, classes: &BTreeMap<String, Class>) -> Result<()> {\n\n write!(\n\n writer,\n\n \"{}\",\n\n r#\"#ifndef LIVESPLIT_CORE_H\n\n#define LIVESPLIT_CORE_H\n\n\n\n#ifdef __cplusplus\n\nnamespace LiveSplit {\n\nextern \"C\" {\n\n#endif\n\n\n\n#include <stdint.h>\n\n#include <stddef.h>\n\n#include <stdbool.h>\n\n\"#\n\n )?;\n\n\n\n for class in classes.values() {\n\n writeln!(writer, \"\")?;\n", "file_path": "capi/bind_gen/src/swift/header.rs", "rank": 91, "score": 210712.5945530943 }, { "content": "fn map_var(var: &str) -> &str {\n\n if var == \"this\" {\n\n \"self\"\n\n } else {\n\n var\n\n }\n\n}\n\n\n", "file_path": "capi/bind_gen/src/python.rs", "rank": 92, "score": 209513.91216538096 }, { "content": "#[test]\n\nfn modifying_last_segments_split_time_clears_run_id() {\n\n let mut run = Run::new();\n\n let mut segment = Segment::new(\"\");\n\n let original_time = Some(TimeSpan::from_seconds(1.0));\n\n segment.set_personal_best_split_time(Time::new().with_real_time(original_time));\n\n run.push_segment(segment);\n\n run.metadata_mut().set_run_id(\"Bla\");\n\n\n\n let mut editor = Editor::new(run).unwrap();\n\n\n\n assert_eq!(editor.run().metadata().run_id(), \"Bla\");\n\n editor.active_segment().set_split_time(original_time);\n\n assert_eq!(editor.run().metadata().run_id(), \"Bla\");\n\n editor\n\n .active_segment()\n\n .set_split_time(Some(TimeSpan::from_seconds(2.0)));\n\n assert_eq!(editor.run().metadata().run_id(), \"\");\n\n}\n", "file_path": "src/run/editor/tests.rs", "rank": 93, "score": 207543.029567954 }, { "content": "fn parsed(run: Run, kind: TimerKind) -> ParsedRun {\n\n ParsedRun { run, kind }\n\n}\n\n\n", "file_path": "src/run/parser/composite.rs", "rank": 94, "score": 206731.31511520146 }, { "content": "fn parse_positive<S>(time: S) -> Result<Option<TimeSpan>, ParseError>\n\nwhere\n\n S: AsRef<str>,\n\n{\n\n let time = TimeSpan::parse_opt(time)?;\n\n if time.map_or(false, |t| t < TimeSpan::zero()) {\n\n Err(ParseError::NegativeTimeNotAllowed)\n\n } else {\n\n Ok(time)\n\n }\n\n}\n", "file_path": "src/run/editor/segment_row.rs", "rank": 95, "score": 204267.67098774438 }, { "content": "pub fn write<W: Write>(mut writer: W, classes: &BTreeMap<String, Class>, opt: &Opt) -> Result<()> {\n\n write!(\n\n writer,\n\n r#\"# coding: utf-8\n\nrequire 'ffi'\n\n\n", "file_path": "capi/bind_gen/src/ruby.rs", "rank": 96, "score": 204056.110592951 }, { "content": "/// Chooses a split color from the Layout Settings based on the current run.\n\n///\n\n/// - `timer`: The current timer.\n\n/// - `time_difference`: The delta that you want to find a color for.\n\n/// - `split_number`: The split number that is associated with this delta.\n\n/// - `show_segment_deltas`: Can show ahead gaining and behind losing colors if\n\n/// true.\n\n/// - `show_best_segments`: Can show the best segment color if true.\n\n/// - `comparison`: The comparison that you are comparing this delta to.\n\n/// - `method`: The timing method of this delta.\n\n///\n\n/// Returns the chosen color.\n\npub fn split_color(\n\n timer: &Timer,\n\n time_difference: Option<TimeSpan>,\n\n split_number: usize,\n\n show_segment_deltas: bool,\n\n show_best_segments: bool,\n\n comparison: &str,\n\n method: TimingMethod,\n\n) -> SemanticColor {\n\n let use_best_segment = true; // TODO Make this a parameter\n\n\n\n if show_best_segments && use_best_segment && check_best_segment(timer, split_number, method) {\n\n SemanticColor::BestSegment\n\n } else if let Some(time_difference) = time_difference {\n\n let last_delta = split_number\n\n .checked_sub(1)\n\n .and_then(|n| last_delta(timer.run(), n, comparison, method));\n\n if time_difference < TimeSpan::zero() {\n\n if show_segment_deltas && last_delta.map_or(false, |d| time_difference > d) {\n\n SemanticColor::AheadLosingTime\n", "file_path": "src/analysis/state_helper.rs", "rank": 97, "score": 203123.27008425718 }, { "content": "#[allow(needless_range_loop)]\n\npub fn calculate(\n\n segments: &[Segment],\n\n predictions: &mut [Option<TimeSpan>],\n\n simple_calculation: bool,\n\n use_current_run: bool,\n\n method: TimingMethod,\n\n) -> Option<TimeSpan> {\n\n predictions[0] = Some(TimeSpan::zero());\n\n let end_index = segments.len();\n\n for segment_index in 0..end_index {\n\n let current_time = predictions[segment_index];\n\n populate_predictions(\n\n segments,\n\n current_time,\n\n segment_index,\n\n predictions,\n\n simple_calculation,\n\n use_current_run,\n\n method,\n\n );\n\n }\n\n predictions[end_index]\n\n}\n", "file_path": "src/analysis/sum_of_segments/best.rs", "rank": 98, "score": 202992.96571683843 }, { "content": "#[allow(needless_range_loop)]\n\npub fn calculate(\n\n segments: &[Segment],\n\n predictions: &mut [Option<TimeSpan>],\n\n use_current_run: bool,\n\n method: TimingMethod,\n\n) -> Option<TimeSpan> {\n\n predictions[0] = Some(TimeSpan::zero());\n\n let end_index = segments.len();\n\n for segment_index in 0..end_index {\n\n let current_time = predictions[segment_index];\n\n populate_predictions(\n\n segments,\n\n current_time,\n\n segment_index,\n\n predictions,\n\n use_current_run,\n\n method,\n\n );\n\n }\n\n predictions[end_index]\n\n}\n", "file_path": "src/analysis/sum_of_segments/worst.rs", "rank": 99, "score": 202992.96571683843 } ]
Rust
warcio/src/record.rs
tari/warcdedupe
e33747e0804965837223c7bc2bca837bf8710aec
use std::cmp; use std::error::Error as StdError; use std::fmt; use std::io::prelude::*; use std::io::Error as IoError; use std::ops::Drop; use buf_redux::BufReader; pub use buf_redux::Buffer; use thiserror::Error; use crate::compression::{self, Compression}; use crate::header::get_record_header; use crate::{FieldName, Header}; use super::HeaderParseError; const SKIP_BUF_LEN: usize = 4096; #[derive(Debug, Error)] pub enum InvalidRecord { #[error("record header is not valid: {0}")] InvalidHeader(#[source] HeaderParseError), #[error("Content-Length is not a valid integer (contained bytes {0:?})")] UnknownLength(Option<Vec<u8>>), #[error("unexpected end of input")] EndOfStream, #[error("I/O error")] IoError(#[source] IoError), } impl From<HeaderParseError> for InvalidRecord { fn from(e: HeaderParseError) -> Self { match e { HeaderParseError::IoError(e) => InvalidRecord::IoError(e), HeaderParseError::Truncated => InvalidRecord::EndOfStream, e => InvalidRecord::InvalidHeader(e), } } } #[derive(Debug)] enum Input<R> where R: BufRead, { Plain(R, Buffer), Compressed(BufReader<flate2::bufread::GzDecoder<R>>), } impl<R> Input<R> where R: BufRead, { fn into_inner(self) -> (R, Buffer) { match self { Input::Plain(r, buf) => (r, buf), Input::Compressed(r) => { let (r, buf) = r.into_inner_with_buffer(); (r.into_inner(), buf) } } } } impl<R> Read for Input<R> where R: BufRead, { fn read(&mut self, buf: &mut [u8]) -> std::io::Result<usize> { match self { Input::Plain(r, _) => r.read(buf), Input::Compressed(r) => r.read(buf), } } } impl<R> BufRead for Input<R> where R: BufRead, { fn fill_buf(&mut self) -> std::io::Result<&[u8]> { match self { Input::Plain(r, _) => r.fill_buf(), Input::Compressed(r) => r.fill_buf(), } } fn consume(&mut self, amt: usize) { match self { Input::Plain(r, _) => r.consume(amt), Input::Compressed(r) => r.consume(amt), } } } #[derive(Debug)] pub struct Record<R> where R: BufRead, { pub header: crate::header::Header, content_length: u64, bytes_remaining: u64, input: Input<R>, debug_info: DebugInfo, } #[cfg(debug_assertions)] #[derive(Clone, Debug, PartialEq, Eq)] struct DebugInfo { consumed_tail: bool, } #[cfg(not(debug_assertions))] #[derive(Clone, Debug, PartialEq, Eq)] struct DebugInfo; impl DebugInfo { #[cfg(debug_assertions)] fn new() -> DebugInfo { DebugInfo { consumed_tail: false, } } #[cfg(debug_assertions)] fn set_consumed_tail(&mut self) { debug_assert!(!self.consumed_tail, "Record tail was already consumed!"); self.consumed_tail = true; } #[cfg(not(debug_assertions))] fn new() -> DebugInfo { DebugInfo } #[cfg(not(debug_assertions))] fn set_consumed_tail(&mut self) {} } impl<R> Read for Record<R> where R: BufRead, { fn read(&mut self, buf: &mut [u8]) -> Result<usize, IoError> { let constrained = if (buf.len() as u64) > self.bytes_remaining { &mut buf[..self.bytes_remaining as usize] } else { buf }; let n = self.input.read(constrained)?; self.bytes_remaining -= n as u64; Ok(n) } } impl<R> BufRead for Record<R> where R: BufRead, { fn fill_buf(&mut self) -> Result<&[u8], IoError> { let buf = self.input.fill_buf()?; let remaining = self.bytes_remaining as usize; let out = if buf.len() > remaining { &buf[..remaining] } else { buf }; debug_assert!(out.len() <= remaining); Ok(out) } fn consume(&mut self, n: usize) { debug_assert!(n <= self.bytes_remaining as usize); self.input.consume(n); self.bytes_remaining -= n as u64; } } #[derive(Debug)] pub enum FinishError { MissingTail, Io(IoError), } impl From<IoError> for FinishError { fn from(e: IoError) -> FinishError { FinishError::Io(e) } } impl fmt::Display for FinishError { fn fmt(&self, f: &mut fmt::Formatter) -> Result<(), fmt::Error> { write!(f, "Error closing WARC record: ")?; match self { FinishError::Io(ref e) => write!(f, "I/O error: {}", e), FinishError::MissingTail => write!(f, "missing record tail"), } } } impl StdError for FinishError { fn cause(&self) -> Option<&dyn StdError> { if let FinishError::Io(e) = self { Some(e) } else { None } } } impl<R> Record<R> where R: BufRead, { pub fn read_from(reader: R, compression: Compression) -> Result<Self, InvalidRecord> { let buffer = Buffer::with_capacity(8 << 10); Self::read_buffered_from(reader, buffer, compression) } pub fn read_buffered_from( reader: R, mut buffer: Buffer, compression: Compression, ) -> Result<Self, InvalidRecord> { let mut input = match compression { Compression::None => Input::Plain(reader, buffer), Compression::Gzip => { buffer.clear(); Input::Compressed(BufReader::with_buffer( buffer, flate2::bufread::GzDecoder::new(reader), )) } }; let header = get_record_header(&mut input)?; let len = match header.content_length_lenient() { None => { return Err(InvalidRecord::UnknownLength( header .get_field_bytes("Content-Length") .map(|bytes| bytes.to_vec()), )); } Some(n) => n, }; let record = Record { content_length: len, bytes_remaining: len, header, input, debug_info: DebugInfo::new(), }; Ok(record) } #[allow(clippy::len_without_is_empty)] pub fn len(&self) -> u64 { self.content_length } pub fn finish(mut self) -> Result<(R, Buffer), FinishError> { self.finish_internal()?; let Record { input, .. } = self; Ok(input.into_inner()) } fn finish_internal(&mut self) -> Result<(), FinishError> { let mut buf = [0u8; SKIP_BUF_LEN]; let mut remaining = self.bytes_remaining; while remaining > 0 { let n = cmp::min(buf.len(), remaining as usize); self.input.read_exact(&mut buf[..n])?; remaining -= n as u64; } self.debug_info.set_consumed_tail(); { let mut buf = [0u8; 4]; if let Err(e) = self.input.read_exact(&mut buf[..]) { if e.kind() == ::std::io::ErrorKind::UnexpectedEof { return Err(FinishError::MissingTail); } return Err(e.into()); } if &buf[..] != b"\r\n\r\n" { return Err(FinishError::MissingTail); } } if let Input::Compressed(ref mut input) = self.input { loop { let n = input.fill_buf()?.len(); if n == 0 { break; } trace!( "compressed record finish consuming {} extra bytes", buf.len() ); input.consume(n); } } Ok(()) } } pub struct RecordWriter<W: Write> { limit: u64, written: u64, writer: compression::Writer<W>, finished: bool, } impl<W: Write> RecordWriter<W> { pub fn new(dest: W, header: &Header, compression: Compression) -> std::io::Result<Self> { let mut dest = compression::Writer::new(dest, compression); write!(&mut dest, "WARC/{}\r\n", header.version())?; for (key, value) in header.iter_field_bytes() { write!(&mut dest, "{}: ", <FieldName as AsRef<str>>::as_ref(key))?; dest.write_all(value)?; write!(&mut dest, "\r\n")?; } write!(&mut dest, "\r\n")?; Ok(RecordWriter { limit: header.content_length(), writer: dest, written: 0, finished: false, }) } } impl<W: Write> Write for RecordWriter<W> { fn write(&mut self, buf: &[u8]) -> std::io::Result<usize> { debug_assert!(self.written <= self.limit); let take = std::cmp::min(buf.len() as u64, self.limit - self.written); let written = self.writer.write(&buf[..take as usize])?; self.written += written as u64; if self.written == self.limit && !self.finished { self.writer.write_all(b"\r\n\r\n")?; self.finished = true; } Ok(written) } fn flush(&mut self) -> std::io::Result<()> { self.writer.flush() } } impl<W: Write> Drop for RecordWriter<W> { fn drop(&mut self) { if self.written < self.limit { error!( "record contents wrote only {} bytes but expected {}", self.written, self.limit ); } } } pub struct RecordReader<R> where R: BufRead { input: R, compression: Compression, } impl<R: BufRead> RecordReader<R> { pub fn new(input: R, compression: Compression) -> Self { RecordReader { input, compression } } pub fn next(&mut self) -> Option<Result<Record<&mut R>, InvalidRecord>> { if self.input.fill_buf().map_or(false, |b| b.is_empty()) { None } else { Some(Record::read_from(&mut self.input, self.compression)) } } }
use std::cmp; use std::error::Error as StdError; use std::fmt; use std::io::prelude::*; use std::io::Error as IoError; use std::ops::Drop; use buf_redux::BufReader; pub use buf_redux::Buffer; use thiserror::Error; use crate::compression::{self, Compression}; use crate::header::get_record_header; use crate::{FieldName, Header}; use super::HeaderParseError; const SKIP_BUF_LEN: usize = 4096; #[derive(Debug, Error)] pub enum InvalidRecord { #[error("record header is not valid: {0}")] InvalidHeader(#[source] HeaderParseError), #[error("Content-Length is not a valid integer (contained bytes {0:?})")] UnknownLength(Option<Vec<u8>>), #[error("unexpected end of input")] EndOfStream, #[error("I/O error")] IoError(#[source] IoError), } impl From<HeaderParseError> for InvalidRecord { fn from(e: HeaderParseError) -> Self { match e { HeaderParseError::IoError(e) => InvalidRecord::IoError(e), HeaderParseError::Truncated => InvalidRecord::EndOfStream, e => InvalidRecord::InvalidHeader(e), } } } #[derive(Debug)] enum Input<R> where R: BufRead, { Plain(R, Buffer), Compressed(BufReader<flate2::bufread::GzDecoder<R>>), } impl<R> Input<R> where R: BufRead, { fn into_inner(self) -> (R, Buffer) { match self { Input::Plain(r, buf) => (r, buf), Input::Compressed(r) => { let (r, buf) = r.into_inner_with_buffer(); (r.into_inner(), buf) } } } } impl<R> Read for Input<R> where R: BufRead, { fn read(&mut self, buf: &mut [u8]) -> std::io::Result<usize> { match self { Input::Plain(r, _) => r.read(buf), Input::Compressed(r) => r.read(buf), } } } impl<R> BufRead for Input<R> where R: BufRead, { fn fill_buf(&mut self) -> std::io::Result<&[u8]> { match self { Input::Plain(r, _) => r.fill_buf(), Input::Compressed(r) => r.fill_buf(), } } fn consume(&mut self, amt: usize) { match self { Input::Plain(r, _) => r.consume(amt), Input::Compressed(r) => r.consume(amt), } } } #[derive(Debug)] pub struct Record<R> where R: BufRead, { pub header: crate::header::Header, content_length: u64, bytes_remaining: u64, input: Input<R>, debug_info: DebugInfo, } #[cfg(debug_assertions)] #[derive(Clone, Debug, PartialEq, Eq)] struct DebugInfo { consumed_tail: bool, } #[cfg(not(debug_assertions))] #[derive(Clone, Debug, PartialEq, Eq)] struct DebugInfo; impl DebugInfo { #[cfg(debug_assertions)] fn new() -> DebugInfo { DebugInfo { consumed_tail: false, } } #[cfg(debug_assertions)] fn set_consumed_tail(&mut self) { debug_assert!(!self.consumed_tail, "Record tail was already consumed!"); self.consumed_tail = true; } #[cfg(not(debug_assertions))] fn new() -> DebugInfo { DebugInfo } #[cfg(not(debug_assertions))] fn set_consumed_tail(&mut self) {} } impl<R> Read for Record<R> where R: BufRead, { fn read(&mut self, buf: &mut [u8]) -> Result<usize, IoError> { let constrained = if (buf.len() as u64) > self.bytes_remaining { &mut buf[..self.bytes_remaining as usize] } else { buf }; let n = self.input.read(constrained)?; self.bytes_remaining -= n as u64; Ok(n) } } impl<R> BufRead for Record<R> where R: BufRead, { fn fill_buf(&mut self) -> Result<&[u8], IoError> { let buf = self.input.fill_buf()?; let remaining = self.bytes_remaining as usize; let out = if buf.len() > remaining { &buf[..remaining] } else { buf }; debug_assert!(out.len() <= remaining); Ok(out) } fn consume(&mut self, n: usize) { debug_assert!(n <= self.bytes_remaining as usize); self.input.consume(n); self.bytes_remaining -= n as u64; } } #[derive(Debug)] pub enum FinishError { MissingTail, Io(IoError), } impl From<IoError> for FinishError { fn from(e: IoError) -> FinishError { FinishError::Io(e) } } impl fmt::Display for FinishError { fn fmt(&self, f: &mut fmt::Formatter) -> Result<(), fmt::Error> { write!(f, "Error closing WARC record: ")?; match self { FinishError::Io(ref e) => write!(f, "I/O error: {}", e), FinishError::MissingTail => write!(f, "missing record tail"), } } } impl StdError for FinishError { fn cause(&self) -> Option<&dyn StdError> { if let FinishError::Io(e) = self { Some(e) } else { None } } } impl<R> Record<R> where R: BufRead, { pub fn read_from(reader: R, compression: Compression) -> Result<Self, InvalidRecord> { let buffer = Buffer::with_capacity(8 << 10); Self::read_buffered_from(reader, buffer, compression) } pub fn read_buffered_from( reader: R, mut buffer: Buffer, compression: Compression, ) -> Result<Self, InvalidRecord> { let mut input = match compression { Compression::None => Input::Plain(reader, buffer), Compression::Gzip => { buffer.clear(); Input::Compressed(BufReader::with_buffer( buffer, flate2::bufread::GzDecoder::new(reader), )) } }; let header = get_record_header(&mut input)?; let len = match header.content_length_lenient() { None => { return
; } Some(n) => n, }; let record = Record { content_length: len, bytes_remaining: len, header, input, debug_info: DebugInfo::new(), }; Ok(record) } #[allow(clippy::len_without_is_empty)] pub fn len(&self) -> u64 { self.content_length } pub fn finish(mut self) -> Result<(R, Buffer), FinishError> { self.finish_internal()?; let Record { input, .. } = self; Ok(input.into_inner()) } fn finish_internal(&mut self) -> Result<(), FinishError> { let mut buf = [0u8; SKIP_BUF_LEN]; let mut remaining = self.bytes_remaining; while remaining > 0 { let n = cmp::min(buf.len(), remaining as usize); self.input.read_exact(&mut buf[..n])?; remaining -= n as u64; } self.debug_info.set_consumed_tail(); { let mut buf = [0u8; 4]; if let Err(e) = self.input.read_exact(&mut buf[..]) { if e.kind() == ::std::io::ErrorKind::UnexpectedEof { return Err(FinishError::MissingTail); } return Err(e.into()); } if &buf[..] != b"\r\n\r\n" { return Err(FinishError::MissingTail); } } if let Input::Compressed(ref mut input) = self.input { loop { let n = input.fill_buf()?.len(); if n == 0 { break; } trace!( "compressed record finish consuming {} extra bytes", buf.len() ); input.consume(n); } } Ok(()) } } pub struct RecordWriter<W: Write> { limit: u64, written: u64, writer: compression::Writer<W>, finished: bool, } impl<W: Write> RecordWriter<W> { pub fn new(dest: W, header: &Header, compression: Compression) -> std::io::Result<Self> { let mut dest = compression::Writer::new(dest, compression); write!(&mut dest, "WARC/{}\r\n", header.version())?; for (key, value) in header.iter_field_bytes() { write!(&mut dest, "{}: ", <FieldName as AsRef<str>>::as_ref(key))?; dest.write_all(value)?; write!(&mut dest, "\r\n")?; } write!(&mut dest, "\r\n")?; Ok(RecordWriter { limit: header.content_length(), writer: dest, written: 0, finished: false, }) } } impl<W: Write> Write for RecordWriter<W> { fn write(&mut self, buf: &[u8]) -> std::io::Result<usize> { debug_assert!(self.written <= self.limit); let take = std::cmp::min(buf.len() as u64, self.limit - self.written); let written = self.writer.write(&buf[..take as usize])?; self.written += written as u64; if self.written == self.limit && !self.finished { self.writer.write_all(b"\r\n\r\n")?; self.finished = true; } Ok(written) } fn flush(&mut self) -> std::io::Result<()> { self.writer.flush() } } impl<W: Write> Drop for RecordWriter<W> { fn drop(&mut self) { if self.written < self.limit { error!( "record contents wrote only {} bytes but expected {}", self.written, self.limit ); } } } pub struct RecordReader<R> where R: BufRead { input: R, compression: Compression, } impl<R: BufRead> RecordReader<R> { pub fn new(input: R, compression: Compression) -> Self { RecordReader { input, compression } } pub fn next(&mut self) -> Option<Result<Record<&mut R>, InvalidRecord>> { if self.input.fill_buf().map_or(false, |b| b.is_empty()) { None } else { Some(Record::read_from(&mut self.input, self.compression)) } } }
Err(InvalidRecord::UnknownLength( header .get_field_bytes("Content-Length") .map(|bytes| bytes.to_vec()), ))
call_expression
[ { "content": "fn run_with_progress<R: std::io::BufRead + std::io::Seek, D, L, W>(\n\n enable: bool,\n\n mut deduplicator: Deduplicator<D, L, W>,\n\n mut input: R,\n\n input_compression: Compression,\n\n) -> Result<(u64, u64), ProcessError>\n\nwhere\n\n R: std::io::BufRead + std::io::Seek,\n\n D: warcdedupe::digest::Digester,\n\n <D as warcdedupe::digest::Digester>::Digest: Clone + Eq,\n\n L: warcdedupe::response_log::ResponseLog<D::Digest>,\n\n W: std::io::Write,\n\n{\n\n if enable {\n\n let input_len = {\n\n use std::io::SeekFrom;\n\n\n\n let n = input.seek(SeekFrom::End(0))?;\n\n input.seek(SeekFrom::Start(0))?;\n\n n\n", "file_path": "warcdedupe/src/main.rs", "rank": 1, "score": 129259.07427573839 }, { "content": "#[test]\n\nfn can_read_record_header() {\n\n let header = b\"WARC/1.0\\r\\n\\\n\n Warc-Type: testdata\\r\\n\\\n\n Content-Length: 6\\r\\n\\\n\n X-Multiline-Test:lol \\r\\n multiline headers\\r\\n\\\n\n \\r\\n\";\n\n\n\n let mut expected = Header::new(Version::WARC1_0);\n\n expected.set_field(\"warc-type\", b\"testdata\".to_vec());\n\n expected.set_field(\"content-length\", b\"6\".to_vec());\n\n expected.set_field(\"x-multiline-test\", b\"lol multiline headers\".to_vec());\n\n\n\n assert_eq!(\n\n get_record_header(&header[..]).expect(\"Should be valid\"),\n\n expected\n\n );\n\n}\n\n\n", "file_path": "warcio/src/tests/read.rs", "rank": 4, "score": 112347.614568193 }, { "content": "fn main() -> Result<(), Box<dyn std::error::Error>> {\n\n pretty_env_logger::init_custom_env(\"WARCDEDUPE_LOG\");\n\n\n\n let matches = app_from_crate!()\n\n .arg(Arg::with_name(\"compress-output\")\n\n .long(\"compress-output\")\n\n .help(\"Write compressed records to non-file output\"))\n\n .arg(Arg::with_name(\"disable-mmap\")\n\n .long(\"disable-mmap\")\n\n .help(\"Never memory-map the input, even if possible\"))\n\n .arg(Arg::with_name(\"disable-progress\")\n\n .long(\"disable-progress\")\n\n .help(\"Do not display progress, even to a terminal\"))\n\n .arg(Arg::with_name(\"infile\")\n\n .required(true)\n\n .help(\"Name of file to read\"))\n\n .arg(Arg::with_name(\"outfile\")\n\n .required(false)\n\n .help(\"Name of file to write, stdout if omitted or '-'\"))\n\n .after_help(\"When output is a file, compression options are ignored. Input and output \\n\\\n", "file_path": "warcdedupe/src/main.rs", "rank": 5, "score": 106624.44297326638 }, { "content": "#[test]\n\nfn extra_buffering_works() {\n\n use std::io::{self, Result};\n\n /// A type to probe the buffering behavior of `get_record_header`.\n\n ///\n\n /// On each `fill_buf` call it transitions to the next state, and\n\n /// after two it is in the terminal state.\n\n #[derive(Debug, PartialEq)]\n\n enum DoubleBuffer<'a> {\n\n /// Nothing read yet.\n\n Start(&'a [u8], &'a [u8]),\n\n /// One whole buffer read.\n\n Second(&'a [u8]),\n\n /// Both buffers read, with n bytes read from the second.\n\n Done(usize),\n\n }\n\n // Only because BufRead: Read\n\n impl<'a> io::Read for DoubleBuffer<'a> {\n\n fn read(&mut self, _: &mut [u8]) -> Result<usize> {\n\n unimplemented!();\n\n }\n", "file_path": "warcio/src/tests/read.rs", "rank": 6, "score": 86190.68172946578 }, { "content": "#[test]\n\nfn truncated_header_is_invalid() {\n\n const BYTES: &[u8] = b\"WARC/1.1\\r\\n\\\n\n Warc-Type: testdata\\r\\n\\r\";\n\n\n\n assert_eq!(get_record_header(BYTES), Err(HeaderParseError::Truncated),);\n\n}\n\n\n", "file_path": "warcio/src/tests/read.rs", "rank": 7, "score": 84385.83045597469 }, { "content": "#[test]\n\nfn header_parse_consumes_full() {\n\n // \"WARC/1.1\" CRLF (=version)\n\n // named-field CRLF (=warc-fields)\n\n // CRLF\n\n let text = b\"\\\n\n WARC/1.1\\r\\n\\\n\n Content-Length: 123\\r\\n\\\n\n \\r\\n\\\n\n \";\n\n\n\n let (header, sz) = Header::parse(&text[..]).expect(\"Parse should succeed\");\n\n assert_eq!(sz, text.len());\n\n let mut test_header = Header::new(Version::WARC1_1);\n\n test_header.set_field(FieldKind::ContentLength, \"123\");\n\n assert_eq!(header, test_header);\n\n}\n\n\n", "file_path": "warcio/src/tests/mod.rs", "rank": 8, "score": 81706.28500165834 }, { "content": "/// Generic log for tracking seen responses.\n\n///\n\n/// While the basic version of this is an in-memory mapping, for very large\n\n/// archives an alternate index may be desired.\n\npub trait ResponseLog<Digest: Eq> {\n\n /// Record a response for the specified URI with digest, captured from\n\n /// the given URL at the given time.\n\n ///\n\n /// Returns None if that response has not been seen before, otherwise the\n\n /// ID of the original record, its URI, and date.\n\n fn add<Id: Into<String>, Uri: Into<String>, Date: Into<String>, IDigest: Into<Digest>>(\n\n &mut self,\n\n record_id: Id,\n\n target_uri: Option<Uri>,\n\n date: Option<Date>,\n\n digest: IDigest,\n\n ) -> Option<(&str, Option<&str>, Option<&str>)>;\n\n}\n\n\n\n/// Basic implementation of a `ResponseLog`.\n\npub struct InMemoryResponseLog<Digest>(HashMap<Digest, RecordInfo>);\n\n\n", "file_path": "warcdedupe/src/response_log.rs", "rank": 9, "score": 70924.92305162892 }, { "content": "#[test]\n\nfn deduplicates_compressed() {\n\n // Two compressed records, both of which are duplicates of a previous one\n\n let mut compressed_input = Vec::<u8>::new();\n\n let mut compress_record = |buf| {\n\n use std::io::Write;\n\n\n\n let mut encoder =\n\n flate2::write::GzEncoder::new(&mut compressed_input, flate2::Compression::fast());\n\n encoder.write_all(buf).unwrap();\n\n };\n\n compress_record(HTTP_RECORD.as_bytes());\n\n compress_record(HTTP_RECORD.as_bytes());\n\n\n\n let mut out = Vec::<u8>::new();\n\n let output_compression = Compression::Gzip;\n\n let mut deduplicator =\n\n Deduplicator::<UnitDigester, _, _>::new(&mut out, AlwaysSeen, output_compression);\n\n\n\n let mut cursor = Cursor::new(&compressed_input);\n\n for _ in 0..2 {\n", "file_path": "warcdedupe/src/test.rs", "rank": 10, "score": 66895.82165827812 }, { "content": "struct RecordInfo {\n\n record_id: String,\n\n target_uri: Option<String>,\n\n date: Option<String>,\n\n}\n\n\n\nimpl<Digest> Default for InMemoryResponseLog<Digest> {\n\n fn default() -> Self {\n\n InMemoryResponseLog(HashMap::new())\n\n }\n\n}\n\n\n\nimpl<Digest> InMemoryResponseLog<Digest> {\n\n pub fn new() -> Self {\n\n Default::default()\n\n }\n\n}\n\n\n\nimpl<Digest: Eq + Hash> ResponseLog<Digest> for InMemoryResponseLog<Digest> {\n\n fn add<T, U, V, W>(\n", "file_path": "warcdedupe/src/response_log.rs", "rank": 11, "score": 66722.56565896266 }, { "content": "#[test]\n\nfn deduplicates_simple_warc() {\n\n const PNG_WARC_GZ: &[u8] = include_bytes!(\"png2.warc\");\n\n let mut out: Vec<u8> = vec![];\n\n let response_log: InMemoryResponseLog<_> = Default::default();\n\n\n\n let mut deduplicator =\n\n Deduplicator::<LengthSha1Digester, _, _>::new(&mut out, response_log, Compression::Gzip);\n\n let (n_copied, n_deduplicated) = deduplicator\n\n .read_stream(Cursor::new(PNG_WARC_GZ), Compression::None)\n\n .expect(\"read_stream returned an unexpected error\");\n\n\n\n assert_eq!(n_copied, 7);\n\n assert_eq!(n_deduplicated, 1);\n\n\n\n let mut reader = RecordReader::new(&out[..], Compression::Gzip);\n\n let mut i = 0;\n\n const EXPECTED_TYPES: &[RecordKind] = &[\n\n RecordKind::Info, // Leading warcinfo\n\n RecordKind::Request, // First request for resource\n\n RecordKind::Response, // Response for resource\n", "file_path": "warcdedupe/tests/simple_dedupe.rs", "rank": 12, "score": 62482.36344956778 }, { "content": "#[test]\n\nfn incorrect_signature_is_invalid() {\n\n assert_eq!(\n\n Version::parse(b\"\\x89PNG\\r\\n\\x1a\\n\"),\n\n Err(HeaderParseError::InvalidSignature(\"\\u{fffd}PNG\\r\".into()))\n\n );\n\n assert_eq!(\n\n Version::parse(b\"WARC/1.0a\\r\\n\"),\n\n Err(HeaderParseError::InvalidSignature(\"WARC/1.0a\\r\".into()))\n\n );\n\n}\n\n\n", "file_path": "warcio/src/tests/read.rs", "rank": 13, "score": 62248.44979629478 }, { "content": "#[test]\n\nfn invalid_fields_are_invalid() {\n\n assert_eq!(\n\n Header::parse_field(b\"This is not a valid field\"),\n\n Err(HeaderParseError::MalformedField)\n\n );\n\n\n\n assert_eq!(\n\n Header::parse_field(b\"X-Invalid-UTF-8\\xFF: yes\"),\n\n Err(HeaderParseError::MalformedField)\n\n );\n\n}\n", "file_path": "warcio/src/tests/read.rs", "rank": 14, "score": 62248.44979629478 }, { "content": "#[test]\n\nfn header_adjusts_bare_uri_brackets() {\n\n let mut header = Header::new(Version::WARC1_0);\n\n header.set_field(FieldKind::TargetURI, \"http://example.com\");\n\n\n\n assert_eq!(\n\n header.get_field(FieldKind::TargetURI),\n\n Some(\"http://example.com\")\n\n );\n\n assert_eq!(\n\n header.get_field_bytes_raw(FieldKind::TargetURI),\n\n Some(&b\"<http://example.com>\"[..])\n\n );\n\n\n\n header.set_version(Version::WARC1_1);\n\n assert_eq!(\n\n header.get_field(FieldKind::TargetURI),\n\n Some(\"http://example.com\")\n\n );\n\n assert_eq!(\n\n header.get_field_bytes_raw(FieldKind::TargetURI),\n\n Some(&b\"http://example.com\"[..])\n\n );\n\n}\n", "file_path": "warcio/src/tests/mod.rs", "rank": 15, "score": 57010.1237559282 }, { "content": "// We use an IndexMap to preserve the read order of fields when writing them back out;\n\n// std::collections::HashMap randomizes ordering.\n\ntype FieldMap = IndexMap<FieldName, Vec<u8>>;\n\n\n\n/// The header of a WARC record.\n\n///\n\n/// Field values can be accessed using the [`get_field`](Self::get_field) family of functions, or\n\n/// accessed in parsed form through specific methods such as\n\n/// [`content_length`](Self::content_length). Field values can be modified using the\n\n/// [`set_field`](Self::set_field) method, or fields can be removed entirely with [`remove_field`](\n\n/// Self::remove_field).\n\n///\n\n/// ```\n\n/// # use warcio::{Header, Version, FieldName, FieldKind};\n\n/// # fn main() -> Result<(), Box<dyn std::error::Error>> {\n\n/// // Parse a header from bytes\n\n/// let raw_header = b\"\\\n\n/// WARC/1.1\\r\n\n/// WARC-Record-ID: <urn:uuid:b4beb26f-54c4-4277-8e23-51aa9fc4476d>\\r\n\n/// WARC-Date: 2021-08-05T06:22Z\\r\n\n/// WARC-Type: resource\\r\n\n/// Content-Length: 0\\r\n", "file_path": "warcio/src/header.rs", "rank": 16, "score": 51552.37306445383 }, { "content": "#[derive(Debug, PartialEq, Eq)]\n\nenum ProcessOutcome {\n\n Deduplicated,\n\n NeedsCopy,\n\n}\n\n\n\n#[derive(Debug, Error)]\n\npub enum ProcessError {\n\n #[error(\"record is malformed\")]\n\n InvalidRecord(#[from] InvalidRecord),\n\n #[error(\"input was truncated\")]\n\n Truncated,\n\n #[error(\"I/O error\")]\n\n IoError(#[from] std::io::Error),\n\n}\n\n\n\nimpl From<FinishError> for ProcessError {\n\n fn from(e: FinishError) -> Self {\n\n match e {\n\n FinishError::Io(e) => ProcessError::IoError(e),\n\n FinishError::MissingTail => ProcessError::Truncated,\n\n }\n\n }\n\n}\n\n\n\n#[cfg(test)]\n\nmod test;\n", "file_path": "warcdedupe/src/lib.rs", "rank": 17, "score": 45160.94119987896 }, { "content": "/// A ResponseLog that panics if a record is checked against it.\n\nstruct PanickingLog;\n\n\n\nimpl<T: Eq> ResponseLog<T> for PanickingLog {\n\n fn add<Id: Into<String>, Uri: Into<String>, Date: Into<String>, IDigest: Into<T>>(\n\n &mut self,\n\n _: Id,\n\n _: Option<Uri>,\n\n _: Option<Date>,\n\n _: IDigest,\n\n ) -> Option<(&str, Option<&str>, Option<&str>)> {\n\n unimplemented!()\n\n }\n\n}\n\n\n", "file_path": "warcdedupe/src/test.rs", "rank": 18, "score": 43701.94121854655 }, { "content": "/// A Digester for which records may never be deduplicated.\n\nstruct IneligibleDigester;\n\n\n\nimpl Digester for IneligibleDigester {\n\n type Digest = ();\n\n\n\n fn new(_: &Header) -> Option<Self> {\n\n None\n\n }\n\n\n\n fn handle_data(&mut self, _: &[u8]) {\n\n unreachable!()\n\n }\n\n fn finalize(self) -> Self::Digest {\n\n unreachable!()\n\n }\n\n fn format_digest(_: &Self::Digest) -> String {\n\n unreachable!()\n\n }\n\n}\n\n\n", "file_path": "warcdedupe/src/test.rs", "rank": 19, "score": 43701.94121854655 }, { "content": "/// A ResponseLog that has always seen a record before with fixed properties.\n\nstruct AlwaysSeen;\n\n\n\nimpl AlwaysSeen {\n\n const RECORD_ID: &'static str = \"urn:fake\";\n\n const URL: Option<&'static str> = Some(\"http://example.com\");\n\n const DATE: Option<&'static str> = Some(\"fakedate\");\n\n}\n\n\n\nimpl<T: Eq> ResponseLog<T> for AlwaysSeen {\n\n fn add<Id: Into<String>, Uri: Into<String>, Date: Into<String>, IDigest: Into<T>>(\n\n &mut self,\n\n _: Id,\n\n _: Option<Uri>,\n\n _: Option<Date>,\n\n _: IDigest,\n\n ) -> Option<(&str, Option<&str>, Option<&str>)> {\n\n Some((Self::RECORD_ID, Self::URL, Self::DATE))\n\n }\n\n}\n\n\n", "file_path": "warcdedupe/src/test.rs", "rank": 20, "score": 43701.86046959512 }, { "content": "/// A Digester that digests to `()`.\n\nstruct UnitDigester;\n\n\n\nimpl Digester for UnitDigester {\n\n type Digest = ();\n\n\n\n fn new(_: &Header) -> Option<Self> {\n\n Some(Self)\n\n }\n\n\n\n fn handle_data(&mut self, _: &[u8]) {}\n\n\n\n fn finalize(self) -> Self::Digest {\n\n ()\n\n }\n\n\n\n fn format_digest(_digest: &Self::Digest) -> String {\n\n \"nop:\".into()\n\n }\n\n}\n\n\n", "file_path": "warcdedupe/src/test.rs", "rank": 21, "score": 43698.96507077209 }, { "content": "struct SequentialMmap {\n\n map: memmap2::Mmap,\n\n}\n\n\n\nimpl SequentialMmap {\n\n /// This is unsafe because some uses can trigger undefined behavior if another mapping of the\n\n /// same file (perhaps in another process) mutates what appears to Rust to be an immutable\n\n /// slice. See https://users.rust-lang.org/t/how-unsafe-is-mmap/19635 for detailed discussion.\n\n unsafe fn of_file(file: &File) -> std::io::Result<SequentialMmap> {\n\n let map = memmap2::Mmap::map(file)?;\n\n // We do sequential access, so advise the OS of that where such a mechanism exists.\n\n #[cfg(unix)]\n\n {\n\n use nix::sys::mman::{madvise, MmapAdvise};\n\n let _ = madvise(\n\n map.as_ptr() as *mut _,\n\n map.len(),\n\n MmapAdvise::MADV_SEQUENTIAL,\n\n );\n\n }\n", "file_path": "warcdedupe/src/main.rs", "rank": 22, "score": 43698.96507077209 }, { "content": "fn main() {\n\n let base_path: PathBuf = env::var(\"OUT_DIR\").unwrap().into();\n\n let ini_dir = \"data/\";\n\n println!(\"cargo:rerun-if-changed={}\", ini_dir);\n\n\n\n for entry in std::fs::read_dir(ini_dir).expect(\"failed to read data dir\") {\n\n let entry = entry.expect(\"error reading directory entry\");\n\n let ini_path = entry.path();\n\n // Only try to read *.ini\n\n if ini_path.extension().map(|ext| ext != \"ini\").unwrap_or(true) {\n\n continue;\n\n }\n\n\n\n let ini = Ini::load_from_file(&ini_path).unwrap();\n\n\n\n let out_path = base_path.to_owned().join(\n\n ini.general_section()\n\n .get(\"file\")\n\n .expect(\"file property missing from ini general section\"),\n\n );\n", "file_path": "warcio/build.rs", "rank": 23, "score": 43514.72683185608 }, { "content": "#[test]\n\nfn deduplicates_duplicate() {\n\n fn run_with_compression(output_compression: Compression) {\n\n println!(\"{:?}\", output_compression);\n\n\n\n let mut out = Vec::<u8>::new();\n\n let mut deduplicator =\n\n Deduplicator::<UnitDigester, _, _>::new(&mut out, AlwaysSeen, output_compression);\n\n let deduplicated = deduplicator\n\n .read_record(Cursor::new(HTTP_RECORD.as_bytes()), Compression::None)\n\n .expect(\"should read record okay\");\n\n assert!(deduplicated, \"record should have been deduplicated\");\n\n\n\n println!(\"Output record:\\n{:?}\", &out);\n\n let mut reparse_cursor = Cursor::new(&out);\n\n let mut reparsed = Record::read_from(&mut reparse_cursor, output_compression)\n\n .expect(\"should be able to parse an emitted revisit record\");\n\n\n\n //assert_eq!(reparsed, ...)\n\n let mut reparsed_contents = Vec::new();\n\n reparsed.read_to_end(&mut reparsed_contents).unwrap();\n", "file_path": "warcdedupe/src/test.rs", "rank": 24, "score": 40789.08861232923 }, { "content": "#[test]\n\nfn copies_ineligible() {\n\n let mut out = Vec::<u8>::new();\n\n let mut deduplicator =\n\n Deduplicator::<IneligibleDigester, _, _>::new(&mut out, AlwaysSeen, Compression::None);\n\n let deduplicated = deduplicator\n\n .read_record(Cursor::new(HTTP_RECORD.as_bytes()), Compression::None)\n\n .expect(\"should read record okay\");\n\n\n\n assert!(!deduplicated);\n\n assert_eq!(\n\n out,\n\n HTTP_RECORD.as_bytes(),\n\n \"ineligible record should be copied to output\"\n\n );\n\n}\n\n\n", "file_path": "warcdedupe/src/test.rs", "rank": 25, "score": 40789.08861232923 }, { "content": "pub trait Digester: Sized {\n\n type Digest: Debug + Eq + Clone;\n\n\n\n /// Create a new digester, or return None if the record is not eligible\n\n /// for deduplication.\n\n fn new(x: &Header) -> Option<Self>;\n\n /// Collect data from a record body and accumulate it into the digest.\n\n fn handle_data(&mut self, data: &[u8]);\n\n /// Compute the final digest from the initial state and any accumulated\n\n /// data.\n\n fn finalize(self) -> Self::Digest;\n\n\n\n /// Write a digest to the provided writer as a `labelled-digest` as specified\n\n /// by WARC 1.1 section 5.8.\n\n fn format_digest(digest: &Self::Digest) -> String;\n\n\n\n /// Compute the digest of a record and return the digest, or None if the record is not\n\n /// eligible for deduplication (according to [`Self::new`]).\n\n fn digest_record<Input: BufRead>(\n\n record: &mut Record<Input>,\n", "file_path": "warcdedupe/src/digest.rs", "rank": 26, "score": 39843.878923699864 }, { "content": "#[test]\n\nfn writes_well_formed_warc1_1() {\n\n let mut header = Header::new(Version::WARC1_1);\n\n header.set_field(FieldKind::ContentLength, &b\"8\"[..]);\n\n\n\n let mut write_buf = Vec::new();\n\n let mut body = header\n\n .write_to(&mut write_buf, Compression::None)\n\n .expect(\"failed to write record header\");\n\n body.write_all(b\"abcdefgh\").unwrap();\n\n assert_eq!(body.write(b\"IGNOREME\").unwrap(), 0);\n\n drop(body);\n\n\n\n assert_eq!(\n\n String::from_utf8_lossy(&write_buf),\n\n \"WARC/1.1\\r\n\nContent-Length: 8\\r\n\n\\r\n\nabcdefgh\\r\n\n\\r\n\n\"\n", "file_path": "warcio/src/tests/write.rs", "rank": 27, "score": 37556.96767316959 }, { "content": " Compression::Gzip => Self::Gzip(GzEncoder::new(dest, flate2::Compression::best())),\n\n }\n\n }\n\n\n\n /// Gracefully close the writer (terminating a compressed stream) and return the output stream.\n\n pub fn finish(self) -> IoResult<W> {\n\n match self {\n\n Self::Plain(w) => Ok(w),\n\n Self::Gzip(gz) => gz.finish(),\n\n }\n\n }\n\n}\n\n\n\nimpl<W: Write> Write for Writer<W> {\n\n fn write(&mut self, buf: &[u8]) -> IoResult<usize> {\n\n match self {\n\n Writer::Plain(w) => w.write(buf),\n\n Writer::Gzip(w) => w.write(buf),\n\n }\n\n }\n\n\n\n fn flush(&mut self) -> IoResult<()> {\n\n match self {\n\n Writer::Plain(w) => w.flush(),\n\n Writer::Gzip(w) => w.flush(),\n\n }\n\n }\n\n}\n", "file_path": "warcio/src/compression.rs", "rank": 28, "score": 28906.4904146814 }, { "content": "//! Handling of record compression.\n\n//!\n\n//! WARC files can be compressed, but the structure of the compressed data must be managed\n\n//! to ensure a record can be accessed without decompressing every previous one in a file\n\n//! (which may contain many records).\n\n//!\n\n//! In general, records are individually compressed to ensure they can be the subject of random\n\n//! access in a file containing many records. Provided the file offset of a compressed record is\n\n//! known, a reading tool can read a record alone. If records were not compressed individually,\n\n//! readers would need to decompress every preceding record in a file in order to reach a desired\n\n//! one.\n\n\n\nuse std::io::{Result as IoResult, Write};\n\nuse std::path::Path;\n\n\n\nuse flate2::write::GzEncoder;\n\n\n\n/// The supported methods of compressing a single [`Record`](crate::Record).\n\n#[derive(Debug, PartialEq, Eq, Clone, Copy)]\n\npub enum Compression {\n", "file_path": "warcio/src/compression.rs", "rank": 29, "score": 28901.074098689514 }, { "content": " /// Uncompressed data\n\n None,\n\n /// `gzip` compression\n\n ///\n\n /// gzip uses DEFLATE compression which is relatively simple but doesn't have particularly good\n\n /// compression. Each record has a gzip header and footer that include some uninteresting\n\n /// fields but also include a checksum.\n\n Gzip,\n\n // TODO zstd mode https://iipc.github.io/warc-specifications/specifications/warc-zstd/\n\n}\n\n\n\nimpl Compression {\n\n /// Return the best guess of compression to be used for a file with the given name.\n\n ///\n\n /// A file that may be present is not accessed in any way; only the path is used to guess based\n\n /// on the name.\n\n ///\n\n /// ```\n\n /// # use warcio::Compression;\n\n /// assert_eq!(Compression::guess_for_filename(\"test.warc.gz\"), Compression::Gzip);\n", "file_path": "warcio/src/compression.rs", "rank": 30, "score": 28896.086674641127 }, { "content": " /// ```\n\n pub fn guess_for_filename<P: AsRef<Path>>(path: P) -> Compression {\n\n match path.as_ref().extension() {\n\n Some(ext) if ext == \"gz\" => Compression::Gzip,\n\n _ => Compression::None,\n\n }\n\n }\n\n}\n\n\n\n/// Writes to an output stream with specified [`Compression`].\n\npub enum Writer<W: Write> {\n\n Plain(W),\n\n Gzip(GzEncoder<W>),\n\n}\n\n\n\nimpl<W: Write> Writer<W> {\n\n /// Construct a writer to the given adapter with the given compression mode.\n\n pub fn new(dest: W, mode: Compression) -> Self {\n\n match mode {\n\n Compression::None => Self::Plain(dest),\n", "file_path": "warcio/src/compression.rs", "rank": 31, "score": 28892.875685474948 }, { "content": "fn open_output_stream(p: Option<&OsStr>) -> Box<dyn Write> {\n\n if let Some(p) = p {\n\n Box::new(BufWriter::new(\n\n File::create(&p).expect(\"Failed to create output file\"),\n\n ))\n\n } else {\n\n // Locking stdout takes a ref to the instance, so it must be static\n\n lazy_static! {\n\n static ref STDOUT: std::io::Stdout = std::io::stdout();\n\n }\n\n Box::new(STDOUT.lock())\n\n }\n\n}\n\n\n", "file_path": "warcdedupe/src/main.rs", "rank": 54, "score": 27489.349179254365 }, { "content": " }\n\n impl<'a> io::BufRead for DoubleBuffer<'a> {\n\n fn fill_buf(&mut self) -> Result<&[u8]> {\n\n eprintln!(\"fill_buf {:?}\", self);\n\n match self {\n\n &mut DoubleBuffer::Start(fst, _) => Ok(fst),\n\n &mut DoubleBuffer::Second(snd) => Ok(snd),\n\n &mut DoubleBuffer::Done(_) => panic!(\"Should not fill after snd\"),\n\n }\n\n }\n\n\n\n fn consume(&mut self, amt: usize) {\n\n eprintln!(\"consume {} {:?}\", amt, self);\n\n let next = match *self {\n\n DoubleBuffer::Start(fst, snd) => {\n\n assert_eq!(amt, fst.len());\n\n DoubleBuffer::Second(snd)\n\n }\n\n DoubleBuffer::Second(snd) => DoubleBuffer::Done(snd.len() - amt),\n\n DoubleBuffer::Done(_) => panic!(\"Should not consume after snd\"),\n", "file_path": "warcio/src/tests/read.rs", "rank": 55, "score": 27322.34546710944 }, { "content": " };\n\n *self = next;\n\n }\n\n }\n\n\n\n let mut reader = DoubleBuffer::Start(\n\n b\"\\\n\n WARC/1.0\\r\\n\\\n\n X-First-Header: yes\\r\\n\\\n\n X-Second-Header:yes\\r\\n\\\n\n \\r\",\n\n // Header termination spans two buffers\n\n // to catch potential errors in splitting.\n\n b\"\\nIGNORED_DATA\",\n\n );\n\n get_record_header(&mut reader).expect(\"failed to parse valid header\");\n\n assert_eq!(reader, DoubleBuffer::Done(12));\n\n}\n\n\n", "file_path": "warcio/src/tests/read.rs", "rank": 56, "score": 27312.757853225314 }, { "content": "use crate::header::{get_record_header, Header};\n\nuse crate::version::Version;\n\nuse crate::HeaderParseError;\n\n\n\n#[test]\n", "file_path": "warcio/src/tests/read.rs", "rank": 57, "score": 27300.819135215344 }, { "content": "/// A header field.\n\n///\n\n/// The name of a field is case-insensitive, and its value may be any bytes.\n\n///\n\n/// This type is a convenience for parsing; actual header fields are stored in\n\n/// a map inside the record header.\n\n#[derive(Debug, PartialEq, Eq)]\n\npub(crate) struct Field {\n\n name: FieldName,\n\n value: Vec<u8>,\n\n}\n\n\n\n/// Parse a WARC record header out of the provided `BufRead`.\n\n///\n\n/// Consumes the bytes that are parsed, leaving the reader at the beginning\n\n/// of the record payload. In case of an error in parsing, some or all of the\n\n/// input may be consumed.\n\n// TODO put this on a RecordReader type or something\n\npub(crate) fn get_record_header<R: BufRead>(mut reader: R) -> Result<Header, HeaderParseError> {\n\n enum FirstChanceOutcome {\n", "file_path": "warcio/src/header.rs", "rank": 58, "score": 26869.826786156787 }, { "content": " // buffer but still buffered so we can give bytes back at the end.\n\n loop {\n\n // Tracks the number of bytes we've read that definitely aren't a complete header\n\n let bytes_consumed = owned_buf.len();\n\n // Grab some data out of the reader and copy into the owned buffer\n\n owned_buf.extend(reader.fill_buf()?);\n\n if owned_buf.len() == bytes_consumed {\n\n // Read returned 0 bytes\n\n return Err(HeaderParseError::Truncated);\n\n }\n\n\n\n // Try to parse what we have buffered\n\n match Header::parse(&owned_buf) {\n\n Ok((parsed, n)) => {\n\n reader.consume(n - bytes_consumed);\n\n return Ok(parsed);\n\n }\n\n Err(HeaderParseError::Truncated) => {}\n\n Err(e) => return Err(e),\n\n }\n\n\n\n // Otherwise keep looking\n\n reader.consume(owned_buf.len() - bytes_consumed);\n\n // TODO enforce maximum vec size? (to avoid unbounded memory use on malformed input)\n\n }\n\n}\n", "file_path": "warcio/src/header.rs", "rank": 59, "score": 26862.297781294368 }, { "content": " version: Version,\n\n fields: FieldMap,\n\n}\n\n\n\nimpl Header {\n\n pub fn new<V: Into<Version>>(version: V) -> Self {\n\n Header {\n\n version: version.into(),\n\n fields: Default::default(),\n\n }\n\n }\n\n\n\n /// Parse a header from bytes, returning the header and the number of bytes consumed.\n\n pub fn parse(mut bytes: &[u8]) -> Result<(Header, usize), HeaderParseError> {\n\n let (version_consumed, version) = Version::parse(bytes)?;\n\n bytes = &bytes[version_consumed..];\n\n\n\n let mut fields: FieldMap = Default::default();\n\n let mut headers_consumed = 0;\n\n loop {\n", "file_path": "warcio/src/header.rs", "rank": 60, "score": 26860.676322221305 }, { "content": " Success(usize, Header),\n\n KeepLooking(Vec<u8>),\n\n }\n\n\n\n // First-chance: without copying anything, operating only from the input's buffer\n\n let outcome = {\n\n let buf = reader.fill_buf()?;\n\n if buf.is_empty() {\n\n return Err(HeaderParseError::Truncated);\n\n }\n\n // Weird split of parse and consume here is necessary because buf\n\n // is borrowed from the reader so we can't consume until we no\n\n // longer hold a reference to the buffer.\n\n match Header::parse(buf) {\n\n Ok((parsed, n)) => FirstChanceOutcome::Success(n, parsed),\n\n Err(HeaderParseError::Truncated) => {\n\n // Copy the input we've already searched into a buffer to continue past it\n\n let owned_buf: Vec<u8> = buf.into();\n\n reader.consume(owned_buf.len());\n\n FirstChanceOutcome::KeepLooking(owned_buf)\n", "file_path": "warcio/src/header.rs", "rank": 61, "score": 26860.013936137973 }, { "content": " pub(crate) fn parse_field(bytes: &[u8]) -> Result<(&[u8], Vec<u8>, usize), HeaderParseError> {\n\n if bytes.is_empty() {\n\n return Err(HeaderParseError::Truncated);\n\n }\n\n\n\n // field-name: at least one token, which is an ASCII value excluding CTL or SEPARATORS\n\n let name_end = match bytes\n\n .iter()\n\n .position(|b| !b.is_ascii() || CTL.contains(b) || SEPARATORS.contains(b))\n\n {\n\n Some(i) => i,\n\n None => return Err(HeaderParseError::MalformedField),\n\n };\n\n // literal colon must follow field-name\n\n match bytes.get(name_end) {\n\n None => return Err(HeaderParseError::Truncated),\n\n Some(b':') => { /* Correctly formed */ }\n\n Some(_) => return Err(HeaderParseError::MalformedField),\n\n }\n\n\n", "file_path": "warcio/src/header.rs", "rank": 62, "score": 26858.816400826337 }, { "content": " }\n\n Err(e) => return Err(e),\n\n }\n\n };\n\n\n\n let mut owned_buf = match outcome {\n\n FirstChanceOutcome::Success(sz, header) => {\n\n trace!(\"Found complete header in buffer, {} bytes\", sz);\n\n reader.consume(sz);\n\n return Ok(header);\n\n }\n\n FirstChanceOutcome::KeepLooking(buf) => buf,\n\n };\n\n trace!(\n\n \"First-chance read unsuccessful yielding {} bytes\",\n\n owned_buf.len()\n\n );\n\n\n\n // Second chance: need to start copying out of the reader's buffer. Throughout this loop,\n\n // we've grabbed some number of bytes and own them with a tail copied out of the reader's\n", "file_path": "warcio/src/header.rs", "rank": 63, "score": 26857.71176419429 }, { "content": " pub fn write_to<W: std::io::Write>(\n\n &self,\n\n dest: W,\n\n compression: Compression,\n\n ) -> std::io::Result<RecordWriter<W>> {\n\n RecordWriter::new(dest, self, compression)\n\n }\n\n\n\n /// Get the value of a header field as bytes, or None if no such header exists.\n\n ///\n\n /// Although the WARC specification does not permit values that are not also valid Rust strings,\n\n /// users that wish to be lenient in accepting malformed records may wish to relax that\n\n /// requirement by using this function.\n\n ///\n\n /// ## URL translation\n\n ///\n\n /// For fields that are [defined to contain a bare URI by the\n\n /// specification](FieldName::value_is_bare_uri), this function will strip surrounding angle\n\n /// brackets from the value if the [WARC version](Version) of the record is less than 1.1\n\n /// and they are present. This hides the changed definition of a URL in the standard from\n", "file_path": "warcio/src/header.rs", "rank": 64, "score": 26855.95384525009 }, { "content": " /// rarely be required.\n\n pub fn get_field<F: Into<FieldName>>(&self, field: F) -> Option<&str> {\n\n str::from_utf8(self.get_field_bytes(field)?).ok()\n\n }\n\n\n\n /// Return `true` if a field with the given name currently exists in this header.\n\n pub fn field_exists<F: Into<FieldName>>(&self, field: F) -> bool {\n\n self.get_field_bytes(field).is_some()\n\n }\n\n\n\n /// Set the value of a header field, returning the old value (if any).\n\n ///\n\n /// This function will panic if the provided name contains characters that are not\n\n /// permitted in `field-name` context. The value will have angle brackets added if\n\n /// the field value is a [bare URI](FieldName::value_is_bare_uri) and the record's WARC\n\n /// version is pre-1.1, performing the opposite transformation of\n\n /// [`get_field_bytes`](Header::get_field_bytes).\n\n pub fn set_field<N: Into<FieldName>, V: Into<Vec<u8>>>(\n\n &mut self,\n\n name: N,\n", "file_path": "warcio/src/header.rs", "rank": 65, "score": 26855.675255348004 }, { "content": "//! WARC record header data structures.\n\n\n\nuse std::borrow::Borrow;\n\nuse std::io::BufRead;\n\nuse std::str;\n\n\n\nuse indexmap::map::IndexMap;\n\n\n\npub use fieldkind::FieldKind;\n\npub use fieldname::FieldName;\n\npub use recordkind::RecordKind;\n\npub use recordtype::RecordType;\n\n\n\nuse crate::compression::Compression;\n\nuse crate::record::RecordWriter;\n\nuse crate::version::Version;\n\nuse crate::HeaderParseError;\n\n\n\nuse super::{CTL, SEPARATORS};\n\n\n\nmod fieldkind;\n\nmod fieldname;\n\nmod recordkind;\n\nmod recordtype;\n\n\n\n// We use an IndexMap to preserve the read order of fields when writing them back out;\n\n// std::collections::HashMap randomizes ordering.\n", "file_path": "warcio/src/header.rs", "rank": 66, "score": 26853.2518518102 }, { "content": " let mut chunk_start = name_end + 1;\n\n let mut value: Vec<u8> = vec![];\n\n let consumed = loop {\n\n // Trim leading whitespace\n\n chunk_start += match bytes[chunk_start..]\n\n .iter()\n\n .position(|&x| x != b' ' && x != b'\\t')\n\n {\n\n None => return Err(HeaderParseError::Truncated),\n\n Some(idx) => idx,\n\n };\n\n\n\n // Take data until CRLF\n\n let chunk_end = match bytes[chunk_start..].windows(2).position(|s| s == b\"\\r\\n\") {\n\n Some(idx) => chunk_start + idx,\n\n None => return Err(HeaderParseError::Truncated),\n\n };\n\n value.extend_from_slice(&bytes[chunk_start..chunk_end]);\n\n\n\n // Stop if the following byte after CRLF isn't LWS, otherwise continue since it's a\n", "file_path": "warcio/src/header.rs", "rank": 67, "score": 26852.99797337664 }, { "content": " .expect(\"record header does not have a WARC-Record-ID\")\n\n }\n\n\n\n /// Get the record [`Content-Length`](FieldKind::ContentLength) or panic.\n\n ///\n\n /// `Content-Length` is a mandatory WARC field, so if it is not present or does not\n\n /// represent a valid length, this function will panic. If the caller wishes to be\n\n /// lenient and accept records without comprehensible length, use\n\n /// [`content_length_lenient`](Header::content_length_lenient) or\n\n /// [`get_field`](Header::get_field) to read as an optional value instead.\n\n pub fn content_length(&self) -> u64 {\n\n self.get_field(FieldKind::ContentLength)\n\n .expect(\"record header does not have a Content-Length\")\n\n .parse()\n\n .expect(\"record Content-Length is not a valid integer\")\n\n }\n\n\n\n /// Get the record `Content-Length`, if valid.\n\n ///\n\n /// If not present or not parseable as an integer, returns None. If the None\n", "file_path": "warcio/src/header.rs", "rank": 68, "score": 26852.55212846694 }, { "content": " }\n\n\n\n pub fn remove_field<N: Borrow<FieldName>>(&mut self, name: N) -> Option<Vec<u8>> {\n\n self.fields.shift_remove(name.borrow())\n\n }\n\n\n\n /// Get an iterator over the fields in this header.\n\n ///\n\n /// In comparison to [`get_field_bytes`](Self::get_field_bytes), the values yielded by this\n\n /// iterator will have the raw value to be read or written from a serialized record, including\n\n /// angle brackets or not for values which are [bare URIs](FieldName::value_is_bare_uri) based\n\n /// on the WARC version.\n\n pub fn iter_field_bytes(&self) -> impl Iterator<Item = (&FieldName, &[u8])> {\n\n self.fields.iter().map(|(k, v)| (k, v.as_slice()))\n\n }\n\n\n\n /// Get an iterator over mutable field values.\n\n ///\n\n /// As with [`iter_field_bytes`](Self::iter_field_bytes), the yielded values are not transformed\n\n /// URIs if the field is a bare URI like they would be if retrieved by\n", "file_path": "warcio/src/header.rs", "rank": 69, "score": 26851.751212367588 }, { "content": " // folded line.\n\n match bytes.get(chunk_end + 2) {\n\n // LWS follows: this is a folded line. Advance to it.\n\n Some(b' ') | Some(b'\\t') => {\n\n chunk_start = chunk_end + 2;\n\n continue;\n\n }\n\n // Non-LWS: end of this field\n\n Some(_) => break chunk_end + 2,\n\n // Absent: can't tell\n\n None => return Err(HeaderParseError::Truncated),\n\n }\n\n };\n\n\n\n Ok((&bytes[..name_end], value, consumed))\n\n }\n\n\n\n /// Write the current record to the given output stream.\n\n ///\n\n /// This works equivalently to [`RecordWriter::new`].\n", "file_path": "warcio/src/header.rs", "rank": 70, "score": 26851.71281248881 }, { "content": " /// [`get_field_bytes`](Self::get_field_bytes) or modified with [`set_field`](Self::set_field).\n\n pub fn iter_field_bytes_mut(&mut self) -> impl Iterator<Item = (&FieldName, &mut Vec<u8>)> {\n\n self.fields.iter_mut()\n\n }\n\n\n\n /// Get the WARC version of this record.\n\n pub fn version(&self) -> &Version {\n\n &self.version\n\n }\n\n\n\n /// Update the WARC version of this header.\n\n ///\n\n /// This will update any bare URIs to account for version differences as described for\n\n /// [`set_field`](Self::set_field), then set the version to the provided one.\n\n pub fn set_version<V: Into<Version>>(&mut self, version: V) {\n\n let version = version.into();\n\n let transform: Option<fn(&mut Vec<u8>)> =\n\n if self.version <= Version::WARC1_0 && version > Version::WARC1_0 {\n\n // Upgrading: remove angle brackets if present. Malformed pre-1.1 records might\n\n // not have brackets.\n", "file_path": "warcio/src/header.rs", "rank": 71, "score": 26851.416133156657 }, { "content": " }\n\n\n\n /// Get the value of a header field as bytes, without URL translation.\n\n ///\n\n /// This function works like [`get_field_bytes`](Self::get_field_bytes), except bare URIs are\n\n /// not translated as described in that function's documentation.\n\n pub fn get_field_bytes_raw<F: Into<FieldName>>(&self, field: F) -> Option<&[u8]> {\n\n self.fields.get(&field.into()).map(Vec::as_slice)\n\n }\n\n\n\n /// Get the value of a header field, or None if it does not exist or is not a valid Rust string.\n\n ///\n\n /// This function transforms fields that are bare URIs in the same way as\n\n /// [`get_field_bytes`](Header::get_field_bytes), stripping angle brackets from\n\n /// the value when the record's WARC version is pre-1.1.\n\n ///\n\n /// If you want to handle potentially malformed records,\n\n /// [`get_field_bytes`](Header::get_field_bytes) allows you to\n\n /// access values that are not acceptable Rust strings (that is, they are not valid UTF-8).\n\n /// However, because such a value would be malformed according to the specification, it should\n", "file_path": "warcio/src/header.rs", "rank": 72, "score": 26850.39735273683 }, { "content": " match bytes.get(..2) {\n\n Some([b'\\r', b'\\n', ..]) => break,\n\n Some(_) => { /* Not end of headers, so probably a field */ }\n\n None => return Err(HeaderParseError::Truncated),\n\n }\n\n\n\n let (name, value, sz) = Self::parse_field(bytes)?;\n\n let name =\n\n str::from_utf8(name).expect(\"parse_field should only accept ASCII field names\");\n\n fields.insert(name.into(), value);\n\n bytes = &bytes[sz..];\n\n headers_consumed += sz;\n\n }\n\n\n\n Ok((\n\n Header { version, fields },\n\n version_consumed + headers_consumed + 2,\n\n ))\n\n }\n\n\n", "file_path": "warcio/src/header.rs", "rank": 73, "score": 26848.91425505448 }, { "content": " for (name, value) in self.iter_field_bytes_mut() {\n\n if name.value_is_bare_uri() {\n\n transform(value);\n\n }\n\n }\n\n }\n\n self.version = version;\n\n }\n\n\n\n /// Get the [`WARC-Record-ID`](FieldKind::RecordId) field value.\n\n ///\n\n /// `WARC-Record-ID` is a mandatory WARC field, so if it is not present this\n\n /// function will panic. If the caller wishes to be lenient in this situation,\n\n /// use [`get_field`](Header::get_field) to read the field instead.\n\n ///\n\n /// Note that a valid value is assumed to be a valid `str` because the\n\n /// record ID is specified to be a [RFC 3986](https://dx.doi.org/10.17487/rfc3986) URI,\n\n /// which are always valid ASCII (and therefore UTF-8) strings when well-formed.\n\n pub fn record_id(&self) -> &str {\n\n self.get_field(FieldKind::RecordId)\n", "file_path": "warcio/src/header.rs", "rank": 74, "score": 26848.561281478636 }, { "content": " /// version 1.1.\n\n ///\n\n /// For example, a `WARC-Record-ID` field in WARC 1.0 might have the raw value\n\n /// `<urn:uuid:ea07dfdd-9452-4b7d-add0-b2c538af5fa5>` but the same value in WARC 1.1 has the\n\n /// value `urn:uuid:ea07dfdd-9452-4b7d-add0-b2c538af5fa5` (without angle brackets). This\n\n /// function would return the value without brackets for all record versions.\n\n pub fn get_field_bytes<F: Into<FieldName>>(&self, field: F) -> Option<&[u8]> {\n\n let field = field.into();\n\n if !field.value_is_bare_uri() {\n\n return self.get_field_bytes_raw(field);\n\n }\n\n\n\n let mut value = self.get_field_bytes_raw(field)?;\n\n if self.version <= Version::WARC1_0 {\n\n // Strip angle brackets for pre-1.1 WARC versions\n\n if value.first() == Some(&b'<') && value.last() == Some(&b'>') {\n\n value = &value[1..value.len() - 1];\n\n }\n\n }\n\n Some(value)\n", "file_path": "warcio/src/header.rs", "rank": 75, "score": 26847.09195720229 }, { "content": "/// \\r\n\n/// \";\n\n/// let (parsed_header, parsed_size) = Header::parse(raw_header)?;\n\n/// assert_eq!(parsed_size, raw_header.len());\n\n///\n\n/// // Construct a header from nothing\n\n/// let mut synthetic_header = Header::new(Version::WARC1_1);\n\n/// synthetic_header.set_field(FieldKind::RecordId,\n\n/// \"<urn:uuid:b4beb26f-54c4-4277-8e23-51aa9fc4476d>\");\n\n/// synthetic_header.set_field(FieldKind::Date, \"2021-08-05T06:22Z\");\n\n/// synthetic_header.set_field(FieldKind::Type, \"resource\");\n\n/// synthetic_header.set_field(FieldKind::ContentLength, \"0\");\n\n///\n\n/// // Headers compare equal because they have the same version and fields\n\n/// assert_eq!(parsed_header, synthetic_header);\n\n/// # Ok(())\n\n/// # }\n\n/// ```\n\n#[derive(Debug, PartialEq, Eq, Clone)]\n\npub struct Header {\n", "file_path": "warcio/src/header.rs", "rank": 76, "score": 26846.54920061581 }, { "content": " /// case is uninteresting, use [`content_length`](Header::content_length) to panic instead\n\n /// if the value is missing or invalid.\n\n pub fn content_length_lenient(&self) -> Option<u64> {\n\n self.get_field(FieldKind::ContentLength)?.parse().ok()\n\n }\n\n\n\n /// Get the [`WARC-Date`](FieldKind::Date) field value, parsed as a `DateTime`.\n\n ///\n\n /// Equivalent to parsing the result of [`warc_date`] as a datetime in the\n\n /// format dictated by the WARC specification, and panics if the field is\n\n /// malformed or missing. Callers should use [`get_field`] and parse the value\n\n /// themselves to avoid panicking if required.\n\n #[cfg(feature = \"chrono\")]\n\n pub fn warc_date_parsed(&self) -> chrono::DateTime<chrono::Utc> {\n\n // YYYY-MM-DDThh:mm:ssZ per WARC-1.0. This is valid RFC3339, which is\n\n // itself valid ISO 8601. We're slightly lenient in accepting non-UTC\n\n // zone offsets.\n\n use chrono::{DateTime, Utc};\n\n DateTime::parse_from_rfc3339(s)\n\n .expect(\"WARC-Date field cannot be parsed as RTC3339 datetime\")\n", "file_path": "warcio/src/header.rs", "rank": 77, "score": 26846.24587789276 }, { "content": " .with_timezone(&Utc)\n\n }\n\n\n\n /// Get the [`WARC-Date`](FieldKind::Date) field value or panic.\n\n ///\n\n /// `WARC-Date` is a mandatory field, so this function panics if it is not present.\n\n /// If the caller wishes to be lenient, use [`get_field`](Self::get_field) to avoid panicking.\n\n pub fn warc_date(&self) -> &str {\n\n self.get_field(FieldKind::Date)\n\n .expect(\"record header does not have a WARC-Date field\")\n\n }\n\n\n\n /// Get the [`WARC-Type`](FieldKind::Type) field value or panic.\n\n ///\n\n /// Because `WARC-Type` is a mandatory field, this function will panic if the\n\n /// field is not present. Callers should use [`get_field`](Self::get_field) to gracefully handle\n\n /// that case.\n\n ///\n\n /// The WARC specification non-exhausively defines the following record\n\n /// types:\n", "file_path": "warcio/src/header.rs", "rank": 78, "score": 26843.523258564033 }, { "content": " ///\n\n /// * warcinfo\n\n /// * response\n\n /// * resource\n\n /// * request\n\n /// * metadata\n\n /// * revisit\n\n /// * conversion\n\n /// * continuation\n\n ///\n\n /// Additional types are permitted as core format extensions. Creators of\n\n /// extensions are encouraged by the standard to discuss their intentions\n\n /// within the IIPC.\n\n pub fn warc_type(&self) -> RecordType<&str> {\n\n self.get_field(FieldKind::Type)\n\n .expect(\"record header does not have a WARC-Type field\")\n\n .into()\n\n }\n\n}\n\n\n", "file_path": "warcio/src/header.rs", "rank": 79, "score": 26839.806914756748 }, { "content": " value: V,\n\n ) -> Option<Vec<u8>> {\n\n let name = name.into();\n\n let name_str: &str = name.as_ref();\n\n assert!(\n\n name_str\n\n .chars()\n\n .any(|c| c.is_ascii()\n\n && !(SEPARATORS.contains(&(c as u8)) || CTL.contains(&(c as u8)))),\n\n \"field name {:?} contains illegal characters\",\n\n name\n\n );\n\n\n\n let mut value = value.into();\n\n if name.value_is_bare_uri() && self.version < Version::WARC1_1 {\n\n value.reserve_exact(2);\n\n value.insert(0, b'<');\n\n value.push(b'>');\n\n }\n\n self.fields.insert(name, value)\n", "file_path": "warcio/src/header.rs", "rank": 80, "score": 26838.574937240744 }, { "content": " Some(|v| {\n\n if v.starts_with(b\"<\") && v.ends_with(b\">\") {\n\n v.pop();\n\n v.remove(0);\n\n }\n\n })\n\n } else if version < Version::WARC1_1 && self.version >= Version::WARC1_1 {\n\n // Downgrading: add angle brackets if not present. Malformed post-1.1 records might\n\n // already have brackets.\n\n Some(|v| {\n\n if !(v.starts_with(b\"<\") && v.ends_with(b\">\")) {\n\n v.insert(0, b'<');\n\n v.push(b'>');\n\n }\n\n })\n\n } else {\n\n None\n\n };\n\n\n\n if let Some(transform) = transform {\n", "file_path": "warcio/src/header.rs", "rank": 81, "score": 26837.35912600394 }, { "content": "fn generate_conversions<'a, W: Write, V: Iterator<Item = (&'a str, &'a str)>>(\n\n mut out: W,\n\n type_name: &str,\n\n variants: V,\n\n) -> Result<(), Box<dyn std::error::Error>> {\n\n let mut map = phf_codegen::Map::<&'static UncasedStr>::new();\n\n\n\n writeln!(\n\n &mut out,\n\n \"impl std::convert::AsRef<str> for {t} {{\n\n fn as_ref(&self) -> &str {{\n\n use {t}::*;\n\n match self {{\",\n\n t = type_name\n\n )?;\n\n\n\n for (variant, repr) in variants {\n\n writeln!(&mut out, \" {} => \\\"{}\\\",\", variant, repr)?;\n\n\n\n map.entry(\n", "file_path": "warcio/build.rs", "rank": 82, "score": 26294.235720752156 }, { "content": " ///\n\n /// Users will generally not need to use this function directly; field values will be\n\n /// transformed as necessary when accessing values through a [`Header`](crate::Header)\n\n /// (brackets added when writing a value to a pre-1.1 record, and removed when reading).\n\n pub fn value_is_bare_uri(&self) -> bool {\n\n let kind = match self {\n\n Self::Known(kind) => kind,\n\n Self::Other(_) => return false,\n\n };\n\n\n\n use crate::FieldKind::*;\n\n match kind {\n\n TargetURI | RefersToTargetURI | Profile => true,\n\n // Types that include angle brackets regardless of WARC version: \"<\" uri \">\"\n\n RecordId | ConcurrentTo | RefersTo | InfoID | SegmentOriginID => false,\n\n // Types that don't contain URIs\n\n ContentLength\n\n | Date\n\n | Type\n\n | ContentType\n", "file_path": "warcio/src/header/fieldname.rs", "rank": 83, "score": 25501.822332670883 }, { "content": "}\n\n\n\nimpl PartialEq<FieldKind> for FieldName {\n\n fn eq(&self, other: &FieldKind) -> bool {\n\n match self {\n\n FieldName::Known(k) => k == other,\n\n FieldName::Other(s) => s.as_ref().as_uncased() == other.as_ref(),\n\n }\n\n }\n\n}\n\n\n\nimpl FieldName {\n\n /// Returns `true` if a field's value consists of a bare URI.\n\n ///\n\n /// This is useful for handling the difference in grammar between WARC 1.1 and earlier versions:\n\n /// while earlier versions define a URI as `\"<\" <'URI' per RFC3986> \">\"` (surrounded by angle\n\n /// brackets), WARC 1.1 removes the angle brackets from the grammar describing a URI and\n\n /// explicitly adds the angle brackets to some (but not all) fields.\n\n /// This function will return `true` for those fields that do not have angle brackets in a\n\n /// WARC 1.1 record but do in earlier versions, and `false` for all other fields.\n", "file_path": "warcio/src/header/fieldname.rs", "rank": 84, "score": 25499.180482099382 }, { "content": " }\n\n }\n\n}\n\n\n\n// This impl covers RecordKind and hopefully optimization can see through the\n\n// map lookup in TryFrom. An explicit impl depends on specialization.\n\nimpl<S: AsRef<str>> From<S> for RecordType<S> {\n\n fn from(s: S) -> Self {\n\n match <RecordKind as std::convert::TryFrom<&str>>::try_from(s.as_ref()) {\n\n Ok(x) => RecordType::Known(x),\n\n Err(_) => RecordType::Other(s.into()),\n\n }\n\n }\n\n}\n\n\n\nimpl<S: AsRef<str>, T: AsRef<str>> PartialEq<T> for RecordType<S> {\n\n fn eq(&self, other: &T) -> bool {\n\n self.as_uncased().eq(other.as_ref())\n\n }\n\n}\n", "file_path": "warcio/src/header/recordtype.rs", "rank": 85, "score": 25495.548085862003 }, { "content": " /// format, such as to ensure the content remains readable with current tools while minimizing\n\n /// lost information.\n\n Conversion,\n\n /// `continuation`: additional data to be appended to a prior block.\n\n ///\n\n /// Continuation records are used when records are segmented, allowing large blocks to be split\n\n /// into multiple records (and also multiple files). Continuations *shall* always have\n\n /// [`Segment-Origin-ID`](crate::FieldKind::SegmentOriginID) and\n\n /// [`WARC-Segment-Number`](crate::FieldKind::SegmentNumber) fields.\n\n Continuation,\n\n}\n\n\n\ninclude!(concat!(env!(\"OUT_DIR\"), \"/record_kind_conversions.rs\"));\n\n\n\nimpl<S: AsRef<str>> PartialEq<S> for RecordKind {\n\n fn eq(&self, other: &S) -> bool {\n\n self.as_uncased().eq(other.as_ref())\n\n }\n\n}\n\n\n\nimpl Eq for RecordKind {}\n", "file_path": "warcio/src/header/recordkind.rs", "rank": 86, "score": 25495.15994817081 }, { "content": "use uncased::{AsUncased, UncasedStr};\n\n\n\n/// Standardized values for [record types](crate::RecordType).\n\n#[derive(Debug, Clone, Copy, PartialOrd, Ord)]\n\npub enum RecordKind {\n\n /// `warcinfo`: describes the records that follow this one.\n\n ///\n\n /// An info record describes the records following itself through the end of the current input\n\n /// or until the next info record. Its [`Content-Type`](crate::FieldKind::ContentType) is recommended\n\n /// to be `application/warc-fields`, and the standard suggests that it contain information about\n\n /// the tools that wrote the WARC file such as tool operator, software version and IP address.\n\n Info,\n\n /// `response`: a complete scheme-specific response to some request.\n\n ///\n\n /// The exact contents of a response depend on the URI scheme of the record's\n\n /// [target URI](crate::FieldKind::TargetURI); the WARC 1.1 specification only defines a format for the\n\n /// http and https schemes, with a `response` record containing a full HTTP response\n\n /// (including headers) received over the network.\n\n Response,\n\n /// `resource`: a resource without full protocol response information.\n", "file_path": "warcio/src/header/recordkind.rs", "rank": 87, "score": 25494.54362041132 }, { "content": "use uncased::UncasedStr;\n\n\n\nuse crate::FieldName;\n\n\n\n/// Standardized values for [field names](FieldName).\n\n#[derive(Debug, Clone, Copy, PartialEq, Eq)]\n\npub enum FieldKind {\n\n /// `WARC-Record-ID`: a globally unique identifier for a record.\n\n ///\n\n /// This field is mandatory and must be present in a standards-compliant record.\n\n /// Values should consist of a URI delimited by angle brackets: `\"<\" uri \">\"`. Often\n\n /// the URI describes a UUID consistent with [RFC 4122](https://dx.doi.org/10.17487/rfc4122),\n\n /// such as `urn:uuid:f81d4fae-7dec-11d0-a765-00a0c91e6bf6`.\n\n RecordId,\n\n /// `Content-Length`: The number of octets (bytes) in a record block.\n\n ///\n\n /// This field is mandatory and must be present in a standards-compliant record.\n\n /// Values should consist of one or more [ASCII](https://dx.doi.org/10.17487/rfc0020) digits.\n\n ContentLength,\n\n /// `WARC-Date`: the instant that record data capture of a record began.\n", "file_path": "warcio/src/header/fieldkind.rs", "rank": 88, "score": 25493.945897621008 }, { "content": "// so Eq, Ord and Hash are implemented in terms of the case-insensitive field name.\n\nimpl PartialEq for FieldName {\n\n fn eq(&self, other: &Self) -> bool {\n\n match (self, other) {\n\n (FieldName::Other(_), _) | (_, FieldName::Other(_)) => {\n\n self.as_ref().as_uncased().eq(other.as_ref())\n\n }\n\n (FieldName::Known(l), FieldName::Known(r)) => l == r,\n\n }\n\n }\n\n}\n\n\n\nimpl Eq for FieldName {}\n\n\n\nimpl PartialOrd for FieldName {\n\n fn partial_cmp(&self, other: &Self) -> Option<Ordering> {\n\n self.as_ref().as_uncased().partial_cmp(other.as_ref())\n\n }\n\n}\n\n\n", "file_path": "warcio/src/header/fieldname.rs", "rank": 89, "score": 25493.84925669367 }, { "content": "/// assert_eq!(response_type, RecordKind::Response);\n\n/// assert_eq!(response_type, \"response\");\n\n/// ```\n\n#[derive(Debug, Clone)]\n\npub enum RecordType<S> {\n\n /// A known (standardized) record type.\n\n Known(RecordKind),\n\n /// Any unrecognized record type.\n\n ///\n\n /// This variant allows unknown record types to be represented, beyond those specified. Software\n\n /// *shall* skip records of unknown type, which may be defined in future versions of the file\n\n /// format.\n\n Other(S),\n\n}\n\n\n\nimpl<S: AsRef<str>> AsRef<str> for RecordType<S> {\n\n fn as_ref(&self) -> &str {\n\n match self {\n\n RecordType::Known(x) => x.as_ref(),\n\n RecordType::Other(s) => s.as_ref(),\n", "file_path": "warcio/src/header/recordtype.rs", "rank": 90, "score": 25493.23503417775 }, { "content": "/// ```\n\n#[derive(Debug, Clone)]\n\npub enum FieldName {\n\n Known(FieldKind),\n\n /// Any unrecognized field name.\n\n ///\n\n /// The WARC format permits arbitrarily-named extension fields, and specifies that software\n\n /// *shall* ignore fields with unrecognized names. This variant allows their representation and\n\n /// processing but does not ascribe any particular meaning to unrecognized names.\n\n ///\n\n /// `Other` should generally not be manually constructed, instead using the [`From`]\n\n /// impl to convert from a string. However, an `Other` value that matches the string\n\n /// representation of a known field name will behave the same as the variant matching\n\n /// that field name (but may have worse performance characteristics).\n\n Other(Box<str>),\n\n}\n\n\n\nimpl AsRef<str> for FieldName {\n\n fn as_ref(&self) -> &str {\n\n use FieldName::*;\n", "file_path": "warcio/src/header/fieldname.rs", "rank": 91, "score": 25492.226624968374 }, { "content": "use crate::RecordKind;\n\nuse std::cmp::Ordering;\n\nuse uncased::AsUncased;\n\n\n\n/// The kind of a single WARC record.\n\n///\n\n/// Every record is specified to have a type in its [`WARC-Type`](crate::FieldKind::Type) field. This\n\n/// enumeration provides variants for those specified in the WARC standard and allows representation\n\n/// of others as might be used by extensions to the core WARC format or future versions.\n\n///\n\n/// A `RecordType` can be parsed from a string using the [`From<str>`](#impl-From<S>) impl, and\n\n/// retrieved as a string via [`AsRef<str>`](#impl-AsRef<str>). Parsed values are case-insensitive\n\n/// and normalize to the standard capitalization, but [unknown](RecordType::Other) values preserve\n\n/// case when parsed. A `RecordType` can also be trivially constructed from a `RecordKind`, meaning\n\n/// most functions that accept a `RecordType` can also accept a `RecordKind`.\n\n///\n\n/// ```\n\n/// # use warcio::{RecordType, RecordKind};\n\n/// let response_type = <RecordType<_> as From<_>>::from(\"Response\");\n\n///\n", "file_path": "warcio/src/header/recordtype.rs", "rank": 92, "score": 25491.894169273535 }, { "content": " /// any record that has associated continuations. In the first record its value is `1`, and\n\n /// for subsequent continuations the value is incremented.\n\n SegmentNumber,\n\n /// `WARC-Segment-Origin-ID`: the ID of the starting record in a series of segmented records.\n\n ///\n\n /// This field if required for [continuation](crate::RecordKind::Continuation) records with the\n\n /// value being a URI surrounded by angle brackets, where the URI is the\n\n /// [ID of the first record](Self::RecordId) in the continuation sequence.\n\n SegmentOriginID,\n\n /// `WARC-Segment-Total-Length`: the total length of concatenated segmented content blocks.\n\n ///\n\n /// This field is required for the last [continuation](crate::RecordKind::Continuation) record\n\n /// of a series, and *shall not* be used elsewhere.\n\n SegmentTotalLength,\n\n}\n\n\n\nimpl FieldKind {\n\n pub fn into_name(self) -> FieldName {\n\n FieldName::Known(self)\n\n }\n", "file_path": "warcio/src/header/fieldkind.rs", "rank": 93, "score": 25491.836371491783 }, { "content": " TargetURI,\n\n /// `WARC-Truncated`: the reason that a record contains a truncated version of the\n\n /// original resource.\n\n ///\n\n /// Reasons a writer may specify when truncating a record (the value of this field) are\n\n /// non-exhaustively enumerated by the standard:\n\n /// * `length`: the record is too large\n\n /// * `time`: the record took too long to capture\n\n /// * `disconnect`: the resource was disconnected from a network\n\n /// * `unspecified`: some other or unknown reason\n\n Truncated,\n\n /// `WARC-Warcinfo-ID`: the [ID](Self::RecordId) of the [warcinfo](crate::RecordKind::Info)\n\n /// record associated with this record.\n\n ///\n\n /// This field is typically used when the context of a record is lost, such as when a collection\n\n /// of records is split into individual files. The value is a URI surrounded by angle brackets:\n\n /// `<uri>`.\n\n InfoID,\n\n /// `WARC-Filename`: the name of the file containing the current\n\n /// [warcinfo](crate::RecordKind::Info) record.\n", "file_path": "warcio/src/header/fieldkind.rs", "rank": 94, "score": 25491.510899851015 }, { "content": "use crate::FieldKind;\n\nuse std::borrow::Borrow;\n\nuse std::cmp::Ordering;\n\nuse std::hash::{Hash, Hasher};\n\nuse uncased::{AsUncased, UncasedStr};\n\n\n\nimpl From<&FieldKind> for FieldName {\n\n fn from(kind: &FieldKind) -> FieldName {\n\n kind.into_name()\n\n }\n\n}\n\n\n\n/// The name of a WARC header field.\n\n///\n\n/// Field names are case-insensitive strings made up of one or more ASCII characters excluding\n\n/// control characters (values 0-31 and 127) and separators (`()<>@,;:\\\"/[]?={} \\t`). A `FieldName`\n\n/// can be constructed from arbitrary input using the [`From<str>` impl](#impl-From<S>), or a\n\n/// variant may be directly constructed. A string representation of a parsed name can be obtained\n\n/// through [`AsRef<str>`](#impl-AsRef<str>).\n\n///\n", "file_path": "warcio/src/header/fieldname.rs", "rank": 95, "score": 25491.241525736004 }, { "content": " ///\n\n /// The field value is a URI surrounded by angle brackets: `<uri>`.\n\n ///\n\n /// [`Revisit`](crate::RecordKind::Revisit) or [`Conversion`](crate::RecordKind::Conversion)\n\n /// records use this field to indicate a preceding record which helps determine the record's\n\n /// content. It can also be used to associate a [`Metadata`](crate::RecordKind::Metadata)\n\n /// record with the record it describes.\n\n RefersTo,\n\n /// `WARC-Refers-To-Target-URI`: the [`TargetURI`](Self::TargetURI) of the record referred to by\n\n /// [`RefersTo`](Self::RefersTo).\n\n RefersToTargetURI,\n\n /// `WARC-Refers-To-Date`: the [`Date`](Self::Date) of the record referred to by\n\n /// [`RefersTo`](Self::RefersTo).\n\n RefersToDate,\n\n /// `WARC-Target-URI`: the original URI that provided the record content.\n\n ///\n\n /// In the context of web crawling, this is the URI that a crawler sent a request to retrieve.\n\n /// For indirect records such as [metadata](crate::RecordKind::Metadata) or\n\n /// [conversion](crate::RecordKind::Conversion)s, the value is a copy of the target URI from the\n\n /// original record.\n", "file_path": "warcio/src/header/fieldkind.rs", "rank": 96, "score": 25490.815044778694 }, { "content": "\n\nimpl<S: AsRef<str>> Eq for RecordType<S> {}\n\n\n\nimpl<S: AsRef<str>, T: AsRef<str>> PartialOrd<T> for RecordType<S> {\n\n fn partial_cmp(&self, other: &T) -> Option<Ordering> {\n\n self.as_uncased().partial_cmp(other.as_uncased())\n\n }\n\n}\n\n\n\nimpl<S: AsRef<str>> Ord for RecordType<S> {\n\n fn cmp(&self, other: &Self) -> Ordering {\n\n self.as_uncased().cmp(other.as_uncased())\n\n }\n\n}\n", "file_path": "warcio/src/header/recordtype.rs", "rank": 97, "score": 25490.36480441053 }, { "content": "/// Standardized values for field names are enumerated by the [`FieldKind`] type, for which\n\n/// conversions and most operations are conveniently implemented. A `FieldKind` can trivially\n\n/// be converted to or compared with a `FieldName`.\n\n///\n\n/// Comparison, ordering, and hashing of field names is always case-insensitive, and the standard\n\n/// variants normalize their case to those used by the standard. Unrecognized values will preserve\n\n/// case when converted to strings but still compare case-insensitively.\n\n///\n\n/// ```\n\n/// # use warcio::{FieldName, FieldKind};\n\n/// let id = FieldKind::RecordId;\n\n/// // Conversion from string via From\n\n/// let parsed_id: FieldName = \"warc-record-id\".into();\n\n///\n\n/// assert_eq!(id, parsed_id);\n\n/// // Input was cased differently: standard name has been normalized\n\n/// assert_eq!(\"WARC-Record-ID\", parsed_id.as_ref());\n\n/// // Only comparison of FieldNames is case-insensitive, a string is not\n\n/// assert_eq!(parsed_id, <FieldName as From<_>>::from(\"wArC-ReCoRd-Id\"));\n\n/// assert_ne!(parsed_id.as_ref(), \"wArC-ReCoRd-Id\");\n", "file_path": "warcio/src/header/fieldname.rs", "rank": 98, "score": 25489.829126630142 }, { "content": " ///\n\n /// This field may only be used in info records.\n\n Filename,\n\n /// `WARC-Profile`: the kind of analysis and handling applied to create a\n\n /// [revisit](crate::RecordKind::Revisit) record, specified as a URI.\n\n ///\n\n /// Readers shall not attempt to interpret records for which the profile is not recognized. The\n\n /// WARC 1.1 standard defines two profiles and allows for others:\n\n /// * `http://netpreserve.org/warc/1.1/revisit/identical-payload-digest`\n\n /// * `http://netpreserve.org/warc/1.1/revisit/server-not-modified`\n\n Profile,\n\n /// `WARC-Identified-Payload-Type`: the content-type discovered by inspecting a record payload.\n\n ///\n\n /// Writers *shall not* blindly promote HTTP `Content-Type` values without inspecting the\n\n /// payload when creating records- such values may be incorrect. Users should perform an\n\n /// independent check to arrive at a value for this field.\n\n IdentifiedPayloadType,\n\n /// `WARC-Segment-Number`: the current record's ordering in a sequence of segmented records.\n\n ///\n\n /// This field is required for [continuation](crate::RecordKind::Continuation) records as well as for\n", "file_path": "warcio/src/header/fieldkind.rs", "rank": 99, "score": 25488.993100208078 } ]
Rust
contracts/q_native/src/contract/handler/token.rs
quasar-protocol/quasar-cosmwasm
3849c83f2057998637c2c32bcebfe535fd47d4a3
use cosmwasm_std::{ log, Api, Binary, CanonicalAddr, Env, Extern, HandleResponse, HumanAddr, InitResponse, Querier, ReadonlyStorage, StdError, StdResult, Storage, Uint128, }; use cosmwasm_storage::{PrefixedStorage, ReadonlyPrefixedStorage}; use crate::state::{ bytes_to_u128, get_allowance, get_balance, set_allowance, to_u128, ALLOWANCE_PREFIX, BALANCE_PREFIX, }; pub fn try_transfer<S: Storage, A: Api, Q: Querier>( deps: &mut Extern<S, A, Q>, env: Env, recipient: &HumanAddr, amount: &Uint128, ) -> StdResult<HandleResponse> { let sender_address_raw = deps.api.canonical_address(recipient)?; let recipient_address_raw = deps.api.canonical_address(recipient)?; let amount_raw = amount.u128(); perform_transfer( &mut deps.storage, &sender_address_raw, &recipient_address_raw, amount_raw, )?; let res = HandleResponse { messages: vec![], log: vec![ log("action", "transfer"), log("sender", env.message.sender.as_str()), log("recipient", recipient.as_str()), ], data: None, }; Ok(res) } pub fn try_transfer_from<S: Storage, A: Api, Q: Querier>( deps: &mut Extern<S, A, Q>, env: Env, owner: &HumanAddr, recipient: &HumanAddr, amount: &Uint128, ) -> StdResult<HandleResponse> { let spender_address_raw = deps.api.canonical_address(&env.message.sender)?; let owner_address_raw = deps.api.canonical_address(owner)?; let recipient_address_raw = deps.api.canonical_address(recipient)?; let amount_raw = amount.u128(); let mut allowance = get_allowance(&deps.storage, &owner_address_raw, &spender_address_raw)?; if allowance < amount_raw { return Err(StdError::generic_err(format!( "Insufficient allowance: allowance={}, required={}", allowance, amount_raw ))); } allowance -= amount_raw; set_allowance( &mut deps.storage, &owner_address_raw, &spender_address_raw, allowance, )?; perform_transfer( &mut deps.storage, &owner_address_raw, &recipient_address_raw, amount_raw, )?; let res = HandleResponse { messages: vec![], log: vec![ log("action", "transfer_from"), log("spender", env.message.sender.as_str()), log("sender", owner.as_str()), log("recipient", recipient.as_str()), ], data: None, }; Ok(res) } pub fn try_approve<S: Storage, A: Api, Q: Querier>( deps: &mut Extern<S, A, Q>, env: Env, spender: &HumanAddr, amount: &Uint128, ) -> StdResult<HandleResponse> { let owner_address_raw = deps.api.canonical_address(&env.message.sender)?; let spender_address_raw = deps.api.canonical_address(spender)?; set_allowance( &mut deps.storage, &owner_address_raw, &spender_address_raw, amount.u128(), )?; let res = HandleResponse { messages: vec![], log: vec![ log("action", "approve"), log("owner", env.message.sender.as_str()), log("spender", spender.as_str()), ], data: None, }; Ok(res) } fn perform_transfer<T: Storage>( store: &mut T, from: &CanonicalAddr, to: &CanonicalAddr, amount: u128, ) -> StdResult<()> { let mut balances_store = PrefixedStorage::new(BALANCE_PREFIX, store); let mut from_balance = to_u128(&balances_store, from.as_slice())?; if from_balance < amount { return Err(StdError::generic_err(format!( "Insufficient funds: sender={}, balance={}, required={}", HumanAddr::from(from.to_string()), from_balance, amount ))); } from_balance -= amount; balances_store.set(from.as_slice(), &from_balance.to_be_bytes()); let mut to_balance = to_u128(&balances_store, to.as_slice())?; to_balance += amount; balances_store.set(to.as_slice(), &to_balance.to_be_bytes()); Ok(()) } pub fn mint_tokens<T: Storage>( store: &mut T, to: &CanonicalAddr, amount: u128, ) -> StdResult<()> { let mut balances_store = PrefixedStorage::new(BALANCE_PREFIX, store); let mut to_balance = to_u128(&balances_store, to.as_slice())?; to_balance += amount; balances_store.set(to.as_slice(), &to_balance.to_be_bytes()); Ok(()) } pub fn burn_tokens<T: Storage>( store: &mut T, to: &CanonicalAddr, amount: u128, ) -> StdResult<()> { let mut balances_store = PrefixedStorage::new(BALANCE_PREFIX, store); let mut to_balance = to_u128(&balances_store, to.as_slice())?; to_balance -= amount; balances_store.set(to.as_slice(), &to_balance.to_be_bytes()); Ok(()) }
use cosmwasm_std::{ log, Api, Binary, CanonicalAddr, Env, Extern, HandleResponse, HumanAddr, InitResponse, Querier, ReadonlyStorage, StdError, StdResult, Storage, Uint128, }; use cosmwasm_storage::{PrefixedStorage, ReadonlyPrefixedStorage}; use crate::state::{ bytes_to_u128, get_allowance, get_balance, set_allowance, to_u128, ALLOWANCE_PREFIX, BALANCE_PREFIX, }; pub fn try_transfer<S: Storage, A: Api, Q: Querier>( deps: &mut Extern<S, A, Q>, env: Env, recipient: &HumanAddr, amount: &Uint128, ) -> StdResult<HandleResponse> { let sender_address_raw = deps.api.canonical_address(recipient)?; let recipient_address_raw = deps.api.canonical_address(recipient)?; let amount_raw = amount.u128(); perform_transfer( &mut deps.storage, &sender_address_raw, &recipient_address_raw, amount_raw, )?; let res = HandleResponse { messages: vec![], log: vec![ log("action", "transfer"), log("sender", env.message.sender.as_str()), log("recipient", recipient.as_str()), ], data: None, }; Ok(res) } pub fn try_transfer_from<S: Storage, A: Api, Q: Querier>( deps: &mut Extern<S, A, Q>, env: Env, owner: &HumanAddr, recipient: &HumanAddr, amount: &Uint128, ) -> StdResult<HandleResponse> { let spender_address_raw = deps.api.canonical_address(&env.message.sender)?; let owner_address_raw = deps.api.canonical_address(owner)?; let recipient_address_raw = deps.api.canonical_address(recipient)?; let amount_raw = amount.u128(); let mut allowance = get_allowance(&deps.storage, &owner_address_raw, &spender_address_raw)?; if allowance < amount_raw { return Err(StdError::generic_err(format!( "Insufficient allowance: allowance={}, required={}", allowance, amount_raw ))); } allowance -= amount_raw; set_allowance( &mut deps.storage, &owner_address_raw, &spender_address_raw, allowance, )?; perform_transfer( &mut deps.storage, &owner_address_raw, &recipient_address_raw, amount_raw, )?; let res = HandleResponse { messages: vec![], log: vec![ log("action", "transfer_from"), log("spender", env.message.sender.as_str()), log("sender", owner.as_str()), log("recipient", recipient.as_str()), ], data: None, }; Ok(res) } pub fn try_approve<S: Storage, A: Api, Q: Querier>( deps: &mut Extern<S, A, Q>, env: Env, spender: &HumanAddr, amount: &Uint128, ) -> StdResult<HandleResponse> { let owner_address_raw = deps.api.canonical_address(&env.message.sender)?; let spender_address_raw = deps.api.canonical_address(spender)?; set_allowance( &mut deps.storage, &owner_address_raw, &spender_address_raw, amount.u128(), )?; let res = HandleResponse { messages: vec![], log: vec![ log("action", "approve"), log("owner", env.message.sender.as_str()), log("spender", spender.as_str()), ], data: None, }; Ok(res) } fn perform_transfer<T: Storage>( store: &mut T,
nce.to_be_bytes()); Ok(()) } pub fn mint_tokens<T: Storage>( store: &mut T, to: &CanonicalAddr, amount: u128, ) -> StdResult<()> { let mut balances_store = PrefixedStorage::new(BALANCE_PREFIX, store); let mut to_balance = to_u128(&balances_store, to.as_slice())?; to_balance += amount; balances_store.set(to.as_slice(), &to_balance.to_be_bytes()); Ok(()) } pub fn burn_tokens<T: Storage>( store: &mut T, to: &CanonicalAddr, amount: u128, ) -> StdResult<()> { let mut balances_store = PrefixedStorage::new(BALANCE_PREFIX, store); let mut to_balance = to_u128(&balances_store, to.as_slice())?; to_balance -= amount; balances_store.set(to.as_slice(), &to_balance.to_be_bytes()); Ok(()) }
from: &CanonicalAddr, to: &CanonicalAddr, amount: u128, ) -> StdResult<()> { let mut balances_store = PrefixedStorage::new(BALANCE_PREFIX, store); let mut from_balance = to_u128(&balances_store, from.as_slice())?; if from_balance < amount { return Err(StdError::generic_err(format!( "Insufficient funds: sender={}, balance={}, required={}", HumanAddr::from(from.to_string()), from_balance, amount ))); } from_balance -= amount; balances_store.set(from.as_slice(), &from_balance.to_be_bytes()); let mut to_balance = to_u128(&balances_store, to.as_slice())?; to_balance += amount; balances_store.set(to.as_slice(), &to_bala
function_block-random_span
[ { "content": "fn accrue_interest<S: Storage, A: Api, Q: Querier>(deps: &mut Extern<S, A, Q>, env: Env) -> StdResult<()> {\n\n let prior_state = get_state(&deps.storage)?;\n\n\n\n let borrow_rate = get_borrow_rate(&prior_state.cash, &prior_state.total_borrows, &prior_state.total_reserves);\n\n\n\n if borrow_rate > prior_state.max_borrow_rate.u128() {\n\n return Err(StdError::generic_err(format!(\n\n \"borrow rate is absurdly high: borrow_rate: {}, max_borrow_rate: {}\",\n\n borrow_rate, prior_state.max_borrow_rate)\n\n )\n\n );\n\n }\n\n\n\n let current_block = env.block.height;\n\n\n\n let block_delta: u128 = (prior_state.block_number - current_block).try_into().unwrap();\n\n\n\n // Calculate the interest accumulated into borrows and reserves and the new index:\n\n let simple_interest_factor = borrow_rate * block_delta;\n\n\n", "file_path": "contracts/q_native/src/contract/handler/collateral.rs", "rank": 0, "score": 232300.13440341403 }, { "content": "fn get_account_borrow<S: Storage, A: Api, Q: Querier>(deps: &mut Extern<S, A, Q>, env: Env) -> StdResult<u128> {\n\n let sender_raw = deps.api.canonical_address(&env.message.sender)?;\n\n let snapshot = get_borrow_balance(&deps.storage, &sender_raw);\n\n \n\n let borrow_snapshot = match snapshot {\n\n Some(s) => {\n\n s\n\n },\n\n None => {\n\n let init_borrow_snapshot = BorrowSnapshot {\n\n principal: Uint128::from(0u128),\n\n interest_index: Uint128::from(0u128)\n\n };\n\n set_borrow_balance(&mut deps.storage, &sender_raw, Some(init_borrow_snapshot.clone()))?;\n\n init_borrow_snapshot\n\n }\n\n };\n\n\n\n if borrow_snapshot.principal == Uint128::from(0u128) {\n\n // if borrow balance is 0, then borrow index is likey also 0.\n\n // Hence, return 0 in this case.\n\n return Ok(0)\n\n }\n\n\n\n let state = get_state(&deps.storage)?;\n\n let principal_time_index = borrow_snapshot.principal.u128() * state.borrow_index.u128();\n\n return Ok(principal_time_index / borrow_snapshot.interest_index.u128());\n\n}\n\n\n", "file_path": "contracts/q_native/src/contract/handler/collateral.rs", "rank": 1, "score": 223850.16883671161 }, { "content": "fn get_exchange_rate<S: Storage, A: Api, Q: Querier>(deps: &mut Extern<S, A, Q>, _env: Env) -> StdResult<u128> {\n\n let config = get_config(&deps.storage)?;\n\n \n\n // if total supply is zero\n\n if config.total_supply == Uint128::from(0u128) {\n\n return Ok(config.initial_exchange_rate.u128());\n\n }\n\n // else calculate exchange rate\n\n let prior_state = get_state(&deps.storage)?;\n\n\n\n let total_cash = prior_state.cash;\n\n\n\n let cash_plus_borrows_minus_reserves = (total_cash + prior_state.total_borrows - prior_state.total_reserves)?;\n\n\n\n let exchange_rate = cash_plus_borrows_minus_reserves.u128() / config.total_supply.u128() * 100_000_000;\n\n\n\n\n\n Ok(exchange_rate)\n\n}\n\n\n\n\n", "file_path": "contracts/q_native/src/contract/handler/collateral.rs", "rank": 2, "score": 217983.6792677471 }, { "content": "pub fn query<S: Storage, A: Api, Q: Querier>(\n\n deps: &Extern<S, A, Q>,\n\n msg: QueryMsg,\n\n) -> StdResult<Binary> {\n\n match msg {\n\n QueryMsg::Config {} => {\n\n let config = get_config(&deps.storage)?;\n\n let out = to_binary(&ConfigResponse {\n\n name: config.name,\n\n total_supply: Uint128::from(config.total_supply),\n\n decimals: config.decimals,\n\n symbol: config.symbol,\n\n denom: config.denom,\n\n intital_exchange_rate: Uint128::from(config.initial_exchange_rate),\n\n reserve_factor: Uint128::from(config.reserve_factor),\n\n borrow_index: Uint128::from(config.borrow_index)\n\n })?;\n\n Ok(out)\n\n }\n\n QueryMsg::Balance { address } => {\n", "file_path": "contracts/q_native/src/contract/querier/mod.rs", "rank": 6, "score": 166478.74546617782 }, { "content": "/// Contract instantiation tx\n\n/// tx inputs are specified in InitMsg in msg.rs file\n\npub fn init<S: Storage, A: Api, Q: Querier>(\n\n deps: &mut Extern<S, A, Q>,\n\n env: Env,\n\n msg: InitMsg,\n\n) -> StdResult<InitResponse> {\n\n let init_config = Config {\n\n name: msg.name,\n\n total_supply: msg.total_supply,\n\n decimals: msg.decimals,\n\n symbol: msg.symbol,\n\n denom: msg.denom,\n\n initial_exchange_rate: msg.initial_exchange_rate,\n\n reserve_factor: msg.reserve_factor,\n\n max_borrow_rate: msg.max_borrow_rate,\n\n borrow_index: msg.borrow_index,\n\n };\n\n\n\n config(&mut deps.storage).save(&init_config)?;\n\n\n\n \n", "file_path": "contracts/q_native/src/contract/init/mod.rs", "rank": 7, "score": 159485.98478504547 }, { "content": "/// General handler for contract tx input\n\n/// tx inputs are defined HandleMsg enum in msg.rs file\n\npub fn handle<S: Storage, A: Api, Q: Querier>(\n\n deps: &mut Extern<S, A, Q>,\n\n env: Env,\n\n msg: HandleMsg,\n\n) -> StdResult<HandleResponse<Empty>> {\n\n match msg {\n\n HandleMsg::Approve { spender, amount } => token::try_approve(deps, env, &spender, &amount),\n\n HandleMsg::Transfer { recipient, amount } => {\n\n token::try_transfer(deps, env, &recipient, &amount)\n\n }\n\n HandleMsg::TransferFrom {\n\n owner,\n\n recipient,\n\n amount,\n\n } => token::try_transfer_from(deps, env, &owner, &recipient, &amount),\n\n HandleMsg::Mint {} => collateral::try_mint(deps, env),\n\n HandleMsg::Redeem {redeem_tokens_in} => collateral::try_redeem(deps, env, redeem_tokens_in),\n\n HandleMsg::RepayBorrow {} => collateral::try_repay_borrow(deps, env),\n\n HandleMsg::Borrow{ borrow_amount } => collateral::try_borrow(deps, env, borrow_amount)\n\n }\n\n}\n", "file_path": "contracts/q_native/src/contract/handler/mod.rs", "rank": 8, "score": 159485.98478504547 }, { "content": "pub fn try_redeem<S: Storage, A: Api, Q: Querier>(\n\n deps: &mut Extern<S, A, Q>,\n\n env: Env,\n\n redeem_tokens_in: Uint128\n\n) -> StdResult<HandleResponse> {\n\n accrue_interest(deps, env.clone())?;\n\n\n\n let current_block = env.block.height;\n\n let state = get_state(&deps.storage)?;\n\n if current_block != state.block_number {\n\n return Err(StdError::generic_err(format!(\n\n \"Market is not fresh: current_block: {}, market_block: {}\",\n\n current_block, state.block_number)\n\n )\n\n );\n\n }\n\n\n\n // TODO: get query from controller contract whether the sender is allowed to borrow\n\n\n\n // Get exchange rate derived from borrow and reserve\n", "file_path": "contracts/q_native/src/contract/handler/collateral.rs", "rank": 9, "score": 156576.19163990617 }, { "content": "pub fn try_borrow<S: Storage, A: Api, Q: Querier>(\n\n deps: &mut Extern<S, A, Q>,\n\n env: Env,\n\n borrow_amount: Uint128\n\n) -> StdResult<HandleResponse> {\n\n\n\n accrue_interest(deps, env.clone())?;\n\n\n\n let current_block = env.block.height;\n\n let state = get_state(&deps.storage)?;\n\n if current_block != state.block_number {\n\n return Err(StdError::generic_err(format!(\n\n \"Market is not fresh: current_block: {}, market_block: {}\",\n\n current_block, state.block_number)\n\n )\n\n );\n\n }\n\n\n\n // TODO: get query from controller contract whether the sender is allowed to borrow\n\n\n", "file_path": "contracts/q_native/src/contract/handler/collateral.rs", "rank": 10, "score": 156576.19163990617 }, { "content": "pub fn try_mint<S: Storage, A: Api, Q: Querier>(\n\n deps: &mut Extern<S, A, Q>,\n\n env: Env,\n\n) -> StdResult<HandleResponse> {\n\n\n\n accrue_interest(deps, env.clone())?;\n\n \n\n let current_block = env.block.height;\n\n let state = get_state(&deps.storage)?;\n\n if current_block != state.block_number {\n\n return Err(StdError::generic_err(format!(\n\n \"Market is not fresh: current_block: {}, market_block: {}\",\n\n current_block, state.block_number)\n\n )\n\n );\n\n }\n\n \n\n\n\n // TODO: get query from controller contract whether the sender is allowed to borrow\n\n\n", "file_path": "contracts/q_native/src/contract/handler/collateral.rs", "rank": 11, "score": 156576.1916399062 }, { "content": "pub fn try_repay_borrow<S: Storage, A: Api, Q: Querier>(\n\n _deps: &mut Extern<S, A, Q>,\n\n env: Env,\n\n) -> StdResult<HandleResponse> {\n\n let res = HandleResponse {\n\n messages: vec![],\n\n log: vec![\n\n log(\"action\", \"repay_borrow\"),\n\n log(\"sender\", env.message.sender.as_str()),\n\n ],\n\n data: None,\n\n };\n\n Ok(res)\n\n}\n\n\n", "file_path": "contracts/q_native/src/contract/handler/collateral.rs", "rank": 12, "score": 153829.6898974025 }, { "content": "/// Get balance from address\n\npub fn get_balance<S: Storage>(store: &S, owner: &CanonicalAddr) -> StdResult<u128> {\n\n let balance_store = ReadonlyPrefixedStorage::new(BALANCE_PREFIX, store);\n\n to_u128(&balance_store, owner.as_slice())\n\n}\n\n\n", "file_path": "contracts/q_native/src/state.rs", "rank": 13, "score": 148355.38791835355 }, { "content": "pub fn get_borrow_balance<S: Storage>(store: &S, owner: &CanonicalAddr) -> Option<BorrowSnapshot> {\n\n match ReadonlyBucket::new(BORROW_PREFIX, store).may_load(owner.as_slice()) {\n\n Ok(Some(wrapped_reserves)) => Some(wrapped_reserves),\n\n _ => None,\n\n }\n\n}\n\n\n", "file_path": "contracts/q_native/src/state.rs", "rank": 14, "score": 132425.7690786481 }, { "content": "// Converts 16 bytes value into u128\n\n// Errors if data found that is not 16 bytes\n\npub fn bytes_to_u128(data: &[u8]) -> StdResult<u128> {\n\n match data[0..16].try_into() {\n\n Ok(bytes) => Ok(u128::from_be_bytes(bytes)),\n\n Err(_) => Err(StdError::generic_err(\n\n \"Corrupted data found. 16 byte expected.\",\n\n )),\n\n }\n\n}\n\n\n", "file_path": "contracts/q_native/src/state.rs", "rank": 15, "score": 121005.06886922597 }, { "content": "// Reads 16 byte storage value into u128\n\n// Returns zero if key does not exist. Returns 0 if data found that is not 16 bytes\n\npub fn to_u128<S: ReadonlyStorage>(store: &S, key: &[u8]) -> StdResult<u128> {\n\n let result = store.get(key);\n\n match result {\n\n Some(data) => bytes_to_u128(&data),\n\n None => Ok(0u128),\n\n }\n\n}\n\n\n", "file_path": "contracts/q_native/src/state.rs", "rank": 16, "score": 118733.66751355986 }, { "content": "/// Set config\n\npub fn set_config<S: Storage>(storage: &mut S, config: &Config) -> StdResult<()> {\n\n Singleton::new(storage, CONFIG_PREFIX).save(config)\n\n}\n\n\n", "file_path": "contracts/q_native/src/state.rs", "rank": 17, "score": 109528.644235332 }, { "content": "/// Set exchange rate\n\npub fn set_state<S: Storage>(storage: &mut S, state: &State) -> StdResult<()> {\n\n Singleton::new(storage, STATE_PREFIX).save(state)\n\n}\n\n\n", "file_path": "contracts/q_native/src/state.rs", "rank": 18, "score": 109528.644235332 }, { "content": "/// Config singleton initialization\n\npub fn config<S: Storage>(storage: &mut S) -> Singleton<S, Config> {\n\n singleton(storage, CONFIG_PREFIX)\n\n}\n\n\n", "file_path": "contracts/q_native/src/state.rs", "rank": 19, "score": 99091.85617924455 }, { "content": "pub fn get_utilization_rate(cash: &Uint128, borrows: &Uint128, reserves: &Uint128) -> u128 {\n\n if *borrows == Uint128::from(0u128) {\n\n return 0;\n\n }\n\n borrows.u128()/((cash.u128() + borrows.u128()) - reserves.u128())\n\n}\n\n\n\n\n", "file_path": "contracts/q_native/src/contract/handler/interest_model.rs", "rank": 20, "score": 93971.73254277871 }, { "content": "pub fn get_borrow_rate(cash: &Uint128, borrows: &Uint128, reserves: &Uint128) -> u128 {\n\n let util = get_utilization_rate(cash, borrows, reserves);\n\n\n\n if util <= kink {\n\n return util * multiplier_per_block + base_rate_per_block;\n\n } else {\n\n let normal_rate = kink * multiplier_per_block + base_rate_per_block;\n\n let excess_util = util - kink;\n\n return excess_util * jump_multiplier_per_block + normal_rate;\n\n }\n\n}\n\n\n", "file_path": "contracts/q_native/src/contract/handler/interest_model.rs", "rank": 21, "score": 93971.73254277871 }, { "content": "pub fn get_supply_rate(cash: &Uint128, borrows: &Uint128, reserves: &Uint128, reserve_factor: &Uint128) -> u128 {\n\n let one_minus_reserve_factor = 1*10_i32.pow(8) as u128 - reserve_factor.u128();\n\n let borrow_rate = get_borrow_rate(cash, borrows, reserves);\n\n let rate_to_pool = borrow_rate * one_minus_reserve_factor;\n\n get_utilization_rate(cash, borrows, reserves) * rate_to_pool\n\n}", "file_path": "contracts/q_native/src/contract/handler/interest_model.rs", "rank": 22, "score": 93545.83949837583 }, { "content": "/// Set allowance from address\n\npub fn set_allowance<S: Storage>(\n\n store: &mut S,\n\n owner: &CanonicalAddr,\n\n spender: &CanonicalAddr,\n\n amount: u128,\n\n) -> StdResult<()> {\n\n let mut allowances_store = PrefixedStorage::new(ALLOWANCE_PREFIX, store);\n\n let mut owner_store = PrefixedStorage::new(owner.as_slice(), &mut allowances_store);\n\n owner_store.set(spender.as_slice(), &amount.to_be_bytes());\n\n Ok(())\n\n}\n\n\n", "file_path": "contracts/q_native/src/state.rs", "rank": 23, "score": 93465.83147388368 }, { "content": "/// Get allowance from address\n\npub fn get_allowance<S: Storage>(\n\n store: &S,\n\n owner: &CanonicalAddr,\n\n spender: &CanonicalAddr,\n\n) -> StdResult<u128> {\n\n let allowances_store = ReadonlyPrefixedStorage::new(ALLOWANCE_PREFIX, store);\n\n let owner_store = ReadonlyPrefixedStorage::new(owner.as_slice(), &allowances_store);\n\n to_u128(&owner_store, spender.as_slice())\n\n}\n\n\n", "file_path": "contracts/q_native/src/state.rs", "rank": 24, "score": 93465.83147388368 }, { "content": "/// Get exchange rate\n\npub fn get_state<S: Storage>(storage: &S) -> StdResult<State> {\n\n ReadonlySingleton::new(storage, STATE_PREFIX).load()\n\n}\n\n\n", "file_path": "contracts/q_native/src/state.rs", "rank": 25, "score": 83476.4594357385 }, { "content": "/// Get config\n\npub fn get_config<S: Storage>(storage: &S) -> StdResult<Config> {\n\n ReadonlySingleton::new(storage, CONFIG_PREFIX).load()\n\n}\n\n\n", "file_path": "contracts/q_native/src/state.rs", "rank": 26, "score": 83476.45943573852 }, { "content": "pub fn set_borrow_balance<S: Storage>(\n\n store: &mut S,\n\n owner: &CanonicalAddr,\n\n snapshot: Option<BorrowSnapshot>,\n\n) -> StdResult<()> {\n\n match Bucket::new(BORROW_PREFIX, store).save(owner.as_slice(), &snapshot) {\n\n Ok(_) => Ok(()),\n\n Err(_) => Err(StdError::generic_err(format!(\n\n \"Failed to write to the borrow_balance. key: {:?}, value: {:?}\",\n\n owner, snapshot\n\n ))),\n\n }\n\n}", "file_path": "contracts/q_native/src/state.rs", "rank": 27, "score": 70970.04468723385 }, { "content": "/// truncate a number according to given mantissa\n\npub fn truncate(a: u128) -> u128 {\n\n a / scale\n\n}", "file_path": "libraries/math/lib.rs", "rank": 31, "score": 55841.35075263574 }, { "content": "/// truncate a number according to given mantissa\n\npub fn truncate(a: u128) -> u128 {\n\n a / scale\n\n}", "file_path": "contracts/q_native/src/contract/handler/exponential.rs", "rank": 32, "score": 52033.78275204211 }, { "content": "fn main() {\n\n let mut out_dir: PathBuf = current_dir().unwrap().parent().unwrap().parent().unwrap().to_path_buf();\n\n out_dir.push(\"schemas\");\n\n out_dir.push(format!(\"{}_schema\", option_env!(\"CARGO_PKG_NAME\").unwrap()));\n\n create_dir_all(&out_dir).unwrap();\n\n remove_schemas(&out_dir).unwrap();\n\n\n\n export_schema(&schema_for!(InitMsg), &out_dir);\n\n export_schema(&schema_for!(HandleMsg), &out_dir);\n\n export_schema(&schema_for!(QueryMsg), &out_dir);\n\n export_schema(&schema_for!(Config), &out_dir);\n\n export_schema(&schema_for!(ConfigResponse), &out_dir);\n\n}\n", "file_path": "contracts/q_native/examples/schema.rs", "rank": 33, "score": 28022.25177811984 }, { "content": " let address_key = deps.api.canonical_address(&address)?;\n\n let balance = get_balance(&deps.storage, &address_key)?;\n\n let out = to_binary(&BalanceResponse {\n\n balance: Uint128::from(balance),\n\n })?;\n\n Ok(out)\n\n }\n\n QueryMsg::Allowance { owner, spender } => {\n\n let owner_key = deps.api.canonical_address(&owner)?;\n\n let spender_key = deps.api.canonical_address(&spender)?;\n\n let allowance = get_allowance(&deps.storage, &owner_key, &spender_key)?;\n\n let out = to_binary(&AllowanceResponse {\n\n allowance: Uint128::from(allowance),\n\n })?;\n\n Ok(out)\n\n }\n\n }\n\n}\n", "file_path": "contracts/q_native/src/contract/querier/mod.rs", "rank": 34, "score": 21967.186312770926 }, { "content": "use cosmwasm_std::{to_binary, Api, Binary, Env, Extern, Querier, StdResult, Storage, Uint128};\n\n\n\nuse crate::msg::{ConfigResponse, QueryMsg, BalanceResponse, AllowanceResponse};\n\nuse crate::state::{get_allowance, get_balance, get_config};\n\n\n", "file_path": "contracts/q_native/src/contract/querier/mod.rs", "rank": 35, "score": 21965.686986409222 }, { "content": " let recipient_address_raw = deps.api.canonical_address(&env.message.sender)?;\n\n mint_tokens(\n\n &mut deps.storage,\n\n &recipient_address_raw,\n\n token_mint_amount,\n\n )?;\n\n\n\n let res = HandleResponse {\n\n messages: vec![],\n\n log: vec![\n\n log(\"action\", \"mint\"),\n\n log(\"sender\", env.message.sender.as_str()),\n\n log(\"minted_amount\", token_mint_amount.clone())\n\n ],\n\n data: None,\n\n };\n\n Ok(res)\n\n}\n\n\n", "file_path": "contracts/q_native/src/contract/handler/collateral.rs", "rank": 37, "score": 21.738237657967243 }, { "content": "pub enum HandleMsg {\n\n Mint {},\n\n Redeem {\n\n redeem_tokens_in: Uint128\n\n },\n\n Borrow {\n\n borrow_amount: Uint128\n\n },\n\n RepayBorrow {},\n\n Approve {\n\n spender: HumanAddr,\n\n amount: Uint128,\n\n },\n\n Transfer {\n\n recipient: HumanAddr,\n\n amount: Uint128,\n\n },\n\n TransferFrom {\n\n owner: HumanAddr,\n\n recipient: HumanAddr,\n", "file_path": "contracts/q_native/src/msg.rs", "rank": 38, "score": 16.055647142559803 }, { "content": "pub enum HandleMsg {\n\n Mint {},\n\n Redeem {\n\n redeem_tokens_in: Uint128\n\n },\n\n Borrow {\n\n borrow_amount: Uint128\n\n },\n\n RepayBorrow {},\n\n Approve {\n\n spender: HumanAddr,\n\n amount: Uint128,\n\n },\n\n Transfer {\n\n recipient: HumanAddr,\n\n amount: Uint128,\n\n },\n\n TransferFrom {\n\n owner: HumanAddr,\n\n recipient: HumanAddr,\n", "file_path": "interfaces/quasar-interfaces/lib.rs", "rank": 39, "score": 16.0556471425598 }, { "content": " denom: \"uluna\".to_string(),\n\n amount: Uint128::from(redeem_native.clone()),\n\n }],\n\n });\n\n\n\n\n\n // TODO: write defense hook\n\n\n\n let res = HandleResponse {\n\n messages: vec![\n\n native_transfer\n\n ],\n\n log: vec![\n\n log(\"action\", \"redeem\"),\n\n log(\"sender\", env.message.sender.as_str()),\n\n log(\"redeem_tokens\", redeem_tokens.clone()),\n\n log(\"redeem_native\", redeem_native.clone())\n\n ],\n\n data: None,\n\n };\n\n Ok(res)\n\n}\n\n\n", "file_path": "contracts/q_native/src/contract/handler/collateral.rs", "rank": 41, "score": 14.88415068181919 }, { "content": " // Check native currency transfer\n\n let mint_amount = env.message.sent_funds[0].amount.u128(); \n\n\n\n // Get exchange rate derived from borrow and reserve\n\n let exchange_rate = get_exchange_rate(deps, env.clone())?;\n\n\n\n let token_mint_amount = truncate(mint_amount * exchange_rate);\n\n\n\n // Set new config\n\n let mut new_config = get_config(&deps.storage)?;\n\n new_config.total_supply += Uint128::from(token_mint_amount);\n\n\n\n // Set new cash amount for contract\n\n let mut new_state = get_state(&deps.storage)?;\n\n new_state.cash += Uint128::from(mint_amount);\n\n set_state(&mut deps.storage, &new_state)?;\n\n\n\n set_config(&mut deps.storage, &new_config)?;\n\n\n\n // Mint token to the sender\n", "file_path": "contracts/q_native/src/contract/handler/collateral.rs", "rank": 42, "score": 13.58235364212994 }, { "content": " &mut deps.storage,\n\n &recipient_address_raw,\n\n redeem_tokens,\n\n )?;\n\n\n\n // Check if the pool has enough balance\n\n if state.cash < Uint128::from(redeem_native) {\n\n return Err(StdError::generic_err(format!(\n\n \"The lending pool has insufficient cash: redeem_amount: {}, pool_reserve: {}\",\n\n redeem_native, state.cash)\n\n )\n\n );\n\n }\n\n\n\n // Transfer native token to the user\n\n // TODO: in this case it is hard coded to luna, include denom in contract config\n\n let native_transfer: CosmosMsg = CosmosMsg::Bank(BankMsg::Send {\n\n from_address: env.contract.address.clone(),\n\n to_address: env.message.sender.clone(),\n\n amount: vec![Coin {\n", "file_path": "contracts/q_native/src/contract/handler/collateral.rs", "rank": 43, "score": 13.253003154164025 }, { "content": " let res = HandleResponse {\n\n messages: vec![native_transfer],\n\n log: vec![\n\n log(\"action\", \"borrow\"),\n\n log(\"sender\", env.message.sender.as_str()),\n\n log(\"new_account_borrow\", new_account_borrow.clone()),\n\n log(\"new_total_borrows\", new_state.clone().total_borrows)\n\n ],\n\n data: None,\n\n };\n\n Ok(res)\n\n}\n\n\n", "file_path": "contracts/q_native/src/contract/handler/collateral.rs", "rank": 44, "score": 13.158191821438095 }, { "content": " // Set new cash amount for contract\n\n let mut new_state = state.clone();\n\n new_state.cash += Uint128::from(redeem_native_in);\n\n (redeem_native_in, truncate(redeem_native_in / (100_000_000 * exchange_rate)), new_state)\n\n }\n\n };\n\n\n\n // Set new state for cash\n\n set_state(&mut deps.storage, &new_state)?;\n\n\n\n // Set new config\n\n let mut new_config = get_config(&deps.storage)?;\n\n new_config.total_supply = (new_config.total_supply - Uint128::from(redeem_tokens))?;\n\n set_config(&mut deps.storage, &new_config)?;\n\n\n\n \n\n\n\n // Burn token to the sender\n\n let recipient_address_raw = deps.api.canonical_address(&env.message.sender)?;\n\n burn_tokens(\n", "file_path": "contracts/q_native/src/contract/handler/collateral.rs", "rank": 45, "score": 12.522308252871808 }, { "content": " set_state(&mut deps.storage, &new_state)?;\n\n\n\n // Set new borrow balance for the sender\n\n let new_borrow_balance = BorrowSnapshot {\n\n principal: Uint128::from(new_account_borrow),\n\n interest_index: new_state.borrow_index\n\n };\n\n set_borrow_balance(&mut deps.storage, &sender_raw, Some(new_borrow_balance))?;\n\n \n\n // Transfer native token to the user\n\n // TODO: in this case it is hard coded to luna, include denom in contract config\n\n let native_transfer: CosmosMsg = CosmosMsg::Bank(BankMsg::Send {\n\n from_address: env.contract.address.clone(),\n\n to_address: env.message.sender.clone(),\n\n amount: vec![Coin {\n\n denom: \"uluna\".to_string(),\n\n amount: borrow_amount.clone(),\n\n }],\n\n });\n\n \n", "file_path": "contracts/q_native/src/contract/handler/collateral.rs", "rank": 46, "score": 12.196014409980792 }, { "content": "use cosmwasm_std::{Api, Env, Extern, InitResponse, Querier, StdResult, Storage, Uint128};\n\n\n\nuse crate::msg::InitMsg;\n\nuse crate::state::{config, Config, set_state, State};\n\n\n\n/// Contract instantiation tx\n\n/// tx inputs are specified in InitMsg in msg.rs file\n", "file_path": "contracts/q_native/src/contract/init/mod.rs", "rank": 47, "score": 11.354873144655997 }, { "content": " // Check if the pool has enough balance to lend to the sender\n\n if state.cash < borrow_amount { \n\n return Err(StdError::generic_err(format!(\n\n \"The lending pool has insufficient cash: redeem_amount: {}, pool_reserve: {}\",\n\n borrow_amount, state.cash)\n\n )\n\n );\n\n }\n\n\n\n // Get borrow balance of the sender\n\n let sender_raw = deps.api.canonical_address(&env.message.sender)?;\n\n // get borrow balance\n\n let account_borrow = get_account_borrow(deps, env.clone())?;\n\n let new_account_borrow = account_borrow + borrow_amount.u128();\n\n \n\n\n\n // Set new cash amount for contract\n\n let mut new_state = get_state(&deps.storage)?;\n\n new_state.cash =(new_state.cash - borrow_amount)?;\n\n new_state.total_borrows += borrow_amount;\n", "file_path": "contracts/q_native/src/contract/handler/collateral.rs", "rank": 48, "score": 10.50511440990604 }, { "content": "use cosmwasm_std::{\n\n log, Api, Env, Extern, HandleResponse, Querier,\n\n StdError, StdResult, Storage, Uint128, BankMsg, CosmosMsg, Coin\n\n};\n\n\n\nuse std::convert::TryInto;\n\n\n\nuse crate::state::{get_state, set_state, get_config, set_config, set_borrow_balance, get_borrow_balance, BorrowSnapshot};\n\n\n\nuse crate::contract::handler::interest_model::{get_borrow_rate};\n\nuse crate::contract::handler::exponential::truncate;\n\nuse crate::contract::handler::token::{mint_tokens, burn_tokens};\n\n\n", "file_path": "contracts/q_native/src/contract/handler/collateral.rs", "rank": 49, "score": 10.11551330529101 }, { "content": "use schemars::JsonSchema;\n\nuse serde::{Deserialize, Serialize};\n\n\n\nuse cosmwasm_std::{CanonicalAddr, StdError, StdResult, Storage, Uint128, ReadonlyStorage};\n\nuse cosmwasm_storage::{singleton, Bucket, ReadonlyBucket, ReadonlySingleton, Singleton, ReadonlyPrefixedStorage, PrefixedStorage};\n\nuse std::convert::TryInto;\n\n\n\npub static CONFIG_PREFIX: &[u8] = b\"config\";\n\npub static BALANCE_PREFIX: &[u8] = b\"balances\";\n\npub static ALLOWANCE_PREFIX: &[u8] = b\"allowance\";\n\npub static STATE_PREFIX: &[u8] = b\"state\";\n\npub static BORROW_PREFIX: &[u8] = b\"borrow\";\n\n\n\n/// Config struct\n\n#[derive(Serialize, Deserialize, Clone, Debug, PartialEq, JsonSchema)]\n\npub struct Config {\n\n pub name: String,\n\n pub total_supply: Uint128,\n\n pub decimals: u8,\n\n pub symbol: String,\n", "file_path": "contracts/q_native/src/state.rs", "rank": 50, "score": 9.745469669753323 }, { "content": "use cosmwasm_std::{Api, Empty, Env, Extern, HandleResponse, Querier, StdResult, Storage};\n\n\n\nuse crate::msg::HandleMsg;\n\n\n\nmod collateral;\n\nmod token;\n\nmod exponential;\n\nmod interest_model;\n\n\n\n/// General handler for contract tx input\n\n/// tx inputs are defined HandleMsg enum in msg.rs file\n", "file_path": "contracts/q_native/src/contract/handler/mod.rs", "rank": 51, "score": 9.327977435100767 }, { "content": " amount: Uint128,\n\n },\n\n}\n\n\n\n#[derive(Serialize, Deserialize, Clone, Debug, PartialEq, JsonSchema)]\n\n#[serde(rename_all = \"snake_case\")]\n\npub enum QueryMsg {\n\n Config {},\n\n Balance {\n\n address: HumanAddr,\n\n },\n\n Allowance {\n\n owner: HumanAddr,\n\n spender: HumanAddr,\n\n },\n\n}\n\n\n\n#[derive(Serialize, Deserialize, Clone, PartialEq, JsonSchema)]\n\npub struct ConfigResponse {\n\n pub name: String,\n", "file_path": "contracts/q_native/src/msg.rs", "rank": 52, "score": 9.151363440976949 }, { "content": " amount: Uint128,\n\n },\n\n}\n\n\n\n#[derive(Serialize, Deserialize, Clone, Debug, PartialEq, JsonSchema)]\n\n#[serde(rename_all = \"snake_case\")]\n\npub enum QueryMsg {\n\n Config {},\n\n Balance {\n\n address: HumanAddr,\n\n },\n\n Allowance {\n\n owner: HumanAddr,\n\n spender: HumanAddr,\n\n },\n\n}\n\n\n\n#[derive(Serialize, Deserialize, Clone, PartialEq, JsonSchema)]\n\npub struct ConfigResponse {\n\n pub name: String,\n", "file_path": "interfaces/quasar-interfaces/lib.rs", "rank": 53, "score": 9.151363440976949 }, { "content": "pub mod handler;\n\npub mod init;\n\npub mod querier;\n\n\n\npub use handler::handle;\n\n\n\npub use init::init;\n\n\n\npub use querier::query;\n", "file_path": "contracts/q_native/src/contract/mod.rs", "rank": 54, "score": 8.47632307731648 }, { "content": " pub total_supply: Uint128,\n\n pub decimals: u8,\n\n pub symbol: String,\n\n pub intital_exchange_rate: Uint128,\n\n pub reserve_factor: Uint128,\n\n pub borrow_index: Uint128,\n\n pub denom: String\n\n}\n\n\n\n#[derive(Serialize, Deserialize, Clone, PartialEq, JsonSchema)]\n\npub struct BalanceResponse {\n\n pub balance: Uint128,\n\n}\n\n\n\n#[derive(Serialize, Deserialize, Clone, PartialEq, JsonSchema)]\n\npub struct AllowanceResponse {\n\n pub allowance: Uint128,\n\n}\n", "file_path": "contracts/q_native/src/msg.rs", "rank": 55, "score": 7.375888084614269 }, { "content": " pub total_supply: Uint128,\n\n pub decimals: u8,\n\n pub symbol: String,\n\n pub intital_exchange_rate: Uint128,\n\n pub reserve_factor: Uint128,\n\n pub borrow_index: Uint128,\n\n pub denom: String\n\n}\n\n\n\n#[derive(Serialize, Deserialize, Clone, PartialEq, JsonSchema)]\n\npub struct BalanceResponse {\n\n pub balance: Uint128,\n\n}\n\n\n\n#[derive(Serialize, Deserialize, Clone, PartialEq, JsonSchema)]\n\npub struct AllowanceResponse {\n\n pub allowance: Uint128,\n\n}\n", "file_path": "interfaces/quasar-interfaces/lib.rs", "rank": 56, "score": 7.375888084614269 }, { "content": "use schemars::JsonSchema;\n\nuse serde::{Deserialize, Serialize};\n\n\n\nuse cosmwasm_std::{HumanAddr, Uint128};\n\n\n\n#[derive(Serialize, Deserialize, Clone, Debug, PartialEq, JsonSchema)]\n\npub struct InitMsg {\n\n pub name: String,\n\n pub total_supply: Uint128,\n\n pub decimals: u8,\n\n pub symbol: String,\n\n pub initial_exchange_rate: Uint128,\n\n pub reserve_factor: Uint128,\n\n pub borrow_index: Uint128,\n\n pub max_borrow_rate: Uint128,\n\n pub denom: String\n\n}\n\n\n\n#[derive(Serialize, Deserialize, Clone, Debug, PartialEq, JsonSchema)]\n\n#[serde(rename_all = \"snake_case\")]\n", "file_path": "interfaces/quasar-interfaces/lib.rs", "rank": 57, "score": 7.152136174204443 }, { "content": "use schemars::JsonSchema;\n\nuse serde::{Deserialize, Serialize};\n\n\n\nuse cosmwasm_std::{HumanAddr, Uint128};\n\n\n\n#[derive(Serialize, Deserialize, Clone, Debug, PartialEq, JsonSchema)]\n\npub struct InitMsg {\n\n pub name: String,\n\n pub total_supply: Uint128,\n\n pub decimals: u8,\n\n pub symbol: String,\n\n pub initial_exchange_rate: Uint128,\n\n pub reserve_factor: Uint128,\n\n pub borrow_index: Uint128,\n\n pub max_borrow_rate: Uint128,\n\n pub denom: String\n\n}\n\n\n\n#[derive(Serialize, Deserialize, Clone, Debug, PartialEq, JsonSchema)]\n\n#[serde(rename_all = \"snake_case\")]\n", "file_path": "contracts/q_native/src/msg.rs", "rank": 58, "score": 7.152136174204443 }, { "content": " let exchange_rate = get_exchange_rate(deps, env.clone())?;\n\n\n\n let redeem_native_in = env.message.sent_funds[0].amount.u128();\n\n if redeem_tokens_in.u128() != 0 && redeem_native_in != 0 {\n\n return Err(StdError::generic_err(format!(\n\n \"one of redeeming tokens or asset must be 0: redeeming_cw20: {}, redeeming_native_currency: {}\",\n\n redeem_tokens_in.u128(), redeem_native_in)\n\n )\n\n );\n\n }\n\n // Calculate redeem amount\n\n let (redeem_native, redeem_tokens, new_state) = match redeem_tokens_in.u128() {\n\n x if x > 0 => {\n\n // Set new cash amount for contract\n\n let mut new_state = state.clone();\n\n let redeem_native = truncate(exchange_rate * 100_000_000 * redeem_tokens_in.u128());\n\n new_state.cash = (new_state.cash - Uint128::from(redeem_native))?;\n\n (redeem_native, redeem_tokens_in.u128(), new_state) \n\n },\n\n _ => {\n", "file_path": "contracts/q_native/src/contract/handler/collateral.rs", "rank": 59, "score": 6.7341156899230175 }, { "content": " let init_state = State {\n\n cash: Uint128::from(0u128),\n\n block_number: env.block.height,\n\n total_reserves: Uint128::from(0u128),\n\n total_borrows: Uint128::from(0u128),\n\n exchange_rate: init_config.initial_exchange_rate,\n\n reserve_factor: init_config.reserve_factor,\n\n max_borrow_rate: init_config.max_borrow_rate,//100_000_000_000,\n\n borrow_index: init_config.borrow_index\n\n };\n\n\n\n set_state(&mut deps.storage, &init_state)?;\n\n \n\n\n\n Ok(InitResponse::default())\n\n}\n", "file_path": "contracts/q_native/src/contract/init/mod.rs", "rank": 60, "score": 6.655040031890274 }, { "content": " let accumulated_interest = truncate(simple_interest_factor * prior_state.total_borrows.u128());\n\n let new_total_borrows = accumulated_interest + prior_state.total_borrows.u128();\n\n let new_total_reserves = truncate(accumulated_interest * prior_state.reserve_factor.u128()) + prior_state.total_reserves.u128();\n\n let new_borrow_index = truncate(simple_interest_factor * prior_state.borrow_index.u128()) + prior_state.borrow_index.u128();\n\n\n\n // Set new state\n\n let mut new_state = get_state(&deps.storage)?;\n\n new_state.block_number = env.block.height; \n\n new_state.borrow_index = Uint128::from(new_borrow_index);\n\n new_state.total_borrows = Uint128::from(new_total_borrows);\n\n new_state.total_reserves = Uint128::from(new_total_reserves);\n\n\n\n set_state(&mut deps.storage, &new_state)?;\n\n\n\n\n\n Ok(())\n\n}\n\n\n", "file_path": "contracts/q_native/src/contract/handler/collateral.rs", "rank": 61, "score": 6.280313873765152 }, { "content": " pub initial_exchange_rate: Uint128,\n\n pub reserve_factor: Uint128,\n\n pub borrow_index: Uint128,\n\n pub max_borrow_rate: Uint128,\n\n pub denom: String,\n\n}\n\n\n\n/// State struct\n\n#[derive(Serialize, Deserialize, Clone, Debug, PartialEq, JsonSchema)]\n\npub struct State {\n\n pub cash: Uint128,\n\n pub block_number: u64,\n\n pub total_reserves: Uint128,\n\n pub total_borrows: Uint128,\n\n pub exchange_rate: Uint128,\n\n pub reserve_factor: Uint128,\n\n pub max_borrow_rate: Uint128,\n\n pub borrow_index: Uint128\n\n}\n\n\n\n#[derive(Serialize, Deserialize, Clone, Debug, PartialEq, JsonSchema)]\n\npub struct BorrowSnapshot {\n\n pub principal: Uint128,\n\n pub interest_index: Uint128\n\n}\n\n\n\n/// Config singleton initialization\n", "file_path": "contracts/q_native/src/state.rs", "rank": 62, "score": 5.725828796835414 }, { "content": "// A mockup interest model \n\n// TODO: make this in a separate contract and let someone manage this per each collaterized asset \n\nuse cosmwasm_std::{Uint128};\n\n// constant that needs to be managed\n\npub static multiplier_per_block: u128 = 23; // 0.000000237823 * 10^8\n\npub static base_rate_per_block: u128 = 0; \n\npub static jump_multiplier_per_block: u128 = 51; // 0.000000518455 * 10^8;\n\npub static kink: u128 = 80_000_000; // 0.8 * 10^8\n\n//pub static config_reserve_factor: u128 = 5_000_000; // 0.05 * 10^8\n\n\n", "file_path": "contracts/q_native/src/contract/handler/interest_model.rs", "rank": 63, "score": 5.145388095696095 }, { "content": "use std::env::current_dir;\n\nuse std::fs::create_dir_all;\n\nuse std::path::{Path, PathBuf};\n\n\n\nuse cosmwasm_schema::{export_schema, remove_schemas, schema_for};\n\n\n\nuse q_native::msg::*;\n\nuse q_native::state::*;\n\n\n", "file_path": "contracts/q_native/examples/schema.rs", "rank": 64, "score": 4.665378500642104 }, { "content": "pub mod contract;\n\npub mod msg;\n\npub mod state;\n\n\n\n#[cfg(target_arch = \"wasm32\")]\n\ncosmwasm_std::create_entry_points!(contract);\n\n\n\n\n", "file_path": "contracts/q_native/src/lib.rs", "rank": 65, "score": 2.7648639502107613 }, { "content": "/// exponential math lib\n\n/// TODO: Generalize this for each cToken asset\n\npub static scale: u128 = 100_000_000; // 10^8\n\n\n\n/// truncate a number according to given mantissa\n", "file_path": "contracts/q_native/src/contract/handler/exponential.rs", "rank": 66, "score": 1.9955437120598025 }, { "content": "/// exponential math lib\n\n/// TODO: Generalize this for each cToken asset\n\npub static scale: u128 = 100_000_000; // 10^8\n\n\n\n/// truncate a number according to given mantissa\n", "file_path": "libraries/math/lib.rs", "rank": 67, "score": 1.9955437120598025 } ]
Rust
nfe/src/base/totais.rs
fernandobatels/fiscal-rs
9c5856907dd1c4429dc256a41914676fc0cc5a70
use super::Error; use serde::{Deserialize, Deserializer, Serialize, Serializer}; use std::str::FromStr; #[derive(Debug, PartialEq, Clone)] pub struct Totalizacao { pub valor_base_calculo: f32, pub valor_icms: f32, pub valor_produtos: f32, pub valor_frete: f32, pub valor_seguro: f32, pub valor_desconto: f32, pub valor_outros: f32, pub valor_pis: f32, pub valor_cofins: f32, pub valor_total: f32, pub valor_aproximado_tributos: f32, } impl FromStr for Totalizacao { type Err = Error; fn from_str(s: &str) -> Result<Self, Self::Err> { quick_xml::de::from_str(s).map_err(|e| e.into()) } } impl ToString for Totalizacao { fn to_string(&self) -> String { quick_xml::se::to_string(self).expect("Falha ao serializar a totalização") } } impl Serialize for Totalizacao { fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error> where S: Serializer, { let icms = IcmsTot { valor_base_calculo: self.valor_base_calculo, valor_icms: self.valor_icms, valor_produtos: self.valor_produtos, valor_frete: self.valor_frete, valor_seguro: self.valor_seguro, valor_desconto: self.valor_desconto, valor_outros: self.valor_outros, valor_pis: self.valor_pis, valor_cofins: self.valor_cofins, valor_total: self.valor_total, valor_aproximado_tributos: self.valor_aproximado_tributos, }; let total = TotalContainer { icms }; total.serialize(serializer) } } impl<'de> Deserialize<'de> for Totalizacao { fn deserialize<D>(deserializer: D) -> Result<Self, D::Error> where D: Deserializer<'de>, { let helper = TotalContainer::deserialize(deserializer)?; Ok(Totalizacao { valor_base_calculo: helper.icms.valor_base_calculo, valor_icms: helper.icms.valor_icms, valor_produtos: helper.icms.valor_produtos, valor_frete: helper.icms.valor_frete, valor_seguro: helper.icms.valor_seguro, valor_desconto: helper.icms.valor_desconto, valor_outros: helper.icms.valor_outros, valor_pis: helper.icms.valor_pis, valor_cofins: helper.icms.valor_cofins, valor_total: helper.icms.valor_total, valor_aproximado_tributos: helper.icms.valor_aproximado_tributos, }) } } #[derive(Deserialize, Serialize)] #[serde(rename = "total")] struct TotalContainer { #[serde(rename = "ICMSTot")] icms: IcmsTot, } #[derive(Deserialize, Serialize)] struct IcmsTot { #[serde(rename = "$unflatten=vBC")] valor_base_calculo: f32, #[serde(rename = "$unflatten=vICMS")] valor_icms: f32, #[serde(rename = "$unflatten=vProd")] valor_produtos: f32, #[serde(rename = "$unflatten=vFrete")] valor_frete: f32, #[serde(rename = "$unflatten=vSeg")] valor_seguro: f32, #[serde(rename = "$unflatten=vDesc")] valor_desconto: f32, #[serde(rename = "$unflatten=vOutro")] valor_outros: f32, #[serde(rename = "$unflatten=vPIS")] valor_pis: f32, #[serde(rename = "$unflatten=vCOFINS")] valor_cofins: f32, #[serde(rename = "$unflatten=vNF")] valor_total: f32, #[serde(rename = "$unflatten=vTotTrib")] valor_aproximado_tributos: f32, }
use super::Error; use serde::{Deserialize, Deserializer, Serialize, Serializer}; use std::str::FromStr; #[derive(Debug, PartialEq, Clone)] pub struct Totalizacao { pub valor_base_calculo: f32, pub valor_icms: f32, pub valor_produtos: f32, pub valor_frete: f32, pub valor_seguro: f32, pub valor_desconto: f32, pub valor_outros: f32, pub valor_pis: f32, pub valor_cofins: f32, pub valor_total: f32, pub valor_aproximado_tributos: f32, } impl FromStr for Totalizacao { type Err = Error; fn from_str(s: &str) -> Result<Self, Self::Err> { quick_xml::de::from_str(s).map_err(|e| e.into()) } } impl ToString for Totalizacao { fn to_string(&self) -> String { quick_xml::se::to_string(self).expect("Falha ao serializar a totalização") } } impl Serialize for Totalizacao {
} impl<'de> Deserialize<'de> for Totalizacao { fn deserialize<D>(deserializer: D) -> Result<Self, D::Error> where D: Deserializer<'de>, { let helper = TotalContainer::deserialize(deserializer)?; Ok(Totalizacao { valor_base_calculo: helper.icms.valor_base_calculo, valor_icms: helper.icms.valor_icms, valor_produtos: helper.icms.valor_produtos, valor_frete: helper.icms.valor_frete, valor_seguro: helper.icms.valor_seguro, valor_desconto: helper.icms.valor_desconto, valor_outros: helper.icms.valor_outros, valor_pis: helper.icms.valor_pis, valor_cofins: helper.icms.valor_cofins, valor_total: helper.icms.valor_total, valor_aproximado_tributos: helper.icms.valor_aproximado_tributos, }) } } #[derive(Deserialize, Serialize)] #[serde(rename = "total")] struct TotalContainer { #[serde(rename = "ICMSTot")] icms: IcmsTot, } #[derive(Deserialize, Serialize)] struct IcmsTot { #[serde(rename = "$unflatten=vBC")] valor_base_calculo: f32, #[serde(rename = "$unflatten=vICMS")] valor_icms: f32, #[serde(rename = "$unflatten=vProd")] valor_produtos: f32, #[serde(rename = "$unflatten=vFrete")] valor_frete: f32, #[serde(rename = "$unflatten=vSeg")] valor_seguro: f32, #[serde(rename = "$unflatten=vDesc")] valor_desconto: f32, #[serde(rename = "$unflatten=vOutro")] valor_outros: f32, #[serde(rename = "$unflatten=vPIS")] valor_pis: f32, #[serde(rename = "$unflatten=vCOFINS")] valor_cofins: f32, #[serde(rename = "$unflatten=vNF")] valor_total: f32, #[serde(rename = "$unflatten=vTotTrib")] valor_aproximado_tributos: f32, }
fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error> where S: Serializer, { let icms = IcmsTot { valor_base_calculo: self.valor_base_calculo, valor_icms: self.valor_icms, valor_produtos: self.valor_produtos, valor_frete: self.valor_frete, valor_seguro: self.valor_seguro, valor_desconto: self.valor_desconto, valor_outros: self.valor_outros, valor_pis: self.valor_pis, valor_cofins: self.valor_cofins, valor_total: self.valor_total, valor_aproximado_tributos: self.valor_aproximado_tributos, }; let total = TotalContainer { icms }; total.serialize(serializer) }
function_block-full_function
[ { "content": "#[test]\n\nfn to_string() -> Result<(), Error> {\n\n let mut xml_original = \"<transp><modFrete>9</modFrete></transp>\".to_string();\n\n xml_original.retain(|c| c != '\\n' && c != ' ');\n\n\n\n let transporte = xml_original.parse::<Transporte>()?;\n\n let xml_novo = transporte.to_string();\n\n\n\n assert_eq!(xml_original, xml_novo);\n\n\n\n Ok(())\n\n}\n", "file_path": "nfe/src/tests/transporte.rs", "rank": 0, "score": 111052.34146284375 }, { "content": "#[test]\n\nfn to_string() -> Result<(), Error> {\n\n let mut xml_original = \"\n\n <dest>\n\n <CNPJ>58716523000119</CNPJ>\n\n <xNome>HOMOLOGACAO</xNome>\n\n <enderDest>\n\n <xLgr>Av.Teste</xLgr>\n\n <nro>2040</nro>\n\n <xBairro>Centro</xBairro>\n\n <cMun>3550308</cMun>\n\n <xMun>Guarulhos</xMun>\n\n <UF>SP</UF>\n\n <CEP>04207040</CEP>\n\n <cPais>1058</cPais>\n\n <xPais>BRASIL</xPais>\n\n <fone>5190909090</fone>\n\n </enderDest>\n\n <IE>112006603110</IE>\n\n <indIEDest>1</indIEDest>\n\n </dest>\n", "file_path": "nfe/src/tests/dest.rs", "rank": 1, "score": 111052.34146284375 }, { "content": "#[test]\n\nfn to_string() -> Result<(), Error> {\n\n let mut xml_original = \"\n\n <det nItem=\\\"1\\\">\n\n <prod>\n\n <cProd>11007</cProd>\n\n <cEAN>SEM GTIN</cEAN>\n\n <xProd>UM PRODUTO TESTE QUALQUER</xProd>\n\n <NCM>64011000</NCM>\n\n <uCom>UN</uCom>\n\n <qCom>10</qCom>\n\n <vUnCom>50</vUnCom>\n\n <vProd>500</vProd>\n\n <indTot>1</indTot>\n\n <CEST>1234567</CEST>\n\n <CFOP>6101</CFOP>\n\n <cEANTrib>SEM GTIN</cEANTrib>\n\n <uTrib>UN</uTrib>\n\n <qTrib>10</qTrib>\n\n <vUnTrib>50</vUnTrib>\n\n </prod>\n", "file_path": "nfe/src/tests/itens.rs", "rank": 2, "score": 111052.34146284375 }, { "content": "#[test]\n\nfn to_string() -> Result<(), Error> {\n\n let mut xml_original = \"<Endereco>\n\n <xLgr>Rua</xLgr>\n\n <nro>1020</nro>\n\n <xCpl>0</xCpl>\n\n <xBairro>Centro</xBairro>\n\n <cMun>4319901</cMun>\n\n <xMun>SAPIRANGA</xMun>\n\n <UF>RS</UF>\n\n <CEP>93800000</CEP>\n\n <cPais>1058</cPais>\n\n <xPais>BRASIL</xPais>\n\n <fone>5190909090</fone>\n\n </Endereco>\"\n\n .to_string();\n\n xml_original.retain(|c| c != '\\n' && c != ' ');\n\n\n\n let endereco = xml_original.parse::<Endereco>()?;\n\n let xml_novo = endereco.to_string();\n\n\n\n assert_eq!(xml_original, xml_novo);\n\n\n\n Ok(())\n\n}\n", "file_path": "nfe/src/tests/endereco.rs", "rank": 3, "score": 111052.34146284375 }, { "content": "#[test]\n\nfn to_string() -> Result<(), Error> {\n\n let mut xml_original = XML_MANUAL.to_string();\n\n xml_original.retain(|c| c != '\\n' && c != ' ');\n\n\n\n let ide = xml_original.parse::<Identificacao>()?;\n\n let xml_novo = ide.to_string();\n\n\n\n assert_eq!(xml_original, xml_novo);\n\n\n\n Ok(())\n\n}\n\n\n\nconst XML_MANUAL: &str = \"\n\n <ide>\n\n <cUF>43</cUF>\n\n <nNF>26</nNF>\n\n <serie>1</serie>\n\n <mod>55</mod>\n\n <cMunFG>4307609</cMunFG>\n\n <tpImp>1</tpImp>\n", "file_path": "nfe/src/tests/ide.rs", "rank": 4, "score": 111052.34146284375 }, { "content": "#[test]\n\nfn to_string() -> Result<(), Error> {\n\n let mut xml_original = \"<total>\n\n <ICMSTot>\n\n <vBC>0</vBC>\n\n <vICMS>0</vICMS>\n\n <vProd>150</vProd>\n\n <vFrete>0</vFrete>\n\n <vSeg>0</vSeg>\n\n <vDesc>0</vDesc>\n\n <vOutro>10</vOutro>\n\n <vPIS>0.89</vPIS>\n\n <vCOFINS>4.09</vCOFINS>\n\n <vNF>150</vNF>\n\n <vTotTrib>35.75</vTotTrib>\n\n </ICMSTot>\n\n </total>\"\n\n .to_string();\n\n xml_original.retain(|c| c != '\\n' && c != ' ');\n\n\n\n let totalizacao = xml_original.parse::<Totalizacao>()?;\n\n let xml_novo = totalizacao.to_string();\n\n\n\n assert_eq!(xml_original, xml_novo);\n\n\n\n Ok(())\n\n}\n", "file_path": "nfe/src/tests/totais.rs", "rank": 5, "score": 111052.34146284375 }, { "content": "#[test]\n\nfn to_string() -> Result<(), Error> {\n\n let mut xml_original = \"\n\n <emit>\n\n <CNPJ>06929383000163</CNPJ>\n\n <xNome>QUALQUER</xNome>\n\n <IE>0018000762</IE>\n\n <enderEmit>\n\n <xLgr>Testes</xLgr>\n\n <nro>1020</nro>\n\n <xCpl>0</xCpl>\n\n <xBairro>Centro</xBairro>\n\n <cMun>4319901</cMun>\n\n <xMun>SAPIRANGA</xMun>\n\n <UF>RS</UF>\n\n <CEP>93800000</CEP>\n\n <cPais>1058</cPais>\n\n <xPais>BRASIL</xPais>\n\n <fone>5190909090</fone>\n\n </enderEmit>\n\n </emit>\n", "file_path": "nfe/src/tests/emit.rs", "rank": 6, "score": 111052.34146284375 }, { "content": "#[test]\n\nfn nfe_from_str() -> Result<(), String> {\n\n let mut f = File::open(\"xmls/nfe_layout4.xml\").map_err(|e| e.to_string())?;\n\n\n\n let mut xml = String::new();\n\n f.read_to_string(&mut xml).map_err(|e| e.to_string())?;\n\n\n\n Nfe::from_str(&xml).map_err(|e| e.to_string())?;\n\n\n\n xml.parse::<Nfe>().map_err(|e| e.to_string())?;\n\n\n\n Ok(())\n\n}\n\n\n", "file_path": "nfe/src/tests/parse.rs", "rank": 7, "score": 108942.05378838693 }, { "content": "#[test]\n\nfn nfce_from_str() -> Result<(), String> {\n\n let mut f = File::open(\"xmls/nfce_layout4.xml\").map_err(|e| e.to_string())?;\n\n\n\n let mut xml = String::new();\n\n f.read_to_string(&mut xml).map_err(|e| e.to_string())?;\n\n\n\n NfeBase::from_str(&xml).map_err(|e| e.to_string())?;\n\n\n\n xml.parse::<NfeBase>().map_err(|e| e.to_string())?;\n\n\n\n Ok(())\n\n}\n\n\n", "file_path": "nfe/src/tests/parse.rs", "rank": 8, "score": 108942.05378838693 }, { "content": "#[test]\n\nfn produto_to_string() -> Result<(), Error> {\n\n let mut xml_original = \"<prod>\n\n <cProd>11007</cProd>\n\n <cEAN>SEM GTIN</cEAN>\n\n <xProd>UM PRODUTO TESTE QUALQUER</xProd>\n\n <NCM>64011000</NCM>\n\n <uCom>UN</uCom>\n\n <qCom>10</qCom>\n\n <vUnCom>50</vUnCom>\n\n <vProd>500</vProd>\n\n <indTot>1</indTot>\n\n <CEST>1234567</CEST>\n\n <CFOP>6101</CFOP>\n\n <cEANTrib>SEM GTIN</cEANTrib>\n\n <uTrib>UN</uTrib>\n\n <qTrib>10</qTrib>\n\n <vUnTrib>50</vUnTrib>\n\n </prod>\"\n\n .to_string();\n\n xml_original.retain(|c| c != '\\n' && c != ' ');\n\n\n\n let produto = xml_original.parse::<Produto>()?;\n\n let xml_novo = produto.to_string();\n\n\n\n assert_eq!(xml_original, xml_novo);\n\n\n\n Ok(())\n\n}\n\n\n", "file_path": "nfe/src/tests/itens.rs", "rank": 9, "score": 108531.10903511477 }, { "content": "#[test]\n\nfn imposto_to_string() -> Result<(), Error> {\n\n let mut xml_original = \"<imposto>\n\n <vTotTrib>0</vTotTrib>\n\n <ICMS>\n\n <ICMSSN202>\n\n <orig>0</orig>\n\n <CSOSN>202</CSOSN>\n\n <modBCST>4</modBCST>\n\n <vBCST>0</vBCST>\n\n <pICMSST>0</pICMSST>\n\n <vICMSST>0</vICMSST>\n\n </ICMSSN202>\n\n </ICMS>\n\n <PIS>\n\n <PISOutr>\n\n <CST>49</CST>\n\n <vBC>0</vBC>\n\n <pPIS>0</pPIS>\n\n </PISOutr>\n\n </PIS>\n", "file_path": "nfe/src/tests/itens.rs", "rank": 10, "score": 108531.10903511477 }, { "content": "#[test]\n\nfn to_string() -> Result<(), String> {\n\n let f = File::open(\"xmls/nfe_layout4.xml\").map_err(|e| e.to_string())?;\n\n let nfe = Nfe::try_from(f).map_err(|e| e.to_string())?;\n\n\n\n let xml_novo = nfe.to_string();\n\n\n\n assert!(xml_novo.contains(\n\n \"<infNFe versao=\\\"4.00\\\" Id=\\\"NFe43180906929383000163550010000000261000010301\\\">\"\n\n ));\n\n assert!(!xml_novo.contains(\"<infAdic>\"));\n\n\n\n Ok(())\n\n}\n\n\n", "file_path": "nfe/src/tests/infnfe.rs", "rank": 11, "score": 91392.53017984034 }, { "content": "#[test]\n\nfn parse_to_string_parse_to_string() -> Result<(), String> {\n\n let f = File::open(\"xmls/nfe_layout4.xml\").map_err(|e| e.to_string())?;\n\n let nfe1 = Nfe::try_from(f).map_err(|e| e.to_string())?;\n\n let xml1 = nfe1.to_string();\n\n\n\n let nfe2 = xml1.parse::<Nfe>().map_err(|e| e.to_string())?;\n\n let xml2 = nfe2.to_string();\n\n\n\n assert_eq!(xml1, xml2);\n\n\n\n Ok(())\n\n}\n\n\n", "file_path": "nfe/src/tests/infnfe.rs", "rank": 12, "score": 91133.20740802784 }, { "content": "#[test]\n\nfn base_parse_to_string_parse_to_string() -> Result<(), String> {\n\n let f = File::open(\"xmls/nfce_layout4.xml\").map_err(|e| e.to_string())?;\n\n let nfe1 = NfeBase::try_from(f).map_err(|e| e.to_string())?;\n\n let xml1 = nfe1.to_string();\n\n\n\n let nfe2 = xml1.parse::<NfeBase>().map_err(|e| e.to_string())?;\n\n let xml2 = nfe2.to_string();\n\n\n\n assert_eq!(xml1, xml2);\n\n\n\n Ok(())\n\n}\n", "file_path": "nfe/src/tests/infnfe.rs", "rank": 13, "score": 89907.69992474426 }, { "content": "#[test]\n\nfn base_to_string() -> Result<(), String> {\n\n let f = File::open(\"xmls/nfce_layout4.xml\").map_err(|e| e.to_string())?;\n\n let nfe = NfeBase::try_from(f).map_err(|e| e.to_string())?;\n\n\n\n let xml_novo = nfe.to_string();\n\n\n\n assert!(xml_novo.contains(\n\n \"<infNFe versao=\\\"4.00\\\" Id=\\\"NFe29181033657677000156650010001654399001654399\\\">\"\n\n ));\n\n println!(\"{}\", xml_novo);\n\n assert!(xml_novo.contains(\"<infAdic><infCpl>11899318;422-JERK DIONNY;CLIENTE RECUSOU INFORMAR CPF/CNPJ NO CUPOM</infCpl></infAdic>\"));\n\n\n\n Ok(())\n\n}\n\n\n", "file_path": "nfe/src/tests/infnfe.rs", "rank": 14, "score": 89853.39332571365 }, { "content": "fn serialize_horario<S>(date: &DateTime<Utc>, serializer: S) -> Result<S::Ok, S::Error>\n\nwhere\n\n S: Serializer,\n\n{\n\n serializer.serialize_str(&date.to_rfc3339())\n\n}\n\n\n", "file_path": "nfe/src/base/ide/mod.rs", "rank": 15, "score": 84795.16264719467 }, { "content": "#[test]\n\nfn destinatario() -> Result<(), Error> {\n\n let xml = \"<enderDest>\n\n <xLgr>Av. Teste</xLgr>\n\n <nro>2040</nro>\n\n <xBairro>Centro</xBairro>\n\n <cMun>3550308</cMun>\n\n <xMun>SAO PAULO</xMun>\n\n <UF>SP</UF>\n\n <CEP>04207040</CEP>\n\n <cPais>1058</cPais>\n\n <xPais>BRASIL</xPais>\n\n <fone>5190909090</fone>\n\n </enderDest>\";\n\n\n\n let endereco = xml.parse::<Endereco>()?;\n\n assert_eq!(\"Av. Teste\", endereco.logradouro);\n\n assert_eq!(\"2040\", endereco.numero);\n\n assert_eq!(None, endereco.complemento);\n\n assert_eq!(\"Centro\", endereco.bairro);\n\n assert_eq!(3550308, endereco.codigo_municipio);\n\n assert_eq!(\"SAO PAULO\", endereco.nome_municipio);\n\n assert_eq!(\"SP\", endereco.sigla_uf);\n\n assert_eq!(\"04207040\", endereco.cep);\n\n assert_eq!(Some(\"5190909090\".to_string()), endereco.telefone);\n\n\n\n Ok(())\n\n}\n\n\n", "file_path": "nfe/src/tests/endereco.rs", "rank": 16, "score": 84117.88125128692 }, { "content": "#[test]\n\nfn manual() -> Result<(), Error> {\n\n let xml = \"\n\n <det nItem=\\\"1\\\">\n\n <prod>\n\n <cProd>11007</cProd>\n\n <cEAN>SEM GTIN</cEAN>\n\n <xProd>UM PRODUTO TESTE QUALQUER</xProd>\n\n <NCM>64011000</NCM>\n\n <CEST>1234567</CEST>\n\n <CFOP>6101</CFOP>\n\n <uCom>UN</uCom>\n\n <qCom>10.0000</qCom>\n\n <vUnCom>50</vUnCom>\n\n <vProd>500.00</vProd>\n\n <cEANTrib>SEM GTIN</cEANTrib>\n\n <uTrib>UN</uTrib>\n\n <qTrib>10.0000</qTrib>\n\n <vUnTrib>50.0000</vUnTrib>\n\n <indTot>1</indTot>\n\n </prod>\n", "file_path": "nfe/src/tests/itens.rs", "rank": 17, "score": 84117.88125128692 }, { "content": "#[test]\n\nfn manual() -> Result<(), Error> {\n\n let xml = \"\n\n <dest>\n\n <CNPJ>58716523000119</CNPJ>\n\n <xNome>NF-E EMITIDA EM AMBIENTE DE HOMOLOGACAO - SEM VALOR FISCAL</xNome>\n\n <enderDest>\n\n <xLgr>Av. Teste</xLgr>\n\n <nro>2040</nro>\n\n <xBairro>Centro</xBairro>\n\n <cMun>3550308</cMun>\n\n <xMun>SAO PAULO</xMun>\n\n <UF>SP</UF>\n\n <CEP>04207040</CEP>\n\n <cPais>1058</cPais>\n\n <xPais>BRASIL</xPais>\n\n <fone>5190909090</fone>\n\n </enderDest>\n\n <indIEDest>1</indIEDest>\n\n <IE>112006603110</IE>\n\n </dest>\n", "file_path": "nfe/src/tests/dest.rs", "rank": 18, "score": 84117.88125128692 }, { "content": "#[test]\n\nfn manual() -> Result<(), Error> {\n\n let xml = \"\n\n <emit>\n\n <CNPJ>06929383000163</CNPJ>\n\n <xNome>UMA RAZAO SOCIAL DE TESTE QUALQUER</xNome>\n\n <enderEmit>\n\n <xLgr>Rua dos Testes</xLgr>\n\n <nro>1020</nro>\n\n <xCpl>0</xCpl>\n\n <xBairro>Centro</xBairro>\n\n <cMun>4319901</cMun>\n\n <xMun>SAPIRANGA</xMun>\n\n <UF>RS</UF>\n\n <CEP>93800000</CEP>\n\n <cPais>1058</cPais>\n\n <xPais>BRASIL</xPais>\n\n <fone>5190909090</fone>\n\n </enderEmit>\n\n <IE>0018000762</IE>\n\n <CRT>1</CRT>\n", "file_path": "nfe/src/tests/emit.rs", "rank": 19, "score": 84117.88125128692 }, { "content": "#[test]\n\nfn manual() -> Result<(), Error> {\n\n let ide = XML_MANUAL.parse::<Identificacao>()?;\n\n\n\n assert_eq!(43, ide.codigo_uf);\n\n assert_eq!(4307609, ide.codigo_municipio);\n\n assert_eq!(1, ide.serie);\n\n assert_eq!(26, ide.numero);\n\n assert_eq!(ModeloDocumentoFiscal::Nfe, ide.modelo);\n\n assert_eq!(FormatoImpressaoDanfe::NormalRetrato, ide.formato_danfe);\n\n assert_eq!(TipoAmbiente::Homologacao, ide.ambiente);\n\n assert_eq!(\"00001030\", ide.chave.codigo);\n\n assert_eq!(1, ide.chave.digito_verificador);\n\n\n\n Ok(())\n\n}\n\n\n", "file_path": "nfe/src/tests/ide.rs", "rank": 20, "score": 84117.88125128692 }, { "content": "#[test]\n\nfn emitente() -> Result<(), Error> {\n\n let xml = \"<enderEmit>\n\n <xLgr>Rua dos Testes</xLgr>\n\n <nro>1020</nro>\n\n <xCpl>0</xCpl>\n\n <xBairro>Centro</xBairro>\n\n <cMun>4319901</cMun>\n\n <xMun>SAPIRANGA</xMun>\n\n <UF>RS</UF>\n\n <CEP>93800000</CEP>\n\n <cPais>1058</cPais>\n\n <xPais>BRASIL</xPais>\n\n <fone>5190909090</fone>\n\n </enderEmit>\";\n\n\n\n let endereco = xml.parse::<Endereco>()?;\n\n assert_eq!(\"Rua dos Testes\", endereco.logradouro);\n\n assert_eq!(\"1020\", endereco.numero);\n\n assert_eq!(Some(\"0\".to_string()), endereco.complemento);\n\n assert_eq!(\"Centro\", endereco.bairro);\n\n assert_eq!(4319901, endereco.codigo_municipio);\n\n assert_eq!(\"SAPIRANGA\", endereco.nome_municipio);\n\n assert_eq!(\"RS\", endereco.sigla_uf);\n\n assert_eq!(\"93800000\", endereco.cep);\n\n assert_eq!(Some(\"5190909090\".to_string()), endereco.telefone);\n\n\n\n Ok(())\n\n}\n\n\n", "file_path": "nfe/src/tests/endereco.rs", "rank": 21, "score": 84117.88125128692 }, { "content": "#[test]\n\nfn manual() -> Result<(), Error> {\n\n let xml = \"<transp><modFrete>9</modFrete></transp>\";\n\n\n\n let transporte = xml.parse::<Transporte>()?;\n\n\n\n assert_eq!(ModalidadeFrete::SemTransporte, transporte.modalidade);\n\n\n\n Ok(())\n\n}\n\n\n", "file_path": "nfe/src/tests/transporte.rs", "rank": 22, "score": 84117.88125128692 }, { "content": "#[test]\n\nfn from_instance() -> Result<(), String> {\n\n let f = File::open(\"xmls/nfe_layout4.xml\").map_err(|e| e.to_string())?;\n\n let itens = Nfe::try_from(f).map_err(|e| e.to_string())?.itens;\n\n\n\n assert_eq!(1, itens.len());\n\n\n\n let item = &itens[0];\n\n\n\n assert_eq!(1, item.numero);\n\n\n\n Ok(())\n\n}\n\n\n", "file_path": "nfe/src/tests/itens.rs", "rank": 23, "score": 83479.10389398248 }, { "content": "#[test]\n\nfn from_instance() -> Result<(), String> {\n\n let f = File::open(\"xmls/nfe_layout4.xml\").map_err(|e| e.to_string())?;\n\n let transporte = Nfe::try_from(f).map_err(|e| e.to_string())?.transporte;\n\n\n\n assert_eq!(ModalidadeFrete::SemTransporte, transporte.modalidade);\n\n\n\n Ok(())\n\n}\n\n\n", "file_path": "nfe/src/tests/transporte.rs", "rank": 24, "score": 83479.10389398248 }, { "content": "#[test]\n\nfn produtos() -> Result<(), String> {\n\n let f = File::open(\"xmls/nfce_layout4.xml\").map_err(|e| e.to_string())?;\n\n let itens = NfeBase::try_from(f).map_err(|e| e.to_string())?.itens;\n\n\n\n assert_eq!(2, itens.len());\n\n\n\n let produto = &itens[0].produto;\n\n\n\n assert_eq!(\"10015300336\", produto.codigo);\n\n assert_eq!(Some(\"7893049207584\".to_string()), produto.gtin);\n\n assert_eq!(\"(153 - C2075) -CILINDRO MESTRE DUPLO UN\", produto.descricao);\n\n assert_eq!(\"87083090\", produto.ncm);\n\n assert_eq!(None, produto.tributacao.cest);\n\n assert_eq!(None, produto.tributacao.escala_relevante);\n\n assert_eq!(None, produto.fabricante_cnpj);\n\n assert_eq!(None, produto.tributacao.codigo_beneficio_fiscal);\n\n assert_eq!(None, produto.tributacao.codigo_excecao_ipi);\n\n assert_eq!(\"5405\", produto.tributacao.cfop);\n\n assert_eq!(\"UN\", produto.unidade);\n\n assert_eq!(1.00, produto.quantidade);\n", "file_path": "nfe/src/tests/itens.rs", "rank": 25, "score": 83479.10389398248 }, { "content": "#[test]\n\nfn from_instance() -> Result<(), String> {\n\n let f = File::open(\"xmls/nfe_layout4.xml\").map_err(|e| e.to_string())?;\n\n let dest = Nfe::try_from(f).map_err(|e| e.to_string())?.dest;\n\n\n\n assert_eq!(\"58716523000119\", dest.cnpj);\n\n assert_eq!(\n\n \"NF-E EMITIDA EM AMBIENTE DE HOMOLOGACAO - SEM VALOR FISCAL\",\n\n dest.razao_social\n\n );\n\n assert_eq!(IndicadorContribuicaoIe::Contribuinte, dest.indicador_ie);\n\n assert_eq!(Some(\"112006603110\".to_string()), dest.ie);\n\n assert_eq!(\"Av. Teste\", dest.endereco.logradouro);\n\n assert_eq!(\"2040\", dest.endereco.numero);\n\n assert_eq!(None, dest.endereco.complemento);\n\n assert_eq!(\"Centro\", dest.endereco.bairro);\n\n assert_eq!(3550308, dest.endereco.codigo_municipio);\n\n assert_eq!(\"SAO PAULO\", dest.endereco.nome_municipio);\n\n assert_eq!(\"SP\", dest.endereco.sigla_uf);\n\n assert_eq!(\"04207040\", dest.endereco.cep);\n\n assert_eq!(Some(\"5190909090\".to_string()), dest.endereco.telefone);\n\n\n\n Ok(())\n\n}\n\n\n", "file_path": "nfe/src/tests/dest.rs", "rank": 26, "score": 83479.10389398248 }, { "content": "#[test]\n\nfn from_instance() -> Result<(), String> {\n\n let f = File::open(\"xmls/nfe_layout4.xml\").map_err(|e| e.to_string())?;\n\n let emit = Nfe::try_from(f).map_err(|e| e.to_string())?.emit;\n\n\n\n assert_eq!(\"06929383000163\", emit.cnpj);\n\n assert_eq!(\"UMA RAZAO SOCIAL DE TESTE QUALQUER\", emit.razao_social);\n\n assert_eq!(None, emit.nome_fantasia);\n\n assert_eq!(\"0018000762\", emit.ie);\n\n assert_eq!(None, emit.iest);\n\n assert_eq!(\"Rua dos Testes\", emit.endereco.logradouro);\n\n assert_eq!(\"1020\", emit.endereco.numero);\n\n assert_eq!(Some(\"0\".to_string()), emit.endereco.complemento);\n\n assert_eq!(\"Centro\", emit.endereco.bairro);\n\n assert_eq!(4319901, emit.endereco.codigo_municipio);\n\n assert_eq!(\"SAPIRANGA\", emit.endereco.nome_municipio);\n\n assert_eq!(\"RS\", emit.endereco.sigla_uf);\n\n assert_eq!(\"93800000\", emit.endereco.cep);\n\n assert_eq!(Some(\"5190909090\".to_string()), emit.endereco.telefone);\n\n\n\n Ok(())\n\n}\n\n\n", "file_path": "nfe/src/tests/emit.rs", "rank": 27, "score": 83479.10389398248 }, { "content": "#[test]\n\nfn nfe() -> Result<(), String> {\n\n let f = File::open(\"xmls/nfe_layout4.xml\").map_err(|e| e.to_string())?;\n\n let nfe = Nfe::try_from(f).map_err(|e| e.to_string())?;\n\n\n\n assert_eq!(\n\n \"43180906929383000163550010000000261000010301\",\n\n nfe.chave_acesso\n\n );\n\n assert_eq!(VersaoLayout::V4_00, nfe.versao);\n\n assert_eq!(None, nfe.informacao_complementar);\n\n\n\n Ok(())\n\n}\n\n\n", "file_path": "nfe/src/tests/infnfe.rs", "rank": 28, "score": 83479.10389398248 }, { "content": "#[test]\n\nfn impostos() -> Result<(), String> {\n\n let f = File::open(\"xmls/nfce_layout4.xml\").map_err(|e| e.to_string())?;\n\n let itens = NfeBase::try_from(f).map_err(|e| e.to_string())?.itens;\n\n\n\n assert_eq!(2, itens.len());\n\n\n\n let imposto = &itens[0].imposto;\n\n\n\n assert_eq!(Some(17.32), imposto.valor_aproximado);\n\n assert_eq!(\n\n Some(GrupoIcms::Icms60(GrupoIcms60 {\n\n origem: OrigemMercadoria::Nacional,\n\n aliquota: 0.0,\n\n valor: 0.0,\n\n valor_base_calculo: 0.0,\n\n })),\n\n imposto.icms\n\n );\n\n assert_eq!(\n\n Some(GrupoPis::PisNt(GrupoPisNt {\n", "file_path": "nfe/src/tests/itens.rs", "rank": 29, "score": 83479.10389398248 }, { "content": "#[test]\n\nfn from_instance() -> Result<(), String> {\n\n let f = File::open(\"xmls/nfe_layout4.xml\").map_err(|e| e.to_string())?;\n\n let ide = Nfe::try_from(f).map_err(|e| e.to_string())?.ide;\n\n\n\n assert_eq!(43, ide.codigo_uf);\n\n assert_eq!(4307609, ide.codigo_municipio);\n\n assert_eq!(1, ide.serie);\n\n assert_eq!(26, ide.numero);\n\n assert_eq!(ModeloDocumentoFiscal::Nfe, ide.modelo);\n\n assert_eq!(FormatoImpressaoDanfe::NormalRetrato, ide.formato_danfe);\n\n assert_eq!(TipoAmbiente::Homologacao, ide.ambiente);\n\n assert_eq!(\"00001030\", ide.chave.codigo);\n\n assert_eq!(1, ide.chave.digito_verificador);\n\n\n\n Ok(())\n\n}\n\n\n", "file_path": "nfe/src/tests/ide.rs", "rank": 30, "score": 83479.10389398248 }, { "content": "#[test]\n\nfn imposto_manual() -> Result<(), Error> {\n\n let xml = \"\n\n <imposto>\n\n <vTotTrib>0.00</vTotTrib>\n\n <ICMS>\n\n <ICMSSN202>\n\n <orig>0</orig>\n\n <CSOSN>202</CSOSN>\n\n <modBCST>4</modBCST>\n\n <vBCST>0.00</vBCST>\n\n <pICMSST>0.0000</pICMSST>\n\n <vICMSST>0.00</vICMSST>\n\n </ICMSSN202>\n\n </ICMS>\n\n <PIS>\n\n <PISOutr>\n\n <CST>49</CST>\n\n <vBC>0.00</vBC>\n\n <pPIS>0.0000</pPIS>\n\n <vPIS>0.00</vPIS>\n", "file_path": "nfe/src/tests/itens.rs", "rank": 31, "score": 82438.62586106369 }, { "content": "#[test]\n\nfn produto_manual() -> Result<(), Error> {\n\n let xml = \"\n\n <prod>\n\n <cProd>11007</cProd>\n\n <cEAN>SEM GTIN</cEAN>\n\n <xProd>UM PRODUTO TESTE QUALQUER</xProd>\n\n <NCM>64011000</NCM>\n\n <CEST>1234567</CEST>\n\n <CFOP>6101</CFOP>\n\n <uCom>UN</uCom>\n\n <qCom>10.0000</qCom>\n\n <vUnCom>50</vUnCom>\n\n <vProd>500.00</vProd>\n\n <cEANTrib>SEM GTIN</cEANTrib>\n\n <uTrib>UN</uTrib>\n\n <qTrib>10.0000</qTrib>\n\n <vUnTrib>50.0000</vUnTrib>\n\n <indTot>1</indTot>\n\n </prod>\n\n \";\n", "file_path": "nfe/src/tests/itens.rs", "rank": 32, "score": 82438.62586106369 }, { "content": "#[test]\n\nfn operacao_from_instance() -> Result<(), String> {\n\n let f = File::open(\"xmls/nfe_layout4.xml\").map_err(|e| e.to_string())?;\n\n let operacao = Nfe::try_from(f).map_err(|e| e.to_string())?.ide.operacao;\n\n\n\n assert_eq!(\"Venda de producao do estabelecimento\", operacao.natureza);\n\n assert_eq!(\n\n Some(Utc.ymd(2018, 09, 25).and_hms(18, 14, 0)),\n\n operacao.horario\n\n );\n\n assert_eq!(TipoOperacao::Saida, operacao.tipo);\n\n assert_eq!(DestinoOperacao::Interestadual, operacao.destino);\n\n assert_eq!(TipoConsumidor::Normal, operacao.consumidor);\n\n assert_eq!(TipoPresencaComprador::Presencial, operacao.presenca);\n\n assert_eq!(None, operacao.intermediador);\n\n\n\n Ok(())\n\n}\n\n\n", "file_path": "nfe/src/tests/ide.rs", "rank": 33, "score": 81810.55904892659 }, { "content": "#[test]\n\nfn nfe_from_read() -> Result<(), String> {\n\n let f = File::open(\"xmls/nfe_layout4.xml\").map_err(|e| e.to_string())?;\n\n\n\n Nfe::try_from(f).map_err(|e| e.to_string())?;\n\n\n\n Ok(())\n\n}\n\n\n", "file_path": "nfe/src/tests/parse.rs", "rank": 34, "score": 81810.55904892659 }, { "content": "#[test]\n\nfn nfce_from_read() -> Result<(), String> {\n\n let f = File::open(\"xmls/nfce_layout4.xml\").map_err(|e| e.to_string())?;\n\n\n\n NfeBase::try_from(f).map_err(|e| e.to_string())?;\n\n\n\n Ok(())\n\n}\n", "file_path": "nfe/src/tests/parse.rs", "rank": 35, "score": 81810.55904892659 }, { "content": "#[test]\n\nfn emissao_from_instance() -> Result<(), String> {\n\n let f = File::open(\"xmls/nfe_layout4.xml\").map_err(|e| e.to_string())?;\n\n let emissao = Nfe::try_from(f).map_err(|e| e.to_string())?.ide.emissao;\n\n\n\n assert_eq!(Utc.ymd(2018, 09, 25).and_hms(3, 0, 0), emissao.horario);\n\n assert_eq!(TipoEmissao::Normal, emissao.tipo);\n\n assert_eq!(FinalidadeEmissao::Normal, emissao.finalidade);\n\n assert_eq!(\n\n TipoProcessoEmissao::ViaAplicativoDoContribuinte,\n\n emissao.processo\n\n );\n\n assert_eq!(\"fernando\", emissao.versao_processo);\n\n\n\n Ok(())\n\n}\n\n\n", "file_path": "nfe/src/tests/ide.rs", "rank": 36, "score": 81810.55904892659 }, { "content": "#[test]\n\nfn imposto_from_instance() -> Result<(), String> {\n\n let f = File::open(\"xmls/nfe_layout4.xml\").map_err(|e| e.to_string())?;\n\n let itens = Nfe::try_from(f).map_err(|e| e.to_string())?.itens;\n\n\n\n assert_eq!(1, itens.len());\n\n\n\n let imposto = &itens[0].imposto;\n\n\n\n assert_eq!(Some(0.0), imposto.valor_aproximado);\n\n assert_eq!(\n\n Some(GrupoIcms::IcmsSn202(GrupoIcmsSn202 {\n\n origem: OrigemMercadoria::Nacional,\n\n aliquota: 0.0,\n\n valor: 0.0,\n\n valor_base_calculo: 0.0,\n\n base_calculo: ModalidadeBaseCalculoIcmsSt::MargemValorAgregado,\n\n codigo_situacao: \"202\".to_string()\n\n })),\n\n imposto.icms\n\n );\n", "file_path": "nfe/src/tests/itens.rs", "rank": 37, "score": 81810.55904892659 }, { "content": "#[test]\n\nfn produto_from_instance() -> Result<(), String> {\n\n let f = File::open(\"xmls/nfe_layout4.xml\").map_err(|e| e.to_string())?;\n\n let itens = Nfe::try_from(f).map_err(|e| e.to_string())?.itens;\n\n\n\n assert_eq!(1, itens.len());\n\n\n\n let produto = &itens[0].produto;\n\n\n\n assert_eq!(\"11007\", produto.codigo);\n\n assert_eq!(None, produto.gtin);\n\n assert_eq!(\"UM PRODUTO TESTE QUALQUER\", produto.descricao);\n\n assert_eq!(\"64011000\", produto.ncm);\n\n assert_eq!(Some(\"1234567\".to_string()), produto.tributacao.cest);\n\n assert_eq!(None, produto.tributacao.escala_relevante);\n\n assert_eq!(None, produto.fabricante_cnpj);\n\n assert_eq!(None, produto.tributacao.codigo_beneficio_fiscal);\n\n assert_eq!(None, produto.tributacao.codigo_excecao_ipi);\n\n assert_eq!(\"6101\", produto.tributacao.cfop);\n\n assert_eq!(\"UN\", produto.unidade);\n\n assert_eq!(10.00, produto.quantidade);\n", "file_path": "nfe/src/tests/itens.rs", "rank": 38, "score": 81810.55904892659 }, { "content": "fn serialize_horario_op<S>(date: &Option<DateTime<Utc>>, serializer: S) -> Result<S::Ok, S::Error>\n\nwhere\n\n S: Serializer,\n\n{\n\n serialize_horario(&date.unwrap(), serializer)\n\n}\n", "file_path": "nfe/src/base/ide/mod.rs", "rank": 39, "score": 81344.78002877577 }, { "content": "#[test]\n\nfn informacao_complementar_from_instance() -> Result<(), String> {\n\n let f = File::open(\"xmls/nfce_layout4.xml\").map_err(|e| e.to_string())?;\n\n let nfe = NfeBase::try_from(f).map_err(|e| e.to_string())?;\n\n\n\n assert_eq!(\n\n Some(\"11899318;422-JERK DIONNY;CLIENTE RECUSOU INFORMAR CPF/CNPJ NO CUPOM\".to_string()),\n\n nfe.informacao_complementar\n\n );\n\n\n\n Ok(())\n\n}\n\n\n", "file_path": "nfe/src/tests/infnfe.rs", "rank": 40, "score": 80243.17018964302 }, { "content": "#[test]\n\nfn produtos_com_pis_cofins() -> Result<(), String> {\n\n let f = File::open(\"xmls/nfce_layout4.xml\").map_err(|e| e.to_string())?;\n\n let totais = NfeBase::try_from(f).map_err(|e| e.to_string())?.totais;\n\n\n\n assert_eq!(0.0, totais.valor_base_calculo);\n\n assert_eq!(0.0, totais.valor_icms);\n\n assert_eq!(150.0, totais.valor_produtos);\n\n assert_eq!(0.0, totais.valor_frete);\n\n assert_eq!(0.0, totais.valor_seguro);\n\n assert_eq!(0.0, totais.valor_desconto);\n\n assert_eq!(0.89, totais.valor_pis);\n\n assert_eq!(0.0, totais.valor_outros);\n\n assert_eq!(4.09, totais.valor_cofins);\n\n assert_eq!(150.0, totais.valor_total);\n\n assert_eq!(35.75, totais.valor_aproximado_tributos);\n\n\n\n Ok(())\n\n}\n\n\n", "file_path": "nfe/src/tests/totais.rs", "rank": 41, "score": 78768.00904187022 }, { "content": "#[test]\n\nfn apenas_valores_dos_produtos() -> Result<(), String> {\n\n let f = File::open(\"xmls/nfe_layout4.xml\").map_err(|e| e.to_string())?;\n\n let totais = Nfe::try_from(f).map_err(|e| e.to_string())?.totais;\n\n\n\n assert_eq!(0.0, totais.valor_base_calculo);\n\n assert_eq!(0.0, totais.valor_icms);\n\n assert_eq!(500.0, totais.valor_produtos);\n\n assert_eq!(0.0, totais.valor_frete);\n\n assert_eq!(0.0, totais.valor_seguro);\n\n assert_eq!(0.0, totais.valor_desconto);\n\n assert_eq!(0.0, totais.valor_pis);\n\n assert_eq!(0.0, totais.valor_outros);\n\n assert_eq!(0.0, totais.valor_cofins);\n\n assert_eq!(500.0, totais.valor_total);\n\n assert_eq!(0.0, totais.valor_aproximado_tributos);\n\n\n\n Ok(())\n\n}\n\n\n", "file_path": "nfe/src/tests/totais.rs", "rank": 42, "score": 78768.00904187022 }, { "content": "#[test]\n\nfn manual_produtos_com_pis_cofins() -> Result<(), Error> {\n\n let xml = \"<total>\n\n <ICMSTot>\n\n <vBC>0.00</vBC>\n\n <vICMS>0.00</vICMS>\n\n <vICMSDeson>0.00</vICMSDeson>\n\n <vFCP>0.00</vFCP>\n\n <vBCST>0.00</vBCST>\n\n <vST>0.00</vST>\n\n <vFCPST>0.00</vFCPST>\n\n <vFCPSTRet>0.00</vFCPSTRet>\n\n <vProd>150.00</vProd>\n\n <vFrete>0.00</vFrete>\n\n <vSeg>0.00</vSeg>\n\n <vDesc>0.00</vDesc>\n\n <vII>0.00</vII>\n\n <vIPI>0.00</vIPI>\n\n <vIPIDevol>0.00</vIPIDevol>\n\n <vPIS>0.89</vPIS>\n\n <vCOFINS>4.09</vCOFINS>\n", "file_path": "nfe/src/tests/totais.rs", "rank": 43, "score": 77976.77647158915 }, { "content": "#[derive(Deserialize, Serialize)]\n\nstruct InfAddContainer {\n\n #[serde(rename = \"$unflatten=infCpl\")]\n\n pub informacao_complementar: Option<String>,\n\n}\n\n\n", "file_path": "nfe/src/base/mod.rs", "rank": 46, "score": 51042.684412235074 }, { "content": "#[derive(Deserialize, Serialize)]\n\nstruct NfeInfContainer {\n\n #[serde(rename = \"versao\")]\n\n pub versao: VersaoLayout,\n\n #[serde(rename = \"Id\")]\n\n pub chave_acesso: String,\n\n #[serde(rename = \"ide\")]\n\n pub ide: Identificacao,\n\n #[serde(rename = \"emit\")]\n\n pub emit: Emitente,\n\n #[serde(rename = \"dest\")]\n\n pub dest: Option<Destinatario>,\n\n #[serde(rename = \"det\")]\n\n pub itens: Vec<Item>,\n\n #[serde(rename = \"total\")]\n\n pub totais: Totalizacao,\n\n #[serde(rename = \"transp\")]\n\n pub transporte: Transporte,\n\n #[serde(rename = \"infAdic\")]\n\n pub add: Option<InfAddContainer>,\n\n}\n", "file_path": "nfe/src/base/mod.rs", "rank": 47, "score": 51042.684412235074 }, { "content": "#[derive(Deserialize, Serialize)]\n\n#[serde(rename = \"ide\")]\n\nstruct IdeContainer {\n\n #[serde(rename = \"$unflatten=cUF\")]\n\n pub codigo_uf: u8,\n\n #[serde(rename = \"$unflatten=nNF\")]\n\n pub numero: u32,\n\n #[serde(rename = \"$unflatten=serie\")]\n\n pub serie: u16,\n\n #[serde(rename = \"$unflatten=mod\")]\n\n pub modelo: ModeloDocumentoFiscal,\n\n #[serde(rename = \"$unflatten=cMunFG\")]\n\n pub codigo_municipio: u32,\n\n #[serde(rename = \"$unflatten=tpImp\")]\n\n pub formato_danfe: FormatoImpressaoDanfe,\n\n #[serde(rename = \"$unflatten=tpAmb\")]\n\n pub ambiente: TipoAmbiente,\n\n\n\n #[serde(rename = \"$unflatten=cNF\")]\n\n pub c_codigo: String,\n\n #[serde(rename = \"$unflatten=cDV\")]\n\n pub c_digito_verificador: u8,\n", "file_path": "nfe/src/base/ide/mod.rs", "rank": 48, "score": 51042.30198660343 }, { "content": "#[derive(Deserialize, Serialize)]\n\n#[serde(rename = \"prod\")]\n\nstruct ProdContainer {\n\n #[serde(rename = \"$unflatten=cProd\")]\n\n pub codigo: String,\n\n #[serde(rename = \"$unflatten=cEAN\")]\n\n pub gtin: String,\n\n #[serde(rename = \"$unflatten=xProd\")]\n\n pub descricao: String,\n\n #[serde(rename = \"$unflatten=NCM\")]\n\n pub ncm: String,\n\n #[serde(rename = \"$unflatten=CNPJFab\")]\n\n #[serde(skip_serializing_if = \"Option::is_none\")]\n\n pub fabricante_cnpj: Option<String>,\n\n #[serde(rename = \"$unflatten=uCom\")]\n\n pub unidade: String,\n\n #[serde(rename = \"$unflatten=qCom\")]\n\n pub quantidade: f32,\n\n #[serde(rename = \"$unflatten=vUnCom\")]\n\n pub valor_unitario: f32,\n\n #[serde(rename = \"$unflatten=vProd\")]\n\n pub valor_bruto: f32,\n", "file_path": "nfe/src/base/item/produto.rs", "rank": 49, "score": 51042.30198660343 }, { "content": "#[derive(Deserialize, Serialize)]\n\n#[serde(rename = \"NFe\")]\n\nstruct NfeRootContainer {\n\n #[serde(rename = \"infNFe\")]\n\n pub inf: NfeInfContainer,\n\n}\n\n\n", "file_path": "nfe/src/base/mod.rs", "rank": 50, "score": 51042.18387566726 }, { "content": "#[derive(Deserialize, Serialize)]\n\nstruct GrupoIcmsContainer {\n\n #[serde(rename = \"ICMSSN202\")]\n\n #[serde(skip_serializing_if = \"Option::is_none\")]\n\n icms_sn_202: Option<GrupoIcmsSn202>,\n\n #[serde(rename = \"ICMS60\")]\n\n #[serde(skip_serializing_if = \"Option::is_none\")]\n\n icms_60: Option<GrupoIcms60>,\n\n}\n\n\n\n/// Grupo ICMS 60 - Tributação ICMS cobrado anteriormente por substituição tributária\n\n#[derive(Debug, PartialEq, Deserialize, Serialize, Clone)]\n\npub struct GrupoIcms60 {\n\n /// Origem da mercadoria\n\n #[serde(rename = \"$unflatten=orig\")]\n\n pub origem: OrigemMercadoria,\n\n /// Valor da base de cálculo do ICMS ST retido\n\n #[serde(rename = \"$unflatten=vBCSTRet\")]\n\n pub valor_base_calculo: f32,\n\n /// Alíquota suportada pelo Consumidor Final\n\n #[serde(rename = \"$unflatten=pST\")]\n", "file_path": "nfe/src/base/item/imposto/icms.rs", "rank": 51, "score": 49361.09327285613 }, { "content": "#[derive(Deserialize, Serialize)]\n\nstruct GrupoPisContainer {\n\n #[serde(rename = \"PISOutr\")]\n\n #[serde(skip_serializing_if = \"Option::is_none\")]\n\n pis_outr: Option<GrupoPisOutr>,\n\n #[serde(rename = \"PISNT\")]\n\n #[serde(skip_serializing_if = \"Option::is_none\")]\n\n pis_nt: Option<GrupoPisNt>,\n\n #[serde(rename = \"PISAliq\")]\n\n #[serde(skip_serializing_if = \"Option::is_none\")]\n\n pis_aliq: Option<GrupoPisAliq>,\n\n}\n\n\n\n/// Grupo PIS Outr - Outras Operações\n\n#[derive(Debug, PartialEq, Deserialize, Serialize, Clone)]\n\npub struct GrupoPisOutr {\n\n /// CST - Código de Situação Tributária do PIS\n\n #[serde(rename = \"$unflatten=CST\")]\n\n pub codigo_situacao: String,\n\n /// Valor da base de cálculo do PIS\n\n #[serde(rename = \"$unflatten=vBC\")]\n", "file_path": "nfe/src/base/item/imposto/pis.rs", "rank": 52, "score": 49361.09327285613 }, { "content": "#[derive(Deserialize, Serialize)]\n\nstruct GrupoCofinsContainer {\n\n #[serde(rename = \"COFINSOutr\")]\n\n #[serde(skip_serializing_if = \"Option::is_none\")]\n\n cofins_outr: Option<GrupoCofinsOutr>,\n\n #[serde(rename = \"COFINSNT\")]\n\n #[serde(skip_serializing_if = \"Option::is_none\")]\n\n cofins_nt: Option<GrupoCofinsNt>,\n\n #[serde(rename = \"COFINSAliq\")]\n\n #[serde(skip_serializing_if = \"Option::is_none\")]\n\n cofins_aliq: Option<GrupoCofinsAliq>,\n\n}\n\n\n\n/// Grupo COFINS Outr - Outras Operações\n\n#[derive(Debug, PartialEq, Deserialize, Serialize, Clone)]\n\npub struct GrupoCofinsOutr {\n\n /// CST - Código de Situação Tributária do COFINS\n\n #[serde(rename = \"$unflatten=CST\")]\n\n pub codigo_situacao: String,\n\n /// Valor da base de cálculo do COFINS\n\n #[serde(rename = \"$unflatten=vBC\")]\n", "file_path": "nfe/src/base/item/imposto/cofins.rs", "rank": 53, "score": 49361.09327285613 }, { "content": "//! Erros de parse, io...\n\n\n\nuse derive_more::{Display, Error, From};\n\n\n\n#[derive(Debug, Display, Error, From)]\n\npub enum Error {\n\n #[display(fmt = \"Falha na leitura do arquivo: {}\", _0)]\n\n Io(std::io::Error),\n\n #[display(fmt = \"Falha no parse: {}\", _0)]\n\n Serde(quick_xml::de::DeError),\n\n}\n", "file_path": "nfe/src/base/error.rs", "rank": 54, "score": 30208.944716433747 }, { "content": "//! Erros referentes ao modelo 55\n\n\n\nuse derive_more::{Display, Error, From};\n\n\n\n#[derive(Debug, Display, Error, From)]\n\npub enum Error {\n\n #[display(fmt = \"Modelo do documento não suportado: {:?}\", _0)]\n\n ModeloInvalido(#[error(not(source))] crate::ModeloDocumentoFiscal),\n\n #[display(fmt = \"Destinatário inválido. {}\", _0)]\n\n DestinatarioInvalido(#[error(not(source))] String),\n\n Base(crate::base::Error),\n\n}\n", "file_path": "nfe/src/modelos/nfe/error.rs", "rank": 55, "score": 29170.896327002687 }, { "content": " pub codigo: String,\n\n pub digito_verificador: u8,\n\n}\n\n\n\nimpl FromStr for Identificacao {\n\n type Err = Error;\n\n\n\n fn from_str(s: &str) -> Result<Self, Self::Err> {\n\n quick_xml::de::from_str(s).map_err(|e| e.into())\n\n }\n\n}\n\n\n\nimpl ToString for Identificacao {\n\n fn to_string(&self) -> String {\n\n quick_xml::se::to_string(self).expect(\"Falha ao serializar a identificação\")\n\n }\n\n}\n\n\n\nimpl<'de> Deserialize<'de> for Identificacao {\n\n fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>\n", "file_path": "nfe/src/base/ide/mod.rs", "rank": 56, "score": 25.345232117805104 }, { "content": "//! Informações sobre o transporte da nota\n\n\n\nuse super::Error;\n\nuse serde::{Deserialize, Serialize};\n\nuse serde_repr::{Deserialize_repr, Serialize_repr};\n\nuse std::str::FromStr;\n\n\n\n/// Transporte da nota\n\n#[derive(Debug, Deserialize, PartialEq, Serialize, Clone)]\n\n#[serde(rename = \"transp\")]\n\npub struct Transporte {\n\n /// Modalidade do frete\n\n #[serde(rename = \"$unflatten=modFrete\")]\n\n pub modalidade: ModalidadeFrete,\n\n}\n\n\n\nimpl FromStr for Transporte {\n\n type Err = Error;\n\n\n\n fn from_str(s: &str) -> Result<Self, Self::Err> {\n", "file_path": "nfe/src/base/transporte.rs", "rank": 58, "score": 23.32055563798089 }, { "content": " #[serde(rename = \"$unflatten=IEST\")]\n\n #[serde(skip_serializing_if = \"Option::is_none\")]\n\n pub iest: Option<u32>,\n\n #[serde(rename = \"enderEmit\")]\n\n pub endereco: Endereco,\n\n}\n\n\n\nimpl FromStr for Emitente {\n\n type Err = Error;\n\n\n\n fn from_str(s: &str) -> Result<Self, Self::Err> {\n\n quick_xml::de::from_str(s).map_err(|e| e.into())\n\n }\n\n}\n\n\n\nimpl ToString for Emitente {\n\n fn to_string(&self) -> String {\n\n quick_xml::se::to_string(self).expect(\"Falha ao serializar o emitente\")\n\n }\n\n}\n", "file_path": "nfe/src/base/emit.rs", "rank": 59, "score": 22.5314052254485 }, { "content": " #[serde(rename = \"imposto\")]\n\n pub imposto: Imposto,\n\n}\n\n\n\nimpl FromStr for Item {\n\n type Err = Error;\n\n\n\n fn from_str(s: &str) -> Result<Self, Self::Err> {\n\n quick_xml::de::from_str(s).map_err(|e| e.into())\n\n }\n\n}\n\n\n\nimpl ToString for Item {\n\n fn to_string(&self) -> String {\n\n quick_xml::se::to_string(self).expect(\"Falha ao serializar o item\")\n\n }\n\n}\n", "file_path": "nfe/src/base/item/mod.rs", "rank": 60, "score": 22.285952945647463 }, { "content": " pub quantidade: f32,\n\n /// Valor unitário de tributação\n\n pub valor_unitario: f32,\n\n}\n\n\n\n/// Indicador de Produção em escala relevante\n\n#[derive(Debug, Eq, PartialEq, Copy, Clone, Deserialize_repr, Serialize_repr)]\n\n#[repr(u8)]\n\npub enum EscalaRelevante {\n\n Sim = 1,\n\n Nao = 2,\n\n}\n\n\n\nimpl FromStr for Produto {\n\n type Err = Error;\n\n\n\n fn from_str(s: &str) -> Result<Self, Self::Err> {\n\n quick_xml::de::from_str(s).map_err(|e| e.into())\n\n }\n\n}\n", "file_path": "nfe/src/base/item/produto.rs", "rank": 61, "score": 21.184481610837008 }, { "content": " pub valor_aproximado: Option<f32>,\n\n /// Informações do ICMS da Operação própria e ST\n\n #[serde(rename = \"ICMS\")]\n\n pub icms: Option<GrupoIcms>,\n\n /// Informações do PIS\n\n #[serde(rename = \"PIS\")]\n\n pub pis: Option<GrupoPis>,\n\n /// Informações do COFINS\n\n #[serde(rename = \"COFINS\")]\n\n pub cofins: Option<GrupoCofins>,\n\n}\n\n\n\nimpl FromStr for Imposto {\n\n type Err = Error;\n\n\n\n fn from_str(s: &str) -> Result<Self, Self::Err> {\n\n quick_xml::de::from_str(s).map_err(|e| e.into())\n\n }\n\n}\n\n\n\nimpl ToString for Imposto {\n\n fn to_string(&self) -> String {\n\n quick_xml::se::to_string(self).expect(\"Falha ao serializar o imposto\")\n\n }\n\n}\n", "file_path": "nfe/src/base/item/imposto/mod.rs", "rank": 62, "score": 20.739463318130234 }, { "content": " #[serde(rename = \"$unflatten=xMun\")]\n\n pub nome_municipio: String,\n\n #[serde(rename = \"$unflatten=UF\")]\n\n pub sigla_uf: String,\n\n #[serde(rename = \"$unflatten=CEP\")]\n\n pub cep: String,\n\n #[serde(rename = \"$unflatten=cPais\")]\n\n pub codigo_pais: u32,\n\n #[serde(rename = \"$unflatten=xPais\")]\n\n pub nome_pais: String,\n\n #[serde(rename = \"$unflatten=fone\")]\n\n #[serde(skip_serializing_if = \"Option::is_none\")]\n\n pub telefone: Option<String>,\n\n}\n\n\n\nimpl FromStr for Endereco {\n\n type Err = Error;\n\n\n\n fn from_str(s: &str) -> Result<Self, Self::Err> {\n\n quick_xml::de::from_str(s).map_err(|e| e.into())\n\n }\n\n}\n\n\n\nimpl ToString for Endereco {\n\n fn to_string(&self) -> String {\n\n quick_xml::se::to_string(self).expect(\"Falha ao serializar o endereço\")\n\n }\n\n}\n", "file_path": "nfe/src/base/endereco.rs", "rank": 63, "score": 20.384070115720803 }, { "content": "//! Produtos\n\n\n\nuse super::Error;\n\nuse serde::{Deserialize, Deserializer, Serialize, Serializer};\n\nuse serde_repr::{Deserialize_repr, Serialize_repr};\n\nuse std::str::FromStr;\n\n\n\n/// Detalhamento do produto do item\n\n#[derive(Debug, PartialEq, Clone)]\n\npub struct Produto {\n\n /// Código do produto\n\n pub codigo: String,\n\n /// GTIN (Global Trade Item Number) do produto, antigo código EAN ou código de barras\n\n pub gtin: Option<String>,\n\n /// Descrição do produto\n\n pub descricao: String,\n\n /// NCM - Nomenclatura Comum do Mercosul\n\n pub ncm: String,\n\n /// CNPJ do Fabricante da Mercadoria\n\n pub fabricante_cnpj: Option<String>,\n", "file_path": "nfe/src/base/item/produto.rs", "rank": 64, "score": 20.293076301033864 }, { "content": "//! Emitente da NF-e\n\n\n\nuse super::endereco::*;\n\nuse super::Error;\n\nuse serde::{Deserialize, Serialize};\n\nuse std::str::FromStr;\n\n\n\n/// Emitente da NF-e\n\n#[derive(Debug, Deserialize, PartialEq, Serialize, Clone)]\n\n#[serde(rename = \"emit\")]\n\npub struct Emitente {\n\n #[serde(rename = \"$unflatten=CNPJ\")]\n\n pub cnpj: String,\n\n #[serde(rename = \"$unflatten=xNome\")]\n\n pub razao_social: String,\n\n #[serde(rename = \"$unflatten=xFant\")]\n\n #[serde(skip_serializing_if = \"Option::is_none\")]\n\n pub nome_fantasia: Option<String>,\n\n #[serde(rename = \"$unflatten=IE\")]\n\n pub ie: String,\n", "file_path": "nfe/src/base/emit.rs", "rank": 65, "score": 20.043385599235666 }, { "content": "//! Destinatário da NF-e\n\n\n\nuse super::endereco::*;\n\nuse super::Error;\n\nuse serde::{Deserialize, Serialize};\n\nuse serde_repr::{Deserialize_repr, Serialize_repr};\n\nuse std::str::FromStr;\n\n\n\n/// Destinatário base da NF-e\n\n#[derive(Debug, Deserialize, PartialEq, Serialize, Clone)]\n\n#[serde(rename = \"dest\")]\n\npub struct Destinatario {\n\n #[serde(rename = \"$unflatten=CNPJ\")]\n\n pub cnpj: String,\n\n #[serde(rename = \"$unflatten=xNome\")]\n\n #[serde(skip_serializing_if = \"Option::is_none\")]\n\n pub razao_social: Option<String>,\n\n #[serde(skip_serializing_if = \"Option::is_none\")]\n\n #[serde(rename = \"enderDest\")]\n\n pub endereco: Option<Endereco>,\n", "file_path": "nfe/src/base/dest.rs", "rank": 66, "score": 19.62941413943573 }, { "content": " /// Informações complementares de interesse do contribuinte\n\n pub informacao_complementar: Option<String>,\n\n}\n\n\n\n/// Versão do layout da NF-e\n\n#[derive(Debug, Eq, PartialEq, Copy, Clone, Deserialize)]\n\npub enum VersaoLayout {\n\n #[serde(rename = \"4.00\")]\n\n V4_00 = 4,\n\n}\n\n\n\nimpl FromStr for Nfe {\n\n type Err = Error;\n\n\n\n fn from_str(s: &str) -> Result<Self, Self::Err> {\n\n quick_xml::de::from_str(s).map_err(|e| e.into())\n\n }\n\n}\n\n\n\nimpl TryFrom<File> for Nfe {\n", "file_path": "nfe/src/base/mod.rs", "rank": 67, "score": 19.3186373621385 }, { "content": "//! Identificação da NF-e\n\n\n\nuse super::Error;\n\nuse chrono::prelude::*;\n\nuse serde::{Deserialize, Deserializer, Serialize, Serializer};\n\nuse serde_repr::{Deserialize_repr, Serialize_repr};\n\nuse std::str::FromStr;\n\n\n\nmod emissao;\n\nmod operacao;\n\n\n\npub use emissao::*;\n\npub use operacao::*;\n\n\n\n/// Identificação da NF-e\n\n#[derive(Debug, PartialEq, Clone)]\n\npub struct Identificacao {\n\n pub codigo_uf: u8,\n\n pub chave: ComposicaoChaveAcesso,\n\n pub numero: u32,\n", "file_path": "nfe/src/base/ide/mod.rs", "rank": 68, "score": 19.174542787466372 }, { "content": "//! Endereço do emitente/destinatário da NF-e\n\n\n\nuse super::Error;\n\nuse serde::{Deserialize, Serialize};\n\nuse std::str::FromStr;\n\n\n\n/// Representação de um endereço usado na NFe\n\n#[derive(Debug, Deserialize, PartialEq, Clone, Serialize)]\n\npub struct Endereco {\n\n #[serde(rename = \"$unflatten=xLgr\")]\n\n pub logradouro: String,\n\n #[serde(rename = \"$unflatten=nro\")]\n\n pub numero: String,\n\n #[serde(rename = \"$unflatten=xCpl\")]\n\n #[serde(skip_serializing_if = \"Option::is_none\")]\n\n pub complemento: Option<String>,\n\n #[serde(rename = \"$unflatten=xBairro\")]\n\n pub bairro: String,\n\n #[serde(rename = \"$unflatten=cMun\")]\n\n pub codigo_municipio: u32,\n", "file_path": "nfe/src/base/endereco.rs", "rank": 69, "score": 19.13046013306765 }, { "content": " type Error = Error;\n\n\n\n fn try_from(mut f: File) -> Result<Self, Self::Error> {\n\n let mut xml = String::new();\n\n f.read_to_string(&mut xml).map_err(|e| Error::Io(e))?;\n\n\n\n xml.parse::<Nfe>()\n\n }\n\n}\n\n\n\nimpl ToString for Nfe {\n\n fn to_string(&self) -> String {\n\n quick_xml::se::to_string(self).expect(\"Falha ao serializar a nota\")\n\n }\n\n}\n\n\n\nimpl<'de> Deserialize<'de> for Nfe {\n\n fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>\n\n where\n\n D: Deserializer<'de>,\n", "file_path": "nfe/src/base/mod.rs", "rank": 70, "score": 18.68528042356047 }, { "content": "//! Detalhamento de produtos e serviços\n\n\n\nuse super::Error;\n\nuse serde::{Deserialize, Serialize};\n\nuse std::str::FromStr;\n\n\n\nmod imposto;\n\nmod produto;\n\n\n\npub use imposto::*;\n\npub use produto::*;\n\n\n\n/// Item da nota\n\n#[derive(Debug, PartialEq, Deserialize, Serialize, Clone)]\n\n#[serde(rename = \"det\")]\n\npub struct Item {\n\n #[serde(rename = \"nItem\")]\n\n pub numero: u8,\n\n #[serde(rename = \"prod\")]\n\n pub produto: Produto,\n", "file_path": "nfe/src/base/item/mod.rs", "rank": 72, "score": 18.46914242595035 }, { "content": "\n\n fn from_str(s: &str) -> Result<Self, Self::Err> {\n\n quick_xml::de::from_str(s).map_err(|e| e.into())\n\n }\n\n}\n\n\n\nimpl ToString for Destinatario {\n\n fn to_string(&self) -> String {\n\n quick_xml::se::to_string(self).expect(\"Falha ao serializar o destinatário\")\n\n }\n\n}\n", "file_path": "nfe/src/base/dest.rs", "rank": 73, "score": 18.303433301252284 }, { "content": "//! Impostos dos itens\n\n\n\nuse super::Error;\n\nuse serde::{Deserialize, Serialize};\n\nuse std::str::FromStr;\n\n\n\nmod cofins;\n\nmod icms;\n\nmod pis;\n\n\n\npub use cofins::*;\n\npub use icms::*;\n\npub use pis::*;\n\n\n\n/// Detalhamentos impostos sobre o item\n\n#[derive(Debug, Deserialize, PartialEq, Serialize, Clone)]\n\n#[serde(rename = \"imposto\")]\n\npub struct Imposto {\n\n /// Valor aproximado total de tributos federais, estaduais e municipais\n\n #[serde(rename = \"$unflatten=vTotTrib\")]\n", "file_path": "nfe/src/base/item/imposto/mod.rs", "rank": 75, "score": 17.832009581795084 }, { "content": "\n\nimpl FromStr for Nfe {\n\n type Err = Error;\n\n\n\n fn from_str(s: &str) -> Result<Self, Self::Err> {\n\n s.parse::<NfeBase>()?.try_into()\n\n }\n\n}\n\n\n\nimpl TryFrom<File> for Nfe {\n\n type Error = Error;\n\n\n\n fn try_from(f: File) -> Result<Self, Self::Error> {\n\n NfeBase::try_from(f)?.try_into()\n\n }\n\n}\n\n\n\nimpl ToString for Nfe {\n\n fn to_string(&self) -> String {\n\n let base: NfeBase = self.into();\n\n\n\n base.to_string()\n\n }\n\n}\n", "file_path": "nfe/src/modelos/nfe/mod.rs", "rank": 76, "score": 17.1183978514146 }, { "content": "//! Destinatário da NF-e no modelo 55\n\n\n\nuse super::Error;\n\nuse crate::base::dest::Destinatario as DestinatarioBase;\n\npub use crate::base::dest::IndicadorContribuicaoIe;\n\npub use crate::base::endereco::Endereco;\n\nuse std::convert::{TryFrom, TryInto};\n\nuse std::str::FromStr;\n\n\n\n/// Destinatário da NF-e\n\npub struct Destinatario {\n\n pub cnpj: String,\n\n pub razao_social: String,\n\n pub endereco: Endereco,\n\n pub ie: Option<String>,\n\n pub indicador_ie: IndicadorContribuicaoIe,\n\n}\n\n\n\nimpl TryFrom<DestinatarioBase> for Destinatario {\n\n type Error = Error;\n", "file_path": "nfe/src/modelos/nfe/dest.rs", "rank": 77, "score": 16.802412298169084 }, { "content": "//! Base da NF-e\n\n//!\n\n//! Tipos e estruturas para tratamento da NF-e sem\n\n//! distinção dos modelos.\n\n\n\nuse serde::{Deserialize, Deserializer, Serialize, Serializer};\n\nuse std::convert::TryFrom;\n\nuse std::fs::File;\n\nuse std::io::Read;\n\nuse std::str::FromStr;\n\npub mod dest;\n\npub mod emit;\n\npub mod endereco;\n\nmod error;\n\npub mod ide;\n\npub mod item;\n\npub mod totais;\n\npub mod transporte;\n\nuse dest::Destinatario;\n\nuse emit::Emitente;\n", "file_path": "nfe/src/base/mod.rs", "rank": 78, "score": 16.252514142894505 }, { "content": "//! Grupos de ICMS\n\n\n\nuse serde::{de::Error, Deserialize, Deserializer, Serialize, Serializer};\n\nuse serde_repr::{Deserialize_repr, Serialize_repr};\n\n\n\n/// ICMS\n\n#[derive(Debug, PartialEq, Clone)]\n\npub enum GrupoIcms {\n\n /// Tributação ICMS pelo Simples Nacional, CSOSN=202 ou 203\n\n IcmsSn202(GrupoIcmsSn202),\n\n /// Tributação ICMS cobrado anteriormente por substituição tributária\n\n Icms60(GrupoIcms60),\n\n}\n\n\n\nimpl<'de> Deserialize<'de> for GrupoIcms {\n\n fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>\n\n where\n\n D: Deserializer<'de>,\n\n {\n\n let grc = GrupoIcmsContainer::deserialize(deserializer)?;\n", "file_path": "nfe/src/base/item/imposto/icms.rs", "rank": 79, "score": 15.452578322081845 }, { "content": "\n\nimpl ToString for Produto {\n\n fn to_string(&self) -> String {\n\n quick_xml::se::to_string(self).expect(\"Falha ao serializar o produto\")\n\n }\n\n}\n\n\n\nimpl<'de> Deserialize<'de> for Produto {\n\n fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>\n\n where\n\n D: Deserializer<'de>,\n\n {\n\n // TODO: voltar a tentar usar o serde flatten\n\n let prod = ProdContainer::deserialize(deserializer)?;\n\n\n\n Ok(Self {\n\n codigo: prod.codigo,\n\n gtin: match prod.gtin.to_lowercase().trim() {\n\n \"sem gtin\" => None,\n\n \"\" => None,\n", "file_path": "nfe/src/base/item/produto.rs", "rank": 80, "score": 14.740176963858016 }, { "content": "/// Grupos de COFINS\n\nuse serde::{de::Error, Deserialize, Deserializer, Serialize, Serializer};\n\n\n\n/// COFINS\n\n#[derive(Debug, PartialEq, Clone)]\n\npub enum GrupoCofins {\n\n /// Outras Operações\n\n CofinsOutr(GrupoCofinsOutr),\n\n /// Não Tributado\n\n CofinsNt(GrupoCofinsNt),\n\n /// Tributado pela alíquota\n\n CofinsAliq(GrupoCofinsAliq),\n\n}\n\n\n\nimpl<'de> Deserialize<'de> for GrupoCofins {\n\n fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>\n\n where\n\n D: Deserializer<'de>,\n\n {\n\n let grc = GrupoCofinsContainer::deserialize(deserializer)?;\n", "file_path": "nfe/src/base/item/imposto/cofins.rs", "rank": 81, "score": 14.735229291746743 }, { "content": "/// Grupos de PIS\n\nuse serde::{de::Error, Deserialize, Deserializer, Serialize, Serializer};\n\n\n\n/// PIS\n\n#[derive(Debug, PartialEq, Clone)]\n\npub enum GrupoPis {\n\n /// Outras Operações\n\n PisOutr(GrupoPisOutr),\n\n /// Não Tributado\n\n PisNt(GrupoPisNt),\n\n /// Tributado pela alíquota\n\n PisAliq(GrupoPisAliq),\n\n}\n\n\n\nimpl<'de> Deserialize<'de> for GrupoPis {\n\n fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>\n\n where\n\n D: Deserializer<'de>,\n\n {\n\n let grc = GrupoPisContainer::deserialize(deserializer)?;\n", "file_path": "nfe/src/base/item/imposto/pis.rs", "rank": 82, "score": 14.735229291746744 }, { "content": " #[serde(rename = \"$unflatten=IE\")]\n\n pub ie: Option<String>,\n\n #[serde(rename = \"$unflatten=indIEDest\")]\n\n pub indicador_ie: IndicadorContribuicaoIe,\n\n}\n\n\n\n/// Indicador da IE do destinatário\n\n#[derive(Debug, Eq, PartialEq, Copy, Clone, Deserialize_repr, Serialize_repr)]\n\n#[repr(u8)]\n\npub enum IndicadorContribuicaoIe {\n\n /// Contribuinte ICMS\n\n Contribuinte = 1,\n\n /// Contribuinte isento de Inscrição no cadastro de Contribuintes\n\n Isento = 2,\n\n /// Não Contribuinte, que pode ou não possuir Inscrição Estadual no Cadastro de Contribuintes do ICMS\n\n NaoContribuinte = 9,\n\n}\n\n\n\nimpl FromStr for Destinatario {\n\n type Err = Error;\n", "file_path": "nfe/src/base/dest.rs", "rank": 83, "score": 14.540201473927205 }, { "content": " pub valor_base_calculo: f32,\n\n /// Alíquota do COFINS(%)\n\n #[serde(rename = \"$unflatten=pCOFINS\")]\n\n pub aliquota: f32,\n\n}\n\n\n\n/// Grupo COFINS NT - COFINS não tributado\n\n#[derive(Debug, PartialEq, Deserialize, Serialize, Clone)]\n\npub struct GrupoCofinsNt {\n\n /// CST - Código de Situação Tributária do COFINS\n\n #[serde(rename = \"$unflatten=CST\")]\n\n pub codigo_situacao: String,\n\n}\n\n\n\n/// Grupo COFINS Aliq - Aliq Operações\n\n#[derive(Debug, PartialEq, Deserialize, Serialize, Clone)]\n\npub struct GrupoCofinsAliq {\n\n /// CST - Código de Situação Tributária do COFINS\n\n #[serde(rename = \"$unflatten=CST\")]\n\n pub codigo_situacao: String,\n", "file_path": "nfe/src/base/item/imposto/cofins.rs", "rank": 84, "score": 14.46334856224938 }, { "content": " pub valor_base_calculo: f32,\n\n /// Alíquota do PIS(%)\n\n #[serde(rename = \"$unflatten=pPIS\")]\n\n pub aliquota: f32,\n\n}\n\n\n\n/// Grupo PIS NT - PIS não tributado\n\n#[derive(Debug, PartialEq, Deserialize, Serialize, Clone)]\n\npub struct GrupoPisNt {\n\n /// CST - Código de Situação Tributária do PIS\n\n #[serde(rename = \"$unflatten=CST\")]\n\n pub codigo_situacao: String,\n\n}\n\n\n\n/// Grupo PIS Aliq - Aliq Operações\n\n#[derive(Debug, PartialEq, Deserialize, Serialize, Clone)]\n\npub struct GrupoPisAliq {\n\n /// CST - Código de Situação Tributária do PIS\n\n #[serde(rename = \"$unflatten=CST\")]\n\n pub codigo_situacao: String,\n", "file_path": "nfe/src/base/item/imposto/pis.rs", "rank": 85, "score": 14.46334856224938 }, { "content": " quick_xml::de::from_str(s).map_err(|e| e.into())\n\n }\n\n}\n\n\n\nimpl ToString for Transporte {\n\n fn to_string(&self) -> String {\n\n quick_xml::se::to_string(self).expect(\"Falha ao serializar o transporte\")\n\n }\n\n}\n\n\n\n/// Modalidade do frete\n\n#[derive(Debug, Eq, PartialEq, Copy, Clone, Deserialize_repr, Serialize_repr)]\n\n#[repr(u8)]\n\npub enum ModalidadeFrete {\n\n /// CIF - Contratação do frete por conta do remetente\n\n ContratacaoPorContaRemetente = 0,\n\n /// FOB - Contratação do frete por conta do destinarário\n\n ContratacaoPorContaDestinatario = 1,\n\n /// Contratação do frete por conta de terceiros\n\n ContratacaoPorContaTerceiros = 2,\n\n /// Transporte próprio por conta do remetente\n\n TransportePorContaRemetente = 3,\n\n /// Transporte próprio por conta do destinatário\n\n TransportePorContaDestinatario = 4,\n\n /// Sem ocorrência de transporte\n\n SemTransporte = 9,\n\n}\n", "file_path": "nfe/src/base/transporte.rs", "rank": 86, "score": 14.309792956551927 }, { "content": "impl From<&Destinatario> for DestinatarioBase {\n\n fn from(dest: &Destinatario) -> Self {\n\n Self {\n\n cnpj: dest.cnpj.clone(),\n\n razao_social: Some(dest.razao_social.clone()),\n\n endereco: Some(dest.endereco.clone()),\n\n ie: dest.ie.clone(),\n\n indicador_ie: dest.indicador_ie,\n\n }\n\n }\n\n}\n\n\n\nimpl FromStr for Destinatario {\n\n type Err = Error;\n\n\n\n fn from_str(s: &str) -> Result<Self, Self::Err> {\n\n let base = s.parse::<DestinatarioBase>()?;\n\n\n\n base.try_into()\n\n }\n", "file_path": "nfe/src/modelos/nfe/dest.rs", "rank": 87, "score": 14.10259921803107 }, { "content": "pub use error::Error;\n\nuse ide::Identificacao;\n\nuse item::Item;\n\nuse totais::Totalizacao;\n\nuse transporte::Transporte;\n\n\n\n/// Base da Nota Fiscal Eletrônica\n\n///\n\n/// Representa o documento ainda sem a interface\n\n/// do seu modelo(NF-e x NFC-e)\n\n#[derive(Debug, PartialEq)]\n\npub struct Nfe {\n\n pub versao: VersaoLayout,\n\n pub chave_acesso: String,\n\n pub ide: Identificacao,\n\n pub emit: Emitente,\n\n pub dest: Option<Destinatario>,\n\n pub itens: Vec<Item>,\n\n pub totais: Totalizacao,\n\n pub transporte: Transporte,\n", "file_path": "nfe/src/base/mod.rs", "rank": 88, "score": 13.968506969725437 }, { "content": "//! Dados da operação da NF-e\n\n\n\nuse chrono::prelude::*;\n\nuse serde_repr::{Deserialize_repr, Serialize_repr};\n\n\n\n/// Dados referentes a operação da nota\n\n#[derive(Debug, PartialEq, Clone)]\n\npub struct Operacao {\n\n pub horario: Option<DateTime<Utc>>,\n\n pub tipo: TipoOperacao,\n\n pub destino: DestinoOperacao,\n\n pub natureza: String,\n\n pub consumidor: TipoConsumidor,\n\n pub presenca: TipoPresencaComprador,\n\n pub intermediador: Option<TipoIntermediador>,\n\n}\n\n\n\n/// Tipo de operação da nota\n\n#[derive(Debug, Eq, PartialEq, Copy, Clone, Deserialize_repr, Serialize_repr)]\n\n#[repr(u8)]\n", "file_path": "nfe/src/base/ide/operacao.rs", "rank": 89, "score": 13.825215243816544 }, { "content": "//! Dados da emissão da NF-e\n\n\n\nuse chrono::prelude::*;\n\nuse serde_repr::{Deserialize_repr, Serialize_repr};\n\n\n\n/// Dados referentes a emissão da nota\n\n#[derive(Debug, PartialEq, Clone)]\n\npub struct Emissao {\n\n pub horario: DateTime<Utc>,\n\n pub tipo: TipoEmissao,\n\n pub finalidade: FinalidadeEmissao,\n\n pub processo: TipoProcessoEmissao,\n\n pub versao_processo: String,\n\n}\n\n\n\n/// Tipo da emissão da nota\n\n#[derive(Debug, Eq, PartialEq, Copy, Clone, Deserialize_repr, Serialize_repr)]\n\n#[repr(u8)]\n\npub enum TipoEmissao {\n\n /// Emissão normal (não em contingência)\n", "file_path": "nfe/src/base/ide/emissao.rs", "rank": 90, "score": 13.785921808493676 }, { "content": "/// Nota Fiscal Eletrônica\n\n///\n\n/// Apenas o modelo 55 é suportado\n\npub struct Nfe {\n\n pub versao: VersaoLayout,\n\n pub chave_acesso: String,\n\n pub ide: Identificacao,\n\n pub emit: Emitente,\n\n pub dest: Destinatario,\n\n pub itens: Vec<Item>,\n\n pub totais: Totalizacao,\n\n pub transporte: Transporte,\n\n /// Informações complementares de interesse do contribuinte\n\n pub informacao_complementar: Option<String>,\n\n}\n\n\n\nimpl TryFrom<NfeBase> for Nfe {\n\n type Error = Error;\n\n\n\n fn try_from(doc: NfeBase) -> Result<Self, Self::Error> {\n", "file_path": "nfe/src/modelos/nfe/mod.rs", "rank": 91, "score": 12.879429288061294 }, { "content": "//! Modelo 55 da NF-e\n\n\n\nuse crate::base::dest::Destinatario as DestinatarioBase;\n\npub use crate::base::emit::*;\n\npub use crate::base::endereco::*;\n\npub use crate::base::ide::*;\n\npub use crate::base::item::*;\n\npub use crate::base::totais::*;\n\npub use crate::base::transporte::*;\n\nuse crate::base::Nfe as NfeBase;\n\npub use crate::base::VersaoLayout;\n\nuse std::convert::{TryFrom, TryInto};\n\nuse std::fs::File;\n\nuse std::str::FromStr;\n\n\n\nmod dest;\n\nmod error;\n\npub use dest::*;\n\npub use error::*;\n\n\n", "file_path": "nfe/src/modelos/nfe/mod.rs", "rank": 92, "score": 12.489322717911271 }, { "content": " };\n\n\n\n let root = NfeRootContainer { inf };\n\n\n\n root.serialize(serializer)\n\n }\n\n}\n\n\n\nimpl Serialize for VersaoLayout {\n\n fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>\n\n where\n\n S: Serializer,\n\n {\n\n serializer.serialize_str(match self {\n\n VersaoLayout::V4_00 => \"4.00\",\n\n })\n\n }\n\n}\n\n\n\n#[derive(Deserialize, Serialize)]\n\n#[serde(rename = \"NFe\")]\n", "file_path": "nfe/src/base/mod.rs", "rank": 93, "score": 12.487510778841877 }, { "content": " pub t_escala_relevante: Option<EscalaRelevante>,\n\n #[serde(rename = \"$unflatten=cBenef\")]\n\n #[serde(skip_serializing_if = \"Option::is_none\")]\n\n pub t_codigo_beneficio_fiscal: Option<String>,\n\n #[serde(rename = \"$unflatten=EXTIPI\")]\n\n #[serde(skip_serializing_if = \"Option::is_none\")]\n\n pub t_codigo_excecao_ipi: Option<String>,\n\n #[serde(rename = \"$unflatten=CFOP\")]\n\n pub t_cfop: String,\n\n #[serde(rename = \"$unflatten=cEANTrib\")]\n\n pub t_gtin: String,\n\n #[serde(rename = \"$unflatten=uTrib\")]\n\n pub t_unidade: String,\n\n #[serde(rename = \"$unflatten=qTrib\")]\n\n pub t_quantidade: f32,\n\n #[serde(rename = \"$unflatten=vUnTrib\")]\n\n pub t_valor_unitario: f32,\n\n}\n", "file_path": "nfe/src/base/item/produto.rs", "rank": 95, "score": 11.42582722102635 }, { "content": "\n\n if let Some(gr) = grc.icms_sn_202 {\n\n return Ok(GrupoIcms::IcmsSn202(gr));\n\n }\n\n\n\n if let Some(gr) = grc.icms_60 {\n\n return Ok(GrupoIcms::Icms60(gr));\n\n }\n\n\n\n Err(Error::custom(\"Tipo de ICMS não suportado\".to_string()))\n\n }\n\n}\n\n\n\nimpl Serialize for GrupoIcms {\n\n fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>\n\n where\n\n S: Serializer,\n\n {\n\n let grc = match self {\n\n GrupoIcms::IcmsSn202(g) => GrupoIcmsContainer {\n", "file_path": "nfe/src/base/item/imposto/icms.rs", "rank": 96, "score": 11.344604487264428 }, { "content": "\n\n if let Some(gr) = grc.pis_outr {\n\n return Ok(GrupoPis::PisOutr(gr));\n\n }\n\n\n\n if let Some(gr) = grc.pis_nt {\n\n return Ok(GrupoPis::PisNt(gr));\n\n }\n\n\n\n if let Some(gr) = grc.pis_aliq {\n\n return Ok(GrupoPis::PisAliq(gr));\n\n }\n\n\n\n Err(Error::custom(\"Tipo de PIS não suportado\".to_string()))\n\n }\n\n}\n\n\n\nimpl Serialize for GrupoPis {\n\n fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>\n\n where\n", "file_path": "nfe/src/base/item/imposto/pis.rs", "rank": 97, "score": 10.956918865012703 }, { "content": "\n\n if let Some(gr) = grc.cofins_outr {\n\n return Ok(GrupoCofins::CofinsOutr(gr));\n\n }\n\n\n\n if let Some(gr) = grc.cofins_nt {\n\n return Ok(GrupoCofins::CofinsNt(gr));\n\n }\n\n\n\n if let Some(gr) = grc.cofins_aliq {\n\n return Ok(GrupoCofins::CofinsAliq(gr));\n\n }\n\n\n\n Err(Error::custom(\"Tipo de COFINS não suportado\".to_string()))\n\n }\n\n}\n\n\n\nimpl Serialize for GrupoCofins {\n\n fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>\n\n where\n", "file_path": "nfe/src/base/item/imposto/cofins.rs", "rank": 98, "score": 10.956918865012705 }, { "content": " t_cfop: self.tributacao.cfop.clone(),\n\n t_gtin: match &self.tributacao.gtin {\n\n Some(gt) => gt.clone(),\n\n None => \"SEM GTIN\".to_string(),\n\n },\n\n t_unidade: self.tributacao.unidade.clone(),\n\n t_quantidade: self.tributacao.quantidade,\n\n t_valor_unitario: self.tributacao.valor_unitario,\n\n };\n\n\n\n prod.serialize(serializer)\n\n }\n\n}\n\n\n\n#[derive(Deserialize, Serialize)]\n\n#[serde(rename = \"prod\")]\n", "file_path": "nfe/src/base/item/produto.rs", "rank": 99, "score": 10.808485897933856 } ]
Rust
src/exmo/mod.rs
terrybrashaw/ni_ce
cf3c2c71a78a567eab8e387d716a15b913bd92c2
use failure::{Error, ResultExt}; use hex; use hmac::{Hmac, Mac}; use http; use rust_decimal::Decimal as d128; use serde::de::DeserializeOwned; use serde::de::{Deserialize, Deserializer, Visitor}; use serde; use serde_json; use sha2::Sha512; use std::collections::HashMap; use std::fmt::{self, Display, Formatter}; use std::str::FromStr; use {HttpClient, Query}; pub const API_HOST: &str = "https://api.exmo.com"; #[derive(Debug, Hash, PartialEq, PartialOrd, Eq, Ord, Clone, Deserialize, Serialize)] pub struct Credential { pub key: String, pub secret: String, pub nonce: i64, } #[derive(Debug, Hash, PartialEq, PartialOrd, Eq, Ord, Clone, Deserialize, Serialize)] pub struct Currency(String); impl FromStr for Currency { type Err = Error; fn from_str(s: &str) -> Result<Self, Self::Err> { Ok(Currency(s.to_uppercase())) } } impl Display for Currency { fn fmt(&self, f: &mut Formatter) -> Result<(), fmt::Error> { let &Currency(ref currency) = self; f.write_str(currency) } } #[derive(Debug, Hash, PartialEq, PartialOrd, Eq, Ord, Clone, Serialize)] pub struct CurrencyPair(pub Currency, pub Currency); impl CurrencyPair { pub fn base(&self) -> &Currency { let &CurrencyPair(ref base, _) = self; base } pub fn quote(&self) -> &Currency { let &CurrencyPair(_, ref quote) = self; quote } } impl Display for CurrencyPair { fn fmt(&self, f: &mut Formatter) -> Result<(), fmt::Error> { write!(f, "{}_{}", self.base(), self.quote()) } } impl<'de> Deserialize<'de> for CurrencyPair { fn deserialize<D>(deserializer: D) -> Result<Self, D::Error> where D: Deserializer<'de> { struct CurrencyPairVisitor; impl<'de> Visitor<'de> for CurrencyPairVisitor { type Value = CurrencyPair; fn expecting(&self, f: &mut fmt::Formatter) -> fmt::Result { f.write_str("a string containing two currencies separated by an underscore") } fn visit_str<E>(self, pair: &str) -> Result<Self::Value, E> where E: serde::de::Error { let currencies: Vec<&str> = pair.split('_').collect(); if currencies.len() < 2 { return Err(E::invalid_value(serde::de::Unexpected::Str(pair), &self)); } let base = Currency::from_str(currencies[0]).map_err(serde::de::Error::custom)?; let quote = Currency::from_str(currencies[1]).map_err(serde::de::Error::custom)?; Ok(CurrencyPair(base, quote)) } } deserializer.deserialize_str(CurrencyPairVisitor) } } #[derive(Debug, Hash, PartialEq, PartialOrd, Eq, Ord, Clone, Deserialize, Serialize)] #[serde(rename_all = "lowercase")] pub enum Side { Buy, Sell, } #[derive(Debug, PartialEq, Eq, Copy, Hash, PartialOrd, Ord, Clone, Deserialize, Serialize)] pub enum OrderInstruction { LimitBuy, LimitSell, MarketBuy, MarketSell, MarketBuyTotal, MarketSellTotal, } impl Display for OrderInstruction { fn fmt(&self, f: &mut Formatter) -> Result<(), fmt::Error> { match *self { OrderInstruction::LimitBuy => f.write_str("buy"), OrderInstruction::LimitSell => f.write_str("sell"), OrderInstruction::MarketBuy => f.write_str("market_buy"), OrderInstruction::MarketSell => f.write_str("market_sell"), OrderInstruction::MarketBuyTotal => f.write_str("market_buy_total"), OrderInstruction::MarketSellTotal => f.write_str("market_sell_total"), } } } #[derive(Debug, Hash, PartialEq, PartialOrd, Eq, Ord, Clone, Deserialize, Serialize)] pub struct Orderbook { pub ask_quantity: d128, pub ask_amount: d128, pub ask_top: d128, pub bid_quantity: d128, pub bid_amount: d128, pub bid_top: d128, pub ask: Vec<(d128, d128, d128)>, pub bid: Vec<(d128, d128, d128)>, } #[derive(Debug, PartialEq, Eq, Clone, Deserialize, Serialize)] pub struct UserInfo { pub uid: i64, pub server_date: u64, pub balances: HashMap<Currency, d128>, pub reserved: HashMap<Currency, d128>, } #[derive(Debug, Hash, PartialEq, PartialOrd, Eq, Ord, Clone, Deserialize, Serialize)] pub struct Order { pub order_id: i64, } pub fn get_user_info<Client>( client: &mut Client, host: &str, credential: &Credential, ) -> Result<UserInfo, Error> where Client: HttpClient, { let query = { let mut query = Query::with_capacity(2); query.append_param("nonce", credential.nonce.to_string()); query.to_string() }; let mut http_request = http::request::Builder::new() .method(http::Method::POST) .uri(format!("{}/v1/user_info?{}", host, query)) .body(query)?; sign_private_request(&mut http_request, credential)?; let http_response = client.send(&http_request)?; deserialize_private_response(&http_response) } pub fn place_limit_order<Client>( client: &mut Client, host: &str, credential: &Credential, product: &CurrencyPair, price: d128, quantity: d128, side: Side, ) -> Result<(), Error> where Client: HttpClient, { let query = { let mut query = Query::with_capacity(5); query.append_param("nonce", credential.nonce.to_string()); query.append_param("pair", product.to_string()); query.append_param("quantity", quantity.to_string()); query.append_param("price", price.to_string()); match side { Side::Buy => query.append_param("type", "buy"), Side::Sell => query.append_param("type", "sell"), } query.to_string() }; let mut http_request = http::request::Builder::new() .method(http::Method::POST) .uri(format!("{}/v1/order_create?{}", host, query)) .body(query)?; sign_private_request(&mut http_request, credential)?; client.send(&http_request)?; Ok(()) } pub fn get_orderbooks<Client>( client: &mut Client, host: &str, products: &[&CurrencyPair], ) -> Result<HashMap<CurrencyPair, Orderbook>, Error> where Client: HttpClient, { let products: Vec<String> = products.iter().map(ToString::to_string).collect(); let query = { let mut query = Query::with_capacity(2); query.append_param("pair", products.as_slice().join(",")); query.append_param("limit", "100"); query.to_string() }; let http_request = http::request::Builder::new() .method(http::Method::GET) .uri(format!("{}/v1/order_book?{}", host, query)) .body(String::new())?; let http_response = client.send(&http_request)?; deserialize_public_response(&http_response) } #[derive(Debug, Hash, PartialEq, PartialOrd, Eq, Ord, Clone, Deserialize, Serialize)] struct ErrorResponse { pub result: bool, pub error: String, } fn sign_private_request( request: &mut http::Request<String>, credential: &Credential, ) -> Result<(), Error> { let mut mac = Hmac::<Sha512>::new(credential.secret.as_bytes()).map_err(|e| format_err!("{:?}", e))?; mac.input(request.body().as_bytes()); let signature = hex::encode(mac.result().code().to_vec()); let headers = request.headers_mut(); headers.insert("Key", credential.key.clone().parse().unwrap()); headers.insert("Sign", signature.parse().unwrap()); Ok(()) } fn deserialize_private_response<T>(response: &http::Response<String>) -> Result<T, Error> where T: DeserializeOwned { let body = response.body(); let response: serde_json::Value = serde_json::from_str(body)?; let is_error = response .as_object() .map(|object| { match object.get("result") { Some(&serde_json::Value::Bool(result)) => !result, _ => false, } }) .unwrap_or(false); if is_error { let error: ErrorResponse = serde_json::from_value(response) .with_context(|_| format!("failed to deserialize: \"{}\"", body))?; Err(format_err!("Server returned: {}", error.error)) } else { let response = serde_json::from_value(response) .context(format!("failed to deserialize: \"{}\"", body))?; Ok(response) } } fn deserialize_public_response<T>(response: &http::Response<String>) -> Result<T, Error> where T: DeserializeOwned { let body = response.body(); Ok(serde_json::from_str(body)?) }
use failure::{Error, ResultExt}; use hex; use hmac::{Hmac, Mac}; use http; use rust_decimal::Decimal as d128; use serde::de::DeserializeOwned; use serde::de::{Deserialize, Deserializer, Visitor}; use serde; use serde_json; use sha2::Sha512; use std::collections::HashMap; use std::fmt::{self, Display, Formatter}; use std::str::FromStr; use {HttpClient, Query}; pub const API_HOST: &str = "https://api.exmo.com"; #[derive(Debug, Hash, PartialEq, PartialOrd, Eq, Ord, Clone, Deserialize, Serialize)] pub struct Credential { pub key: String, pub secret: String, pub nonce: i64, } #[derive(Debug, Hash, PartialEq, PartialOrd, Eq, Ord, Clone, Deserialize, Serialize)] pub struct Currency(String); impl FromStr for Currency { type Err = Error; fn from_str(s: &str) -> Result<Self, Self::Err> { Ok(Currency(s.to_uppercase())) } } impl Display for Currency { fn fmt(&self, f: &mut Formatter) -> Result<(), fmt::Error> { let &Currency(ref currency) = self; f.write_str(currency) } } #[derive(Debug, Hash, PartialEq, PartialOrd, Eq, Ord, Clone, Serialize)] pub struct CurrencyPair(pub Currency, pub Currency); impl CurrencyPair { pub fn base(&self) -> &Currency { let &CurrencyPair(ref base, _) = self; base } pub fn quote(&self) -> &Currency { let &CurrencyPair(_, ref quote) = self; quote } } impl Display for CurrencyPair { fn fmt(&self, f: &mut Formatter) -> Result<(), fmt::Error> { write!(f, "{}_{}", self.base(), self.quote()) } } impl<'de> Deserialize<'de> for CurrencyPair { fn deserialize<D>(deserializer: D) -> Result<Self, D::Error> where D: Deserializer<'de> { struct CurrencyPairVisitor; impl<'de> Visitor<'de> for CurrencyPairVisitor { type Value = CurrencyPair; fn expecting(&self, f: &mut fmt::Formatter) -> fmt::Result { f.write_str("a string containing two currencies separated by an underscore") } fn visit_str<E>(self, pair: &str) -> Result<Self::Value, E> where E: serde::de::Error { let currencies: Vec<&str> = pair.split('_').collect(); if currencies.len() < 2 { return Err(E::invalid_value(serde::de::Unexpected::Str(pair), &self)); } let base = Currency::from_str(currencies[0]).map_err(serde::de::Error::custom)?; let quote = Currency::from_str(currencies[1]).map_err(serde::de::Error::custom)?; Ok(CurrencyPair(base, quote)) } } deserializer.deserialize_str(CurrencyPairVisitor) } } #[derive(Debug, Hash, PartialEq, PartialOrd, Eq, Ord, Clone, Deserialize, Serialize)] #[serde(rename_all = "lowercase")] pub enum Side { Buy, Sell, } #[derive(Debug, PartialEq, Eq, Copy, Hash, PartialOrd, Ord, Clone, Deserialize, Serialize)] pub enum OrderInstruction { LimitBuy, LimitSell, MarketBuy, MarketSell, MarketBuyTotal, MarketSellTotal, } impl Display for OrderInstruction { fn fmt(&self, f: &mut Formatter) -> Result<(), fmt::Error> { match *self { OrderInstruction::LimitBuy => f.write_str("buy"), OrderInstruction::LimitSell => f.write_str("sell"), OrderInstruction::MarketBuy => f.write_str("market_buy"), OrderInstruction::MarketSell => f.write_str("market_sell"), OrderInstruction::MarketBuyTotal => f.write_str("market_buy_total"), OrderInstruction::MarketSellTotal => f.write_str("market_sell_total"), } } } #[derive(Debug, Hash, PartialEq, PartialOrd, Eq, Ord, Clone, Deserialize, Serialize)] pub struct Orderbook { pub ask_quantity: d128, pub ask_amount: d128, pub ask_top: d128, pub bid_quantity: d128, pub bid_amount: d128, pub bid_top: d128, pub ask: Vec<(d128, d128, d128)>, pub bid: Vec<(d128, d128, d128)>, } #[derive(Debug, PartialEq, Eq, Clone, Deserialize, Serialize)] pub struct UserInfo { pub uid: i64, pub server_date: u64, pub balances: HashMap<Currency, d128>, pub reserved: HashMap<Currency, d128>, } #[derive(Debug, Hash, PartialEq, PartialOrd, Eq, Ord, Clone, Deserialize, Serialize)] pub struct Order { pub order_id: i64, }
pub fn place_limit_order<Client>( client: &mut Client, host: &str, credential: &Credential, product: &CurrencyPair, price: d128, quantity: d128, side: Side, ) -> Result<(), Error> where Client: HttpClient, { let query = { let mut query = Query::with_capacity(5); query.append_param("nonce", credential.nonce.to_string()); query.append_param("pair", product.to_string()); query.append_param("quantity", quantity.to_string()); query.append_param("price", price.to_string()); match side { Side::Buy => query.append_param("type", "buy"), Side::Sell => query.append_param("type", "sell"), } query.to_string() }; let mut http_request = http::request::Builder::new() .method(http::Method::POST) .uri(format!("{}/v1/order_create?{}", host, query)) .body(query)?; sign_private_request(&mut http_request, credential)?; client.send(&http_request)?; Ok(()) } pub fn get_orderbooks<Client>( client: &mut Client, host: &str, products: &[&CurrencyPair], ) -> Result<HashMap<CurrencyPair, Orderbook>, Error> where Client: HttpClient, { let products: Vec<String> = products.iter().map(ToString::to_string).collect(); let query = { let mut query = Query::with_capacity(2); query.append_param("pair", products.as_slice().join(",")); query.append_param("limit", "100"); query.to_string() }; let http_request = http::request::Builder::new() .method(http::Method::GET) .uri(format!("{}/v1/order_book?{}", host, query)) .body(String::new())?; let http_response = client.send(&http_request)?; deserialize_public_response(&http_response) } #[derive(Debug, Hash, PartialEq, PartialOrd, Eq, Ord, Clone, Deserialize, Serialize)] struct ErrorResponse { pub result: bool, pub error: String, } fn sign_private_request( request: &mut http::Request<String>, credential: &Credential, ) -> Result<(), Error> { let mut mac = Hmac::<Sha512>::new(credential.secret.as_bytes()).map_err(|e| format_err!("{:?}", e))?; mac.input(request.body().as_bytes()); let signature = hex::encode(mac.result().code().to_vec()); let headers = request.headers_mut(); headers.insert("Key", credential.key.clone().parse().unwrap()); headers.insert("Sign", signature.parse().unwrap()); Ok(()) } fn deserialize_private_response<T>(response: &http::Response<String>) -> Result<T, Error> where T: DeserializeOwned { let body = response.body(); let response: serde_json::Value = serde_json::from_str(body)?; let is_error = response .as_object() .map(|object| { match object.get("result") { Some(&serde_json::Value::Bool(result)) => !result, _ => false, } }) .unwrap_or(false); if is_error { let error: ErrorResponse = serde_json::from_value(response) .with_context(|_| format!("failed to deserialize: \"{}\"", body))?; Err(format_err!("Server returned: {}", error.error)) } else { let response = serde_json::from_value(response) .context(format!("failed to deserialize: \"{}\"", body))?; Ok(response) } } fn deserialize_public_response<T>(response: &http::Response<String>) -> Result<T, Error> where T: DeserializeOwned { let body = response.body(); Ok(serde_json::from_str(body)?) }
pub fn get_user_info<Client>( client: &mut Client, host: &str, credential: &Credential, ) -> Result<UserInfo, Error> where Client: HttpClient, { let query = { let mut query = Query::with_capacity(2); query.append_param("nonce", credential.nonce.to_string()); query.to_string() }; let mut http_request = http::request::Builder::new() .method(http::Method::POST) .uri(format!("{}/v1/user_info?{}", host, query)) .body(query)?; sign_private_request(&mut http_request, credential)?; let http_response = client.send(&http_request)?; deserialize_private_response(&http_response) }
function_block-full_function
[ { "content": "fn private_signature(credential: &Credential, query: &str) -> Result<String, Error> {\n\n let mut mac =\n\n Hmac::<Sha256>::new(credential.secret.as_bytes()).map_err(|e| format_err!(\"{:?}\", e))?;\n\n mac.input(query.as_bytes());\n\n Ok(hex::encode(mac.result().code().to_vec()))\n\n}\n\n\n\nconst X_MBX_APIKEY: &str = \"X-MBX-APIKEY\";\n\n\n", "file_path": "src/binance/mod.rs", "rank": 0, "score": 224957.8884530993 }, { "content": "/// Deserialize a response from a *private* REST request.\n\nfn deserialize_private_response<T>(response: &http::Response<String>) -> Result<T, Error>\n\nwhere T: DeserializeOwned {\n\n let body = response.body();\n\n let response: PrivateResponse<T> = serde_json::from_str(body.as_str())\n\n .with_context(|_| format!(\"failed to deserialize: \\\"{}\\\"\", body))?;\n\n\n\n response\n\n .into_result()\n\n .map_err(|e| format_err!(\"the server returned \\\"{}\\\"\", e))\n\n}\n\n\n\n/// Response to a public request.\n\n///\n\n/// As far as I can tell, a public response is either:\n\n/// * `T` where `T` is the object being requested, or\n\n/// * `PublicResponse` in the event of an error.\n", "file_path": "src/liqui/mod.rs", "rank": 3, "score": 202144.25936843143 }, { "content": "/// Deserialize a response from a *public* REST request.\n\nfn deserialize_public_response<T>(response: &http::Response<String>) -> Result<T, Error>\n\nwhere T: DeserializeOwned {\n\n let body = response.body();\n\n\n\n // First, deserialize into `PublicResponse`, to check if the response is an error.\n\n let response: PublicResponse = serde_json::from_str(body.as_str())\n\n .with_context(|_| format!(\"failed to deserialize: \\\"{}\\\"\", body))?;\n\n if !response.is_ok() {\n\n return Err(format_err!(\"the server returned: \\\"{}\\\"\", response.error()));\n\n }\n\n\n\n // Now, deserialize *again* into the expected reponse.\n\n let response: T = serde_json::from_str(body.as_str())\n\n .with_context(|_| format!(\"failed to deserialize: \\\"{}\\\"\", body))?;\n\n Ok(response)\n\n}\n\n\n", "file_path": "src/liqui/mod.rs", "rank": 4, "score": 202144.2593684314 }, { "content": "fn deserialize_private_response<T>(response: &http::Response<String>) -> Result<T, Error>\n\nwhere T: DeserializeOwned {\n\n deserialize_public_response(response)\n\n}\n\n\n", "file_path": "src/binance/mod.rs", "rank": 5, "score": 202138.0335338206 }, { "content": "fn deserialize_public_response<T>(response: &http::Response<String>) -> Result<T, Error>\n\nwhere T: DeserializeOwned {\n\n let result = serde_json::from_str(response.body().as_str())?;\n\n Ok(result)\n\n}\n", "file_path": "src/binance/mod.rs", "rank": 6, "score": 202138.0335338206 }, { "content": "/// **Public**. Mostly contains product info (min/max price, precision, fees, etc.)\n\npub fn get_exchange_info<Client>(client: &mut Client, host: &str) -> Result<ExchangeInfo, Error>\n\nwhere Client: HttpClient {\n\n let http_request = http::Request::builder()\n\n .method(http::Method::GET)\n\n .uri(format!(\"{}/api/3/info\", host))\n\n .body(String::new())?;\n\n\n\n let http_response = client.send(&http_request)?;\n\n\n\n deserialize_public_response(&http_response)\n\n}\n\n\n", "file_path": "src/liqui/mod.rs", "rank": 7, "score": 179544.03443608482 }, { "content": "/// **Public**.\n\npub fn get_exchange_info<Client>(client: &mut Client, host: &str) -> Result<ExchangeInfo, Error>\n\nwhere Client: HttpClient {\n\n let http_request = http::request::Builder::new()\n\n .method(http::Method::GET)\n\n .uri(format!(\"{}/api/v1/exchangeInfo\", host))\n\n .body(String::new())?;\n\n\n\n let http_response = client.send(&http_request)?;\n\n\n\n deserialize_public_response(&http_response)\n\n}\n\n\n", "file_path": "src/binance/mod.rs", "rank": 8, "score": 179540.69159696583 }, { "content": "fn deserialize_response<D>(response: &HttpResponse) -> Result<D, Error> \n\nwhere D: DeserializeOwned {\n\n match response.body {\n\n Some(api::Payload::Text(ref body)) => {\n\n let response = serde_json::from_str(body)\n\n .map_err(|e| format_err!(\"{}\", e))\n\n .with_context(|_| format_err!(\"failed to deserialize \\\"{}\\\"\", body))?;\n\n Ok(response)\n\n }\n\n Some(api::Payload::Binary(ref body)) => {\n\n let response = serde_json::from_slice(body)\n\n .map_err(|e| format_err!(\"{}\", e))\n\n .with_context(|_| format_err!(\"failed to deserialize <binary>\"))?;\n\n Ok(response)\n\n }\n\n None => {\n\n Err(format_err!(\"the body is empty\"))?\n\n }\n\n }\n\n}\n", "file_path": "src/gemini/rest.rs", "rank": 9, "score": 165344.43019299864 }, { "content": "pub fn send_order(client: &reqwest::Client, env: Environment, user: &str, password: &str, order: &model::OrderForm) -> Result<model::Order> {\n\n client.post(&format!(\"{}/order\", base_url(env)))\n\n .basic_auth(user, Some(password))\n\n .form(order)\n\n .execute()\n\n}\n\n\n", "file_path": "src/hitbtc/rest.rs", "rank": 10, "score": 162195.71694953518 }, { "content": "pub fn get_orders(client: &reqwest::Client, env: Environment, user: &str, password: &str, product: Option<&str>) -> Result<Vec<model::Order>> {\n\n client.get(&format!(\"{}/order\", base_url(env)))\n\n .basic_auth(user, Some(password))\n\n .execute()\n\n}\n\n\n", "file_path": "src/hitbtc/rest.rs", "rank": 11, "score": 154076.6774509549 }, { "content": "pub fn get_balance(client: &reqwest::Client, env: Environment, user: &str, password: &str) -> Result<Vec<model::Balance>> {\n\n client.get(&format!(\"{}/account/balance\", base_url(env)))\n\n .basic_auth(user, Some(password))\n\n .execute()\n\n}\n", "file_path": "src/hitbtc/rest.rs", "rank": 12, "score": 145549.01899290396 }, { "content": "type Result<T> = ::std::result::Result<T, Error>;\n\n\n", "file_path": "src/hitbtc/rest.rs", "rank": 13, "score": 140258.734912982 }, { "content": "fn private_headers<S>(payload: &S, credential: &Credential) -> Result<Headers, Error>\n\nwhere S: Serialize {\n\n let payload = serde_json::to_string(payload)\n\n .map(|json| base64::encode(json.as_bytes()))?;\n\n \n\n let mut mac = Hmac::<Sha384>::new(credential.secret.as_bytes()).map_err(|e| format_err!(\"{:?}\", e))?;\n\n mac.input(payload.as_bytes());\n\n let signature = hex::encode(mac.result().code());\n\n\n\n let headers = vec![\n\n Header::new(\"X-GEMINI-APIKEY\", credential.key.clone()),\n\n Header::new(\"X-GEMINI-PAYLOAD\", payload),\n\n Header::new(\"X-GEMINI-SIGNATURE\", signature),\n\n ];\n\n Ok(headers)\n\n}\n", "file_path": "src/gemini/mod.rs", "rank": 14, "score": 127346.15630655651 }, { "content": "fn nonce() -> i64 {\n\n let now = chrono::Utc::now();\n\n now.timestamp() * 1000 + now.timestamp_subsec_millis() as i64\n\n}", "file_path": "src/gemini/unused.rs", "rank": 15, "score": 124066.60308888514 }, { "content": "fn private_headers<R>(request: &R, credential: &Credential) -> Result<api::Headers, Error>\n\nwhere R: api::RestResource {\n\n let query = {\n\n let query = request.query();\n\n if query.len() > 0 {\n\n let query: Vec<String> = request.query().into_iter().map(|(name, value)| format!(\"{}={}\", name, value)).collect();\n\n format!(\"?{}\", query.as_slice().join(\"&\"))\n\n } else {\n\n String::new()\n\n }\n\n };\n\n \n\n let body = String::from_utf8(request.body().unwrap())?;\n\n let timestamp = Utc::now().timestamp().to_string();\n\n let hmac_key = base64::decode(&credential.secret)?;\n\n let mut signature = Hmac::<sha2::Sha256>::new(&hmac_key).map_err(|e| format_err!(\"{:?}\", e))?;\n\n signature.input(format!(\"{}{}{}{}{}\", timestamp, request.method(), request.path(), query, body).as_bytes());\n\n let signature = base64::encode(&signature.result().code());\n\n\n\n let mut headers = api::Headers::with_capacity(6);\n\n headers.insert(\"Content-Type\".to_owned(), \"application/json\".to_owned());\n\n headers.insert(\"CB-ACCESS-KEY\".to_owned(), credential.key.clone());\n\n headers.insert(\"CB-ACCESS-SIGN\".to_owned(), signature);\n\n headers.insert(\"CB-ACCESS-TIMESTAMP\".to_owned(), timestamp);\n\n headers.insert(\"CB-ACCESS-PASSPHRASE\".to_owned(), credential.password.clone());\n\n Ok(headers)\n\n}", "file_path": "src/gdax/mod.rs", "rank": 16, "score": 122589.23760999506 }, { "content": "/// **Public**. Get the orderbook for a single product.\n\npub fn get_orderbook<Client>(\n\n client: &mut Client,\n\n host: &str,\n\n product: &CurrencyPair,\n\n) -> Result<Orderbook, Error>\n\nwhere\n\n Client: HttpClient,\n\n{\n\n let query = {\n\n let mut query = Query::with_capacity(2);\n\n query.append_param(\"symbol\", product.to_string());\n\n query.append_param(\"limit\", \"100\");\n\n query.to_string()\n\n };\n\n let http_request = http::request::Builder::new()\n\n .method(http::Method::GET)\n\n .uri(format!(\"{}/api/v1/depth?{}\", host, query))\n\n .body(String::new())?;\n\n\n\n let http_response = client.send(&http_request)?;\n\n\n\n deserialize_public_response(&http_response)\n\n}\n\n\n", "file_path": "src/binance/mod.rs", "rank": 17, "score": 110480.33434825299 }, { "content": "/// **Public**. Market depth.\n\npub fn get_orderbooks<Client>(\n\n client: &mut Client,\n\n host: &str,\n\n products: &[&CurrencyPair],\n\n) -> Result<HashMap<CurrencyPair, Orderbook>, Error>\n\nwhere\n\n Client: HttpClient,\n\n{\n\n let products: Vec<String> = products.iter().map(ToString::to_string).collect();\n\n let http_request = http::request::Builder::new()\n\n .method(http::Method::GET)\n\n .uri(format!(\"{}/api/3/depth/{}\", host, products.join(\"-\")))\n\n .body(String::new())?;\n\n\n\n let http_response = client.send(&http_request)?;\n\n\n\n deserialize_public_response(&http_response)\n\n}\n\n\n", "file_path": "src/liqui/mod.rs", "rank": 19, "score": 110476.63498070904 }, { "content": "/// **Private**. Cancel an order by its Liqui-issued order id.\n\npub fn cancel_order<Client>(\n\n client: &mut Client,\n\n host: &str,\n\n credential: &Credential,\n\n order_id: u64,\n\n) -> Result<OrderCancellation, Error>\n\nwhere\n\n Client: HttpClient,\n\n{\n\n let body = {\n\n let mut query = Query::with_capacity(3);\n\n query.append_param(\"method\", \"CancelOrder\");\n\n query.append_param(\"nonce\", credential.nonce.to_string());\n\n query.append_param(\"order_id\", order_id.to_string());\n\n query.to_string()\n\n };\n\n let mut http_request = http::request::Builder::new()\n\n .method(http::Method::POST)\n\n .uri(format!(\"{}/tapi\", host))\n\n .body(body)?;\n\n sign_private_request(credential, &mut http_request)?;\n\n\n\n let http_response = client.send(&http_request)?;\n\n\n\n deserialize_private_response(&http_response)\n\n}\n\n\n\n/// Response to a private, authenticated request.\n\n///\n\n/// As far as I can tell, `PrivateResponse` is ALWAYS returned from the server in all cases.\n", "file_path": "src/liqui/mod.rs", "rank": 20, "score": 110300.51277452821 }, { "content": "/// **Private**. Cancel an active order by Binance-issued order id.\n\npub fn cancel_order<Client>(\n\n client: &mut Client,\n\n host: &str,\n\n credential: &Credential,\n\n order_id: u64,\n\n product: &CurrencyPair,\n\n) -> Result<OrderCancellation, Error>\n\nwhere\n\n Client: HttpClient,\n\n{\n\n let query = {\n\n let mut query = Query::with_capacity(5);\n\n query.append_param(\"timestamp\", timestamp_now().to_string());\n\n query.append_param(\"symbol\", product.to_string());\n\n query.append_param(\"orderId\", order_id.to_string());\n\n let signature = private_signature(credential, query.to_string().as_str())?;\n\n query.append_param(\"signature\", signature);\n\n query.to_string()\n\n };\n\n let http_request = http::request::Builder::new()\n\n .method(http::Method::DELETE)\n\n .uri(format!(\"{}/api/v3/order?{}\", host, query))\n\n .header(X_MBX_APIKEY, credential.key.as_str())\n\n .body(String::new())?;\n\n\n\n let http_response = client.send(&http_request)?;\n\n\n\n deserialize_private_response(&http_response)\n\n}\n\n\n", "file_path": "src/binance/mod.rs", "rank": 21, "score": 110300.47289556153 }, { "content": "/// **Private**. Get a specific order by its Liqui-issued order id.\n\npub fn get_order<Client>(\n\n client: &mut Client,\n\n host: &str,\n\n credential: &Credential,\n\n order_id: u64,\n\n) -> Result<Order, Error>\n\nwhere\n\n Client: HttpClient,\n\n{\n\n let body = {\n\n let mut query = Query::with_capacity(3);\n\n query.append_param(\"method\", \"OrderInfo\");\n\n query.append_param(\"nonce\", credential.nonce.to_string());\n\n query.append_param(\"order_id\", order_id.to_string());\n\n query.to_string()\n\n };\n\n let mut http_request = http::request::Builder::new()\n\n .method(http::Method::POST)\n\n .uri(format!(\"{}/tapi\", host))\n\n .body(body)?;\n\n sign_private_request(credential, &mut http_request)?;\n\n\n\n let http_response = client.send(&http_request)?;\n\n\n\n deserialize_private_response(&http_response)\n\n}\n\n\n", "file_path": "src/liqui/mod.rs", "rank": 22, "score": 110300.47289556153 }, { "content": "pub fn get_book(client: &reqwest::Client, env: Environment, product: &str, limit: usize) -> Result<model::Book> {\n\n client.get(&format!(\"{}/public/orderbook/{}?limit={}\", base_url(env), product, limit))\n\n .execute()\n\n}\n\n\n", "file_path": "src/hitbtc/rest.rs", "rank": 23, "score": 109547.74955783627 }, { "content": "/// A trait for sending HTTP requests. Used by *all* REST API calls.\n\npub trait HttpClient {\n\n fn send(&mut self, request: &http::Request<String>) -> Result<http::Response<String>, Error>;\n\n}\n\n\n\nimpl HttpClient for reqwest::Client {\n\n fn send(&mut self, request: &http::Request<String>) -> Result<http::Response<String>, Error> {\n\n let method = request.method().as_str().parse()?;\n\n let mut headers = reqwest::header::Headers::new();\n\n for (key, value) in request.headers() {\n\n headers.set_raw(key.as_str().to_owned(), value.to_str()?);\n\n }\n\n\n\n let request = self.request(method, request.uri().to_string().as_str())\n\n .body(request.body().clone())\n\n .headers(headers)\n\n .build()?;\n\n\n\n let mut response = self.execute(request)?;\n\n\n\n // TODO: add headers\n\n http::response::Builder::new()\n\n .status(response.status().as_u16())\n\n .body(response.text()?)\n\n .map_err(|e| format_err!(\"{}\", e))\n\n }\n\n}\n", "file_path": "src/http.rs", "rank": 24, "score": 109300.2049636564 }, { "content": "/// **Private**. User's active buy/sell orders for a product.\n\npub fn get_active_orders<Client>(\n\n client: &mut Client,\n\n host: &str,\n\n credential: &Credential,\n\n product: &CurrencyPair,\n\n) -> Result<HashMap<u64, Order>, Error>\n\nwhere\n\n Client: HttpClient,\n\n{\n\n let body = {\n\n let mut query = Query::with_capacity(3);\n\n query.append_param(\"method\", \"ActiveOrders\");\n\n query.append_param(\"nonce\", credential.nonce.to_string());\n\n query.append_param(\"pair\", product.to_string());\n\n query.to_string()\n\n };\n\n let mut http_request = http::request::Builder::new()\n\n .method(http::Method::POST)\n\n .uri(format!(\"{}/tapi\", host))\n\n .body(body)?;\n\n sign_private_request(credential, &mut http_request)?;\n\n\n\n let http_response = client.send(&http_request)?;\n\n\n\n deserialize_private_response(&http_response)\n\n}\n\n\n", "file_path": "src/liqui/mod.rs", "rank": 25, "score": 107128.93688356753 }, { "content": "/// **Private**. Place a limit order -- the only order type Liqui supports.\n\npub fn place_limit_order<Client>(\n\n client: &mut Client,\n\n host: &str,\n\n credential: &Credential,\n\n product: &CurrencyPair,\n\n price: d128,\n\n quantity: d128,\n\n side: Side,\n\n) -> Result<OrderPlacement, Error>\n\nwhere\n\n Client: HttpClient,\n\n{\n\n let body = {\n\n let mut query = Query::with_capacity(6);\n\n query.append_param(\"nonce\", credential.nonce.to_string());\n\n query.append_param(\"method\", \"trade\");\n\n query.append_param(\"pair\", product.to_string());\n\n query.append_param(\"type\", side.to_string());\n\n query.append_param(\"rate\", price.to_string());\n\n query.append_param(\"amount\", quantity.to_string());\n", "file_path": "src/liqui/mod.rs", "rank": 26, "score": 107125.93458551972 }, { "content": "/// **Private**. Get all open orders for every product or all open orders for one product.\n\npub fn get_open_orders<Client>(\n\n client: &mut Client,\n\n host: &str,\n\n credential: &Credential,\n\n product: Option<CurrencyPair>,\n\n) -> Result<Vec<Order>, Error>\n\nwhere\n\n Client: HttpClient,\n\n{\n\n let query = {\n\n let mut query = Query::with_capacity(5);\n\n query.append_param(\"timestamp\", timestamp_now().to_string());\n\n if let Some(product) = product {\n\n query.append_param(\"symbol\", product.to_string());\n\n }\n\n let signature = private_signature(credential, query.to_string().as_str())?;\n\n query.append_param(\"signature\", signature);\n\n query.to_string()\n\n };\n\n let http_request = http::request::Builder::new()\n\n .method(http::Method::GET)\n\n .uri(format!(\"{}/api/v3/openOrders?{}\", host, query))\n\n .header(X_MBX_APIKEY, credential.key.as_str())\n\n .body(String::new())?;\n\n\n\n let http_response = client.send(&http_request)?;\n\n\n\n deserialize_private_response(&http_response)\n\n}\n\n\n", "file_path": "src/binance/mod.rs", "rank": 27, "score": 107122.36735790157 }, { "content": "/// **Private**. Place a limit order.\n\npub fn place_limit_order<Client>(\n\n client: &mut Client,\n\n host: &str,\n\n credential: &Credential,\n\n product: &CurrencyPair,\n\n price: d128,\n\n quantity: d128,\n\n time_in_force: TimeInForce,\n\n side: Side,\n\n) -> Result<Order, Error>\n\nwhere\n\n Client: HttpClient,\n\n{\n\n let query = {\n\n let mut query = Query::with_capacity(7);\n\n query.append_param(\"timestamp\", timestamp_now().to_string());\n\n query.append_param(\"symbol\", product.to_string());\n\n query.append_param(\"side\", side.to_string());\n\n query.append_param(\"type\", OrderInstruction::Limit.to_string());\n\n query.append_param(\"quantity\", quantity.to_string());\n", "file_path": "src/binance/mod.rs", "rank": 29, "score": 107122.04086792763 }, { "content": "fn base_url(environment: Environment) -> &'static str {\n\n match environment {\n\n Environment::Production => \"https://api.hitbtc.com/api/2\",\n\n }\n\n}\n\n\n", "file_path": "src/hitbtc/rest.rs", "rank": 30, "score": 101491.79179032601 }, { "content": "#[derive(Serialize, Deserialize, Debug)]\n\n#[serde(rename_all = \"camelCase\")]\n\nstruct Response<T, E> {\n\n /// This member is **REQUIRED**.\n\n /// It **MUST** be the same as the value of the id member in the `Request` object.\n\n /// If there was an error in detecting the id in the `Request` object (e.g. parse error/invalid \n\n /// request), it **MUST** be `NULL`.\n\n pub id: Option<i64>,\n\n /// **MUST** be exactly \"2.0\"\n\n pub jsonrpc: String,\n\n /// This member is **REQUIRED** on success.\n\n /// This member **MUST NOT** exist if there was an error invoking the method.\n\n pub result: Option<T>,\n\n /// This member is **REQUIRED** on error.\n\n /// This member **MUST NOT** exist if there was no error triggered during invocation.\n\n pub error: Option<Error<E>>,\n\n}\n\n\n\n#[derive(Serialize, Deserialize, Debug)]\n\n#[serde(rename_all = \"camelCase\")]\n\npub struct Error<T> {\n\n pub code: i64,\n\n pub message: String,\n\n pub data: Option<T>,\n\n}\n\n\n", "file_path": "src/hitbtc/ws.rs", "rank": 31, "score": 95943.53284586404 }, { "content": "pub fn order_stream(subscribers: Vec<mpsc::Sender<ccex::ExchangeEvent>>, environment: ccex::Environment, credential: &Credential) {\n\n use ccex::gemini::ws::{interface};\n\n use ccex::api::*;\n\n \n\n let request = interface::GetOrderStream::new(nonce()).authenticate(credential);\n\n let mut client = ccex::api::TungsteniteClient::connect(environment.into(), request).unwrap();\n\n while let Ok(message) = client.recv() {\n\n println!(\"{:?}\", message);\n\n }\n\n}\n\n\n", "file_path": "src/gemini/unused.rs", "rank": 32, "score": 94899.49734496717 }, { "content": "fn timestamp_now() -> u64 {\n\n let now = Utc::now();\n\n // now.timestamp() as u64 * 1000 + now.timestamp_subsec_millis() as u64\n\n now.timestamp() as u64 * 1000\n\n}\n\n\n", "file_path": "src/binance/mod.rs", "rank": 33, "score": 94484.00210520881 }, { "content": "pub fn production() -> Url {\n\n Url::parse(\"wss://ws-feed.gdax.com\").unwrap()\n\n}\n\n\n", "file_path": "src/gdax/ws.rs", "rank": 34, "score": 88334.32619526214 }, { "content": "pub fn sandbox() -> Url {\n\n Url::parse(\"wss://ws-feed-public.sandbox.gdax.com\").unwrap()\n\n}\n\n\n\n#[derive(Clone, Debug, Deserialize, Eq, Hash, PartialEq, Serialize, Copy)]\n\n#[serde(rename_all = \"lowercase\")]\n\npub enum ChannelName {\n\n Level2,\n\n Heartbeat,\n\n Ticker,\n\n Full,\n\n User,\n\n}\n\n\n\n#[derive(Clone, Debug, Deserialize, Eq, Hash, PartialEq, Serialize)]\n\npub struct Channel {\n\n pub name: ChannelName,\n\n #[serde(rename = \"product_ids\")] \n\n pub products: Vec<CurrencyPair>,\n\n}\n", "file_path": "src/gdax/ws.rs", "rank": 35, "score": 88334.32619526214 }, { "content": "/// **Public**. Current price/volume ticker.\n\npub fn get_ticker<Client>(\n\n client: &mut Client,\n\n host: &str,\n\n products: &[CurrencyPair],\n\n) -> Result<HashMap<CurrencyPair, Ticker>, Error>\n\nwhere\n\n Client: HttpClient,\n\n{\n\n let products: Vec<String> = products.iter().map(ToString::to_string).collect();\n\n let http_request = http::request::Builder::new()\n\n .method(http::Method::GET)\n\n .uri(format!(\"{}/api/3/ticker/{}\", host, products.join(\"-\")))\n\n .body(String::new())?;\n\n\n\n let http_response = client.send(&http_request)?;\n\n\n\n deserialize_public_response(&http_response)\n\n}\n\n\n", "file_path": "src/liqui/mod.rs", "rank": 36, "score": 86024.50412434962 }, { "content": "/// **Private**. User account information (balances, api priviliges, and more)\n\npub fn get_account_info<Client>(\n\n client: &mut Client,\n\n host: &str,\n\n credential: &Credential,\n\n) -> Result<AccountInfo, Error>\n\nwhere\n\n Client: HttpClient,\n\n{\n\n let query = {\n\n let mut query = Query::with_capacity(2);\n\n query.append_param(\"method\", \"getInfo\");\n\n query.append_param(\"nonce\", credential.nonce.to_string());\n\n query.to_string()\n\n };\n\n\n\n let mut http_request = http::request::Builder::new()\n\n .method(http::Method::POST)\n\n .uri(format!(\"{}/tapi\", host))\n\n .body(query)?;\n\n sign_private_request(credential, &mut http_request)?;\n\n\n\n let http_response = client.send(&http_request)?;\n\n deserialize_private_response(&http_response)\n\n}\n\n\n", "file_path": "src/liqui/mod.rs", "rank": 38, "score": 83922.30523791478 }, { "content": "/// **Private**. Get priviliges, commission rates, and balances for an account.\n\npub fn get_account_info<Client>(\n\n client: &mut Client,\n\n host: &str,\n\n credential: &Credential,\n\n) -> Result<Account, Error>\n\nwhere\n\n Client: HttpClient,\n\n{\n\n let query = {\n\n let mut query = Query::with_capacity(2);\n\n query.append_param(\"timestamp\", timestamp_now().to_string());\n\n let signature = private_signature(credential, query.to_string().as_str())?;\n\n query.append_param(\"signature\", signature);\n\n query.to_string()\n\n };\n\n let http_request = http::request::Builder::new()\n\n .method(http::Method::GET)\n\n .uri(format!(\"{}/api/v3/account?{}\", host, query))\n\n .header(X_MBX_APIKEY, credential.key.as_str())\n\n .body(String::new())?;\n\n\n\n let http_response = client.send(&http_request)?;\n\n\n\n deserialize_private_response(&http_response)\n\n}\n\n\n", "file_path": "src/binance/mod.rs", "rank": 39, "score": 83922.30523791478 }, { "content": "#[derive(Debug, Fail)]\n\nenum LiquiError {\n\n #[fail(display = \"({}) {}\", _0, _1)]\n\n InvalidOrder(u32, String),\n\n\n\n #[fail(display = \"({}) {}\", _0, _1)]\n\n InsufficientFunds(u32, String),\n\n\n\n #[fail(display = \"({}) {}\", _0, _1)]\n\n OrderNotFound(u32, String),\n\n\n\n #[fail(display = \"({:?}) {}\", _0, _1)]\n\n Unregistered(Option<u32>, String),\n\n}\n\n\n", "file_path": "src/liqui/mod.rs", "rank": 40, "score": 80585.98302635588 }, { "content": "#[derive(Debug, Clone, Serialize, Deserialize)]\n\nstruct ErrorMessage {\n\n pub message: String,\n\n}\n\n\n\n// #[derive(Fail, Debug, Clone, Serialize, Deserialize)]\n\n// #[fail(display = \"the server returned {}: {}\", code, message)]\n\n// pub struct GdaxError {\n\n// pub code: u16,\n\n// pub message: String,\n\n// }\n\n\n\n// #[derive(Debug, Fail)]\n\n// pub enum Error {\n\n// SerdeError(serde_json::Error),\n\n// #[fail(display = \"the server returned {}: {}\", code, message)]\n\n// BadRequest {\n\n// code: u16,\n\n// message: String,\n\n// }\n\n// }\n", "file_path": "src/gdax/rest.rs", "rank": 42, "score": 78903.59163413852 }, { "content": "#[derive(Serialize, Deserialize, Debug)]\n\n#[serde(rename_all = \"camelCase\")]\n\nstruct GetCurrencyParams {\n\n pub currency: String,\n\n}\n\n\n\nimpl RequestParams for GetSymbolParams {}\n", "file_path": "src/hitbtc/ws.rs", "rank": 43, "score": 76589.08986331896 }, { "content": "#[derive(Serialize, Deserialize, Debug)]\n\n#[serde(rename_all = \"camelCase\")]\n\nstruct SubscribeOrderbookParams {\n\n pub symbol: String,\n\n}\n\n\n\nimpl RequestParams for SubscribeTradesParams {}\n", "file_path": "src/hitbtc/ws.rs", "rank": 44, "score": 76568.10904193518 }, { "content": "#[derive(Debug, Serialize, Deserialize)]\n\nstruct OrderCancellationRequest {\n\n pub request: String,\n\n pub nonce: i64,\n\n pub order_id: Option<i64>,\n\n}\n\n\n\n\n\n\n\npub struct Gemini {\n\n pub credential: Credential,\n\n}\n\n\n\nimpl<Client> Exchange<Client> for Gemini \n\nwhere Client: HttpClient {\n\n fn name(&self) -> &'static str {\n\n \"Gemini\"\n\n }\n\n\n\n fn orderbook_cooldown(&self) -> Duration {\n\n Duration::from_millis(500)\n", "file_path": "src/gemini/rest.rs", "rank": 45, "score": 76376.99150447245 }, { "content": "fn market_stream(subscribers: Vec<mpsc::Sender<ccex::ExchangeEvent>>, environment: ccex::Environment, product: ccex::CurrencyPair) {\n\n use ccex::gemini::ws::{interface, model};\n\n\n\n let request = interface::GetMarketStream {\n\n product: product.into(),\n\n };\n\n\n\n let mut client = ccex::api::TungsteniteClient::connect(environment.into(), request).unwrap();\n\n\n\n while let Ok(message) = client.recv() {\n\n // TODO: this is ridiculous\n\n let ccex::gemini::ws::model::market::ExchangeEvents(events) = (message, product.into()).into();\n\n for event in events {\n\n for sub in &subscribers {\n\n sub.send(event.clone());\n\n }\n\n }\n\n }\n\n}\n\n\n", "file_path": "src/gemini/unused.rs", "rank": 46, "score": 70318.19264079268 }, { "content": "fn spawn_market_stream(subscribers: Vec<mpsc::Sender<ccex::ExchangeEvent>>, environment: ccex::Environment, product: ccex::CurrencyPair) -> JoinHandle<()> {\n\n thread::spawn(move || market_stream(subscribers, environment, product))\n\n}\n\n\n", "file_path": "src/gemini/unused.rs", "rank": 47, "score": 65541.91399940843 }, { "content": "fn spawn_order_stream(subscribers: Vec<mpsc::Sender<ccex::ExchangeEvent>>, environment: ccex::Environment, credential: &Credential) -> JoinHandle<()> {\n\n let credential = credential.clone();\n\n thread::spawn(move || order_stream(subscribers, environment, &credential))\n\n}\n\n\n", "file_path": "src/gemini/unused.rs", "rank": 48, "score": 64092.950606839244 }, { "content": "#[derive(Deserialize)]\n\nstruct PublicResponse {\n\n success: Option<i32>,\n\n error: Option<String>,\n\n}\n\n\n\nimpl PublicResponse {\n\n fn is_ok(&self) -> bool {\n\n // If `success` exists it means the response is an error. Also, if `success` exists, it's\n\n // always equal to `0`.\n\n match self.success {\n\n Some(success) => success == 1,\n\n None => true,\n\n }\n\n }\n\n\n\n fn error(&self) -> &str {\n\n match self.error {\n\n Some(ref error) => error.as_str(),\n\n None => \"\",\n\n }\n\n }\n\n}\n\n\n", "file_path": "src/liqui/mod.rs", "rank": 49, "score": 52220.51109295313 }, { "content": "#[derive(Serialize, Deserialize, Debug)]\n\n#[serde(rename_all = \"camelCase\")]\n\nstruct GetTradesParams {\n\n pub symbol: Option<String>,\n\n pub limit: Option<i64>,\n\n pub sort: Option<SortOrder>,\n\n pub by: Option<SortBy>,\n\n pub from: Option<String>,\n\n pub till: Option<String>,\n\n pub offset: Option<i64>,\n\n}\n\n\n\nimpl RequestParams for SubscribeCandlesParams {}\n", "file_path": "src/hitbtc/ws.rs", "rank": 50, "score": 50931.040943957385 }, { "content": "#[derive(Serialize, Deserialize, Debug)]\n\n#[serde(rename_all = \"camelCase\")]\n\nstruct SubscribeTickerParams {\n\n pub symbol: String,\n\n}\n\n\n\nimpl RequestParams for SubscribeOrderbookParams {}\n", "file_path": "src/hitbtc/ws.rs", "rank": 51, "score": 50931.040943957385 }, { "content": "#[derive(Serialize, Deserialize, Debug)]\n\n#[serde(rename_all = \"camelCase\")]\n\nstruct GetSymbolParams {\n\n pub symbol: String,\n\n}\n\n\n\nimpl RequestParams for SubscribeTickerParams {}\n", "file_path": "src/hitbtc/ws.rs", "rank": 52, "score": 50931.040943957385 }, { "content": "#[derive(Serialize, Deserialize, Debug)]\n\n#[serde(rename_all = \"camelCase\")]\n\nstruct SubscribeTradesParams {\n\n pub symbol: String,\n\n}\n\n\n\n#[derive(Serialize, Deserialize, Debug)]\n\npub enum SortOrder {\n\n #[serde(rename = \"DESC\")]\n\n Descending,\n\n #[serde(rename = \"ASC\")]\n\n Ascending,\n\n}\n\n\n\n#[derive(Serialize, Deserialize, Debug)]\n\npub enum SortBy {\n\n #[serde(rename = \"timestamp\")]\n\n Timestamp,\n\n #[serde(rename = \"id\")]\n\n Id,\n\n}\n\n\n\nimpl RequestParams for GetTradesParams {}\n", "file_path": "src/hitbtc/ws.rs", "rank": 53, "score": 50931.040943957385 }, { "content": "#[derive(Serialize, Deserialize, Debug)]\n\n#[serde(rename_all = \"camelCase\")]\n\nstruct SubscribeCandlesParams {\n\n pub symbol: String,\n\n pub period: String,\n\n}\n\n\n\nimpl ResponseResult for Currency {}\n\n#[derive(Serialize, Deserialize, Debug)]\n\n#[serde(rename_all = \"camelCase\")]\n\npub struct Currency {\n\n pub id: String,\n\n pub full_name: String,\n\n pub crypto: bool,\n\n pub payin_enabled: bool,\n\n pub payin_payment_id: bool,\n\n pub payin_confirmations: i64,\n\n pub payout_enabled: bool,\n\n pub payout_is_payment_id: bool,\n\n pub transfer_enabled: bool,\n\n}\n\n\n", "file_path": "src/hitbtc/ws.rs", "rank": 54, "score": 50931.040943957385 }, { "content": "#[derive(Serialize, Deserialize, Debug)]\n\n#[serde(rename_all = \"camelCase\")]\n\nstruct Request<T> {\n\n /// An identifier established by the Client that **MUST** contain a `String`, `Number`, or `NULL` value if included.\n\n /// If it is not included it is assumed to be a notification. The value **SHOULD** normally not be `NULL`.\n\n ///\n\n /// The Server **MUST** reply with the same value in the `Response` object if included. this \n\n /// member is used to correlate the context between the two objects.\n\n pub id: Option<i64>,\n\n /// **MUST** be exactly \"2.0\"\n\n pub jsonrpc: String,\n\n pub method: String,\n\n pub params: Option<T>,\n\n}\n\n\n", "file_path": "src/hitbtc/ws.rs", "rank": 55, "score": 50235.86519629638 }, { "content": "#[derive(Debug, Hash, PartialEq, PartialOrd, Eq, Ord, Clone, Deserialize, Serialize)]\n\nstruct PrivateResponse<T> {\n\n success: i32,\n\n #[serde(rename = \"return\")]\n\n ok: Option<T>,\n\n error: Option<String>,\n\n code: Option<u32>,\n\n}\n\n\n\nimpl<T> PrivateResponse<T> {\n\n pub fn is_ok(&self) -> bool {\n\n self.success == 1\n\n }\n\n\n\n pub fn into_result(self) -> Result<T, LiquiError> {\n\n if self.is_ok() {\n\n Ok(self.ok.unwrap())\n\n } else {\n\n let error = match self.code {\n\n Some(code @ 803) | Some(code @ 804) | Some(code @ 805) | Some(code @ 806)\n\n | Some(code @ 807) => LiquiError::InvalidOrder(code, self.error.unwrap()),\n", "file_path": "src/liqui/mod.rs", "rank": 56, "score": 48951.084056042455 }, { "content": "fn sign_private_request(\n\n credential: &Credential,\n\n request: &mut http::Request<String>,\n\n) -> Result<(), Error>\n\n{\n\n let mut mac =\n\n Hmac::<Sha512>::new(credential.secret.as_bytes()).map_err(|e| format_err!(\"{:?}\", e))?;\n\n mac.input(request.body().as_bytes());\n\n let signature = hex::encode(mac.result().code().to_vec());\n\n\n\n let headers = request.headers_mut();\n\n headers.insert(\"Key\", credential.key.parse().unwrap());\n\n headers.insert(\"Sign\", signature.parse().unwrap());\n\n\n\n Ok(())\n\n}\n", "file_path": "src/liqui/mod.rs", "rank": 58, "score": 45609.20787658839 }, { "content": "use failure::Error;\n\nuse http;\n\nuse reqwest;\n\n\n\n#[derive(Debug, Default, Clone)]\n\npub(crate) struct Query {\n\n pub params: Vec<(String, String)>,\n\n}\n\n\n\nimpl Query {\n\n pub fn with_capacity(capacity: usize) -> Self {\n\n Query {\n\n params: Vec::with_capacity(capacity),\n\n }\n\n }\n\n\n\n pub fn append_param<K, V>(&mut self, key: K, value: V)\n\n where\n\n K: Into<String>,\n\n V: Into<String>, {\n", "file_path": "src/http.rs", "rank": 59, "score": 31676.29561529983 }, { "content": " self.params.push((key.into(), value.into()));\n\n }\n\n\n\n pub fn to_string(&self) -> String {\n\n if self.params.is_empty() {\n\n String::new()\n\n } else {\n\n self.params\n\n .iter()\n\n .map(|&(ref name, ref value)| [name.as_str(), \"=\", value.as_str()])\n\n .collect::<Vec<[&str; 3]>>()\n\n .join(&\"&\")\n\n .into_iter()\n\n .collect()\n\n }\n\n }\n\n}\n\n\n\n/// A trait for sending HTTP requests. Used by *all* REST API calls.\n", "file_path": "src/http.rs", "rank": 60, "score": 31669.099658366646 }, { "content": "trait ResponseResult {}\n", "file_path": "src/hitbtc/ws.rs", "rank": 61, "score": 26631.453141549842 }, { "content": "pub const API_HOST: &str = \"https://api.liqui.io\";\n\n\n\n/// Credentials needed for private API requests.\n\n#[derive(Debug, Hash, PartialEq, PartialOrd, Eq, Ord, Clone, Deserialize, Serialize)]\n\npub struct Credential {\n\n pub secret: String,\n\n pub key: String,\n\n pub nonce: u64,\n\n}\n\n\n\n/// `Buy` or `Sell`\n\n#[derive(Debug, Hash, PartialEq, PartialOrd, Eq, Ord, Clone, Copy, Deserialize, Serialize)]\n\n#[serde(rename_all = \"lowercase\")]\n\npub enum Side {\n\n Buy,\n\n Sell,\n\n}\n\n\n\nimpl Display for Side {\n\n fn fmt(&self, f: &mut Formatter) -> Result<(), fmt::Error> {\n", "file_path": "src/liqui/mod.rs", "rank": 63, "score": 56.451027335124124 }, { "content": " struct CurrencyPairVisitor;\n\n impl<'de> Visitor<'de> for CurrencyPairVisitor {\n\n type Value = CurrencyPair;\n\n\n\n fn expecting(&self, f: &mut fmt::Formatter) -> fmt::Result {\n\n f.write_str(\"a string containing two currencies separated by an underscore\")\n\n }\n\n\n\n fn visit_str<E>(self, pair: &str) -> Result<Self::Value, E>\n\n where E: de::Error {\n\n let currencies: Vec<&str> = pair.split('_').collect();\n\n if currencies.len() < 2 {\n\n return Err(E::invalid_value(serde::de::Unexpected::Str(pair), &self));\n\n }\n\n let base = Currency::from_str(currencies[0]).map_err(serde::de::Error::custom)?;\n\n let quote = Currency::from_str(currencies[1]).map_err(serde::de::Error::custom)?;\n\n Ok(CurrencyPair(base, quote))\n\n }\n\n }\n\n deserializer.deserialize_str(CurrencyPairVisitor)\n", "file_path": "src/liqui/mod.rs", "rank": 65, "score": 53.1110892999254 }, { "content": " match *self {\n\n Side::Buy => writeln!(f, \"buy\"),\n\n Side::Sell => writeln!(f, \"sell\"),\n\n }\n\n }\n\n}\n\n\n\n/// Single currency. `ETH`, `BTC`, `USDT`, etc.\n\n///\n\n/// Use `Currency::from_str` to create a new `Currency`.\n\n///\n\n/// ```rust\n\n/// let ether: Currency = \"ETH\".parse()?;\n\n/// ```\n\n#[derive(Debug, Hash, PartialEq, PartialOrd, Eq, Ord, Clone, Deserialize, Serialize)]\n\npub struct Currency(String);\n\n\n\nimpl FromStr for Currency {\n\n type Err = Error;\n\n fn from_str(s: &str) -> Result<Self, Self::Err> {\n", "file_path": "src/liqui/mod.rs", "rank": 66, "score": 49.09877143204871 }, { "content": "\n\nimpl FromStr for Currency {\n\n type Err = Error;\n\n fn from_str(s: &str) -> Result<Self, Self::Err> {\n\n Ok(Currency(s.to_uppercase()))\n\n }\n\n}\n\n\n\nimpl Display for Currency {\n\n fn fmt(&self, f: &mut Formatter) -> Result<(), fmt::Error> {\n\n let &Currency(ref currency) = self;\n\n f.write_str(currency.as_str())\n\n }\n\n}\n\n\n\n/// Usually represents a product. `ETH_BTC`, `BTC_USDT`, etc.\n\n#[derive(Debug, Serialize, Deserialize, PartialEq, Eq, PartialOrd, Ord, Hash, Clone)]\n\npub struct CurrencyPair(pub Currency, pub Currency);\n\n\n\nimpl CurrencyPair {\n", "file_path": "src/binance/mod.rs", "rank": 67, "score": 47.668144502136265 }, { "content": "\n\nimpl Display for Side {\n\n fn fmt(&self, f: &mut Formatter) -> Result<(), fmt::Error> {\n\n match *self {\n\n Side::Buy => f.write_str(\"BUY\"),\n\n Side::Sell => f.write_str(\"SELL\"),\n\n }\n\n }\n\n}\n\n\n\n#[derive(Debug, Serialize, Deserialize, PartialEq, Eq, PartialOrd, Ord, Hash, Clone, Copy)]\n\npub enum TimeInForce {\n\n #[serde(rename = \"IOC\")]\n\n ImmediateOrCancel,\n\n #[serde(rename = \"GTC\")]\n\n GoodTillCancelled,\n\n #[serde(rename = \"FOK\")]\n\n FillOrKill,\n\n}\n\n\n", "file_path": "src/binance/mod.rs", "rank": 70, "score": 46.296348545253124 }, { "content": "#[derive(Debug, Serialize, Deserialize, PartialEq, Eq, PartialOrd, Ord, Hash, Clone)]\n\npub struct Order {}\n\n\n\n/// Result of a `cancel_order` request.\n\n#[derive(Debug, Serialize, Deserialize, PartialEq, Eq, PartialOrd, Ord, Hash, Clone)]\n\n#[serde(rename_all = \"camelCase\")]\n\npub struct OrderCancellation {\n\n pub symbol: String,\n\n pub orig_client_order_id: String,\n\n pub order_id: u64,\n\n pub client_order_id: String,\n\n}\n\n\n\n/// `Buy` or `Sell`\n\n#[derive(Debug, Serialize, Deserialize, PartialEq, Eq, PartialOrd, Ord, Hash, Clone, Copy)]\n\n#[serde(rename_all = \"UPPERCASE\")]\n\npub enum Side {\n\n Buy,\n\n Sell,\n\n}\n", "file_path": "src/binance/mod.rs", "rank": 72, "score": 43.285877790908096 }, { "content": " MakerOrCancel,\n\n }\n\n\n\n #[derive(Clone, Debug, Deserialize, Eq, Hash, PartialEq, Serialize, Copy)]\n\n #[serde(rename_all = \"lowercase\")]\n\n pub enum Side {\n\n Buy,\n\n Sell,\n\n }\n\n\n\n impl From<Side> for ccex::Side {\n\n fn from(side: Side) -> Self {\n\n match side {\n\n Side::Buy => ccex::Side::Bid,\n\n Side::Sell => ccex::Side::Ask,\n\n }\n\n }\n\n }\n\n\n\n #[derive(Clone, Debug, Deserialize, Hash, PartialEq, Serialize)]\n", "file_path": "src/gemini/ws.rs", "rank": 73, "score": 42.987120692687114 }, { "content": "//! [Binance.com](https://binance.com) API.\n\nuse {HttpClient, Query};\n\nuse chrono::Utc;\n\nuse failure::Error;\n\nuse hex;\n\nuse serde_json;\n\nuse hmac::{Hmac, Mac};\n\nuse rust_decimal::Decimal as d128;\n\nuse serde::de::DeserializeOwned;\n\nuse sha2::Sha256;\n\nuse std::fmt::{self, Display, Formatter};\n\nuse http;\n\nuse std::str::FromStr;\n\n\n\n/// Use this as the `host` for REST requests.\n\npub const API_HOST: &str = \"https://api.binance.com\";\n\n\n\n/// API key and secret. Required for private API calls.\n\n#[derive(Debug, Serialize, Deserialize, PartialEq, Eq, PartialOrd, Ord, Hash, Clone)]\n\npub struct Credential {\n", "file_path": "src/binance/mod.rs", "rank": 74, "score": 41.73292359229623 }, { "content": " base\n\n }\n\n\n\n /// Convenience method for accessing the quote currency when `CurrencyPair` represents a\n\n /// product.\n\n pub fn quote(&self) -> &Currency {\n\n let &CurrencyPair(_, ref quote) = self;\n\n quote\n\n }\n\n}\n\n\n\nimpl Display for CurrencyPair {\n\n fn fmt(&self, f: &mut Formatter) -> Result<(), fmt::Error> {\n\n write!(f, \"{}_{}\", self.base(), self.quote())\n\n }\n\n}\n\n\n\nimpl<'de> Deserialize<'de> for CurrencyPair {\n\n fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>\n\n where D: Deserializer<'de> {\n", "file_path": "src/liqui/mod.rs", "rank": 76, "score": 41.4951359230044 }, { "content": " use std::fmt;\n\n use std::fmt::Display;\n\n\n\n #[derive(Clone, Debug, Deserialize, Eq, Hash, PartialEq, Serialize, Copy)]\n\n #[serde(rename_all = \"lowercase\")]\n\n pub enum CurrencyPair {\n\n BTCUSD,\n\n ETHUSD,\n\n ETHBTC,\n\n }\n\n\n\n impl Display for CurrencyPair {\n\n fn fmt(&self, f: &mut fmt::Formatter) -> Result<(), fmt::Error> {\n\n match self {\n\n &CurrencyPair::BTCUSD => write!(f, \"btcusd\"),\n\n &CurrencyPair::ETHUSD => write!(f, \"ethusd\"),\n\n &CurrencyPair::ETHBTC => write!(f, \"ethbtc\"),\n\n }\n\n }\n\n }\n", "file_path": "src/gemini/ws.rs", "rank": 77, "score": 41.34753812010284 }, { "content": " }\n\n\n\n pub mod market {\n\n use super::*;\n\n use crate as ccex;\n\n use decimal::d128;\n\n\n\n #[derive(Clone, Debug, Deserialize, Eq, Hash, PartialEq, Serialize, Copy)]\n\n #[serde(rename_all = \"lowercase\")]\n\n pub enum Side {\n\n Bid,\n\n Ask,\n\n Auction,\n\n }\n\n\n\n impl From<Side> for ccex::Side {\n\n fn from(side: Side) -> Self {\n\n match side {\n\n Side::Bid => ccex::Side::Bid,\n\n Side::Ask => ccex::Side::Ask,\n", "file_path": "src/gemini/ws.rs", "rank": 78, "score": 40.883968817477935 }, { "content": " Ok(Currency(s.to_lowercase()))\n\n }\n\n}\n\n\n\nimpl Display for Currency {\n\n fn fmt(&self, f: &mut Formatter) -> Result<(), fmt::Error> {\n\n let &Currency(ref currency) = self;\n\n f.write_str(currency)\n\n }\n\n}\n\n\n\n/// Usually represents a product. `ETH_BTC`, `BTC_USDT`, etc.\n\n#[derive(Debug, Hash, PartialEq, PartialOrd, Eq, Ord, Clone, Serialize)]\n\npub struct CurrencyPair(pub Currency, pub Currency);\n\n\n\nimpl CurrencyPair {\n\n /// Convenience method for accessing the base currency when `CurrencyPair` represents a\n\n /// product.\n\n pub fn base(&self) -> &Currency {\n\n let &CurrencyPair(ref base, _) = self;\n", "file_path": "src/liqui/mod.rs", "rank": 80, "score": 39.70709962484841 }, { "content": "impl Display for TimeInForce {\n\n fn fmt(&self, f: &mut Formatter) -> Result<(), fmt::Error> {\n\n use self::TimeInForce::*;\n\n match *self {\n\n ImmediateOrCancel => f.write_str(\"IOC\"),\n\n GoodTillCancelled => f.write_str(\"GTC\"),\n\n FillOrKill => f.write_str(\"FOK\"),\n\n }\n\n }\n\n}\n\n\n\n/// A single currency. `ETH`, `BTC`, `USDT`, etc.\n\n///\n\n/// Use `Currency::from_str` to create a new `Currency`.\n\n///\n\n/// ```rust\n\n/// let bitcoin: Currency = \"BTC\".parse()?;\n\n/// ```\n\n#[derive(Debug, Serialize, Deserialize, PartialEq, Eq, PartialOrd, Ord, Hash, Clone)]\n\npub struct Currency(String);\n", "file_path": "src/binance/mod.rs", "rank": 82, "score": 38.39074415184992 }, { "content": "}\n\n\n\n/// Order type. `Limit`, `Market`, etc.\n\n#[derive(Debug, Serialize, Deserialize, PartialEq, Eq, PartialOrd, Ord, Hash, Clone, Copy)]\n\n#[serde(rename_all = \"SCREAMING_SNAKE_CASE\")]\n\npub enum OrderInstruction {\n\n Limit,\n\n LimitMaker,\n\n Market,\n\n StopLossLimit,\n\n TakeProfitLimit,\n\n}\n\n\n\nimpl Display for OrderInstruction {\n\n fn fmt(&self, f: &mut Formatter) -> Result<(), fmt::Error> {\n\n use self::OrderInstruction::*;\n\n match *self {\n\n Limit => f.write_str(\"LIMIT\"),\n\n LimitMaker => f.write_str(\"LIMIT_MAKER\"),\n\n Market => f.write_str(\"MARKET\"),\n", "file_path": "src/binance/mod.rs", "rank": 83, "score": 38.152586785487095 }, { "content": "/// Status of an order.\n\n#[derive(Debug, Hash, PartialEq, PartialOrd, Eq, Ord, Clone, Copy, Deserialize, Serialize)]\n\npub enum OrderStatus {\n\n Active = 0,\n\n Executed = 1,\n\n Cancelled = 2,\n\n CancelledPartiallyExecuted = 3,\n\n}\n\n\n\n/// Limit order (the only type of order Liqui supports).\n\n#[derive(Debug, PartialEq, PartialOrd, Clone, Deserialize, Serialize)]\n\npub struct Order {\n\n pub status: OrderStatus,\n\n pub pair: CurrencyPair,\n\n #[serde(rename = \"type\")]\n\n pub side: Side,\n\n pub amount: d128,\n\n pub rate: d128,\n\n pub timestamp_created: u64,\n\n}\n\n\n\n/// **Public**. Mostly contains product info (min/max price, precision, fees, etc.)\n", "file_path": "src/liqui/mod.rs", "rank": 84, "score": 38.00860776936776 }, { "content": "\n\n#[derive(Clone, Debug, Deserialize, Eq, Hash, PartialEq, Serialize)]\n\npub struct Error {\n\n pub message: String,\n\n}\n\n\n\n#[derive(Clone, Debug, Deserialize, Eq, Hash, PartialEq, Serialize)]\n\npub struct Subscribe {\n\n #[serde(rename = \"product_ids\")] \n\n pub products: Vec<CurrencyPair>,\n\n pub channels: Vec<Channel>,\n\n pub key: String,\n\n pub timestamp: String,\n\n pub signature: String,\n\n pub passphrase: String,\n\n}\n\n\n\nimpl Subscribe {\n\n pub fn new(products: &[CurrencyPair], channels: &[Channel], credential: &Credential) -> Self {\n\n let timestamp = Utc::now().timestamp().to_string();\n", "file_path": "src/gdax/ws.rs", "rank": 85, "score": 37.84639926320585 }, { "content": "}\n\n\n\n#[derive(Clone, Copy, Debug, Deserialize, Serialize)]\n\n#[serde(rename_all=\"lowercase\")]\n\npub enum Side {\n\n Buy,\n\n Sell,\n\n}\n\n\n\nimpl From<Side> for ccex::Side {\n\n fn from(side: Side) -> Self {\n\n match side {\n\n Side::Buy => ccex::Side::Bid,\n\n Side::Sell => ccex::Side::Ask,\n\n }\n\n }\n\n}\n\n\n\nimpl From<ccex::Side> for Side {\n\n fn from(side: ccex::Side) -> Self {\n", "file_path": "src/gemini/rest.rs", "rank": 86, "score": 37.43563859501928 }, { "content": " /// This is `base` and `quote` concatenated. This can't be processed into an actual\n\n /// `CurrencyPair` since there's no seperator.\n\n pub symbol: String,\n\n pub status: SymbolStatus,\n\n #[serde(rename = \"baseAsset\")]\n\n pub base: Currency,\n\n #[serde(rename = \"baseAssetPrecision\")]\n\n pub base_precision: u32,\n\n #[serde(rename = \"quoteAsset\")]\n\n pub quote: Currency,\n\n pub quote_precision: u32,\n\n pub order_types: Vec<OrderInstruction>,\n\n pub iceberg_allowed: bool,\n\n pub filters: Vec<Filter>,\n\n}\n\n\n\n#[derive(Debug, Serialize, Deserialize, PartialEq, Eq, PartialOrd, Ord, Hash, Clone, Copy)]\n\n#[serde(rename_all = \"UPPERCASE\")]\n\npub enum SymbolStatus {\n\n Trading,\n", "file_path": "src/binance/mod.rs", "rank": 87, "score": 36.25813691917656 }, { "content": " pub sequence: i64,\n\n pub time: DateTime<Utc>,\n\n #[serde(rename = \"product_id\")] \n\n pub product: CurrencyPair,\n\n pub price: d128,\n\n #[serde(rename = \"side\")] \n\n pub taker_side: Side,\n\n pub last_size: d128,\n\n pub best_bid: d128,\n\n pub best_ask: d128,\n\n}\n\n\n\n#[derive(Clone, Debug, Deserialize, Hash, PartialEq, Serialize)]\n\npub struct Snapshot {\n\n #[serde(rename = \"product_id\")] \n\n pub product: CurrencyPair,\n\n pub bids: Vec<(d128, d128)>,\n\n pub asks: Vec<(d128, d128)>,\n\n}\n\n\n", "file_path": "src/gdax/ws.rs", "rank": 88, "score": 34.96483417848229 }, { "content": "pub mod ws;\n\npub mod rest;\n\n\n\nuse chrono::{Utc};\n\nuse api;\n\nuse sha2;\n\nuse base64;\n\nuse hmac::{Hmac, Mac};\n\nuse std::io::Read;\n\nuse crate as ccex;\n\nuse failure::Error;\n\n\n\n#[derive(Debug, Clone)]\n\npub struct Credential {\n\n pub key: String,\n\n pub secret: String,\n\n pub password: String,\n\n}\n\n\n\n#[derive(Clone, Debug, Deserialize, Eq, Hash, PartialEq, Serialize, Copy)]\n", "file_path": "src/gdax/mod.rs", "rank": 89, "score": 34.60747112933828 }, { "content": " /// Convenience method for accessing the base currency when `CurrencyPair` represents a\n\n /// product.\n\n pub fn base(&self) -> &Currency {\n\n let &CurrencyPair(ref base, _) = self;\n\n base\n\n }\n\n\n\n /// Convenience method for accessing the quote currency when `CurrencyPair` represents a\n\n /// product.\n\n pub fn quote(&self) -> &Currency {\n\n let &CurrencyPair(_, ref quote) = self;\n\n quote\n\n }\n\n}\n\n\n\nimpl Display for CurrencyPair {\n\n fn fmt(&self, f: &mut Formatter) -> Result<(), fmt::Error> {\n\n write!(f, \"{}{}\", self.base(), self.quote())\n\n }\n\n}\n\n\n\n/// **Private**. Get priviliges, commission rates, and balances for an account.\n", "file_path": "src/binance/mod.rs", "rank": 90, "score": 34.40574154316717 }, { "content": "//! [Liqui.io](https://liqui.io/) API.\n\n//!\n\n//! [Liqui's API documentation](https://liqui.io/api)\n\n//!\n\n//! Naming between `ccex::liqui` and Liqui is not 1:1.\n\nuse {HttpClient, Query};\n\nuse failure::{Error, ResultExt};\n\nuse hex;\n\nuse hmac::{Hmac, Mac};\n\nuse rust_decimal::Decimal as d128;\n\nuse serde::de::{self, Deserialize, DeserializeOwned, Deserializer, Visitor};\n\nuse serde;\n\nuse serde_json;\n\nuse sha2::Sha512;\n\nuse std::collections::HashMap;\n\nuse std::fmt::{self, Display, Formatter};\n\nuse http;\n\nuse std::str::FromStr;\n\n\n\n/// Use this as the `host` for REST requests.\n", "file_path": "src/liqui/mod.rs", "rank": 91, "score": 33.37926824083742 }, { "content": "\n\n// fn headers(&self) -> Headers {\n\n// let (ref key, ref secret) = self.credential;\n\n// gemini::private_headers2(&self.request, key, secret)\n\n// }\n\n\n\n// fn body(&self) -> Self::Body {\n\n// io::empty()\n\n// }\n\n\n\n// fn parse<R>(&self, response: &mut R) -> Result<Self::Response, Error> where R: HttpResponse {\n\n// serde_json::from_reader(response.body())\n\n// }\n\n// }\n\n\n\n// impl api::Request for AuthenticatedPrivateRequest<CancelOrder, (String, String)> {\n\n// type Error: serde_json::Error;\n\n// type Response: model::OrderStatus;\n\n\n\n// pub fn headers()\n", "file_path": "src/gemini/rest.rs", "rank": 92, "score": 33.242981375472766 }, { "content": " trade_id: Option<i64>,\n\n taker_user_id: Option<String>,\n\n user_id: Option<String>,\n\n taker_profile_id: Option<String>,\n\n profile_id: Option<String>,\n\n}\n\n\n\n#[derive(Clone, Debug, Deserialize, Eq, Hash, PartialEq, Serialize, Copy)]\n\n#[serde(rename_all=\"lowercase\")]\n\npub enum OrderType {\n\n Limit,\n\n Market,\n\n}\n\n\n\n#[derive(Clone, Debug, Deserialize, Eq, Hash, PartialEq, Serialize, Copy)]\n\n#[serde(rename_all=\"lowercase\")]\n\npub enum OrderReason {\n\n Filled,\n\n Canceled,\n\n}\n", "file_path": "src/gdax/ws.rs", "rank": 93, "score": 32.719153602820406 }, { "content": " pub secret: String,\n\n pub key: String,\n\n}\n\n\n\n/// General exchange info; rate limits, products, filters, etc.\n\n#[derive(Debug, Serialize, Deserialize, PartialEq, Eq, PartialOrd, Ord, Hash, Clone)]\n\n#[serde(rename_all = \"camelCase\")]\n\npub struct ExchangeInfo {\n\n pub timezone: String,\n\n pub server_time: u64,\n\n pub rate_limits: Vec<RateLimit>,\n\n pub exchange_filters: Vec<Filter>,\n\n #[serde(rename = \"symbols\")]\n\n pub products: Vec<ProductInfo>,\n\n}\n\n\n\n/// Symbol info; base, quote, precision, status, etc.\n\n#[derive(Debug, Serialize, Deserialize, PartialEq, Eq, PartialOrd, Ord, Hash, Clone)]\n\n#[serde(rename_all = \"camelCase\")]\n\npub struct ProductInfo {\n", "file_path": "src/binance/mod.rs", "rank": 94, "score": 32.66810178939876 }, { "content": "pub struct Orderbook {\n\n pub ask: Vec<BidAsk>,\n\n pub bid: Vec<BidAsk>,\n\n pub symbol: String,\n\n pub sequence: i64,\n\n}\n\n\n\n#[derive(Serialize, Deserialize, Debug)]\n\n#[serde(rename_all = \"camelCase\")]\n\npub struct Trade {\n\n pub id: i64,\n\n pub price: String,\n\n pub quantity: String,\n\n pub side: String,\n\n pub timestamp: String,\n\n}\n\n\n\nimpl NotificationParams for Trades {}\n\n#[derive(Serialize, Deserialize, Debug)]\n\n#[serde(rename_all = \"camelCase\")]\n", "file_path": "src/hitbtc/ws.rs", "rank": 95, "score": 32.22326970973602 }, { "content": "\n\n fn headers(&self) -> Result<Headers, Error> {\n\n #[derive(Serialize)]\n\n struct Payload {\n\n request: &'static str,\n\n nonce: i64,\n\n }\n\n\n\n let payload = Payload {\n\n request: \"/v1/balances\",\n\n nonce: self.request.nonce,\n\n };\n\n\n\n private_headers(&payload, &self.credential)\n\n }\n\n\n\n fn deserialize(&self, response: &HttpResponse) -> Result<Self::Response, Error> {\n\n deserialize_response(response)\n\n }\n\n}\n\n\n", "file_path": "src/gemini/rest.rs", "rank": 96, "score": 31.91849590174182 }, { "content": " Ok(private_headers(self, &self.credential)?)\n\n }\n\n\n\n fn deserialize(&self, response: &HttpResponse) -> Result<Self::Response, Error> {\n\n if response.status == 200 {\n\n Ok(serde_json::from_slice(&response.body)?)\n\n } else {\n\n let error: ErrorMessage = serde_json::from_slice(&response.body)?;\n\n Err(format_err!(\"the server returned {}: {}\", response.status, error.message))\n\n }\n\n }\n\n}\n\n\n\n#[derive(Default, Debug, Clone, Serialize, Deserialize)]\n\npub struct GetOrders;\n\nimpl<'a> api::NeedsAuthentication<&'a Credential> for GetOrders {}\n\nimpl<'a> api::RestResource for api::PrivateRequest<GetOrders, &'a Credential> {\n\n type Response = Vec<Order>;\n\n // type Error = Error;\n\n\n", "file_path": "src/gdax/rest.rs", "rank": 97, "score": 31.227312055930966 }, { "content": " pub bids: Vec<(d128, d128)>,\n\n pub asks: Vec<(d128, d128)>,\n\n}\n\n\n\n/// An account's funds, privileges, and number of open orders.\n\n#[derive(Debug, PartialEq, Clone, Deserialize, Serialize)]\n\npub struct AccountInfo {\n\n /// Your account balance available for trading. Doesn’t include funds on\n\n /// your open orders.\n\n pub funds: HashMap<Currency, d128>,\n\n\n\n /// The privileges of the current API key.\n\n pub rights: Rights,\n\n\n\n /// The number of open orders on this account.\n\n #[serde(rename = \"open_orders\")]\n\n pub num_open_orders: u32,\n\n\n\n /// Server time (UTC).\n\n pub server_time: i64,\n", "file_path": "src/liqui/mod.rs", "rank": 98, "score": 31.14563441133148 }, { "content": "\n\n /// Available for trading.\n\n pub free: d128,\n\n\n\n /// Locked (not sure when this would happen)\n\n pub locked: d128,\n\n}\n\n\n\n/// Market depth.\n\n#[derive(Debug, Serialize, Deserialize, PartialEq, Eq, PartialOrd, Ord, Hash, Clone)]\n\n#[serde(rename_all = \"camelCase\")]\n\npub struct Orderbook {\n\n pub last_update_id: u64,\n\n /// Vector of `(price, quantity, /*ignore this*/)`\n\n pub asks: Vec<(d128, d128, [(); 0])>,\n\n\n\n /// Vector of `(price, quantity, /*ignore this*/)`\n\n pub bids: Vec<(d128, d128, [(); 0])>,\n\n}\n\n\n", "file_path": "src/binance/mod.rs", "rank": 99, "score": 30.94379287561992 } ]
Rust
src/utils.rs
ripe-tech/pconvert-rust
cf9ffcfc59d5838cf4d74a2c6c666e3f94f7cdc3
use crate::blending::demultiply_image; use crate::errors::PConvertError; use image::codecs::png::{CompressionType, FilterType, PngDecoder, PngEncoder}; use image::ImageDecoder; use image::{ColorType, ImageBuffer, Rgba}; use std::fs::File; use std::io::{BufWriter, Read, Write}; pub fn decode_png( readable_stream: impl Read, demultiply: bool, ) -> Result<ImageBuffer<Rgba<u8>, Vec<u8>>, PConvertError> { let decoder = PngDecoder::new(readable_stream)?; let (width, height) = decoder.dimensions(); let mut reader = decoder.into_reader()?; let mut bytes = Vec::<u8>::new(); reader.read_to_end(&mut bytes)?; let mut img = ImageBuffer::from_vec(width, height, bytes).unwrap(); if demultiply { demultiply_image(&mut img) } Ok(img) } pub fn read_png_from_file( file_in: String, demultiply: bool, ) -> Result<ImageBuffer<Rgba<u8>, Vec<u8>>, PConvertError> { let file = File::open(file_in)?; decode_png(file, demultiply) } pub fn encode_png( writable_buff: impl Write, png: &ImageBuffer<Rgba<u8>, Vec<u8>>, compression: CompressionType, filter: FilterType, ) -> Result<(), PConvertError> { let buff = BufWriter::new(writable_buff); let encoder = PngEncoder::new_with_quality(buff, compression, filter); Ok(encoder.encode(&png, png.width(), png.height(), ColorType::Rgba8)?) } pub fn write_png_to_file( file_out: String, png: &ImageBuffer<Rgba<u8>, Vec<u8>>, compression: CompressionType, filter: FilterType, ) -> Result<(), PConvertError> { let file = File::create(&file_out)?; encode_png(file, png, compression, filter) } pub fn write_png_to_file_d( file_out: String, png: &ImageBuffer<Rgba<u8>, Vec<u8>>, ) -> Result<(), PConvertError> { let file = File::create(&file_out)?; encode_png(file, png, CompressionType::Fast, FilterType::NoFilter) } #[cfg(not(feature = "wasm-extension"))] pub fn write_png_parallel( file_out: String, png: &ImageBuffer<Rgba<u8>, Vec<u8>>, compression: CompressionType, filter: FilterType, ) -> Result<(), PConvertError> { let writer = File::create(file_out)?; let mut header = mtpng::Header::new(); header.set_size(png.width(), png.height())?; header.set_color(mtpng::ColorType::TruecolorAlpha, 8)?; let mut options = mtpng::encoder::Options::new(); options.set_compression_level(mtpng_compression_from(compression))?; options.set_filter_mode(mtpng::Mode::Fixed(mtpng_filter_from(filter)))?; let mut encoder = mtpng::encoder::Encoder::new(writer, &options); encoder.write_header(&header)?; encoder.write_image_rows(&png)?; encoder.finish()?; Ok(()) } #[cfg(feature = "wasm-extension")] pub fn write_png_parallel( file_out: String, png: &ImageBuffer<Rgba<u8>, Vec<u8>>, compression: CompressionType, filter: FilterType, ) -> Result<(), PConvertError> { write_png_to_file(file_out, png, compression, filter) } pub fn image_compression_from(compression: String) -> CompressionType { match compression.trim().to_lowercase().as_str() { "best" => CompressionType::Best, "default" => CompressionType::Default, "fast" => CompressionType::Fast, "huffman" => CompressionType::Huffman, "rle" => CompressionType::Rle, _ => CompressionType::Fast, } } pub fn image_filter_from(filter: String) -> FilterType { match filter.trim().to_lowercase().as_str() { "avg" => FilterType::Avg, "nofilter" => FilterType::NoFilter, "paeth" => FilterType::Paeth, "sub" => FilterType::Sub, "up" => FilterType::Up, _ => FilterType::NoFilter, } } #[cfg(not(feature = "wasm-extension"))] fn mtpng_compression_from(compression: CompressionType) -> mtpng::CompressionLevel { match compression { CompressionType::Default => mtpng::CompressionLevel::Default, CompressionType::Best => mtpng::CompressionLevel::High, CompressionType::Fast => mtpng::CompressionLevel::Fast, _ => mtpng::CompressionLevel::Fast, } } #[cfg(not(feature = "wasm-extension"))] fn mtpng_filter_from(filter: FilterType) -> mtpng::Filter { match filter { FilterType::Avg => mtpng::Filter::Average, FilterType::Paeth => mtpng::Filter::Paeth, FilterType::Sub => mtpng::Filter::Sub, FilterType::Up => mtpng::Filter::Up, FilterType::NoFilter => mtpng::Filter::None, _ => mtpng::Filter::None, } } pub fn max<T: PartialOrd>(x: T, y: T) -> T { if x > y { x } else { y } } pub fn min<T: PartialOrd>(x: T, y: T) -> T { if x < y { x } else { y } }
use crate::blending::demultiply_image; use crate::errors::PConvertError; use image::codecs::png::{CompressionType, FilterType, PngDecoder, PngEncoder}; use image::ImageDecoder; use image::{ColorType, ImageBuffer, Rgba}; use std::fs::File; use std::io::{BufWriter, Read, Write}; pub fn decode_png( readable_stream: impl Read, demultiply: bool, ) -> Result<ImageBuffer<Rgba<u8>, Vec<u8>>, PConvertError> { let decoder = PngDecoder::new(readable_stream)?; let (width, height) = decoder.dimensions(); let mut reader = decoder.into_reader()?; let mut bytes = Vec::<u8>::new(); reader.read_to_end(&mut bytes)?; let mut img = ImageBuffer::from_vec(width, height, bytes).unwrap(); if demultiply { demultiply_image(&mut img) } Ok(img) } pub fn read_png_from_file( file_in: String, demultiply: bool, ) -> Result<ImageBuffer<Rgba<u8>, Vec<u8>>, PConvertError> { let file = File::open(file_in)?; decode_png(file, demultiply) } pub fn encode_png( writable_buff: impl Write, png: &ImageBuffer<Rgba<u8>, Vec<u8>>, compression: CompressionType, filter: FilterType, ) -> Result<(), PConvertError> { let buff = BufWriter::new(writable_buff); let encoder = PngEncoder::new_with_quality(buff, compression, filter); Ok(encoder.encode(&png, png.width(), png.height(), ColorType::Rgba8)?) } pub fn write_png_to_file( file_out: String, png: &ImageBuffer<Rgba<u8>, Vec<u8>>, compression: CompressionType, filter: FilterType, ) -> Result<(), PConvertError> { let file = File::create(&file_out)?; encode_png(file, png, compression, filter) } pub fn write_png_to_file_d( file_out: String, png: &ImageBuffer<Rgba<u8>, Vec<u8>>, ) -> Result<(), PConvertError> { let file = File::create(&file_out)?; encode_png(file, png, CompressionType::Fast, FilterType::NoFilter) } #[cfg(not(feature = "wasm-extension"))] pub fn write_png_parallel( file_out: String, png: &ImageBuffer<Rgba<u8>, Vec<u8>>, compression: CompressionType, filter: FilterType, ) -> Result<(), PConvertError> { let writer = File::create(file_out)?; let mut header = mtpng::Header::new(); header.set_size(png.width(), png.height())?; header.set_color(mtpng::ColorType::TruecolorAlpha, 8)?; let mut options = mtpng::encoder::Options::new(); options.set_compression_level(mtpng_compression_from(compression))?; options.set_filter_mode(mtpng::Mode::Fixed(mtpng_filter_from(filter)))?; let mut encoder = mtpng::encoder::Encoder::new(writer, &options); encoder.write_header(&header)?; encoder.write_image_rows(&png)?; encoder.finish()?; Ok(()) } #[cfg(feature = "wasm-extension")]
pub fn image_compression_from(compression: String) -> CompressionType { match compression.trim().to_lowercase().as_str() { "best" => CompressionType::Best, "default" => CompressionType::Default, "fast" => CompressionType::Fast, "huffman" => CompressionType::Huffman, "rle" => CompressionType::Rle, _ => CompressionType::Fast, } } pub fn image_filter_from(filter: String) -> FilterType { match filter.trim().to_lowercase().as_str() { "avg" => FilterType::Avg, "nofilter" => FilterType::NoFilter, "paeth" => FilterType::Paeth, "sub" => FilterType::Sub, "up" => FilterType::Up, _ => FilterType::NoFilter, } } #[cfg(not(feature = "wasm-extension"))] fn mtpng_compression_from(compression: CompressionType) -> mtpng::CompressionLevel { match compression { CompressionType::Default => mtpng::CompressionLevel::Default, CompressionType::Best => mtpng::CompressionLevel::High, CompressionType::Fast => mtpng::CompressionLevel::Fast, _ => mtpng::CompressionLevel::Fast, } } #[cfg(not(feature = "wasm-extension"))] fn mtpng_filter_from(filter: FilterType) -> mtpng::Filter { match filter { FilterType::Avg => mtpng::Filter::Average, FilterType::Paeth => mtpng::Filter::Paeth, FilterType::Sub => mtpng::Filter::Sub, FilterType::Up => mtpng::Filter::Up, FilterType::NoFilter => mtpng::Filter::None, _ => mtpng::Filter::None, } } pub fn max<T: PartialOrd>(x: T, y: T) -> T { if x > y { x } else { y } } pub fn min<T: PartialOrd>(x: T, y: T) -> T { if x < y { x } else { y } }
pub fn write_png_parallel( file_out: String, png: &ImageBuffer<Rgba<u8>, Vec<u8>>, compression: CompressionType, filter: FilterType, ) -> Result<(), PConvertError> { write_png_to_file(file_out, png, compression, filter) }
function_block-full_function
[ { "content": "/// Demultiplies an image buffer, by applying the demultiply operation over the\n\n/// complete set of pixels in the provided image buffer.\n\n///\n\n/// # Arguments\n\n///\n\n/// * `img` - The image buffer to demultiply.\n\npub fn demultiply_image(img: &mut ImageBuffer<Rgba<u8>, Vec<u8>>) {\n\n for pixel in img.pixels_mut() {\n\n demultiply_pixel(pixel);\n\n }\n\n}\n\n\n", "file_path": "src/blending/mod.rs", "rank": 1, "score": 206622.3895085475 }, { "content": "/// Testing utility that applies a blue-ish filter to an image\n\npub fn apply_blue_filter(pixel: &mut Rgba<u8>) {\n\n // sets red value to 0 and green value to the blue one (blue filter effect)\n\n pixel[0] = 0;\n\n pixel[1] = pixel[2];\n\n}\n", "file_path": "src/compose.rs", "rank": 2, "score": 194480.58152971184 }, { "content": "/// Multiplies an image buffer, running the opposite operation over the\n\n/// complete set of pixels in the image buffer.\n\n///\n\n/// # Arguments\n\n///\n\n/// * `img` - The image buffer to multiply.\n\npub fn multiply_image(img: &mut ImageBuffer<Rgba<u8>, Vec<u8>>) {\n\n for pixel in img.pixels_mut() {\n\n multiply_pixel(pixel);\n\n }\n\n}\n\n\n", "file_path": "src/blending/mod.rs", "rank": 8, "score": 184551.5772755195 }, { "content": "/// Retrieves the `image::codecs::png::CompressionType` value from the\n\n/// `HashMap<String, JSONValue>` map if it exists.\n\n/// Otherwise it returns the default value: `CompressionType::Fast`.\n\npub fn get_compression_type(options: &Option<HashMap<String, JSONValue>>) -> CompressionType {\n\n options.as_ref().map_or(CompressionType::Fast, |options| {\n\n options\n\n .get(\"compression\")\n\n .map_or(CompressionType::Fast, |compression| match compression {\n\n JSONValue::String(compression) => image_compression_from(compression.to_string()),\n\n _ => CompressionType::Fast,\n\n })\n\n })\n\n}\n\n\n", "file_path": "src/wasm/utils.rs", "rank": 9, "score": 184530.41697777392 }, { "content": "/// Retrieves the `image::codecs::png::FilterType` value from the\n\n/// `HashMap<String, JSONValue>` map if it exists.\n\n/// Otherwise it returns the default value: `FilterType::NoFilter`.\n\npub fn get_filter_type(options: &Option<HashMap<String, JSONValue>>) -> FilterType {\n\n options.as_ref().map_or(FilterType::NoFilter, |options| {\n\n options\n\n .get(\"filter\")\n\n .map_or(FilterType::NoFilter, |filter| match filter {\n\n JSONValue::String(filter) => image_filter_from(filter.to_string()),\n\n _ => FilterType::NoFilter,\n\n })\n\n })\n\n}\n\n\n", "file_path": "src/wasm/utils.rs", "rank": 10, "score": 184506.99479151002 }, { "content": "pub fn pconvert(args: &mut env::Args) -> Result<(), PConvertError> {\n\n let file_in = match args.next() {\n\n Some(name) => name,\n\n None => {\n\n return Err(PConvertError::ArgumentError(\n\n \"ArgumentError: 'file_in' not specified\".to_string(),\n\n ))\n\n }\n\n };\n\n\n\n let file_out = match args.next() {\n\n Some(name) => name,\n\n None => {\n\n return Err(PConvertError::ArgumentError(\n\n \"ArgumentError: 'file_out' not specified\".to_string(),\n\n ))\n\n }\n\n };\n\n\n\n let mut img = read_png_from_file(file_in, false)?;\n\n\n\n for pixel in img.pixels_mut() {\n\n apply_blue_filter(pixel);\n\n }\n\n\n\n img.save_with_format(file_out, ImageFormat::Png)?;\n\n\n\n Ok(())\n\n}\n\n\n", "file_path": "src/cli.rs", "rank": 12, "score": 172197.4013673651 }, { "content": "pub fn pbenchmark(args: &mut env::Args) -> Result<(), PConvertError> {\n\n let dir = match args.next() {\n\n Some(name) => {\n\n if name.ends_with('/') {\n\n name\n\n } else {\n\n format!(\"{}/\", name)\n\n }\n\n }\n\n None => {\n\n return Err(PConvertError::ArgumentError(\n\n \"ArgumentError: 'directory' not specified\".to_string(),\n\n ))\n\n }\n\n };\n\n\n\n let run_parallel = match args.next() {\n\n Some(flag) => flag.eq(\"--parallel\"),\n\n _ => false,\n\n };\n", "file_path": "src/cli.rs", "rank": 13, "score": 172197.4013673651 }, { "content": "pub fn pcompose(args: &mut env::Args) -> Result<(), PConvertError> {\n\n let dir = match args.next() {\n\n Some(name) => {\n\n if name.ends_with('/') {\n\n name\n\n } else {\n\n format!(\"{}/\", name)\n\n }\n\n }\n\n None => {\n\n return Err(PConvertError::ArgumentError(\n\n \"ArgumentError: 'directory' not specified\".to_string(),\n\n ))\n\n }\n\n };\n\n\n\n let mut benchmark = Benchmark::new();\n\n\n\n let backgrounds = vec![\n\n Background::Alpha,\n", "file_path": "src/cli.rs", "rank": 14, "score": 172197.4013673651 }, { "content": "/// Retrieves the `image::codecs::png::CompressionType` value from the `Options` map if it exists.\n\n/// Otherwise it returns the default value: `CompressionType::Fast`.\n\npub fn get_compression_type(options: &Option<Options>) -> CompressionType {\n\n options.clone().map_or(CompressionType::Fast, |options| {\n\n options\n\n .get(\"compression\")\n\n .map_or(CompressionType::Fast, |compression| match compression {\n\n Value::Str(compression) => image_compression_from(compression.to_string()),\n\n _ => CompressionType::Fast,\n\n })\n\n })\n\n}\n\n\n", "file_path": "src/pymodule/utils.rs", "rank": 16, "score": 167866.6937231592 }, { "content": "/// Retrieves the `image::codecs::png::FilterType` value from the `Options` map if it exists.\n\n/// Otherwise it returns the default value: `FilterType::NoFilter`.\n\npub fn get_filter_type(options: &Option<Options>) -> FilterType {\n\n options.clone().map_or(FilterType::NoFilter, |options| {\n\n options\n\n .get(\"filter\")\n\n .map_or(FilterType::NoFilter, |filter| match filter {\n\n Value::Str(filter) => image_filter_from(filter.to_string()),\n\n _ => FilterType::NoFilter,\n\n })\n\n })\n\n}\n\n\n", "file_path": "src/pymodule/utils.rs", "rank": 17, "score": 167841.1388087933 }, { "content": "fn write_str_constant_to_file(file: &mut File, key: &str, val: &str) {\n\n writeln!(file, \"pub const {}: &str = \\\"{}\\\";\", key, val)\n\n .unwrap_or_else(|_| panic!(\"Failed to write '{}' to 'build_constants.rs'\", key));\n\n}\n\n\n", "file_path": "build.rs", "rank": 18, "score": 162878.27940798586 }, { "content": "fn demultiply_pixel(pixel: &mut Rgba<u8>) {\n\n let (r, g, b, a) = (pixel[0], pixel[1], pixel[2], pixel[3]);\n\n let af = a as f32 / 255.0;\n\n\n\n let r = (r as f32 * af).round() as u8;\n\n let g = (g as f32 * af).round() as u8;\n\n let b = (b as f32 * af).round() as u8;\n\n\n\n pixel[0] = r;\n\n pixel[1] = g;\n\n pixel[2] = b;\n\n}\n\n\n", "file_path": "src/blending/mod.rs", "rank": 19, "score": 160670.80996803835 }, { "content": "fn write_constant_to_file<T>(file: &mut File, key: &str, val: T)\n\nwhere\n\n T: std::fmt::Display,\n\n{\n\n writeln!(\n\n file,\n\n \"pub const {}: {} = {};\",\n\n key,\n\n std::any::type_name::<T>(),\n\n val\n\n )\n\n .unwrap_or_else(|_| panic!(\"Failed to write '{}' to 'build_constants.rs'\", key));\n\n}\n\n\n", "file_path": "build.rs", "rank": 20, "score": 160109.17586612282 }, { "content": "/// Receives png buffer data and encodes it as a `File` with specified\n\n/// `CompressionType` and `FilterType`.\n\npub fn encode_file(\n\n image_buffer: ImageBuffer<Rgba<u8>, Vec<u8>>,\n\n compression: CompressionType,\n\n filter: FilterType,\n\n target_file_name: String,\n\n) -> Result<File, JsValue> {\n\n let mut encoded_data = Vec::<u8>::with_capacity(image_buffer.to_vec().capacity());\n\n encode_png(&mut encoded_data, &image_buffer, compression, filter)?;\n\n\n\n unsafe {\n\n let array_buffer = Uint8Array::view(&encoded_data);\n\n File::new_with_u8_array_sequence(&Array::of1(&array_buffer), &target_file_name)\n\n }\n\n}\n\n\n", "file_path": "src/wasm/utils.rs", "rank": 21, "score": 157644.6673329918 }, { "content": "fn write_enum_variants_to_file<T>(file: &mut File, key: &str, vec: Vec<T>)\n\nwhere\n\n T: std::fmt::Debug,\n\n{\n\n let mut list_str = String::new();\n\n for value in &vec {\n\n list_str.push_str(&format!(\"{}::{:?},\", std::any::type_name::<T>(), value))\n\n }\n\n list_str.pop();\n\n writeln!(\n\n file,\n\n \"pub const {}: [{}; {}] = [{}];\",\n\n key,\n\n std::any::type_name::<T>(),\n\n vec.len(),\n\n list_str\n\n )\n\n .unwrap_or_else(|_| panic!(\"Failed to write '{}' to 'build_constants.rs'\", key));\n\n}\n", "file_path": "build.rs", "rank": 22, "score": 152288.77309588314 }, { "content": "fn write_vec_constant_to_file<T>(file: &mut File, key: &str, vec: Vec<T>)\n\nwhere\n\n T: std::fmt::Display,\n\n{\n\n let mut list_str = String::new();\n\n for value in &vec {\n\n list_str.push_str(&format!(\"\\\"{}\\\",\", value))\n\n }\n\n list_str.pop();\n\n writeln!(\n\n file,\n\n \"pub const {}: [{}; {}] = [{}];\",\n\n key,\n\n std::any::type_name::<T>(),\n\n vec.len(),\n\n list_str\n\n )\n\n .unwrap_or_else(|_| panic!(\"Failed to write '{}' to 'build_constants.rs'\", key));\n\n}\n\n\n", "file_path": "build.rs", "rank": 23, "score": 152288.77309588314 }, { "content": "/// Retrieves the number of threads value from the `Options` map if it exists.\n\n/// Otherwise it returns the default value: 0.\n\npub fn get_num_threads(options: &Option<Options>) -> i32 {\n\n options.clone().map_or(0, |options| {\n\n options\n\n .get(\"num_threads\")\n\n .map_or(0, |num_threads| match num_threads {\n\n Value::Int(num_threads) => *num_threads,\n\n _ => 0,\n\n })\n\n })\n\n}\n", "file_path": "src/pymodule/utils.rs", "rank": 24, "score": 137195.9780224681 }, { "content": "fn multiply_pixel(pixel: &mut Rgba<u8>) {\n\n let (r, g, b, a) = (pixel[0], pixel[1], pixel[2], pixel[3]);\n\n let af = a as f32 / 255.0;\n\n\n\n let r = (r as f32 / af).round() as u8;\n\n let g = (g as f32 / af).round() as u8;\n\n let b = (b as f32 / af).round() as u8;\n\n\n\n pixel[0] = r;\n\n pixel[1] = g;\n\n pixel[2] = b;\n\n}\n", "file_path": "src/blending/mod.rs", "rank": 25, "score": 134749.33865035864 }, { "content": "/// Attempts to parse a `&String` to a `BlendAlgorithm`.\n\n/// Returns the enum variant if it suceeds. Otherwise it returns a `PConvertError`.\n\npub fn build_algorithm(algorithm: &str) -> Result<BlendAlgorithm, PConvertError> {\n\n match BlendAlgorithm::from_str(&algorithm) {\n\n Ok(algorithm) => Ok(algorithm),\n\n Err(algorithm) => Err(PConvertError::ArgumentError(format!(\n\n \"Invalid algorithm '{}'\",\n\n algorithm\n\n ))),\n\n }\n\n}\n\n\n", "file_path": "src/wasm/utils.rs", "rank": 26, "score": 131739.6197718103 }, { "content": "/// Returns whether or not a `BlendAlgorithm` enum variant corresponds to a\n\n/// multiplied blending algorithm.\n\n///\n\n/// # Arguments\n\n///\n\n/// * `algorithm` - The BlendAlgorithm enum variant.\n\npub fn is_algorithm_multiplied(algorithm: &BlendAlgorithm) -> bool {\n\n match algorithm {\n\n BlendAlgorithm::Alpha => false,\n\n BlendAlgorithm::Multiplicative => false,\n\n BlendAlgorithm::SourceOver => false,\n\n BlendAlgorithm::DestinationOver => false,\n\n BlendAlgorithm::MaskTop => false,\n\n BlendAlgorithm::FirstTop => false,\n\n BlendAlgorithm::FirstBottom => false,\n\n BlendAlgorithm::DisjointOver => true,\n\n BlendAlgorithm::DisjointUnder => true,\n\n BlendAlgorithm::DisjointDebug => true,\n\n }\n\n}\n\n\n", "file_path": "src/blending/mod.rs", "rank": 27, "score": 129252.52931285788 }, { "content": "/// Logs the header/column names of the benchmarks table to the browser\n\n/// console (with `console.log`).\n\npub fn log_benchmark_header() {\n\n console_log!(\n\n \"{:<20}{:<20}{:<20}{:<20}\",\n\n \"Algorithm\",\n\n \"Compression\",\n\n \"Filter\",\n\n \"Times\"\n\n );\n\n}\n\n\n", "file_path": "src/wasm/utils.rs", "rank": 28, "score": 125813.67761035849 }, { "content": "/// Receives png buffer data and encodes it as an `ImageData` object with\n\n/// specified `CompressionType` and `FilterType`.\n\npub fn encode_image_data(\n\n image_buffer: ImageBuffer<Rgba<u8>, Vec<u8>>,\n\n compression: CompressionType,\n\n filter: FilterType,\n\n) -> Result<ImageData, JsValue> {\n\n let (width, height) = image_buffer.dimensions();\n\n\n\n let mut encoded_data = Vec::<u8>::with_capacity(image_buffer.to_vec().capacity());\n\n encode_png(&mut encoded_data, &image_buffer, compression, filter)?;\n\n\n\n let bytes = &mut image_buffer.to_vec();\n\n let clamped_bytes: Clamped<&[u8]> = Clamped(bytes);\n\n\n\n ImageData::new_with_u8_clamped_array_and_sh(clamped_bytes, width, height)\n\n}\n\n\n", "file_path": "src/wasm/utils.rs", "rank": 29, "score": 125775.49557221952 }, { "content": "fn main() -> Result<(), PConvertError> {\n\n let mut args = env::args();\n\n\n\n // skips program name, facilitating the parsing\n\n // of the extra argument from command line\n\n args.next();\n\n\n\n match args.next() {\n\n Some(action) => match &action[..] {\n\n \"convert\" => pconvert(&mut args)?,\n\n \"compose\" => pcompose(&mut args)?,\n\n \"benchmark\" => pbenchmark(&mut args)?,\n\n \"version\" => pversion(),\n\n _ => print_usage(),\n\n },\n\n None => print_usage(),\n\n };\n\n\n\n Ok(())\n\n}\n", "file_path": "src/main.rs", "rank": 30, "score": 122723.83554326938 }, { "content": "/// Attempts to parse a `&String` to a `BlendAlgorithm`.\n\n/// Returns the enum variant if it succeeds. Otherwise it returns a `PyErr`.\n\npub fn build_algorithm(algorithm: &str) -> Result<BlendAlgorithm, PyErr> {\n\n match BlendAlgorithm::from_str(algorithm) {\n\n Ok(algorithm) => Ok(algorithm),\n\n Err(algorithm) => Err(PyErr::from(PConvertError::ArgumentError(format!(\n\n \"ArgumentError: invalid algorithm '{}'\",\n\n algorithm\n\n )))),\n\n }\n\n}\n\n\n", "file_path": "src/pymodule/utils.rs", "rank": 31, "score": 115248.47039791994 }, { "content": "/// Wrapper function for nodejs `fs.readFileSync`.\n\npub fn node_read_file_sync(fs: &NodeFs, path: &str) -> Vec<u8> {\n\n fs.readFileSync(path)\n\n}\n\n\n", "file_path": "src/wasm/utils.rs", "rank": 33, "score": 112576.13946787277 }, { "content": "/// Wrapper function for nodejs `fs.writeFileSync`.\n\npub fn node_write_file_sync(fs: &NodeFs, path: &str, data: &[u8]) {\n\n fs.writeFileSync(path, data);\n\n}\n", "file_path": "src/wasm/utils.rs", "rank": 34, "score": 112474.27149751422 }, { "content": "/// Rust Future from nodejs `fs.readFile` Promise (awaitable in node).\n\npub fn node_read_file_async(fs: &NodeFs, path: &str) -> wasm_bindgen_futures::JsFuture {\n\n let promise = js_sys::Promise::new(&mut |resolve, reject| {\n\n let callback = js_sys::Function::new_with_args(\n\n \"resolve, reject, err, data\",\n\n \"err ? reject(err) : resolve(data);\",\n\n )\n\n .bind2(&JsValue::NULL, &resolve, &reject);\n\n fs.readFile(path, callback)\n\n });\n\n\n\n wasm_bindgen_futures::JsFuture::from(promise)\n\n}\n\n\n", "file_path": "src/wasm/utils.rs", "rank": 35, "score": 105947.61717344417 }, { "content": "/// Testing utility that composes an image made up of the specified\n\n/// background image, using the specified algorithm, compression and filter types.\n\n/// Looks for the layers and outputs the final composition to the given `dir` and\n\n/// takes track of times spent in each phase in the benchmark struct\n\npub fn compose(\n\n dir: &str,\n\n algorithm: BlendAlgorithm,\n\n background: &Background,\n\n compression: CompressionType,\n\n filter: FilterType,\n\n benchmark: &mut Benchmark,\n\n) -> Result<String, PConvertError> {\n\n let demultiply = is_algorithm_multiplied(&algorithm);\n\n\n\n let algorithm_fn = get_blending_algorithm(&algorithm);\n\n\n\n // reads one PNG at the time and blends it with the current result\n\n // these values are hardcoded by the multiple layer files\n\n let background_file = format!(\"background_{}.png\", background);\n\n let png_file_names = vec![\n\n \"sole.png\",\n\n \"back.png\",\n\n \"front.png\",\n\n \"shoelace.png\",\n", "file_path": "src/compose.rs", "rank": 36, "score": 104606.03851101967 }, { "content": "pub fn pversion() {\n\n println!(\n\n \"P(NG)Convert Rust {} ({} {}) [{} {} {} bit] [libpng {}] {:?}\",\n\n constants::VERSION,\n\n constants::COMPILATION_DATE,\n\n constants::COMPILATION_TIME,\n\n constants::COMPILER,\n\n constants::COMPILER_VERSION,\n\n constants::PLATFORM_CPU_BITS,\n\n constants::LIBPNG_VERSION,\n\n constants::FEATURES\n\n );\n\n println!(\"Copyright (c) 2008-2021 Platforme International Limited. All rights reserved.\");\n\n}\n", "file_path": "src/cli.rs", "rank": 37, "score": 104598.7925214837 }, { "content": "/// Multi-threaded version of the `compose` testing utility\n\n/// Reads each PNG in a different thread and makes use of the\n\n/// `mtpng` library to write the final composition\n\npub fn compose_parallel(\n\n dir: &str,\n\n algorithm: BlendAlgorithm,\n\n background: &Background,\n\n compression: CompressionType,\n\n filter: FilterType,\n\n benchmark: &mut Benchmark,\n\n) -> Result<String, PConvertError> {\n\n let demultiply = is_algorithm_multiplied(&algorithm);\n\n let algorithm_fn = get_blending_algorithm(&algorithm);\n\n\n\n let mut thread_pool = ThreadPool::new(THREAD_POOL_SIZE)?;\n\n thread_pool.start();\n\n\n\n // sends the PNG reading tasks to multiple threads\n\n // these values are hardcoded by the multiple layer files\n\n let background_file = format!(\"background_{}.png\", background);\n\n let png_file_names = vec![\n\n \"sole.png\",\n\n \"back.png\",\n", "file_path": "src/compose.rs", "rank": 38, "score": 102201.96921958678 }, { "content": "pub fn print_usage() {\n\n println!(\"Usage: pconvert-rust <command> [args...]\\nwhere command can be one of the following: compose, convert, benchmark, version\");\n\n}\n\n\n", "file_path": "src/cli.rs", "rank": 39, "score": 102190.78323746576 }, { "content": "/// Blends two images buffers with the given blending function and\n\n/// optional parameters.\n\n///\n\n/// # Arguments\n\n///\n\n/// * `bot` - An image buffer corresponding to the bottom layer, in typical\n\n/// composition language this should be considered the `source`.\n\n/// * `top` - An image buffer corresponding to the top layer, in typical\n\n/// composition language this should be considered the `destination`.\n\n/// * `blending_algorithm` - A function that blends two pixels according\n\n/// to optional blending parameters.\n\n/// * `algorithm_params` - A optional map of key-value pairs of blending\n\n/// properties and values.\n\n///\n\n/// # Examples\n\n///\n\n/// ```no_run\n\n/// use pconvert_rust::blending::{blend_images, get_blending_algorithm, BlendAlgorithm};\n\n/// use pconvert_rust::utils::read_png_from_file;\n\n///\n\n/// let mut bot = read_png_from_file(\"bot.png\".to_string(), false).unwrap();\n\n/// let top = read_png_from_file(\"top.png\".to_string(), false).unwrap();\n\n/// let algorithm_fn = get_blending_algorithm(&BlendAlgorithm::Alpha);\n\n///\n\n/// blend_images(&mut bot, &top, &algorithm_fn, &None);\n\n/// ```\n\npub fn blend_images(\n\n bot: &mut ImageBuffer<Rgba<u8>, Vec<u8>>,\n\n top: &ImageBuffer<Rgba<u8>, Vec<u8>>,\n\n blending_algorithm: &impl Fn((&mut Rgba<u8>, &Rgba<u8>), &Option<BlendAlgorithmParams>),\n\n algorithm_params: &Option<BlendAlgorithmParams>,\n\n) {\n\n for pixel_pair in bot.pixels_mut().zip(top.pixels()) {\n\n blending_algorithm(pixel_pair, algorithm_params);\n\n }\n\n}\n\n\n", "file_path": "src/blending/mod.rs", "rank": 40, "score": 99991.0508083049 }, { "content": "/// Logs one line (algorithm, compression, filter, blend time, read time, write time)\n\n/// of the benchmarks table to the browser console (with `console.log`).\n\npub fn log_benchmark(\n\n algorithm: String,\n\n compression: CompressionType,\n\n filter: FilterType,\n\n blend_time: f64,\n\n read_time: f64,\n\n write_time: f64,\n\n) {\n\n console_log!(\n\n \"{:<20}{:<20}{:<20}{:<20}\",\n\n algorithm,\n\n format!(\"{:#?}\", compression),\n\n format!(\"{:#?}\", filter),\n\n format!(\n\n \"{}ms (blend {}ms, read {}ms, write {}ms)\",\n\n read_time + blend_time + write_time,\n\n blend_time,\n\n read_time,\n\n write_time\n\n )\n\n );\n\n}\n\n\n", "file_path": "src/wasm/utils.rs", "rank": 41, "score": 99981.81722740765 }, { "content": "#[inline]\n\npub fn blend_multiplicative(\n\n (bot_pixel, top_pixel): (&mut Rgba<u8>, &Rgba<u8>),\n\n _params: &Option<BlendAlgorithmParams>,\n\n) {\n\n let (rb, gb, bb, ab) = (bot_pixel[0], bot_pixel[1], bot_pixel[2], bot_pixel[3]);\n\n let (rt, gt, bt, at) = (top_pixel[0], top_pixel[1], top_pixel[2], top_pixel[3]);\n\n\n\n let atf = 1.0 * (at as f32 / 255.0);\n\n\n\n let mut r = rb as f32 * (1.0 - atf) + rt as f32 * atf;\n\n let mut g = gb as f32 * (1.0 - atf) + gt as f32 * atf;\n\n let mut b = bb as f32 * (1.0 - atf) + bt as f32 * atf;\n\n let a = max(0, min(255, at as u16 + ab as u16));\n\n\n\n r = max(0.0, min(255.0, r));\n\n g = max(0.0, min(255.0, g));\n\n b = max(0.0, min(255.0, b));\n\n\n\n bot_pixel[0] = r as u8;\n\n bot_pixel[1] = g as u8;\n\n bot_pixel[2] = b as u8;\n\n bot_pixel[3] = a as u8;\n\n}\n\n\n", "file_path": "src/blending/algorithms.rs", "rank": 42, "score": 99970.72765001224 }, { "content": "/// Attempts to build a vector of blending operations and extra parameters.\n\n/// One pair per blending operation. Returns a `PyErr` if it fails parsing.\n\npub fn build_params(\n\n algorithms: &PySequence,\n\n) -> Result<Vec<(BlendAlgorithm, Option<BlendAlgorithmParams>)>, PyErr> {\n\n let mut result = Vec::new();\n\n\n\n // parses the parameter sequence which is a python sequence (tuple or list)\n\n // made of either algorithms or more sequences of algorithms and special parameters\n\n for i in 0..algorithms.len()? {\n\n let element = algorithms.get_item(i)?;\n\n\n\n if let Ok(string) = element.cast_as::<PyString>() {\n\n let algorithm = build_algorithm(&string.to_string())?;\n\n result.push((algorithm, None));\n\n } else if let Ok(sequence) = element.cast_as::<PySequence>() {\n\n let algorithm = sequence.get_item(0)?.extract::<String>()?;\n\n let algorithm = build_algorithm(&algorithm)?;\n\n\n\n let mut blending_params = BlendAlgorithmParams::new();\n\n let params_sequence = sequence.get_item(1)?;\n\n if let Ok(params_sequence) = params_sequence.cast_as::<PySequence>() {\n", "file_path": "src/pymodule/utils.rs", "rank": 43, "score": 99970.72765001224 }, { "content": "#[inline]\n\npub fn blend_disjoint_under(\n\n (bot_pixel, top_pixel): (&mut Rgba<u8>, &Rgba<u8>),\n\n _params: &Option<BlendAlgorithmParams>,\n\n) {\n\n let (rb, gb, bb, ab) = (bot_pixel[0], bot_pixel[1], bot_pixel[2], bot_pixel[3]);\n\n let (rt, gt, bt, at) = (top_pixel[0], top_pixel[1], top_pixel[2], top_pixel[3]);\n\n\n\n let abf = 1.0 * (ab as f32 / 255.0);\n\n let atf = 1.0 * (at as f32 / 255.0);\n\n\n\n let mut r = if atf * abf > 0.0 {\n\n rt as f32 / atf * (1.0 - abf) + rb as f32\n\n } else {\n\n rt as f32 * (1.0 - abf) + rb as f32\n\n };\n\n let mut g = if atf * abf > 0.0 {\n\n gt as f32 / atf * (1.0 - abf) + gb as f32\n\n } else {\n\n gt as f32 * (1.0 - abf) + gb as f32\n\n };\n", "file_path": "src/blending/algorithms.rs", "rank": 44, "score": 99970.72765001224 }, { "content": "#[inline]\n\npub fn blend_alpha(\n\n (bot_pixel, top_pixel): (&mut Rgba<u8>, &Rgba<u8>),\n\n _params: &Option<BlendAlgorithmParams>,\n\n) {\n\n let (rb, gb, bb, ab) = (bot_pixel[0], bot_pixel[1], bot_pixel[2], bot_pixel[3]);\n\n let (rt, gt, bt, at) = (top_pixel[0], top_pixel[1], top_pixel[2], top_pixel[3]);\n\n\n\n let abf = 1.0 * (ab as f32 / 255.0);\n\n let atf = 1.0 * (at as f32 / 255.0);\n\n let af = atf + abf * (1.0 - atf);\n\n\n\n let mut r = if af == 0.0 {\n\n 0.0\n\n } else {\n\n (rb as f32 * abf + rt as f32 * atf * (1.0 - abf)) / af\n\n };\n\n let mut g = if af == 0.0 {\n\n 0.0\n\n } else {\n\n (gb as f32 * abf + gt as f32 * atf * (1.0 - abf)) / af\n", "file_path": "src/blending/algorithms.rs", "rank": 45, "score": 99970.72765001224 }, { "content": "#[inline]\n\npub fn blend_disjoint_over(\n\n (bot_pixel, top_pixel): (&mut Rgba<u8>, &Rgba<u8>),\n\n _params: &Option<BlendAlgorithmParams>,\n\n) {\n\n let (rb, gb, bb, ab) = (bot_pixel[0], bot_pixel[1], bot_pixel[2], bot_pixel[3]);\n\n let (rt, gt, bt, at) = (top_pixel[0], top_pixel[1], top_pixel[2], top_pixel[3]);\n\n\n\n let abf = 1.0 * (ab as f32 / 255.0);\n\n let atf = 1.0 * (at as f32 / 255.0);\n\n\n\n let mut r = if atf + abf < 1.0 {\n\n rt as f32 + rb as f32 * (1.0 - atf) / abf\n\n } else {\n\n rt as f32 + rb as f32\n\n };\n\n let mut g = if atf + abf < 1.0 {\n\n gt as f32 + gb as f32 * (1.0 - atf) / abf\n\n } else {\n\n gt as f32 + gb as f32\n\n };\n", "file_path": "src/blending/algorithms.rs", "rank": 46, "score": 99970.72765001224 }, { "content": "/// Attempts to build a vector of blending operations and extra parameters.\n\n/// One pair per blending operation. Returns a `PConvertError` if it fails parsing.\n\npub fn build_params(\n\n algorithms: &[JsValue],\n\n) -> Result<Vec<(BlendAlgorithm, Option<BlendAlgorithmParams>)>, PConvertError> {\n\n let mut result = Vec::new();\n\n\n\n for algorithm in algorithms {\n\n if algorithm.is_string() {\n\n let algorithm =\n\n build_algorithm(&algorithm.as_string().unwrap_or_else(|| \"multiplicative\".to_string()))?;\n\n\n\n result.push((algorithm, None));\n\n } else if algorithm.is_object() {\n\n let params: JSONParams = algorithm.into_serde::<JSONParams>().unwrap();\n\n let algorithm = build_algorithm(&params.algorithm)?;\n\n\n\n let mut blending_params = BlendAlgorithmParams::new();\n\n for (param_name, param_value) in params.params {\n\n let param_value: Value = param_value.into();\n\n blending_params.insert(param_name, param_value);\n\n }\n\n\n\n result.push((algorithm, Some(blending_params)));\n\n }\n\n }\n\n\n\n Ok(result)\n\n}\n\n\n", "file_path": "src/wasm/utils.rs", "rank": 47, "score": 99970.72765001224 }, { "content": "#[inline]\n\npub fn blend_source_over(\n\n (bot_pixel, top_pixel): (&mut Rgba<u8>, &Rgba<u8>),\n\n _params: &Option<BlendAlgorithmParams>,\n\n) {\n\n let (rb, gb, bb, ab) = (bot_pixel[0], bot_pixel[1], bot_pixel[2], bot_pixel[3]);\n\n let (rt, gt, bt, at) = (top_pixel[0], top_pixel[1], top_pixel[2], top_pixel[3]);\n\n\n\n let abf = 1.0 * (ab as f32 / 255.0);\n\n let atf = 1.0 * (at as f32 / 255.0);\n\n let af = abf + atf * (1.0 - abf);\n\n\n\n let mut r = if af == 0.0 {\n\n 0.0\n\n } else {\n\n (rb as f32 * abf + rt as f32 * atf * (1.0 - abf)) / af\n\n };\n\n let mut g = if af == 0.0 {\n\n 0.0\n\n } else {\n\n (gb as f32 * abf + gt as f32 * atf * (1.0 - abf)) / af\n", "file_path": "src/blending/algorithms.rs", "rank": 48, "score": 99970.72765001224 }, { "content": "#[inline]\n\npub fn blend_destination_over(\n\n (bot_pixel, top_pixel): (&mut Rgba<u8>, &Rgba<u8>),\n\n _params: &Option<BlendAlgorithmParams>,\n\n) {\n\n let (rb, gb, bb, ab) = (bot_pixel[0], bot_pixel[1], bot_pixel[2], bot_pixel[3]);\n\n let (rt, gt, bt, at) = (top_pixel[0], top_pixel[1], top_pixel[2], top_pixel[3]);\n\n\n\n let abf = 1.0 * (ab as f32 / 255.0);\n\n let atf = 1.0 * (at as f32 / 255.0);\n\n let af = atf + abf * (1.0 - atf);\n\n\n\n let mut r = if af == 0.0 {\n\n 0.0\n\n } else {\n\n (rt as f32 * atf + rb as f32 * abf * (1.0 - atf)) / af\n\n };\n\n let mut g = if af == 0.0 {\n\n 0.0\n\n } else {\n\n (gt as f32 * atf + gb as f32 * abf * (1.0 - atf)) / af\n", "file_path": "src/blending/algorithms.rs", "rank": 49, "score": 99970.72765001224 }, { "content": "/// Blends two image buffers using `algorithm` and the extra\n\n/// `options` given. Algorithm defaults to `BlendAlgorithm::Multiplicative`.\n\npub fn blend_image_buffers(\n\n bot: &mut ImageBuffer<Rgba<u8>, Vec<u8>>,\n\n top: &mut ImageBuffer<Rgba<u8>, Vec<u8>>,\n\n algorithm: Option<String>,\n\n is_inline: Option<bool>,\n\n) -> Result<(), PConvertError> {\n\n let algorithm = algorithm.unwrap_or_else(|| String::from(\"multiplicative\"));\n\n let algorithm = build_algorithm(&algorithm)?;\n\n let algorithm_fn = get_blending_algorithm(&algorithm);\n\n let demultiply = is_algorithm_multiplied(&algorithm);\n\n let _is_inline = is_inline.unwrap_or(false);\n\n\n\n if demultiply {\n\n demultiply_image(bot);\n\n demultiply_image(top);\n\n }\n\n\n\n blend_images(bot, &top, &algorithm_fn, &None);\n\n Ok(())\n\n}\n", "file_path": "src/wasm/mod.rs", "rank": 50, "score": 97923.34623598287 }, { "content": "/// Matches a `BlendAlgorithm` enum variant with a blend function.\n\n///\n\n/// # Arguments\n\n///\n\n/// * `algorithm` - The BlendAlgorithm enum variant.\n\npub fn get_blending_algorithm(\n\n algorithm: &BlendAlgorithm,\n\n) -> impl Fn((&mut Rgba<u8>, &Rgba<u8>), &Option<BlendAlgorithmParams>) {\n\n match algorithm {\n\n BlendAlgorithm::Alpha => blend_alpha,\n\n BlendAlgorithm::Multiplicative => blend_multiplicative,\n\n BlendAlgorithm::SourceOver => blend_source_over,\n\n BlendAlgorithm::DestinationOver => blend_destination_over,\n\n BlendAlgorithm::MaskTop => blend_mask_top,\n\n BlendAlgorithm::FirstTop => blend_first_top,\n\n BlendAlgorithm::FirstBottom => blend_first_bottom,\n\n BlendAlgorithm::DisjointOver => blend_disjoint_over,\n\n BlendAlgorithm::DisjointUnder => blend_disjoint_under,\n\n BlendAlgorithm::DisjointDebug => blend_disjoint_debug,\n\n }\n\n}\n\n\n", "file_path": "src/blending/mod.rs", "rank": 51, "score": 97917.44662971303 }, { "content": "#[inline]\n\npub fn blend_first_top(\n\n (bot_pixel, top_pixel): (&mut Rgba<u8>, &Rgba<u8>),\n\n _params: &Option<BlendAlgorithmParams>,\n\n) {\n\n let (rb, gb, bb, ab) = (bot_pixel[0], bot_pixel[1], bot_pixel[2], bot_pixel[3]);\n\n let (rt, gt, bt, at) = (top_pixel[0], top_pixel[1], top_pixel[2], top_pixel[3]);\n\n\n\n let mut r = if at == 0 { rb } else { rt };\n\n let mut g = if at == 0 { gb } else { gt };\n\n let mut b = if at == 0 { bb } else { bt };\n\n let mut a = if at == 0 { ab } else { at };\n\n\n\n r = max(0, min(255, r));\n\n g = max(0, min(255, g));\n\n b = max(0, min(255, b));\n\n a = max(0, min(255, a));\n\n\n\n bot_pixel[0] = r;\n\n bot_pixel[1] = g;\n\n bot_pixel[2] = b;\n\n bot_pixel[3] = a;\n\n}\n\n\n", "file_path": "src/blending/algorithms.rs", "rank": 52, "score": 97917.44662971303 }, { "content": "#[inline]\n\npub fn blend_mask_top(\n\n (bot_pixel, top_pixel): (&mut Rgba<u8>, &Rgba<u8>),\n\n params: &Option<BlendAlgorithmParams>,\n\n) {\n\n let (rb, gb, bb, ab) = (bot_pixel[0], bot_pixel[1], bot_pixel[2], bot_pixel[3]);\n\n let (rt, gt, bt, at) = (top_pixel[0], top_pixel[1], top_pixel[2], top_pixel[3]);\n\n\n\n let factor = params\n\n .as_ref()\n\n .and_then(|params| params.get(\"factor\"))\n\n .and_then(|param| match param {\n\n Value::Float(float) => Some(*float),\n\n _ => None,\n\n })\n\n .unwrap_or(1.0) as f32;\n\n\n\n let atf = factor * (at as f32 / 255.0);\n\n let abf = 1.0 - atf;\n\n\n\n let mut r = rb as f32 * abf + rt as f32 * atf;\n", "file_path": "src/blending/algorithms.rs", "rank": 53, "score": 97917.44662971303 }, { "content": "#[wasm_bindgen(js_name = blendMultipleFs)]\n\npub fn blend_multiple_fs(\n\n image_paths: Vec<JsValue>,\n\n out_path: String,\n\n algorithm: Option<String>,\n\n algorithms: Option<Vec<JsValue>>,\n\n is_inline: Option<bool>,\n\n options: JsValue,\n\n) -> Result<(), JsValue> {\n\n let num_images = image_paths.len();\n\n\n\n if num_images < 1 {\n\n return Err(PConvertError::ArgumentError(\n\n \"ArgumentError: 'img_paths' must contain at least one path\".to_string(),\n\n )\n\n .into());\n\n }\n\n\n\n let options = match options.is_object() {\n\n true => options.into_serde::<HashMap<String, JSONValue>>().ok(),\n\n false => None,\n", "file_path": "src/wasm/mod.rs", "rank": 54, "score": 97917.44662971303 }, { "content": "#[inline]\n\npub fn blend_first_bottom(\n\n (bot_pixel, top_pixel): (&mut Rgba<u8>, &Rgba<u8>),\n\n _params: &Option<BlendAlgorithmParams>,\n\n) {\n\n let (rb, gb, bb, ab) = (bot_pixel[0], bot_pixel[1], bot_pixel[2], bot_pixel[3]);\n\n let (rt, gt, bt, at) = (top_pixel[0], top_pixel[1], top_pixel[2], top_pixel[3]);\n\n\n\n let mut r = if ab == 0 { rt } else { rb };\n\n let mut g = if ab == 0 { gt } else { gb };\n\n let mut b = if ab == 0 { bt } else { bb };\n\n let mut a = if ab == 0 { at } else { ab };\n\n\n\n r = max(0, min(255, r));\n\n g = max(0, min(255, g));\n\n b = max(0, min(255, b));\n\n a = max(0, min(255, a));\n\n\n\n bot_pixel[0] = r;\n\n bot_pixel[1] = g;\n\n bot_pixel[2] = b;\n\n bot_pixel[3] = a;\n\n}\n\n\n", "file_path": "src/blending/algorithms.rs", "rank": 55, "score": 97917.44662971303 }, { "content": "#[inline]\n\npub fn blend_disjoint_debug(\n\n (bot_pixel, top_pixel): (&mut Rgba<u8>, &Rgba<u8>),\n\n _params: &Option<BlendAlgorithmParams>,\n\n) {\n\n let ab = bot_pixel[3];\n\n let at = top_pixel[3];\n\n\n\n let abf = 1.0 * (ab as f32 / 255.0);\n\n let atf = 1.0 * (at as f32 / 255.0);\n\n\n\n let mut r = if atf + abf < 1.0 { 0 } else { 255 };\n\n let mut g = if atf + abf < 1.0 { 255 } else { 0 };\n\n let mut b = 0;\n\n let a = max(0, min(255, at as u16 + ab as u16));\n\n\n\n r = max(0, min(255, r));\n\n g = max(0, min(255, g));\n\n b = max(0, min(255, b));\n\n\n\n bot_pixel[0] = r;\n\n bot_pixel[1] = g;\n\n bot_pixel[2] = b;\n\n bot_pixel[3] = a as u8;\n\n}\n", "file_path": "src/blending/algorithms.rs", "rank": 56, "score": 97917.44662971303 }, { "content": "#[wasm_bindgen(js_name = blendImagesData)]\n\npub fn blend_images_data_js(\n\n bot: ImageData,\n\n top: ImageData,\n\n algorithm: Option<String>,\n\n is_inline: Option<bool>,\n\n options: JsValue,\n\n) -> Result<ImageData, JsValue> {\n\n let options = match options.is_object() {\n\n true => options.into_serde::<HashMap<String, JSONValue>>().ok(),\n\n false => None,\n\n };\n\n\n\n let (width, height) = (bot.width(), bot.height());\n\n let mut bot = ImageBuffer::from_vec(width, height, bot.data().to_vec())\n\n .ok_or_else(|| PConvertError::ArgumentError(\"Could not parse \\\"bot\\\"\".to_string()))?;\n\n let mut top = ImageBuffer::from_vec(width, height, top.data().to_vec())\n\n .ok_or_else(|| PConvertError::ArgumentError(\"Could not parse \\\"top\\\"\".to_string()))?;\n\n\n\n blend_image_buffers(&mut bot, &mut top, algorithm, is_inline)?;\n\n\n\n encode_image_data(\n\n bot,\n\n get_compression_type(&options),\n\n get_filter_type(&options),\n\n )\n\n}\n\n\n", "file_path": "src/wasm/mod.rs", "rank": 57, "score": 96012.82788261934 }, { "content": "#[wasm_bindgen(js_name = blendMultipleData)]\n\npub fn blend_multiple_data_js(\n\n images: &JsValue,\n\n algorithm: Option<String>,\n\n algorithms: Option<Vec<JsValue>>,\n\n is_inline: Option<bool>,\n\n options: JsValue,\n\n) -> Result<ImageData, JsValue> {\n\n let options = match options.is_object() {\n\n true => options.into_serde::<HashMap<String, JSONValue>>().ok(),\n\n false => None,\n\n };\n\n\n\n let mut image_buffers: Vec<RgbaImage> = Vec::new();\n\n let mut images = try_iter(images).unwrap().unwrap();\n\n while let Some(Ok(img_data)) = images.next() {\n\n let img_data: ImageData = img_data.into();\n\n let img_buffer: RgbaImage = ImageBuffer::from_vec(\n\n img_data.width(),\n\n img_data.height(),\n\n img_data.data().to_vec(),\n", "file_path": "src/wasm/mod.rs", "rank": 58, "score": 96012.82788261934 }, { "content": "#[wasm_bindgen(js_name = getModuleConstants)]\n\npub fn get_module_constants_js() -> JsValue {\n\n let filters: Vec<String> = constants::FILTER_TYPES\n\n .to_vec()\n\n .iter()\n\n .map(|x| format!(\"{:?}\", x))\n\n .collect();\n\n\n\n let compressions: Vec<String> = constants::COMPRESSION_TYPES\n\n .to_vec()\n\n .iter()\n\n .map(|x| format!(\"{:?}\", x))\n\n .collect();\n\n\n\n JsValue::from_serde(&json!({\n\n \"COMPILATION_DATE\": constants::COMPILATION_DATE,\n\n \"COMPILATION_TIME\": constants::COMPILATION_TIME,\n\n \"VERSION\": constants::VERSION,\n\n \"ALGORITHMS\": constants::ALGORITHMS,\n\n \"COMPILER\": constants::COMPILER,\n\n \"COMPILER_VERSION\": constants::COMPILER_VERSION,\n", "file_path": "src/wasm/mod.rs", "rank": 59, "score": 88856.53906112045 }, { "content": "#[pymodule]\n\nfn pconvert_rust(_py: Python, module: &PyModule) -> PyResult<()> {\n\n unsafe {\n\n let mut thread_pool = ThreadPool::new(constants::DEFAULT_THREAD_POOL_SIZE).unwrap();\n\n thread_pool.start();\n\n THREAD_POOL = Some(thread_pool);\n\n }\n\n\n\n module.add(\"COMPILATION_DATE\", constants::COMPILATION_DATE)?;\n\n module.add(\"COMPILATION_TIME\", constants::COMPILATION_TIME)?;\n\n module.add(\"VERSION\", constants::VERSION)?;\n\n module.add(\"ALGORITHMS\", constants::ALGORITHMS.to_vec())?;\n\n module.add(\"COMPILER\", constants::COMPILER)?;\n\n module.add(\"COMPILER_VERSION\", constants::COMPILER_VERSION)?;\n\n module.add(\"LIBPNG_VERSION\", constants::LIBPNG_VERSION)?;\n\n module.add(\"FEATURES\", constants::FEATURES.to_vec())?;\n\n module.add(\"PLATFORM_CPU_BITS\", constants::PLATFORM_CPU_BITS)?;\n\n\n\n let filters: Vec<String> = constants::FILTER_TYPES\n\n .to_vec()\n\n .iter()\n", "file_path": "src/pymodule/mod.rs", "rank": 63, "score": 61273.15758384775 }, { "content": "fn main() {\n\n // in case we're running under docs.rs then we must return the control\n\n // flow immediately as it's not possible to generated files under the\n\n // expected read only file system present in docs.rs build environment\n\n if std::env::var(\"DOCS_RS\").is_ok() {\n\n return;\n\n }\n\n\n\n let dest_path = Path::new(SOURCE_DIR).join(Path::new(BUILD_OUT_FILE));\n\n let mut file = OpenOptions::new()\n\n .truncate(true)\n\n .write(true)\n\n .create(true)\n\n .open(dest_path)\n\n .unwrap_or_else(|_| panic!(\"Can't open '{}'\", BUILD_OUT_FILE));\n\n\n\n let module_doc_string = \"//! Global constants, such as compiler version used, algorithms, compression and filters supported and others\\n\";\n\n writeln!(file, \"{}\", module_doc_string).unwrap();\n\n\n\n let now_utc = Utc::now();\n", "file_path": "build.rs", "rank": 64, "score": 55953.25555119295 }, { "content": "#[test]\n\nfn test_convert() {\n\n let file_in = format!(\"{}{}\", TEST_DIR, TEST_FILE);\n\n let mut img = read_png_from_file(file_in.clone(), false)\n\n .unwrap_or_else(|_| panic!(\"failure reading {}\", file_in));\n\n\n\n for pixel in img.pixels_mut() {\n\n apply_blue_filter(pixel);\n\n }\n\n\n\n let out = format!(\"{}{}\", TEST_DIR, TEST_FILE_OUT);\n\n img.save_with_format(out.clone(), ImageFormat::Png)\n\n .unwrap_or_else(|_| panic!(\"failure writing {}\", out));\n\n}\n", "file_path": "src/test/mod.rs", "rank": 65, "score": 52048.548685068075 }, { "content": "#[test]\n\nfn test_compose() {\n\n let mut benchmark = Benchmark::new();\n\n let backgrounds = vec![\n\n Background::Alpha,\n\n Background::Blue,\n\n Background::Texture,\n\n Background::White,\n\n ];\n\n\n\n // composes with different combinations of blending algorithms and backgrounds\n\n for background in &backgrounds {\n\n for algorithm in constants::ALGORITHMS.iter() {\n\n compose(\n\n &TEST_DIR,\n\n BlendAlgorithm::from_str(algorithm).unwrap(),\n\n background,\n\n CompressionType::Fast,\n\n FilterType::NoFilter,\n\n &mut benchmark,\n\n )\n\n .unwrap_or_else(|_| panic!(\"failed composing with algorithm={} background={} compression=Fast filter=NoFilter\", algorithm, background));\n\n }\n\n }\n\n}\n\n\n", "file_path": "src/test/mod.rs", "rank": 66, "score": 52048.548685068075 }, { "content": "#[test]\n\nfn test_benchmark() {\n\n let mut benchmark1 = Benchmark::new();\n\n Benchmark::add_blend_time(&mut benchmark1, 100);\n\n Benchmark::add_read_png_time(&mut benchmark1, 200);\n\n Benchmark::add_write_png_time(&mut benchmark1, 150);\n\n\n\n assert!(benchmark1.total() == 100 + 200 + 150);\n\n\n\n let mut benchmark2 = Benchmark::new();\n\n Benchmark::add_blend_time(&mut benchmark2, 50);\n\n Benchmark::add_read_png_time(&mut benchmark2, 100);\n\n Benchmark::add_write_png_time(&mut benchmark2, 75);\n\n\n\n assert!(benchmark2.total() == 50 + 100 + 75);\n\n\n\n let sum_benchmark = benchmark1 + benchmark2;\n\n assert!(sum_benchmark.total() == 100 + 200 + 150 + 50 + 100 + 75);\n\n}\n\n\n", "file_path": "src/test/mod.rs", "rank": 67, "score": 52048.548685068075 }, { "content": "#[test]\n\nfn test_compose_parallel() {\n\n let mut benchmark = Benchmark::new();\n\n let backgrounds = vec![\n\n Background::Alpha,\n\n Background::Blue,\n\n Background::Texture,\n\n Background::White,\n\n ];\n\n\n\n // composes with different combinations of blending algorithms and backgrounds\n\n for background in backgrounds {\n\n for algorithm in constants::ALGORITHMS.iter() {\n\n compose_parallel(\n\n &TEST_DIR,\n\n BlendAlgorithm::from_str(algorithm).unwrap(),\n\n &background,\n\n CompressionType::Fast,\n\n FilterType::NoFilter,\n\n &mut benchmark,\n\n )\n\n .unwrap_or_else(|_| panic!(\"failed composing with algorithm={} background={} compression=Fast filter=NoFilter\", algorithm, background));\n\n }\n\n }\n\n}\n\n\n", "file_path": "src/test/mod.rs", "rank": 68, "score": 50950.163910186006 }, { "content": "fn blend_multiple_buffers(\n\n image_buffers: Vec<ImageBuffer<Rgba<u8>, Vec<u8>>>,\n\n algorithm: Option<String>,\n\n algorithms: Option<Vec<JsValue>>,\n\n is_inline: Option<bool>,\n\n) -> Result<ImageBuffer<Rgba<u8>, Vec<u8>>, PConvertError> {\n\n let num_images = image_buffers.len();\n\n if num_images < 1 {\n\n return Err(PConvertError::ArgumentError(\n\n \"'images' must contain at least one path\".to_string(),\n\n ));\n\n }\n\n\n\n if algorithms.is_some() && algorithms.as_ref().unwrap().len() != num_images - 1 {\n\n return Err(PConvertError::ArgumentError(format!(\n\n \"'algorithms' must be of size {} (one per blending operation)\",\n\n num_images - 1\n\n )));\n\n };\n\n\n", "file_path": "src/wasm/mod.rs", "rank": 69, "score": 50950.163910186006 }, { "content": "type Task = Box<dyn FnOnce() -> ResultMessage + Send>;\n", "file_path": "src/parallelism.rs", "rank": 70, "score": 50009.09502482963 }, { "content": "fn blend_images_single_thread(\n\n bot_path: String,\n\n top_path: String,\n\n target_path: String,\n\n algorithm: Option<String>,\n\n is_inline: Option<bool>,\n\n options: Option<Options>,\n\n) -> PyResult<()> {\n\n let algorithm = algorithm.unwrap_or_else(|| String::from(\"multiplicative\"));\n\n let algorithm = build_algorithm(&algorithm)?;\n\n\n\n let _is_inline = is_inline.unwrap_or(false);\n\n\n\n let demultiply = is_algorithm_multiplied(&algorithm);\n\n let algorithm_fn = get_blending_algorithm(&algorithm);\n\n\n\n let mut bot = read_png_from_file(bot_path, demultiply)?;\n\n let top = read_png_from_file(top_path, demultiply)?;\n\n\n\n blend_images(&mut bot, &top, &algorithm_fn, &None);\n", "file_path": "src/pymodule/mod.rs", "rank": 71, "score": 49934.291774372556 }, { "content": "fn blend_multiple_single_thread(\n\n img_paths: Vec<String>,\n\n out_path: String,\n\n algorithms: Vec<(BlendAlgorithm, Option<BlendAlgorithmParams>)>,\n\n is_inline: Option<bool>,\n\n options: Option<Options>,\n\n) -> PyResult<()> {\n\n let num_images = img_paths.len();\n\n\n\n if num_images < 1 {\n\n return Err(PyErr::from(PConvertError::ArgumentError(\n\n \"ArgumentError: 'img_paths' must contain at least one path\".to_string(),\n\n )));\n\n }\n\n\n\n if algorithms.len() != num_images - 1 {\n\n return Err(PyErr::from(PConvertError::ArgumentError(format!(\n\n \"ArgumentError: 'algorithms' must be of size {} (one per blending operation)\",\n\n num_images - 1\n\n ))));\n", "file_path": "src/pymodule/mod.rs", "rank": 72, "score": 49934.291774372556 }, { "content": "const selectCompression = document.querySelector(\"select#compression\");\n", "file_path": "examples/wasm/index.js", "rank": 73, "score": 24986.31385362757 }, { "content": "const selectFilter = document.querySelector(\"select#filter\");\n", "file_path": "examples/wasm/index.js", "rank": 74, "score": 24966.532948433338 }, { "content": "const inputFiles = document.querySelector(\"input#files\");\n", "file_path": "examples/wasm/index.js", "rank": 75, "score": 24846.960747188357 }, { "content": "}\n\n\n\nmacro_rules! console_log {\n\n ($($t:tt)*) => (log(&format_args!($($t)*).to_string()))\n\n}\n\n\n\n/// Receives a `File` and returns the decoded PNG byte buffer.\n\npub async fn load_png(\n\n file: File,\n\n demultiply: bool,\n\n) -> Result<ImageBuffer<Rgba<u8>, Vec<u8>>, JsValue> {\n\n let array_buffer = JsFuture::from(file.array_buffer()).await?;\n\n let uint8_array = Uint8Array::new(&array_buffer);\n\n let png = decode_png(&uint8_array.to_vec()[..], demultiply)?;\n\n Ok(png)\n\n}\n\n\n\n/// Receives png buffer data and encodes it as a `File` with specified\n\n/// `CompressionType` and `FilterType`.\n", "file_path": "src/wasm/utils.rs", "rank": 77, "score": 28.08580224553181 }, { "content": " &algorithm_fn,\n\n algorithm_params,\n\n );\n\n }\n\n\n\n let compression_type = get_compression_type(&options);\n\n let filter_type = get_filter_type(&options);\n\n write_png_to_file(out_path, &composition, compression_type, filter_type)?;\n\n\n\n Ok(())\n\n}\n\n\n\nunsafe fn blend_multiple_multi_thread(\n\n img_paths: Vec<String>,\n\n out_path: String,\n\n algorithms: Vec<(BlendAlgorithm, Option<BlendAlgorithmParams>)>,\n\n is_inline: Option<bool>,\n\n options: Option<Options>,\n\n num_threads: i32,\n\n) -> PyResult<()> {\n", "file_path": "src/pymodule/mod.rs", "rank": 78, "score": 25.912693465365365 }, { "content": " }\n\n }\n\n Ok(())\n\n}\n\n\n\nasync fn blend_images_benchmark_js(\n\n bot: File,\n\n top: File,\n\n target_file_name: String,\n\n algorithm: Option<String>,\n\n is_inline: Option<bool>,\n\n compression: CompressionType,\n\n filter: FilterType,\n\n) -> Result<File, JsValue> {\n\n let start_read = js_sys::Date::now();\n\n\n\n let mut bot = load_png(bot, false).await?;\n\n let mut top = load_png(top, false).await?;\n\n\n\n let start_blend = js_sys::Date::now();\n", "file_path": "src/wasm/benchmark.rs", "rank": 79, "score": 25.380492590255518 }, { "content": "use utils::{\n\n build_algorithm, build_params, encode_file, encode_image_data, get_compression_type,\n\n get_filter_type, load_png, node_read_file_async, node_read_file_sync, node_require,\n\n node_write_file_sync,\n\n};\n\nuse wasm_bindgen::prelude::*;\n\nuse web_sys::{File, ImageData};\n\n\n\n/// Blends two `File`s into one, named `target_file_name`, using `algorithm` and the extra\n\n/// `options` given. Algorithm defaults to `BlendAlgorithm::Multiplicative`.\n\n#[wasm_bindgen(js_name = blendImages)]\n\npub async fn blend_images_js(\n\n bot: File,\n\n top: File,\n\n target_file_name: String,\n\n algorithm: Option<String>,\n\n is_inline: Option<bool>,\n\n options: JsValue,\n\n) -> Result<File, JsValue> {\n\n let options = match options.is_object() {\n", "file_path": "src/wasm/mod.rs", "rank": 80, "score": 25.35811026998887 }, { "content": " let (algorithm, algorithm_params) = pair.1;\n\n let demultiply = is_algorithm_multiplied(&algorithm);\n\n let algorithm_fn = get_blending_algorithm(&algorithm);\n\n let current_layer = node_read_file_sync(&node_fs, &path);\n\n let current_layer = decode_png(&current_layer[..], demultiply)?;\n\n blend_images(\n\n &mut composition,\n\n &current_layer,\n\n &algorithm_fn,\n\n algorithm_params,\n\n );\n\n }\n\n\n\n let compression_type = get_compression_type(&options);\n\n let filter_type = get_filter_type(&options);\n\n\n\n let mut encoded_data = Vec::<u8>::with_capacity(composition.to_vec().capacity());\n\n encode_png(\n\n &mut encoded_data,\n\n &composition,\n", "file_path": "src/wasm/mod.rs", "rank": 81, "score": 24.73641460010802 }, { "content": "\n\n blend_images(\n\n &mut composition,\n\n &current_layer,\n\n &algorithm_fn,\n\n algorithm_params,\n\n );\n\n }\n\n\n\n let compression_type = get_compression_type(&options);\n\n let filter_type = get_filter_type(&options);\n\n\n\n let mut encoded_data = Vec::<u8>::with_capacity(composition.to_vec().capacity());\n\n encode_png(\n\n &mut encoded_data,\n\n &composition,\n\n compression_type,\n\n filter_type,\n\n )?;\n\n\n\n node_write_file_sync(&node_fs, &out_path, &encoded_data);\n\n\n\n Ok(())\n\n}\n\n\n", "file_path": "src/wasm/mod.rs", "rank": 82, "score": 23.91684628203708 }, { "content": " ResultMessage::ImageResult(result) => result,\n\n }?;\n\n\n\n blend_images(&mut bot, &top, &algorithm_fn, &None);\n\n\n\n let compression_type = get_compression_type(&options);\n\n let filter_type = get_filter_type(&options);\n\n write_png_parallel(target_path, &bot, compression_type, filter_type)?;\n\n\n\n Ok(())\n\n}\n\n\n", "file_path": "src/pymodule/mod.rs", "rank": 83, "score": 23.298030535823564 }, { "content": " );\n\n\n\n Ok(file)\n\n}\n\n\n\nasync fn blend_multiple_benchmark_js(\n\n image_files: JsValue,\n\n target_file_name: String,\n\n algorithm: Option<String>,\n\n algorithms: Option<Vec<JsValue>>,\n\n is_inline: Option<bool>,\n\n compression: CompressionType,\n\n filter: FilterType,\n\n) -> Result<File, JsValue> {\n\n let start_read = js_sys::Date::now();\n\n\n\n let mut image_buffers = Vec::new();\n\n let image_files = try_iter(&image_files).unwrap().unwrap();\n\n for file in image_files {\n\n let file = file?;\n", "file_path": "src/wasm/benchmark.rs", "rank": 85, "score": 22.385473597295896 }, { "content": "\n\n let compression_type = get_compression_type(&options);\n\n let filter_type = get_filter_type(&options);\n\n write_png_to_file(target_path, &bot, compression_type, filter_type)?;\n\n\n\n Ok(())\n\n}\n\n\n\nunsafe fn blend_images_multi_thread(\n\n bot_path: String,\n\n top_path: String,\n\n target_path: String,\n\n algorithm: Option<String>,\n\n is_inline: Option<bool>,\n\n options: Option<Options>,\n\n num_threads: i32,\n\n) -> PyResult<()> {\n\n let algorithm = algorithm.unwrap_or_else(|| String::from(\"multiplicative\"));\n\n let algorithm = build_algorithm(&algorithm)?;\n\n let _is_inline = is_inline.unwrap_or(false);\n", "file_path": "src/pymodule/mod.rs", "rank": 86, "score": 21.855587553343888 }, { "content": "\n\n let mut composition = benchmark.execute(Benchmark::add_read_png_time, || {\n\n if let Ok(ResultMessage::ImageResult(result)) = result_channels[4].recv() {\n\n result\n\n } else {\n\n panic!(format!(\"failure reading '{}'\", background_file))\n\n }\n\n })?;\n\n benchmark.execute(Benchmark::add_blend_time, || {\n\n blend_images(&mut composition, &bot, &algorithm_fn, &None)\n\n });\n\n\n\n // writes the final composition PNG to the output file,\n\n // this is considered to be the most expensive operation\n\n let file_name = format!(\n\n \"result_{}_{}_{:#?}_{:#?}.png\",\n\n algorithm, background, compression, filter\n\n );\n\n let file_out = format!(\"{}{}\", dir, file_name);\n\n benchmark.execute(Benchmark::add_write_png_time, || {\n\n write_png_parallel(file_out, &composition, compression, filter)\n\n })?;\n\n\n\n Ok(file_name)\n\n}\n\n\n", "file_path": "src/compose.rs", "rank": 87, "score": 21.573050115525188 }, { "content": "//! Python extension, exported functions and type conversions.\n\n\n\npub mod conversions;\n\npub mod utils;\n\n\n\nuse crate::blending::params::{BlendAlgorithmParams, Options};\n\nuse crate::blending::{\n\n blend_images, demultiply_image, get_blending_algorithm, is_algorithm_multiplied, BlendAlgorithm,\n\n};\n\nuse crate::constants;\n\nuse crate::errors::PConvertError;\n\nuse crate::parallelism::{ResultMessage, ThreadPool};\n\nuse crate::utils::{read_png_from_file, write_png_parallel, write_png_to_file};\n\nuse pyo3::exceptions::PyException;\n\nuse pyo3::prelude::*;\n\nuse pyo3::types::{IntoPyDict, PyDict, PySequence};\n\nuse std::sync::mpsc;\n\nuse utils::{\n\n build_algorithm, build_params, get_compression_type, get_filter_type, get_num_threads,\n\n};\n\n\n\nstatic mut THREAD_POOL: Option<ThreadPool> = None;\n\n\n\n#[pymodule]\n", "file_path": "src/pymodule/mod.rs", "rank": 88, "score": 21.471702618860213 }, { "content": "//! Benchmarking functions of the WASM API exposed\n\n\n\nuse crate::constants;\n\nuse crate::wasm::utils::{encode_file, load_png, log_benchmark, log_benchmark_header};\n\nuse crate::wasm::{blend_image_buffers, blend_multiple_buffers};\n\nuse image::codecs::png::{CompressionType, FilterType};\n\nuse js_sys::try_iter;\n\nuse wasm_bindgen::prelude::*;\n\nuse web_sys::File;\n\n\n\n/// Benchmarks the `blend_images_js` API method for all combinations of\n\n/// algorithms, compression and filter types.\n\n#[wasm_bindgen(js_name = blendImagesBenchmarkAll)]\n\npub async fn blend_images_benchmark_all_js(\n\n bot: File,\n\n top: File,\n\n is_inline: Option<bool>,\n\n) -> Result<(), JsValue> {\n\n log_benchmark_header();\n\n for algorithm in constants::ALGORITHMS.iter() {\n", "file_path": "src/wasm/benchmark.rs", "rank": 89, "score": 21.168807061304534 }, { "content": " /// let demultiply = false;\n\n /// let path = \"path/to/file.png\".to_owned();\n\n /// let top = benchmark.execute(Benchmark::add_read_png_time, || {\n\n /// read_png_from_file(path, demultiply)\n\n /// }).unwrap();\n\n /// ```\n\n pub fn execute<F, T, H>(&mut self, update_fn: H, target_fn: F) -> T\n\n where\n\n F: FnOnce() -> T,\n\n H: FnOnce(&mut Self, u128),\n\n {\n\n // saves beginning Instant, executes the target function,\n\n // measures time spent and updates the benchmark struct according\n\n // to the update function (read, write or blend time)\n\n let start = Instant::now();\n\n let result = target_fn();\n\n update_fn(self, start.elapsed().as_millis() as u128);\n\n result\n\n }\n\n\n", "file_path": "src/benchmark.rs", "rank": 90, "score": 21.078326126898233 }, { "content": "/// * `algorithm_params` - A optional map of key-value pairs of blending\n\n/// properties and values.\n\n///\n\n/// # Examples\n\n///\n\n/// ```no_run\n\n/// use pconvert_rust::blending::{blend_images, get_blending_algorithm, BlendAlgorithm};\n\n/// use pconvert_rust::utils::read_png_from_file;\n\n///\n\n/// let mut bot = read_png_from_file(\"bot.png\".to_string(), false).unwrap();\n\n/// let top = read_png_from_file(\"top.png\".to_string(), false).unwrap();\n\n/// let algorithm_fn = get_blending_algorithm(&BlendAlgorithm::Alpha);\n\n///\n\n/// blend_images(&mut bot, &top, &algorithm_fn, &None);\n\n/// ```\n", "file_path": "src/blending/mod.rs", "rank": 91, "score": 20.838302278326587 }, { "content": " panic!(\"failure reading 'sole.png'\")\n\n }\n\n })?;\n\n\n\n for i in 1..=3 {\n\n let top = benchmark.execute(Benchmark::add_read_png_time, || {\n\n if let Ok(ResultMessage::ImageResult(result)) = result_channels[i].recv() {\n\n result\n\n } else {\n\n panic!(format!(\"failure reading '{}'\", png_file_names[i]))\n\n }\n\n })?;\n\n benchmark.execute(Benchmark::add_blend_time, || {\n\n blend_images(&mut bot, &top, &algorithm_fn, &None)\n\n });\n\n }\n\n\n\n if demultiply {\n\n multiply_image(&mut bot);\n\n }\n", "file_path": "src/compose.rs", "rank": 92, "score": 20.61520254747185 }, { "content": " true => options.into_serde::<HashMap<String, JSONValue>>().ok(),\n\n false => None,\n\n };\n\n\n\n let mut bot = load_png(bot, false).await?;\n\n let mut top = load_png(top, false).await?;\n\n\n\n blend_image_buffers(&mut bot, &mut top, algorithm, is_inline)?;\n\n\n\n encode_file(\n\n bot,\n\n get_compression_type(&options),\n\n get_filter_type(&options),\n\n target_file_name,\n\n )\n\n}\n\n\n\n/// Blends two `ImageData` objects into one using `algorithm` and the extra\n\n/// `options` given. Algorithm defaults to `BlendAlgorithm::Multiplicative`.\n\n#[wasm_bindgen(js_name = blendImagesData)]\n", "file_path": "src/wasm/mod.rs", "rank": 93, "score": 20.61448521795994 }, { "content": "use crate::benchmark::Benchmark;\n\nuse crate::blending::{\n\n blend_images, get_blending_algorithm, is_algorithm_multiplied, multiply_image, BlendAlgorithm,\n\n};\n\nuse crate::errors::PConvertError;\n\nuse crate::parallelism::{ResultMessage, ThreadPool};\n\nuse crate::utils::{read_png_from_file, write_png_parallel, write_png_to_file};\n\nuse image::codecs::png::{CompressionType, FilterType};\n\nuse image::Rgba;\n\nuse std::fmt::{Display, Formatter};\n\nuse std::{fmt, sync::mpsc::Receiver};\n\n\n\nconst THREAD_POOL_SIZE: usize = 5;\n\n\n\n#[derive(Clone)]\n\npub enum Background {\n\n Alpha,\n\n White,\n\n Blue,\n\n Texture,\n", "file_path": "src/compose.rs", "rank": 94, "score": 20.54301976409537 }, { "content": " compression_type,\n\n filter_type,\n\n )?;\n\n\n\n node_write_file_sync(&node_fs, &out_path, &encoded_data);\n\n\n\n Ok(())\n\n}\n\n\n\n/// [NodeJS only]\n\n/// Asynchronously blends multiple images read from local file system into one using `algorithm` or `algorithms` and the extra\n\n/// `options` given. Algorithm defaults to `BlendAlgorithm::Multiplicative`.\n\n#[wasm_bindgen(js_name = blendMultipleFsAsync)]\n\npub async fn blend_multiple_fs_async(\n\n image_paths: Vec<JsValue>,\n\n out_path: String,\n\n algorithm: Option<String>,\n\n algorithms: Option<Vec<JsValue>>,\n\n is_inline: Option<bool>,\n\n options: JsValue,\n", "file_path": "src/wasm/mod.rs", "rank": 95, "score": 20.09770093150894 }, { "content": " blend_time: 0,\n\n read_png_time: 0,\n\n write_png_time: 0,\n\n }\n\n }\n\n\n\n /// Returns the total time (in milliseconds), i.e., the sum of read,\n\n /// write and blend times.\n\n pub fn total(&self) -> u128 {\n\n self.blend_time + self.read_png_time + self.write_png_time\n\n }\n\n\n\n /// Executes the function to benchmark and adds the time spent\n\n /// to a certain counter with the given `target_fn`.\n\n ///\n\n /// ```no_run\n\n /// use pconvert_rust::benchmark::Benchmark;\n\n /// use pconvert_rust::utils::read_png_from_file;\n\n ///\n\n /// let mut benchmark = Benchmark::new();\n", "file_path": "src/benchmark.rs", "rank": 96, "score": 19.86613262880892 }, { "content": "#[wasm_bindgen(js_name = blendMultipleBenchmarkAll)]\n\npub async fn blend_multiple_benchmark_all_js(\n\n image_files: JsValue,\n\n is_inline: Option<bool>,\n\n) -> Result<(), JsValue> {\n\n log_benchmark_header();\n\n for algorithm in constants::ALGORITHMS.iter() {\n\n for compression in constants::COMPRESSION_TYPES.iter() {\n\n for filter in constants::FILTER_TYPES.iter() {\n\n blend_multiple_benchmark_js(\n\n image_files.clone(),\n\n \"\".to_string(),\n\n Some(algorithm.to_string()),\n\n None,\n\n is_inline,\n\n *compression,\n\n *filter,\n\n )\n\n .await?;\n\n }\n", "file_path": "src/wasm/benchmark.rs", "rank": 97, "score": 19.387781510851287 }, { "content": " };\n\n\n\n let _is_inline = is_inline.unwrap_or(false);\n\n\n\n // loops through the algorithms to apply and blends the\n\n // current composition with the next layer\n\n let mut img_paths_iter = img_paths.iter();\n\n let first_path = img_paths_iter.next().unwrap().to_string();\n\n let first_demultiply = is_algorithm_multiplied(&algorithms[0].0);\n\n let mut composition = read_png_from_file(first_path, first_demultiply)?;\n\n let zip_iter = img_paths_iter.zip(algorithms.iter());\n\n for pair in zip_iter {\n\n let path = pair.0.to_string();\n\n let (algorithm, algorithm_params) = pair.1;\n\n let demultiply = is_algorithm_multiplied(&algorithm);\n\n let algorithm_fn = get_blending_algorithm(&algorithm);\n\n let current_layer = read_png_from_file(path, demultiply)?;\n\n blend_images(\n\n &mut composition,\n\n &current_layer,\n", "file_path": "src/pymodule/mod.rs", "rank": 98, "score": 19.309041947797137 }, { "content": "}\n\n\n\nimpl Display for Benchmark {\n\n fn fmt(&self, fmt: &mut Formatter) -> Result {\n\n fmt.write_str(&format!(\n\n \"{}ms (blend {}ms, read {}ms, write {}ms)\",\n\n self.total(),\n\n self.blend_time,\n\n self.read_png_time,\n\n self.write_png_time\n\n ))?;\n\n Ok(())\n\n }\n\n}\n\n\n\nimpl Add for Benchmark {\n\n type Output = Self;\n\n\n\n fn add(self, other: Self) -> Self {\n\n Self {\n", "file_path": "src/benchmark.rs", "rank": 99, "score": 18.92242677306493 } ]